Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(server): request ids, access log, and handler error envelope (#2801)
Andrew Mikofalvy4a4d370c5781
diff --git a/.changeset/http-request-ids-access-log.md b/.changeset/http-request-ids-access-log.mdnew file mode 100644index 000000000..1b9b27b80--- /dev/null+++ b/.changeset/http-request-ids-access-log.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Every `/api/*` response now carries an `x-request-id` correlation header — a well-formed incoming `x-request-id` is honored, anything else gets a minted UUID — and the server emits one structured `api.access` log line per API request (method, route template, status, duration) to the on-disk log for bug-report bundles. The same ID lands on the request trace span, so a client-reported ID joins against both the logs and the trace. Verb-dispatch and error-tail plumbing inside the HTTP API was consolidated into shared helpers with no wire-shape changes.diff --git a/knip.config.ts b/knip.config.tsindex 6f8bbbc63..d8a79af2f 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -122,7 +122,9 @@ export default {'packages/server': {entry: ['src/**/*.test.ts'],project: 'src/**',- ignoreDependencies: ['@types/shell-quote'],+ ignoreDependencies: [+ '@types/shell-quote',+ ],},'packages/cli': {entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts'],diff --git a/packages/app/tests/integration/conflict-gate-coverage.test.ts b/packages/app/tests/integration/conflict-gate-coverage.test.tsindex 730f58868..062ae6f46 100644--- a/packages/app/tests/integration/conflict-gate-coverage.test.ts+++ b/packages/app/tests/integration/conflict-gate-coverage.test.ts@@ -247,14 +247,18 @@ const EXEMPT_HANDLERS = new Set([]);function extractHandlerBody(handlerName: string): string | null {- // Same legacy vs migrated detection as the attribution-sweep meta-test.+ // Same legacy vs migrated detection as the attribution-sweep meta-test,+ // plus the `methodRouter({...})` dispatcher shape.const fnDecl = `async function ${handlerName}(`;const constDecl = `const ${handlerName} = withValidation(`;+ const routerDecl = `const ${handlerName} = methodRouter(`;const fnIdx = source.indexOf(fnDecl);const constIdx = source.indexOf(constDecl);+ const routerIdx = source.indexOf(routerDecl);let start = -1;if (fnIdx !== -1) start = fnIdx;else if (constIdx !== -1) start = constIdx;+ else if (routerIdx !== -1) start = routerIdx;if (start === -1) return null;const nextFn = source.indexOf('\n async function handle', start + 1);const nextConst = source.indexOf('\n const handle', start + 1);@@ -299,14 +303,14 @@ describe('conflict-gate coverage (FR9)', () => {body.includes('applyAgentMarkdownWrite(') || body.includes('applyAgentUndo(');// For dispatcher-style handlers (handleTemplate), accept routing// through a sibling sub-handler that itself gates. The structural- // check: the dispatcher calls one of the gated sub-handlers AND that- // sub-handler appears in REQUIRED_HANDLERS itself.+ // check: the dispatcher references one of the gated sub-handlers —+ // as a call (`handleTemplatePut(req, res)`) or as a `methodRouter`+ // verb-map value (`PUT: handleTemplatePut`) — AND that sub-handler+ // appears in REQUIRED_HANDLERS itself.const dispatcherRouting =- body.includes('handleTemplatePut(') ||- body.includes('handleTemplateDelete(') ||- body.includes('handleTemplateMove(') ||- body.includes('handleSkillPut(') ||- body.includes('handleSkillFilePut(');+ /\b(?:handleTemplatePut|handleTemplateDelete|handleTemplateMove|handleSkillPut|handleSkillFilePut)\b/.test(+ body,+ );if (!directGate && !spineRouting && !dispatcherRouting) {failures.push(`${handler}: missing conflict gate — must call respondDocInConflict(...) directly, route through applyAgentMarkdownWrite/applyAgentUndo, or dispatch to a gated sub-handler`,diff --git a/packages/app/tests/integration/error-envelope-coverage.test.ts b/packages/app/tests/integration/error-envelope-coverage.test.tsindex bddc1b785..de12ed33f 100644--- a/packages/app/tests/integration/error-envelope-coverage.test.ts+++ b/packages/app/tests/integration/error-envelope-coverage.test.ts@@ -24,12 +24,16 @@ const API_EXT_PATH = join(import.meta.dirname, '../../../server/src/api-extensioconst source = readFileSync(API_EXT_PATH, 'utf8');function listAllHandlers(): string[] {- // Handlers in `api-extension.ts` come in two shapes:+ // Handlers in `api-extension.ts` come in three shapes:// (1) Legacy `async function handleX(...)` (read-only routes).// (2) `const handleX = withValidation(Schema, handler, options)` —// where `handler` may be an inline arrow function OR a named// `handleXInner` function declared adjacent to the wrapper for// streaming endpoints whose bodies are too long for inline form.+ // (3) `const handleX = methodRouter({ GET: ..., PUT: ... }, options)` —+ // verb dispatchers. The 405 fallback emits via `errorResponse(...)`+ // inside the helper (unit-tested in `http/method-router.test.ts`);+ // the per-verb handlers are scanned separately under their own names.// Inner functions co-located with a wrapper are excluded from the public// handler list — they are scanned as part of the parent's body slice via// `extractHandlerBody`.@@ -37,20 +41,26 @@ function listAllHandlers(): string[] {const wrapperNames = [...source.matchAll(/const (handle\w+) = withValidation\(/g)].map((m) => m[1],);+ const routerNames = [...source.matchAll(/const (handle\w+) = methodRouter\(/g)].map((m) => m[1]);const innerNames = new Set(wrapperNames.map((wrapper) => `${wrapper}Inner`).filter((inner) => fnNames.includes(inner)),);- return Array.from(new Set([...fnNames, ...wrapperNames])).filter((n) => !innerNames.has(n));+ return Array.from(new Set([...fnNames, ...wrapperNames, ...routerNames])).filter(+ (n) => !innerNames.has(n),+ );}function extractHandlerBody(name: string): string | null {const fnDecl = `async function ${name}(`;const constDecl = `const ${name} = withValidation(`;+ const routerDecl = `const ${name} = methodRouter(`;const fnIdx = source.indexOf(fnDecl);const constIdx = source.indexOf(constDecl);+ const routerIdx = source.indexOf(routerDecl);let start = -1;if (fnIdx !== -1) start = fnIdx;else if (constIdx !== -1) start = constIdx;+ else if (routerIdx !== -1) start = routerIdx;if (start === -1) return null;// For wrappers that delegate to a named inner function (`const handleX =@@ -153,6 +163,10 @@ type EmitClass = 'json' | 'non-json' | 'dispatcher';*/function classifyHandlerEmit(body: string): EmitClass {if (isNonJsonEmit(body)) return 'non-json';+ // `methodRouter({...})` declarations are dispatchers by construction —+ // the per-verb handlers they reference emit the actual bodies and are+ // scanned separately; the 405 fallback lives inside the helper.+ if (body.includes('= methodRouter(')) return 'dispatcher';if (DISPATCHER_RE.test(body) && !body.includes('successResponse(')) {return 'dispatcher';}@@ -214,10 +228,20 @@ describe('error envelope coverage (FR17, D36 a) — fail-on-any-occurrence', ()`${name}: contains inline json(res, 2xx, ...) — must use successResponse(...)`,);}- if (!body.includes('errorResponse(') && !STREAM_AUTH_DELEGATION_RE.test(body)) {- // `streamAuthFlow` delegators: every error emit (429 concurrency- // envelope, RFC 9457 streaming errors) lives inside the shared helper,- // so the handler body legitimately contains no `errorResponse(` call.+ // `catchErrors(...)` routes handler throws through `errorResponse(...)`+ // internally, and `methodRouter(...)` emits its 405 fallback the same+ // way — both wrappers satisfy the sanctioned-emitter requirement for+ // handlers whose remaining body has no direct error emit of its own.+ // `streamAuthFlow` delegators likewise: every error emit (429+ // concurrency envelope, RFC 9457 streaming errors) lives inside the+ // shared helper, so the handler body legitimately contains no+ // `errorResponse(` call.+ if (+ !body.includes('errorResponse(') &&+ !body.includes('catchErrors(') &&+ !body.includes('= methodRouter(') &&+ !STREAM_AUTH_DELEGATION_RE.test(body)+ ) {failures.push(`${name}: missing errorResponse(...) usage`);}}diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.tsindex c014b1413..8f9d95287 100644--- a/packages/core/src/bridge/bind-frontmatter-doc.ts+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts@@ -1,3 +1,4 @@+import type * as Y from 'yjs';import type { Err, Ok, Result } from '../config/result.ts';import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.tsindex 005627195..8bfdb40cd 100644--- a/packages/core/src/bridge/bridge-invariant.ts+++ b/packages/core/src/bridge/bridge-invariant.ts@@ -1,3 +1,4 @@+import { fnv1aDigest } from './hash-util.ts';export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex 8890f6739..c18c086d5 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,3 +1,4 @@+import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';const LEADING_BOUNDARY_RE = /^(?:\r?\n)+/;diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.tsindex 9d9c244b0..463e89595 100644--- a/packages/core/src/bridge/growth-detect.ts+++ b/packages/core/src/bridge/growth-detect.ts@@ -1,3 +1,4 @@+const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.tsindex 3ab9cc6ef..3c927eb47 100644--- a/packages/core/src/bridge/merge-three-way.ts+++ b/packages/core/src/bridge/merge-three-way.ts@@ -38,6 +38,7 @@ function mergeThreeWayImpl(baseline: string, userText: string, agentText: stringreturn parts.join('\n');}+export type BridgeMergeContentLossSide = 'user' | 'agent';export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.tsindex 4b8890476..3f0880aa5 100644--- a/packages/core/src/bridge/normalize.ts+++ b/packages/core/src/bridge/normalize.ts@@ -1,3 +1,4 @@+const COMMONMARK_ESCAPE_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~])/g;const TABLE_ALIGN_ROW_RE = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/;diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.tsindex 754dc5cc2..0be5203e4 100644--- a/packages/core/src/bridge/pm-structural-equivalence.ts+++ b/packages/core/src/bridge/pm-structural-equivalence.ts@@ -32,6 +32,7 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };const BR_LITERAL_RE = /^<br\s*\/?>$/i;+interface DegradeEntry {readonly label: string;readonly severity: ToleranceClassSeverity;@@ -127,6 +128,7 @@ export interface ComparePmStructuralOptions {ignoreAttrs?: (attrKey: string) => boolean;}+/** Rebuild a node with `fn` applied to each child; identity when childless.* Shared by the degrade canonicalizers so none re-implements the walk. */function mapChildren(@@ -248,6 +250,7 @@ function applyDegrades(tree: PmStructuralNode): {return { normalized: current, fired };}+export function comparePmStructural(expected: PmStructuralNode,actual: PmStructuralNode,diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.tsindex af20de1e2..dca644141 100644--- a/packages/core/src/bridge/subsequence.ts+++ b/packages/core/src/bridge/subsequence.ts@@ -1,3 +1,4 @@+/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):* insertions in `haystack` are free; any dropped or substituted `needle` byte* fails. */diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.tsindex 83d47404a..a363dfd54 100644--- a/packages/core/src/markdown/callout-transformer.ts+++ b/packages/core/src/markdown/callout-transformer.ts@@ -1,3 +1,4 @@+import type { Blockquote, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex 193e286b0..47f0d07e4 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.tsindex ece5c02a1..b6299a948 100644--- a/packages/core/src/markdown/dedent-block-jsx-close.ts+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts@@ -1,3 +1,4 @@+import { findFencedRegions, isInsideFence } from './fence-regions.ts';const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.tsindex 54774764a..acd398aa6 100644--- a/packages/core/src/markdown/details-accordion-promoter.ts+++ b/packages/core/src/markdown/details-accordion-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.tsindex c7518d614..fb5ac8e8a 100644--- a/packages/core/src/markdown/fence-regions.ts+++ b/packages/core/src/markdown/fence-regions.ts@@ -1,3 +1,4 @@+const FENCE_RE = /^(`{3,}|~{3,})/gm;export function findFencedRegions(src: string): Array<[number, number]> {diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.tsindex 00f5771ee..6931623c7 100644--- a/packages/core/src/markdown/fixtures/index.ts+++ b/packages/core/src/markdown/fixtures/index.ts@@ -1,3 +1,4 @@+import { readFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -8,6 +9,7 @@ function fixturePath(...segments: string[]): string {return resolve(FIXTURES_DIR, ...segments);}+interface GfmExample {section: string;markdown: string;@@ -17,6 +19,7 @@ export function loadGfmExamples(): GfmExample[] {return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];}+interface MdxCrashEntry {id: string;input: string;@@ -68,6 +71,7 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {) as LargeEmbedFixture[];}+export function loadPrd6955Before(): string {return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');}@@ -76,6 +80,7 @@ export function loadPrd6955CorruptedTriplicated(): string {return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');}+export interface NgPinnedCase {id: string;name: string;@@ -92,6 +97,7 @@ export function loadNgPinnedCases(): NgPinnedCase[] {) as NgPinnedCase[];}+export function loadLargeRealistic(): string {return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');}diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.tsindex 8b1eb8519..daa3ef82b 100644--- a/packages/core/src/markdown/fixtures/perf/generate.ts+++ b/packages/core/src/markdown/fixtures/perf/generate.ts@@ -1,3 +1,4 @@+import { writeFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -10,6 +11,7 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;const SEED = 0xf1de1117;+function mulberry32(seed: number): () => number {let a = seed >>> 0;return () => {@@ -36,6 +38,7 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {return items[items.length - 1][0];}+const WORDS = ['lorem','ipsum',@@ -153,6 +156,7 @@ function mdxBlock(rand: () => number): string {return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;}+type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';const MIX: readonly [BlockKind, number][] = [@@ -191,6 +195,7 @@ function generateDocument(blockCount: number, seed: number): string {return `${blocks.join('\n\n')}\n`;}+function main(): void {for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {const doc = generateDocument(count, SEED);diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.tsindex 420dc0fe5..32c055c5b 100644--- a/packages/core/src/markdown/guard-flanking-matrix.ts+++ b/packages/core/src/markdown/guard-flanking-matrix.ts@@ -7,6 +7,7 @@ import {import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';+export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;export type FlankClass = 'whitespace' | 'punctuation' | 'other';diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.tsindex 2653473da..283913255 100644--- a/packages/core/src/markdown/handler-shadow-audit.ts+++ b/packages/core/src/markdown/handler-shadow-audit.ts@@ -1,3 +1,4 @@+export interface HandlerShadowWitness {input: string;expect: 'byte' | 'byte-and-reparse-type';diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.tsindex f55912407..6319f264f 100644--- a/packages/core/src/markdown/highlight-promoter.ts+++ b/packages/core/src/markdown/highlight-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.tsindex b1f252c31..8dc3a81b5 100644--- a/packages/core/src/markdown/html-to-mdast.ts+++ b/packages/core/src/markdown/html-to-mdast.ts@@ -1,3 +1,4 @@+import type { Root as HastRoot } from 'hast';import type { List, Root as MdastRoot } from 'mdast';import rehypeParse from 'rehype-parse';@@ -85,7 +86,8 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRothrow new HtmlPayloadTooLargeError(html.length, maxBytes);}- const processor = unified().use(rehypeParse, { fragment: true });+ const processor = unified()+ .use(rehypeParse, { fragment: true });for (const plugin of cleanupPlugins) {processor.use(plugin);diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.tsindex 706fa9afb..994eb6917 100644--- a/packages/core/src/markdown/image-promoter.ts+++ b/packages/core/src/markdown/image-promoter.ts@@ -1,3 +1,4 @@+import type { Image, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.tsindex 8b36807fd..fc30bda02 100644--- a/packages/core/src/markdown/index.ts+++ b/packages/core/src/markdown/index.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromPmMark,@@ -196,6 +197,7 @@ export class MarkdownManager {}}+const registry = createRegistry();function destructureAttrs(@@ -244,6 +246,7 @@ function destructureAttrs(return result;}+function hasDirtyDescendant(node: PmNode): boolean {let found = false;node.descendants((child) => {@@ -263,6 +266,7 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChecreturn freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;}+function isEmptyMdastParagraph(node: MdastNodes): boolean {if (node.type !== 'paragraph') return false;const children = node.children ?? [];@@ -331,6 +335,7 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {return out;}+import {AUDIO_EXTENSIONS,FILE_ATTACHMENT_EXTENSIONS,@@ -577,6 +582,7 @@ function buildMdastToPmHandlers(}));}+if (m.emphasis) {handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({sourceDelimiter: node.data?.sourceDelimiter ?? '*',@@ -657,6 +663,7 @@ function buildMdastToPmHandlers(}));}+if (m.link) {const sourceLiteralMark = m.sourceLiteral;handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {@@ -935,6 +942,7 @@ function buildMdastToPmHandlers(};}+const blockUnknownHandler = (node: {type: string;position?: { start: { offset: number }; end: { offset: number } };@@ -1060,6 +1068,7 @@ function buildMdastToPmHandlers(return handlers as RemarkProseMirrorOptions['handlers'];}+function buildPmToMdastHandlers(schema: Schema,freshness: FreshnessCheckerHolder,diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.tsindex 312c9c74b..94b34dee1 100644--- a/packages/core/src/markdown/lint/config-files.ts+++ b/packages/core/src/markdown/lint/config-files.ts@@ -1,3 +1,4 @@+const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set(['.markdownlint.json','.markdownlint.jsonc',diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.tsindex e78a1381d..207cd95c2 100644--- a/packages/core/src/markdown/lint/config-schemas.ts+++ b/packages/core/src/markdown/lint/config-schemas.ts@@ -29,6 +29,7 @@ const fullPluginShape = Object.fromEntries(LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),) as z.ZodRawShape;+export const LinterConfigSchema = z.object({enabled: z.boolean(),plugins: z.object(fullPluginShape),diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.tsindex d48eea5e4..a51f2ffb0 100644--- a/packages/core/src/markdown/lint/default-config.ts+++ b/packages/core/src/markdown/lint/default-config.ts@@ -6,6 +6,7 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSettingMD013: false,};+export function resolveMarkdownlintConfig(rules: Record<string, MarkdownlintRuleSetting> | undefined,): Configuration {diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.tsindex 8a154ce30..d763d8d28 100644--- a/packages/core/src/markdown/lint/index.ts+++ b/packages/core/src/markdown/lint/index.ts@@ -1,3 +1,4 @@+import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';import type { LintDiagnostic } from './types.ts';diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.tsindex 1cd40ef3a..65a1b564c 100644--- a/packages/core/src/markdown/lint/plugins.ts+++ b/packages/core/src/markdown/lint/plugins.ts@@ -1,3 +1,4 @@+import { z } from 'zod';import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';import { fixMarkdownText, runMarkdownlint } from './markdownlint-runner.ts';@@ -8,6 +9,7 @@ import {type MarkdownlintSlice,} from './types.ts';+const MarkdownlintRuleSettingSchema = z.union([z.boolean(),z.enum(MARKDOWNLINT_RULE_SEVERITIES),diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.tsindex 617f6e5b9..3651bd7eb 100644--- a/packages/core/src/markdown/lint/types.ts+++ b/packages/core/src/markdown/lint/types.ts@@ -1,3 +1,4 @@+export const LINT_PLUGIN_IDS = ['markdownlint'] as const;export type LintPluginId = (typeof LINT_PLUGIN_IDS)[number];@@ -41,6 +42,7 @@ export interface MarkdownlintSlice {rules: Record<string, MarkdownlintRuleSetting>;}+interface RuleOptionSpecBase {key: string;description: string;diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.tsindex a5b511f25..bd79424c7 100644--- a/packages/core/src/markdown/math-promoter.ts+++ b/packages/core/src/markdown/math-promoter.ts@@ -1,3 +1,4 @@+import type { Code, Root } from 'mdast';import type { Math as MdastMath } from 'mdast-util-math';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.tsindex 679c72ef7..f84967798 100644--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts@@ -1,3 +1,4 @@+import type { Comment, Element, ElementContent, Properties } from 'hast';import type { FootnoteDefinition, FootnoteReference } from 'mdast';import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.tsindex 8ce2b2492..df788a80d 100644--- a/packages/core/src/markdown/mdast-to-html.ts+++ b/packages/core/src/markdown/mdast-to-html.ts@@ -1,3 +1,4 @@+import type { Element, Root as HastRoot, Text as HastText } from 'hast';import type { Root as MdastRoot, Text as MdastText } from 'mdast';import type { Handler } from 'mdast-util-to-hast';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex bfd7e3109..fa3cfcd86 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.tsindex 1a897fca8..17ed2b829 100644--- a/packages/core/src/markdown/mermaid-promoter.ts+++ b/packages/core/src/markdown/mermaid-promoter.ts@@ -1,3 +1,4 @@+import type { Code, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.tsindex 9864b3b60..7e4a9a48b 100644--- a/packages/core/src/markdown/parse-with-fallback.ts+++ b/packages/core/src/markdown/parse-with-fallback.ts@@ -168,6 +168,7 @@ export function parseRecursive(}}+interface VFilePlace {offset?: number;start?: { offset?: number };@@ -186,6 +187,7 @@ function extractErrorOffset(err: unknown): number | undefined {return undefined;}+interface Region {start: number;end: number;@@ -209,6 +211,7 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {return null;}+export interface TagEvent {kind: 'open' | 'close' | 'self-close';name: string;@@ -355,6 +358,7 @@ function findFallbackRegion(src: string, errorOffset: number): Region {return { start: blockStart, end: blockEnd };}+interface SourceBlock {src: string;start: number;@@ -452,6 +456,7 @@ function tryPerBlockFallback(};}+function wholeDocRawText(source: string): JSONContent {return {type: 'doc',diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.tsindex e6ab4fd57..43d420187 100644--- a/packages/core/src/markdown/parser-drop-closure.ts+++ b/packages/core/src/markdown/parser-drop-closure.ts@@ -1,3 +1,4 @@+export type DroppedTokenAdjudication =| {kind: 'format-dof-axis';diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.tsindex 7f2d5adca..e9e507469 100644--- a/packages/core/src/markdown/pipeline.ts+++ b/packages/core/src/markdown/pipeline.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromProseMirror,diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.tsindex 5a5e4c42a..f8f5e8530 100644--- a/packages/core/src/markdown/position-aware-join.ts+++ b/packages/core/src/markdown/position-aware-join.ts@@ -1,3 +1,4 @@+import type { Join } from 'mdast-util-to-markdown';import type { Position } from 'unist';diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.tsindex 0f399d34c..e5b4c9eba 100644--- a/packages/core/src/markdown/position-slice.ts+++ b/packages/core/src/markdown/position-slice.ts@@ -1,3 +1,4 @@+import type { Nodes, Root } from 'mdast';import { visit } from 'unist-util-visit';import type { VFile } from 'vfile';@@ -476,7 +477,8 @@ export function applyPositionSliceToNode(const first = source[startOff];if (first !== '[' && first !== '<' && !node.title) {node.data.sourceStyle = 'gfm-autolink';- } else if (first === '[') {+ }+ else if (first === '[') {const slice = source.slice(startOff, endOff);const closeBracketIdx = slice.lastIndexOf('](');if (closeBracketIdx !== -1) {diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.tsindex db10fa54b..ca225ce9b 100644--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts@@ -1,3 +1,4 @@+import type { Comment, Element, Root, Text } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.tsindex 34068d103..3a2524a9a 100644--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.tsindex 93151d43b..2279a0189 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.tsindex 188f02d83..a0f467c42 100644--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.tsindex 4ba2c3418..4e8542a21 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.tsindex 1a74b1272..a3c96b24a 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.tsindex de35e7b79..e95cf43d6 100644--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts@@ -1,3 +1,4 @@+import type { Comment, Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.tsindex b4be1b2ea..ffdb4d5b5 100644--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.tsindex 3c8d88b7c..e2a96d1a7 100644--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.tsindex cf2c9da8e..0389575ac 100644--- a/packages/core/src/markdown/resolve-image-url.ts+++ b/packages/core/src/markdown/resolve-image-url.ts@@ -1,3 +1,4 @@+import { isRelativeUrl } from './safe-url.ts';function isDevDiagnosticContext(): boolean {diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 4d3250d3a..8be632ba4 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,3 +1,4 @@+export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.tsindex 46cc6a074..542204403 100644--- a/packages/core/src/markdown/serialize-helpers.ts+++ b/packages/core/src/markdown/serialize-helpers.ts@@ -1,3 +1,4 @@+import type { Node as PmNode } from '@tiptap/pm/model';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { PropDef, SerializeContext } from '../registry/types.ts';diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.tsindex be97d4d62..fe73659e6 100644--- a/packages/core/src/markdown/single-dollar-math-promoter.ts+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts@@ -1,3 +1,4 @@+import type { PhrasingContent, Root, Text } from 'mdast';import type { InlineMath } from 'mdast-util-math';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.tsindex 8f4e9a41c..7bce04302 100644--- a/packages/core/src/markdown/to-markdown-handlers.ts+++ b/packages/core/src/markdown/to-markdown-handlers.ts@@ -1,3 +1,4 @@+import type { Nodes, Parents } from 'mdast';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { Handle, Info, State } from 'mdast-util-to-markdown';diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.tsindex cd245c38c..c5bfd2386 100644--- a/packages/core/src/markdown/unknown-mdast-guard.ts+++ b/packages/core/src/markdown/unknown-mdast-guard.ts@@ -1,3 +1,4 @@+import type { Root as MdastRoot } from 'mdast';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.tsindex d578476a7..ac9f5239b 100644--- a/packages/core/src/markdown/whitespace-char-ref.ts+++ b/packages/core/src/markdown/whitespace-char-ref.ts@@ -1,3 +1,4 @@+const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([[0x20, ' '],[0x09, '\t'],diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.tsindex 6dad26200..afd9936fe 100644--- a/packages/core/src/markdown/wiki-link-micromark.ts+++ b/packages/core/src/markdown/wiki-link-micromark.ts@@ -17,6 +17,7 @@ declare module 'micromark-util-types' {}}+const CODE_BANG = 33; // !const CODE_LBRACKET = 91; // [const CODE_RBRACKET = 93; // ]@@ -260,6 +261,7 @@ export function wikiLinkSyntax(): Extension {};}+function enterWikiLink(this: CompileContext, token: Token) {this.enter({@@ -385,6 +387,7 @@ export const wikiLinkToMarkdown: {unsafe: [{ character: '[', inConstruct: ['phrasing'] }],};+const MICROMARK_EXT = wikiLinkSyntax();export function remarkWikiLink(this: Processor) {diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 681416dac..b5aa00051 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -515,11 +515,15 @@ import {import { CHECKOUT_HANDLER_TAG, runCheckoutFlow } from './git-checkout.ts';import { withParentLock } from './git-handle.ts';import { writeGitIdentity } from './git-identity.ts';+import { catchErrors } from './http/catch-errors.ts';import {createStreamingErrorWriter,errorResponse,type HttpErrorStatus,} from './http/error-response.ts';+import { errnoCode, parseQuery } from './http/handler-utils.ts';+import { methodRouter } from './http/method-router.ts';+import { REQUEST_ID_HEADER, rememberRequestId, resolveRequestId } from './http/request-id.ts';import { validateBody, withValidation } from './http/request-validation.ts';import { successResponse } from './http/success-response.ts';import { initContent } from './init-project.ts';@@ -1107,7 +1111,7 @@ async function findDuplicateAsset(// candidate otherwise spiked heap to 500 MB per scan.candidateSha = await streamingHashFile(fullPath);} catch (err) {- const code = (err as NodeJS.ErrnoException).code;+ const code = errnoCode(err);// ENOENT is the legitimate concurrent-rename race — stay silent.if (code !== 'ENOENT') {log.warn(@@ -2106,7 +2110,7 @@ function assertNoSymlinkEscape(fullPath: string, resolvedContentDir: string): votry {contentRoot = realpathSync(resolvedContentDir);} catch (err) {- const code = (err as NodeJS.ErrnoException).code;+ const code = errnoCode(err);// ENOENT means the content dir hasn't been created yet — no symlink// escape is possible against a non-existent directory, but we have// no safe baseline for the check either. Throw the same@@ -2130,7 +2134,7 @@ function assertNoSymlinkEscape(fullPath: string, resolvedContentDir: string): vo}return;} catch (err) {- const code = (err as NodeJS.ErrnoException).code;+ const code = errnoCode(err);if (code === 'ELOOP') {throw new SymlinkEscapeError('symlink cycle in path');}@@ -2193,7 +2197,7 @@ class DuplicateNameExhaustedError extends Error {}function isAlreadyExistsError(err: unknown): boolean {- const code = (err as NodeJS.ErrnoException).code;+ const code = errnoCode(err);// Node's cpSync distinguishes the destination-occupied cases by the type// mismatch: a same-type collision surfaces as ERR_FS_CP_EEXIST, but copying a// directory onto an existing file (or a file onto an existing directory)@@ -2216,7 +2220,7 @@ type DuplicatePathFilesystemProblem = {function classifyDuplicatePathFilesystemProblem(err: unknown,): DuplicatePathFilesystemProblem | null {- const code = (err as NodeJS.ErrnoException).code;+ const code = errnoCode(err);if (code === 'ENOSPC' || code === 'EDQUOT') {return {status: 507,@@ -3929,7 +3933,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {try {entries = readdirSync(parentPath, { withFileTypes: true });} catch (err) {- const code = (err as NodeJS.ErrnoException).code;+ const code = errnoCode(err);if (code === 'ENOENT' || code === 'ENOTDIR') {return { path: assetPath, ambiguous: false };}@@ -3975,7 +3979,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {try {if (!statSync(sourcePathRoot).isDirectory()) return docNames;} catch (err) {- const code = (err as NodeJS.ErrnoException).code;+ const code = errnoCode(err);if (code === 'ENOENT' || code === 'ENOTDIR') return docNames;throw err;}@@ -9194,7 +9198,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {try {resolvedContentDir = realpathSync(resolvedRoot);} catch (err) {- const code = (err as NodeJS.ErrnoException | undefined)?.code;+ const code = errnoCode(err);if (code === 'ENOENT') {log.warn({ path: resolvedRoot },@@ -10025,7 +10029,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {try {tracedRmdirSync(destinationDir);} catch (cleanupErr) {- const cleanupCode = (cleanupErr as NodeJS.ErrnoException).code;+ const cleanupCode = errnoCode(cleanupErr);if (cleanupCode !== 'ENOENT' && cleanupCode !== 'ENOTEMPTY') {log.warn({ destinationDir, err: cleanupErr },@@ -11294,7 +11298,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {return;}} catch (e) {- const code = (e as NodeJS.ErrnoException).code;+ const code = errnoCode(e);if (code === 'ENOENT') {// Directory doesn't exist yet — will be created below; no symlink escape possible} else {@@ -13672,19 +13676,6 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {return out;}- async function handleFolderConfig(req: IncomingMessage, res: ServerResponse): Promise<void> {- if (req.method === 'GET') {- return handleFolderConfigGet(req, res);- }- if (req.method === 'PUT') {- return handleFolderConfigPut(req, res);- }- errorResponse(res, 405, 'urn:ok:error:method-not-allowed', 'Method not allowed.', {- handler: 'folder-config',- extraHeaders: { Allow: 'GET, PUT' },- });- }-const handleFolderConfigGet = withValidation(EmptyRequestSchema,async (req, res) => {@@ -13834,6 +13825,11 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {{ handler: 'folder-config-put', method: 'PUT' },);+ const handleFolderConfig = methodRouter(+ { GET: handleFolderConfigGet, PUT: handleFolderConfigPut },+ { handler: 'folder-config' },+ );+/*** Conflict-aware refusal helper for the template handlers. Templates* write to `<folder>/.ok/templates/<name>.md`, under `.ok/`, which the@@ -13897,8 +13893,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {*/const handleTemplatesList = withValidation(EmptyRequestSchema,- async (_req, res) => {- try {+ catchErrors(+ async (_req, res) => {const resolvedContentDir = resolve(contentDir);const result = resolveProjectTemplates(resolvedContentDir);// Drop `scope` from each entry — every flat-enumeration entry is@@ -13916,35 +13912,12 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {{ templates, truncated: result.truncated },{ handler: 'templates-list' },);- } catch (e) {- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to list templates.', {- handler: 'templates-list',- cause: e,- });- }- },+ },+ { handler: 'templates-list', title: 'Failed to list templates.' },+ ),{ handler: 'templates-list', method: 'GET', skipBodyParse: true },);- async function handleTemplate(req: IncomingMessage, res: ServerResponse): Promise<void> {- if (req.method === 'GET') {- return handleTemplateGet(req, res);- }- if (req.method === 'PUT') {- return handleTemplatePut(req, res);- }- if (req.method === 'POST') {- return handleTemplateMove(req, res);- }- if (req.method === 'DELETE') {- return handleTemplateDelete(req, res);- }- errorResponse(res, 405, 'urn:ok:error:method-not-allowed', 'Method not allowed.', {- handler: 'template',- extraHeaders: { Allow: 'GET, PUT, POST, DELETE' },- });- }-// Generic frontmatter splitter for managed `.md` files (SKILL.md, etc.):// returns the parsed YAML frontmatter object + the body. Distinct from core's// `parseTemplateFile`, which parses the single-block TEMPLATE format@@ -14431,6 +14404,16 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {{ handler: 'template-move', method: 'POST' },);+ const handleTemplate = methodRouter(+ {+ GET: handleTemplateGet,+ PUT: handleTemplatePut,+ POST: handleTemplateMove,+ DELETE: handleTemplateDelete,+ },+ { handler: 'template' },+ );+const handleTemplateImport = withValidation(TemplateImportRequestSchema,async (_req, res, body) => {@@ -14982,8 +14965,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {const handleSkillsList = withValidation(EmptyRequestSchema,- async (_req, res) => {- try {+ catchErrors(+ async (_req, res) => {// Union both scopes: project skills (`<contentDir>/.ok/skills`, git-// shared) + global skills (`<home>/.ok/skills`, user-level). Each is// enriched from ITS OWN install marker — the project marker at@@ -15022,27 +15005,12 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {truncated: project.truncated || globalSkills.truncated,};successResponse(res, 200, SkillsListSuccessSchema, enriched, { handler: 'skills-list' });- } catch (e) {- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to list skills.', {- handler: 'skills-list',- cause: e,- });- }- },+ },+ { handler: 'skills-list', title: 'Failed to list skills.' },+ ),{ handler: 'skills-list', method: 'GET', skipBodyParse: true },);- async function handleSkill(req: IncomingMessage, res: ServerResponse): Promise<void> {- if (req.method === 'GET') return handleSkillGet(req, res);- if (req.method === 'PUT') return handleSkillPut(req, res);- if (req.method === 'POST') return handleSkillMove(req, res);- if (req.method === 'DELETE') return handleSkillDelete(req, res);- errorResponse(res, 405, 'urn:ok:error:method-not-allowed', 'Method not allowed.', {- handler: 'skill',- extraHeaders: { Allow: 'GET, PUT, POST, DELETE' },- });- }-// ─── `/api/skills/management` — project-managed opt-in (the import gate) ──────// GET → { managed: bool | null (undecided), importable: count of non-`.ok`// editor skills an import would adopt }. PUT { manageEditorSkills } records@@ -15107,14 +15075,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {{ handler: 'skills-management-put', method: 'PUT' },);- async function handleSkillsManagement(req: IncomingMessage, res: ServerResponse): Promise<void> {- if (req.method === 'GET') return handleSkillsManagementGet(req, res);- if (req.method === 'PUT') return handleSkillsManagementPut(req, res);- errorResponse(res, 405, 'urn:ok:error:method-not-allowed', 'Method not allowed.', {- handler: 'skills-management',- extraHeaders: { Allow: 'GET, PUT' },- });- }+ const handleSkillsManagement = methodRouter(+ { GET: handleSkillsManagementGet, PUT: handleSkillsManagementPut },+ { handler: 'skills-management' },+ );const handleSkillGet = withValidation(EmptyRequestSchema,@@ -15605,6 +15569,11 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {{ handler: 'skill-move', method: 'POST' },);+ const handleSkill = methodRouter(+ { GET: handleSkillGet, PUT: handleSkillPut, POST: handleSkillMove, DELETE: handleSkillDelete },+ { handler: 'skill' },+ );+// ─── `/api/skill-file` — ONE bundle file (references/** + scripts/**) ──────//// The whole-bundle read/write/delete surface beneath SKILL.md. Routing splits@@ -16086,15 +16055,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {{ handler: 'skill-file-delete', method: 'DELETE', skipBodyParse: true },);- async function handleSkillFile(req: IncomingMessage, res: ServerResponse): Promise<void> {- if (req.method === 'GET') return handleSkillFileGet(req, res);- if (req.method === 'PUT') return handleSkillFilePut(req, res);- if (req.method === 'DELETE') return handleSkillFileDelete(req, res);- errorResponse(res, 405, 'urn:ok:error:method-not-allowed', 'Method not allowed.', {- handler: 'skill-file',- extraHeaders: { Allow: 'GET, PUT, DELETE' },- });- }+ const handleSkillFile = methodRouter(+ { GET: handleSkillFileGet, PUT: handleSkillFilePut, DELETE: handleSkillFileDelete },+ { handler: 'skill-file' },+ );// `POST /api/skill/install` — project a skill's `.ok/skills/<name>/` source// into the project-configured editor host dirs. This is a local-op@@ -16288,19 +16252,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {// (from the marker) AND OK's shipped `open-knowledge` bundle — to the new// editors, reverse-projecting from dropped ones. A user/UI action (the set// is project-config with teammate-wide blast radius), not agent-attributed.- async function handleSkillTargets(req: IncomingMessage, res: ServerResponse): Promise<void> {- if (req.method === 'GET') return handleSkillTargetsGet(req, res);- if (req.method === 'PUT') return handleSkillTargetsPut(req, res);- errorResponse(res, 405, 'urn:ok:error:method-not-allowed', 'Method not allowed.', {- handler: 'skill-targets',- extraHeaders: { Allow: 'GET, PUT' },- });- }-const handleSkillTargetsGet = withValidation(EmptyRequestSchema,- async (_req, res) => {- try {+ catchErrors(+ async (_req, res) => {const committed = projectDir ? readSkillTargets(projectDir) : null;const targets = resolveSkillTargets(projectDir ?? '', committed ?? undefined);successResponse(@@ -16310,23 +16265,16 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {{ targets, configured: committed !== null },{ handler: 'skill-targets-get' },);- } catch (e) {- errorResponse(- res,- 500,- 'urn:ok:error:internal-server-error',- 'Failed to read skill targets.',- { handler: 'skill-targets-get', cause: e },- );- }- },+ },+ { handler: 'skill-targets-get', title: 'Failed to read skill targets.' },+ ),{ handler: 'skill-targets-get', method: 'GET', skipBodyParse: true },);const handleSkillTargetsPut = withValidation(SkillTargetsPutRequestSchema,- async (_req, res, body) => {- try {+ catchErrors(+ async (_req, res, body) => {if (!projectDir) {errorResponse(res,@@ -16367,19 +16315,17 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {},{ handler: 'skill-targets-put' },);- } catch (e) {- errorResponse(- res,- 500,- 'urn:ok:error:internal-server-error',- 'Failed to set skill targets.',- { handler: 'skill-targets-put', cause: e },- );- }- },+ },+ { handler: 'skill-targets-put', title: 'Failed to set skill targets.' },+ ),{ handler: 'skill-targets-put', method: 'PUT' },);+ const handleSkillTargets = methodRouter(+ { GET: handleSkillTargetsGet, PUT: handleSkillTargetsPut },+ { handler: 'skill-targets' },+ );+// `POST /api/skill/restore` — restore a skill's source to a prior shadow-repo// version (fs-direct; net-new). The// restore itself is attributed as a new `skill-restore` version.@@ -17264,45 +17210,30 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {prewarmWorkspaceSearchCache();- async function handleSearch(req: IncomingMessage, res: ServerResponse): Promise<void> {- if (req.method === 'GET') {- return handleSearchGet(req, res);- }- if (req.method === 'POST') {- return handleSearchPost(req, res);- }- errorResponse(res, 405, 'urn:ok:error:method-not-allowed', 'Method not allowed.', {- handler: 'search',- extraHeaders: { Allow: 'GET, POST' },- });- }-const handleSearchGet = withValidation(EmptyRequestSchema,- async (req, res) => {- const url = new URL(req.url ?? '', 'http://localhost');- const limit = url.searchParams.get('limit');- const query = url.searchParams.get('query') ?? '';- const intent = parseSearchIntent(url.searchParams.get('intent'));- const ranking = parseSearchRanking(url.searchParams.get('ranking'));- const scopes = parseSearchScopes(- url.searchParams.get('scope') ?? url.searchParams.get('scopes'),- );- const semanticParam = parseSemanticParam(url.searchParams.get('semantic'));- const source = parseSearchSource(url.searchParams.get('source'));- const limitNum = limit === null ? undefined : Number(limit);-- if (query.length > 200) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Query is too long (max 200 chars).',- { handler: 'search-get' },- );- return;- }- try {+ catchErrors(+ async (req, res) => {+ const params = parseQuery(req);+ const limit = params.get('limit');+ const query = params.get('query') ?? '';+ const intent = parseSearchIntent(params.get('intent'));+ const ranking = parseSearchRanking(params.get('ranking'));+ const scopes = parseSearchScopes(params.get('scope') ?? params.get('scopes'));+ const semanticParam = parseSemanticParam(params.get('semantic'));+ const source = parseSearchSource(params.get('source'));+ const limitNum = limit === null ? undefined : Number(limit);++ if (query.length > 200) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Query is too long (max 200 chars).',+ { handler: 'search-get' },+ );+ return;+ }const body = await buildSearchResponse({query,intent,@@ -17313,41 +17244,34 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {source,});successResponse(res, 200, SearchSuccessSchema, body, { handler: 'search-get' });- } catch (e) {- errorResponse(- res,- 500,- 'urn:ok:error:internal-server-error',- 'Failed to search workspace.',- { handler: 'search-get', cause: e },- );- }- },+ },+ { handler: 'search-get', title: 'Failed to search workspace.' },+ ),{ handler: 'search-get', method: 'GET', skipBodyParse: true },);const handleSearchPost = withValidation(SearchRequestSchema,- async (_req, res, body) => {- const query = typeof body.query === 'string' ? body.query : '';- const intent = parseSearchIntent(body.intent);- const ranking = parseSearchRanking(body.ranking);- const scopes = parseSearchScopes(body.scopes ?? body.scope);- const limit = typeof body.limit === 'number' ? body.limit : undefined;- const semanticParam = parseSemanticParam(body.semantic);- const source = parseSearchSource(body.source);-- if (query.length > 200) {- errorResponse(- res,- 400,- 'urn:ok:error:invalid-request',- 'Query is too long (max 200 chars).',- { handler: 'search-post' },- );- return;- }- try {+ catchErrors(+ async (_req, res, body) => {+ const query = typeof body.query === 'string' ? body.query : '';+ const intent = parseSearchIntent(body.intent);+ const ranking = parseSearchRanking(body.ranking);+ const scopes = parseSearchScopes(body.scopes ?? body.scope);+ const limit = typeof body.limit === 'number' ? body.limit : undefined;+ const semanticParam = parseSemanticParam(body.semantic);+ const source = parseSearchSource(body.source);++ if (query.length > 200) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-request',+ 'Query is too long (max 200 chars).',+ { handler: 'search-post' },+ );+ return;+ }const responseBody = await buildSearchResponse({query,intent,@@ -17358,23 +17282,21 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {source,});successResponse(res, 200, SearchSuccessSchema, responseBody, { handler: 'search-post' });- } catch (e) {- errorResponse(- res,- 500,- 'urn:ok:error:internal-server-error',- 'Failed to search workspace.',- { handler: 'search-post', cause: e },- );- }- },+ },+ { handler: 'search-post', title: 'Failed to search workspace.' },+ ),{ handler: 'search-post', method: 'POST' },);+ const handleSearch = methodRouter(+ { GET: handleSearchGet, POST: handleSearchPost },+ { handler: 'search' },+ );+const handleSkillInstallState = withValidation(EmptyRequestSchema,- async (_req, res) => {- try {+ catchErrors(+ async (_req, res) => {const snapshot = await readSkillInstallStateSnapshot(homedir());successResponse(res,@@ -17386,16 +17308,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {extraHeaders: { 'Cache-Control': 'no-store' },},);- } catch (e) {- errorResponse(- res,- 500,- 'urn:ok:error:internal-server-error',- 'Failed to read skill install state.',- { handler: 'skill-install-state', cause: e },- );- }- },+ },+ { handler: 'skill-install-state', title: 'Failed to read skill install state.' },+ ),{handler: 'skill-install-state',method: 'GET',@@ -19253,6 +19168,58 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {secFetchUser: headerString('sec-fetch-user'),});+ const method = request.method ?? 'GET';+ // Normalize route for low-cardinality labels (metric labels, span+ // attributes, and the access log below). `:id` placeholders replace+ // dynamic segments; anything else collapses to the URL prefix.+ let routeTemplate = url;+ if (url.startsWith('/api/history/')) routeTemplate = '/api/history/:sha';+ else if (url.startsWith('/api/tags/')) routeTemplate = '/api/tags/:name';+ else if (!routes[url]) routeTemplate = '/api/*';++ // Request identity + access log for the /api/* surface. Slots BEFORE the+ // origin/loopback/host gates (without touching their order) so even+ // gate-rejected responses carry the `x-request-id` echo and produce an+ // access-log line. The `typeof` guards mirror the CORS block below —+ // unit-test doubles stub only `writeHead` + `end`.+ const requestId = url.startsWith('/api/') ? resolveRequestId(request) : undefined;+ if (requestId !== undefined) {+ rememberRequestId(request, requestId);+ if (typeof response.setHeader === 'function') {+ response.setHeader(REQUEST_ID_HEADER, requestId);+ }+ if (typeof response.once === 'function') {+ const accessStarted = Date.now();+ let accessLogged = false;+ // One line per request on whichever of finish/close fires first:+ // 'finish' is the fully-flushed response (including long-lived+ // NDJSON streams, logged at stream end); 'close' catches aborted+ // sockets (client disconnect, timeout destroy) that never finish.+ // Route TEMPLATE, never the raw path — cardinality discipline for+ // log aggregators matches the metric-label STOP rule. Byte counts+ // are omitted: Node exposes no cheap per-response counter under+ // chunked encoding (socket.bytesWritten is per-connection).+ const emitAccessLog = () => {+ if (accessLogged) return;+ accessLogged = true;+ log.info(+ {+ event: 'api.access',+ requestId,+ method,+ route: routeTemplate,+ status: response.statusCode,+ durationMs: Date.now() - accessStarted,+ ...(response.writableFinished ? {} : { aborted: true }),+ },+ `${method} ${routeTemplate} ${response.statusCode}`,+ );+ };+ response.once('finish', emitAccessLog);+ response.once('close', emitAccessLog);+ }+ }+// Origin-allowlist CORS for /api/*. Only loopback origins are accepted:// - No Origin header (same-origin browser tab, curl, CLI): passes through.// - Origin "null" (Electron packaged renderer, file:// per Fetch spec §4.3): allowed.@@ -19295,8 +19262,11 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {// origin / file:// packaged) before the real request fires.response.setHeader('Access-Control-Allow-Headers',- `Content-Type, Authorization, traceparent, tracestate, baggage, ${CLIENT_VERSION_HEADER.protocol}, ${CLIENT_VERSION_HEADER.runtime}, ${CLIENT_VERSION_HEADER.kind}`,+ `Content-Type, Authorization, traceparent, tracestate, baggage, ${REQUEST_ID_HEADER}, ${CLIENT_VERSION_HEADER.protocol}, ${CLIENT_VERSION_HEADER.runtime}, ${CLIENT_VERSION_HEADER.kind}`,);+ // Let cross-origin renderer JS read the correlation ID echo — CORS+ // hides non-safelisted response headers by default.+ response.setHeader('Access-Control-Expose-Headers', REQUEST_ID_HEADER);}// OPTIONS preflight — short-circuit with 204 + the headers above.if (request.method === 'OPTIONS') {@@ -19387,13 +19357,6 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {// Extract incoming trace context (W3C traceparent header) so this server// span attaches as a child of the browser-initiated trace.const extractedCtx = propagation.extract(context.active(), request.headers);- const method = request.method ?? 'GET';- // Normalize route for low-cardinality metric labels. `:id` placeholders- // replace dynamic segments; anything else collapses to the URL prefix.- let routeTemplate = url;- if (url.startsWith('/api/history/')) routeTemplate = '/api/history/:sha';- else if (url.startsWith('/api/tags/')) routeTemplate = '/api/tags/:name';- else if (!routes[url]) routeTemplate = '/api/*';const tracer = getTracer();const started = Date.now();@@ -19408,6 +19371,11 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {[ATTR_URL_PATH]: url,[ATTR_URL_SCHEME]: 'http',[ATTR_USER_AGENT_ORIGINAL]: request.headers['user-agent'] ?? '',+ // Correlation ID (UUID or client-supplied bounded token) — a+ // sanctioned span attribute like `ok.error.instance`; the+ // cardinality STOP rule governs metric labels, which stay+ // request-id-free.+ 'ok.request.id': requestId,},},async (span) => {diff --git a/packages/server/src/api-request-id.test.ts b/packages/server/src/api-request-id.test.tsnew file mode 100644index 000000000..6988290cf--- /dev/null+++ b/packages/server/src/api-request-id.test.ts@@ -0,0 +1,195 @@+/**+ * Request-identity + access-log behavior of the `onRequest` gate stack:+ * `x-request-id` echo (minted or honored), gate-rejection coverage, the+ * `ok.request.id`/access-log plumbing, and route-TEMPLATE cardinality on the+ * `api.access` line (never the raw path).+ */++import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import type { IncomingMessage, ServerResponse } from 'node:http';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { Readable } from 'node:stream';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { createApiExtension } from './api-extension.ts';+import type { FileIndexEntry } from './file-watcher.ts';+import { loggerFactory } from './logger.ts';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;++interface CapturedResponse {+ status: number;+ headers: Record<string, string>;+ setHeaders: Record<string, string>;+ body: string;+}++function makeReq(url: string, extraHeaders: Record<string, string> = {}): IncomingMessage {+ const readable = Readable.from(Buffer.from('')) as unknown as IncomingMessage;+ readable.method = 'GET';+ readable.url = url;+ readable.headers = { host: 'localhost', ...extraHeaders };+ return readable;+}++/**+ * Mock `ServerResponse` with the surface the gate stack exercises:+ * `setHeader` (header echo), `once` + synchronous `'finish'` dispatch on+ * `end()` (access log), and `statusCode` tracking through `writeHead`.+ */+function makeRes(): { res: ServerResponse; captured: CapturedResponse } {+ const captured: CapturedResponse = { status: 0, headers: {}, setHeaders: {}, body: '' };+ const listeners: Record<string, Array<() => void>> = {};+ const res = {+ statusCode: 200,+ headersSent: false,+ writableEnded: false,+ writableFinished: false,+ destroyed: false,+ setHeader(name: string, value: string) {+ captured.setHeaders[name.toLowerCase()] = value;+ },+ once(event: string, fn: () => void) {+ listeners[event] ??= [];+ listeners[event].push(fn);+ return res;+ },+ writeHead(status: number, headers?: Record<string, string>) {+ captured.status = status;+ res.statusCode = status;+ res.headersSent = true;+ if (headers) Object.assign(captured.headers, headers);+ return res;+ },+ end(body?: string) {+ captured.body = body ?? '';+ res.writableEnded = true;+ res.writableFinished = true;+ for (const fn of listeners.finish ?? []) fn();+ for (const fn of listeners.close ?? []) fn();+ },+ };+ return { res: res as unknown as ServerResponse, captured };+}++describe('onRequest request identity + access log', () => {+ let projectDir: string;+ let contentDir: string;++ beforeEach(() => {+ projectDir = mkdtempSync(join(tmpdir(), 'ok-request-id-'));+ contentDir = join(projectDir, 'content');+ mkdirSync(contentDir, { recursive: true });+ });++ afterEach(() => {+ rmSync(projectDir, { recursive: true, force: true });+ vi.restoreAllMocks();+ });++ async function callRoute(+ url: string,+ headers: Record<string, string> = {},+ ): Promise<CapturedResponse> {+ const ext = createApiExtension({+ hocuspocus: {} as never,+ sessionManager: {} as never,+ contentDir,+ getFileIndex: () => new Map<string, FileIndexEntry>(),+ });+ const req = makeReq(url, headers);+ const { res, captured } = makeRes();+ await (+ ext as {+ onRequest: (ctx: { request: IncomingMessage; response: ServerResponse }) => Promise<void>;+ }+ ).onRequest({ request: req, response: res });+ return captured;+ }++ test('mints a UUID x-request-id echo when the client sends none', async () => {+ const captured = await callRoute('/api/nonexistent-route');+ expect(captured.status).toBe(404);+ expect(captured.setHeaders['x-request-id']).toMatch(UUID_RE);+ });++ test('honors a well-formed incoming x-request-id', async () => {+ const captured = await callRoute('/api/nonexistent-route', {+ 'x-request-id': 'caller-supplied.001',+ });+ expect(captured.setHeaders['x-request-id']).toBe('caller-supplied.001');+ });++ test('replaces a malformed incoming x-request-id with a minted UUID', async () => {+ const captured = await callRoute('/api/nonexistent-route', {+ 'x-request-id': 'bad id with spaces',+ });+ expect(captured.setHeaders['x-request-id']).toMatch(UUID_RE);+ expect(captured.setHeaders['x-request-id']).not.toBe('bad id with spaces');+ });++ test('origin-gate 403 rejections still carry the x-request-id echo', async () => {+ const captured = await callRoute('/api/documents', {+ origin: 'https://evil.example.com',+ });+ expect(captured.status).toBe(403);+ expect(JSON.parse(captured.body).type).toBe('urn:ok:error:invalid-origin');+ expect(captured.setHeaders['x-request-id']).toMatch(UUID_RE);+ });++ test('exposes the header to cross-origin readers and allows it on requests', async () => {+ const captured = await callRoute('/api/nonexistent-route', {+ origin: 'http://localhost:5173',+ });+ expect(captured.setHeaders['access-control-expose-headers']).toBe('x-request-id');+ expect(captured.setHeaders['access-control-allow-headers']).toContain('x-request-id');+ });++ test('emits ONE api.access line with the route TEMPLATE, status, duration, and request id', async () => {+ const log = loggerFactory.getLogger('api');+ const infoSpy = vi.spyOn(log, 'info');+ // Empty dynamic segment: templated as /api/history/:sha but dispatches+ // nothing, so the request closes as an api-dispatch 404 without touching+ // handler dependencies.+ const captured = await callRoute('/api/history/');+ const accessCalls = infoSpy.mock.calls.filter(+ (c) => (c[0] as { event?: string })?.event === 'api.access',+ );+ expect(accessCalls).toHaveLength(1);+ const line = accessCalls[0]?.[0] as {+ requestId: string;+ method: string;+ route: string;+ status: number;+ durationMs: number;+ };+ expect(line.route).toBe('/api/history/:sha');+ expect(line.route).not.toBe('/api/history/');+ expect(line.method).toBe('GET');+ expect(line.status).toBe(404);+ expect(typeof line.durationMs).toBe('number');+ expect(line.requestId).toBe(captured.setHeaders['x-request-id']);+ });++ test('unmatched routes collapse to the /api/* template on the access line', async () => {+ const log = loggerFactory.getLogger('api');+ const infoSpy = vi.spyOn(log, 'info');+ await callRoute('/api/no-such-endpoint-xyz');+ const accessCalls = infoSpy.mock.calls.filter(+ (c) => (c[0] as { event?: string })?.event === 'api.access',+ );+ expect(accessCalls).toHaveLength(1);+ expect((accessCalls[0]?.[0] as { route: string }).route).toBe('/api/*');+ });++ test('non-API requests get no x-request-id echo and no access line', async () => {+ const log = loggerFactory.getLogger('api');+ const infoSpy = vi.spyOn(log, 'info');+ const captured = await callRoute('/some/static/path.css');+ expect(captured.setHeaders['x-request-id']).toBeUndefined();+ const accessCalls = infoSpy.mock.calls.filter(+ (c) => (c[0] as { event?: string })?.event === 'api.access',+ );+ expect(accessCalls).toHaveLength(0);+ });+});diff --git a/packages/server/src/http/catch-errors.test.ts b/packages/server/src/http/catch-errors.test.tsnew file mode 100644index 000000000..f00467c58--- /dev/null+++ b/packages/server/src/http/catch-errors.test.ts@@ -0,0 +1,148 @@+/**+ * `catchErrors(...)` boundary behavior: typed 500 emission with `cause`,+ * variadic pass-through composition with `withValidation`, and the STOP-rule+ * guarantee that `BridgeMergeContentLossError` is NEVER swallowed (its single+ * sanctioned catch site is Observer A Path B in `server-observers.ts`).+ */++import type { IncomingMessage, ServerResponse } from 'node:http';+import { BridgeMergeContentLossError } from '@inkeep/open-knowledge-core';+import { describe, expect, test } from 'vitest';+import { catchErrors } from './catch-errors.ts';++function makeMockRes(opts: { headersSent?: boolean } = {}) {+ const writeHeadCalls: Array<{ status: number; headers: Record<string, string> }> = [];+ const endCalls: string[] = [];+ const res = {+ headersSent: opts.headersSent ?? false,+ writableEnded: false,+ destroyed: false,+ writeHead(status: number, headers: Record<string, string>) {+ writeHeadCalls.push({ status, headers });+ return res;+ },+ end(body: string) {+ endCalls.push(body);+ return res;+ },+ };+ return { res: res as unknown as ServerResponse, writeHeadCalls, endCalls };+}++const req = {} as IncomingMessage;++function makeContentLossError(): BridgeMergeContentLossError {+ return new BridgeMergeContentLossError({+ baseline: 'a',+ userText: 'b',+ agentText: 'c',+ result: 'd',+ lostSubstrings: ['b'],+ which: 'substring',+ side: 'user',+ });+}++describe('catchErrors', () => {+ test('success path passes through without touching the response', async () => {+ const { res, writeHeadCalls } = makeMockRes();+ let sawBody: unknown;+ const wrapped = catchErrors(+ async (_req, _res, body: { x: number }) => {+ sawBody = body;+ },+ { handler: 'test-handler' },+ );+ await wrapped(req, res, { x: 42 });+ expect(sawBody).toEqual({ x: 42 });+ expect(writeHeadCalls).toHaveLength(0);+ });++ test('generic throw emits an RFC 9457 500 with the handler title', async () => {+ const { res, writeHeadCalls, endCalls } = makeMockRes();+ const wrapped = catchErrors(+ async () => {+ throw new Error('disk exploded');+ },+ { handler: 'test-handler', title: 'Failed to list widgets.' },+ );+ await wrapped(req, res);+ expect(writeHeadCalls).toHaveLength(1);+ expect(writeHeadCalls[0]?.status).toBe(500);+ expect(writeHeadCalls[0]?.headers['Content-Type']).toBe('application/problem+json');+ const body = JSON.parse(endCalls[0] ?? '{}') as Record<string, unknown>;+ expect(body.type).toBe('urn:ok:error:internal-server-error');+ expect(body.title).toBe('Failed to list widgets.');+ expect(body.status).toBe(500);+ expect(String(body.instance)).toMatch(/^urn:uuid:/);+ });++ test('title defaults to the generic internal-server-error copy', async () => {+ const { res, endCalls } = makeMockRes();+ const wrapped = catchErrors(+ () => {+ throw new Error('boom');+ },+ { handler: 'test-handler' },+ );+ await wrapped(req, res);+ const body = JSON.parse(endCalls[0] ?? '{}') as Record<string, unknown>;+ expect(body.title).toBe('Internal server error.');+ });++ test('non-Error throw values still produce the typed 500', async () => {+ const { res, writeHeadCalls } = makeMockRes();+ const stringFailure: unknown = 'string failure';+ const wrapped = catchErrors(+ () => {+ throw stringFailure;+ },+ { handler: 'test-handler' },+ );+ await wrapped(req, res);+ expect(writeHeadCalls[0]?.status).toBe(500);+ });++ test('STOP rule: BridgeMergeContentLossError passes through uncaught, response untouched', async () => {+ const { res, writeHeadCalls, endCalls } = makeMockRes();+ const loss = makeContentLossError();+ const wrapped = catchErrors(+ async () => {+ throw loss;+ },+ { handler: 'test-handler' },+ );+ await expect(wrapped(req, res)).rejects.toBe(loss);+ expect(writeHeadCalls).toHaveLength(0);+ expect(endCalls).toHaveLength(0);+ });++ test('STOP rule: name-matched content-loss error from a foreign class identity also passes through', async () => {+ // Two loaded copies of core would break `instanceof`; the wrapper's+ // name-based companion check must keep the pass-through guarantee.+ const { res, writeHeadCalls } = makeMockRes();+ const foreign = new Error('bridge loss (foreign identity)');+ foreign.name = 'BridgeMergeContentLossError';+ const wrapped = catchErrors(+ () => {+ throw foreign;+ },+ { handler: 'test-handler' },+ );+ await expect(wrapped(req, res)).rejects.toBe(foreign);+ expect(writeHeadCalls).toHaveLength(0);+ });++ test('throw after the response is committed suppresses the double-write', async () => {+ const { res, writeHeadCalls } = makeMockRes({ headersSent: true });+ const wrapped = catchErrors(+ () => {+ throw new Error('late failure');+ },+ { handler: 'test-handler' },+ );+ await wrapped(req, res);+ // errorResponse's internal triple-guard owns this case: no second head.+ expect(writeHeadCalls).toHaveLength(0);+ });+});diff --git a/packages/server/src/http/catch-errors.ts b/packages/server/src/http/catch-errors.tsnew file mode 100644index 000000000..0fa83b725--- /dev/null+++ b/packages/server/src/http/catch-errors.ts@@ -0,0 +1,81 @@+/**+ * Opt-in error boundary for `api-extension.ts` handlers.+ *+ * `withValidation(...)` deliberately does NOT catch inner-handler throws, so+ * historically every handler carried a hand-rolled+ * `try { ... } catch (e) { errorResponse(res, 500, ...) }` tail. `catchErrors`+ * replaces that tail: it wraps the handler, catches anything the handler+ * throws, and routes it through the sanctioned `errorResponse(...)` emitter+ * as a typed RFC 9457 500 with the original error attached as `cause` (Pino+ * `err` serialization; never on the wire).+ *+ * Composes on either side of `withValidation`'s inner handler thanks to the+ * variadic signature:+ *+ * ```ts+ * const handleFoo = withValidation(+ * FooRequestSchema,+ * catchErrors(async (req, res, body) => { ... }, { handler: 'foo' }),+ * { handler: 'foo', method: 'POST' },+ * );+ * ```+ *+ * STOP rule: `BridgeMergeContentLossError` is NEVER swallowed here — its+ * single sanctioned catch site is Observer A Path B in `server-observers.ts`+ * (silent checkpoint + merge as-computed). This wrapper re-throws it so the+ * error keeps propagating to the extension-level machinery unchanged; a+ * catch here would silently drop the content-loss observability signal.+ */++import type { IncomingMessage, ServerResponse } from 'node:http';+import { BridgeMergeContentLossError } from '@inkeep/open-knowledge-core';+import { errorResponse } from './error-response.ts';++export interface CatchErrorsOptions {+ /** Handler tag for telemetry (`ok.api.error.count{handler}`) + the log line. */+ handler: string;+ /**+ * Wire `title` for the 500 envelope. Defaults to `'Internal server+ * error.'`; migrated handlers pass their historical per-handler title+ * (e.g. `'Failed to list templates.'`) so the wire contract is unchanged.+ */+ title?: string;+}++/**+ * Wrap a handler so any throw becomes a typed RFC 9457 500.+ *+ * The already-responded case (handler wrote a response, then threw) is+ * delegated to `errorResponse`'s internal `headersSent || writableEnded ||+ * destroyed` triple-guard, which suppresses the double-write and logs the+ * `api.error.double-write` structured event — identical to what the+ * hand-rolled catch tails did before migration.+ */+export function catchErrors<Args extends unknown[]>(+ fn: (req: IncomingMessage, res: ServerResponse, ...rest: Args) => Promise<void> | void,+ options: CatchErrorsOptions,+): (req: IncomingMessage, res: ServerResponse, ...rest: Args) => Promise<void> {+ return async (req, res, ...rest) => {+ try {+ await fn(req, res, ...rest);+ } catch (err) {+ // STOP rule: content-loss errors pass through uncaught (see module doc).+ // The name check is a belt-and-braces companion to `instanceof` so a+ // duplicated class identity (two loaded copies of core) cannot demote+ // the signal into a generic 500.+ if (+ err instanceof BridgeMergeContentLossError ||+ (err instanceof Error && err.name === 'BridgeMergeContentLossError')+ ) {+ throw err;+ }+ errorResponse(+ res,+ 500,+ 'urn:ok:error:internal-server-error',+ options.title ?? 'Internal server error.',+ { handler: options.handler, cause: err },+ );+ }+ };+}diff --git a/packages/server/src/http/handler-utils.test.ts b/packages/server/src/http/handler-utils.test.tsnew file mode 100644index 000000000..d93f8d1c4Binary files /dev/null and b/packages/server/src/http/handler-utils.test.ts differdiff --git a/packages/server/src/http/handler-utils.ts b/packages/server/src/http/handler-utils.tsnew file mode 100644index 000000000..be24658ca--- /dev/null+++ b/packages/server/src/http/handler-utils.ts@@ -0,0 +1,31 @@+/**+ * Small shared idioms for `api-extension.ts` handlers: query-string parsing+ * and errno extraction. Extracted so handlers stop hand-rolling competing+ * variants (two `new URL(...)` base idioms; repeated+ * `(err as NodeJS.ErrnoException).code` casts).+ */++import type { IncomingMessage } from 'node:http';++/**+ * Parse the request's query string.+ *+ * Uses a fixed dummy base rather than deriving one from the `Host` header:+ * query parsing never needs the authority component, and a malformed `Host`+ * header would make `new URL(req.url, `http://${host}`)` throw — turning a+ * hostile header into a 500 on an otherwise-valid request.+ */+export function parseQuery(req: IncomingMessage): URLSearchParams {+ return new URL(req.url ?? '', 'http://localhost').searchParams;+}++/**+ * Extract the string `code` from a Node errno-style error (`'ENOENT'`,+ * `'EACCES'`, ...). Returns `undefined` for non-objects, errors without a+ * `code`, and non-string codes — callers compare against errno literals, so+ * `undefined` behaves like any non-matching code.+ */+export function errnoCode(err: unknown): string | undefined {+ const code = (err as NodeJS.ErrnoException | null | undefined)?.code;+ return typeof code === 'string' ? code : undefined;+}diff --git a/packages/server/src/http/method-router.test.ts b/packages/server/src/http/method-router.test.tsnew file mode 100644index 000000000..b9196a443--- /dev/null+++ b/packages/server/src/http/method-router.test.ts@@ -0,0 +1,83 @@+/**+ * `methodRouter(...)` dispatch + the preserved 405 wire shape (RFC 9457+ * problem+json, `Allow` header in declaration order, handler tag).+ */++import type { IncomingMessage, ServerResponse } from 'node:http';+import { describe, expect, test } from 'vitest';+import { methodRouter } from './method-router.ts';++function makeMockRes() {+ const writeHeadCalls: Array<{ status: number; headers: Record<string, string> }> = [];+ const endCalls: string[] = [];+ const res = {+ headersSent: false,+ writableEnded: false,+ destroyed: false,+ writeHead(status: number, headers: Record<string, string>) {+ writeHeadCalls.push({ status, headers });+ return res;+ },+ end(body: string) {+ endCalls.push(body);+ return res;+ },+ };+ return { res: res as unknown as ServerResponse, writeHeadCalls, endCalls };+}++function makeReq(method: string | undefined): IncomingMessage {+ return { method } as IncomingMessage;+}++describe('methodRouter', () => {+ test('dispatches to the matching verb handler and awaits it', async () => {+ const calls: string[] = [];+ const router = methodRouter(+ {+ GET: async () => {+ calls.push('GET');+ },+ PUT: async () => {+ calls.push('PUT');+ },+ },+ { handler: 'test-route' },+ );+ const { res } = makeMockRes();+ await router(makeReq('PUT'), res);+ expect(calls).toEqual(['PUT']);+ });++ test('unknown verb emits the historical 405 problem+json with Allow in declaration order', async () => {+ const router = methodRouter(+ { GET: async () => {}, PUT: async () => {}, POST: async () => {}, DELETE: async () => {} },+ { handler: 'test-route' },+ );+ const { res, writeHeadCalls, endCalls } = makeMockRes();+ await router(makeReq('PATCH'), res);+ expect(writeHeadCalls).toHaveLength(1);+ expect(writeHeadCalls[0]?.status).toBe(405);+ expect(writeHeadCalls[0]?.headers.Allow).toBe('GET, PUT, POST, DELETE');+ expect(writeHeadCalls[0]?.headers['Content-Type']).toBe('application/problem+json');+ const body = JSON.parse(endCalls[0] ?? '{}') as Record<string, unknown>;+ expect(body.type).toBe('urn:ok:error:method-not-allowed');+ expect(body.title).toBe('Method not allowed.');+ expect(body.status).toBe(405);+ });++ test('missing req.method falls through to the 405', async () => {+ const router = methodRouter({ GET: async () => {} }, { handler: 'test-route' });+ const { res, writeHeadCalls } = makeMockRes();+ await router(makeReq(undefined), res);+ expect(writeHeadCalls[0]?.status).toBe(405);+ expect(writeHeadCalls[0]?.headers.Allow).toBe('GET');+ });++ test('HEAD is not implicitly mapped to GET (historical dispatcher behavior)', async () => {+ const router = methodRouter({ GET: async () => {} }, { handler: 'test-route' });+ const { res, writeHeadCalls } = makeMockRes();+ await router(makeReq('HEAD'), res);+ expect(writeHeadCalls[0]?.status).toBe(405);+ });+});diff --git a/packages/server/src/http/method-router.ts b/packages/server/src/http/method-router.tsnew file mode 100644index 000000000..78cd735d8--- /dev/null+++ b/packages/server/src/http/method-router.ts@@ -0,0 +1,47 @@+/**+ * HTTP-verb dispatcher for `api-extension.ts` routes that multiplex several+ * handlers behind one path (`/api/skill` GET/PUT/POST/DELETE, `/api/search`+ * GET/POST, ...). Replaces the hand-rolled+ * `if (req.method === 'GET') return handleXGet(req, res); ... errorResponse(405)`+ * dispatcher functions with a single declarative map.+ *+ * The 405 fallback preserves the historical wire shape exactly: RFC 9457+ * `urn:ok:error:method-not-allowed` via `errorResponse(...)` with an `Allow`+ * header listing the supported verbs in declaration order.+ */++import type { IncomingMessage, ServerResponse } from 'node:http';+import { errorResponse } from './error-response.ts';++export type RouteHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void> | void;++type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';++export interface MethodRouterOptions {+ /** Handler tag for the 405 fallback's telemetry + log line. */+ handler: string;+}++/**+ * Build a route handler that dispatches on `req.method`.+ *+ * Declare AFTER the per-verb handlers it references — the map captures the+ * handler values at declaration time (`const` initializers are not hoisted).+ */+export function methodRouter(+ methods: Partial<Record<HttpMethod, RouteHandler>>,+ options: MethodRouterOptions,+): (req: IncomingMessage, res: ServerResponse) => Promise<void> {+ const allow = Object.keys(methods).join(', ');+ return async (req, res) => {+ const handler = req.method !== undefined ? methods[req.method as HttpMethod] : undefined;+ if (handler) {+ await handler(req, res);+ return;+ }+ errorResponse(res, 405, 'urn:ok:error:method-not-allowed', 'Method not allowed.', {+ handler: options.handler,+ extraHeaders: { Allow: allow },+ });+ };+}diff --git a/packages/server/src/http/request-id.test.ts b/packages/server/src/http/request-id.test.tsnew file mode 100644index 000000000..a83caaf55--- /dev/null+++ b/packages/server/src/http/request-id.test.ts@@ -0,0 +1,54 @@+import type { IncomingMessage } from 'node:http';+import { describe, expect, test } from 'vitest';+import {+ getRequestId,+ REQUEST_ID_HEADER,+ rememberRequestId,+ resolveRequestId,+} from './request-id.ts';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;++function makeReq(headerValue?: string | string[]): IncomingMessage {+ return {+ headers: headerValue === undefined ? {} : { [REQUEST_ID_HEADER]: headerValue },+ } as IncomingMessage;+}++describe('resolveRequestId', () => {+ test('mints a UUID when no header is present', () => {+ expect(resolveRequestId(makeReq())).toMatch(UUID_RE);+ });++ test('honors a well-formed incoming id', () => {+ expect(resolveRequestId(makeReq('mcp-shim.0042_a'))).toBe('mcp-shim.0042_a');+ });++ test('takes the first value of a multi-valued header', () => {+ expect(resolveRequestId(makeReq(['first-id', 'second-id']))).toBe('first-id');+ });++ test('replaces out-of-charset ids with a minted UUID', () => {+ for (const hostile of ['has space', 'crlf\r\ninject', 'ünïcode', 'semi;colon', '']) {+ const resolved = resolveRequestId(makeReq(hostile));+ expect(resolved).not.toBe(hostile);+ expect(resolved).toMatch(UUID_RE);+ }+ });++ test('replaces over-length ids with a minted UUID', () => {+ const long = 'a'.repeat(129);+ expect(resolveRequestId(makeReq(long))).toMatch(UUID_RE);+ expect(resolveRequestId(makeReq('a'.repeat(128)))).toBe('a'.repeat(128));+ });+});++describe('remember/getRequestId', () => {+ test('round-trips per request object', () => {+ const a = makeReq();+ const b = makeReq();+ rememberRequestId(a, 'id-a');+ expect(getRequestId(a)).toBe('id-a');+ expect(getRequestId(b)).toBeUndefined();+ });+});diff --git a/packages/server/src/http/request-id.ts b/packages/server/src/http/request-id.tsnew file mode 100644index 000000000..80acb5cf0--- /dev/null+++ b/packages/server/src/http/request-id.ts@@ -0,0 +1,50 @@+/**+ * Per-request correlation IDs for the `/api/*` surface.+ *+ * The `onRequest` gate stack in `api-extension.ts` resolves one ID per API+ * request — honoring a well-formed incoming `x-request-id` (so multi-hop+ * callers like the MCP shim can propagate their own ID) or minting a UUID —+ * then echoes it as an `x-request-id` response header, stamps it on the+ * request span (`ok.request.id`), and includes it on the `api.access` log+ * line. Handlers can read it via `getRequestId(req)` for their own log+ * lines; the WeakMap keeps the plumbing off the handler signatures until+ * the planned route split introduces a real per-request context object.+ */++import { randomUUID } from 'node:crypto';+import type { IncomingMessage } from 'node:http';++/** Canonical header name, shared by the inbound read and the response echo. */+export const REQUEST_ID_HEADER = 'x-request-id';++/**+ * Accepted shape for a client-supplied request ID. Bounded length + a+ * conservative token charset so a hostile header can't smuggle log-breaking+ * or header-splitting bytes into the echo/log path. Anything non-conforming+ * is silently replaced with a minted UUID (never an error — the ID is a+ * diagnostic courtesy, not an input contract).+ */+const REQUEST_ID_RE = /^[A-Za-z0-9._-]{1,128}$/;++/**+ * Resolve the request ID for an incoming request: the validated inbound+ * `x-request-id` when present and well-formed, else a fresh UUID.+ */+export function resolveRequestId(req: IncomingMessage): string {+ const raw = req.headers[REQUEST_ID_HEADER];+ const candidate = Array.isArray(raw) ? raw[0] : raw;+ if (candidate !== undefined && REQUEST_ID_RE.test(candidate)) return candidate;+ return randomUUID();+}++const requestIds = new WeakMap<IncomingMessage, string>();++/** Associate the resolved ID with the request object (gate-stack only). */+export function rememberRequestId(req: IncomingMessage, id: string): void {+ requestIds.set(req, id);+}++/** Read the ID the gate stack resolved for this request, if any. */+export function getRequestId(req: IncomingMessage): string | undefined {+ return requestIds.get(req);+}