Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(ok): Wave 2 group 5 multi-verb + mutating natives (PRD-8396) (#3928)

omar-inkeep435f6a06a187
diff --git a/packages/app/tests/integration/attribution-sweep-coverage.test.ts b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
index 93040288f..a44098bb5 100644
--- a/packages/app/tests/integration/attribution-sweep-coverage.test.ts
+++ b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
@@ -1,11 +1,13 @@
/**
* Attribution sweep meta-test — static analysis gate.
*
- * Asserts: (1) every mutating POST handler in api-extension.ts threads
+ * Asserts: (1) every mutating POST handler — scanned over `api-extension.ts`
+ * plus every lifted handler source (`skills-sh-handlers.ts`,
+ * `http/*-routes.ts` — see `HANDLER_SOURCES`) — threads
* identity at entry (via either `extractAgentIdentity` for agent-write
* handlers or `extractActorIdentity` for rename + rollback); (2) no new
- * POST handler can be added to the route registry without being explicitly
- * tracked here; (3) `extract-actor-identity.ts` never reads body-supplied
+ * POST handler can be added to those sources' route records without being
+ * explicitly tracked here; (3) `extract-actor-identity.ts` never reads body-supplied
* `principalId` — server's `getPrincipal()` is the sole source (HTTP body
* is unauthenticated; structurally enforcing the trust boundary).
*/
@@ -13,29 +15,29 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, test } from 'vitest';
+import {
+ extractRouteHandlerNames,
+ HANDLER_RUN_END_NEEDLES,
+ listNativeRouteFiles,
+} from '../native-route-files.test-helper.ts';
const API_EXT_PATH = join(import.meta.dirname, '../../../server/src/api-extension.ts');
const source = readFileSync(API_EXT_PATH, 'utf8');
/**
* Handlers and route records no longer all live in `api-extension.ts`: lifted
* groups (`skills-sh-handlers.ts`, and native Wave 2 groups like
- * `http/link-graph-routes.ts`, which carry their OWN `const routes:` record)
- * must stay inside the sweep, mirroring `error-envelope-coverage.test.ts` —
+ * `http/link-graph-routes.ts`, which carry their OWN route record in any
+ * sanctioned declaration shape) must stay inside the sweep, mirroring
+ * `error-envelope-coverage.test.ts` —
* otherwise a mutating handler added to a lifted file would ship without a
* categorization decision.
*/
+const SERVER_SRC = join(import.meta.dirname, '../../../server/src');
const HANDLER_SOURCES = [
source,
- ...[
- 'skills-sh-handlers.ts',
- 'http/link-graph-routes.ts',
- 'http/metrics-routes.ts',
- 'http/document-routes.ts',
- 'http/config-system-routes.ts',
- 'http/lint-routes.ts',
- 'http/history-routes.ts',
- 'http/skills-read-routes.ts',
- ].map((file) => readFileSync(join(import.meta.dirname, '../../../server/src', file), 'utf8')),
+ ...['skills-sh-handlers.ts', ...listNativeRouteFiles(SERVER_SRC)].map((file) =>
+ readFileSync(join(SERVER_SRC, file), 'utf8'),
+ ),
];
const ACTOR_HELPER_PATH = join(
import.meta.dirname,
@@ -488,29 +490,24 @@ function extractHandlerBody(handlerName: string): string | null {
if (start === -1) return null;
const nextFn = owner.indexOf('\n async function handle', start + 1);
const nextConst = owner.indexOf('\n const handle', start + 1);
- // Bound the last handler at the route table so the onRequest extension
- // body (which uses `errorResponse(...)` for the /api/* Origin gate) is
- // never folded into the handler slice. Factory modules end their handler
- // run at the returned record instead, so bound on that too.
- const nextRoutes = owner.indexOf('\n const routes:', start + 1);
+ // Bound the last handler at the route-record declaration (any sanctioned
+ // shape) so the module tail after the handler run — the record itself and
+ // the table plumbing — is never folded into the last handler's slice.
+ // Factory modules end their handler run at the returned record instead,
+ // so bound on that too.
+ const nextRoutes = HANDLER_RUN_END_NEEDLES.map((needle) => owner.indexOf(needle, start + 1));
const nextReturn = owner.indexOf('\n return {', start + 1);
- const candidates = [nextFn, nextConst, nextRoutes, nextReturn].filter((i) => i !== -1);
+ const candidates = [nextFn, nextConst, ...nextRoutes, nextReturn].filter((i) => i !== -1);
const next = candidates.length === 0 ? -1 : Math.min(...candidates);
return owner.slice(start, next === -1 ? owner.length : next);
}
function extractStaticRouteHandlerNames(): string[] {
- // Every source's `const routes:` record participates — the legacy dispatch
- // record in `api-extension.ts` AND each native group's own record.
- return HANDLER_SOURCES.flatMap((text) => {
- const routesStart = text.indexOf('\n const routes:');
- if (routesStart === -1) return [];
- const enableTestRoutes = text.indexOf('\n if (enableTestRoutes)', routesStart);
- const nativeTable = text.indexOf('\n const table', routesStart);
- const bounds = [enableTestRoutes, nativeTable].filter((i) => i !== -1);
- const slice = text.slice(routesStart, bounds.length === 0 ? text.length : Math.min(...bounds));
- return [...slice.matchAll(/:\s*(handle\w+)/g)].map((m) => m[1]);
- });
+ // Every source's route record participates — the legacy dispatch record in
+ // `api-extension.ts` AND each native group's record in every declaration
+ // shape the helper sanctions (shared extractor:
+ // `native-route-files.test-helper.ts`).
+ return HANDLER_SOURCES.flatMap((text) => extractRouteHandlerNames(text));
}
describe('attribution sweep coverage (FR-5, D42)', () => {
diff --git a/packages/app/tests/integration/conflict-gate-coverage.test.ts b/packages/app/tests/integration/conflict-gate-coverage.test.ts
index 90032cb4c..de7218199 100644
--- a/packages/app/tests/integration/conflict-gate-coverage.test.ts
+++ b/packages/app/tests/integration/conflict-gate-coverage.test.ts
@@ -2,7 +2,9 @@
* Conflict-gate coverage meta-test.
*
* Mirror of `attribution-sweep-coverage.test.ts` for the conflict-aware
- * write-refusal contract. Statically scans `api-extension.ts` and asserts:
+ * write-refusal contract. Statically scans `api-extension.ts` plus every
+ * lifted handler source (`skills-sh-handlers.ts`, `http/*-routes.ts` — see
+ * `HANDLER_SOURCES`) and asserts:
*
* (1) Every REQUIRED mutating handler (the 8 surfaces) either calls
* `respondDocInConflict` directly OR routes
@@ -23,6 +25,11 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, test } from 'vitest';
+import {
+ extractRouteHandlerNames,
+ HANDLER_RUN_END_NEEDLES,
+ listNativeRouteFiles,
+} from '../native-route-files.test-helper.ts';
const API_EXT_PATH = join(import.meta.dirname, '../../../server/src/api-extension.ts');
const source = readFileSync(API_EXT_PATH, 'utf8');
@@ -30,21 +37,15 @@ const source = readFileSync(API_EXT_PATH, 'utf8');
* The conflict-refusal contract applies to any handler that writes user
* content, regardless of which file it lives in — lifted route groups
* (`skills-sh-handlers.ts`, native Wave 2 groups like
- * `http/link-graph-routes.ts` with their OWN `const routes:` record) stay
- * inside the scan, mirroring `error-envelope-coverage.test.ts`.
+ * `http/link-graph-routes.ts` with their OWN route record in any sanctioned
+ * declaration shape) stay inside the scan, mirroring `error-envelope-coverage.test.ts`.
*/
+const SERVER_SRC = join(import.meta.dirname, '../../../server/src');
const HANDLER_SOURCES = [
source,
- ...[
- 'skills-sh-handlers.ts',
- 'http/link-graph-routes.ts',
- 'http/metrics-routes.ts',
- 'http/document-routes.ts',
- 'http/config-system-routes.ts',
- 'http/lint-routes.ts',
- 'http/history-routes.ts',
- 'http/skills-read-routes.ts',
- ].map((file) => readFileSync(join(import.meta.dirname, '../../../server/src', file), 'utf8')),
+ ...['skills-sh-handlers.ts', ...listNativeRouteFiles(SERVER_SRC)].map((file) =>
+ readFileSync(join(SERVER_SRC, file), 'utf8'),
+ ),
];
/**
@@ -392,26 +393,20 @@ function extractHandlerBody(handlerName: string): string | null {
if (start === -1) return null;
const nextFn = owner.indexOf('\n async function handle', start + 1);
const nextConst = owner.indexOf('\n const handle', start + 1);
- const nextRoutes = owner.indexOf('\n const routes:', start + 1);
+ const nextRoutes = HANDLER_RUN_END_NEEDLES.map((needle) => owner.indexOf(needle, start + 1));
// Factory modules end their handler run at the returned record.
const nextReturn = owner.indexOf('\n return {', start + 1);
- const candidates = [nextFn, nextConst, nextRoutes, nextReturn].filter((i) => i !== -1);
+ const candidates = [nextFn, nextConst, ...nextRoutes, nextReturn].filter((i) => i !== -1);
const next = candidates.length === 0 ? -1 : Math.min(...candidates);
return owner.slice(start, next === -1 ? owner.length : next);
}
function extractStaticRouteHandlerNames(): string[] {
- // Every source's `const routes:` record participates — the legacy dispatch
- // record in `api-extension.ts` AND each native group's own record.
- return HANDLER_SOURCES.flatMap((text) => {
- const routesStart = text.indexOf('\n const routes:');
- if (routesStart === -1) return [];
- const enableTestRoutes = text.indexOf('\n if (enableTestRoutes)', routesStart);
- const nativeTable = text.indexOf('\n const table', routesStart);
- const bounds = [enableTestRoutes, nativeTable].filter((i) => i !== -1);
- const slice = text.slice(routesStart, bounds.length === 0 ? text.length : Math.min(...bounds));
- return [...slice.matchAll(/:\s*(handle\w+)/g)].map((m) => m[1]);
- });
+ // Every source's route record participates — the legacy dispatch record in
+ // `api-extension.ts` AND each native group's record in every declaration
+ // shape the helper sanctions (shared extractor:
+ // `native-route-files.test-helper.ts`).
+ return HANDLER_SOURCES.flatMap((text) => extractRouteHandlerNames(text));
}
describe('conflict-gate coverage (FR9)', () => {
diff --git a/packages/app/tests/integration/error-envelope-coverage.test.ts b/packages/app/tests/integration/error-envelope-coverage.test.ts
index e08d35120..2c1a7a35e 100644
--- a/packages/app/tests/integration/error-envelope-coverage.test.ts
+++ b/packages/app/tests/integration/error-envelope-coverage.test.ts
@@ -2,7 +2,9 @@
* Error-envelope coverage meta-test — fail-on-any-occurrence mode.
*
* Mirrors the precedent #20 / `attribution-sweep-coverage.test.ts` style:
- * static AST scan over `packages/server/src/api-extension.ts` enforcing that
+ * static source scan over `api-extension.ts` plus every lifted handler source
+ * (`skills-sh-handlers.ts`, `http/*-routes.ts` — see `HANDLER_SOURCES`),
+ * enforcing that
*
* 1. Every handler emits errors via `errorResponse(...)` and never via an
* inline `json(res, NNN, { ok: false, ... })` envelope.
@@ -19,11 +21,16 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, test } from 'vitest';
+import {
+ extractRouteHandlerNames,
+ HANDLER_RUN_END_NEEDLES,
+ listNativeRouteFiles,
+} from '../native-route-files.test-helper.ts';
const SERVER_SRC = join(import.meta.dirname, '../../../server/src');
/**
- * Route handlers do not all live in one file: the six skills.sh handlers sit in
- * `skills-sh-handlers.ts`, built by a factory the route table destructures. Every
+ * Route handlers do not all live in one file: the seven skills.sh handlers sit in
+ * `skills-sh-handlers.ts`, whose record lives in `skills-sh-routes.ts`. Every
* scan below runs over each source, because a handler that moves out of
* `api-extension.ts` would otherwise escape these rules silently rather than
* failing anything.
@@ -31,42 +38,25 @@ const SERVER_SRC = join(import.meta.dirname, '../../../server/src');
const HANDLER_SOURCES = [
'api-extension.ts',
'skills-sh-handlers.ts',
- 'http/link-graph-routes.ts',
- 'http/metrics-routes.ts',
- 'http/document-routes.ts',
- 'http/config-system-routes.ts',
- 'http/lint-routes.ts',
- 'http/history-routes.ts',
- 'http/skills-read-routes.ts',
+ ...listNativeRouteFiles(SERVER_SRC),
].map((file) => ({
file,
text: readFileSync(join(SERVER_SRC, file), 'utf8'),
}));
/** The shared success spine lives in `api-extension.ts` only (fallback owner
- * for `extractHandlerBody`). Route-table records, by contrast, now live in
- * `api-extension.ts` AND each native group file — see
- * `extractRouteTableHandlerNames`. */
+ * for `extractHandlerBody`). Route records, by contrast, now live in
+ * `api-extension.ts` AND each native group file, in any sanctioned
+ * declaration shape — see `extractRouteRecordHandlerNames`. */
const source = HANDLER_SOURCES[0]?.text ?? '';
/**
* Every `'/api/…': handle<X>` binding across all handler sources — the legacy
- * dispatch record in `api-extension.ts` AND each native group's own `const
- * routes:` record. Mirrors `attribution-sweep-coverage.test.ts` /
- * `conflict-gate-coverage.test.ts`'s `extractStaticRouteHandlerNames`: bound
- * each record on the `if (enableTestRoutes)` block (api-extension) or the
- * group file's `const table` so the table's `resolve`/`dispatch` bindings are
- * not scooped up.
+ * dispatch record in `api-extension.ts` AND each native group's route record
+ * in every declaration shape the helper sanctions (shared extractor:
+ * `native-route-files.test-helper.ts`).
*/
-function extractRouteTableHandlerNames(): string[] {
- return HANDLER_SOURCES.flatMap(({ text }) => {
- const routesStart = text.indexOf('\n const routes:');
- if (routesStart === -1) return [];
- const enableTestRoutes = text.indexOf('\n if (enableTestRoutes)', routesStart);
- const nativeTable = text.indexOf('\n const table', routesStart);
- const bounds = [enableTestRoutes, nativeTable].filter((i) => i !== -1);
- const slice = text.slice(routesStart, bounds.length === 0 ? text.length : Math.min(...bounds));
- return [...slice.matchAll(/:\s*(handle\w+)/g)].flatMap((m) => (m[1] ? [m[1]] : []));
- });
+function extractRouteRecordHandlerNames(): string[] {
+ return HANDLER_SOURCES.flatMap(({ text }) => extractRouteHandlerNames(text));
}
function listAllHandlers(): string[] {
@@ -124,15 +114,15 @@ function extractHandlerBody(name: string): string | null {
const searchFrom = innerIdx === -1 ? start + 1 : innerIdx + 1;
const nextFn = owner.indexOf('\n async function handle', searchFrom);
const nextConst = owner.indexOf('\n const handle', searchFrom);
- // The last handler in the file has no successor — bound at the route table
- // declaration `\n const routes:` so we don't accidentally fold the
- // onRequest extension (which itself uses `errorResponse(...)` for the
- // /api/* Origin gate) into the prior handler's slice.
- const nextRoutes = owner.indexOf('\n const routes:', searchFrom);
- // The factory module ends its handler run at the returned record instead of
- // a route table, so bound on that too or the last handler swallows it.
+ // The last handler in the file has no successor — bound at the route
+ // record declaration (any sanctioned shape) so the module tail after the
+ // handler run — the record itself and the table plumbing — is never folded
+ // into the last handler's slice.
+ const nextRoutes = HANDLER_RUN_END_NEEDLES.map((needle) => owner.indexOf(needle, searchFrom));
+ // The factory module ends its handler run at the returned record instead,
+ // so bound on that too or the last handler swallows it.
const nextReturn = owner.indexOf('\n return {', searchFrom);
- const candidates = [nextFn, nextConst, nextRoutes, nextReturn].filter((i) => i !== -1);
+ const candidates = [nextFn, nextConst, ...nextRoutes, nextReturn].filter((i) => i !== -1);
const next = candidates.length === 0 ? -1 : Math.min(...candidates);
return owner.slice(start, next === -1 ? owner.length : next);
}
@@ -249,20 +239,22 @@ describe('error envelope coverage (FR17, D36 a) — fail-on-any-occurrence', ()
test('handler discovery covers every entry in the route table (cross-check)', () => {
// Stronger anti-vacuousness guard: every `'/api/<path>': handle<X>`
- // entry in the route table at the bottom of `api-extension.ts` must
- // resolve to a handler the discovery regex finds. A novel handler
+ // entry across the route records (the legacy dispatch record and each
+ // native group's own) must resolve to a handler the discovery regex
+ // finds. A novel handler
// shape (e.g., `const handleFoo = someOtherWrapper(...)`) that the
// baseline floor above happens to clear (because deletions elsewhere
// offset the addition) would still trip this check, because the
- // route-table entry references a handler name the regex would miss.
+ // route-record entry references a handler name the regex would miss.
//
- // The route-table block is the single source of truth for which
- // handlers are HTTP-reachable; the meta-test's job is only valuable
- // if every reachable handler is scanned.
- const routeTableHandlerNames = extractRouteTableHandlerNames();
- expect(routeTableHandlerNames.length).toBeGreaterThan(0);
+ // The route records — the legacy dispatch record plus each native
+ // group's own — are the source of truth for which handlers are
+ // HTTP-reachable; the meta-test's job is only valuable if every
+ // reachable handler is scanned.
+ const routeRecordHandlerNames = extractRouteRecordHandlerNames();
+ expect(routeRecordHandlerNames.length).toBeGreaterThan(0);
const discovered = new Set(listAllHandlers());
- const missingFromDiscovery = routeTableHandlerNames.filter(
+ const missingFromDiscovery = routeRecordHandlerNames.filter(
(name): name is string => !!name && !discovered.has(name),
);
expect(missingFromDiscovery).toEqual([]);
@@ -385,8 +377,8 @@ describe('error envelope coverage (FR17, D36 a) — fail-on-any-occurrence', ()
test('zero inline { ok: false } envelopes in any handler source', () => {
// Whole-file sweep: catches inline literals outside per-handler bodies
- // (helper functions, the onRequest extension, route-table fallthroughs).
- // The per-handler scan above bounds at the `\n const routes:` declaration
+ // (helper functions, the onRequest extension, route-record fallthroughs).
+ // The per-handler scan above bounds at the route-record declaration
// and would miss anything below; this assertion is the structural
// backstop.
const matches = HANDLER_SOURCES.flatMap((h) =>
@@ -429,8 +421,8 @@ describe('error envelope coverage (FR17, D36 a) — fail-on-any-occurrence', ()
// schema-vs-server drift class is closed structurally at the wire
// boundary. Whole-file sweep mirrors the `{ ok: false/true }` ratchets
// above: catches inline literals outside per-handler bodies (helper
- // functions, the route table, the onRequest extension). The per-handler
- // scan above bounds at the `\n const routes:` declaration and would
+ // functions, the route records, the onRequest extension). The per-handler
+ // scan above bounds at the route-record declaration and would
// miss anything below; this assertion is the structural backstop.
//
// The inline `json()` helper itself was deleted — every
diff --git a/packages/app/tests/meta/native-route-unit-reachability.test.ts b/packages/app/tests/meta/native-route-unit-reachability.test.ts
index a404486f4..008e7674c 100644
--- a/packages/app/tests/meta/native-route-unit-reachability.test.ts
+++ b/packages/app/tests/meta/native-route-unit-reachability.test.ts
@@ -3,44 +3,72 @@
*
* The Wave 2 strangler moves route groups out of the legacy dispatch into
* `http/*-routes.ts` factories mounted natively. In the unit tier, ported
- * routes stay reachable from `ext.onRequest` ONLY through
- * `api-extension.test-helper.ts`, whose wrapper dispatches the native groups
- * before falling through to the legacy hook. A test that imports
- * `createApiExtension` from `./api-extension.ts` directly and requests a
- * ported path exercises the pipeline's `/api/*` 404 fallback instead of the
- * handler — the suite keeps passing while silently asserting nothing about
- * the route it names. With each group lift this failure mode gets quieter
- * and larger, so it is closed mechanically here: base-factory tests may not
- * name natively-owned paths. Fix by importing from the test-helper (routes
- * reach the real handler) or by targeting a deliberately unregistered path
- * with a comment saying so.
+ * routes are reachable only through a seam that dispatches the native groups
+ * ahead of the legacy hook: `api-extension.test-helper.ts`'s wrapper, or a
+ * `createServer` harness that runs `nativeApi.dispatch` before its own
+ * `onRequest` loop. A test that drives `/api/*` through a legacy-only seam —
+ * the BASE `createApiExtension` import, or a hand-rolled `createServer`
+ * HTTP/`onRequest` harness — and requests a ported path exercises the
+ * pipeline's `/api/*` 404 fallback instead of the handler; the suite keeps
+ * passing while silently asserting nothing about the route it names. With
+ * each group lift this failure mode gets quieter and larger, so it is closed
+ * mechanically here for BOTH seams. Fix a base-factory offender by importing
+ * from the test-helper, a `createServer` harness by dispatching
+ * `nativeApi.dispatch` first, or target a legacy-owned path.
+ *
+ * This file also hosts two contracts for the guard family itself: the
+ * route-record extraction floor for the three registry cross-check guards
+ * (they each carried a private copy; one copy here keeps the assertion
+ * single-sourced in the directory whose tests need no coverage tags), and
+ * the discovery/mount set equality that keeps `listNativeRouteFiles` — the
+ * discovered slice of the guards' scan surfaces (several also hand-list
+ * extra sources such as `api-extension.ts`) — in lockstep with the factory
+ * mounts in `api-extension.ts`.
*/
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, test } from 'vitest';
+import {
+ extractRouteHandlerNames,
+ listNativeRouteFiles,
+} from '../native-route-files.test-helper.ts';
const SERVER_SRC_ROOT = join(import.meta.dirname, '../../../server/src');
-const HTTP_ROUTES_ROOT = join(SERVER_SRC_ROOT, 'http');
-/** Every `'/api/...'` key in any native group's routes record or paths list. */
-function collectNativePaths(): { exact: Set<string>; prefixes: string[] } {
+/** Every `'/api/...'` key in any native group's routes record or paths list, per file. */
+function collectNativePaths(): {
+ exact: Set<string>;
+ prefixes: string[];
+ perFile: Map<string, number>;
+} {
const exact = new Set<string>();
const prefixes: string[] = [];
- for (const entry of readdirSync(HTTP_ROUTES_ROOT)) {
- if (!entry.endsWith('-routes.ts') || entry.endsWith('.test.ts')) continue;
- const source = readFileSync(join(HTTP_ROUTES_ROOT, entry), 'utf8');
+ const perFile = new Map<string, number>();
+ for (const entry of listNativeRouteFiles(SERVER_SRC_ROOT)) {
+ const source = readFileSync(join(SERVER_SRC_ROOT, entry), 'utf8');
+ let count = 0;
for (const match of source.matchAll(/'(\/api\/[^']+)'/g)) {
const path = match[1] ?? '';
+ count += 1;
if (path.endsWith('/*')) {
// A wildcard claims its namespace: '/api/tags/*' owns '/api/tags/…'.
prefixes.push(path.slice(0, -1));
+ } else if (path.endsWith('/')) {
+ // A `createApiRouteGroup` dynamic-leg `prefix:` ('/api/tags/') — the
+ // wildcard path is built at runtime, so the prefix literal is the
+ // namespace claim the source scan sees.
+ prefixes.push(path);
+ } else if (path.includes('/:')) {
+ // A dynamic-leg `template:` ('/api/tags/:name') — the namespace is
+ // already claimed by its prefix; the template is not a requestable path.
} else {
exact.add(path);
}
}
+ perFile.set(entry, count);
}
- return { exact, prefixes };
+ return { exact, prefixes, perFile };
}
function listServerTestFiles(): string[] {
@@ -64,33 +92,132 @@ function importsBaseFactory(source: string): boolean {
);
}
+/**
+ * True when the file drives `/api/*` through a seam that skips the native
+ * mount. Two construction paths produce that seam: the BASE
+ * `createApiExtension` import, and a `createServer` harness that hand-rolls
+ * its own HTTP/`onRequest` loop. A `createServer` harness is exempt once it
+ * dispatches `nativeApi.dispatch` first (the production order) — the
+ * property being protected is "ported paths reach their real handler", not
+ * which import the file happens to use.
+ */
+function usesLegacyOnlySeam(source: string): boolean {
+ if (importsBaseFactory(source)) return true;
+ const importsServerFactory =
+ /import\s*\{[^}]*\bcreateServer\b[^}]*\}\s*from\s*'[^']*\/server-factory\.ts'/.test(source);
+ // The exemption is what makes a `createServer` harness production-shaped;
+ // note it is FILE-scoped — one native-first driver exempts every driver in
+ // the file.
+ return importsServerFactory && !source.includes('nativeApi.dispatch');
+}
+
describe('native-route unit-tier reachability', () => {
- test('anti-vacuousness: the native path inventory is non-trivial', () => {
- const { exact, prefixes } = collectNativePaths();
- // Three merged groups own 18 exact paths + the tags wildcard; a scan
- // regression that returns near-zero would mute the guard silently.
- expect(exact.size).toBeGreaterThanOrEqual(15);
- expect(prefixes.length).toBeGreaterThanOrEqual(1);
+ test('anti-vacuousness: every route file contributes paths and the inventory is non-trivial', () => {
+ const { exact, prefixes, perFile } = collectNativePaths();
+ // Structural, so the floor scales with the inventory it protects: a scan
+ // regression that silently drops a whole group's paths reddens here, not
+ // just a near-zero collapse. Nine merged groups own 51 exact paths + 2
+ // dynamic namespaces at the time of writing; the two numeric floors are
+ // group-sized backstops (they drift as groups land), and file-set
+ // coverage is owned by the mount equality below rather than a
+ // hand-recalibrated count.
+ for (const [file, count] of perFile) {
+ expect(count, `${file} contributes no '/api/...' paths — scan regression?`).toBeGreaterThan(
+ 0,
+ );
+ }
+ expect(exact.size).toBeGreaterThanOrEqual(45);
+ expect(new Set(prefixes).size).toBeGreaterThanOrEqual(2);
});
- test('no base-factory test names a natively-owned path', () => {
+ test('the discovered route files and the extension mounts are the same set', () => {
+ // Set-shaped in BOTH directions, so no integer needs recalibrating as
+ // groups come and go. Discovered-not-mounted: usually a dead file (or a
+ // group mounted somewhere other than `api-extension.ts`, the only file
+ // read here). Mounted-not-discovered: usually a group whose filename
+ // left the `-routes.ts` glob, which silently drops it from every guard
+ // keyed on `listNativeRouteFiles` — the per-file floors above cannot see
+ // that, because they only visit what discovery returned. The diagnoses
+ // are not exclusive: the `http/<kebab>-routes.ts` ⇒ `create<Pascal>Routes`
+ // naming convention is what joins the two sides, so a one-sided rename
+ // of a live group trips BOTH directions and the fix is the rename.
+ const ext = readFileSync(join(SERVER_SRC_ROOT, 'api-extension.ts'), 'utf8');
+ // `=\s*` requires an assignment site, so a bare prose mention of a
+ // factory name cannot register as a mount (a commented-out assignment
+ // still would; the import lines never match because they carry no call
+ // paren).
+ const mounted = [...ext.matchAll(/=\s*create(\w+)Routes\(/g)].flatMap((m) =>
+ m[1] ? [m[1]] : [],
+ );
+ const discovered = listNativeRouteFiles(SERVER_SRC_ROOT).map((file) =>
+ file
+ .replace('http/', '')
+ .replace('-routes.ts', '')
+ .split('-')
+ .map((seg) => (seg[0] ?? '').toUpperCase() + seg.slice(1))
+ .join(''),
+ );
+ expect(
+ [...new Set(mounted)].sort(),
+ 'mounted (received) vs discovered (expected) name sets diverged — map the diff back to a file/factory via the divergence taxonomy in the comment above this assertion',
+ ).toEqual([...new Set(discovered)].sort());
+ });
+
+ test('no legacy-only test seam names a natively-owned path', () => {
const { exact, prefixes } = collectNativePaths();
const offenders: string[] = [];
for (const file of listServerTestFiles()) {
const source = readFileSync(file, 'utf8');
- if (!importsBaseFactory(source)) continue;
- for (const match of source.matchAll(/'(\/api\/[^'?]+)/g)) {
+ if (!usesLegacyOnlySeam(source)) continue;
+ // Bind the remedy to the seam that fired: a base-factory import swaps
+ // to the test-helper; a hand-rolled `createServer` harness dispatches
+ // the native groups first.
+ const remedy = importsBaseFactory(source)
+ ? "Import from './api-extension.test-helper.ts' instead"
+ : 'Dispatch `nativeApi.dispatch` ahead of the legacy onRequest';
+ // Both quote styles: template literals are how query-carrying requests
+ // are usually built (`/api/search?query=${q}`), and one slipped through
+ // the single-quote-only scan.
+ for (const match of source.matchAll(/['`](\/api\/[^'`?$]+)/g)) {
const path = match[1] ?? '';
const owned = exact.has(path) || prefixes.some((prefix) => path.startsWith(prefix));
if (!owned) continue;
- const line = source.slice(0, match.index ?? 0).split('\n').length;
+ const upToMatch = source.slice(0, match.index ?? 0);
+ // Comment prose (docblocks narrating a trigger) is not a request —
+ // only literals in live code can produce the vacuous 404.
+ const lineText = upToMatch.slice(upToMatch.lastIndexOf('\n') + 1).trimStart();
+ if (lineText.startsWith('*') || lineText.startsWith('//') || lineText.startsWith('/*')) {
+ continue;
+ }
+ const line = upToMatch.split('\n').length;
offenders.push(
- `${file}:${line} — requests natively-owned '${path}' through the BASE createApiExtension ` +
- '(the legacy table 404s it; the handler never runs). Import from ' +
- "'./api-extension.test-helper.ts' instead, or target a legacy-owned path.",
+ `${file}:${line} — requests natively-owned '${path}' through a legacy-only seam ` +
+ `(the legacy table 404s it; the handler never runs). ${remedy}, ` +
+ 'or target a legacy-owned path.',
);
}
}
expect(offenders).toEqual([]);
});
});
+
+describe('route-record extraction floor', () => {
+ test('every route-record source contributes handler names to the registry guards', () => {
+ // The registry cross-checks (error-envelope / attribution-sweep /
+ // conflict-gate) extract `'/api/…': handleX` bindings per source; a
+ // source contributing zero names means the extractor went blind to its
+ // record shape and the guards shrink silently. `api-extension.ts` is the
+ // majority contributor while the legacy record drains — when a group lift
+ // finally empties it, remove it from this list in the same PR.
+ // `skills-sh-handlers.ts` is scanned by the guards but owns no record of
+ // its own (its record lives in `skills-sh-routes.ts`), so it is not
+ // floored here.
+ for (const file of ['api-extension.ts', ...listNativeRouteFiles(SERVER_SRC_ROOT)]) {
+ const names = extractRouteHandlerNames(readFileSync(join(SERVER_SRC_ROOT, file), 'utf8'));
+ expect(
+ names.length,
+ `${file} contributes no route-record handler names — extractor blind to its record shape?`,
+ ).toBeGreaterThan(0);
+ }
+ });
+});
diff --git a/packages/app/tests/native-route-files.test-helper.ts b/packages/app/tests/native-route-files.test-helper.ts
new file mode 100644
index 000000000..ee5bd2f10
--- /dev/null
+++ b/packages/app/tests/native-route-files.test-helper.ts
@@ -0,0 +1,48 @@
+import { readdirSync } from 'node:fs';
+import { join } from 'node:path';
+
+/**
+ * Handler-run END boundaries for the guards' per-handler body extraction:
+ * whichever route-record declaration shape follows the last handler in a
+ * source (an annotated record — `api-extension.ts` and the pre-helper
+ * factories — a `satisfies` literal, or the record passed inline to
+ * `createApiRouteGroup(...)`). These needles are
+ * indentation-sensitive by contract — they must match the two-space
+ * module-function body layout of `api-extension.ts` and the `http/*-routes.ts`
+ * factories, and exist ONLY for that boundary role; route-record NAME
+ * extraction matches the bindings directly and needs no anchors.
+ */
+export const HANDLER_RUN_END_NEEDLES = [
+ '\n const routes:',
+ '\n const routes =',
+ '\n return createApiRouteGroup(',
+] as const;
+
+/**
+ * Every `'/api/…': handle<X>` binding in a source, whatever the record's
+ * declaration shape or position — the quoted path key is what distinguishes a
+ * route-record binding from a `methodRouter` verb map (`GET: handleFoo`),
+ * so no slice anchors are needed. Deliberately out of scope — closure- or
+ * assignment-bound, never record-bound, so they must be categorized in the
+ * guards by hand: handlers reached through a `dynamic.dispatch` leg or a
+ * hand-rolled `resolve` closure, and bracket assignments like the
+ * `enableTestRoutes` block's `routes['/api/test-reset'] = ...`.
+ */
+export function extractRouteHandlerNames(text: string): string[] {
+ return [...text.matchAll(/'\/api\/[^']*':\s*(handle\w+)/g)].flatMap((m) => (m[1] ? [m[1]] : []));
+}
+
+/**
+ * Every native route-group factory under `server/src/http`, as `http/<file>`
+ * paths relative to `server/src`. The single discovery point for the guards
+ * that must scan ALL groups (error-envelope, attribution-sweep, conflict-gate,
+ * native-route-unit-reachability): a new `http/*-routes.ts` group joins every
+ * scan without a per-PR list edit, so a forgotten edit cannot silently shrink
+ * a guard's coverage.
+ */
+export function listNativeRouteFiles(serverSrcRoot: string): string[] {
+ return readdirSync(join(serverSrcRoot, 'http'))
+ .filter((entry) => entry.endsWith('-routes.ts') && !entry.endsWith('.test.ts'))
+ .sort()
+ .map((entry) => `http/${entry}`);
+}
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index d5f9a2493..bbf373bc8 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -100,8 +100,6 @@ import {
isSkillInstallTarget,
LEGACY_SKILL_STORE_ROOT,
LINKABLE_ASSET_EXTENSIONS,
- LinkPreviewRequestSchema,
- LinkPreviewResponseSchema,
type LinksValidationSetting,
LintConfigResponseSchema,
type LinterConfig,
@@ -146,17 +144,8 @@ import {
RollbackRequestSchema,
RollbackSuccessSchema,
readFmMap,
- SavedThemeDeleteSuccessSchema,
- SavedThemeSaveRequestSchema,
- SavedThemeSaveSuccessSchema,
- SavedThemesListSuccessSchema,
- SavedThemeUpdateRequestSchema,
- SavedThemeUpdateSuccessSchema,
SaveVersionRequestSchema,
SaveVersionSuccessSchema,
- SearchRequestSchema,
- type SearchSource,
- SearchSuccessSchema,
SeedApplyRequestSchema,
SeedApplySuccessSchema,
SeedInstallPackSkillRequestSchema,
@@ -209,9 +198,6 @@ import {
SkillsListSuccessSchema,
SkillsReimportBulkRequestSchema,
SkillsReimportBulkSuccessSchema,
- SkillTargetsGetSuccessSchema,
- SkillTargetsPutRequestSchema,
- SkillTargetsPutSuccessSchema,
SkillTrackInGitRequestSchema,
SkillTrackInGitSuccessSchema,
SkillUninstallRequestSchema,
@@ -251,9 +237,6 @@ import {
USER_SKILL_EDITOR_IDS,
unwrapFrontmatterFences,
type ValidationDiagnostic,
- type WorkspaceSearchIntent,
- type WorkspaceSearchRanking,
- type WorkspaceSearchScope,
} from '@inkeep/open-knowledge-core';
import {
formatRenameSubject,
@@ -287,7 +270,6 @@ import {
} from '@inkeep/open-knowledge-core/skills-catalog';
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
import { type Entry, fromBuffer as yauzlFromBuffer, type ZipFile } from 'yauzl';
-import { z } from 'zod';
import {
type AcpHarnessAvailability,
createAcpHarnessAvailabilityProbe,
@@ -398,8 +380,6 @@ import {
parseFrontmatterMetadata,
} from './page-identity.ts';
import type { RecentlyRemovedDocs } from './recently-removed-docs.ts';
-import { scanSavedThemes } from './saved-themes-store.ts';
-import { deleteSavedTheme, saveSavedTheme, updateSavedTheme } from './saved-themes-write.ts';
import {
buildGitHubBlobUrl,
buildGitHubTreeUrl,
@@ -573,7 +553,7 @@ import {
errorResponse,
type HttpErrorStatus,
} from './http/error-response.ts';
-import { errnoCode, parseQuery } from './http/handler-utils.ts';
+import { errnoCode } from './http/handler-utils.ts';
import { createHistoryRoutes } from './http/history-routes.ts';
import { assertSingleRouterOwnership, type NativeApiHandle } from './http/http-app.ts';
import { createLinkGraphRoutes } from './http/link-graph-routes.ts';
@@ -584,11 +564,14 @@ import { createMetricsRoutes } from './http/metrics-routes.ts';
import { getRequestId } from './http/request-id.ts';
import { validateBody, withValidation } from './http/request-validation.ts';
import { createSkillsReadRoutes } from './http/skills-read-routes.ts';
+import { createSkillsShRoutes } from './http/skills-sh-routes.ts';
import { successResponse } from './http/success-response.ts';
+import {
+ createWorkspaceToolsRoutes,
+ type GeneratedIndexSettingsStatus,
+} from './http/workspace-tools-routes.ts';
import {
aliasedSourceRoots,
- isActivatedSkillRoot,
- knownSkillRootsFor,
removableSkillOccurrenceDirs,
resolveDefaultSkillHomeRel,
resolveGlobalNativeSkillDir,
@@ -604,10 +587,7 @@ import {
isPeerAdmitted,
} from './ingress-policy.ts';
import { initContent } from './init-project.ts';
-import { guardedFetch } from './link-preview/guarded-fetch.ts';
-import { buildLinkPreviewMetadata, type GuardedFetch } from './link-preview/metadata.ts';
-import { LinkPreviewCache, type LinkPreviewOutcome } from './link-preview/preview-cache.ts';
-import { classifyLinkPreviewRequest } from './link-preview/request-gate.ts';
+import type { GuardedFetch } from './link-preview/metadata.ts';
import {
checkLocalOpSecurity as checkLocalOpSecurityBase,
createConcurrencyGuard,
@@ -685,25 +665,15 @@ import {
type WriterIdentity,
} from './shadow-repo.ts';
import { shouldResetAmbientCredentials } from './share/git-context.ts';
-import {
- linkEditorSkillFolder,
- previewEditorFolderLink,
- scanSkillFolderStates,
- unlinkEditorSkillFolder,
-} from './skill-folder-links.ts';
import { isDisallowedGitSpec, rejectDisallowedGitSpec } from './skill-git-spec-guard.ts';
import { resolveSkillInstallReportSettings } from './skill-install-report-config.ts';
import {
clearSkillPlacements,
- readFolderExpectations,
readSkillInstallModeRaw,
readSkillPlacements,
- recordFolderExpectation,
- recordKnownSkillRoot,
} from './skill-placements.ts';
import { restoreSkillVersion } from './skill-restore.ts';
import { mutateSkillsLock, readSkillsLockFile } from './skills-lock-store.ts';
-import { createSkillsShHandlers } from './skills-sh-handlers.ts';
import { reportSkillInstall } from './skills-sh-install-report.ts';
import type { SyncEngine } from './sync-engine.ts';
import { getMeter, withSpan, withSpanSync } from './telemetry.ts';
@@ -2377,20 +2347,6 @@ async function renameTrackedPathInGit(
});
}
-const GeneratedIndexSettingsStatusSchema = z.object({
- enabled: z.boolean(),
- active: z.boolean(),
- git: z.object({
- state: z.enum(['not-applicable', 'ready', 'missing', 'conflict', 'unavailable']),
- ownership: z.enum(['open-knowledge', 'existing']).optional(),
- }),
- applied: z.boolean().optional(),
- reason: z.enum(['git-conflict', 'git-unavailable', 'config-write']).optional(),
-});
-const GeneratedIndexSettingsRequestSchema = z.object({ enabled: z.boolean() }).strict();
-
-export type GeneratedIndexSettingsStatus = z.infer<typeof GeneratedIndexSettingsStatusSchema>;
-
export interface ApiExtensionOptions {
/**
* The boot-built ingress policy. Drives the browser-Origin allowlists (the
@@ -12032,246 +11988,6 @@ export function createApiExtension(
{ handler: 'folder-config' },
);
- // ── Saved themes (`/api/saved-themes` list, `/api/saved-theme` mutations) ──
- // The store is a user-global folder of scheme files the renderer can't reach;
- // save/delete/list run here. Discovery is by scan (no live watcher in v1), and
- // the home is the same `homeDirOverride` seam the skills store uses so tests
- // isolate against a tempdir without touching `os.homedir()`.
-
- const handleSavedThemesList = withValidation(
- EmptyRequestSchema,
- async (_req, res) => {
- try {
- const { entries, truncated } = scanSavedThemes({ homedirOverride: homeDirOverride });
- // Entries carry their own `ok` discriminator: usable themes ship their
- // palette for the picker preview; unusable ones ship a warning `code` so
- // a file the user placed is listed, never silently missing.
- successResponse(
- res,
- 200,
- SavedThemesListSuccessSchema,
- { themes: entries, truncated },
- { handler: 'saved-themes-list' },
- );
- } catch (e) {
- errorResponse(
- res,
- 500,
- 'urn:ok:error:internal-server-error',
- 'Failed to list saved themes.',
- {
- handler: 'saved-themes-list',
- cause: e,
- },
- );
- }
- },
- { handler: 'saved-themes-list', method: 'GET', skipBodyParse: true },
- );
-
- const handleSavedThemeSave = withValidation(
- SavedThemeSaveRequestSchema,
- async (_req, res, body) => {
- try {
- const result = await saveSavedTheme({
- name: body.name,
- stem: body.stem,
- scheme: body.scheme,
- extension: body.extension,
- homedirOverride: homeDirOverride,
- lockTimeoutMs: savedThemeLockTimeoutMs,
- });
- if (!result.ok) {
- if (result.code === 'lock-timeout') {
- errorResponse(
- res,
- 503,
- 'urn:ok:error:concurrent-operation',
- 'Saved themes are temporarily busy.',
- {
- handler: 'saved-theme-save',
- detail: result.code,
- extraHeaders: { 'Retry-After': '5' },
- },
- );
- return;
- }
- if (result.code === 'name-taken') {
- // Refuse-and-prompt: a collision never overwrites prior work.
- errorResponse(
- res,
- 409,
- 'urn:ok:error:theme-name-taken',
- 'A saved theme with that name already exists.',
- { handler: 'saved-theme-save', detail: body.name },
- );
- return;
- }
- // Restore stems remain strict; a new human-facing name only fails when
- // it is empty. The specific cause rides `detail` so the save form can
- // localize the reason.
- errorResponse(
- res,
- 400,
- 'urn:ok:error:theme-name-invalid',
- 'That name cannot be used as a theme id.',
- { handler: 'saved-theme-save', detail: result.code },
- );
- return;
- }
- successResponse(
- res,
- 201,
- SavedThemeSaveSuccessSchema,
- { id: result.id, filename: result.filename },
- { handler: 'saved-theme-save' },
- );
- } catch (e) {
- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to save theme.', {
- handler: 'saved-theme-save',
- cause: e,
- });
- }
- },
- { handler: 'saved-theme-save', method: 'POST' },
- );
-
- const handleSavedThemeDelete = withValidation(
- EmptyRequestSchema,
- async (req, res) => {
- try {
- const id = parseQuery(req).get('id') ?? '';
- if (id === '') {
- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Missing theme id.', {
- handler: 'saved-theme-delete',
- });
- return;
- }
- const result = await deleteSavedTheme({
- id,
- homedirOverride: homeDirOverride,
- lockTimeoutMs: savedThemeLockTimeoutMs,
- });
- if (!result.ok) {
- if (result.code === 'lock-timeout') {
- errorResponse(
- res,
- 503,
- 'urn:ok:error:concurrent-operation',
- 'Saved themes are temporarily busy.',
- {
- handler: 'saved-theme-delete',
- detail: result.code,
- extraHeaders: { 'Retry-After': '5' },
- },
- );
- return;
- }
- const conflict = result.code !== 'invalid-id';
- errorResponse(
- res,
- conflict ? 409 : 400,
- 'urn:ok:error:invalid-request',
- 'Cannot delete saved theme.',
- {
- handler: 'saved-theme-delete',
- detail: result.code,
- },
- );
- return;
- }
- // Deleting an id that names no file is a benign no-op (`existed: false`),
- // and deleting one currently assigned to a mode slot is allowed — the
- // config's read-time fallback makes the dangling reference harmless.
- successResponse(
- res,
- 200,
- SavedThemeDeleteSuccessSchema,
- result.existed
- ? { existed: true, filename: result.filename, scheme: result.scheme }
- : { existed: false },
- { handler: 'saved-theme-delete' },
- );
- } catch (e) {
- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to delete theme.', {
- handler: 'saved-theme-delete',
- cause: e,
- });
- }
- },
- { handler: 'saved-theme-delete', method: 'DELETE', skipBodyParse: true },
- );
-
- const handleSavedThemeUpdate = withValidation(
- SavedThemeUpdateRequestSchema,
- async (_req, res, body) => {
- try {
- const result = await updateSavedTheme({
- id: body.id,
- scheme: body.scheme,
- homedirOverride: homeDirOverride,
- lockTimeoutMs: savedThemeLockTimeoutMs,
- });
- if (!result.ok) {
- if (result.code === 'lock-timeout') {
- errorResponse(
- res,
- 503,
- 'urn:ok:error:concurrent-operation',
- 'Saved themes are temporarily busy.',
- {
- handler: 'saved-theme-update',
- detail: result.code,
- extraHeaders: { 'Retry-After': '5' },
- },
- );
- return;
- }
- if (result.code === 'not-found') {
- errorResponse(res, 404, 'urn:ok:error:not-found', 'Saved theme not found.', {
- handler: 'saved-theme-update',
- });
- return;
- }
- if (result.code === 'ambiguous-id' || result.code === 'unsafe-target') {
- const message =
- result.code === 'ambiguous-id'
- ? 'Multiple saved theme files claim that id.'
- : 'The saved theme id conflicts with a file that cannot be safely updated.';
- errorResponse(res, 409, 'urn:ok:error:invalid-request', message, {
- handler: 'saved-theme-update',
- detail: result.code,
- });
- return;
- }
- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Not a saved theme id.', {
- handler: 'saved-theme-update',
- detail: result.code,
- });
- return;
- }
- successResponse(
- res,
- 200,
- SavedThemeUpdateSuccessSchema,
- { id: result.id, filename: result.filename },
- { handler: 'saved-theme-update' },
- );
- } catch (e) {
- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to update theme.', {
- handler: 'saved-theme-update',
- cause: e,
- });
- }
- },
- { handler: 'saved-theme-update', method: 'PUT' },
- );
-
- const handleSavedTheme = methodRouter(
- { POST: handleSavedThemeSave, PUT: handleSavedThemeUpdate, DELETE: handleSavedThemeDelete },
- { handler: 'saved-theme' },
- );
-
/**
* Conflict-aware refusal helper for the template handlers. A template is a
* content doc now (`<folder>/.ok/templates/<name>`), so its live Y.Doc carries
@@ -13824,10 +13540,6 @@ export function createApiExtension(
return templateContentDocName(folderRel, name);
}
- function parseSearchRanking(value: unknown): WorkspaceSearchRanking | undefined {
- return value === 'navigation' || value === 'relevance' ? value : undefined;
- }
-
/**
* POSIX store-relative path for a skill file. Project skills are reported
* relative to `contentDir` (→ `.ok/skills/<name>/SKILL.md`); global skills
@@ -18663,259 +18375,6 @@ export function createApiExtension(
{ handler: 'skill-uninstall', method: 'POST' },
);
- const handleSkillTargetsGet = withValidation(
- EmptyRequestSchema,
- async (_req, res) => {
- try {
- // Store retirement: the committed `.ok/skill-targets.json` set is dead —
- // targets are DETECTED from the project's configured editors, and
- // per-skill reach lives in each skill's install menu.
- const targets = resolveSkillTargets(projectDir ?? '');
- // Folder-link receipt vs disk: a recorded expectation that no longer
- // matches the observed state is DRIFT — passive disclosure only (the
- // "changed outside" chip); the next explicit verb wins + re-records.
- const withDrift = (
- base: string,
- f: ReturnType<typeof scanSkillFolderStates>[number],
- ): { drift?: true; expected?: string } => {
- const exp = readFolderExpectations(base)[f.root];
- if (exp === undefined) return {};
- const matches =
- exp.expect === 'link'
- ? f.state === 'linked' && f.target === exp.target
- : f.state === 'own';
- if (matches) return {};
- return {
- drift: true,
- expected: exp.expect === 'link' ? `link → ${exp.target}` : 'own folder',
- };
- };
- successResponse(
- res,
- 200,
- SkillTargetsGetSuccessSchema,
- {
- targets,
- configured: false,
- // Only folders OK may actually write to on this machine. A row here
- // is a destination — the Folders surface links and unlinks it — so a
- // root under a dotdir that does not exist is an offer to create that
- // dotdir for a tool the user never installed. Custom roots are always
- // kept; see `isActivatedSkillRoot`.
- folders: [
- ...(projectDir
- ? scanSkillFolderStates(contentDir, knownSkillRootsFor(contentDir, 'project'))
- .filter((f) => isActivatedSkillRoot(contentDir, 'project', f.root))
- .map((f) => ({
- ...f,
- scope: 'project' as const,
- ...withDrift(contentDir, f),
- }))
- : []),
- ...scanSkillFolderStates(skillsHome, knownSkillRootsFor(skillsHome, 'global'))
- .filter((f) => isActivatedSkillRoot(skillsHome, 'global', f.root))
- .map((f) => ({
- ...f,
- scope: 'global' as const,
- ...withDrift(skillsHome, f),
- })),
- ],
- },
- { 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', method: 'GET', skipBodyParse: true },
- );
-
- const handleSkillTargetsPut = withValidation(
- SkillTargetsPutRequestSchema,
- async (_req, res, body) => {
- try {
- {
- const fa = body.folderAction;
- const base = fa.scope === 'project' ? contentDir : skillsHome;
- if (fa.scope === 'project' && !projectDir) {
- errorResponse(
- res,
- 400,
- 'urn:ok:error:invalid-request',
- 'Cannot manage skill folders — no project root is resolved for this server.',
- { handler: 'skill-targets-put', detail: 'NO_PROJECT_ROOT' },
- );
- return;
- }
- // DECLARE a new custom root (rows/link-targets from declaration,
- // not first placement). Shape-validated only — it's a declaration,
- // not a write; the folder stays absent until something lands there.
- if (fa.action === 'add-root') {
- const raw = fa.root.replace(/\\/g, '/');
- const rel = raw.replace(/\/+$/g, '');
- const segs = rel.split('/').filter((seg) => seg !== '' && seg !== '.');
- if (
- rel === '' ||
- rel.startsWith('/') ||
- rel.startsWith('~') ||
- /^[A-Za-z]:/.test(rel) ||
- rel.includes('\x00') ||
- segs.length === 0 ||
- segs.some((seg) => seg === '..')
- ) {
- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid folder path.', {
- handler: 'skill-targets-put',
- detail: fa.root,
- });
- return;
- }
- await recordKnownSkillRoot(base, segs.join('/'));
- signalChannel?.('files');
- successResponse(
- res,
- 200,
- SkillTargetsPutSuccessSchema,
- {
- targets: resolveSkillTargets(projectDir ?? ''),
- reprojected: [],
- bundleHosts: [],
- removedFrom: [],
- },
- { handler: 'skill-targets-put' },
- );
- return;
- }
- // Folder verbs operate on KNOWN roots only (standard host roots +
- // ledger-known custom roots) — arbitrary paths never reach the
- // link/unlink primitives. The link target is an EXPLICIT user pick;
- // no root is ever assumed.
- const knownRoots = new Set(
- knownSkillRootsFor(base, fa.scope)
- .map((r) => r.root)
- .filter((r) => !r.startsWith('/') && !r.split('/').includes('..')),
- );
- const target = fa.action === 'link' ? (fa.target ?? '') : fa.root;
- if (
- !knownRoots.has(fa.root) ||
- (fa.action === 'link' && (!knownRoots.has(target) || fa.root === target))
- ) {
- errorResponse(
- res,
- 400,
- 'urn:ok:error:invalid-request',
- 'Folder and target must be distinct standard skills roots.',
- { handler: 'skill-targets-put', detail: `${fa.root} -> ${target}` },
- );
- return;
- }
- // PREVIEW: classify the merge and return it, writing nothing — the
- // Folders surface discloses what a link moves and deletes before it
- // asks for it. No receipt, no change signal: nothing changed.
- if (fa.action === 'link' && fa.preview) {
- const p = previewEditorFolderLink({
- base,
- folderRel: fa.root,
- targetRootRel: target,
- });
- const plan = p.kind === 'plan' ? p.plan : null;
- successResponse(
- res,
- 200,
- SkillTargetsPutSuccessSchema,
- {
- targets: resolveSkillTargets(projectDir ?? ''),
- reprojected: [],
- bundleHosts: [],
- removedFrom: [],
- preview: {
- moves: plan
- ? [...plan.linkedBundlesToMove.map(({ name }) => name), ...plan.toMove]
- : [],
- drops: plan?.toDrop ?? [],
- removes: plan?.removes ?? [],
- replaces: plan?.liveDestLinks ?? [],
- conflicts: p.kind === 'conflicts' ? p.conflicts : [],
- strays: p.kind === 'stray-entries' ? p.strays : [],
- },
- },
- { handler: 'skill-targets-put' },
- );
- return;
- }
- const result =
- fa.action === 'link'
- ? linkEditorSkillFolder({ base, folderRel: fa.root, targetRootRel: target })
- : unlinkEditorSkillFolder({
- base,
- folderRel: fa.root,
- ...(fa.exclude !== undefined ? { exclude: fa.exclude } : {}),
- });
- if (!result.ok) {
- errorResponse(
- res,
- 409,
- 'urn:ok:error:invalid-request',
- result.reason === 'conflicts'
- ? `Cannot link — differing skills exist in both folders: ${(result.conflicts ?? []).join(', ')}. Resolve them first.`
- : result.reason === 'stray-entries'
- ? `Cannot link — the folder holds non-skill entries: ${(result.strays ?? []).join(', ')}.`
- : result.reason === 'partial-move'
- ? `The merge stopped partway (${(result.moved ?? []).length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${result.error ?? ''})`
- : result.reason === 'not-linked'
- ? 'That folder is not a symlink — nothing to unlink.'
- : 'That folder cannot be linked (it is already a link or the same directory).',
- { handler: 'skill-targets-put', detail: result.reason },
- );
- return;
- }
- // RECEIPT: record the expected folder form so an external rewrite
- // (symlink deleted, re-pointed, or re-materialized) renders a
- // passive "changed outside" chip. The next explicit verb wins.
- await recordFolderExpectation(
- base,
- fa.root,
- fa.action === 'link' ? { expect: 'link', target } : { expect: 'own' },
- );
- signalChannel?.('files');
- successResponse(
- res,
- 200,
- SkillTargetsPutSuccessSchema,
- {
- targets: resolveSkillTargets(projectDir ?? ''),
- reprojected: [],
- bundleHosts: [],
- removedFrom: [],
- folder: { moved: result.moved, dropped: result.dropped, linked: result.linked },
- },
- { handler: 'skill-targets-put' },
- );
- return;
- }
- } 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', 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.
@@ -19626,35 +19085,6 @@ export function createApiExtension(
{ handler: 'skill-revert', method: 'POST' },
);
- function parseSearchIntent(value: unknown): WorkspaceSearchIntent {
- if (value === 'autocomplete' || value === 'full_text' || value === 'omnibar') return value;
- return 'omnibar';
- }
-
- function parseSearchScopes(value: unknown): WorkspaceSearchScope[] | undefined {
- const rawScopes =
- typeof value === 'string' ? value.split(',') : Array.isArray(value) ? value : undefined;
- if (!rawScopes) return undefined;
- const scopes = rawScopes.filter(
- (scope): scope is WorkspaceSearchScope =>
- scope === 'page' || scope === 'folder' || scope === 'content' || scope === 'file',
- );
- return scopes.length > 0 ? scopes : undefined;
- }
-
- /** Parse the opt-in `semantic` param from a query string / JSON body value. */
- function parseSemanticParam(value: unknown): boolean | undefined {
- if (typeof value === 'boolean') return value;
- if (value === 'true') return true;
- if (value === 'false') return false;
- return undefined;
- }
-
- /** Resolve the bounded `source` telemetry label; unknown / absent → `http`. */
- function parseSearchSource(value: unknown): SearchSource {
- return value === 'omnibar' || value === 'mcp' || value === 'http' ? value : 'http';
- }
-
const searchService = createSearchService({
contentDir,
projectDir,
@@ -19669,89 +19099,6 @@ export function createApiExtension(
});
searchService.prewarm();
- const handleSearchGet = withValidation(
- EmptyRequestSchema,
- 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 searchService.buildSearchResponse({
- query,
- intent,
- ranking,
- scopes,
- limit: limitNum,
- semanticParam,
- source,
- });
- successResponse(res, 200, SearchSuccessSchema, body, { handler: 'search-get' });
- },
- { handler: 'search-get', title: 'Failed to search workspace.' },
- ),
- { handler: 'search-get', method: 'GET', skipBodyParse: true },
- );
-
- const handleSearchPost = withValidation(
- SearchRequestSchema,
- 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 searchService.buildSearchResponse({
- query,
- intent,
- ranking,
- scopes,
- limit,
- semanticParam,
- source,
- });
- successResponse(res, 200, SearchSuccessSchema, responseBody, { handler: 'search-post' });
- },
- { handler: 'search-post', title: 'Failed to search workspace.' },
- ),
- { handler: 'search-post', method: 'POST' },
- );
-
- const handleSearch = methodRouter(
- { GET: handleSearchGet, POST: handleSearchPost },
- { handler: 'search' },
- );
-
async function handleHandoffDispatchRoute(
req: IncomingMessage,
res: ServerResponse,
@@ -21365,147 +20712,6 @@ export function createApiExtension(
{ handler: 'lint-fix', method: 'POST' },
);
- // ───────────────────── Link preview (external hover cards) ─────────────────
- // Fetches page metadata for an external link on the user's behalf, so it is
- // guarded on two independent axes: an anti-proxy gate decides WHO may ask, and
- // the SSRF-guarded fetch decides WHERE the server may reach. The gate refuses
- // absent / `null` / non-loopback Origins that the shared /api/* allowlist would
- // wave through, because an admitted caller would be a readable server-side
- // request-forgery proxy for any local browser tab. Read-only — kept out of
- // MUTATING_ROUTES.
- const LINK_PREVIEW_HANDLER = 'link-preview';
- // Ephemeral single-file mode keeps zero user-dir artifacts, so its cache stays
- // in memory; otherwise it lives beside the other project-local sidecars.
- const linkPreviewCacheDir = ephemeral
- ? null
- : resolve(projectDir ?? contentDir, '.ok', 'local', 'link-previews');
- const linkPreviewCache = new LinkPreviewCache({ cacheDir: linkPreviewCacheDir });
- // Load the disk cache once, lazily, before the first lookup. init() never
- // throws; serializing it ahead of load() keeps a warm entry from being
- // clobbered by a late disk read.
- let linkPreviewCacheInit: Promise<void> | null = null;
- const ensureLinkPreviewCacheReady = (): Promise<void> => {
- linkPreviewCacheInit ??= linkPreviewCache.init();
- return linkPreviewCacheInit;
- };
- const linkPreviewFetchImpl: GuardedFetch = linkPreviewFetch ?? guardedFetch;
-
- // The cache-miss path: one SSRF-guarded page fetch, a bounded head-scan parse,
- // and a favicon fetch through the SAME chokepoint. Never throws — the guard
- // and the parser each absorb their own failures into a bounded reason.
- async function computeLinkPreview(rawUrl: string): Promise<LinkPreviewOutcome> {
- const fetched = await linkPreviewFetchImpl(rawUrl);
- if (!fetched.ok) return { ok: false, reason: fetched.reason };
- const metadata = await buildLinkPreviewMetadata({
- html: new TextDecoder().decode(fetched.body),
- requestUrl: rawUrl,
- finalUrl: fetched.finalUrl,
- fetch: linkPreviewFetchImpl,
- });
- return { ok: true, metadata };
- }
-
- // The egress opt-in is enforced HERE, not only in the renderer: the anti-proxy
- // gate admits ANY loopback http(s) origin by design, so without this check a
- // second local app could drive outbound fetches while the user has previews
- // OFF. Fail-closed (absent getter or a throwing read = disabled) and evaluated
- // fresh per request so a Settings toggle applies without a restart.
- const linkPreviewsEnabled = (): boolean => {
- try {
- return getLinkPreviewsEnabled?.() === true;
- } catch {
- return false;
- }
- };
-
- const handleLinkPreview = withValidation(
- LinkPreviewRequestSchema,
- async (_req, res, body) => {
- try {
- // Checked BEFORE the cache is touched so the disabled path can never
- // record a negative entry that would outlive re-enabling.
- if (!linkPreviewsEnabled()) {
- // Outcome instrumentation: one greppable category per request.
- // Category ONLY, never the URL, hostname, resolved IP, or fetched
- // content.
- log.debug({ outcome: 'disabled' }, '[link-preview] request outcome');
- successResponse(
- res,
- 200,
- LinkPreviewResponseSchema,
- { ok: false, reason: 'disabled' },
- { handler: LINK_PREVIEW_HANDLER },
- );
- return;
- }
- await ensureLinkPreviewCacheReady();
- // Side flag on the compute closure: load() invokes compute only on a
- // cache miss, so hit-vs-computed falls out here without widening the
- // cache API.
- let computed = false;
- const outcome = await linkPreviewCache.load(body.url, () => {
- computed = true;
- return computeLinkPreview(body.url);
- });
- // Persist is best-effort and never throws; fire-and-forget so a slow disk
- // write can't stall the response.
- void linkPreviewCache.persist();
- // Rejections cross the wire with ONE coarse reason. The granular guard
- // taxonomy (private-ip / dns-failure / non-html / …) stays in local logs
- // and the on-disk cache for debugging, but returning it would let a
- // loopback caller pair chosen hostnames with reasons to enumerate
- // internal names; the renderer ignores the field either way.
- const wireOutcome: LinkPreviewOutcome = outcome.ok
- ? outcome
- : { ok: false, reason: 'blocked' };
- // Outcome instrumentation: one greppable category per request
- // (disabled / cache-hit / fetched-ok / fallback). A negative cache hit
- // logs cache-hit (served without a fetch). Category ONLY, never the
- // URL, hostname, resolved IP, or fetched content; the granular
- // rejection taxonomy is already logged at the guarded-fetch chokepoint.
- log.debug(
- { outcome: computed ? (outcome.ok ? 'fetched-ok' : 'fallback') : 'cache-hit' },
- '[link-preview] request outcome',
- );
- successResponse(res, 200, LinkPreviewResponseSchema, wireOutcome, {
- handler: LINK_PREVIEW_HANDLER,
- });
- } catch (e) {
- errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Internal server error.', {
- handler: LINK_PREVIEW_HANDLER,
- cause: e,
- });
- }
- },
- {
- handler: LINK_PREVIEW_HANDLER,
- method: 'POST',
- // Reject a cross-origin / null-origin / non-JSON caller before the body is
- // read, so a bypass request never reaches the outbound fetch.
- preBodyGate: (req, res) => {
- const verdict = classifyLinkPreviewRequest({
- origin: req.headers.origin,
- contentType: req.headers['content-type'],
- });
- if (verdict.ok) return true;
- if (verdict.reason === 'origin') {
- errorResponse(res, 403, 'urn:ok:error:invalid-origin', 'Origin not allowed.', {
- handler: LINK_PREVIEW_HANDLER,
- });
- } else {
- errorResponse(
- res,
- 400,
- 'urn:ok:error:invalid-request',
- 'Content-Type must be application/json.',
- { handler: LINK_PREVIEW_HANDLER },
- );
- }
- return false;
- },
- },
- );
-
// The comment store + service are constructed near `resolveDocPath` above so
// the rename walk can follow renames. Two dispatchers keep the surface to two
// paths; the mutating sub-handlers in `comment-api.ts` thread
@@ -21525,87 +20731,18 @@ export function createApiExtension(
{ handler: 'comment' },
);
- // Built here, not at their old spot ~18k lines up: `skillsHome` is a `const`
- // initialized further down, so an earlier call would hit its temporal dead zone.
- const {
- handleSkillsSearch,
- handleSkillsPopular,
- handleSkillsPublisher,
- handleSkillsDetail,
- handleSkillsPreview,
- handleSkillsDiscover,
- handleSkillsResolveRef,
- } = createSkillsShHandlers({ log, skillsHome, projectDir, contentDir, resolveSkillDirForRead });
-
- const handleGetGeneratedIndexSettings = withValidation(
- EmptyRequestSchema,
- async (_req, res) => {
- if (!getGeneratedIndexSettingsStatus) {
- errorResponse(res, 404, 'urn:ok:error:not-found', 'Not found.', {
- handler: 'generated-index-settings-get',
- });
- return;
- }
- successResponse(
- res,
- 200,
- GeneratedIndexSettingsStatusSchema,
- getGeneratedIndexSettingsStatus(),
- {
- handler: 'generated-index-settings-get',
- extraHeaders: { 'Cache-Control': 'no-store' },
- },
- );
- },
- { handler: 'generated-index-settings-get', method: 'GET', skipBodyParse: true },
- );
-
- const handleSetGeneratedIndexSettings = withValidation(
- GeneratedIndexSettingsRequestSchema,
- async (_req, res, body) => {
- if (!setGeneratedIndexEnabled) {
- errorResponse(res, 404, 'urn:ok:error:not-found', 'Not found.', {
- handler: 'generated-index-settings-set',
- });
- return;
- }
- const result = await setGeneratedIndexEnabled(body.enabled);
- successResponse(res, 200, GeneratedIndexSettingsStatusSchema, result, {
- handler: 'generated-index-settings-set',
- extraHeaders: { 'Cache-Control': 'no-store' },
- });
- },
- { handler: 'generated-index-settings-set', method: 'POST' },
- );
-
- const handleGeneratedIndexSettings = methodRouter(
- { GET: handleGetGeneratedIndexSettings, POST: handleSetGeneratedIndexSettings },
- { handler: 'generated-index-settings' },
- );
-
const routes: Record<string, (req: IncomingMessage, res: ServerResponse) => Promise<void>> = {
- '/api/generated-index/settings': handleGeneratedIndexSettings,
'/api/comments': handleCommentsRoute,
'/api/comment': handleCommentRoute,
'/api/asset': handleAsset,
'/api/asset-text': handleAssetText,
- '/api/link-preview': handleLinkPreview,
'/api/folder-config': handleFolderConfig,
- '/api/saved-themes': handleSavedThemesList,
- '/api/saved-theme': handleSavedTheme,
'/api/template': handleTemplate,
'/api/template/import': handleTemplateImport,
'/api/skill': handleSkill,
'/api/skill-file': handleSkillFile,
'/api/skill-file/rename': handleSkillFileRename,
'/api/skills': handleSkillsList,
- '/api/skills/search': handleSkillsSearch,
- '/api/skills/popular': handleSkillsPopular,
- '/api/skills/publisher': handleSkillsPublisher,
- '/api/skills/detail': handleSkillsDetail,
- '/api/skills/preview': handleSkillsPreview,
- '/api/skills/discover': handleSkillsDiscover,
- '/api/skills/resolve-ref': handleSkillsResolveRef,
'/api/skill/import': handleSkillImport,
'/api/skills/import-bulk': handleSkillsImportBulk,
'/api/skill/edit-external': handleSkillEditExternal,
@@ -21619,8 +20756,6 @@ export function createApiExtension(
'/api/skills/reimport-bulk': handleSkillsReimportBulk,
'/api/skill/revert': handleSkillRevert,
'/api/skill/track-in-git': handleSkillTrackInGit,
- '/api/skill-targets': handleSkillTargets,
- '/api/search': handleSearch,
'/api/lint/markdownlint-config': handleWriteMarkdownlintRule,
'/api/lint/frontmatter-schema': handleWriteFrontmatterSchema,
'/api/lint/fix': handleLintFix,
@@ -21698,7 +20833,6 @@ export function createApiExtension(
'/api/lint/markdownlint-config',
'/api/lint/frontmatter-schema',
'/api/lint/fix',
- '/api/generated-index/settings',
'/api/create-page',
'/api/create-folder',
'/api/duplicate-path',
@@ -21723,9 +20857,6 @@ export function createApiExtension(
'/api/test-rescan-files',
'/api/install-skill',
'/api/folder-config',
- // `/api/saved-theme` (POST save / PUT update / DELETE) mutates the user-global theme
- // store; `/api/saved-themes` (GET list) is read-only and stays out.
- '/api/saved-theme',
'/api/template',
'/api/template/import',
'/api/skill',
@@ -21744,12 +20875,6 @@ export function createApiExtension(
'/api/skills/reimport-bulk',
'/api/skill/revert',
'/api/skill/track-in-git',
- // Read-shaped GETs, but each triggers an arbitrary `git clone` (network egress)
- // + local SKILL.md reads, so they ride the loopback/host gate, not the read posture.
- '/api/skills/preview',
- '/api/skills/discover',
- '/api/skills/resolve-ref',
- '/api/skill-targets',
'/api/seed/apply',
'/api/seed/install-pack-skill',
'/api/client-logs',
@@ -21869,6 +20994,28 @@ export function createApiExtension(
enumerateInstalledSkillsCached,
checkLocalOpSecurity,
});
+ const skillsShRoutes = createSkillsShRoutes({
+ log,
+ skillsHome,
+ projectDir,
+ contentDir,
+ resolveSkillDirForRead,
+ });
+ const workspaceToolsRoutes = createWorkspaceToolsRoutes({
+ contentDir,
+ projectDir,
+ skillsHome,
+ homeDirOverride,
+ savedThemeLockTimeoutMs,
+ ephemeral,
+ log,
+ signalChannel,
+ searchService,
+ linkPreviewFetch,
+ getLinkPreviewsEnabled,
+ getGeneratedIndexSettingsStatus,
+ setGeneratedIndexEnabled,
+ });
const nativeGroups = [
linkGraphRoutes,
metricsRoutes,
@@ -21877,6 +21024,8 @@ export function createApiExtension(
lintRoutes,
historyRoutes,
skillsReadRoutes,
+ skillsShRoutes,
+ workspaceToolsRoutes,
];
// "A route lives in exactly one router" — enforced at construction, not
// just documented; covers every group aggregated into the native paths.
@@ -21915,7 +21064,7 @@ export function createApiExtension(
// template + skill CRUD) has no extracted service yet and stays on HTTP;
// extend this set as further capabilities extract.
const MCP_LOCAL_API_PATHS: ReadonlySet<string> = new Set([
- // searchService
+ // searchService (native workspace-tools group)
'/api/search',
// fileOpsService
'/api/delete-path',
@@ -21939,8 +21088,19 @@ export function createApiExtension(
// Every collapsed path must resolve to a handler at construction — a typo
// here, or a later route rename, would otherwise fall back to HTTP forever
// with no signal. Same posture as `assertSingleRouterOwnership` above.
+ // The local-api collapse may consult any native group's table (the
+ // link-graph reads and the workspace-tools `/api/search` resolve this way);
+ // the MCP_LOCAL_API_PATHS allowlist is what bounds the reachable set.
+ const localApiNativeTables = nativeGroups.map((group) => group.table);
+ const resolveLocalApiNativeDispatch = (pathname: string) => {
+ for (const table of localApiNativeTables) {
+ const dispatch = table.resolve(pathname)?.dispatch;
+ if (dispatch !== undefined) return dispatch;
+ }
+ return undefined;
+ };
for (const path of MCP_LOCAL_API_PATHS) {
- if (routes[path] === undefined && linkGraphRoutes.table.resolve(path)?.dispatch === undefined) {
+ if (routes[path] === undefined && resolveLocalApiNativeDispatch(path) === undefined) {
throw new Error(`MCP_LOCAL_API_PATHS has no handler for ${path}`);
}
}
@@ -21949,7 +21109,7 @@ export function createApiExtension(
if (!MCP_LOCAL_API_PATHS.has(pathname)) return undefined;
const legacy = routes[pathname];
if (legacy !== undefined) return legacy;
- return linkGraphRoutes.table.resolve(pathname)?.dispatch;
+ return resolveLocalApiNativeDispatch(pathname);
},
});
diff --git a/packages/server/src/api-search-incremental.test.ts b/packages/server/src/api-search-incremental.test.ts
index c37404db3..c4ae271f3 100644
--- a/packages/server/src/api-search-incremental.test.ts
+++ b/packages/server/src/api-search-incremental.test.ts
@@ -4,7 +4,10 @@ import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { Readable } from 'node:stream';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
-import { createApiExtension } from './api-extension.ts';
+// The test-helper wrapper (not the base factory): its `onRequest` dispatches
+// the native route groups ahead of the legacy hook, so the now-native
+// `/api/search` reaches its real handler instead of the legacy 404 fallback.
+import { createApiExtension } from './api-extension.test-helper.ts';
import type { FileIndexEntry } from './file-watcher.ts';
// Count how the server maintains the search corpus: `create` = from-scratch
@@ -130,7 +133,7 @@ function createHarness(contentDir: string, options: { withGeneration: boolean })
const req = makeReq('GET', `/api/search?query=${encodeURIComponent(query)}&intent=${intent}`);
const { res, captured } = makeRes();
await (
- ext as {
+ ext as unknown as {
onRequest: (ctx: { request: IncomingMessage; response: ServerResponse }) => Promise<void>;
}
).onRequest({ request: req, response: res });
diff --git a/packages/server/src/api-search-semantic-factory.test.ts b/packages/server/src/api-search-semantic-factory.test.ts
index 56130396f..016e1bed2 100644
--- a/packages/server/src/api-search-semantic-factory.test.ts
+++ b/packages/server/src/api-search-semantic-factory.test.ts
@@ -96,12 +96,13 @@ let tmpDir: string;
let server: ServerInstance;
/**
- * Drive one `POST /api/search` through the booted server's wired extension
- * chain. Several extensions expose `onRequest`; Hocuspocus calls them in
- * registration order until one writes a response. We mirror that here (a fresh
- * request per attempt so an early extension can't consume the body the api
- * extension needs) rather than reaching for one extension by index — that keeps
- * the test honest about which extension actually serves `/api/search`.
+ * Drive one `POST /api/search` through the booted server's request surface in
+ * the production order: the native group dispatch first, then the legacy
+ * `onRequest` extension chain (Hocuspocus calls those in registration order
+ * until one writes a response; a fresh request per attempt so an early
+ * extension can't consume the body the api extension needs). Mirroring the
+ * composed order keeps the test honest about which surface actually serves a
+ * path as routes migrate.
*/
async function callViaServer(
srv: ServerInstance,
@@ -112,8 +113,8 @@ async function callViaServer(
// Natively-routed groups take precedence in the composed server — their Hono
// routes match ahead of the legacy `onRequest` catch-all — so mirror that
// order here: try the native dispatch first, then fall back to the legacy
- // `onRequest` chain. Several `/api/*` reads (e.g. `semantic-status`) now serve
- // from a native group, where the legacy pipeline would answer 404.
+ // `onRequest` chain. Several `/api/*` routes (e.g. `search`, `semantic-status`)
+ // now serve from a native group, where the legacy pipeline would answer 404.
{
const req = makeReq(method, url, bodyObj === undefined ? '' : JSON.stringify(bodyObj));
const { res, captured } = makeRes();
diff --git a/packages/server/src/api-skills-sh-composition.test.ts b/packages/server/src/api-skills-sh-composition.test.ts
new file mode 100644
index 000000000..aa82b230b
--- /dev/null
+++ b/packages/server/src/api-skills-sh-composition.test.ts
@@ -0,0 +1,137 @@
+import { mkdtempSync, writeFileSync } from 'node:fs';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { resolve } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import type { BootedServer } from './boot.ts';
+import { bootCompositionRig, parseProblem, rawRequest } from './composition-rig.test-helper.ts';
+
+/**
+ * Characterization: the natively-routed skills.sh proxy group over a REAL
+ * socket through the composed `bootServer` stack — native registration and
+ * the shared admission posture. The wire cannot distinguish the mutating
+ * gate from the read gate (both apply the same loopback + workspace-Host
+ * checks), so the mutating DECLARATION itself is pinned at the table tier in
+ * `http/skills-sh-routes.test.ts`; the rebound-Host pins here hold that the
+ * admission outcome is unchanged across the lift.
+ *
+ * Every request below refuses BEFORE any outbound fetch (missing/invalid
+ * params, wrong verb, or a gate) — the suite never reaches skills.sh, GitHub,
+ * or `git clone`.
+ */
+
+/** The whole proxy family — method-gated, so a POST answers 405 when registered. */
+const ALL_ROUTES = [
+ '/api/skills/search',
+ '/api/skills/popular',
+ '/api/skills/publisher',
+ '/api/skills/detail',
+ '/api/skills/preview',
+ '/api/skills/discover',
+ '/api/skills/resolve-ref',
+];
+
+/** The clone-egress trio — legacy `MUTATING_ROUTES` members (declaration pinned in the table suite). */
+const MUTATING_ROUTES = ['/api/skills/preview', '/api/skills/discover', '/api/skills/resolve-ref'];
+
+/**
+ * Missing-required-param requests that the real handler refuses with its OWN
+ * 400 before any network egress — proving dispatch reaches the handler (an
+ * unregistered path would return the pipeline's generic `/api/*` 404).
+ */
+const HANDLER_400S = [
+ '/api/skills/search',
+ '/api/skills/publisher',
+ '/api/skills/detail',
+ '/api/skills/preview',
+ '/api/skills/discover',
+ '/api/skills/resolve-ref',
+];
+
+let tmpRoot: string;
+let server: BootedServer;
+
+beforeAll(async () => {
+ tmpRoot = await mkdtemp(resolve(tmpdir(), 'ok-skills-sh-native-'));
+ const contentDir = mkdtempSync(resolve(tmpRoot, 'content-'));
+ writeFileSync(resolve(contentDir, 'alpha.md'), '# Alpha\n\nBody.\n', 'utf-8');
+ server = await bootCompositionRig(contentDir);
+ await server.ready;
+}, 60_000);
+
+afterAll(async () => {
+ await server?.destroy();
+ await rm(tmpRoot, { recursive: true, force: true });
+});
+
+describe('skills.sh proxy group over the composed listener — served natively', () => {
+ test('every route in the group is registered natively (POST → 405, not a route-miss 404)', async () => {
+ for (const path of ALL_ROUTES) {
+ const res = await fetch(`http://127.0.0.1:${server.port}${path}`, { method: 'POST' });
+ expect(res.status, path).toBe(405);
+ }
+ });
+
+ test('missing-param requests reach the real handler (its own 400, x-request-id echoed)', async () => {
+ for (const path of HANDLER_400S) {
+ const res = await fetch(`http://127.0.0.1:${server.port}${path}`);
+ expect(res.status, path).toBe(400);
+ expect(((await res.json()) as { type?: string }).type, path).toBe(
+ 'urn:ok:error:invalid-request',
+ );
+ expect(res.headers.get('x-request-id'), path).not.toBeNull();
+ }
+ });
+
+ test('mutating trio refuses a rebound Host with 403 (loopback/host gate survives the lift)', async () => {
+ for (const path of MUTATING_ROUTES) {
+ const res = await rawRequest(server.port, `${path}?source=owner/repo`, {
+ headers: { Host: 'evil.example' },
+ });
+ expect(res.status, path).toBe(403);
+ expect(parseProblem(res.body).type, path).toBe('urn:ok:error:host-not-allowed');
+ }
+ });
+
+ test('proxy reads are Host-gated by the shared read choke point too', async () => {
+ const res = await rawRequest(server.port, '/api/skills/search?q=x', {
+ headers: { Host: 'evil.example' },
+ });
+ expect(res.status).toBe(403);
+ expect(parseProblem(res.body).type).toBe('urn:ok:error:host-not-allowed');
+ });
+
+ test('both chained groups answer on one server (multi-group dispatch)', async () => {
+ const linkGraph = await fetch(`http://127.0.0.1:${server.port}/api/backlinks?docName=alpha`);
+ expect(linkGraph.status).toBe(200);
+ const detail = await fetch(`http://127.0.0.1:${server.port}/api/skills/detail`);
+ expect(detail.status).toBe(400);
+ });
+
+ test('foreign Origin is refused before dispatch on a ported route', async () => {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/skills/preview`, {
+ headers: { Origin: 'https://evil.example' },
+ });
+ expect(res.status).toBe(403);
+ expect(((await res.json()) as { type?: string }).type).toBe('urn:ok:error:invalid-origin');
+ });
+
+ test('OPTIONS preflight answers 204 on a ported route', async () => {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/skills/search`, {
+ method: 'OPTIONS',
+ headers: { Origin: 'http://localhost:5173' },
+ });
+ expect(res.status).toBe(204);
+ expect(res.headers.get('access-control-allow-methods')).toBe('GET, POST, PUT, DELETE, OPTIONS');
+ });
+
+ test('any forwarding header trips the proxied-request refusal on a mutating route', async () => {
+ const res = await rawRequest(server.port, '/api/skills/preview?source=owner/repo', {
+ headers: { 'X-Forwarded-For': '203.0.113.7' },
+ });
+ expect(res.status).toBe(403);
+ const body = parseProblem(res.body);
+ expect(body.type).toBe('urn:ok:error:host-not-allowed');
+ expect(body.detail ?? body.title).toContain('Proxied request refused');
+ });
+});
diff --git a/packages/server/src/api-workspace-tools-composition.test.ts b/packages/server/src/api-workspace-tools-composition.test.ts
new file mode 100644
index 000000000..c0c48d684
--- /dev/null
+++ b/packages/server/src/api-workspace-tools-composition.test.ts
@@ -0,0 +1,178 @@
+import { mkdtempSync, writeFileSync } from 'node:fs';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { resolve } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import type { BootedServer } from './boot.ts';
+import { bootCompositionRig, parseProblem, rawRequest } from './composition-rig.test-helper.ts';
+
+/**
+ * Characterization: the natively-routed workspace-tools group (`search`,
+ * `link-preview`, `skill-targets`, `saved-themes`/`saved-theme`,
+ * `generated-index/settings`) over a REAL socket through the composed
+ * `bootServer` stack: verb gating (405 + `Allow` in declaration order — via
+ * `methodRouter` for the four multi-verb paths, via `withValidation`'s
+ * method check for single-verb `link-preview` and `saved-themes`), both
+ * `/api/search` verbs served, and the shared admission posture. The wire
+ * cannot distinguish the mutating gate from the read gate (both apply the
+ * same loopback + workspace-Host checks), so the mutating DECLARATION is
+ * pinned at the table tier in `http/workspace-tools-routes.test.ts`; the
+ * rebound-Host pins here hold that the admission outcome is unchanged
+ * across the lift, GET arms included.
+ */
+
+/** Every path in the group, with the verbs the legacy record dispatched. */
+const METHOD_SURFACE: ReadonlyArray<{ path: string; unsupported: string; allow: string }> = [
+ { path: '/api/search', unsupported: 'DELETE', allow: 'GET, POST' },
+ { path: '/api/link-preview', unsupported: 'GET', allow: 'POST' },
+ { path: '/api/skill-targets', unsupported: 'POST', allow: 'GET, PUT' },
+ { path: '/api/saved-themes', unsupported: 'POST', allow: 'GET' },
+ { path: '/api/saved-theme', unsupported: 'GET', allow: 'POST, PUT, DELETE' },
+ { path: '/api/generated-index/settings', unsupported: 'DELETE', allow: 'GET, POST' },
+];
+
+/** Legacy `MUTATING_ROUTES` members (declaration pinned in the table suite). */
+const MUTATING_ROUTES = ['/api/skill-targets', '/api/saved-theme', '/api/generated-index/settings'];
+
+let tmpRoot: string;
+let server: BootedServer;
+
+beforeAll(async () => {
+ tmpRoot = await mkdtemp(resolve(tmpdir(), 'ok-workspace-tools-native-'));
+ const contentDir = mkdtempSync(resolve(tmpRoot, 'content-'));
+ writeFileSync(resolve(contentDir, 'alpha.md'), '# Alpha\n\nBody.\n', 'utf-8');
+ server = await bootCompositionRig(contentDir);
+ await server.ready;
+}, 60_000);
+
+afterAll(async () => {
+ await server?.destroy();
+ await rm(tmpRoot, { recursive: true, force: true });
+});
+
+describe('workspace-tools group over the composed listener — served natively', () => {
+ test('every path is registered natively with verb gating (405 + Allow)', async () => {
+ for (const { path, unsupported, allow } of METHOD_SURFACE) {
+ const res = await fetch(`http://127.0.0.1:${server.port}${path}`, { method: unsupported });
+ expect(res.status, path).toBe(405);
+ expect(res.headers.get('allow'), path).toBe(allow);
+ }
+ });
+
+ test('GET /api/search serves the search body natively (both verbs, one handler pair)', async () => {
+ const viaGet = await fetch(`http://127.0.0.1:${server.port}/api/search?query=alpha`);
+ expect(viaGet.status).toBe(200);
+ expect(viaGet.headers.get('x-request-id')).not.toBeNull();
+ const getBody = (await viaGet.json()) as { results?: unknown[] };
+ expect(Array.isArray(getBody.results)).toBe(true);
+
+ const viaPost = await fetch(`http://127.0.0.1:${server.port}/api/search`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ query: 'alpha' }),
+ });
+ expect(viaPost.status).toBe(200);
+ const postBody = (await viaPost.json()) as { results?: unknown[] };
+ expect(Array.isArray(postBody.results)).toBe(true);
+ });
+
+ test('GET reads serve 200 natively (skill-targets, saved-themes, generated-index settings)', async () => {
+ for (const path of [
+ '/api/skill-targets',
+ '/api/saved-themes',
+ '/api/generated-index/settings',
+ ]) {
+ const res = await fetch(`http://127.0.0.1:${server.port}${path}`);
+ expect(res.status, path).toBe(200);
+ expect(res.headers.get('content-type'), path).toBe('application/json');
+ expect(res.headers.get('x-request-id'), path).not.toBeNull();
+ }
+ });
+
+ test('link-preview anti-proxy gate survives the lift (no Origin → 403 before any fetch)', async () => {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/link-preview`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ url: 'https://example.com/' }),
+ });
+ expect(res.status).toBe(403);
+ expect(((await res.json()) as { type?: string }).type).toBe('urn:ok:error:invalid-origin');
+ });
+
+ test('link-preview serves the coarse blocked envelope through the lift (no egress attempted)', async () => {
+ // A literal loopback target lets the pin run without real network egress;
+ // the wire cannot tell a pre-I/O guard refusal from a failed connect
+ // (both collapse to the ONE coarse category by design), so the SSRF
+ // guard itself is pinned at the unit tier in
+ // `link-preview/guarded-fetch.test.ts` — this pin holds the collapsed
+ // wire shape across the lift.
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/link-preview`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', Origin: 'http://localhost:5173' },
+ body: JSON.stringify({ url: 'http://127.0.0.1/' }),
+ });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ ok: false, reason: 'blocked' });
+ });
+
+ test('legacy-mutating paths refuse a rebound Host on their GET arms too (admission unchanged)', async () => {
+ for (const path of MUTATING_ROUTES) {
+ const res = await rawRequest(server.port, path, {
+ headers: { Host: 'evil.example' },
+ });
+ expect(res.status, path).toBe(403);
+ expect(parseProblem(res.body).type, path).toBe('urn:ok:error:host-not-allowed');
+ }
+ });
+
+ test('read paths are Host-gated by the shared read choke point', async () => {
+ const res = await rawRequest(server.port, '/api/saved-themes', {
+ headers: { Host: 'evil.example' },
+ });
+ expect(res.status).toBe(403);
+ expect(parseProblem(res.body).type).toBe('urn:ok:error:host-not-allowed');
+ });
+
+ test('both chained groups answer on one server (multi-group dispatch)', async () => {
+ const linkGraph = await fetch(`http://127.0.0.1:${server.port}/api/backlinks?docName=alpha`);
+ expect(linkGraph.status).toBe(200);
+ const search = await fetch(`http://127.0.0.1:${server.port}/api/search?query=alpha`);
+ expect(search.status).toBe(200);
+ });
+
+ test('foreign Origin is refused before dispatch on a ported route', async () => {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/search?query=alpha`, {
+ headers: { Origin: 'https://evil.example' },
+ });
+ expect(res.status).toBe(403);
+ expect(((await res.json()) as { type?: string }).type).toBe('urn:ok:error:invalid-origin');
+ });
+
+ test('allowed browser Origin gets CORS reflection on a ported route', async () => {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/search?query=alpha`, {
+ headers: { Origin: 'http://localhost:5173' },
+ });
+ expect(res.status).toBe(200);
+ expect(res.headers.get('access-control-allow-origin')).toBe('http://localhost:5173');
+ expect(res.headers.get('vary')).toContain('Origin');
+ });
+
+ test('OPTIONS preflight answers 204 on a ported route', async () => {
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/skill-targets`, {
+ method: 'OPTIONS',
+ headers: { Origin: 'http://localhost:5173' },
+ });
+ expect(res.status).toBe(204);
+ expect(res.headers.get('access-control-allow-methods')).toBe('GET, POST, PUT, DELETE, OPTIONS');
+ });
+
+ test('any forwarding header trips the proxied-request refusal on a ported route', async () => {
+ const res = await rawRequest(server.port, '/api/skill-targets', {
+ headers: { 'X-Forwarded-For': '203.0.113.7' },
+ });
+ expect(res.status).toBe(403);
+ const body = parseProblem(res.body);
+ expect(body.type).toBe('urn:ok:error:host-not-allowed');
+ expect(body.detail ?? body.title).toContain('Proxied request refused');
+ });
+});
diff --git a/packages/server/src/http/api-pipeline.test.ts b/packages/server/src/http/api-pipeline.test.ts
index fa3894cf9..6e30e014f 100644
--- a/packages/server/src/http/api-pipeline.test.ts
+++ b/packages/server/src/http/api-pipeline.test.ts
@@ -2,7 +2,11 @@ import { createServer } from 'node:http';
import { describe, expect, test } from 'vitest';
import { parseProblem, rawRequest } from '../composition-rig.test-helper.ts';
import { listenOnLoopback } from '../loopback-rig-test-helpers.ts';
-import { type ApiRouteTable, createApiRequestPipeline } from './api-pipeline.ts';
+import {
+ type ApiRouteTable,
+ createApiRequestPipeline,
+ createApiRouteGroup,
+} from './api-pipeline.ts';
import { createHttpApp, type NativeApiHandle } from './http-app.ts';
/**
@@ -328,3 +332,103 @@ describe('natively-mounted /api routes run the shared admission pipeline', () =>
}
});
});
+
+describe('createApiRouteGroup', () => {
+ const handler = async () => {};
+
+ test('exact paths resolve with the URL as template; everything else declines', () => {
+ const group = createApiRouteGroup({ '/api/alpha': handler, '/api/beta': handler });
+ expect(group.paths).toEqual(['/api/alpha', '/api/beta']);
+ const hit = group.table.resolve('/api/alpha');
+ expect(hit?.template).toBe('/api/alpha');
+ expect(hit?.dispatch).toBeDefined();
+ // Decline is `null`, not a template-only resolution — the multi-group
+ // chain relies on zero side effects for unclaimed URLs.
+ expect(group.table.resolve('/api/gamma')).toBeNull();
+ });
+
+ test('mutating membership is URL-keyed and defaults to none', () => {
+ const readOnly = createApiRouteGroup({ '/api/alpha': handler });
+ expect(readOnly.table.isMutating('/api/alpha')).toBe(false);
+ const mixed = createApiRouteGroup(
+ { '/api/alpha': handler, '/api/beta': handler },
+ { mutating: ['/api/beta'] },
+ );
+ expect(mixed.table.isMutating('/api/alpha')).toBe(false);
+ expect(mixed.table.isMutating('/api/beta')).toBe(true);
+ });
+
+ test('mutatingPrefixes protect a namespace family by default, matching the legacy prefix rule', () => {
+ const group = createApiRouteGroup(
+ { '/api/local-op/clone': handler },
+ { mutatingPrefixes: ['/api/local-op/'] },
+ );
+ expect(group.table.isMutating('/api/local-op/clone')).toBe(true);
+ // Default-protect: a member never enumerated anywhere still gates.
+ expect(group.table.isMutating('/api/local-op/brand-new-route')).toBe(true);
+ expect(group.table.isMutating('/api/alpha')).toBe(false);
+ });
+
+ test('a mutating dynamic namespace declares its prefix in mutatingPrefixes', () => {
+ const group = createApiRouteGroup(
+ {},
+ {
+ mutatingPrefixes: ['/api/thing/'],
+ dynamic: {
+ prefix: '/api/thing/',
+ template: '/api/thing/:id',
+ dispatch: () => undefined,
+ },
+ },
+ );
+ expect(group.table.isMutating('/api/thing/abc')).toBe(true);
+ expect(group.table.isMutating('/api/other')).toBe(false);
+ });
+
+ test('a malformed or orphaned mutatingPrefixes entry fails at construction', () => {
+ // Slash dropped: would also match unrelated siblings.
+ expect(() =>
+ createApiRouteGroup(
+ { '/api/local-op/clone': handler },
+ { mutatingPrefixes: ['/api/local-op'] },
+ ),
+ ).toThrow(/must end in '\/'/);
+ // Typo: covers nothing, so the real family would ride the read posture.
+ expect(() =>
+ createApiRouteGroup(
+ { '/api/local-op/clone': handler },
+ { mutatingPrefixes: ['/api/loca-op/'] },
+ ),
+ ).toThrow(/covers no registered route/);
+ });
+
+ test('a dynamic leg claims its namespace: wildcard path, bound template, 404-able empty tail', () => {
+ const seen: string[] = [];
+ const group = createApiRouteGroup(
+ { '/api/tags': handler },
+ {
+ dynamic: {
+ prefix: '/api/tags/',
+ template: '/api/tags/:name',
+ dispatch: (suffix) => {
+ if (!suffix) return undefined;
+ return async () => {
+ seen.push(suffix);
+ };
+ },
+ },
+ },
+ );
+ expect(group.paths).toEqual(['/api/tags', '/api/tags/*']);
+ const named = group.table.resolve('/api/tags/til');
+ expect(named?.template).toBe('/api/tags/:name');
+ expect(named?.dispatch).toBeDefined();
+ // Empty tail: the table OWNS the URL (template resolution) but binds no
+ // dispatch, so the pipeline's explicit 404 answers under the template.
+ const empty = group.table.resolve('/api/tags/');
+ expect(empty?.template).toBe('/api/tags/:name');
+ expect(empty?.dispatch).toBeUndefined();
+ // Outside the namespace still declines.
+ expect(group.table.resolve('/api/other')).toBeNull();
+ });
+});
diff --git a/packages/server/src/http/api-pipeline.ts b/packages/server/src/http/api-pipeline.ts
index 005dc4cb6..7d127cdf9 100644
--- a/packages/server/src/http/api-pipeline.ts
+++ b/packages/server/src/http/api-pipeline.ts
@@ -92,6 +92,121 @@ export interface ApiRouteTable {
isMutating(pathname: string): boolean;
}
+/** One handler per exact `/api/...` path — a native group's routes record. */
+export type ApiRouteRecord = Readonly<
+ Record<string, (req: IncomingMessage, res: ServerResponse) => Promise<void>>
+>;
+
+/**
+ * A dynamic namespace leg (`/api/tags/:name`, `/api/history/:sha`) alongside
+ * a group's exact-path record. The Hono mount claims `<prefix>*` so an empty
+ * or slash-containing tail reaches the table exactly like the legacy prefix
+ * match did.
+ */
+export interface ApiRouteGroupDynamicLeg {
+ /** The URL prefix owning the namespace, trailing slash included (`'/api/tags/'`). */
+ prefix: string;
+ /** Low-cardinality template for the leg (`'/api/tags/:name'`). */
+ template: string;
+ /**
+ * Bound dispatch for the captured (still-encoded) suffix. Return
+ * `undefined` for an unservable suffix (empty segment) — the pipeline's
+ * explicit RFC 9457 404 then owns the response under the leg's template.
+ */
+ dispatch: (
+ suffix: string,
+ ) => ((req: IncomingMessage, res: ServerResponse) => Promise<void>) | undefined;
+}
+
+/** A native group's contribution to the Hono mount + the shared pipeline. */
+export interface ApiRouteGroup {
+ /** Hono patterns for the native mount (`NativeApiHandle.paths`). */
+ paths: readonly string[];
+ /** The group's view for the shared /api/* admission pipeline. */
+ table: ApiRouteTable;
+}
+
+/**
+ * The `{paths, table}` tail every native group factory used to hand-roll
+ * byte-identically: exact-path resolve over a routes record, an optional
+ * dynamic namespace leg, decline (`null`) for everything else, and the
+ * group's mutating-gate membership in one declared place.
+ *
+ * `mutating` tracks legacy `MUTATING_ROUTES` MEMBERSHIP, not side effects —
+ * URL-keyed like the legacy set, so a multi-verb path whose any verb mutates
+ * rides the mutating gate on every verb. Omit it for a read-only group.
+ * Entries are typed against the routes record's own keys, so a typo or a
+ * rename-drift entry on this security-gate declaration is a compile error,
+ * not a silent no-op. The record must be declared as a literal
+ * (`satisfies ApiRouteRecord`, never a widening `: Record<string, ...>`
+ * annotation): a widened record collapses `keyof R` to `string`, and the
+ * conditional element type below turns that into a compile error on the
+ * `mutating` declaration rather than a silently disabled check.
+ *
+ * `mutatingPrefixes` reproduces the legacy `STATE_MUTATING_PREFIXES` rule for
+ * namespace families (`/api/local-op/`): every member — a mutating dynamic
+ * leg included — is protected by DEFAULT, so adding a route under the prefix
+ * can never silently land on the read posture. Use it rather than
+ * enumerating a mutating family's members into `mutating`. Each prefix must
+ * end in `/` and cover a registered route or the dynamic leg's namespace —
+ * asserted at construction, since a malformed entry here silently re-postures
+ * routes in both directions.
+ */
+export function createApiRouteGroup<R extends ApiRouteRecord>(
+ routes: R,
+ opts: {
+ // `string extends keyof R` is true only for a WIDENED record — the
+ // element type then collapses to `never`, turning the silently-disabled
+ // key-check into a compile error at the declaring call site.
+ mutating?: readonly (string extends keyof R ? never : keyof R & string)[];
+ mutatingPrefixes?: readonly string[];
+ dynamic?: ApiRouteGroupDynamicLeg;
+ } = {},
+): ApiRouteGroup {
+ const { dynamic } = opts;
+ const mutating: ReadonlySet<string> = new Set(opts.mutating ?? []);
+ const mutatingPrefixes: readonly string[] = opts.mutatingPrefixes ?? [];
+ const routeKeys = Object.keys(routes);
+ for (const prefix of mutatingPrefixes) {
+ if (!prefix.endsWith('/')) {
+ throw new Error(
+ `mutatingPrefixes entry '${prefix}' must end in '/' — a bare prefix also matches unrelated siblings ('/api/local-op' matches '/api/local-op-status')`,
+ );
+ }
+ if (prefix !== dynamic?.prefix && !routeKeys.some((key) => key.startsWith(prefix))) {
+ throw new Error(
+ `mutatingPrefixes entry '${prefix}' covers no registered route and is not the dynamic leg's prefix — a typo here leaves its family on the read posture`,
+ );
+ }
+ }
+ // `Map.get` is `handler | undefined` regardless of `noUncheckedIndexedAccess`,
+ // so the unregistered-path guard below stays type-enforced.
+ const routeMap = new Map<string, (req: IncomingMessage, res: ServerResponse) => Promise<void>>(
+ Object.entries(routes),
+ );
+ const table: ApiRouteTable = {
+ resolve(url) {
+ const handler = routeMap.get(url);
+ if (handler) {
+ return { template: url, dispatch: (req, res) => handler(req, res) };
+ }
+ if (dynamic !== undefined && url.startsWith(dynamic.prefix)) {
+ return {
+ template: dynamic.template,
+ dispatch: dynamic.dispatch(url.slice(dynamic.prefix.length)),
+ };
+ }
+ return null;
+ },
+ isMutating: (url) => mutating.has(url) || mutatingPrefixes.some((p) => url.startsWith(p)),
+ };
+ return {
+ paths:
+ dynamic !== undefined ? [...Object.keys(routes), `${dynamic.prefix}*`] : Object.keys(routes),
+ table,
+ };
+}
+
export interface ApiPipelineOptions {
log: PinoLogger;
/**
diff --git a/packages/server/src/http/link-graph-routes.ts b/packages/server/src/http/link-graph-routes.ts
index 63467c1b2..4c9eb5a16 100644
--- a/packages/server/src/http/link-graph-routes.ts
+++ b/packages/server/src/http/link-graph-routes.ts
@@ -42,7 +42,7 @@ import { toForwardLinkLocalTargets } from '../local-target-assessment.ts';
import type { FrontmatterMetadata } from '../page-identity.ts';
import { isInternalBundleSkillName } from '../skill-bundles.ts';
import { SuggestLinksTargetNotFoundError, suggestLinks } from '../suggest-links.ts';
-import type { ApiRouteTable } from './api-pipeline.ts';
+import { type ApiRouteGroup, type ApiRouteRecord, createApiRouteGroup } from './api-pipeline.ts';
import { errorResponse } from './error-response.ts';
import { withValidation } from './request-validation.ts';
import { successResponse } from './success-response.ts';
@@ -68,14 +68,7 @@ export interface LinkGraphRouteDeps {
) => void;
}
-export interface LinkGraphRoutes {
- /** Hono patterns for the native mount (`NativeApiHandle.paths`). */
- paths: readonly string[];
- /** The group's view for the shared /api/* admission pipeline. */
- table: ApiRouteTable;
-}
-
-export function createLinkGraphRoutes(deps: LinkGraphRouteDeps): LinkGraphRoutes {
+export function createLinkGraphRoutes(deps: LinkGraphRouteDeps): ApiRouteGroup {
const {
hocuspocus,
derivedDocumentIndex,
@@ -649,7 +642,10 @@ export function createLinkGraphRoutes(deps: LinkGraphRouteDeps): LinkGraphRoutes
}
}
- const routes: Record<string, (req: IncomingMessage, res: ServerResponse) => Promise<void>> = {
+ // A literal declaration (`satisfies`, never a widening `: Record<...>`
+ // annotation) — the helper's `mutating` key-check needs the literal path
+ // union to survive inference.
+ const routes = {
'/api/backlinks': handleBacklinks,
'/api/backlink-counts': handleBacklinkCounts,
'/api/forward-links': handleForwardLinks,
@@ -659,34 +655,18 @@ export function createLinkGraphRoutes(deps: LinkGraphRouteDeps): LinkGraphRoutes
'/api/hubs': handleHubs,
'/api/tags': handleTagsList,
'/api/suggest-links': handleSuggestLinks,
- };
+ } satisfies ApiRouteRecord;
- const table: ApiRouteTable = {
- resolve(url) {
- const handler = routes[url];
- if (handler) {
- return { template: url, dispatch: (req, res) => handler(req, res) };
- }
- if (url.startsWith('/api/tags/')) {
- const rawName = url.slice('/api/tags/'.length);
- return {
- template: '/api/tags/:name',
- // Empty name (`/api/tags/`): no dispatch — the pipeline's explicit
- // 404 owns it, under the same template the legacy dispatch used.
- dispatch: rawName ? (req, res) => handleTagsForName(req, res, rawName) : undefined,
- };
- }
- return null;
+ // Every route in this group is a read (none rode the legacy
+ // MUTATING_ROUTES loopback/Host gate), so no mutating set is declared.
+ return createApiRouteGroup(routes, {
+ dynamic: {
+ prefix: '/api/tags/',
+ template: '/api/tags/:name',
+ // Empty name (`/api/tags/`): no dispatch — the pipeline's explicit
+ // 404 owns it, under the same template the legacy dispatch used.
+ dispatch: (rawName) =>
+ rawName ? (req, res) => handleTagsForName(req, res, rawName) : undefined,
},
- // Every route in this group is a read (none rode the legacy
- // MUTATING_ROUTES loopback/Host gate).
- isMutating: () => false,
- };
-
- return {
- // `/api/tags/*` (not `:name`) so an empty or slash-containing tail
- // reaches the table exactly like the legacy prefix match did.
- paths: [...Object.keys(routes), '/api/tags/*'],
- table,
- };
+ });
}
diff --git a/packages/server/src/http/skills-sh-routes.test.ts b/packages/server/src/http/skills-sh-routes.test.ts
new file mode 100644
index 000000000..446f45eb2
--- /dev/null
+++ b/packages/server/src/http/skills-sh-routes.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, test } from 'vitest';
+import { loggerFactory } from '../logger.ts';
+import { createSkillsShRoutes } from './skills-sh-routes.ts';
+
+/**
+ * Table-level pins for the skills.sh proxy group's mutating declaration. The
+ * wire cannot pin this: the read half of the DNS-rebinding defense applies
+ * the identical loopback + workspace-Host checks to every `/api/*` request,
+ * so an emptied mutating set changes no composition-suite response — only
+ * which gate (and telemetry tag) fires first. The declared membership is
+ * pinned here directly against the legacy `MUTATING_ROUTES` membership it
+ * reproduces.
+ */
+
+function buildGroup() {
+ return createSkillsShRoutes({
+ log: loggerFactory.getLogger('test'),
+ skillsHome: '/nonexistent-skills-home',
+ projectDir: undefined,
+ contentDir: '/nonexistent-content',
+ resolveSkillDirForRead: () => null,
+ });
+}
+
+describe('createSkillsShRoutes table', () => {
+ test('registers exactly the seven proxy paths', () => {
+ expect([...buildGroup().paths].sort()).toEqual(
+ [
+ '/api/skills/search',
+ '/api/skills/popular',
+ '/api/skills/publisher',
+ '/api/skills/detail',
+ '/api/skills/preview',
+ '/api/skills/discover',
+ '/api/skills/resolve-ref',
+ ].sort(),
+ );
+ });
+
+ test('the clone-egress trio is mutating; the four proxy reads are not', () => {
+ const { table } = buildGroup();
+ for (const path of ['/api/skills/preview', '/api/skills/discover', '/api/skills/resolve-ref']) {
+ expect(table.isMutating(path), path).toBe(true);
+ }
+ for (const path of [
+ '/api/skills/search',
+ '/api/skills/popular',
+ '/api/skills/publisher',
+ '/api/skills/detail',
+ ]) {
+ expect(table.isMutating(path), path).toBe(false);
+ }
+ });
+});
diff --git a/packages/server/src/http/skills-sh-routes.ts b/packages/server/src/http/skills-sh-routes.ts
new file mode 100644
index 000000000..baaabd94d
--- /dev/null
+++ b/packages/server/src/http/skills-sh-routes.ts
@@ -0,0 +1,45 @@
+/**
+ * The skills.sh proxy family — `skills/search`, `skills/popular`,
+ * `skills/publisher`, `skills/detail` (reads) plus `skills/preview`,
+ * `skills/discover`, `skills/resolve-ref` (mutating) — natively routed as one
+ * group. The handler bodies were already lifted into
+ * `skills-sh-handlers.ts`; this factory closes the loop by owning their route
+ * table so the extension's legacy record loses the paths in the same change.
+ *
+ * The preview/discover/resolve-ref trio are read-shaped GETs, but each
+ * triggers an arbitrary `git clone` (network egress) + local SKILL.md reads,
+ * so they ride the loopback/host mutating gate, not the read posture — the
+ * same legacy `MUTATING_ROUTES` membership, declared on the table. The four
+ * proxy reads stay on the read posture.
+ */
+
+import type { SkillsShHandlerDeps } from '../skills-sh-handlers.ts';
+import { createSkillsShHandlers } from '../skills-sh-handlers.ts';
+import { type ApiRouteGroup, createApiRouteGroup } from './api-pipeline.ts';
+
+export type SkillsShRouteDeps = SkillsShHandlerDeps;
+
+export function createSkillsShRoutes(deps: SkillsShRouteDeps): ApiRouteGroup {
+ const {
+ handleSkillsSearch,
+ handleSkillsPopular,
+ handleSkillsPublisher,
+ handleSkillsDetail,
+ handleSkillsPreview,
+ handleSkillsDiscover,
+ handleSkillsResolveRef,
+ } = createSkillsShHandlers(deps);
+
+ return createApiRouteGroup(
+ {
+ '/api/skills/search': handleSkillsSearch,
+ '/api/skills/popular': handleSkillsPopular,
+ '/api/skills/publisher': handleSkillsPublisher,
+ '/api/skills/detail': handleSkillsDetail,
+ '/api/skills/preview': handleSkillsPreview,
+ '/api/skills/discover': handleSkillsDiscover,
+ '/api/skills/resolve-ref': handleSkillsResolveRef,
+ },
+ { mutating: ['/api/skills/preview', '/api/skills/discover', '/api/skills/resolve-ref'] },
+ );
+}
diff --git a/packages/server/src/http/workspace-tools-routes.test.ts b/packages/server/src/http/workspace-tools-routes.test.ts
new file mode 100644
index 000000000..7255447ff
--- /dev/null
+++ b/packages/server/src/http/workspace-tools-routes.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, test } from 'vitest';
+import { loggerFactory } from '../logger.ts';
+import type { SearchService } from '../services/search.ts';
+import { createWorkspaceToolsRoutes } from './workspace-tools-routes.ts';
+
+/**
+ * Table-level pins for the workspace-tools group's mutating declaration.
+ * The wire cannot pin this:
+ * the read half of the DNS-rebinding defense applies the identical loopback +
+ * workspace-Host checks to every `/api/*` request, so an emptied mutating set
+ * changes no composition-suite response — only which gate (and telemetry tag)
+ * fires first. The declared membership is pinned here directly against the
+ * legacy `MUTATING_ROUTES` membership it reproduces, GET arms included.
+ */
+
+function buildGroup() {
+ return createWorkspaceToolsRoutes({
+ contentDir: '/nonexistent-content',
+ projectDir: undefined,
+ skillsHome: '/nonexistent-skills-home',
+ homeDirOverride: '/nonexistent-home',
+ savedThemeLockTimeoutMs: undefined,
+ // Ephemeral keeps the link-preview cache memory-only — constructing the
+ // group must not touch disk.
+ ephemeral: true,
+ log: loggerFactory.getLogger('test'),
+ signalChannel: undefined,
+ // Never dispatched by these pins; the table declaration is what's under test.
+ searchService: {} as SearchService,
+ linkPreviewFetch: undefined,
+ getLinkPreviewsEnabled: undefined,
+ getGeneratedIndexSettingsStatus: undefined,
+ setGeneratedIndexEnabled: undefined,
+ });
+}
+
+describe('createWorkspaceToolsRoutes table', () => {
+ test('registers exactly the six workspace-tool paths', () => {
+ expect([...buildGroup().paths].sort()).toEqual(
+ [
+ '/api/search',
+ '/api/link-preview',
+ '/api/skill-targets',
+ '/api/saved-themes',
+ '/api/saved-theme',
+ '/api/generated-index/settings',
+ ].sort(),
+ );
+ });
+
+ test('legacy MUTATING_ROUTES members are mutating on every verb; the reads are not', () => {
+ const { table } = buildGroup();
+ for (const path of [
+ '/api/skill-targets',
+ '/api/saved-theme',
+ '/api/generated-index/settings',
+ ]) {
+ expect(table.isMutating(path), path).toBe(true);
+ }
+ for (const path of ['/api/search', '/api/link-preview', '/api/saved-themes']) {
+ expect(table.isMutating(path), path).toBe(false);
+ }
+ });
+});
diff --git a/packages/server/src/http/workspace-tools-routes.ts b/packages/server/src/http/workspace-tools-routes.ts
new file mode 100644
index 000000000..c50c72e72
--- /dev/null
+++ b/packages/server/src/http/workspace-tools-routes.ts
@@ -0,0 +1,950 @@
+/**
+ * The workspace-tools group — `/api/search`, `/api/link-preview`,
+ * `/api/skill-targets`, `/api/saved-themes` + `/api/saved-theme`, and
+ * `/api/generated-index/settings` — natively routed together. What the
+ * handlers closed over in the extension arrives as
+ * {@link WorkspaceToolsRouteDeps}, the handler bodies are unchanged, and the
+ * extension composes this group's table into its `nativeApi` handle while
+ * the legacy dispatch record loses the paths in the same change.
+ * `searchService` is constructed in the extension (its inputs — file-index
+ * generation, semantic backend, skills-root resolution — stay there) and is
+ * consumed here by reference.
+ *
+ * The multi-verb paths (`search`, `skill-targets`, `saved-theme`,
+ * `generated-index/settings`) dispatch through the shared `methodRouter`
+ * helper exactly as they did in the legacy record.
+ * `ApiRouteTable.isMutating` is URL-keyed (no method), so a path is mutating
+ * when ANY of its verbs mutates — reproducing the legacy `MUTATING_ROUTES`
+ * membership exactly (`/api/skill-targets` and
+ * `/api/generated-index/settings` ride the mutating gate on GET too, as they
+ * always have). Per-verb granularity would widen the shared pipeline
+ * signature for a telemetry-tag-only difference: the read half of the
+ * DNS-rebinding defense applies the same loopback + workspace-Host checks to
+ * every `/api/*` request, so admission outcomes are identical either way.
+ */
+
+import { resolve } from 'node:path';
+import {
+ EmptyRequestSchema,
+ LinkPreviewRequestSchema,
+ LinkPreviewResponseSchema,
+ SavedThemeDeleteSuccessSchema,
+ SavedThemeSaveRequestSchema,
+ SavedThemeSaveSuccessSchema,
+ SavedThemesListSuccessSchema,
+ SavedThemeUpdateRequestSchema,
+ SavedThemeUpdateSuccessSchema,
+ SearchRequestSchema,
+ type SearchSource,
+ SearchSuccessSchema,
+ SkillTargetsGetSuccessSchema,
+ SkillTargetsPutRequestSchema,
+ SkillTargetsPutSuccessSchema,
+ type WorkspaceSearchIntent,
+ type WorkspaceSearchRanking,
+ type WorkspaceSearchScope,
+} from '@inkeep/open-knowledge-core';
+import { z } from 'zod';
+import { isActivatedSkillRoot, knownSkillRootsFor } from '../in-place-skills.ts';
+import { guardedFetch } from '../link-preview/guarded-fetch.ts';
+import { buildLinkPreviewMetadata, type GuardedFetch } from '../link-preview/metadata.ts';
+import { LinkPreviewCache, type LinkPreviewOutcome } from '../link-preview/preview-cache.ts';
+import { classifyLinkPreviewRequest } from '../link-preview/request-gate.ts';
+import type { PinoLogger } from '../logger.ts';
+import { scanSavedThemes } from '../saved-themes-store.ts';
+import { deleteSavedTheme, saveSavedTheme, updateSavedTheme } from '../saved-themes-write.ts';
+import type { SearchService } from '../services/search.ts';
+import {
+ linkEditorSkillFolder,
+ previewEditorFolderLink,
+ scanSkillFolderStates,
+ unlinkEditorSkillFolder,
+} from '../skill-folder-links.ts';
+import {
+ readFolderExpectations,
+ recordFolderExpectation,
+ recordKnownSkillRoot,
+} from '../skill-placements.ts';
+import { resolveSkillTargets } from '../skill-projection.ts';
+import { type ApiRouteGroup, createApiRouteGroup } from './api-pipeline.ts';
+import { catchErrors } from './catch-errors.ts';
+import { errorResponse } from './error-response.ts';
+import { parseQuery } from './handler-utils.ts';
+import { methodRouter } from './method-router.ts';
+import { withValidation } from './request-validation.ts';
+import { successResponse } from './success-response.ts';
+
+const GeneratedIndexSettingsStatusSchema = z.object({
+ enabled: z.boolean(),
+ active: z.boolean(),
+ git: z.object({
+ state: z.enum(['not-applicable', 'ready', 'missing', 'conflict', 'unavailable']),
+ ownership: z.enum(['open-knowledge', 'existing']).optional(),
+ }),
+ applied: z.boolean().optional(),
+ reason: z.enum(['git-conflict', 'git-unavailable', 'config-write']).optional(),
+});
+const GeneratedIndexSettingsRequestSchema = z.object({ enabled: z.boolean() }).strict();
+
+export type GeneratedIndexSettingsStatus = z.infer<typeof GeneratedIndexSettingsStatusSchema>;
+
+export interface WorkspaceToolsRouteDeps {
+ contentDir: string;
+ projectDir: string | undefined;
+ /** The resolved skills-home root (`homeDirOverride ?? homedir()`). */
+ skillsHome: string;
+ /** Home-dir seam so a rig / embedded host never touches the REAL `~/.ok`. */
+ homeDirOverride: string | undefined;
+ savedThemeLockTimeoutMs: number | undefined;
+ /** No-project ephemeral single-file mode (link-preview cache stays in memory). */
+ ephemeral: boolean | undefined;
+ log: PinoLogger;
+ /** The extension's CC1 change-signal emitter (already system-doc-guarded). */
+ signalChannel: ((channel: 'files' | 'lint-config' | 'comments') => void) | undefined;
+ /**
+ * The extension's search capability service — its inputs (file index +
+ * generation, semantic backend, skills root) stay in the extension, so it is
+ * consumed by reference rather than moved.
+ */
+ searchService: SearchService;
+ /** Test seam for the SSRF-guarded outbound fetch. */
+ linkPreviewFetch: GuardedFetch | undefined;
+ getLinkPreviewsEnabled: (() => boolean) | undefined;
+ /** Read and mutate the config + Git-attribute joint admission state. */
+ getGeneratedIndexSettingsStatus: (() => GeneratedIndexSettingsStatus) | undefined;
+ setGeneratedIndexEnabled:
+ | ((enabled: boolean) => Promise<GeneratedIndexSettingsStatus>)
+ | undefined;
+}
+
+export function createWorkspaceToolsRoutes(deps: WorkspaceToolsRouteDeps): ApiRouteGroup {
+ const {
+ contentDir,
+ projectDir,
+ skillsHome,
+ homeDirOverride,
+ savedThemeLockTimeoutMs,
+ ephemeral,
+ log,
+ signalChannel,
+ searchService,
+ linkPreviewFetch,
+ getLinkPreviewsEnabled,
+ getGeneratedIndexSettingsStatus,
+ setGeneratedIndexEnabled,
+ } = deps;
+
+ // ── Saved themes (`/api/saved-themes` list, `/api/saved-theme` mutations) ──
+ // The store is a user-global folder of scheme files the renderer can't reach;
+ // save/delete/list run here. Discovery is by scan (no live watcher in v1), and
+ // the home is the same `homeDirOverride` seam the skills store uses so tests
+ // isolate against a tempdir without touching `os.homedir()`.
+
+ const handleSavedThemesList = withValidation(
+ EmptyRequestSchema,
+ async (_req, res) => {
+ try {
+ const { entries, truncated } = scanSavedThemes({ homedirOverride: homeDirOverride });
+ // Entries carry their own `ok` discriminator: usable themes ship their
+ // palette for the picker preview; unusable ones ship a warning `code` so
+ // a file the user placed is listed, never silently missing.
+ successResponse(
+ res,
+ 200,
+ SavedThemesListSuccessSchema,
+ { themes: entries, truncated },
+ { handler: 'saved-themes-list' },
+ );
+ } catch (e) {
+ errorResponse(
+ res,
+ 500,
+ 'urn:ok:error:internal-server-error',
+ 'Failed to list saved themes.',
+ {
+ handler: 'saved-themes-list',
+ cause: e,
+ },
+ );
+ }
+ },
+ { handler: 'saved-themes-list', method: 'GET', skipBodyParse: true },
+ );
+
+ const handleSavedThemeSave = withValidation(
+ SavedThemeSaveRequestSchema,
+ async (_req, res, body) => {
+ try {
+ const result = await saveSavedTheme({
+ name: body.name,
+ stem: body.stem,
+ scheme: body.scheme,
+ extension: body.extension,
+ homedirOverride: homeDirOverride,
+ lockTimeoutMs: savedThemeLockTimeoutMs,
+ });
+ if (!result.ok) {
+ if (result.code === 'lock-timeout') {
+ errorResponse(
+ res,
+ 503,
+ 'urn:ok:error:concurrent-operation',
+ 'Saved themes are temporarily busy.',
+ {
+ handler: 'saved-theme-save',
+ detail: result.code,
+ extraHeaders: { 'Retry-After': '5' },
+ },
+ );
+ return;
+ }
+ if (result.code === 'name-taken') {
+ // Refuse-and-prompt: a collision never overwrites prior work.
+ errorResponse(
+ res,
+ 409,
+ 'urn:ok:error:theme-name-taken',
+ 'A saved theme with that name already exists.',
+ { handler: 'saved-theme-save', detail: body.name },
+ );
+ return;
+ }
+ // Restore stems remain strict; a new human-facing name only fails when
+ // it is empty. The specific cause rides `detail` so the save form can
+ // localize the reason.
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:theme-name-invalid',
+ 'That name cannot be used as a theme id.',
+ { handler: 'saved-theme-save', detail: result.code },
+ );
+ return;
+ }
+ successResponse(
+ res,
+ 201,
+ SavedThemeSaveSuccessSchema,
+ { id: result.id, filename: result.filename },
+ { handler: 'saved-theme-save' },
+ );
+ } catch (e) {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to save theme.', {
+ handler: 'saved-theme-save',
+ cause: e,
+ });
+ }
+ },
+ { handler: 'saved-theme-save', method: 'POST' },
+ );
+
+ const handleSavedThemeDelete = withValidation(
+ EmptyRequestSchema,
+ async (req, res) => {
+ try {
+ const id = parseQuery(req).get('id') ?? '';
+ if (id === '') {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Missing theme id.', {
+ handler: 'saved-theme-delete',
+ });
+ return;
+ }
+ const result = await deleteSavedTheme({
+ id,
+ homedirOverride: homeDirOverride,
+ lockTimeoutMs: savedThemeLockTimeoutMs,
+ });
+ if (!result.ok) {
+ if (result.code === 'lock-timeout') {
+ errorResponse(
+ res,
+ 503,
+ 'urn:ok:error:concurrent-operation',
+ 'Saved themes are temporarily busy.',
+ {
+ handler: 'saved-theme-delete',
+ detail: result.code,
+ extraHeaders: { 'Retry-After': '5' },
+ },
+ );
+ return;
+ }
+ const conflict = result.code !== 'invalid-id';
+ errorResponse(
+ res,
+ conflict ? 409 : 400,
+ 'urn:ok:error:invalid-request',
+ 'Cannot delete saved theme.',
+ {
+ handler: 'saved-theme-delete',
+ detail: result.code,
+ },
+ );
+ return;
+ }
+ // Deleting an id that names no file is a benign no-op (`existed: false`),
+ // and deleting one currently assigned to a mode slot is allowed — the
+ // config's read-time fallback makes the dangling reference harmless.
+ successResponse(
+ res,
+ 200,
+ SavedThemeDeleteSuccessSchema,
+ result.existed
+ ? { existed: true, filename: result.filename, scheme: result.scheme }
+ : { existed: false },
+ { handler: 'saved-theme-delete' },
+ );
+ } catch (e) {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to delete theme.', {
+ handler: 'saved-theme-delete',
+ cause: e,
+ });
+ }
+ },
+ { handler: 'saved-theme-delete', method: 'DELETE', skipBodyParse: true },
+ );
+
+ const handleSavedThemeUpdate = withValidation(
+ SavedThemeUpdateRequestSchema,
+ async (_req, res, body) => {
+ try {
+ const result = await updateSavedTheme({
+ id: body.id,
+ scheme: body.scheme,
+ homedirOverride: homeDirOverride,
+ lockTimeoutMs: savedThemeLockTimeoutMs,
+ });
+ if (!result.ok) {
+ if (result.code === 'lock-timeout') {
+ errorResponse(
+ res,
+ 503,
+ 'urn:ok:error:concurrent-operation',
+ 'Saved themes are temporarily busy.',
+ {
+ handler: 'saved-theme-update',
+ detail: result.code,
+ extraHeaders: { 'Retry-After': '5' },
+ },
+ );
+ return;
+ }
+ if (result.code === 'not-found') {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Saved theme not found.', {
+ handler: 'saved-theme-update',
+ });
+ return;
+ }
+ if (result.code === 'ambiguous-id' || result.code === 'unsafe-target') {
+ const message =
+ result.code === 'ambiguous-id'
+ ? 'Multiple saved theme files claim that id.'
+ : 'The saved theme id conflicts with a file that cannot be safely updated.';
+ errorResponse(res, 409, 'urn:ok:error:invalid-request', message, {
+ handler: 'saved-theme-update',
+ detail: result.code,
+ });
+ return;
+ }
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Not a saved theme id.', {
+ handler: 'saved-theme-update',
+ detail: result.code,
+ });
+ return;
+ }
+ successResponse(
+ res,
+ 200,
+ SavedThemeUpdateSuccessSchema,
+ { id: result.id, filename: result.filename },
+ { handler: 'saved-theme-update' },
+ );
+ } catch (e) {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to update theme.', {
+ handler: 'saved-theme-update',
+ cause: e,
+ });
+ }
+ },
+ { handler: 'saved-theme-update', method: 'PUT' },
+ );
+
+ const handleSavedTheme = methodRouter(
+ { POST: handleSavedThemeSave, PUT: handleSavedThemeUpdate, DELETE: handleSavedThemeDelete },
+ { handler: 'saved-theme' },
+ );
+
+ const handleSkillTargetsGet = withValidation(
+ EmptyRequestSchema,
+ async (_req, res) => {
+ try {
+ // Store retirement: the committed `.ok/skill-targets.json` set is dead —
+ // targets are DETECTED from the project's configured editors, and
+ // per-skill reach lives in each skill's install menu.
+ const targets = resolveSkillTargets(projectDir ?? '');
+ // Folder-link receipt vs disk: a recorded expectation that no longer
+ // matches the observed state is DRIFT — passive disclosure only (the
+ // "changed outside" chip); the next explicit verb wins + re-records.
+ const withDrift = (
+ base: string,
+ f: ReturnType<typeof scanSkillFolderStates>[number],
+ ): { drift?: true; expected?: string } => {
+ const exp = readFolderExpectations(base)[f.root];
+ if (exp === undefined) return {};
+ const matches =
+ exp.expect === 'link'
+ ? f.state === 'linked' && f.target === exp.target
+ : f.state === 'own';
+ if (matches) return {};
+ return {
+ drift: true,
+ expected: exp.expect === 'link' ? `link → ${exp.target}` : 'own folder',
+ };
+ };
+ successResponse(
+ res,
+ 200,
+ SkillTargetsGetSuccessSchema,
+ {
+ targets,
+ configured: false,
+ // Only folders OK may actually write to on this machine. A row here
+ // is a destination — the Folders surface links and unlinks it — so a
+ // root under a dotdir that does not exist is an offer to create that
+ // dotdir for a tool the user never installed. Custom roots are always
+ // kept; see `isActivatedSkillRoot`.
+ folders: [
+ ...(projectDir
+ ? scanSkillFolderStates(contentDir, knownSkillRootsFor(contentDir, 'project'))
+ .filter((f) => isActivatedSkillRoot(contentDir, 'project', f.root))
+ .map((f) => ({
+ ...f,
+ scope: 'project' as const,
+ ...withDrift(contentDir, f),
+ }))
+ : []),
+ ...scanSkillFolderStates(skillsHome, knownSkillRootsFor(skillsHome, 'global'))
+ .filter((f) => isActivatedSkillRoot(skillsHome, 'global', f.root))
+ .map((f) => ({
+ ...f,
+ scope: 'global' as const,
+ ...withDrift(skillsHome, f),
+ })),
+ ],
+ },
+ { 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', method: 'GET', skipBodyParse: true },
+ );
+
+ const handleSkillTargetsPut = withValidation(
+ SkillTargetsPutRequestSchema,
+ async (_req, res, body) => {
+ try {
+ {
+ const fa = body.folderAction;
+ const base = fa.scope === 'project' ? contentDir : skillsHome;
+ if (fa.scope === 'project' && !projectDir) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Cannot manage skill folders — no project root is resolved for this server.',
+ { handler: 'skill-targets-put', detail: 'NO_PROJECT_ROOT' },
+ );
+ return;
+ }
+ // DECLARE a new custom root (rows/link-targets from declaration,
+ // not first placement). Shape-validated only — it's a declaration,
+ // not a write; the folder stays absent until something lands there.
+ if (fa.action === 'add-root') {
+ const raw = fa.root.replace(/\\/g, '/');
+ const rel = raw.replace(/\/+$/g, '');
+ const segs = rel.split('/').filter((seg) => seg !== '' && seg !== '.');
+ if (
+ rel === '' ||
+ rel.startsWith('/') ||
+ rel.startsWith('~') ||
+ /^[A-Za-z]:/.test(rel) ||
+ rel.includes('\x00') ||
+ segs.length === 0 ||
+ segs.some((seg) => seg === '..')
+ ) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid folder path.', {
+ handler: 'skill-targets-put',
+ detail: fa.root,
+ });
+ return;
+ }
+ await recordKnownSkillRoot(base, segs.join('/'));
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillTargetsPutSuccessSchema,
+ {
+ targets: resolveSkillTargets(projectDir ?? ''),
+ reprojected: [],
+ bundleHosts: [],
+ removedFrom: [],
+ },
+ { handler: 'skill-targets-put' },
+ );
+ return;
+ }
+ // Folder verbs operate on KNOWN roots only (standard host roots +
+ // ledger-known custom roots) — arbitrary paths never reach the
+ // link/unlink primitives. The link target is an EXPLICIT user pick;
+ // no root is ever assumed.
+ const knownRoots = new Set(
+ knownSkillRootsFor(base, fa.scope)
+ .map((r) => r.root)
+ .filter((r) => !r.startsWith('/') && !r.split('/').includes('..')),
+ );
+ const target = fa.action === 'link' ? (fa.target ?? '') : fa.root;
+ if (
+ !knownRoots.has(fa.root) ||
+ (fa.action === 'link' && (!knownRoots.has(target) || fa.root === target))
+ ) {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Folder and target must be distinct standard skills roots.',
+ { handler: 'skill-targets-put', detail: `${fa.root} -> ${target}` },
+ );
+ return;
+ }
+ // PREVIEW: classify the merge and return it, writing nothing — the
+ // Folders surface discloses what a link moves and deletes before it
+ // asks for it. No receipt, no change signal: nothing changed.
+ if (fa.action === 'link' && fa.preview) {
+ const p = previewEditorFolderLink({
+ base,
+ folderRel: fa.root,
+ targetRootRel: target,
+ });
+ const plan = p.kind === 'plan' ? p.plan : null;
+ successResponse(
+ res,
+ 200,
+ SkillTargetsPutSuccessSchema,
+ {
+ targets: resolveSkillTargets(projectDir ?? ''),
+ reprojected: [],
+ bundleHosts: [],
+ removedFrom: [],
+ preview: {
+ moves: plan
+ ? [...plan.linkedBundlesToMove.map(({ name }) => name), ...plan.toMove]
+ : [],
+ drops: plan?.toDrop ?? [],
+ removes: plan?.removes ?? [],
+ replaces: plan?.liveDestLinks ?? [],
+ conflicts: p.kind === 'conflicts' ? p.conflicts : [],
+ strays: p.kind === 'stray-entries' ? p.strays : [],
+ },
+ },
+ { handler: 'skill-targets-put' },
+ );
+ return;
+ }
+ const result =
+ fa.action === 'link'
+ ? linkEditorSkillFolder({ base, folderRel: fa.root, targetRootRel: target })
+ : unlinkEditorSkillFolder({
+ base,
+ folderRel: fa.root,
+ ...(fa.exclude !== undefined ? { exclude: fa.exclude } : {}),
+ });
+ if (!result.ok) {
+ errorResponse(
+ res,
+ 409,
+ 'urn:ok:error:invalid-request',
+ result.reason === 'conflicts'
+ ? `Cannot link — differing skills exist in both folders: ${(result.conflicts ?? []).join(', ')}. Resolve them first.`
+ : result.reason === 'stray-entries'
+ ? `Cannot link — the folder holds non-skill entries: ${(result.strays ?? []).join(', ')}.`
+ : result.reason === 'partial-move'
+ ? `The merge stopped partway (${(result.moved ?? []).length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${result.error ?? ''})`
+ : result.reason === 'not-linked'
+ ? 'That folder is not a symlink — nothing to unlink.'
+ : 'That folder cannot be linked (it is already a link or the same directory).',
+ { handler: 'skill-targets-put', detail: result.reason },
+ );
+ return;
+ }
+ // RECEIPT: record the expected folder form so an external rewrite
+ // (symlink deleted, re-pointed, or re-materialized) renders a
+ // passive "changed outside" chip. The next explicit verb wins.
+ await recordFolderExpectation(
+ base,
+ fa.root,
+ fa.action === 'link' ? { expect: 'link', target } : { expect: 'own' },
+ );
+ signalChannel?.('files');
+ successResponse(
+ res,
+ 200,
+ SkillTargetsPutSuccessSchema,
+ {
+ targets: resolveSkillTargets(projectDir ?? ''),
+ reprojected: [],
+ bundleHosts: [],
+ removedFrom: [],
+ folder: { moved: result.moved, dropped: result.dropped, linked: result.linked },
+ },
+ { handler: 'skill-targets-put' },
+ );
+ return;
+ }
+ } 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', method: 'PUT' },
+ );
+
+ const handleSkillTargets = methodRouter(
+ { GET: handleSkillTargetsGet, PUT: handleSkillTargetsPut },
+ { handler: 'skill-targets' },
+ );
+
+ function parseSearchRanking(value: unknown): WorkspaceSearchRanking | undefined {
+ return value === 'navigation' || value === 'relevance' ? value : undefined;
+ }
+
+ function parseSearchIntent(value: unknown): WorkspaceSearchIntent {
+ if (value === 'autocomplete' || value === 'full_text' || value === 'omnibar') return value;
+ return 'omnibar';
+ }
+
+ function parseSearchScopes(value: unknown): WorkspaceSearchScope[] | undefined {
+ const rawScopes =
+ typeof value === 'string' ? value.split(',') : Array.isArray(value) ? value : undefined;
+ if (!rawScopes) return undefined;
+ const scopes = rawScopes.filter(
+ (scope): scope is WorkspaceSearchScope =>
+ scope === 'page' || scope === 'folder' || scope === 'content' || scope === 'file',
+ );
+ return scopes.length > 0 ? scopes : undefined;
+ }
+
+ /** Parse the opt-in `semantic` param from a query string / JSON body value. */
+ function parseSemanticParam(value: unknown): boolean | undefined {
+ if (typeof value === 'boolean') return value;
+ if (value === 'true') return true;
+ if (value === 'false') return false;
+ return undefined;
+ }
+
+ /** Resolve the bounded `source` telemetry label; unknown / absent → `http`. */
+ function parseSearchSource(value: unknown): SearchSource {
+ return value === 'omnibar' || value === 'mcp' || value === 'http' ? value : 'http';
+ }
+
+ const handleSearchGet = withValidation(
+ EmptyRequestSchema,
+ 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 searchService.buildSearchResponse({
+ query,
+ intent,
+ ranking,
+ scopes,
+ limit: limitNum,
+ semanticParam,
+ source,
+ });
+ successResponse(res, 200, SearchSuccessSchema, body, { handler: 'search-get' });
+ },
+ { handler: 'search-get', title: 'Failed to search workspace.' },
+ ),
+ { handler: 'search-get', method: 'GET', skipBodyParse: true },
+ );
+
+ const handleSearchPost = withValidation(
+ SearchRequestSchema,
+ 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 searchService.buildSearchResponse({
+ query,
+ intent,
+ ranking,
+ scopes,
+ limit,
+ semanticParam,
+ source,
+ });
+ successResponse(res, 200, SearchSuccessSchema, responseBody, { handler: 'search-post' });
+ },
+ { handler: 'search-post', title: 'Failed to search workspace.' },
+ ),
+ { handler: 'search-post', method: 'POST' },
+ );
+
+ const handleSearch = methodRouter(
+ { GET: handleSearchGet, POST: handleSearchPost },
+ { handler: 'search' },
+ );
+
+ // ───────────────────── Link preview (external hover cards) ─────────────────
+ // Fetches page metadata for an external link on the user's behalf, so it is
+ // guarded on two independent axes: an anti-proxy gate decides WHO may ask, and
+ // the SSRF-guarded fetch decides WHERE the server may reach. The gate refuses
+ // absent / `null` / non-loopback Origins that the shared /api/* allowlist would
+ // wave through, because an admitted caller would be a readable server-side
+ // request-forgery proxy for any local browser tab. Read-only — kept out of
+ // MUTATING_ROUTES.
+ const LINK_PREVIEW_HANDLER = 'link-preview';
+ // Ephemeral single-file mode keeps zero user-dir artifacts, so its cache stays
+ // in memory; otherwise it lives beside the other project-local sidecars.
+ const linkPreviewCacheDir = ephemeral
+ ? null
+ : resolve(projectDir ?? contentDir, '.ok', 'local', 'link-previews');
+ const linkPreviewCache = new LinkPreviewCache({ cacheDir: linkPreviewCacheDir });
+ // Load the disk cache once, lazily, before the first lookup. init() never
+ // throws; serializing it ahead of load() keeps a warm entry from being
+ // clobbered by a late disk read.
+ let linkPreviewCacheInit: Promise<void> | null = null;
+ const ensureLinkPreviewCacheReady = (): Promise<void> => {
+ linkPreviewCacheInit ??= linkPreviewCache.init();
+ return linkPreviewCacheInit;
+ };
+ const linkPreviewFetchImpl: GuardedFetch = linkPreviewFetch ?? guardedFetch;
+
+ // The cache-miss path: one SSRF-guarded page fetch, a bounded head-scan parse,
+ // and a favicon fetch through the SAME chokepoint. Never throws — the guard
+ // and the parser each absorb their own failures into a bounded reason.
+ async function computeLinkPreview(rawUrl: string): Promise<LinkPreviewOutcome> {
+ const fetched = await linkPreviewFetchImpl(rawUrl);
+ if (!fetched.ok) return { ok: false, reason: fetched.reason };
+ const metadata = await buildLinkPreviewMetadata({
+ html: new TextDecoder().decode(fetched.body),
+ requestUrl: rawUrl,
+ finalUrl: fetched.finalUrl,
+ fetch: linkPreviewFetchImpl,
+ });
+ return { ok: true, metadata };
+ }
+
+ // The egress opt-in is enforced HERE, not only in the renderer: the anti-proxy
+ // gate admits ANY loopback http(s) origin by design, so without this check a
+ // second local app could drive outbound fetches while the user has previews
+ // OFF. Fail-closed (absent getter or a throwing read = disabled) and evaluated
+ // fresh per request so a Settings toggle applies without a restart.
+ const linkPreviewsEnabled = (): boolean => {
+ try {
+ return getLinkPreviewsEnabled?.() === true;
+ } catch {
+ return false;
+ }
+ };
+
+ const handleLinkPreview = withValidation(
+ LinkPreviewRequestSchema,
+ async (_req, res, body) => {
+ try {
+ // Checked BEFORE the cache is touched so the disabled path can never
+ // record a negative entry that would outlive re-enabling.
+ if (!linkPreviewsEnabled()) {
+ // Outcome instrumentation: one greppable category per request.
+ // Category ONLY, never the URL, hostname, resolved IP, or fetched
+ // content.
+ log.debug({ outcome: 'disabled' }, '[link-preview] request outcome');
+ successResponse(
+ res,
+ 200,
+ LinkPreviewResponseSchema,
+ { ok: false, reason: 'disabled' },
+ { handler: LINK_PREVIEW_HANDLER },
+ );
+ return;
+ }
+ await ensureLinkPreviewCacheReady();
+ // Side flag on the compute closure: load() invokes compute only on a
+ // cache miss, so hit-vs-computed falls out here without widening the
+ // cache API.
+ let computed = false;
+ const outcome = await linkPreviewCache.load(body.url, () => {
+ computed = true;
+ return computeLinkPreview(body.url);
+ });
+ // Persist is best-effort and never throws; fire-and-forget so a slow disk
+ // write can't stall the response.
+ void linkPreviewCache.persist();
+ // Rejections cross the wire with ONE coarse reason. The granular guard
+ // taxonomy (private-ip / dns-failure / non-html / …) stays in local logs
+ // and the on-disk cache for debugging, but returning it would let a
+ // loopback caller pair chosen hostnames with reasons to enumerate
+ // internal names; the renderer ignores the field either way.
+ const wireOutcome: LinkPreviewOutcome = outcome.ok
+ ? outcome
+ : { ok: false, reason: 'blocked' };
+ // Outcome instrumentation: one greppable category per request
+ // (disabled / cache-hit / fetched-ok / fallback). A negative cache hit
+ // logs cache-hit (served without a fetch). Category ONLY, never the
+ // URL, hostname, resolved IP, or fetched content; the granular
+ // rejection taxonomy is already logged at the guarded-fetch chokepoint.
+ log.debug(
+ { outcome: computed ? (outcome.ok ? 'fetched-ok' : 'fallback') : 'cache-hit' },
+ '[link-preview] request outcome',
+ );
+ successResponse(res, 200, LinkPreviewResponseSchema, wireOutcome, {
+ handler: LINK_PREVIEW_HANDLER,
+ });
+ } catch (e) {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Internal server error.', {
+ handler: LINK_PREVIEW_HANDLER,
+ cause: e,
+ });
+ }
+ },
+ {
+ handler: LINK_PREVIEW_HANDLER,
+ method: 'POST',
+ // Reject a cross-origin / null-origin / non-JSON caller before the body is
+ // read, so a bypass request never reaches the outbound fetch.
+ preBodyGate: (req, res) => {
+ const verdict = classifyLinkPreviewRequest({
+ origin: req.headers.origin,
+ contentType: req.headers['content-type'],
+ });
+ if (verdict.ok) return true;
+ if (verdict.reason === 'origin') {
+ errorResponse(res, 403, 'urn:ok:error:invalid-origin', 'Origin not allowed.', {
+ handler: LINK_PREVIEW_HANDLER,
+ });
+ } else {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Content-Type must be application/json.',
+ { handler: LINK_PREVIEW_HANDLER },
+ );
+ }
+ return false;
+ },
+ },
+ );
+
+ const handleGetGeneratedIndexSettings = withValidation(
+ EmptyRequestSchema,
+ async (_req, res) => {
+ if (!getGeneratedIndexSettingsStatus) {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Not found.', {
+ handler: 'generated-index-settings-get',
+ });
+ return;
+ }
+ successResponse(
+ res,
+ 200,
+ GeneratedIndexSettingsStatusSchema,
+ getGeneratedIndexSettingsStatus(),
+ {
+ handler: 'generated-index-settings-get',
+ extraHeaders: { 'Cache-Control': 'no-store' },
+ },
+ );
+ },
+ { handler: 'generated-index-settings-get', method: 'GET', skipBodyParse: true },
+ );
+
+ const handleSetGeneratedIndexSettings = withValidation(
+ GeneratedIndexSettingsRequestSchema,
+ async (_req, res, body) => {
+ if (!setGeneratedIndexEnabled) {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'Not found.', {
+ handler: 'generated-index-settings-set',
+ });
+ return;
+ }
+ const result = await setGeneratedIndexEnabled(body.enabled);
+ successResponse(res, 200, GeneratedIndexSettingsStatusSchema, result, {
+ handler: 'generated-index-settings-set',
+ extraHeaders: { 'Cache-Control': 'no-store' },
+ });
+ },
+ { handler: 'generated-index-settings-set', method: 'POST' },
+ );
+
+ const handleGeneratedIndexSettings = methodRouter(
+ { GET: handleGetGeneratedIndexSettings, POST: handleSetGeneratedIndexSettings },
+ { handler: 'generated-index-settings' },
+ );
+
+ // Byte-exact legacy `MUTATING_ROUTES` membership for this group. The
+ // multi-verb paths (`skill-targets` GET+PUT, `generated-index/settings`
+ // GET+POST, `saved-theme` POST/PUT/DELETE) are mutating on every verb,
+ // exactly as before the lift; `/api/saved-themes` (GET list),
+ // `/api/search`, and `/api/link-preview` stay on the read posture,
+ // exactly as before.
+ return createApiRouteGroup(
+ {
+ '/api/search': handleSearch,
+ '/api/link-preview': handleLinkPreview,
+ '/api/skill-targets': handleSkillTargets,
+ '/api/saved-themes': handleSavedThemesList,
+ '/api/saved-theme': handleSavedTheme,
+ '/api/generated-index/settings': handleGeneratedIndexSettings,
+ },
+ { mutating: ['/api/skill-targets', '/api/saved-theme', '/api/generated-index/settings'] },
+ );
+}
diff --git a/packages/server/src/server-factory.test.ts b/packages/server/src/server-factory.test.ts
index b21ea3893..1f5ed6838 100644
--- a/packages/server/src/server-factory.test.ts
+++ b/packages/server/src/server-factory.test.ts
@@ -3340,8 +3340,16 @@ describe('createServer() — shouldUnloadDocument forceUnloadSet branched guard'
if (!apiExt) throw new Error('api-extension not found in extensions array');
const { createServer: createNodeHttp } = await import('node:http');
+ // Same production dispatch order as `apiBaseUrl()`'s seam: native
+ // groups first, then the legacy hook — so this driver stays faithful
+ // as routes migrate rather than relying on its target staying
+ // legacy-owned.
+ const nativeApi = server.nativeApi;
localHttp = createNodeHttp((req, res) => {
- void apiExt.onRequest({ request: req, response: res });
+ void (async () => {
+ if (await nativeApi.dispatch(req, res)) return;
+ await apiExt.onRequest({ request: req, response: res });
+ })();
});
await new Promise<void>((resolve) => localHttp?.listen(0, '127.0.0.1', resolve));
const address = localHttp.address();
@@ -3813,8 +3821,16 @@ describe('createServer() — generated index wiring', () => {
if (!apiExt) throw new Error('api-extension not found in extensions array');
const { createServer: createNodeHttp } = await import('node:http');
+ // Mirror the composed production order: natively-routed groups dispatch
+ // ahead of the legacy onRequest catch-all, so ported paths (e.g.
+ // `/api/generated-index/settings`) reach their real handler instead of
+ // the legacy pipeline's 404 fallback.
+ const nativeApi = server?.nativeApi;
localHttp = createNodeHttp((req, res) => {
- void apiExt.onRequest({ request: req, response: res });
+ void (async () => {
+ if (nativeApi !== undefined && (await nativeApi.dispatch(req, res))) return;
+ await apiExt.onRequest({ request: req, response: res });
+ })();
});
await new Promise<void>((resolve) => localHttp?.listen(0, '127.0.0.1', resolve));
const address = localHttp.address();
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index 093c8c79a..4a0f5dbdb 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -61,12 +61,7 @@ import { AcpRegistry, loadCustomAgents } from './acp/registry.ts';
import { AgentFocusBroadcaster } from './agent-focus.ts';
import { AgentPresenceBroadcaster } from './agent-presence.ts';
import { AgentSessionManager } from './agent-sessions.ts';
-import {
- type CommentDocHooks,
- createApiExtension,
- type GeneratedIndexSettingsStatus,
- isSafeDocName,
-} from './api-extension.ts';
+import { type CommentDocHooks, createApiExtension, isSafeDocName } from './api-extension.ts';
import { assetReferencesChanged } from './asset-references.ts';
import { seedBasenameIndex, seedSingleDirBasenameIndex } from './asset-walk.ts';
import {
@@ -170,6 +165,7 @@ import { type HeadWatcherHandle, readProjectHeadState, startHeadWatcher } from '
import { errnoCode } from './http/handler-utils.ts';
import type { NativeApiHandle } from './http/http-app.ts';
import type { LocalApiDispatch } from './http/local-api-dispatch.ts';
+import type { GeneratedIndexSettingsStatus } from './http/workspace-tools-routes.ts';
import {
scanGlobalInPlaceSkills,
scanInPlaceSkillDirs,
diff --git a/packages/server/src/skills-sh-handlers.ts b/packages/server/src/skills-sh-handlers.ts
index 3cadbe522..ac5b6053e 100644
--- a/packages/server/src/skills-sh-handlers.ts
+++ b/packages/server/src/skills-sh-handlers.ts
@@ -1,5 +1,5 @@
/**
- * The six skills.sh discovery handlers, lifted out of `api-extension.ts`.
+ * The seven skills.sh discovery handlers, lifted out of `api-extension.ts`.
*
* Stateless proxy and cache reads: no `session`, no `dc`, no `transact`. What
* they closed over in the extension arrives as {@link SkillsShHandlerDeps} so