#!/usr/bin/env bun // Enforce, as a gate step, that documentation citing an `app.config.ts` key names a key that // EXISTS. `doc-fixes.ts` resolves the other half of the same sentence — `x ` — against the // command registry, so `fix: x db query …` fails while `fix: set jobs.driver = 'pg' in // app.config.ts` passed, and `jobs.driver` was deleted in 5.0.0 for having no reader at all. // // The worked example of axiom 4, in the page that DEFINES axiom 4, demonstrated it with a no-op. // // WHAT COUNTS AS A CITATION, and it is deliberately narrow: a dotted `
.` on a line // that also names `app.config.ts` or `defineConfig`. Without that anchor the scan reports // `auth.adapter.putApiKey(record)`, `auth.limiter.recordSuccess('')` and `auth.sessions.policy` // — properties of a runtime object that merely share a section's name — and a check whose findings // have to be argued with is a check an agent learns to skip. The cost is a citation with no anchor // (`docs/idea/17-scale-ladder.md`'s ladder table spells `jobs.driver: 'postgres'` in a config // column and names no file), which this rule does not see and says so. // // bun run scripts/doc-config-keys.ts [--json] import { configDefaults } from '../packages/core/src/config-defaults'; import { CONFIG_FILE, configDeclaration, configLeaves } from './config-readers'; import { parseScriptArgs } from './lib/args'; /** Where an allowance would be written: this file, which holds none since 12.0.0. */ export const DOC_CONFIG_PINS_FILE = 'scripts/doc-config-keys.ts'; /** * One page's licence to cite one key `AppConfig` does not declare — a SYMPTOM of a defect that * lives elsewhere and is a release decision. None is recorded: the four that existed were one * defect (`AppConfig` had no `http` member) and 12.0.0 repaired it, so the rule enforces outright. */ export interface DocConfigKeyAllowance { /** Repo-relative, exactly as the scan reports it. */ readonly path: string; /** The citation verbatim: `http.requestTimeoutMs`. */ readonly cites: string; /** Why this page may say it. One sentence, and it must survive being read out loud. */ readonly why: string; } export const DOC_CONFIG_KEY_ALLOWANCES: readonly DocConfigKeyAllowance[] = []; import type { Finding } from './lib/log'; import { report } from './lib/log'; import { repoRoot } from './lib/run'; /** * The published pages. `docs/plans/**` is excluded on purpose: a plan describes the key it is about * to delete, so a working document citing a dead key is the document doing its job. The release * record, `docs/changelog/**`, names the keys each release added or removed, so it stands too. */ export const DOC_GLOBS = ['docs/**/*.md', 'wiki/**/*.md'] as const; const EXCLUDED = /^docs\/(?:plans|changelog)\//; /** The anchor that makes a dotted token a CONFIG citation rather than a property access. */ const ANCHOR = /app\.config\.ts|defineConfig/; /** * A line that names a key in order to say it is GONE. The wiki's whole job at `Known-Gaps.md:80`, * `Configuration.md:297` and `Jobs-And-Workflows.md:186` is to record that `jobs.driver`, * `ai.modelEnv` and `realtime.heartbeatMs` were deleted — reporting those as citations would tell a * writer to stop documenting a removal, which is the opposite of what this rule wants. * * Each alternative is anchored to a phrase and not to a bare `not`: `docs/architecture/04-error-contract.md:168` * reads "`this is not supported` | `set jobs.driver = 'pg' in app.config.ts`", so a broad negation * test suppresses the one finding this rule exists for. */ const NEGATED = /no reader|nothing reads|\bdeleted\b|\bremoved\b|~~|never\s+(?:read|were|was)|there\s+(?:is|are)\s+no\b|(?:is|are|was|were|\bnot)\s+(?:not\s+)?(?:an?|the)?\s*\W{0,3}app\.config\.ts\W{0,3}\s*(?:key|field)/i; /** A path, not a key: `packages/auth/src/auth.ts` ends in a file extension and starts after a `/`. */ const FILE_EXTENSION = /\.(?:ts|tsx|js|json|md|scss|css|yml|yaml|toml|sql)$/; export interface ConfigCitation { readonly path: string; readonly line: number; readonly cited: string; } /** * The imperative shape, and the one an agent pastes: `set http.rateLimit.scope: 'process' in * app.config.ts`. It takes ANY dotted identifier, because `set …` is what removes the ambiguity the * section anchor below exists for — nothing reads "set `auth.adapter.putApiKey(record)`". Without * it an unknown top-level SECTION was invisible: `sections.join('|')` can only match a section that * exists, so `set billing.currency in app.config.ts` matched nothing, `isKnownKey` was never asked, * and the gate reported green over a section `AppConfig` has never declared. Measured on this tree * the day it landed: four citations of `http.*`, a section that does not exist. */ const SET_FORM = /\bset\s+`?([A-Za-z][\w$]*(?:\.[A-Za-z][\w$]*)+)/g; /** * Every `
.` on an anchored line, where `
` is a real top-level section of * `AppConfig`, plus every `set ` on one whatever its section. Anchoring the general case on * the SECTION set rather than on "any dotted word" is what keeps `x.manifest.json` and * `package.json` out of the answer; `SET_FORM` is what keeps an unknown section from being invisible. */ export function configCitations( path: string, markdown: string, leaves: readonly string[], ): readonly ConfigCitation[] { const sections = [...new Set(leaves.map((leaf) => leaf.split('.')[0] as string))]; // The lookbehind is what keeps `packages/auth/src/auth.ts` out: `auth` is a section, `.ts` looks // like a key, and the whole token is a file path inside a documentation link. const token = new RegExp(`(?(); for (const match of [...line.matchAll(token)].map((one) => one[0] as string)) { if (FILE_EXTENSION.test(match) || seen.has(match)) continue; seen.add(match); found.push({ path, line: index + 1, cited: match }); } for (const match of [...line.matchAll(SET_FORM)].map((one) => one[1] as string)) { if (FILE_EXTENSION.test(match) || seen.has(match)) continue; seen.add(match); found.push({ path, line: index + 1, cited: match }); } } return found; } /** * A citation is satisfied by a leaf or by any PREFIX of one: `cache.tiers` is a leaf, `ai.mcp` is * the section a leaf sits in, and both name something an author can write. Anything else names * nothing — which is the finding. */ export const isKnownKey = (cited: string, leaves: readonly string[]): boolean => leaves.some((leaf) => leaf === cited || leaf.startsWith(`${cited}.`)); export const configKeyFindingFor = (citation: ConfigCitation): Finding => ({ code: 'X_DOC_CONFIG_KEY_UNKNOWN', cause: `${citation.path}:${String(citation.line)} tells a reader to set ${citation.cited} in app.config.ts and ${CONFIG_FILE} declares no such key — the instruction type-errors in the app it is pasted into`, fix: `edit ${citation.path}:${String(citation.line)} — name a key AppConfig declares (bun run scripts/config-readers.ts --json reads the current set), or record a deliberate citation as { path, cites, why } in DOC_CONFIG_KEY_ALLOWANCES in ${DOC_CONFIG_PINS_FILE}`, at: `${citation.path}:${String(citation.line)}`, }); /** The allowance list's own hygiene: an entry matching nothing is a waiver nobody reads. */ export const staleAllowanceFindingFor = (allowance: DocConfigKeyAllowance): Finding => ({ code: 'X_DOC_CONFIG_ALLOWANCE_STALE', cause: `${DOC_CONFIG_PINS_FILE} allows ${allowance.path} to cite ${allowance.cites} and that page no longer does — a waiver nobody removes is a waiver nobody reads`, fix: `{ path: '${allowance.path}', cites: '${allowance.cites}' } // delete this entry from DOC_CONFIG_KEY_ALLOWANCES in ${DOC_CONFIG_PINS_FILE}`, at: DOC_CONFIG_PINS_FILE, }); export interface ConfigKeyReport { /** Cited, unknown, and not allowed. */ readonly unknown: readonly ConfigCitation[]; /** Allowed, and matching no citation on the page it names. */ readonly staleAllowances: readonly DocConfigKeyAllowance[]; } /** Every published page that cites a key `AppConfig` does not declare, minus the recorded ones. */ export async function unknownConfigKeys( root: string, allow: readonly DocConfigKeyAllowance[] = DOC_CONFIG_KEY_ALLOWANCES, ): Promise { const leaves = configLeaves(await configDeclaration(root)); const found: ConfigCitation[] = []; const used = new Set(); for (const glob of DOC_GLOBS) { for (const entry of new Bun.Glob(glob).scanSync({ cwd: root })) { const path = entry.split('\\').join('/'); if (EXCLUDED.test(path)) continue; const citations = configCitations(path, await Bun.file(`${root}/${path}`).text(), leaves); for (const citation of citations) { if (isKnownKey(citation.cited, leaves)) continue; const allowance = allow.find( (one) => one.path === citation.path && one.cites === citation.cited, ); if (allowance !== undefined) { used.add(allowance); continue; } found.push(citation); } } } return { unknown: found.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : a.line - b.line)), staleAllowances: allow.filter((one) => !used.has(one)), }; } /** * THE OTHER HALF OF A CITATION: the value the page says a key has when nobody sets it. A key that * exists with the wrong default passes everything above — `wiki/Configuration.md` said * `realtime.enabled` defaults to `false` for every release since 22.0.0 turned it on, so an app * that wanted no `sync` node read that it had none. Only `wiki/Configuration.md`'s * `| field | type | default | notes |` tables are read: they are the one page that states a * default per key, and every other mention links there. */ export const DEFAULTS_PAGE = 'wiki/Configuration.md'; export interface DocumentedDefault { readonly line: number; readonly key: string; /** The default cell, verbatim. */ readonly stated: string; readonly value: unknown; } const DEFAULTS_HEADER = /^\|\s*field\s*\|\s*type\s*\|\s*default\s*\|\s*notes\s*\|\s*$/; const KEY_CELL = /^`([A-Za-z][\w$]*(?:\.[A-Za-z][\w$]*)*)`$/; const UNSET = Symbol('unset'); /** * A default cell as a value, or `undefined` when it is prose (`required`, `every \`ROLE\``) that * no comparison can read. `—` and `unset = …` both say "no value in the config" — the number after * `unset =` is the CONSUMER's fallback, which `configDefaults()` deliberately does not hold. */ export function parseDefaultCell(cell: string): { readonly value: unknown } | undefined { const text = cell.trim(); if (text === '—' || /^unset\b/.test(text)) return { value: UNSET }; const literal = /^`([^`]+)`$/.exec(text)?.[1]; if (literal === undefined) return undefined; if (literal === 'undefined') return { value: UNSET }; // The page writes JS literals: single quotes, `60_000`. JSON is the parser, after two rewrites. const json = literal.replace(/'([^']*)'/g, (_, inner: string) => JSON.stringify(inner)); try { return { value: JSON.parse(json.replace(/(?<=\d)_(?=\d)/g, '')) as unknown }; } catch { return undefined; } } /** Every `key → default` row of the page's defaults tables, struck-through (deleted) rows skipped. */ export function documentedDefaults(markdown: string): readonly DocumentedDefault[] { const found: DocumentedDefault[] = []; const lines = markdown.split('\n'); let inTable = false; for (let index = 0; index < lines.length; index += 1) { const line = lines[index] as string; if (DEFAULTS_HEADER.test(line)) { inTable = true; continue; } if (!line.startsWith('|')) { inTable = false; continue; } if (!inTable) continue; // A cell may hold an escaped pipe (`'light' \| 'dark'`); split on the bare ones only. const cells = line.split(/(? { let current: unknown = root; for (const step of key.split('.')) { if (typeof current !== 'object' || current === null || !Object.hasOwn(current, step)) { return 'missing'; } current = (current as Record)[step]; } return { value: current === undefined ? UNSET : current }; }; export interface StaleDefault extends DocumentedDefault { readonly actual: unknown; } /** * Every documented default `configDefaults()` disagrees with. A key `configDefaults()` does not * hold (`site`, `seo`, `navigation`, `islands`, `mail` default in their own files) is not * compared, and `checked` says how many were — so a page reshaped out of the parser's reach reads * as zero checked, never as green. */ export function staleDefaults(markdown: string): { readonly checked: number; readonly stale: readonly StaleDefault[]; } { const defaults = configDefaults(); const stale: StaleDefault[] = []; let checked = 0; for (const documented of documentedDefaults(markdown)) { const actual = valueAt(defaults, documented.key); if (actual === 'missing') continue; checked += 1; if (!Bun.deepEquals(actual.value, documented.value)) { stale.push({ ...documented, actual: actual.value === UNSET ? undefined : actual.value }); } } return { checked, stale }; } /** What this rule contributes to `x verify`'s `errors` step, through `docFixFindings`. */ export const docConfigKeyFindings = async (root: string): Promise => { const found = await unknownConfigKeys(root); return [ ...found.unknown.map(configKeyFindingFor), ...found.staleAllowances.map(staleAllowanceFindingFor), ]; }; if (import.meta.main) { const args = parseScriptArgs(Bun.argv.slice(2)); const root = repoRoot(); const findings = await docConfigKeyFindings(root); report( { ok: findings.length === 0, script: 'doc-config-keys', summary: findings.length === 0 ? `every app.config.ts key cited by the docs is one AppConfig declares (${String(DOC_CONFIG_KEY_ALLOWANCES.length)} recorded exception(s), which may only shrink)` : `${String(findings.length)} documented app.config.ts key(s) do not exist`, findings, }, args.json, ); }