Skip to main content
Glama
README.md
# wiki-formant

The portable half of a wiki: a page store, derived taxonomy, a spec-correct MCP transport, markdown twins, block rendering and editing, and the conditional-GET plumbing an agent surface needs.

The editor, history, sanitiser, chart and passkey modules bring their libraries as dependencies (`@tiptap/*`, `fast-diff`, `sanitize-html`, `lightweight-charts`, `@simplewebauthn/*`). What only some apps use is an optional peer: `pg`, `react`, `jose` and `@radixdlt/rola` for ROLA, `sharp` and `@vercel/blob` for uploads. Web-standard `Request`/`Response` throughout, so it runs on Next route handlers, Hono, Bun, Deno and workers.

```bash
npm install wiki-formant
```

An agent can start a wiki for you, hosted on miow.me or in your own app, with the skill in `skills/wiki-formant`: `npx skills add tutmoses/wiki-formant`.

What stays the app's: its design system, its block types beyond the core, its connection, cache and auth. Everything else here is shared.

## API

Every module has a subpath (`wiki-formant/taxonomy`, `wiki-formant/mcp`, …) and there is no root export: a barrel loads every module for the one symbol a route wanted. The emitted `.d.ts` files are the reference; this README shows one use of each subpath and the rules a signature cannot say. A function a module uses only itself is marked `@internal` and left out of the `.d.ts`.

`wiki-formant/tsconfig.base.json` is the compiler floor: an app's `tsconfig.json` extends it and keeps only `paths`, `include`, `exclude` and any licensed extra, since tsconfig resolves those against the file that declares them.

```json
{ "extends": "wiki-formant/tsconfig.base.json", "compilerOptions": { "paths": { "@/*": ["./src/*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "src/app/.well-known/**/*.ts", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"], "exclude": ["node_modules"] }
```

## Store

`wiki-formant/store`: `wikiStore` reads and writes `WikiPage` and `WikiRevision` through one `Sql` function the app binds to its own client, scoped to one site.

```ts
import { wikiStore } from 'wiki-formant/store';

const store = wikiStore({
  sql: (query, ...values) => prisma.$queryRawUnsafe(query, ...values),
  siteId: '',                 // a multi-tenant app passes the site's key
  hidden: tree.hiddenPaths,   // back office: never listed unasked
});

const page = await store.get('contents/tech', 'radix-engine');
const { items, total } = await store.search('validators', { take: 20 });
await store.save({ tagPath, slug, content, authorId, message, baseVersion: page.version });
```

- **A save is one statement**: the page update and its revision in a CTE guarded on the version read. A lost race, a stale `baseVersion`, a page deleted since or a rename onto a taken slug writes nothing and throws a 409 `HttpError` whose body names the reason as `conflict`: `stale` and `deleted` mean reload, `taken` means another slug (`ConflictReason`).
- **The bump is the diff's**: added, removed or moved blocks are `major`, changed prose or title `minor`; `change` overrides it. A metadata-only save moves no version and writes no revision.
- **History is diffed on read.** A revision stores the page as saved. `history(pageId, { limit })` reads one row more than it returns, so the oldest entry shown has its real predecessor.
- **Listings carry a snippet, not the article**: `list`, `recent` and `byIds` drop `content`, and carry `banner`, the page's picture for its card (`metadata.banner`, or the `banner` option's reading).
- **Search is four tiers**: title prefix, title, literal prose, then full text on `search_tsv` with Postgres' headline as the snippet. Hidden paths, and paths under them, are left out unless named.
- `branch` is an agent's walk of a path and everything under it; `counts` is pages per tag path.
- Copy the models with `npx prisma-models wiki` (`--tenant` for a tenant-keyed copy), then build the full-text column with `npx fts-ddl '"WikiPage"'`.

## Tree

`wiki-formant/tree`: the category tree a wiki declares, and its walks.

```ts
import { createTree, parseWikiPath } from 'wiki-formant/tree';

const tree = createTree(NODES, { globalKeys: [QUALITY] });
tree.resolve('contents/tech');   // { node, trail, valid, hidden, sort, mainArticle, metadataKeys }
parseWikiPath(tree, ['contents', 'tech', 'radix-engine', 'history']);
// { type: 'page', tagPath: 'contents/tech', slug: 'radix-engine', mode: 'history' }
```

- Metadata keys accumulate down the trail; `sort`, `mainArticle` and `hidden` inherit, the nearest declaration winning. A field only one wiki reads rides on the node.
- A path that is itself a category wins over a mode suffix. The empty slug is a category's hub article.
- `crumbs` makes one crumb per URL segment, linked only where the tree knows it.

## Category view

`wiki-formant/category`: a category page from the tree, the taxonomy and anything that reads like the store.

```ts
import { categoryView } from 'wiki-formant/category';

const view = await categoryView({ tree, taxonomy, pages: store }, 'ecosystem', searchParams);
// { sort, total, pages, all, filters, letter, facets, letters, sortable, clearHref, sortHref, sections }
```

A link carries `sort` only when it is not the category's default, so the bare category and its default are one address.

## Wiki read tools

`wiki-formant/wiki-tools`: the read half of a wiki's MCP server: `search_wiki`, `get_page`, `get_pages`, `list_pages`, `get_categories`, `get_recent_changes`, `get_full_corpus` and `get_page_history`. `searchWiki` is the same rows for a plain-GET `?q=` and a search page.

```ts
import { wikiReadTools, searchWiki, type CorpusSection } from 'wiki-formant/wiki-tools';

const reading = { store, tree, url: (tagPath, slug) => `${SITE}/${tagPath}/${slug}`, text: extractText, noun: 'the Radix Wiki', corpusTitle: 'Radix Wiki' };
const tools = [...wikiReadTools(reading), ...myOwnTools];
const { items, total } = await searchWiki(reading, 'validators', { page: 1, size: 20 });
```

- Every row carries `path`, which every read tool takes back, its `id` (what a `pageList` block takes), and `chars` where the text was read. A pasted URL resolves, with `pathPrefix` stripped; a miss names the nearest pages.
- `get_page` with `blocks: true` returns the stored blocks, `id`, metadata and `version`: what an edit starts from. `forEdit` adds the app's own edit fields; `authors` names revision authors.
- `text` should be the twin's serializer and `resolve` the page's live resolver, so a page reads the same over MCP as at its twin.
- `get_full_corpus` is a `sizeOnly` preflight, then page-aligned slices under `maxChars` (`CORPUS_BUDGET`) with `truncated`, `nextSkip` and `clippedPage`. `corpus` returns the app's own `CorpusSection`s.
- `privateHidden` closes the back office to every tool. `metadata`, `label`, `noMatch` and `skills` are the app's. `onSearch` hears each first-page `search_wiki` query, except one narrowed by `tagPath` that found nothing; pass the tracker's `trackSearch` under `MCP_SURFACE` and the stats page lists what agents searched for.
- Writes stay with each app.

## Taxonomy

`wiki-formant/taxonomy`: the cross-cutting browsing axis derived from the `select` metadata pages already carry. The tree is yours; supply `getMetadataKeys` and one `href` builder.

```ts
import { createTaxonomy } from 'wiki-formant/taxonomy';

const taxonomy = createTaxonomy({
  getMetadataKeys: tagPath => TAGS[tagPath]?.metadataKeys ?? [],
  href: (tagPath, { sort, filters, letter }) => /* your URL contract */,
});
const state   = { sort, filters, letter: taxonomy.resolveLetter(all, filters, query.letter) };
const groups  = taxonomy.facetControls('ecosystem', all, state);  // [{ key, label, options }]
const letters = taxonomy.alphaControls('ecosystem', all, state);  // [] below the threshold
```

- Each facet is counted over the set narrowed by every *other* filter, so its options stay switchable.
- Values come from the data, not the declared `options`. A single-valued facet hides unless it is active.
- Every control is `{ value, label, count, href, active }` with every other axis carried in `href`. The reset control leads the row, flagged `reset`.
- `alphaControls` is `[]` below `needsAlphaIndex` (40 pages unless `alphaIndexMinPages`); `resolveLetter` drops a letter no page starts with.
- `metadataRows` returns a page's populated keys as rows with `href` on the facet ones; `rankRelated` ranks by shared facet values and returns the shared axis for the *See also* heading.

## Headings

`wiki-formant/headings`: heading ids, permalink anchors, and the list an "on this page" rail renders.

```ts
import { articleHtml, headingsFrom } from 'wiki-formant/headings';

const used = new Set([slug(page.title)]);
const blocks = page.blocks.map(b => ({ ...b, text: articleHtml(b.text, { used, links: { selfHost: 'radix.wiki' } }) }));
const toc = headingsFrom(blocks.map(b => b.text).join(''));   // [{ id, text, level }]
```

- `injectHeadingIds` is idempotent; `slug` is a parameter, since a heading id is a published URL.
- Pass one `used` set across a page's blocks, seeded with ids the template renders, or a repeated heading mints a duplicate id.
- `articleHtml` is the render-path chain: heading ids, `scrollTables`, and with `links` the link pass: an internal link loses `target` and `rel`, an external one gets them, and a bare-URL anchor gets readable text.

## MCP

`wiki-formant/mcp`: a [Model Context Protocol](https://modelcontextprotocol.io) server over Streamable HTTP.

```ts
import { mcpResponse, mcpGet, mcpOptions, McpToolError } from 'wiki-formant/mcp';
import { MCP_RATE_LIMIT } from 'wiki-formant/rate-limit';

const config = {
  serverInfo: { name: 'my-wiki', version: '1.4.0' },
  instructions: 'Call search_pages first; get_page needs a full path.',
  docsUrl: 'https://example.com/llms.txt',
  tools: [{
    name: 'search_pages',
    description: 'Full-text search across the wiki.',
    inputSchema: { type: 'object', properties: { q: { type: 'string', description: 'query' } }, required: ['q'] },
    annotations: { readOnlyHint: true },
    handler: async ({ q }) => search(String(q)),
  }],
  rateLimit: MCP_RATE_LIMIT,
  onCall: (req, body) => track(req, body),
};

export const POST = (req: Request) => mcpResponse(req, config);
export const GET  = () => mcpGet(config.docsUrl);
export const OPTIONS = () => mcpOptions();
```

- A caller-fixable mistake is a tool result with `isError`, never `-32603`: bad arguments name every bad field, quote legal values and append the schema. Throw `McpToolError(message, details)` from a handler for the same.
- Capabilities, and the `-32601` method list, advertise only what the config populates.
- A notification-only POST is a bare `202`; malformed JSON is `-32700` with a `400`; `GET` is an explicit 405 with CORS; the preflight allow-list and `Access-Control-Expose-Headers` cover what MCP clients send and read.
- Batches are capped (`DEFAULT_MAX_BATCH`, 20) and refused from 2025-06-18 on.
- Both protocol eras on one endpoint: a request with `io.modelcontextprotocol/protocolVersion` in `params._meta` is served as `2026-07-28` (`server/discover`, per-request version checks, `resultType` and cache hints); everything else is the legacy era, which echoes a supported client version. Every response carries `MCP-Protocol-Version`.
- The A2A call an agent card invites (`message/send`, `SendMessage`) is answered from the tool `answer` names.
- `rateLimit: { capacity, refillPerSec }` is enforced before the body is parsed, with `RateLimit-*` headers on every answer; `mcpRateLimited(sec)` is the JSON-RPC 429.
- Every object a handler returns comes back as `structuredContent` beside the text; `outputSchema` is the stronger contract when declared. `inputSchema.requireOneOf` names a set of which one must be present.
- A handler's second argument is its context: `ctx.meta` (the request's `params._meta`) and `ctx.setMeta(key, value)` (onto `result._meta`). `config.gate` is envelope-level middleware, for a payment gate whose demand replaces the call.
- `readArgs` reads raw arguments as typed, clamped values and records every override; `withAdjustments` puts them on the result as `adjustments`.
- `feedbackTool(record, noun)` is `send_feedback`. Listed, `initialize` appends `FEEDBACK_INVITE` and an empty `listEnvelope` page or an `McpToolError` carries a one-line pointer to it.

## Markdown twins

`wiki-formant/markdown`: `htmlToMarkdown` keeps the structure an agent cites by (headings, lists, tables, code, emphasis); `markdownDocument` adds the frontmatter.

```ts
import { htmlToMarkdown, markdownDocument } from 'wiki-formant/markdown';
import { markdownHeaders, cacheTagHeaders, VARY_ACCEPT } from 'wiki-formant/http';

return notModified(request, etag, lastModified) ?? new Response(
  markdownDocument(
    { title: page.title, url, updated: page.updatedAt, lastVerified: page.lastVerifiedAt, license },
    blocksToMarkdown(page.content),
  ),
  { headers: markdownHeaders(lastModified, { etag, noindex: true, extra: { ...VARY_ACCEPT, ...cacheTagHeaders(pageTag(path)) } }) },
);
```

- Tables convert first, ordered lists number per list, cell pipes are escaped, and a headerless table gets a header.
- `noindex` is for a twin of an HTML page; a document with no HTML page (AGENTS.md) leaves it off.
- `cacheTagHeaders(tags)` with the tags the save path revalidates, or the CDN holds a route handler's twin past every save. The same goes for `llms.txt`, a search index and a sitemap.
- Next drops a rewrite destination's query string, so a twin rewrite carries the `.md` extension through to its destination.

## Conditional GET and route errors

`wiki-formant/http`: validators, the headers of every text surface, and the answers a route gives when it is not answering with data.

```ts
import { corpusValidatorsFrom, corpusRoute, errors, handleRoute, HttpError } from 'wiki-formant/http';

export const GET = corpusRoute(async () => {
  const agg = await prisma.page.aggregate({ _count: true, _max: { updatedAt: true } });
  return corpusValidatorsFrom([agg._count], [agg._max.updatedAt]);
}, buildCorpus);

export const POST = (req: Request) => handleRoute(async () => {
  const q = new URL(req.url).searchParams.get('q');
  if (!q) return errors.badRequest('q is required');
  if (q.length > 200) throw new HttpError(400, 'q is too long', { code: 'INVALID_PARAMS' });
  return Response.json(await search(q));
}, 'Search failed');
```

- `corpusEtag`, `notModified` and `textHeaders` are the parts; `corpusRoute` skips the build on a 304.
- A URL answering JSON or markdown by `Accept` asks `wantsMarkdown(request)` and sends `VARY_ACCEPT` on both branches.
- `descriptorResponse` serves a JSON descriptor with its own ETag and `Access-Control-Allow-Origin: *`.
- Every error body is `{ error, ...extra }`. A thrown `HttpError` answers with its status, a thrown `Response` (`errors.tooManyRequests(sec)`, say) is the answer as built; anything else is logged and answered with a 500 carrying only the handler's message (`'Search failed'`), so no exception text reaches a caller. `errors.tooManyRequests(sec)` states `Retry-After`.

## Response headers and the Next config

`wiki-formant/headers`: the headers every route sends, the shared CSP, and the Next config defaults. It imports nothing, so `next.config.ts` pays for nothing it does not use.

```ts
import type { NextConfig } from 'next';
import { contentSecurityPolicy, withWikiDefaults } from 'wiki-formant/headers';

const csp = contentSecurityPolicy({ 'connect-src': ["'self'", 'https://*.radixdlt.com'] });
export default withWikiDefaults({ async redirects() { /* … */ } } satisfies NextConfig, { csp });
```

`withWikiDefaults(config, { csp })` adds:

- The security headers on every route, `csp` enforced in production only (Next's dev runtime is inline and `eval`); an origin with a per-request nonce passes none.
- `/openapi.json` rewritten to `/.well-known/openapi.json` first in `beforeFiles`, merged with the app's own `rewrites()` in either form.
- AVIF before WebP, `turbopackFileSystemCacheForBuild: false` (Vercel restores a stale build cache), and `distDir` from `STUDIO_DIST_DIR` for radix-studio's second dev server.

What the app sets wins, and its `headers()` follow these. `contentSecurityPolicy` starts from the shared base and each directive passed replaces its default; an empty list drops one. The default `frame-src` is `DEFAULT_IFRAME_HOSTS`, the sanitiser's default `iframeHosts`, so an embed that clears one clears the other; a site with its own hosts passes the same list to both.

## Pagination, versioning and rate limits

```ts
import { parsePagination, paginatedResponse, listEnvelope } from 'wiki-formant/pagination';
import { bump, parseVersion } from 'wiki-formant/versioning';
import { limitClient, rateLimitedResponse } from 'wiki-formant/rate-limit';

const { page, pageSize } = parsePagination(searchParams);            // page ≥ 1, pageSize 1–100
return Response.json(paginatedResponse(items, total, page, pageSize)); // always carries totalPages

bump(page.version, 'minor');                                           // tolerant of null or junk

const limit = limitClient('search', request.headers, { capacity: 30, refillPerSec: 0.5 });
if (!limit.ok) return rateLimitedResponse(limit.retryAfterSec);
```

- `listEnvelope` is the shape every list tool answers with, its `note` on an empty page.
- `rateLimit` is an in-memory token bucket; `blockMs` blocks an abusive key outright across every bucket naming it. `cost` spends more than one token on a call, which is how `mcpResponse` charges a batch for each call it carries. `clientIp` reads `x-real-ip` first, then the leftmost `x-forwarded-for`. `MCP_RATE_LIMIT` is the MCP servers' budget.

## React

`wiki-formant/react` carries `'use client'`. What is shared is behaviour; class names and icons are passed in.

```tsx
// A Next layout passes the rail its data: `wiki-formant/next`'s `Rail` brings the router's link and pathname.
import { Rail } from 'wiki-formant/next';

<RailFrame rail={<Rail label="Wiki" nav={[{ href: '/', label: 'Home' }]} groups={[{ label: 'Sections', links: sections }]} />}>
// The page hands up its headings.
<RailHeadings headings={article.headings} />
```

`wiki-formant/next` (`'use client'`, `next` an optional peer) is `Rail` bound to `next/link` and `usePathname()`, `/index` read as `/`; a `pathname` prop overrides the router's. Off Next, `wiki-formant/react`'s `Rail` takes `pathname` and `link` itself.

- `SidebarProvider` / `useSidebar` hold the rail's collapse state, remembered across loads and defaulted from the viewport only when the reader never chose. Pair it with `sidebarBootScript` (`wiki-formant/sidebar`) in `<head>`, or a remembered-closed rail paints open first.
- `Rail` is every rail, in one order: a `title` (`.wiki-rail__title`), a `search` box, the unlabelled `nav` links, "On this page", then the labelled `groups`, an empty one left out. "On this page" lists the `headings` passed, or else those a page handed up with `RailHeadings`, which `SidebarProvider` holds; a heading a view draws rather than the stored HTML is added with `referencesHeading(id?, title?)` or `seeAlsoHeading(text, id?)` (`wiki-formant/headings`, callable on the server), the ids `ReferencesView` and `RelatedPages` use; `toc` sets its label, indent and offset.
- `RailShell` renders the rail's landmark, scroll wrapper and collapse states, and closes a mobile drawer on a followed link; mark the active link with `isRailLinkActive`. With its default `prefix`, `"wiki-sidebar"`, in a `.wiki-layout` beside `.wiki-layout__main`, `base.css` lays it out: a sticky column from 1024px, a drawer above the article below it. The site supplies `--rail-top`, `--rail-border` and `--rail-bg`.
- `RailToggle` is the button that opens and closes the rail, a menu glyph and a cross while open, drawn by `base.css` as every header button, `.header-btn` (`--header-btn`, `--header-btn-radius`, `--header-ink`, `--header-ink-hover`, `--header-btn-hover`). It goes at the leading edge of the header, inside the `SidebarProvider`, on the pages that have a rail.
- `Menu({ label, trigger, children })` is a panel that opens from a button and hangs from it, on the browser's `popover`: a click outside, Escape and another menu shut it, as does a link or button inside unless it carries `data-keep-open`. Its contents render the first time it opens, and its button is lit while it is open. `base.css` draws it as `.menu`, its rows `.menu__item` (`--danger` for one that signs out or deletes), a heading `.menu__label` and a rule `.menu__rule`; the button is a `.header-btn` unless `triggerClassName` says otherwise.
- `AccountSlot({ status, avatar, children, signIn, pending })` is the header's account corner: `pending` (a `.account-slot__pending` disc by default) while `status` is `unknown`, `signIn` when `signedOut`, and a `Menu` on `avatar` holding `children` when `signedIn`.
- `HeaderNav({ links, label, pathname, link, prefetch })` is the header's links in `nav.header-nav`, one row that scrolls sideways rather than wrapping, each `.header-nav__link` (a link's own `className` added) and the one being read `aria-current` (`page`, or `true` beneath a `tree` link) by `isRailLinkActive`; a link to another origin is an `<a>`. It reads the header tokens and `--header-nav-gap`, `--header-nav-pad`, `--header-nav-weight`. `wiki-formant/next`'s `HeaderNav` is it on Next's link and pathname.
- The breakpoint is known twice, in `matchMedia` and in CSS. `base.css` sets `--rail-floating: 1` inside its media query and the hook warns in development when the two disagree; a rail laid out by its own CSS sets the property the same way. `railBreakpointMismatch` and `readRailFloating` (`wiki-formant/sidebar`) are the mechanism.
- `treeRailLinks(nodes, base, glyph?)` (`wiki-formant/react-server`, so a server layout can call it) walks a category tree (`WikiNode[]`) into rail links under `base`: each node a section titled by its description, its children opening on its trail, a hidden node left out with its subtree.
- `RailGroup` is a labelled group of rail links (`RailLink`: `href`, `label`, `icon`, `glyph`, `title`, `tree`, `children`; a `glyph` is drawn in `.wiki-rail__glyph`, hidden from a screen reader) in the `wiki-rail__*` classes `base.css` draws. The link being read is lit with `aria-current="page"`, a section with `aria-current="true"` while the reader is beneath it, and a link's `children` open while the reader is on its trail, the deepest link on it the one lit.
- `TableOfContents` is the "on this page" list with scroll-spy over the `headings` it is given, read from the article's source with the ids the server gave them, never scanned from the DOM; each entry is a `#section` link, so a section is in the URL to share. Unless given, its classes are the rail's (`wiki-rail__toc-*`), its icon a chevron and its offset `--rail-top`.
- `WikiLinkPreview` is the hover card over the internal links in `scope`, each asked of `GET <endpoint>?path=`, which answers `LinkPreviewData` (`title`, `excerpt`, `bannerImage`) or 404. Its props are data, so a server layout mounts it; `container` names a query container the card is drawn inside.
- `useLinkPreview` is the hover card: one delegated listener, an intent delay, a grace period into the card, viewport clamping and a per-href cache of answers; a `fetch` that throws is asked again on the next hover, a null is cached as no card. `LinkPreviewCard` is its markup (`link-preview-card`, `-banner`, `-body`, `-title`, `-excerpt`); a caller that must move the card passes its own `style`.
- `useTypeahead` is the search field's state machine: a request-id guard, keyboard navigation, abort and a per-mount cache. `results` is `idle`, `searching`, `found` or `failed`, so "no results" is `found` with none and a failed search is never cached; `items` is the rows on screen. `clearItems` dismisses the list and keeps the query; `reopen` asks for that query again (from the cache where it can), so a refocused field shows its list without a keystroke. `fetch` must be referentially stable. Its `combobox(listKey)` hands out `inputProps`, `listProps` and `optionProps(i)`, with `aria-activedescendant` omitted rather than emptied; `listKey` keeps two rendered lists' ids apart. The arithmetic is `wiki-formant/combobox`, which imports nothing.
- `SearchField` is the search box every wiki shares, on `useTypeahead`: a GET `<form>` to `action` with `name="q"`, the first few rows under it as links (`hrefOf`, `renderRow`), a last row to `action?q=`, and a note for a failed or empty search. Enter opens the results page unless the arrows chose a row; Escape and a click outside shut the list; "/" reaches it, calling `reveal` first for a field hidden in a closed rail. An `icon` folds it to a magnifier until opened, and again when left empty or a row is followed: that is `SearchFold({ label, icon, href, at, className, toggleClassName, children })`, which wraps any search form of a site's own the same way (`<search data-folded>` > the toggle while folded; "/" opens it and focuses its input; Escape or a blur with the input empty folds it, as does a change of `at`, the page it was opened on). Its classes are always `search-field` > `__form` > `__input`, `__toggle`, `__list` > `__item` (`--active`; the last row also `__all`), `__note`, which `base.css` draws as a dropdown on the `--ui-*` tokens; `classNames` adds a site's own to each. `navigate` (the router's push) and the words (`all`, `empty`, `failed`) are the site's.
- `useSnapRow` is a carousel as a scroll-snapped row: `step`, `go(i)` and `at`, no markup.
- `useClickOutside` ignores a container hidden at the current breakpoint (`offsetParent`).
- `useUnsavedChanges(dirty)` asks before leaving and returns `confirmLeave()` for a client-side navigation; `useSaveShortcut(save)` binds ⌘S / Ctrl+S; `useSearchShortcut(open)` is "/" to search, with `focusShown(input)`.
- `SortHeader` renders `useTableSort`'s `headerProps(key)` as a `<th aria-sort>` holding a `<button>`, the markup `sortTables` writes.
- `useBlockOperations(blocks, setBlocks, { duplicate })` and `BlockActions` are a block list's five edits and their buttons; `useRevisionRestore(restore, { onRestored })` confirms and restores, `restoreViaPost(endpoint)` being the usual `restore`.
- `useArticlePasses(ref, [blocks])` runs `wiki-formant/dom`'s passes and renders math with KaTeX (an optional peer, loaded only when a page has `$$…$$`, `\[…\]` or `\(…\)`).
- `<Beacon />` sends page views and outbound clicks to `wiki-formant/analytics`.
- `toast.success(message)` and `toast.error(message)`, with an optional `action` link and `duration`, raise a toast from any code; `toast.carry(message)` shows one on the page a full load reaches. `Toaster`, which `SiteShell` mounts, stacks them above the dock, `.toast-stack` > `.toast.toast--success|error` > `.toast__message`, `.toast__action`, `.toast__close`, drawn by `base.css` on the `--ui-*` tokens.
- `RouteError` is what `error.tsx` draws: an `EmptyState` with the heading, an optional `description`, Try again (Next's `retry`, never `reset`) and Home (or `home`); the button is `.btn-primary`, the class every site gives its primary button, unless `buttonClassName` names another. `GlobalRouteError` is `global-error.tsx`: the document, `.app-shell` and `main#main.app-main.page-frame` around a `RouteError`, with `htmlClassName` for the font variables the root layout sets on `<html>`; the file imports the site's stylesheet and fonts itself.

`useClickOutside`, `useSnapRow` and the editor hooks ship no class names.

## Server components

`wiki-formant/react-server`: the same React without the directive, for parts that are pure functions of their props. Each takes the router's link component, since a bare `<a>` turns every press into a full load.

```tsx
import Link from 'next/link';
import { Breadcrumbs, FacetBar, FacetSummary, InfoboxFacts, JsonLd, Pager } from 'wiki-formant/react-server';

<Breadcrumbs link={Link} items={tree.crumbs(path)} base={SITE_URL} />
<FacetBar link={Link} facets={groups} letters={letters} alphaFirst />
<Pager href={p => `?page=${p}`} page={page} total={totalPages} noun="Page" />
```

- `Highlight({ text, query, lead })` marks where a search's words fall in a result's title or snippet, in `<mark class="search-mark">` (`base.css` sets it in bold), matched as the search matched: case and accents ignored, a hyphenated word as its parts, each word anywhere and its stem at the start of a word, no stop words or excluded `-words`. `lead` starts a snippet at most that many characters before its first mark, after an ellipsis, so a line-clamped snippet keeps its mark in sight. `wiki-formant/highlight`'s `highlightRanges(text, query)` is the same answer as ranges, for a caller that must know whether a text is marked at all.
- `EmptyState({ title, description, action, as, className })` is "there is nothing here": a 404 (`as="h1"`), an empty table, a filtered-out grid. `.empty-state` > the title (`h1`, or `p.empty-state-title`), `.empty-state-desc`, `.empty-state-action`; `base.css` stacks and centres it, the site sets its look on the `--empty-*` tokens.
- `NotFound({ site, link, buttonClassName })` is what `not-found.tsx` draws: an `EmptyState` in `.not-found` titled "Page not found", `site.notFound`'s `description` under it, and its `home` (the front page, Home, unless given) as a `.btn-primary` link.

- `FacetBar` renders `facetControls` and `alphaControls`; `letterRow`, `letterControl`, `text` and `letterCounts="title"` separate the A–Z row and let a label truncate while its count stays.
- `Breadcrumbs` renders the trail and its `BreadcrumbList` JSON-LD together; `base` makes the URLs absolute.
- `JsonLd` escapes every `<`, so an authored `</script>` cannot close the tag.
- `SiteDocument` is the root layout's `<html>`: the rail's boot script and the `site`'s `SiteLinks` in the head, its `JsonLd` graph and `Beacon` (`beacon`, on by default) in the body, `suppressHydrationWarning` for the attribute the script stamps. Other props go on `<html>`; `bodyClassName` on the body.
- `SiteShell` is `base.css`'s shell under `SidebarProvider`: `.app-shell` > skip link, `header.app-header` (around `header`, which is its contents), `main#main.app-main.page-frame`, the footer (a `SiteFooter` of `site`'s `footer` with `link`, unless `footer` gives another): the main is the column, so no page frames itself, bar a full-width `.page-bleed` band that draws its own `.page-frame` (`frame={false}` for a site that draws its own column). `RailFrame` is a section layout's rail beside its column, `.wiki-layout` > `rail` + `.wiki-layout__main` > `.page-frame`, inside `main`, where the main's frame gives way to it; it mounts `WikiLinkPreview` over the column from `/api/wiki/preview` unless `preview` names another `endpoint` or is `false`. Given a site with a `logo` (`defineSite`'s), the shell leads the header with `RailToggle` and the mark as a link home, `.header-logo`, named for `site.name`, ahead of `header`; a header drawn without one puts `RailToggle` first itself. `base.css` hides the toggle on a page with no rail. A `dock` is pinned to the window's foot in `.dock`, a click-through strip whose buttons are `.dock-button` (`--dock-button`, `--dock-inset`, and the look `--dock-bg`, `--dock-ink`, `--dock-border`, `--dock-shadow`, `--dock-hover`); `DockLink({ href, label, link })` is a disc that is a link, its glyph the children. The shell mounts the `Toaster`. With no `header` it draws none; other attributes go on the shell's box; `prefix` renames the boxes (`<prefix>-shell`, `-header`, `-main`) for a host that styles a shell of its own and keeps the skip link and landmarks.
- `SiteFooter` is `footer.app-footer`: the site's own matter (`children`), a row of `links` ending on the `x` follow link, and `© <year> <owner>`, `Content licensed under <license>` and a `note` (a disclaimer, a credit). Given `site`, each comes from `defineSite`'s `footer` (`links`, `owner`, which defaults to the site's name, `license`, `note`) and `x`, a prop overriding its own.

```tsx
// @/lib/site
export const site = defineSite({ name, url, description, x: X, image, feeds, agentsMd: true, themeColor, graph: { logo }, logo: <Mark />, notFound: { description } });

// src/app/layout.tsx
export const { metadata, viewport } = site;
<SiteDocument className={fontVariables} site={site}>
  <SiteShell site={site} link={Link} header={<Header />} dock={<SearchButton />}>{children}</SiteShell>
</SiteDocument>

// src/app/not-found.tsx
export default function NotFoundPage() {
  return <NotFound site={site} link={Link} />;
}
```

- `SiteLinks` is the root layout's agent-surface `<link>`s: `/llms.txt` as `help`, the RSS `feeds`, the OpenAPI document as `service-desc` and the agent card as `service-meta` (`described`, on by default), `/AGENTS.md` as `service-doc` (`agentsMd`). React hoists them into `<head>` from anywhere. `service-desc` is never the MCP endpoint, which is POST-only.
- `Pager` steps by links (`href`) or buttons (`onPage`, `wrap`); a step with nowhere to go stays in place, inert. `SnapDots` are a snap row's dots.
- `FacetSummary` is the count and Clear line under the facets; `RelatedPages` the see-also aside; `InfoboxAside` the facts landmark with its series line; `InfoboxFacts` renders `metadataRows` with `formatFactValue` as its default cell.
- `RevisionChanges` renders `withChanges` rows; `MaintenanceQueues` renders `maintenanceQueues`; `Cite` is an article's citation in a `<details>`.
- `ArticleMeta` is an article's provenance line, `ul.article-meta`: `children` (who wrote it), Updated (`updated`, or `updatedLabel`), `version`, `revisions` (linked to `historyHref`), `verified`, the `license` and `cite`. `PageWithInfobox` sets a body beside its `infobox` in `.page-with-infobox` > `.page-main-content`, and is the body alone without one.
- `SectionIndex` is a front page's or a section page's listing (STRUCTURE.md S12): `groups` of `{ title, href, blurb, glyph, count, sections, pages, more }`, each `.wiki-cat` headed by a link to its section (`.wiki-cat__head`, its heading at `level`) and its `blurb` (`.wiki-cat__blurb`), its sections as `IndexCards` (`.wiki-grid--sections` of `IndexCardLink`, `.wiki-card--section` with a glyph, status, count, blurb and an optional banner `thumb`) and its pages as title tiles in `.wiki-grid`, the blurb a tooltip. `base.css` draws them on the `--ui-*` tokens; `--index-glyph` inks the marks and `--index-edge` a section card's leading edge.

## Block trees

`wiki-formant/blocks`: the two core containers (`columns[i].blocks`, an infobox's `blocks`), the walks over them, and the core leaves' text, markdown and defaults.

```ts
import { coreBlockShape, mapBlockTree, coreAtomicToMarkdown, coreBlockDefaults } from 'wiki-formant/blocks';

export const BLOCK_SHAPE = coreBlockShape<Block>();
mapBlockTree(blocks, processLeaf, BLOCK_SHAPE);

switch (block.type) {
  case 'content': case 'codeTabs': case 'banner': case 'references':
  case 'stats': case 'linkGrid': case 'recentPages': case 'pageList':
    return coreAtomicToMarkdown(block, { siteUrl: SITE_URL, referencesTitle: 'Sources' });
  case 'corpusStats':
    return block.resolvedHtml ? htmlToMarkdown(block.resolvedHtml) : '';
}
```

- The dispatch over a repo's own union stays in that repo, so a new type is a compile error there; the core bodies come from here (`coreAtomicText`, `coreAtomicToMarkdown`, `coreBlockDefaults`).
- The core leaves are `content`, `codeTabs`, `banner`, `references`, `stats`, `linkGrid`, `testimonial`, `events`, `locations`, `recentPages`, `pageList` and `list`. `CoreLeafBlock` is their union (less the list and containers) and `CoreLeafType` its types; a wiki's atomic union is `CoreLeafBlock | ListBlock | its native types`, and a leaf added here fails to compile in every wiki until wired.
- `coreAtomicToMarkdown` makes a resolved page's `href` absolute with `siteUrl`, since a twin is read off-site.
- A `codeTabs` tab's `code` is source text: escaped by its view, fenced verbatim by the twin. Pass `highlighted` to the view for server-highlighted markup. `CODE_LANGS` and `DEFAULT_LANG` are the language list.
- `recentPages`, `pageList` and `list` resolve to `ResolvedPageRef`s built with `pageRef(page, now)`.
- `ListBlock` is the pages under a section (`source: 'under'`), the newest (`'newest'`, `count`) or chosen ones (`'chosen'`, `pages`), shown as links or cards.
- An `events` item is `{ id, date, end?, text }`, dated to the year, month or day (`EVENT_DATE`); `splitEvents`, `eventWhen`, `eventBegun` and `eventEnded` split upcoming from past by a `day`, which the browser re-splits by the visitor's own.
- A `testimonial` is `{ quote, author, role?, avatarUrl? }`. A `locations` item carries an address, `hours` rows of `{ days, opens, closes }` and a `timeZone`.

## Validation

`wiki-formant/validation`: the block model in one declaration, and the checks under it.

```ts
import { defineBlocks, describeBlockIssues } from 'wiki-formant/validation';
import { coreBlockDefaults } from 'wiki-formant/blocks';

const model = defineBlocks<Block>({
  defaults: { ...coreBlockDefaults(), corpusStats: () => ({ type: 'corpusStats', view: 'sourceTiers' }) },
  checks: { corpusStats: b => isCorpusView(b.view), list: (b, core) => core(b) && isSection(b.under) },
});
export const { shape: BLOCK_SHAPE, createBlock, duplicateBlock, validateBlocks, blockIssues } = model;

const issues = blockIssues(body.content);
if (issues.length) return errors.badRequest(`Invalid content: ${describeBlockIssues(issues)}`);
// Invalid content: [2].columns[0].blocks[1]: malformed linkGrid block
```

- A check for a core type narrows the package's (`core` is passed in).
- `MAX_BLOCK_ROWS` caps `recentPages.limit` and `pageIds`, since both end in a database `take:`; `blockLimit` is the read side.
- `safeLinkHref` is the link check the views rely on.

## Block views

`wiki-formant/block-views`: the views of the core leaves, as client components that render server-side.

```tsx
import { CodeTabsView, ColumnsView, LinkGridView, PageRefsView, StatsView, EventsView, LocationsView, BannerView } from 'wiki-formant/block-views';

case 'codeTabs': return <CodeTabsView tabs={block.tabs} />;
case 'columns':  return <ColumnsView columns={block.columns} gap={block.gap} render={renderBlock} />;
case 'pageList': return <PageRefsView refs={block.items} link={Link} renderItem={row} />;
```

- `ColumnsView` states its gap and alignment as data attributes and an inactive code tab is `hidden`, so no view needs Tailwind to scan the package.
- `TestimonialView` is `figure.testimonial`; pass `photo` for sized images.
- `EventsView` sets upcoming soonest first and past latest first, with "Now on" beside one begun; `day` fills the server's split.
- `LocationsView` draws each place's address, week (`PlaceHours`), note and map; the browser adds whether it is open by the place's clock, once a minute. `wiki-formant/hours` holds those rules (`hoursRows`, `openState`, `clock`, `hoursLd`, `mapHref`, `mapEmbed`) for a twin or structured data; a closing time at or before the opening one is the next morning, and `DEFAULT_ZONE` is `Europe/London`.
- `BannerView` shows `BANNER_MESSAGES` (`wiki-formant/text`) unless `message` overrides it.

## Text

`wiki-formant/text`: a block tree as plain prose, for an LLM export or a description.

```ts
import { openingText, plainText, stripHtml } from 'wiki-formant/text';
import { describe } from 'wiki-formant/metadata';

const description = describe(page.metadata?.excerpt || openingText(page.content));
```

`openingText` is the first top-level `content` block with prose once headings are out, so a page opening on an infobox is not described by its table. `matchSnippet` is a search hit's line.

## Page metadata

`wiki-formant/metadata`: a page's canonical, markdown alternate, Open Graph and Twitter card from one input, and the schema.org nodes beside them.

```ts
export const generateMetadata = () => ({
  title,
  ...pageMetadata({ title, description, url, type: 'article', image: ogImageUrl(title), siteName, handle, markdownTwin: true }),
});
<JsonLd data={articleLd({ headline: title, url, image, published, modified, publisher: SITE.publisher, citation: citationsFromReferences(refs) })} />
```

- `defineSite({ ...rootMetadata's options, x, feeds, agentsMd, themeColor, graph, footer, logo, notFound })` is a site's identity stated once in `@/lib/site` (a `.tsx` module where its `logo` is markup): it returns the facts (`name`, `url`, `description`, `x`) and what each surface takes, `metadata` and `viewport` for the root layout, `links` and `graph` for `<SiteDocument site>`, `footer` and `logo` for `<SiteShell site>`, `notFound` for `<NotFound site>`. The handle and the graph's `sameAs` come from `x`; `graph` adds to `siteGraphLd`'s options or overrides them.
- `rootMetadata({ name, url, description, title, image, handle, keywords, icons })` is the root layout's `metadata`: title template, robots, and an inherited card with no title, description or URL, which Next fills from each page's own; the site's name as author, creator and publisher; and Search Console and Bing verification from `GOOGLE_SITE_VERIFICATION` and `BING_SITE_VERIFICATION` where set.
- Next replaces `openGraph` and `twitter` per segment rather than merging, so `pageMetadata` sets both; `sitePageMetadata({ siteName, handle })` binds the fields every page's card needs.
- `sitePageMetadata({ ..., card: `${SITE_URL}/og` })` binds the site's card route, and a page then passes `card: { title, eyebrow, description, banner }` in place of `image`. `cardUrl(base, fields)` is the same address for JSON-LD: empty fields left out, the order fixed, so one card has one URL.
- `articleLd` requires `image`. `collectionLd` is an index over an `ItemList`. `siteGraphLd` is the Organization, WebSite and `WebAPI` `@graph` for the root layout (search defaults to `/search?q=` on the origin, the API's documentation to its `llms.txt`), and `siteRefs(url)` hands out the same `@id`s for a page's `publisher` and `isPartOf`.
- `questionPairs(html)` reads a FAQ from headings ending in `?`; `faqPageLd(pairs, url)` is null under two pairs.
- `describe(text)` is a meta description from any prose within 160 characters: whole sentences where they fill half, else cut at a word with an ellipsis.

## Social cards

`wiki-formant/og`: the `/og` card, as the element `next/og`'s `ImageResponse` takes.

```tsx
import { SocialCard, bannerField, bubbles, cardRandom, OG_SIZE, OG_HEADERS } from 'wiki-formant/og';

const field = (await bannerField(searchParams.get('banner'), /\.public\.blob\.vercel-storage\.com$/))
  ?? bubbles(cardRandom(title), { field: [BG, NAVY], colors: [GREEN, ORANGE] });
return new ImageResponse(<SocialCard {...{ title, eyebrow, description }} {...field} mark="example.org" colors={colors} fontFamily="Inter" />, { ...OG_SIZE, headers: OG_HEADERS, fonts });
```

- A page's banner is its card; the generated field is for a page without one. `bannerField` fetches only from the hosts named, crops, inlines PNG and turns the scrim on, or returns null. It loads `sharp`.
- Fonts stay with the site: Next traces a font file only from a literal path in the app, and satori reads TTF or OTF.
- `wiki-formant/seeded`'s `hashStr` and `seededRandom` are the deterministic randomness the art draws from, identical on server and browser.

## Page banners

`wiki-formant/banner`: the banner a page is headed with, its own picture or art seeded by the page.

```tsx
import { PageBanner, CardBanner } from 'wiki-formant/banner';

<PageBanner seed={page.title + page.tagPath} picture={banner && <Image src={banner} alt="" fill preload sizes="100vw" />}>
  <Breadcrumbs items={crumbs} />
  <h1>{page.title}</h1>
</PageBanner>
<CardBanner seed={page.title + page.tagPath} picture={card.banner && <Image src={card.banner} alt="" fill sizes="33vw" />} />
```

- Every page has a banner: a page without a picture gets art seeded by `seed`, the same on every render, server and browser. `CardBanner` is the same picture or art at the top of the page's card, cropped to 4:1; seed both alike, so a card and its page match.
- A listing carries `banner`, the picture both show: `metadata.banner` unless the store's `banner` option reads it elsewhere, such as the article's first picture.
- The art is inline SVG with a class per role, coloured by custom properties: `--banner-from` and `--banner-to` the gradient (transparent unset), `--banner-mid` the blobs and half the shapes (`--ui-muted` unset), `--banner-ink` the rest and the dots (`--ui-accent` unset), over `--banner-field` (`--ui-surface` unset). A category's palette or a section's band is a style on the frame.
- `mark` replaces the triangle with a wiki's own shape, as a path from its anchor, size and generator. `fill-opacity` on a role's class dims it under a title.
- The frame's 4:1 is a floor, not a height (`base.css`): the trail and title grow it rather than being cropped.

## Revisions and history

`wiki-formant/revisions`: what changed between two versions of a page, and which bump to ask for. `wiki-formant/history`: what each revision changed, as a history view shows it.

```tsx
import { computeRevisionDiff } from 'wiki-formant/revisions';
import { withChanges } from 'wiki-formant/history';

const diff = computeRevisionDiff({ currentVersion: page.version, oldContent, newContent, oldTitle, newTitle });
const rows = withChanges(revisionsNewestFirst);   // each row needs its `content`; it leaves without it
<RevisionChanges changes={rows[0].changes} label={type => BLOCK_LABELS[type]} />
```

- Blocks match by id, so a moved block is one `moved`. Container keys are walked as their own entries, never diffed as attributes. A path like `root.1.columns.0.blocks.2` is part of the contract; pass `containers` beyond the core two.
- `withChanges` diffs on the server, by words, leaves only. The oldest row is diffed against an empty page, so fetch one more than you show.

## Feeds and sitemaps

```ts
import { feedResponse } from 'wiki-formant/feed';
import { treeSitemap, tagPrefixes } from 'wiki-formant/sitemap';

export const GET = async (request: Request) => feedResponse(request, channel, await items());

...treeSitemap(pages, {
  sections: tagPrefixes(pages.map(p => p.tagPath)),
  sectionRow: path => ({ url: `${SITE_URL}/wiki/${path}`, changeFrequency: 'weekly', priority: 0.6 }),
  pageRow: p => ({ url: pageUrl(p), changeFrequency: 'weekly', priority: 0.7 }),
}),
```

- `feedResponse` answers a conditional GET; `lastBuildDate` is the newest item's date, and an empty feed carries none.
- A section is dated by the newest page at or beneath it, or not at all. Every URL appears once: an empty-slug page dates its section and gets no row.

## Licences and the X account

```ts
import { ccBy40, licenseBlock, openApiLicense } from 'wiki-formant/license';
import { xAccount, followLines, followNote, followLinkProps } from 'wiki-formant/social';

const license = ccBy40({ siteName: 'AcuiQ', siteUrl: SITE_URL });
const block = licenseBlock({ license, scope: 'The protocol compilation and prose', excludes });
export const X = xAccount({ siteName: 'AcuiQ', handle: '@acu_iq', posts: "a named trial's prescription with its citation" });
```

- One `License` goes to `licenseBlock`, `agentCard({ license, licenseScope })` and `openApiDocument`, which sets `info.license` from it.
- `X.url` is the `sameAs`, `X.handle` the card's, `followLines(X)` goes into llms.txt and AGENTS.md, `followNote(X)` into the MCP instructions, and `<a {...followLinkProps(X)}>` is the footer link with `rel="me"`.

## Agent descriptors

`wiki-formant/well-known`: the A2A agent card, the MCP manifest and server card, and the registry's domain proof.

```ts
import { agentCard, mcpManifest, skillsFromTools, wellKnownHandler, serverCardHandler } from 'wiki-formant/well-known';

const AGENT_CARD = agentCard({ name, description, url: `${SITE_URL}/api/mcp`, version, skills: skillsFromTools(TOOLS), license });
// src/app/.well-known/[doc]/route.ts
export const GET = wellKnownHandler({ agentCard: AGENT_CARD, mcpManifest: mcpManifest({ … }), openapi: SPEC });
```

The card is served at `agent-card.json`, and its `url` is the MCP endpoint, which answers A2A. The well-known routes serve `MCP_REGISTRY_PUBLIC_KEY` at `/.well-known/mcp-registry-auth`, 404 when unset.

## OpenAPI

`wiki-formant/openapi`: the frame of the spec `wellKnownHandler` serves, and the paths every site shares. A spec writes only its own paths.

```ts
import { openApiDocument, jsonBody, jsonResponse, toolBody, llmsTxtPath, mcpPath } from 'wiki-formant/openapi';

export const SPEC = openApiDocument({ title, version, description, license, siteUrl: SITE_URL }, {
  '/api/wiki/{path}': { put: { requestBody: toolBody(toolInput('edit_page'), { inPath: ['tagPath', 'slug'], refs: { Block: BLOCK_SCHEMA } }), … } },
  '/llms.txt': llmsTxtPath('Index of every page (plain text)'),
  '/api/mcp': mcpPath(TOOLS.map(t => t.name)),
}, { schemas: { Block: BLOCK_SCHEMA } });
```

`toolBody` is a write tool's input schema as the REST body, so `openapiWriteParity` holds by construction. `mcpPath` states the protocol versions, the batch cap and `MCP_RATE_LIMIT_TEXT`; `llmsTxtPath` the `If-None-Match` and its 304.

## AI crawlers

`wiki-formant/crawlers`: one roster of AI crawlers, for the proxy that counts them and the robots.txt that addresses them.

```ts
import { trackAiBot, crawlerRules } from 'wiki-formant/crawlers';

trackAiBot(request, event, () => import('@/lib/track'));   // in proxy.ts
const rules = crawlerRules({ allow: '/', disallow, aiAllow });
```

- Every agent group allows the agent surface (`/api/mcp`, `/llms.txt`, `/openapi.json`, `/.well-known/`); `aiAllow` adds the origin's own.
- Search engines get the HTML site and no twins (`/*.md$`, plus `searchDisallow`). The `?_rsc=` prefetch payload is refused in every group.
- `trackAiBot` counts a rostered crawler anywhere, and anything but a search engine asking for what only agents read. `load` is a dynamic import so the proxy does not load a database client.

## Rendered-article passes

`wiki-formant/dom`: what runs against an article element once it is in the document.

```ts
import { addCopyButtons, sortTables, activateTabGroups, hydrateTweetEmbeds, onTweetResize, sizeTweetEmbed } from 'wiki-formant/dom';

addCopyButtons(el);
sortTables(el);
activateTabGroups(el);
hydrateTweetEmbeds(el);
const off = onTweetResize((h, source) => sizeTweetEmbed(el, h, source));
```

- Each pass is idempotent.
- `sortTables` sorts a column as dates, numbers or text (one stray value makes it text), restores the author's order on a third press, and leaves label/value and merged-cell tables alone.
- `activateTabGroups` makes stored `[data-tabs]` markup a working tab group; without script every tab shows in order.
- `onTweetResize` believes only the embed host and hands over the posting window, so `sizeTweetEmbed` sizes that iframe alone.
- `scrollTables(html)` (`wiki-formant/headings`) wraps each table in a `.table-scroll` box on the string, before layout.
- `track(name, props)` sends a browser event to the analytics beacon.

## Search

`wiki-formant/search`: what a literal tier and a full-text tier must agree on: `proseSql`, `HEADLINE_OPTIONS`, `FTS_RANK_NORMALIZATION`, and `searchTsvDdl(table)`, the statements that drop and re-add the generated `search_tsv` column and its index in one transaction. `fullTextQuery` is a query as the full-text tier reads it, a hyphen or underscore inside a word a space; `correctQuery(query, vocabulary)` corrects a query's misspelt words against a site's own, which the store's `search` retries with when its first page is empty, returning the query that found the rows as `corrected`.

```ts
const { column, index } = searchTsvDdl('"WikiPage"');
```

## Dates, freshness and the maintenance queues

`wiki-formant/freshness` and `wiki-formant/queues`.

```ts
import { relativeTime, formatDay, freshnessBanner } from 'wiki-formant/freshness';
import { maintenanceQueues } from 'wiki-formant/queues';

relativeTime(then, now, { style: 'short' });        // '3h ago'; `now` is always passed in
formatDay(day, { locale: 'en-GB', month: 'long' }); // '19 September 2026', always UTC
const banner = freshnessBanner(page, Date.now(), { against: 'current sources and the live ledger' });
const queues = maintenanceQueues(pages, { href, required, nowMs, verify, listedIds });
```

- `freshnessBanner` is the `outdated` banner once a page goes unchecked for `maxAgeDays` (180), or null. `freshnessAge` is the days since a page was verified, or edited if never, and null when it carries neither, which `isStale` counts as stale.
- `maintenanceQueues` returns the outdated, orphaned, unsourced and missing-facts queues, empty ones dropped. Pass every page but the home page and the back office. `MaintenanceQueues` draws them on a `noindex` page.

## Sanitising stored HTML

`wiki-formant/sanitize`: the allowlist between saved HTML and a reader's browser. Run it server-side on the render path.

```ts
import { createHtmlSanitizer, sanitizeCoreLeaf } from 'wiki-formant/sanitize';

const clean = createHtmlSanitizer({ iframeHosts: FRAME_HOSTS });   // the same hosts in the CSP's frame-src
const safe = mapBlockTree(blocks, b => sanitizeCoreLeaf(b, clean), BLOCK_SHAPE);
```

- The default list is what `wiki-formant/tiptap`'s nodes store plus a presentational SVG subset. Extend `tags`, `attributes`, `classes` and `schemesByTag` from your stored HTML, never from memory.
- A YouTube iframe comes out as the YouTube node's markup, whoever wrote it, and `base.css` draws it as a 16:9 player.
- Classes pass by name only, since a site's own utilities can draw over the chrome.
- `sanitizeLine(html, { links })` cleans what a `WikiLine` stores: its marks and `wikiTextStyle`'s spans. `sanitizeCoreLeaf` runs it over the core leaves' one-line fields (a figure, a quote and who said it, the events' and places' headings, a place's name), which `block-views` draws as HTML.

## Image uploads

`wiki-formant/upload`: the route an editor's image upload posts to.

```ts
// src/app/api/upload/route.ts
export const runtime = 'nodejs';
export const POST = uploadHandler({
  authorize: async () => (await currentUser())?.id ?? errors.unauthorized('Sign in to upload.'),
  prefix: 'wiki/',
});
```

- The file's own bytes say what it is; SVG is refused. Every image is re-encoded upright, so no source metadata (GPS included) is kept. Defaults: 4 MB, 40 megapixels.
- Each uploader has a budget on `authorize`'s id and address, and each address its own.
- `encode`, `maxBytes`, `maxPixels`, `rateLimit` and `store` (Vercel Blob by default) are options. `normalizeImage(bytes, opts)` is the sniff, cap and re-encode without the route.

## Maps

`wiki-formant/maps`: a pasted Google or Apple Maps URL as one an `<iframe>` accepts.

```ts
import { toMapEmbedUrl, resolveMapHandler } from 'wiki-formant/maps';

toMapEmbedUrl('https://maps.apple.com/?ll=51.5,-0.12');
export const GET = resolveMapHandler({ authorize: async () => !!(await currentUser()) });   // /api/resolve-map
```

A short link resolves through the wiki's own route (`resolveMapUrl` is the client half): exact shortener hosts, one hop, an allowlisted landing host, a timeout and your sign-in check. A pasted short link inserts as a placeholder at once and `settleMapEmbed` settles it: the embed, or, when the link cannot be resolved, the link itself as text, never a blank frame.

## Editor nodes

`wiki-formant/tiptap`: the custom nodes: `embedNodes` (an iframe, YouTube with its paste rule, an X post and a map), `createCodeBlock`, `createTabs` and `createHeadingIds`.

```ts
import { embedNodes, createCodeBlock, createTabs, createHeadingIds } from 'wiki-formant/tiptap';

const { TabGroup, TabItem } = createTabs();
const nodes = [...embedNodes({ resolveMapUrl }), createCodeBlock({ classNames, icons }), TabGroup, TabItem, createHeadingIds({ slug })];
```

- `embedNodes` turns a pasted YouTube, X or map link into its player. The iframe and map nodes draw only an https src on `DEFAULT_IFRAME_HOSTS`, since the editor draws stored HTML where its author is signed in; a site whose sanitiser takes its own `iframeHosts` passes `embedNodes` the same list, or the editor draws those frames empty and a save strips them.
- The node views draw in default classes `base.css` styles; `classNames` and `icons` replace them.
- `createTabs` returns both nodes, since one is unsatisfiable without the other. A short map link inserts at once and swaps its `src` when it resolves.
- `createHeadingIds` gives each heading the id its published copy will carry.

## Editor

`wiki-formant/editor`: the rich-text editor's engine, minus its chrome.

```tsx
import { useWikiEditor, useUrlPrompt, WikiToolbar, UrlPromptField, WikiLine, uploadImageTo } from 'wiki-formant/editor';

const url = useUrlPrompt(editor, { resolveMapUrl });
<WikiToolbar editor={editor} prompt={url} onUpload={triggerUpload}
  icons={{ ...ICONS, unlink: <Unlink />, upload: <Upload />, embed: <Globe /> }}
  classNames={{ toolbar: 'toolbar', button: 'toolbar-btn', pressed: 'toolbar-btn-on', divider: 'toolbar-divider' }} />
<UrlPromptField prompt={url} classNames={{ row: 'row', input: 'input', apply: 'btn', cancel: 'btn-quiet' }} />
<WikiLine as="h1" value={title} onChange={setTitle} placeholder="The page's title" />
```

- `WikiToolbar` shows each command the editor's extensions support (`supports`) and nothing else, in fixed groups, with the table controls while the cursor is in a table.
- `useUrlPrompt` is the link and embed field: it opens on the current link, unlinks on an emptied one, and closes when its editor changes.
- `WikiLine` is a one-line field with its own `marks`, undo and `onFocus`, so one toolbar can drive the field last touched. Its `style` mark is `wikiTextStyle`: a font, colour and size on a run of words, which an article editor takes through `nodes` and an app's own controls set with `setTextStyle`.
- A link is stored as its `href` and the `link` class only; whether it is external is decided at render by `articleHtml`'s `links` pass. `uploadImageTo('/api/upload')` is the `uploadImage` an editor passes: it resolves the URL or throws the route's reason, and `useWikiEditor`'s `upload` is `idle`, `uploading` or `failed` with that reason for the editor to show.

## Block editor

`wiki-formant/block-editor`: the block list an author edits and the fields of the core types. The look arrives as a kit.

```tsx
const KIT: BlockEditorKit = {
  classNames: { action: 'icon-btn', input: 'input', row: 'row', stack: 'stack-sm' },
  icons: { add: <Plus />, up: <ChevronUp />, down: <ChevronDown />, duplicate: <Copy />, remove: <Trash2 /> },
};
const SCHEMA: BlockSchema<Block> = {
  meta: type => BLOCK_META[type], create: createBlock, duplicate: duplicateBlock,
  types: PAGE_TYPES, nestedTypes: ATOMIC_TYPES, single: ['infobox'],
  renderBody: (block, onUpdate) => {
    switch (block.type) {
      case 'codeTabs': return <CodeTabsFields block={block} onUpdate={onUpdate} />;
      case 'columns': return <ColumnsFields block={block} onUpdate={onUpdate} />;
      case 'daoTimeline': return <DaoTimelineEdit block={block} onUpdate={onUpdate} />;
    }
  },
};
<BlockEditor blocks={blocks} onChange={setBlocks} schema={SCHEMA} kit={KIT} />
```

- Each block is a card with a toolbar (name, add below, move, duplicate, delete); an add menu of more than eight types opens on a filter box. An option's `group` heads it.
- The core fields are `CodeTabsFields`, `StatsFields`, `TestimonialFields`, `EventsFields`, `LocationsFields`, `ReferencesFields`, `LinkGridFields`, `BannerFields`, `PageListFields`, `ListFields`, `ColumnsFields` and `InfoboxFields`. `Field`, `Choice` and `LimitField` are for a wiki's own types.
- A type the build does not know is shown by its raw type and carried through untouched.
- Keep the kit and schema stable (a module constant or `useMemo`): both reach every card through context.
- An editor that draws blocks in place hosts the fields in `<BlockFieldsKit kit={KIT}>`.

## Analytics

`wiki-formant/analytics`: page views and events in the site's own Postgres. No cookie and no stored address: a visitor is a hash of address and browser under a salt replaced every UTC day. Rows are kept 400 days. A view is marked engaged once its reader has had the page visible fifteen seconds or given it input, so `engaged` counts people where `agents` counts crawlers. Its time on page is the seconds its page was in a visible tab, capped at an hour, sent as the reader hides the tab or moves on. The tables ship in `prisma/analytics.prisma`; `ViewDay` holds days a site counted elsewhere first, and `AgentDay` one row for each agent on each day, so an agent's requests are counted and not kept.

```ts
// src/lib/track.ts
const sql: Sql = (query, ...values) => prisma.$queryRawUnsafe(query, ...values);
export const { trackEvent, trackMcpCall, trackFeedback, trackSearch, viewRoute } = createTracker({ sql, defer: after, siteUrl: SITE_URL });

// src/app/api/view/route.ts
export const POST = viewRoute();
```

- `createTracker` records only on a Vercel production deployment unless `enabled` says otherwise. A beacon naming an event the server records is dropped: the tracker's own, and those an app records with `trackEvent`, which it lists as `events` and which `trackEvent` is then typed to. `trackMcpCall` fits `McpServerConfig.onCall`; `trackSearch` normalises a query and drops an empty one; `recordEvent` is the undeferred write.
- A proxy reaches the tracker through a dynamic `import()` inside `event.waitUntil`, since it imports the database client.
- `digest(sql, { days })` is the site as one JSON object: people, engaged people, agents, views, visits, bounce rate, median time on page, sources, pages, countries, devices, by day, agents by name, MCP calls, every search people made, every `search_wiki` query agents made, the searches of either that found nothing, and agents' `send_feedback` reports. A search its visitor went on typing within five minutes is left out, as is any of one character. A visit is a run of views with no gap over 30 minutes; a bounce is a one-view visit its reader never engaged with. Agents are counted beside people, never among them: the ranked lists are people's. `ownAgents` leaves the site's own out. A multi-tenant app passes `site`.
- A browser under automation (`navigator.webdriver`) sends no beacon.

## Passkeys and the stats page

`wiki-formant/passkey`: the door to a site's own admin pages, a passkey and nothing else. `wiki-formant/stats`: the stats page behind it.

```ts
// src/lib/admin.ts
export const gate = createPasskeyGate({ sql, rpName: 'Caper' });

// src/app/api/passkey/route.ts
export const POST = gate.route;
export const DELETE = gate.signOut;

// src/app/stats/page.tsx
const q = statsQuery(params);
return (
  <StatsGate gate={gate} session={(await cookies()).get(gate.cookie)?.value} invite={params.invite} host="caper.network">
    {async () => <Stats digest={await digest(sql, q)} {...q} link={Link} />}
  </StatsGate>
);
```

- There is no sign-up: every passkey is saved from a single-use link `npx passkey-invite` prints. A passkey is bound to its host. Deleting a `Passkey` row signs out every session it opened. Tokens are kept only as hashes (`prisma/passkey.prisma`).
- A challenge store that does not answer is a 503 (`SIGN_IN_UNAVAILABLE`, `wiki-formant/http`), never a refused passkey.
- `gate.signedIn(cookie)` is a page's check and `gate.allows(request)` a write route's.
- `statsQuery` reads `?days=` (1, 7, 30, 90, 365 or all) and the narrowings `?segment=`, `?page=`, `?entry=`, `?source=`, `?country=`, `?device=`, which stack and recount every figure from the visits that pass.
- `?segment=engaged` is the visitors who engaged, with every visit of theirs; `?segment=agents` is the agents, each one's day a visit and its requests that visit's views, and `visitors` the agents; `?segment=all` is people and agents together, each counted as its own segment counts it. The page switches between people, engaged, agents and all beside the windows, so its one Visitors figure and every other reads for each: the bounce rate of engaged visitors, an agent's views per visit. The segment is the switch, never a chip.
- Each headline figure shows its change from the window before (`.stats-delta[data-better]`) and charts on press. A narrowed page over `ViewDay` totals starts at `counted_from` and says so.

## ROLA sign-in

`wiki-formant/rola`: a Radix wallet sign-in up to the token: a single-use challenge, the wallet's proof, the HS256 session, and the two MCP tools that sign an agent in. How a site keeps the session stays with it.

```ts
import { createRola, sessionSecret, signSession, verifySession, bearerToken, rolaLoginTools } from 'wiki-formant/rola';

const rola = createRola({ expectedOrigin, dAppDefinitionAddress, networkId, applicationName, challenges: prisma.challenge });
const v = await rola.verifySignedChallenge(signed);        // { isValid, error? }; an outage throws a 503 HttpError
const secret = sessionSecret(process.env.JWT_SECRET);      // throws under 32 characters
const token = await signSession({ id: signed.address }, secret, 7 * 86400);
const claims = await verifySession<{ id: string }>(bearerToken(request.headers) ?? cookie, secret);

const tools = rolaLoginTools({
  site: 'the wiki', dAppDefinitionAddress, origin: SITE_URL, tokenTtlSec: 7 * 86400, writeTools: 'create_page / edit_page',
  generateChallenge: rola.generateChallenge,
  login: async signed => issueToken(signed),   // { token, expiresAt, ...shown }; throw McpToolError to refuse
  notes: { sign: { address: 'your virtual account; its key must be an on-ledger owner_keys entry' } },
});
```

- A challenge is spent by one conditional delete whatever the outcome, so one signature cannot pass twice; making one purges the expired. Only an account proof signs in. Verification pins HS256.
- `rolaLoginTools` gives `get_challenge` (the exact message to sign, naming the dApp definition address and the origin `rolaOriginCheck` looks for) and `login`, whose refusal says to fetch a new challenge. `notes.challenge`, `notes.sign` and `notes.address` add a surface's own lines.

`wiki-formant/rola-client` is the browser's half: `loadRadixWallet` imports `@radixdlt/radix-dapp-toolkit` (an optional peer) on first use, hands it the `challenge`, asks for `accounts` (`'one'`, the default, or `'some'`) with a proof, and calls `onProof(signedChallenge, response)` with a fresh answer's first account, never on the replay of a cached wallet; what `onProof` throws goes to `onError`, so the wallet's request still settles. It returns the toolkit for the site to mirror `walletData$` and send transactions.

```ts
const rdt = await loadRadixWallet({
  dAppDefinitionAddress, networkId, applicationName: 'Caper',
  challenge: async () => (await generateChallenge()).challenge,
  onProof: async proof => signIn(await loginWithProof(proof)),
  onError: error => toast.error(errorMessage(error)),
});
```

## Charts

`wiki-formant/chart`: `TimeChart`, every time-series chart: one area series in the box's `color`, range buttons (24H to All) and day, week and month steps.

```tsx
<TimeChart series={days} label="Transactions" aggregate="sum" fromZero
  markers={[{ time: haltAt, label: 'Network halt' }]} step="month" onView={v => keep(v)} />
<TimeChart series={load} label="Price" format={formatPrice} range="30d" candles />
```

- `series` is the points or a loader asked for `'hour'` (24H), `'4h'` (7D) or `'day'`, once each.
- The default step is the finest that makes 200 points or fewer; no step is finer than the points. `aggregate` is `last` for a price, `sum` for a count, `mean` for a rate. A stepped range starts on a whole week or month.
- Points with `open`, `high` and `low` get a candles switch; with `volume`, a volume pane. A zero-volume point leaves its slot empty.
- `format` gets the tick spacing too; `stepDecimals` and `formatChartValue` keep ticks at one precision. `markers` are tooltips on the last point at or before each event.

## Base stylesheet

`wiki-formant/base.css`: the layout the package's markup needs and the package's components drawn on the `--ui-*` tokens (`--ui-surface`, `--ui-surface-2`, `--ui-stripe`, `--ui-border`, `--ui-radius`, `--ui-pad`, `--ui-small`, `--ui-muted`, `--ui-accent`, `--ui-accent-soft`, `--ui-on-accent`, `--ui-up`, `--ui-down`, `--ui-shadow`). Each defaults to the house colour vocabulary (`--color-surface-1`, `--color-text-muted`, `--color-accent` and the rest, listed in `base.css`), so a site whose `@theme` uses it maps only what it names otherwise, in its own `:root`.

The classes on its `@dressed` line take their look from tokens listed beside their rules: the shell (`--shell-*`, `--footer-*`, `--header-*`, `--layout-bg`), the rail (`--rail-*`), the dock (`--dock-*`), and `EmptyState` (`--empty-*`), breadcrumbs (`--crumb-*`), `ArticleMeta` (`--meta-*`), the stats figures (`--figure-*`), the infobox (`--infobox-*`), ColumnsView (`--columns-*`, `--column-flex`), code blocks (`--code-*`), `SearchField` (`--search-*`) and `SectionIndex` (`--index-*`). A site sets the tokens and never restates the class; `check-classes --restated` enforces it, bar a rule licensed by a `/* licensed: <why> */` comment above it.

```css
@import "wiki-formant/base.css" layer(components);
```

It declares the page frame (`--content-width` 120rem for every page, `--sidebar-width` 18rem, `--infobox-width`, `--page-pad` 16/24/64px) in the components layer, so a site never restates them in `@theme`; the shell every root layout draws (`.app-shell`, `.app-main`, `.page-frame`, `.skip-link`), whose header sticks at every width on `--header-bg`, `--header-border` and `--header-filter` and lays out its row on `--header-gap`, `--header-pad`, `--header-wrap`, `--header-justify` and `--header-z`, and whose column beside a rail is a flex column `--frame-gap` apart; the primitives `.spinner`, `.skeleton`, `.empty-state`; and the reduced-motion guard. The rail's rows are tokens a site sets in `:root` rather than restating `wiki-rail__*`: `--rail-pad-block`, `--rail-section`, `--rail-gap`, `--rail-row`, `--rail-inline`, `--rail-size`, `--rail-ink`, `--rail-weight`, and its title, labels, glyphs, subtrees and "On this page" the same way (`--rail-title-*`, `--rail-label-*`, `--rail-glyph-*`, `--rail-subtree-*`, `--rail-toc-*`; the list and defaults are `base.css`'s comment), so no site restates a `wiki-rail__*` class. It also splits a page beside its infobox at 768px of its column, where the infobox sticks (`--infobox-top`, `--infobox-position`), and a ColumnsView row at 40rem of its column: `.page-frame` is a container, so both read the width they have rather than the window's. The rail's surface is `--rail-bg`.

## Database and scripts

`wiki-formant/db`: `pgPoolConfig(url)`, ten clients on the 6543 transaction pooler and three on the 5432 session pooler, and `prismaConfig(root, schema?)`, which prefers `DIRECT_URL`, since the Prisma CLI hangs on the transaction pooler.

```ts
// prisma.config.ts
import { defineConfig } from 'prisma/config';
import { prismaConfig } from 'wiki-formant/db';
export default defineConfig(prismaConfig(import.meta.dirname));
```

`wiki-formant/scripts`: what a seed or sweep script shares: `withClient` (a `pg` client that rolls back on a throw and expires the cache tag after a write), `readPage`, `writeRevision` (refused if the page moved on), `upsertWikiPage` (`created`, `updated` or `unchanged`), the block builders `content`, `banner` and `infobox`, and `assertLinkShapes`.

```ts
import { withClient, readPage, writeRevision } from 'wiki-formant/scripts';
await withClient(async client => {
  const page = await readPage(client, 'contents/tech', 'radix-engine');
  await writeRevision(client, page!, blocks, { change: 'minor', message: 'Why, with the source.' });
}, { tag: 'wiki' });
```

`wiki-formant/link-check`: `auditLinks`, each link once with the pages that carry it, probed with `probeExternal` or the checker's own, and `printLinkAudit`. `verdictOf` reads a probe as `alive`, `dead`, `walled`, `tls` or `unreachable`; only `dead` lands in `brokenExternal`, the rest in `unverifiableExternal`, which a sweep confirms by hand and never strips.

`wiki-formant/knip`: the shared knip configuration, spread into each app's `knip.ts`.

## Bins

Run each from the app's root, where `.env` holds `DATABASE_URL`.

```sh
npx check-classes [--warn] [--compositions] [--unused] [--restated]   # a className token no stylesheet defines; 3+ inline utilities; dead selectors; a dressed class restated
npx check-pages https://radix.wiki            # the served HTML of every sitemap page
npx analytics-digest --days 7 [--gap "Symptom Miss:term"]
npx passkey-invite https://caper.network/stats [--days n]
npx prisma-models [analytics|passkey|wiki] [--check] [--in prisma/schema.prisma --tenant]
npx fts-ddl '"WikiPage"'                      # rebuild search_tsv and its index over DIRECT_URL
npx indexnow https://radix.wiki [--hours 6 | --all]
npx mark-verified <tagPath> <slug> | --all <tagPath> [--invalidate wiki]
npx maintenance-log read|write|compact|backlog-add --at <path> --routine <name> [--author <id>]
```

- `prisma-models` copies the shipped models into `prisma/schema/` (Prisma reads a folder of files; a generator `output` gains a `../`), and `--check` fails on a missing or drifted copy. `--in` compares models in one file, and `--tenant` lets `siteId` drop its default and gain a relation.
- `fts-ddl` runs before the column is declared in `schema.prisma`; a PascalCase table goes in quoted.
- `indexnow` posts the sitemap rows modified in the window to IndexNow, after checking the origin serves the key file in `public/`. The sitemap must render per request.
- `mark-verified` stamps `lastVerifiedAt` so `freshnessBanner` stops calling a page outdated.
- `maintenance-log` is the state of a sweep routine kept in one page's `metadata.state`: every mode holds the row lock from read to write, `backlog-add` files an item another routine raised and a stale `write` merges it back, and a `write` whose `totalRuns` is below the stored one is refused. `--site` names the wiki in a multi-tenant app.

## A reusable workflow

`.github/workflows/publish-mcp-registry.yml` republishes an origin's server to the MCP registry when its `server.json` version moves.

```yaml
on:
  push: { branches: [main], paths: ['server.json'] }
  workflow_dispatch:
jobs:
  publish:
    uses: tutmoses/wiki-formant/.github/workflows/publish-mcp-registry.yml@main
    with:
      domain: example.com
    secrets:
      MCP_REGISTRY_PRIVATE_KEY: ${{ secrets.MCP_REGISTRY_PRIVATE_KEY }}
```

## Licence

MIT.