Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

PRD-8618: Migrate agent integration apply to native Hono (#4461)

omar-inkeepda9de429d227
diff --git a/knip.config.ts b/knip.config.ts
index c58ed3f2e..802352af8 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -143,10 +143,7 @@ export default {
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],
- ignoreDependencies: [
- '@inkeep/open-knowledge-app', // the CLI's `build:assets` script runs `cp -r ../app/dist dist/public`
- 'yjs',
- ],
+ ignoreDependencies: ['yjs'],
},
'packages/desktop': {
entry: [
diff --git a/packages/app/package.json b/packages/app/package.json
index 09efd2350..1ae9ef568 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -4,6 +4,14 @@
"license": "GPL-3.0-or-later",
"private": true,
"type": "module",
+ "exports": {
+ "./test-support/agent-connections": {
+ "@inkeep/source": "./src/lib/agent-connections.ts",
+ "development": "./src/lib/agent-connections.ts",
+ "types": "./src/lib/agent-connections.ts",
+ "default": "./src/lib/agent-connections.ts"
+ }
+ },
"scripts": {
"predev": "turbo run build --filter=@inkeep/open-knowledge-core --filter=@inkeep/open-knowledge-server && sh scripts/i18n-compile-unless-skipped.sh && node scripts/copy-excalidraw-assets.mjs",
"dev": "vite",
diff --git a/packages/app/src/lib/agent-connections.test.ts b/packages/app/src/lib/agent-connections.test.ts
index 50d138bd7..d4109f4ee 100644
--- a/packages/app/src/lib/agent-connections.test.ts
+++ b/packages/app/src/lib/agent-connections.test.ts
@@ -128,6 +128,67 @@ describe('applyAgentConnectionIntents', () => {
expect(result.report.conflicts[0]?.kind).toBe('unknown-satisfier');
expect(result.snapshot).toEqual(SNAPSHOT);
});
+
+ test('keeps the post-apply snapshot when an action carries an error', async () => {
+ vi.stubGlobal('window', {});
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(
+ async () =>
+ new Response(
+ JSON.stringify({
+ actions: [
+ {
+ satisfierId: 'claude/mcp/project/config-entry',
+ agentId: 'claude',
+ piece: 'mcp',
+ scope: 'project',
+ kind: 'config-entry',
+ desired: 'present',
+ action: 'failed',
+ errorId: 'write-failed',
+ },
+ ],
+ conflicts: [],
+ withheld: [],
+ snapshot: SNAPSHOT,
+ }),
+ { status: 200, headers: { 'Content-Type': 'application/json' } },
+ ),
+ ),
+ );
+
+ const result = await applyAgentConnectionIntents([]);
+
+ expect(result.ok).toBe(false);
+ expect(result.report.actions[0]?.errorId).toBe('write-failed');
+ expect(result.snapshot).toEqual(SNAPSHOT);
+ });
+
+ test('treats withheld work without conflicts or action errors as successful', async () => {
+ vi.stubGlobal('window', {});
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(
+ async () =>
+ new Response(
+ JSON.stringify({
+ actions: [],
+ conflicts: [],
+ withheld: ['claude/mcp/project/config-entry'],
+ snapshot: SNAPSHOT,
+ }),
+ { status: 200, headers: { 'Content-Type': 'application/json' } },
+ ),
+ ),
+ );
+
+ const result = await applyAgentConnectionIntents([]);
+
+ expect(result.ok).toBe(true);
+ expect(result.report.withheld).toEqual(['claude/mcp/project/config-entry']);
+ expect(result.snapshot).toEqual(SNAPSHOT);
+ });
});
describe('what a refused desktop apply carries back', () => {
diff --git a/packages/app/tests/integration/api-error-envelope/agent-integrations-apply.test.ts b/packages/app/tests/integration/api-error-envelope/agent-integrations-apply.test.ts
index 57c085d40..b911fe52e 100644
--- a/packages/app/tests/integration/api-error-envelope/agent-integrations-apply.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/agent-integrations-apply.test.ts
@@ -1,6 +1,14 @@
-import { AgentIntegrationsApplySuccessSchema } from '@inkeep/open-knowledge-core';
+import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ AgentIntegrationsApplySuccessSchema,
+ ProblemDetailsSchema,
+} from '@inkeep/open-knowledge-core';
+import { buildIngressPolicy } from '@inkeep/open-knowledge-server';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
+import { fetchWithHostHeader } from '../host-header-request.test-helper';
import { createTestServer, type TestServer } from '../test-harness';
let server: TestServer;
@@ -24,6 +32,25 @@ afterAll(async () => {
});
describe('agent-integrations apply — a host with no writers injected', () => {
+ test('accepts loose JSON without a Content-Type gate and emits shared success headers', async () => {
+ const res = await fetch(`${base()}/api/agent-integrations/apply`, {
+ method: 'POST',
+ headers: { Origin: 'http://localhost:5173', 'X-Request-Id': 'apply-success-contract' },
+ body: JSON.stringify({
+ intents: [{ satisfierId: CLAUDE_PROJECT_MCP, desired: 'present', futureIntentField: true }],
+ futureRequestField: true,
+ }),
+ });
+ expect(res.status).toBe(200);
+ expect(res.headers.get('content-type')).toBe('application/json');
+ expect(res.headers.get('x-content-type-options')).toBe('nosniff');
+ expect(res.headers.get('x-request-id')).toBe('apply-success-contract');
+ expect(res.headers.get('access-control-allow-origin')).toBe('http://localhost:5173');
+ expect(res.headers.get('access-control-expose-headers')).toContain('x-request-id');
+ const parsed = AgentIntegrationsApplySuccessSchema.parse(await res.json());
+ expect(parsed.actions[0]?.action).toBe('skipped-unsupported');
+ });
+
test('reports every step unwritable rather than failing the request', async () => {
const res = await apply({ intents: [{ satisfierId: CLAUDE_PROJECT_MCP, desired: 'present' }] });
expect(res.status).toBe(200);
@@ -34,6 +61,7 @@ describe('agent-integrations apply — a host with no writers injected', () => {
const step = parsed.data.actions.find((a) => a.satisfierId === CLAUDE_PROJECT_MCP);
expect(step?.action).toBe('skipped-unsupported');
expect(step?.errorId).toBe('no-writer');
+ expect(existsSync(join(server.contentDir, '.mcp.json'))).toBe(false);
});
test('answers an empty batch with a snapshot instead of an error', async () => {
@@ -44,6 +72,8 @@ describe('agent-integrations apply — a host with no writers injected', () => {
expect(parsed.success).toBe(true);
if (!parsed.success) return;
expect(parsed.data.actions).toEqual([]);
+ expect(parsed.data.conflicts).toEqual([]);
+ expect(parsed.data.withheld).toEqual([]);
expect(parsed.data.snapshot.probes.env).toBe('local-web');
});
@@ -57,31 +87,248 @@ describe('agent-integrations apply — a host with no writers injected', () => {
expect(parsed.data.actions).toEqual([]);
expect(parsed.data.conflicts.map((c) => c.kind)).toContain('unknown-satisfier');
});
+
+ test('reports contradictory intents as a conflict without executing an action', async () => {
+ const res = await apply({
+ intents: [
+ { satisfierId: CLAUDE_PROJECT_MCP, desired: 'present' },
+ { satisfierId: CLAUDE_PROJECT_MCP, desired: 'absent' },
+ ],
+ });
+ expect(res.status).toBe(200);
+
+ const parsed = AgentIntegrationsApplySuccessSchema.parse(await res.json());
+ expect(parsed.actions).toEqual([]);
+ expect(parsed.conflicts.map((conflict) => conflict.kind)).toContain('contradictory-intents');
+ });
+
+ test('matches the exact path with a query but not a slash or neighboring path', async () => {
+ const query = await fetch(`${base()}/api/agent-integrations/apply?source=test`, {
+ method: 'POST',
+ body: JSON.stringify({ intents: [] }),
+ });
+ expect(query.status).toBe(200);
+ expect(AgentIntegrationsApplySuccessSchema.safeParse(await query.json()).success).toBe(true);
+
+ for (const suffix of ['/', '-other']) {
+ const res = await fetch(`${base()}/api/agent-integrations/apply${suffix}`, {
+ method: 'POST',
+ body: JSON.stringify({ intents: [] }),
+ });
+ expect(res.status, suffix).toBe(404);
+ const problem = ProblemDetailsSchema.parse(await res.json());
+ expect(problem.type).toBe('urn:ok:error:not-found');
+ }
+ });
});
describe('agent-integrations apply — refusals use the shared envelope', () => {
+ test('rejects an unsupported method before parsing malformed JSON', async () => {
+ const res = await fetch(`${base()}/api/agent-integrations/apply`, {
+ method: 'PATCH',
+ headers: { 'X-Request-Id': 'apply-method-contract' },
+ body: '{',
+ });
+ expect(res.status).toBe(405);
+ expect(res.headers.get('allow')).toBe('POST');
+ expect(res.headers.get('content-type')).toBe('application/problem+json');
+ expect(res.headers.get('x-content-type-options')).toBe('nosniff');
+ expect(res.headers.get('x-request-id')).toBe('apply-method-contract');
+ const body = ProblemDetailsSchema.parse(await res.json());
+ expect(body.type).toBe('urn:ok:error:method-not-allowed');
+ });
+
+ test('preserves HEAD body suppression and admitted preflight handling', async () => {
+ const head = await fetch(`${base()}/api/agent-integrations/apply`, { method: 'HEAD' });
+ expect(head.status).toBe(405);
+ expect(head.headers.get('allow')).toBe('POST');
+ expect(await head.text()).toBe('');
+
+ const options = await fetch(`${base()}/api/agent-integrations/apply`, {
+ method: 'OPTIONS',
+ headers: { Origin: 'http://localhost:5173', 'X-Request-Id': 'apply-preflight' },
+ body: '{',
+ });
+ expect(options.status).toBe(204);
+ expect(options.headers.get('access-control-allow-origin')).toBe('http://localhost:5173');
+ expect(options.headers.get('access-control-allow-methods')).toContain('POST');
+ expect(options.headers.get('x-request-id')).toBe('apply-preflight');
+ expect(await options.text()).toBe('');
+ });
+
test('a body with no intents list is refused with problem+json', async () => {
const res = await apply({});
expect(res.status).toBe(400);
expect(res.headers.get('content-type')).toContain('application/problem+json');
- const body = (await res.json()) as { type?: string; status?: number };
+ expect(res.headers.get('x-content-type-options')).toBe('nosniff');
+ const body = ProblemDetailsSchema.parse(await res.json());
expect(body.type).toMatch(/^urn:ok:error:/);
+ expect(body.title).toBe('Request body is invalid.');
expect(body.status).toBe(400);
});
+ test.each([
+ ['an absent body', undefined, 'Request body is invalid.'],
+ ['malformed JSON', '{', 'Request body is not valid JSON.'],
+ ])('rejects %s with its validation title', async (_label, body, title) => {
+ const res = await fetch(`${base()}/api/agent-integrations/apply`, {
+ method: 'POST',
+ ...(body === undefined ? {} : { body }),
+ });
+ expect(res.status).toBe(400);
+ const problem = ProblemDetailsSchema.parse(await res.json());
+ expect(problem.type).toBe('urn:ok:error:invalid-request');
+ expect(problem.title).toBe(title);
+ });
+
test('an intent that names no artifact is refused with problem+json', async () => {
const res = await apply({ intents: [{ desired: 'present' }] });
expect(res.status).toBe(400);
expect(res.headers.get('content-type')).toContain('application/problem+json');
});
- test('a cross-origin caller is refused before the body is read', async () => {
- const res = await apply(
- { intents: [{ satisfierId: CLAUDE_PROJECT_MCP, desired: 'present' }] },
+ test.each([
+ ['an empty satisfier ID', { intents: [{ satisfierId: '', desired: 'present' }] }],
+ [
+ 'an unsupported desired state',
+ { intents: [{ satisfierId: CLAUDE_PROJECT_MCP, desired: 'later' }] },
+ ],
+ [
+ 'a non-string summary',
+ { intents: [{ satisfierId: CLAUDE_PROJECT_MCP, desired: 'present' }], summary: 42 },
+ ],
+ ])('rejects %s at schema validation', async (_label, body) => {
+ const res = await apply(body);
+ expect(res.status).toBe(400);
+ const problem = ProblemDetailsSchema.parse(await res.json());
+ expect(problem.type).toBe('urn:ok:error:invalid-request');
+ expect(problem.title).toBe('Request body is invalid.');
+ });
+
+ test('rejects a body larger than one mebibyte', async () => {
+ const res = await fetch(`${base()}/api/agent-integrations/apply`, {
+ method: 'POST',
+ body: JSON.stringify({ intents: [], extra: 'x'.repeat(1_048_576) }),
+ });
+ expect(res.status).toBe(413);
+ const problem = ProblemDetailsSchema.parse(await res.json());
+ expect(problem).toMatchObject({
+ type: 'urn:ok:error:payload-too-large',
+ title: 'Payload too large.',
+ status: 413,
+ });
+ });
+
+ test.each([
+ [
+ 'a rebound Host',
+ 'attacker.example',
+ {},
+ 'urn:ok:error:host-not-allowed',
+ 'Host header not allowed.',
+ ],
+ [
+ 'a cross-origin caller',
+ `127.0.0.1`,
{ Origin: 'http://attacker.example' },
- );
+ 'urn:ok:error:invalid-origin',
+ 'Origin not allowed.',
+ ],
+ [
+ 'a forwarding header',
+ `127.0.0.1`,
+ { 'X-Forwarded-For': '203.0.113.8' },
+ 'urn:ok:error:host-not-allowed',
+ 'Proxied request refused: this server has not consented to external exposure. Set OK_EXTERNAL_URL to the public origin and OK_ALLOW_EXTERNAL=1 (or server.externalUrl + server.allowExternal in config), then restart the server.',
+ ],
+ ])('refuses %s before malformed-body parsing', async (_label, host, headers, type, title) => {
+ const res = await fetchWithHostHeader(`${base()}/api/agent-integrations/apply`, host, {
+ method: 'POST',
+ headers,
+ body: '{',
+ });
expect(res.status).toBe(403);
- const body = (await res.json()) as { type?: string };
- expect(body.type).toBe('urn:ok:error:invalid-origin');
+ const body = ProblemDetailsSchema.parse(await res.json());
+ expect(body.type).toBe(type);
+ expect(body.title).toBe(title);
+ expect(existsSync(join(server.contentDir, '.mcp.json'))).toBe(false);
+ });
+
+ test('refuses forwarded preflight at the outer listener', async () => {
+ const res = await fetchWithHostHeader(`${base()}/api/agent-integrations/apply`, '127.0.0.1', {
+ method: 'OPTIONS',
+ headers: {
+ Origin: 'http://localhost:5173',
+ 'X-Forwarded-For': '203.0.113.8',
+ },
+ });
+ expect(res.status).toBe(403);
+ const body = ProblemDetailsSchema.parse(await res.json());
+ expect(body.type).toBe('urn:ok:error:host-not-allowed');
+ });
+
+ test('admits a consented external origin and forwarding metadata before parsing', async () => {
+ const external = await createTestServer({
+ ingressPolicy: buildIngressPolicy({
+ serverRuntime: {
+ bind: ['127.0.0.1'],
+ port: 0,
+ externalUrl: 'https://integrations.example.com',
+ allowExternal: true,
+ openBrowser: false,
+ idleShutdown: 'off',
+ loopbackOnly: false,
+ },
+ }),
+ });
+ try {
+ const res = await fetchWithHostHeader(
+ `http://127.0.0.1:${external.port}/api/agent-integrations/apply`,
+ '127.0.0.1',
+ {
+ method: 'POST',
+ headers: {
+ Origin: 'https://integrations.example.com',
+ 'X-Forwarded-For': '203.0.113.8',
+ },
+ body: '{',
+ },
+ );
+ expect(res.status).toBe(400);
+ const body = ProblemDetailsSchema.parse(await res.json());
+ expect(body).toMatchObject({
+ type: 'urn:ok:error:invalid-request',
+ title: 'Request body is not valid JSON.',
+ });
+ } finally {
+ await external.cleanup();
+ }
+ });
+});
+
+describe('agent-integrations apply — ephemeral admission', () => {
+ test('retains apply without adding a single-file-mode prohibition', async () => {
+ const contentDir = mkdtempSync(join(tmpdir(), 'ok-apply-ephemeral-'));
+ writeFileSync(join(contentDir, 'note.md'), '# Note\n', 'utf8');
+ let ephemeral: TestServer | undefined;
+ try {
+ ephemeral = await createTestServer({
+ contentDir,
+ ephemeral: true,
+ keepContentDir: true,
+ singleDocRelPath: 'note.md',
+ });
+ const res = await fetch(`http://127.0.0.1:${ephemeral.port}/api/agent-integrations/apply`, {
+ method: 'POST',
+ body: JSON.stringify({ intents: [] }),
+ });
+ expect(res.status).toBe(200);
+ const parsed = AgentIntegrationsApplySuccessSchema.parse(await res.json());
+ expect(parsed.actions).toEqual([]);
+ expect(parsed.snapshot.probes.env).toBe('local-web');
+ } finally {
+ await ephemeral?.cleanup();
+ rmSync(contentDir, { recursive: true, force: true });
+ }
});
});
diff --git a/packages/app/tests/integration/test-harness.ts b/packages/app/tests/integration/test-harness.ts
index 99af7df64..3e18b8f3b 100644
--- a/packages/app/tests/integration/test-harness.ts
+++ b/packages/app/tests/integration/test-harness.ts
@@ -69,6 +69,7 @@ export interface TestServer {
}
export interface CreateTestServerOptions {
+ ingressPolicy?: ServerOptions['ingressPolicy'];
debounce?: ServerOptions['debounce'];
maxDebounce?: ServerOptions['maxDebounce'];
stalenessGraceMs?: ServerOptions['stalenessGraceMs'];
@@ -140,6 +141,7 @@ export async function createTestServer(options: CreateTestServerOptions = {}): P
const srv = createServer({
contentDir,
projectDir,
+ ingressPolicy: options.ingressPolicy,
quiet: true,
debounce: options.debounce ?? 200,
maxDebounce: options.maxDebounce ?? 1000,
@@ -177,6 +179,7 @@ export async function createTestServer(options: CreateTestServerOptions = {}): P
httpServer,
hocuspocus: srv.hocuspocus,
nativeApi: srv.nativeApi,
+ ingressPolicy: options.ingressPolicy,
mcpHttpHandler,
log: getLogger('test-harness'),
sessionManager: srv.sessionManager,
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 753a8302b..3d23093b6 100644
--- a/packages/app/tests/meta/native-route-unit-reachability.test.ts
+++ b/packages/app/tests/meta/native-route-unit-reachability.test.ts
@@ -63,6 +63,31 @@ function usesLegacyOnlySeam(source: string): boolean {
return importsServerFactory && !source.includes('nativeApi.dispatch');
}
+function factoryNameForRouteFile(file: string): string {
+ return file
+ .replace('http/', '')
+ .replace('-routes.ts', '')
+ .split('-')
+ .map((segment) => (segment[0] ?? '').toUpperCase() + segment.slice(1))
+ .join('');
+}
+
+function nativeFactoryDivergence(
+ extensionSource: string,
+ routeFiles: readonly string[],
+): { missing: string[]; unexpected: string[] } {
+ const mounted = new Set(
+ [...extensionSource.matchAll(/=\s*create(\w+)Routes\(/g)].flatMap((match) =>
+ match[1] ? [match[1]] : [],
+ ),
+ );
+ const discovered = new Set(routeFiles.map(factoryNameForRouteFile));
+ return {
+ missing: [...discovered].filter((name) => !mounted.has(name)).sort(),
+ unexpected: [...mounted].filter((name) => !discovered.has(name)).sort(),
+ };
+}
+
describe('native-route unit-tier reachability', () => {
test('anti-vacuousness: every route file contributes paths and the inventory is non-trivial', () => {
const { exact, prefixes, perFile } = collectNativePaths();
@@ -77,21 +102,30 @@ describe('native-route unit-tier reachability', () => {
test('the discovered route files and the extension mounts are the same set', () => {
const ext = readFileSync(join(SERVER_SRC_ROOT, 'api-extension.ts'), 'utf8');
- 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(),
+ nativeFactoryDivergence(ext, listNativeRouteFiles(SERVER_SRC_ROOT)),
'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());
+ ).toEqual({ missing: [], unexpected: [] });
+ });
+
+ test('the mount comparison rejects an omitted or renamed discovered factory', () => {
+ const ext = readFileSync(join(SERVER_SRC_ROOT, 'api-extension.ts'), 'utf8');
+ const routeFiles = listNativeRouteFiles(SERVER_SRC_ROOT);
+ const witness = routeFiles.map(factoryNameForRouteFile).sort()[0];
+ if (witness === undefined) throw new Error('no native route factory witness was discovered');
+ const mountedFactory = `create${witness}Routes`;
+ const renamedFactory = `createRenamed${witness}Routes`;
+ const omitted = ext.replace(`= ${mountedFactory}(`, '= buildUnmountedRouteGroup(');
+ if (omitted === ext) throw new Error(`${mountedFactory} mount is absent`);
+ expect(nativeFactoryDivergence(omitted, routeFiles)).toEqual({
+ missing: [witness],
+ unexpected: [],
+ });
+ const renamed = ext.replaceAll(mountedFactory, renamedFactory);
+ expect(nativeFactoryDivergence(renamed, routeFiles)).toMatchObject({
+ missing: [witness],
+ unexpected: expect.arrayContaining([`Renamed${witness}`]),
+ });
});
test('no legacy-only test seam names a natively-owned path', () => {
diff --git a/packages/cli/src/integrations/registry-http-composition.test.ts b/packages/cli/src/integrations/registry-http-composition.test.ts
new file mode 100644
index 000000000..8e7144b85
--- /dev/null
+++ b/packages/cli/src/integrations/registry-http-composition.test.ts
@@ -0,0 +1,182 @@
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { isAbsolute, join, relative, sep } from 'node:path';
+import { applyAgentConnectionIntents } from '@inkeep/open-knowledge-app/test-support/agent-connections';
+import { type ApplyIntent, SatisfierIdSchema } from '@inkeep/open-knowledge-core';
+import { ConfigSchema, MCP_SERVER_NAME, readBundleDecision } from '@inkeep/open-knowledge-server';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { type BootedStartServer, bootStartServer } from '../commands/start.ts';
+
+const AMBIENT_PATH_KEYS = [
+ 'HOME',
+ 'USERPROFILE',
+ 'CODEX_HOME',
+ 'COPILOT_HOME',
+ 'XDG_CONFIG_HOME',
+ 'APPDATA',
+ 'LOCALAPPDATA',
+ 'PI_CODING_AGENT_DIR',
+] as const;
+
+type AmbientPathKey = (typeof AMBIENT_PATH_KEYS)[number];
+
+const CLAUDE_PROJECT_MCP = SatisfierIdSchema.parse('claude/mcp/project/config-entry');
+const COPILOT_PROJECT_MCP = SatisfierIdSchema.parse('copilot/mcp/project/config-entry');
+const CLAUDE_USER_SKILL = SatisfierIdSchema.parse('claude/skill/user/skill-bundle-copy');
+const APPLY_PATH = '/api/agent-integrations/apply';
+
+function isWithin(root: string, candidate: string): boolean {
+ const delta = relative(root, candidate);
+ return delta !== '..' && !delta.startsWith(`..${sep}`) && !isAbsolute(delta);
+}
+
+describe('web apply through the CLI registry host', () => {
+ let projectDir: string;
+ let temporaryHome: string;
+ let booted: BootedStartServer | null;
+ let previousFetch: typeof globalThis.fetch;
+ let previousEnv: ReadonlyArray<readonly [AmbientPathKey, string | undefined]>;
+
+ beforeEach(async () => {
+ projectDir = await mkdtemp(join(tmpdir(), 'ok-registry-http-project-'));
+ temporaryHome = await mkdtemp(join(tmpdir(), 'ok-registry-http-home-'));
+ booted = null;
+ previousFetch = globalThis.fetch;
+ previousEnv = AMBIENT_PATH_KEYS.map((key) => [key, process.env[key]] as const);
+
+ const homePaths = {
+ HOME: temporaryHome,
+ USERPROFILE: temporaryHome,
+ CODEX_HOME: join(temporaryHome, '.codex'),
+ COPILOT_HOME: join(temporaryHome, '.copilot'),
+ XDG_CONFIG_HOME: join(temporaryHome, '.config'),
+ APPDATA: join(temporaryHome, 'AppData', 'Roaming'),
+ LOCALAPPDATA: join(temporaryHome, 'AppData', 'Local'),
+ PI_CODING_AGENT_DIR: join(temporaryHome, '.pi', 'agent'),
+ } as const satisfies Record<AmbientPathKey, string>;
+ for (const key of AMBIENT_PATH_KEYS) process.env[key] = homePaths[key];
+
+ await mkdir(join(projectDir, '.ok'), { recursive: true });
+ await writeFile(join(projectDir, '.ok', 'config.yml'), '');
+ await mkdir(join(temporaryHome, '.claude'), { recursive: true });
+ });
+
+ afterEach(async () => {
+ try {
+ if (booted !== null) await booted.destroy();
+ } finally {
+ globalThis.fetch = previousFetch;
+ for (const [key, value] of previousEnv) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ await Promise.all([
+ rm(projectDir, { recursive: true, force: true }),
+ rm(temporaryHome, { recursive: true, force: true }),
+ ]);
+ }
+ });
+
+ async function bootWithAppFetch(): Promise<void> {
+ booted = await bootStartServer({
+ config: ConfigSchema.parse({}),
+ cwd: projectDir,
+ host: '127.0.0.1',
+ port: 0,
+ skipAutoInit: true,
+ idleThresholdMs: null,
+ });
+ await booted.ready;
+ const loopbackOrigin = `http://127.0.0.1:${booted.port}`;
+ const delegatedFetch = globalThis.fetch;
+ globalThis.fetch = (input, init) => {
+ if (input !== APPLY_PATH) throw new TypeError(`Unexpected fetch target: ${String(input)}`);
+ return delegatedFetch(`${loopbackOrigin}${input}`, init);
+ };
+ }
+
+ test('the app helper writes and observes the real project MCP integration', async () => {
+ const configPath = join(projectDir, '.mcp.json');
+ const unrelatedEntry = { command: 'unrelated-command', args: ['--keep'] };
+ await writeFile(
+ configPath,
+ `${JSON.stringify({ unrelated: { keep: true }, mcpServers: { unrelated: unrelatedEntry } }, null, 2)}\n`,
+ );
+ await bootWithAppFetch();
+ const intent = {
+ satisfierId: CLAUDE_PROJECT_MCP,
+ desired: 'present',
+ } as const satisfies ApplyIntent;
+
+ const result = await applyAgentConnectionIntents([intent]);
+
+ expect(result.ok).toBe(true);
+ expect(
+ result.report.actions.find((action) => action.satisfierId === CLAUDE_PROJECT_MCP),
+ ).toMatchObject({ action: expect.stringMatching(/^(written|overwritten)$/) });
+ expect(result.snapshot?.probes.satisfiers[CLAUDE_PROJECT_MCP]?.state).toBe('satisfied');
+ expect(JSON.parse(await readFile(configPath, 'utf8'))).toMatchObject({
+ unrelated: { keep: true },
+ mcpServers: {
+ unrelated: unrelatedEntry,
+ [MCP_SERVER_NAME]: expect.any(Object),
+ },
+ });
+ const writtenBytes = await readFile(configPath, 'utf8');
+
+ const repeated = await applyAgentConnectionIntents([intent]);
+
+ expect(repeated.ok).toBe(true);
+ expect(
+ repeated.report.actions.find((action) => action.satisfierId === CLAUDE_PROJECT_MCP),
+ ).toMatchObject({ action: expect.stringMatching(/^(unchanged|no-op)$/) });
+ expect(await readFile(configPath, 'utf8')).toBe(writtenBytes);
+
+ const removed = await applyAgentConnectionIntents([
+ { satisfierId: CLAUDE_PROJECT_MCP, desired: 'absent' },
+ { satisfierId: COPILOT_PROJECT_MCP, desired: 'absent' },
+ ]);
+
+ expect(removed.ok).toBe(true);
+ expect(
+ removed.report.actions.find((action) => action.satisfierId === CLAUDE_PROJECT_MCP),
+ ).toMatchObject({ action: 'removed' });
+ expect(removed.snapshot?.probes.satisfiers[CLAUDE_PROJECT_MCP]?.state).toBe('absent');
+ expect(removed.snapshot?.probes.satisfiers[COPILOT_PROJECT_MCP]?.state).toBe('absent');
+ expect(JSON.parse(await readFile(configPath, 'utf8'))).toEqual({
+ unrelated: { keep: true },
+ mcpServers: { unrelated: unrelatedEntry },
+ });
+ expect(isWithin(projectDir, configPath)).toBe(true);
+ expect(AMBIENT_PATH_KEYS.every((key) => isWithin(temporaryHome, process.env[key] ?? ''))).toBe(
+ true,
+ );
+ });
+
+ test('the app helper installs the real user skill and records its decision', async () => {
+ await bootWithAppFetch();
+ const skillPath = join(
+ temporaryHome,
+ '.claude',
+ 'skills',
+ 'open-knowledge-discovery',
+ 'SKILL.md',
+ );
+ const decisionPath = join(temporaryHome, '.ok', 'skill-state.yml');
+
+ const result = await applyAgentConnectionIntents([
+ { satisfierId: CLAUDE_USER_SKILL, desired: 'present' },
+ ]);
+
+ expect(result.ok).toBe(true);
+ expect(
+ result.report.actions.find((action) => action.satisfierId === CLAUDE_USER_SKILL),
+ ).toMatchObject({ action: expect.stringMatching(/^(written|overwritten)$/) });
+ expect(result.snapshot?.probes.satisfiers[CLAUDE_USER_SKILL]?.state).toBe('satisfied');
+ expect((await readFile(skillPath, 'utf8')).length).toBeGreaterThan(0);
+ expect((await readFile(decisionPath, 'utf8')).length).toBeGreaterThan(0);
+ expect(await readBundleDecision(temporaryHome, 'open-knowledge-discovery')).toBe(true);
+ expect(isWithin(temporaryHome, skillPath)).toBe(true);
+ expect(isWithin(temporaryHome, decisionPath)).toBe(true);
+ });
+});
diff --git a/packages/server/src/api-agent-integrations-composition.test.ts b/packages/server/src/api-agent-integrations-composition.test.ts
new file mode 100644
index 000000000..33a59cd8c
--- /dev/null
+++ b/packages/server/src/api-agent-integrations-composition.test.ts
@@ -0,0 +1,296 @@
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { connect } from 'node:net';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ AgentIntegrationsApplySuccessSchema,
+ type ProbeResolver,
+ type StepExecutor,
+} from '@inkeep/open-knowledge-core';
+import { afterEach, expect, test } from 'vitest';
+import type { AgentRegistryHostSeam } from './agent-registry-apply.ts';
+import type { BootedServer } from './boot.ts';
+import {
+ assertPathAbsentFromLegacyRegistry,
+ bootCompositionRig,
+ parseProblem,
+ rawRequest,
+} from './composition-rig.test-helper.ts';
+
+const APPLY_PATH = '/api/agent-integrations/apply';
+const CLAUDE_PROJECT_MCP = 'claude/mcp/project/config-entry';
+const COPILOT_PROJECT_MCP = 'copilot/mcp/project/config-entry';
+const COPILOT_PROJECT_SKILL = 'copilot/skill/project/skill-bundle-copy';
+const COPILOT_USER_MCP = 'copilot/mcp/user/config-entry';
+const SEEDED_CONFIG = '{\n "unrelated": { "keep": true }\n}\n';
+
+interface ApplyCompositionFixture {
+ readonly root: string;
+ readonly contentDir: string;
+ readonly configPath: string;
+ readonly server: BootedServer;
+}
+
+const fixtures: ApplyCompositionFixture[] = [];
+
+function assertExclusiveNativeOwnership(server: BootedServer): void {
+ expect(server.serverInstance.nativeApi.paths.filter((path) => path === APPLY_PATH)).toHaveLength(
+ 1,
+ );
+ const source = readFileSync(new URL('./api-extension.ts', import.meta.url), 'utf8');
+ assertPathAbsentFromLegacyRegistry(source, APPLY_PATH);
+}
+
+async function bootApplyComposition(
+ agentIntegrations: AgentRegistryHostSeam,
+): Promise<ApplyCompositionFixture> {
+ const root = mkdtempSync(join(tmpdir(), 'ok-agent-integrations-composition-'));
+ const contentDir = join(root, 'project');
+ const configPath = join(contentDir, '.mcp.json');
+ mkdirSync(contentDir);
+ writeFileSync(configPath, SEEDED_CONFIG, 'utf8');
+ let server: BootedServer;
+ try {
+ server = await bootCompositionRig(contentDir, { agentIntegrations });
+ } catch (error) {
+ rmSync(root, { recursive: true, force: true });
+ throw error;
+ }
+ try {
+ await server.ready;
+ assertExclusiveNativeOwnership(server);
+ } catch (error) {
+ try {
+ await server.destroy();
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ throw error;
+ }
+ const fixture = { root, contentDir, configPath, server };
+ fixtures.push(fixture);
+ return fixture;
+}
+
+async function postIntents(server: BootedServer, intents: readonly unknown[]) {
+ return rawRequest(server.port, APPLY_PATH, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ intents }),
+ });
+}
+
+function settleWithin<T>(promise: Promise<T>, label: string): Promise<T> {
+ return new Promise((resolvePromise, reject) => {
+ const timeout = setTimeout(() => reject(new Error(`timed out waiting for ${label}`)), 4_000);
+ promise.then(
+ (value) => {
+ clearTimeout(timeout);
+ resolvePromise(value);
+ },
+ (error: unknown) => {
+ clearTimeout(timeout);
+ reject(error);
+ },
+ );
+ });
+}
+
+function observeNextRequest(server: BootedServer): Promise<{
+ readonly partialBodyBytes: Promise<number>;
+ readonly completedOnClose: Promise<boolean>;
+}> {
+ return new Promise((resolveRequest) => {
+ server.httpServer.once('request', (request) => {
+ const partialBodyBytes = new Promise<number>((resolveBytes) => {
+ request.once('data', (chunk: Buffer) => resolveBytes(chunk.length));
+ });
+ const completedOnClose = new Promise<boolean>((resolveComplete) => {
+ request.once('close', () => resolveComplete(request.complete));
+ });
+ resolveRequest({ partialBodyBytes, completedOnClose });
+ });
+ });
+}
+
+async function interruptPartialApply(server: BootedServer): Promise<{
+ readonly acceptedBytes: number;
+ readonly completed: boolean;
+}> {
+ const observedRequest = observeNextRequest(server);
+ const socket = connect(server.port, '127.0.0.1');
+ await settleWithin(
+ new Promise<void>((resolveConnected, reject) => {
+ socket.once('connect', resolveConnected);
+ socket.once('error', reject);
+ }),
+ 'socket connection',
+ );
+ const body = `{"intents":[{"satisfierId":"${CLAUDE_PROJECT_MCP}","desired":"present"}`;
+ const request = [
+ `POST ${APPLY_PATH} HTTP/1.1`,
+ `Host: 127.0.0.1:${server.port}`,
+ 'Content-Type: application/json',
+ `Content-Length: ${Buffer.byteLength(body) + 128}`,
+ '',
+ body,
+ ].join('\r\n');
+ socket.write(request);
+ const lifecycle = await settleWithin(observedRequest, 'request acceptance');
+ const acceptedBytes = await settleWithin(lifecycle.partialBodyBytes, 'partial request body');
+ socket.destroy();
+ const completed = await settleWithin(lifecycle.completedOnClose, 'incomplete request close');
+ return { acceptedBytes, completed };
+}
+
+afterEach(async () => {
+ const current = fixtures.splice(0);
+ const destroyed = await Promise.allSettled(current.map(({ server }) => server.destroy()));
+ for (const { root } of current) rmSync(root, { recursive: true, force: true });
+ const failures = destroyed.flatMap((result) =>
+ result.status === 'rejected' ? [result.reason] : [],
+ );
+ if (failures.length > 0)
+ throw new AggregateError(failures, 'composition fixture teardown failed');
+});
+
+test('independent integration work continues after an executor failure', async () => {
+ let executionStarted = false;
+ const executionOrder: string[] = [];
+ const probe: ProbeResolver = (item) => {
+ if (executionStarted) throw new Error('host probes unavailable');
+ return { state: item.satisfierId === COPILOT_USER_MCP ? 'satisfied' : 'absent' };
+ };
+ const execute: StepExecutor = (step) => {
+ executionStarted = true;
+ executionOrder.push(step.satisfierId);
+ if (step.satisfierId === CLAUDE_PROJECT_MCP) throw new Error('first write failed');
+ return { action: 'written' };
+ };
+ const { server } = await bootApplyComposition({ probe, execute });
+
+ const response = await postIntents(server, [
+ { satisfierId: CLAUDE_PROJECT_MCP, desired: 'present' },
+ { satisfierId: COPILOT_PROJECT_SKILL, desired: 'present' },
+ ]);
+
+ expect(response.status).toBe(200);
+ const result = AgentIntegrationsApplySuccessSchema.parse(JSON.parse(response.body));
+ expect(executionOrder).toEqual([CLAUDE_PROJECT_MCP, COPILOT_PROJECT_SKILL]);
+ expect(
+ result.actions.map(({ satisfierId, action, errorId }) => ({ satisfierId, action, errorId })),
+ ).toEqual([
+ {
+ satisfierId: CLAUDE_PROJECT_MCP,
+ action: 'failed',
+ errorId: 'executor-threw',
+ },
+ {
+ satisfierId: COPILOT_PROJECT_SKILL,
+ action: 'written',
+ errorId: undefined,
+ },
+ ]);
+ expect(result.snapshot.probes.env).toBe('local-web');
+ expect(Object.keys(result.snapshot.probes.satisfiers).length).toBeGreaterThan(0);
+ expect(
+ Object.values(result.snapshot.probes.satisfiers).every(({ state }) => state === 'unprobed'),
+ ).toBe(true);
+});
+
+test('a shared project entry is withheld while another owner still uses it', async () => {
+ const executionOrder: string[] = [];
+ const probe: ProbeResolver = (item) => ({
+ state:
+ item.satisfierId === CLAUDE_PROJECT_MCP || item.satisfierId === COPILOT_PROJECT_MCP
+ ? 'satisfied'
+ : 'absent',
+ });
+ const execute: StepExecutor = (step) => {
+ executionOrder.push(step.satisfierId);
+ return { action: 'removed' };
+ };
+ const { server, configPath } = await bootApplyComposition({ probe, execute });
+
+ const response = await postIntents(server, [
+ { satisfierId: CLAUDE_PROJECT_MCP, desired: 'absent' },
+ ]);
+
+ expect(response.status).toBe(200);
+ const result = AgentIntegrationsApplySuccessSchema.parse(JSON.parse(response.body));
+ expect(result.actions).toEqual([]);
+ expect(result.conflicts.map(({ kind }) => kind)).toContain('unresolved-shared-copy');
+ expect(result.withheld).toContain(CLAUDE_PROJECT_MCP);
+ expect(executionOrder).toEqual([]);
+ expect(readFileSync(configPath, 'utf8')).toBe(SEEDED_CONFIG);
+});
+
+test('admission, method, and schema refusals prevent integration execution', async () => {
+ let executionCount = 0;
+ const { server, configPath } = await bootApplyComposition({
+ probe: () => ({ state: 'absent' }),
+ execute: () => {
+ executionCount += 1;
+ return { action: 'written' };
+ },
+ });
+ const malformedWrite = `{"intents":[{"satisfierId":"${CLAUDE_PROJECT_MCP}","desired":"present"}`;
+
+ const rejectedHost = await rawRequest(server.port, APPLY_PATH, {
+ method: 'POST',
+ headers: { Host: 'evil.example', 'Content-Type': 'application/json' },
+ body: malformedWrite,
+ });
+ expect(rejectedHost.status).toBe(403);
+ expect(parseProblem(rejectedHost.body).type).toBe('urn:ok:error:host-not-allowed');
+
+ const rejectedMethod = await rawRequest(server.port, APPLY_PATH, {
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json' },
+ body: malformedWrite,
+ });
+ expect(rejectedMethod.status).toBe(405);
+ expect(rejectedMethod.headers.allow).toBe('POST');
+ expect(parseProblem(rejectedMethod.body).type).toBe('urn:ok:error:method-not-allowed');
+
+ const rejectedBody = await rawRequest(server.port, APPLY_PATH, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ intents: [{ satisfierId: CLAUDE_PROJECT_MCP, desired: 'present' }],
+ summary: 7,
+ }),
+ });
+ expect(rejectedBody.status).toBe(400);
+ expect(parseProblem(rejectedBody.body)).toMatchObject({
+ type: 'urn:ok:error:invalid-request',
+ title: 'Request body is invalid.',
+ });
+ expect(executionCount).toBe(0);
+ expect(readFileSync(configPath, 'utf8')).toBe(SEEDED_CONFIG);
+});
+
+test('an interrupted partial apply has no effect and the listener stays usable', async () => {
+ let executionCount = 0;
+ const { server, configPath } = await bootApplyComposition({
+ probe: () => ({ state: 'absent' }),
+ execute: () => {
+ executionCount += 1;
+ return { action: 'written' };
+ },
+ });
+
+ const interrupted = await interruptPartialApply(server);
+
+ expect(interrupted.acceptedBytes).toBeGreaterThan(0);
+ expect(interrupted.completed).toBe(false);
+ expect(executionCount).toBe(0);
+ expect(readFileSync(configPath, 'utf8')).toBe(SEEDED_CONFIG);
+
+ const nextResponse = await postIntents(server, []);
+ expect(nextResponse.status).toBe(200);
+ const nextResult = AgentIntegrationsApplySuccessSchema.parse(JSON.parse(nextResponse.body));
+ expect(nextResult.actions).toEqual([]);
+ expect(executionCount).toBe(0);
+ expect(readFileSync(configPath, 'utf8')).toBe(SEEDED_CONFIG);
+}, 15_000);
diff --git a/packages/server/src/api-agent-write-native-preservation.test.ts b/packages/server/src/api-agent-write-native-preservation.test.ts
index 66f04878e..7fb1750e7 100644
--- a/packages/server/src/api-agent-write-native-preservation.test.ts
+++ b/packages/server/src/api-agent-write-native-preservation.test.ts
@@ -3,7 +3,12 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterAll, beforeAll, expect, test } from 'vitest';
import type { BootedServer } from './boot.ts';
-import { bootCompositionRig, parseProblem, rawRequest } from './composition-rig.test-helper.ts';
+import {
+ assertPathAbsentFromLegacyRegistry,
+ bootCompositionRig,
+ parseProblem,
+ rawRequest,
+} from './composition-rig.test-helper.ts';
const READS = ['/api/agent-activity', '/api/agent-burst-diff'];
const WRITES = [
@@ -27,8 +32,8 @@ const RESIDUAL = [
'/api/lint/markdownlint-config',
'/api/lint/frontmatter-schema',
'/api/lint/fix',
- '/api/agent-integrations/apply',
];
+const AGENT_INTEGRATIONS_APPLY = '/api/agent-integrations/apply';
let root: string;
let enabled: BootedServer;
let disabled: BootedServer;
@@ -58,6 +63,9 @@ test('native ownership is exclusive and the remaining legacy registry matches it
expect(server.serverInstance.nativeApi.paths.filter((entry) => entry === path)).toHaveLength(
1,
);
+ expect(
+ server.serverInstance.nativeApi.paths.filter((entry) => entry === AGENT_INTEGRATIONS_APPLY),
+ ).toHaveLength(1);
for (const path of RESIDUAL) expect(server.serverInstance.nativeApi.paths).not.toContain(path);
}
for (const path of TEST_PATHS) {
@@ -65,12 +73,11 @@ test('native ownership is exclusive and the remaining legacy registry matches it
expect(disabled.serverInstance.nativeApi.paths).not.toContain(path);
}
const source = readFileSync(new URL('./api-extension.ts', import.meta.url), 'utf8');
- const registry = source.match(/const routes:[\s\S]*?= (\{[\s\S]*?\n {2}\});/)?.[1];
- expect(registry).toBeDefined();
+ const registry = assertPathAbsentFromLegacyRegistry(source, AGENT_INTEGRATIONS_APPLY);
- expect(
- [...(registry?.matchAll(/'([^']*\/api\/[^']*)'/g) ?? [])].map((match) => match[1]).sort(),
- ).toEqual([...RESIDUAL].sort());
+ expect([...registry.matchAll(/'([^']*\/api\/[^']*)'/g)].map((match) => match[1]).sort()).toEqual(
+ [...RESIDUAL].sort(),
+ );
});
test('ingress rejects every migrated route before method or malformed-body admission', async () => {
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 94c995a78..6813cc6be 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -1,3 +1,4 @@
+import { createAgentIntegrationsRoutes } from './http/agent-integrations-routes.ts';
import { createAgentWriteRoutes } from './http/agent-write-routes.ts';
import { createTestRoutes } from './http/test-routes.ts';
@@ -18,13 +19,10 @@ import type { IncomingMessage, ServerResponse } from 'node:http';
import { homedir } from 'node:os';
import { dirname, extname, join, relative, resolve, sep } from 'node:path';
import type { Document, Extension, Hocuspocus } from '@hocuspocus/server';
-import type { EnvTier } from '@inkeep/open-knowledge-core';
import {
type AdvisoryWarning,
AGENT_ICON_COLORS,
AGENTS_SKILLS_ROOT,
- AgentIntegrationsApplyRequestSchema,
- AgentIntegrationsApplySuccessSchema,
AgentWriteBatchRequestSchema,
AgentWriteBatchSuccessSchema,
AgentWriteRequestSchema,
@@ -85,8 +83,7 @@ import type { AcpRegistry, CustomAgentEntry } from './acp/registry.ts';
import { captureEffect } from './activity-log.ts';
import type { AgentFocusBroadcaster } from './agent-focus.ts';
import type { AgentPresenceBroadcaster } from './agent-presence.ts';
-import { type AgentRegistryHostSeam, applyAgentRegistryIntents } from './agent-registry-apply.ts';
-import { collectServerHostSnapshot } from './agent-registry-probes.ts';
+import type { AgentRegistryHostSeam } from './agent-registry-apply.ts';
import {
AgentSessionCapacityError,
type AgentSessionManager,
@@ -251,7 +248,6 @@ import {
import { withParentLock } from './git-handle.ts';
import { type ApiRouteTable, createApiRequestPipeline } from './http/api-pipeline.ts';
import { createAssetRoutes } from './http/asset-routes.ts';
-import { catchErrors } from './http/catch-errors.ts';
import { createCommentRoutes } from './http/comment-routes.ts';
import { createConfigSystemRoutes } from './http/config-system-routes.ts';
import { createDocumentRoutes } from './http/document-routes.ts';
@@ -309,7 +305,6 @@ import type { GuardedFetch } from './link-preview/metadata.ts';
import {
checkLocalOpSecurity as checkLocalOpSecurityBase,
createConcurrencyGuard,
- isLoopbackRequest,
} from './local-op-security.ts';
import { localTargetInventoryFromIndexes } from './local-target-inventory.ts';
import { getLogger } from './logger.ts';
@@ -4528,62 +4523,6 @@ export function createApiExtension(
});
searchService.prewarm();
- const handleAgentIntegrationsApply = withValidation(
- AgentIntegrationsApplyRequestSchema,
- catchErrors(
- async (req, res, body) => {
- const bodyObj = body as unknown as Record<string, unknown>;
- const actor = extractActorIdentity(bodyObj, getPrincipal);
- if (actor.kind === 'invalid-summary') {
- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
- handler: 'agent-integrations-apply',
- });
- return;
- }
-
- const envTier: EnvTier = isLoopbackRequest(req) ? 'local-web' : 'remote-web';
- const { report, snapshot } = await applyAgentRegistryIntents(body.intents, {
- execute: agentIntegrations?.execute,
- env: envTier,
- snapshot: () =>
- collectServerHostSnapshot({ env: envTier, resolve: agentIntegrations?.probe }),
- decisionHome: homeDirOverride ?? homedir(),
- ...(agentIntegrations?.userSkillPresentAnywhere !== undefined
- ? { userSkillPresentAnywhere: agentIntegrations.userSkillPresentAnywhere }
- : {}),
- projectDir,
- });
-
- log.info(
- {
- actor: actor.kind,
- applied: report.actions.length,
- failed: report.actions.filter((action) => action.errorId !== undefined).length,
- conflicts: report.conflicts.map((conflict) => conflict.kind),
- },
- '[agent-integrations] batch applied',
- );
-
- successResponse(
- res,
- 200,
- AgentIntegrationsApplySuccessSchema,
- { ...report, snapshot },
- { handler: 'agent-integrations-apply' },
- );
- },
- {
- handler: 'agent-integrations-apply',
- title: 'Failed to apply AI tool connections.',
- },
- ),
- {
- handler: 'agent-integrations-apply',
- method: 'POST',
- preBodyGate: (req, res) =>
- checkLocalOpSecurity(req, res, { handler: 'agent-integrations-apply' }),
- },
- );
let lintConfigEpoch = 0;
function signalLintConfigChanged(): void {
lintConfigEpoch += 1;
@@ -5050,7 +4989,6 @@ export function createApiExtension(
'/api/lint/fix': handleLintFix,
'/api/agent-write': handleAgentWrite,
'/api/agent-write-batch': handleAgentWriteBatch,
- '/api/agent-integrations/apply': handleAgentIntegrationsApply,
};
const MUTATING_ROUTES: ReadonlySet<string> = new Set([
@@ -5064,7 +5002,6 @@ export function createApiExtension(
'/api/test-rescan-backlinks',
'/api/test-rescan-files',
'/api/skill/uninstall',
- '/api/agent-integrations/apply',
]);
const apiRouteTable: ApiRouteTable = {
@@ -5410,6 +5347,14 @@ export function createApiExtension(
mutateFileIndex,
});
const assetRoutes = createAssetRoutes({ assetService, log });
+ const agentIntegrationsRoutes = createAgentIntegrationsRoutes({
+ log,
+ checkLocalOpSecurity,
+ getPrincipal,
+ homeDirOverride,
+ projectDir,
+ agentIntegrations,
+ });
const handoffInstallRoutes = createHandoffInstallRoutes({ checkLocalOpSecurity });
const skillsInstallRoutes = createSkillsInstallRoutes({
resolveSkillsRoot,
@@ -5525,6 +5470,7 @@ export function createApiExtension(
});
const nativeGroups = [
assetRoutes,
+ agentIntegrationsRoutes,
agentWriteRoutes,
...(enableTestRoutes ? [testRoutes] : []),
skillsTrackingRoutes,
diff --git a/packages/server/src/composition-rig.test-helper.ts b/packages/server/src/composition-rig.test-helper.ts
index 3c9f6be6a..a0431aeb7 100644
--- a/packages/server/src/composition-rig.test-helper.ts
+++ b/packages/server/src/composition-rig.test-helper.ts
@@ -8,6 +8,16 @@ import { OK_DIR } from '@inkeep/open-knowledge-core';
import { type BootedServer, type BootServerOptions, bootServer } from './boot.ts';
import { ConfigSchema } from './config/schema.ts';
+const LEGACY_ROUTE_REGISTRY_PATTERN = /const routes:[\s\S]*?= (\{[\s\S]*?\n {2}\});/;
+
+export function assertPathAbsentFromLegacyRegistry(source: string, path: string): string {
+ const registry = source.match(LEGACY_ROUTE_REGISTRY_PATTERN)?.[1];
+ if (registry === undefined) throw new Error('legacy route registry declaration is absent');
+ if (registry.includes(`'${path}'`))
+ throw new Error(`${path} remains in the legacy route registry`);
+ return registry;
+}
+
function seedOkScaffold(projectDir: string): void {
const okDir = resolve(projectDir, OK_DIR);
mkdirSync(okDir, { recursive: true });
diff --git a/packages/server/src/http/agent-integrations-routes.test.ts b/packages/server/src/http/agent-integrations-routes.test.ts
new file mode 100644
index 000000000..14ce5ff0c
--- /dev/null
+++ b/packages/server/src/http/agent-integrations-routes.test.ts
@@ -0,0 +1,347 @@
+import { IncomingMessage } from 'node:http';
+import { Socket } from 'node:net';
+import {
+ AgentIntegrationsApplySuccessSchema,
+ type Principal,
+ type StepExecutor,
+} from '@inkeep/open-knowledge-core';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { makeCaptureRes, parseProblem } from '../composition-rig.test-helper.ts';
+import { buildIngressPolicy, type IngressPolicy } from '../ingress-policy.ts';
+import { checkLocalOpSecurity } from '../local-op-security.ts';
+import { loggerFactory } from '../logger.ts';
+import { createAgentIntegrationsRoutes } from './agent-integrations-routes.ts';
+import { type ApiRouteGroup, createApiRequestPipeline } from './api-pipeline.ts';
+
+type AgentIntegrationsRouteDeps = Parameters<typeof createAgentIntegrationsRoutes>[0];
+
+function buildGroup(overrides: Partial<AgentIntegrationsRouteDeps> = {}) {
+ return createAgentIntegrationsRoutes({
+ log: loggerFactory.getLogger('test'),
+ checkLocalOpSecurity: () => true,
+ getPrincipal: undefined,
+ homeDirOverride: undefined,
+ projectDir: undefined,
+ agentIntegrations: undefined,
+ ...overrides,
+ });
+}
+
+const APPLY_PATH = '/api/agent-integrations/apply';
+
+const EXTERNAL_POLICY = buildIngressPolicy({
+ serverRuntime: {
+ bind: ['127.0.0.1'],
+ port: 0,
+ externalUrl: 'https://integrations.example.com',
+ allowExternal: true,
+ openBrowser: false,
+ idleShutdown: 'off',
+ loopbackOnly: false,
+ },
+});
+
+const FIXTURE_PRINCIPAL = {
+ id: 'principal-real',
+ display_name: 'Project User',
+ display_email: '[email protected]',
+ source: 'synthesized',
+ created_at: '2026-09-10T00:00:00.000Z',
+} satisfies Principal;
+
+const ACTOR_CASES = [
+ {
+ label: 'agent identity takes precedence over the server principal',
+ body: { agentId: 'codex-actor', principalId: 'principal-spoof' },
+ getPrincipal: () => FIXTURE_PRINCIPAL,
+ expectedActor: 'agent',
+ forbiddenExecutorValues: ['codex-actor', 'principal-real', 'principal-spoof'],
+ },
+ {
+ label: 'the server principal supplies identity when agent identity is absent',
+ body: { principalId: 'principal-spoof' },
+ getPrincipal: () => FIXTURE_PRINCIPAL,
+ expectedActor: 'principal',
+ forbiddenExecutorValues: ['principal-real', 'principal-spoof'],
+ },
+ {
+ label: 'body principal identity is ignored when the server has no principal',
+ body: { principalId: 'principal-spoof' },
+ getPrincipal: undefined,
+ expectedActor: 'anonymous',
+ forbiddenExecutorValues: ['principal-spoof'],
+ },
+] satisfies readonly {
+ readonly label: string;
+ readonly body: Readonly<Record<string, unknown>>;
+ readonly getPrincipal: AgentIntegrationsRouteDeps['getPrincipal'];
+ readonly expectedActor: 'agent' | 'principal' | 'anonymous';
+ readonly forbiddenExecutorValues: readonly string[];
+}[];
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+type RequestOptions = {
+ readonly method?: string;
+ readonly host?: string;
+ readonly remoteAddress?: string;
+ readonly headers?: Readonly<Record<string, string>>;
+};
+
+function makeRequestBytes(body: string, options: RequestOptions = {}): IncomingMessage {
+ const req = new IncomingMessage(new Socket());
+ req.push(Buffer.from(body));
+ req.push(null);
+ req.method = options.method ?? 'POST';
+ req.url = '/api/agent-integrations/apply';
+ req.headers = {
+ host: options.host ?? '127.0.0.1',
+ 'content-type': 'application/json',
+ ...options.headers,
+ };
+ Object.defineProperty(req.socket, 'remoteAddress', {
+ value: options.remoteAddress ?? '127.0.0.1',
+ });
+ return req;
+}
+
+function makeRequest(body: unknown, options: RequestOptions = {}): IncomingMessage {
+ return makeRequestBytes(JSON.stringify(body), options);
+}
+
+async function dispatchThroughPipeline(
+ group: ApiRouteGroup,
+ request: IncomingMessage,
+ policy: IngressPolicy,
+ log = loggerFactory.getLogger('agent-integrations-pipeline-test'),
+) {
+ const pipeline = createApiRequestPipeline({ log, policy, table: group.table });
+ const { res, captured } = makeCaptureRes();
+ const handled = await pipeline(request, res);
+ return { captured, handled };
+}
+
+describe('createAgentIntegrationsRoutes table', () => {
+ test('owns only the exact apply path and classifies it as mutating', () => {
+ const group = buildGroup();
+ expect(group.paths).toEqual(['/api/agent-integrations/apply']);
+ expect(group.table.resolve('/api/agent-integrations/apply')?.dispatch).toBeDefined();
+ expect(group.table.isMutating('/api/agent-integrations/apply')).toBe(true);
+ for (const path of ['/api/agent-integrations/apply/', '/api/agent-integrations/other']) {
+ expect(group.table.resolve(path), path).toBeNull();
+ expect(group.table.isMutating(path), path).toBe(false);
+ }
+ });
+
+ test('uses the remote socket tier and leaves user-scope probes unprobed', async () => {
+ const probedScopes: string[] = [];
+ const group = buildGroup({
+ checkLocalOpSecurity: (req, res, opts) =>
+ checkLocalOpSecurity(req, res, { ...opts, policy: EXTERNAL_POLICY }),
+ agentIntegrations: {
+ probe: (item) => {
+ probedScopes.push(item.scope);
+ return { state: 'absent' };
+ },
+ },
+ });
+ const request = makeRequest(
+ { intents: [] },
+ { remoteAddress: '203.0.113.8', host: 'integrations.example.com' },
+ );
+
+ expect(group.paths.filter((path) => path === APPLY_PATH)).toHaveLength(1);
+ expect(group.table.isMutating(APPLY_PATH)).toBe(true);
+ const { captured, handled } = await dispatchThroughPipeline(group, request, EXTERNAL_POLICY);
+
+ expect(handled).toBe(true);
+ expect(captured.status, captured.body).toBe(200);
+ const parsed = AgentIntegrationsApplySuccessSchema.parse(JSON.parse(captured.body));
+ expect(parsed.snapshot.probes.env).toBe('remote-web');
+ expect(parsed.snapshot.probes.satisfiers['claude/skill/user/skill-bundle-copy']).toEqual({
+ state: 'unprobed',
+ });
+ expect(probedScopes).not.toContain('user');
+ expect(request.headers['x-forwarded-for']).toBeUndefined();
+ });
+
+ test.each(['127.0.0.1', '::1', '::ffff:127.0.0.1'])(
+ 'uses the local tier for loopback socket %s despite forwarded metadata',
+ async (remoteAddress) => {
+ const policy = buildIngressPolicy({});
+ const probedScopes: string[] = [];
+ const group = buildGroup({
+ checkLocalOpSecurity: (req, res, opts) =>
+ checkLocalOpSecurity(req, res, { ...opts, policy }),
+ agentIntegrations: {
+ probe: (item) => {
+ probedScopes.push(item.scope);
+ return { state: 'absent' };
+ },
+ },
+ });
+ const request = makeRequest(
+ { intents: [] },
+ {
+ remoteAddress,
+ headers: { 'x-forwarded-for': '203.0.113.8' },
+ },
+ );
+
+ const { captured, handled } = await dispatchThroughPipeline(group, request, policy);
+
+ expect(handled).toBe(true);
+ expect(captured.status, captured.body).toBe(200);
+ const parsed = AgentIntegrationsApplySuccessSchema.parse(JSON.parse(captured.body));
+ expect(parsed.snapshot.probes.env).toBe('local-web');
+ expect(probedScopes).toContain('user');
+ },
+ );
+
+ test.each(ACTOR_CASES)('$label', async (actorCase) => {
+ const policy = buildIngressPolicy({});
+ const log = loggerFactory.getLogger(`agent-integrations-${actorCase.expectedActor}-test`);
+ const info = vi.spyOn(log, 'info');
+ const executorCalls: Parameters<StepExecutor>[] = [];
+ const execute: StepExecutor = (...args) => {
+ executorCalls.push(args);
+ return { action: 'written' };
+ };
+ const group = buildGroup({
+ log,
+ getPrincipal: actorCase.getPrincipal,
+ checkLocalOpSecurity: (req, res, opts) => checkLocalOpSecurity(req, res, { ...opts, policy }),
+ agentIntegrations: {
+ execute,
+ probe: () => ({ state: 'absent' }),
+ },
+ });
+ const request = makeRequest({
+ intents: [{ satisfierId: 'claude/mcp/project/config-entry', desired: 'present' }],
+ ...actorCase.body,
+ });
+
+ const { captured, handled } = await dispatchThroughPipeline(group, request, policy, log);
+
+ expect(handled).toBe(true);
+ expect(captured.status, captured.body).toBe(200);
+ const parsed = AgentIntegrationsApplySuccessSchema.parse(JSON.parse(captured.body));
+ expect(parsed.actions).toEqual([
+ expect.objectContaining({
+ satisfierId: 'claude/mcp/project/config-entry',
+ action: 'written',
+ }),
+ ]);
+ expect(executorCalls).toHaveLength(1);
+ expect(executorCalls[0]).toHaveLength(1);
+ const step = executorCalls[0]?.[0];
+ expect(step).not.toHaveProperty('actor');
+ expect(step).not.toHaveProperty('principalId');
+ expect(step).not.toHaveProperty('writerId');
+ const serializedStep = JSON.stringify(step);
+ for (const forbidden of actorCase.forbiddenExecutorValues) {
+ expect(serializedStep).not.toContain(forbidden);
+ }
+ expect(info).toHaveBeenCalledTimes(1);
+ expect(info).toHaveBeenCalledWith(
+ {
+ actor: actorCase.expectedActor,
+ applied: 1,
+ failed: 0,
+ conflicts: [],
+ },
+ '[agent-integrations] batch applied',
+ );
+ });
+
+ test('runs the policy-bound local-operation gate before malformed body parsing', async () => {
+ const strictPolicy = buildIngressPolicy({});
+ let gateCalls = 0;
+ let executorCalls = 0;
+ const group = buildGroup({
+ checkLocalOpSecurity: (req, res, opts) => {
+ gateCalls += 1;
+ return checkLocalOpSecurity(req, res, { ...opts, policy: strictPolicy });
+ },
+ agentIntegrations: {
+ execute: () => {
+ executorCalls += 1;
+ return { action: 'written' };
+ },
+ },
+ });
+ const request = makeRequestBytes('{"intents":[', {
+ remoteAddress: '203.0.113.8',
+ host: 'integrations.example.com',
+ });
+
+ const { captured, handled } = await dispatchThroughPipeline(group, request, EXTERNAL_POLICY);
+
+ expect(handled).toBe(true);
+ expect(captured.status, captured.body).toBe(403);
+ expect(parseProblem(captured.body)).toMatchObject({
+ type: 'urn:ok:error:loopback-required',
+ title: 'Local-op endpoints require a loopback connection.',
+ });
+ expect(gateCalls).toBe(1);
+ expect(executorCalls).toBe(0);
+ expect(request.readableEnded).toBe(false);
+ request.destroy();
+ });
+
+ test('rejects a nonstring summary before actor extraction and execution', async () => {
+ const policy = buildIngressPolicy({});
+ const log = loggerFactory.getLogger('agent-integrations-summary-schema-test');
+ const info = vi.spyOn(log, 'info');
+ let principalReads = 0;
+ let executorCalls = 0;
+ const group = buildGroup({
+ log,
+ getPrincipal: () => {
+ principalReads += 1;
+ return FIXTURE_PRINCIPAL;
+ },
+ checkLocalOpSecurity: (req, res, opts) => checkLocalOpSecurity(req, res, { ...opts, policy }),
+ agentIntegrations: {
+ execute: () => {
+ executorCalls += 1;
+ return { action: 'written' };
+ },
+ probe: () => ({ state: 'absent' }),
+ },
+ });
+ const request = makeRequest({
+ intents: [{ satisfierId: 'claude/mcp/project/config-entry', desired: 'present' }],
+ agentId: 'codex-actor',
+ summary: 42,
+ });
+
+ const { captured, handled } = await dispatchThroughPipeline(group, request, policy, log);
+
+ expect(handled).toBe(true);
+ expect(captured.status, captured.body).toBe(400);
+ expect(parseProblem(captured.body)).toMatchObject({
+ type: 'urn:ok:error:invalid-request',
+ title: 'Request body is invalid.',
+ });
+ expect(principalReads).toBe(0);
+ expect(executorCalls).toBe(0);
+ expect(info).not.toHaveBeenCalled();
+ });
+
+ test('dispatches the real apply handler and returns the flat success report', async () => {
+ const resolution = buildGroup().table.resolve('/api/agent-integrations/apply');
+ if (!resolution?.dispatch) throw new Error('apply route did not resolve');
+ const { res, captured } = makeCaptureRes();
+ await resolution.dispatch(makeRequest({ intents: [] }), res);
+ expect(captured.status).toBe(200);
+ const parsed = AgentIntegrationsApplySuccessSchema.parse(JSON.parse(captured.body));
+ expect(parsed.actions).toEqual([]);
+ expect(parsed.conflicts).toEqual([]);
+ expect(parsed.withheld).toEqual([]);
+ expect(parsed.snapshot.probes.env).toBe('local-web');
+ expect(captured.body).not.toContain('"report"');
+ });
+});
diff --git a/packages/server/src/http/agent-integrations-routes.ts b/packages/server/src/http/agent-integrations-routes.ts
new file mode 100644
index 000000000..896e50ef5
--- /dev/null
+++ b/packages/server/src/http/agent-integrations-routes.ts
@@ -0,0 +1,104 @@
+import type { IncomingMessage, ServerResponse } from 'node:http';
+import { homedir } from 'node:os';
+import {
+ AgentIntegrationsApplyRequestSchema,
+ AgentIntegrationsApplySuccessSchema,
+ type EnvTier,
+ type Principal,
+} from '@inkeep/open-knowledge-core';
+import { type AgentRegistryHostSeam, applyAgentRegistryIntents } from '../agent-registry-apply.ts';
+import { collectServerHostSnapshot } from '../agent-registry-probes.ts';
+import { extractActorIdentity } from '../extract-actor-identity.ts';
+import { isLoopbackRequest } from '../local-op-security.ts';
+import type { PinoLogger } from '../logger.ts';
+import { type ApiRouteGroup, createApiRouteGroup } from './api-pipeline.ts';
+import { catchErrors } from './catch-errors.ts';
+import { errorResponse } from './error-response.ts';
+import { withValidation } from './request-validation.ts';
+import { successResponse } from './success-response.ts';
+
+export interface AgentIntegrationsRouteDeps {
+ log: PinoLogger;
+ checkLocalOpSecurity: (
+ req: IncomingMessage,
+ res: ServerResponse,
+ opts: { handler: string },
+ ) => boolean;
+ getPrincipal: (() => Principal | null) | undefined;
+ homeDirOverride: string | undefined;
+ projectDir: string | undefined;
+ agentIntegrations: AgentRegistryHostSeam | undefined;
+}
+
+export function createAgentIntegrationsRoutes(deps: AgentIntegrationsRouteDeps): ApiRouteGroup {
+ const {
+ log,
+ checkLocalOpSecurity,
+ getPrincipal,
+ homeDirOverride,
+ projectDir,
+ agentIntegrations,
+ } = deps;
+
+ const handleAgentIntegrationsApply = withValidation(
+ AgentIntegrationsApplyRequestSchema,
+ catchErrors(
+ async (req, res, body) => {
+ const bodyObj = body as unknown as Record<string, unknown>;
+ const actor = extractActorIdentity(bodyObj, getPrincipal);
+ if (actor.kind === 'invalid-summary') {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
+ handler: 'agent-integrations-apply',
+ });
+ return;
+ }
+
+ const envTier: EnvTier = isLoopbackRequest(req) ? 'local-web' : 'remote-web';
+ const { report, snapshot } = await applyAgentRegistryIntents(body.intents, {
+ execute: agentIntegrations?.execute,
+ env: envTier,
+ snapshot: () =>
+ collectServerHostSnapshot({ env: envTier, resolve: agentIntegrations?.probe }),
+ decisionHome: homeDirOverride ?? homedir(),
+ ...(agentIntegrations?.userSkillPresentAnywhere !== undefined
+ ? { userSkillPresentAnywhere: agentIntegrations.userSkillPresentAnywhere }
+ : {}),
+ projectDir,
+ });
+
+ log.info(
+ {
+ actor: actor.kind,
+ applied: report.actions.length,
+ failed: report.actions.filter((action) => action.errorId !== undefined).length,
+ conflicts: report.conflicts.map((conflict) => conflict.kind),
+ },
+ '[agent-integrations] batch applied',
+ );
+
+ successResponse(
+ res,
+ 200,
+ AgentIntegrationsApplySuccessSchema,
+ { ...report, snapshot },
+ { handler: 'agent-integrations-apply' },
+ );
+ },
+ {
+ handler: 'agent-integrations-apply',
+ title: 'Failed to apply AI tool connections.',
+ },
+ ),
+ {
+ handler: 'agent-integrations-apply',
+ method: 'POST',
+ preBodyGate: (req, res) =>
+ checkLocalOpSecurity(req, res, { handler: 'agent-integrations-apply' }),
+ },
+ );
+
+ return createApiRouteGroup(
+ { '/api/agent-integrations/apply': handleAgentIntegrationsApply },
+ { mutating: ['/api/agent-integrations/apply'] },
+ );
+}
diff --git a/packages/server/src/http/handler-equivalence.test-helper.ts b/packages/server/src/http/handler-equivalence.test-helper.ts
new file mode 100644
index 000000000..57c7969dc
--- /dev/null
+++ b/packages/server/src/http/handler-equivalence.test-helper.ts
@@ -0,0 +1,58 @@
+import { type Node, Project, SyntaxKind, ts } from 'ts-morph';
+
+export type NormalizedSyntax = readonly [kind: string, value: string | readonly NormalizedSyntax[]];
+
+function readHandlerDeclaration(source: string, handlerName: string): Node {
+ const project = new Project({
+ useInMemoryFileSystem: true,
+ skipFileDependencyResolution: true,
+ skipLoadingLibFiles: true,
+ skipAddingFilesFromTsConfig: true,
+ compilerOptions: { noLib: true },
+ });
+ const sourceFile = project.createSourceFile('handler.ts', source);
+ const declaration = sourceFile
+ .getDescendantsOfKind(SyntaxKind.VariableDeclaration)
+ .find((candidate) => candidate.getName() === handlerName);
+ if (declaration === undefined) throw new Error(`${handlerName} is absent`);
+ const statement = declaration.getFirstAncestorByKind(SyntaxKind.VariableStatement);
+ if (statement === undefined) throw new Error(`${handlerName} has no statement`);
+ return statement;
+}
+
+function normalizeSyntax(node: Node): NormalizedSyntax {
+ const children = node
+ .getChildren()
+ .filter(
+ (child) =>
+ child.getKind() !== SyntaxKind.SingleLineCommentTrivia &&
+ child.getKind() !== SyntaxKind.MultiLineCommentTrivia,
+ );
+ return children.length === 0
+ ? [node.getKindName(), node.getText()]
+ : [node.getKindName(), children.map(normalizeSyntax)];
+}
+
+export function normalizedHandler(source: string, handlerName: string): NormalizedSyntax {
+ return normalizeSyntax(readHandlerDeclaration(source, handlerName));
+}
+
+export function orderedComments(source: string, handlerName: string): string[] {
+ const declaration = readHandlerDeclaration(source, handlerName).getFullText();
+ const scanner = ts.createScanner(
+ ts.ScriptTarget.Latest,
+ false,
+ ts.LanguageVariant.Standard,
+ declaration,
+ );
+ const comments: string[] = [];
+ for (let kind = scanner.scan(); kind !== ts.SyntaxKind.EndOfFileToken; kind = scanner.scan()) {
+ if (
+ kind === ts.SyntaxKind.SingleLineCommentTrivia ||
+ kind === ts.SyntaxKind.MultiLineCommentTrivia
+ ) {
+ comments.push(scanner.getTokenText());
+ }
+ }
+ return comments;
+}
diff --git a/packages/server/src/http/handler-equivalence.test.ts b/packages/server/src/http/handler-equivalence.test.ts
new file mode 100644
index 000000000..39d25c3fb
--- /dev/null
+++ b/packages/server/src/http/handler-equivalence.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, test } from 'vitest';
+import { normalizedHandler, orderedComments } from './handler-equivalence.test-helper.ts';
+
+const HANDLER_NAME = 'handleExample';
+const BASELINE = `
+ const handleExample = () => {
+ /* first */
+ const value = 'two spaces';
+ return value;
+ };
+`;
+
+describe('handler equivalence test helper', () => {
+ test('normalizes syntax formatting without weakening literal comparisons', () => {
+ const reformatted = `const handleExample=()=>{/* first */const value='two spaces';return value;};`;
+ const changedLiteral = BASELINE.replace('two spaces', 'two spaces');
+ expect(normalizedHandler(reformatted, HANDLER_NAME)).toEqual(
+ normalizedHandler(BASELINE, HANDLER_NAME),
+ );
+ expect(normalizedHandler(changedLiteral, HANDLER_NAME)).not.toEqual(
+ normalizedHandler(BASELINE, HANDLER_NAME),
+ );
+ });
+
+ test('compares ordered comments independently from syntax', () => {
+ const changedComment = BASELINE.replace('first', 'changed');
+ expect(normalizedHandler(changedComment, HANDLER_NAME)).toEqual(
+ normalizedHandler(BASELINE, HANDLER_NAME),
+ );
+ expect(orderedComments(changedComment, HANDLER_NAME)).not.toEqual(
+ orderedComments(BASELINE, HANDLER_NAME),
+ );
+ });
+
+ test('fails when the requested declaration is absent', () => {
+ expect(() => normalizedHandler('const other = 1;', HANDLER_NAME)).toThrow(
+ 'handleExample is absent',
+ );
+ });
+});
diff --git a/packages/server/src/package-exports.test.ts b/packages/server/src/package-exports.test.ts
index 6eb707b37..67c162853 100644
--- a/packages/server/src/package-exports.test.ts
+++ b/packages/server/src/package-exports.test.ts
@@ -3,6 +3,7 @@ import { resolve } from 'node:path';
import { describe, expect, test } from 'vitest';
interface ExportEntry {
+ '@inkeep/source'?: string;
development?: string;
types?: string;
node?: string;
@@ -63,3 +64,25 @@ describe('dev-boot mechanism — predev hook + dist exports', () => {
});
}
});
+
+describe('app test-support exports', () => {
+ test('keep source-only conditions aligned', () => {
+ const testSupportExports = Object.entries(readPkg('app').exports).filter(([subpath]) =>
+ subpath.startsWith('./test-support/'),
+ );
+ expect(testSupportExports.length).toBeGreaterThan(0);
+ for (const [subpath, entry] of testSupportExports) {
+ expect(Object.keys(entry), `app exports["${subpath}"] condition order`).toEqual([
+ '@inkeep/source',
+ 'development',
+ 'types',
+ 'default',
+ ]);
+ for (const condition of ['development', 'types', 'default'] as const) {
+ expect(entry[condition], `app exports["${subpath}"] source vs ${condition}`).toBe(
+ entry['@inkeep/source'],
+ );
+ }
+ }
+ });
+});
diff --git a/turbo.json b/turbo.json
index 45753f3f5..ecf825233 100644
--- a/turbo.json
+++ b/turbo.json
@@ -85,6 +85,7 @@
"tests/integration/idb-preload.ts",
"../../test-support/*.ts",
"../test-support/*.ts",
+ "../app/package.json",
"../../oxlint.config.ts",
"../../lint-plugins/**"
]