Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

PRD-8033: Prevent MCP launcher conflicts from blocking sync (#3586)

mike-inkeep55f96a72d8bb
diff --git a/knip.config.ts b/knip.config.ts
index 78162ec09..f9179f2d4 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -123,7 +123,9 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],
project: 'src/**',
- ignoreDependencies: ['@types/shell-quote'],
+ ignoreDependencies: [
+ '@types/shell-quote',
+ ],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],
diff --git a/packages/cli/src/commands/init.test.ts b/packages/cli/src/commands/init.test.ts
index f7847b6d5..93356c586 100644
--- a/packages/cli/src/commands/init.test.ts
+++ b/packages/cli/src/commands/init.test.ts
@@ -259,7 +259,7 @@ describe('runInit', () => {
expect(config.mcpServers['open-knowledge']).toEqual(PUBLISHED_CHAIN_ENTRY);
});
- it('replaces user-added fields instead of merging them', async () => {
+ it('preserves user-added fields while updating the managed launcher', async () => {
writeFileSync(
claudeConfigPath(),
JSON.stringify(
@@ -283,10 +283,14 @@ describe('runInit', () => {
expect(result.editors[0].action).toBe('overwritten');
const config = JSON.parse(readFileSync(claudeConfigPath(), 'utf-8'));
- expect(config.mcpServers['open-knowledge']).toEqual(PUBLISHED_CHAIN_ENTRY);
+ expect(config.mcpServers['open-knowledge']).toEqual({
+ ...PUBLISHED_CHAIN_ENTRY,
+ cwd: testDir,
+ env: { OK_MODE: 'local' },
+ });
});
- it('overwrites a published MCP entry in dev mode', async () => {
+ it('updates only the managed launcher when switching a published entry to dev mode', async () => {
writeFileSync(
claudeConfigPath(),
JSON.stringify(
@@ -309,7 +313,10 @@ describe('runInit', () => {
expect(result.editors[0].action).toBe('overwritten');
const config = JSON.parse(readFileSync(claudeConfigPath(), 'utf-8'));
- expect(config.mcpServers['open-knowledge']).toEqual(expectedDevMcpEntry());
+ expect(config.mcpServers['open-knowledge']).toEqual({
+ command: expectedDevMcpEntry().command,
+ args: expectedDevMcpEntry().args,
+ });
});
it('does not touch ~/.claude.json when --no-mcp is passed', async () => {
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index 5a1de8870..8f22df498 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -17,7 +17,10 @@ import { existsSync, mkdirSync, readFileSync, realpathSync, statSync } from 'nod
import { homedir } from 'node:os';
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
import { inspect } from 'node:util';
-import { OPENKNOWLEDGE_SKILLS_REPO } from '@inkeep/open-knowledge-core';
+import {
+ type McpLauncherDeclineReason,
+ OPENKNOWLEDGE_SKILLS_REPO,
+} from '@inkeep/open-knowledge-core';
import { atomicWriteFileSync, withFileLockSync } from '@inkeep/open-knowledge-core/server';
import type {
BundleId,
@@ -218,6 +221,23 @@ function jsonValueEqual(a: unknown, b: unknown): boolean {
return false;
}
+const STANDARD_MANAGED_ENTRY_KEYS = ['command', 'args'] as const;
+const OPENCODE_MANAGED_ENTRY_KEYS = ['type', 'command'] as const;
+
+function managedEntryKeys(entry: Record<string, unknown>): readonly string[] {
+ return entry.type === 'local' && Array.isArray(entry.command)
+ ? OPENCODE_MANAGED_ENTRY_KEYS
+ : STANDARD_MANAGED_ENTRY_KEYS;
+}
+
+function managedEntryFieldsEqual(
+ existing: unknown,
+ desired: Record<string, unknown>,
+ keys: readonly string[],
+): boolean {
+ return isObject(existing) && keys.every((key) => jsonValueEqual(existing[key], desired[key]));
+}
+
/**
* Detect the indentation a JSON/JSONC file already uses so a surgically-inserted
* entry matches its convention. jsonc-parser's `modify` formats only the
@@ -330,7 +350,8 @@ function upsertJsonMcpConfig(
const container = readServerContainer(root, topLevelKey, subKey);
const existing = isObject(container) ? container[serverName] : undefined;
const entryExists = existing !== undefined;
- if (entryExists && jsonValueEqual(existing, entry)) {
+ const managedKeys = managedEntryKeys(entry);
+ if (entryExists && managedEntryFieldsEqual(existing, entry, managedKeys)) {
// Already present and current: skip the write so the file never churns on an
// idempotent re-run.
return { kind: 'overwritten' };
@@ -341,10 +362,21 @@ function upsertJsonMcpConfig(
const hasBom = raw.charCodeAt(0) === 0xfeff;
const body = hasBom ? raw.slice(1) : raw;
const eol = body.includes('\r\n') ? '\r\n' : '\n';
- const edits = modifyJsonc(body, serverMapPath(topLevelKey, subKey, serverName), entry, {
- formattingOptions: { ...detectJsonIndent(body), eol },
- });
- const newText = `${hasBom ? '\uFEFF' : ''}${applyJsoncEdits(body, edits)}`;
+ const formattingOptions = { ...detectJsonIndent(body), eol };
+ const entryPath = serverMapPath(topLevelKey, subKey, serverName);
+ let editedBody = body;
+ if (entryExists && isObject(existing)) {
+ for (const key of managedKeys) {
+ const edits = modifyJsonc(editedBody, [...entryPath, key], entry[key], {
+ formattingOptions,
+ });
+ editedBody = applyJsoncEdits(editedBody, edits);
+ }
+ } else {
+ const edits = modifyJsonc(editedBody, entryPath, entry, { formattingOptions });
+ editedBody = applyJsoncEdits(editedBody, edits);
+ }
+ const newText = `${hasBom ? '\uFEFF' : ''}${editedBody}`;
if (newText !== raw) {
atomicWriteFileSync(configPath, newText, { mode: existingFileMode(configPath) });
}
@@ -513,9 +545,15 @@ function upsertYamlMcpConfig(
if (doc.hasIn([topLevelKey]) && !isCollection(doc.getIn([topLevelKey], true))) {
doc.deleteIn([topLevelKey]);
}
- // Wrap the plain entry into YAML nodes explicitly so `command`/`args`/`env`
- // serialize as a proper map/seq (the multi-line chain becomes a block scalar).
- doc.setIn(path, doc.createNode(entry));
+ const existingEntryNode = doc.getIn(path, true);
+ if (entryExists && isCollection(existingEntryNode)) {
+ for (const key of managedEntryKeys(entry)) {
+ doc.setIn([...path, key], doc.createNode(entry[key]));
+ }
+ } else {
+ // A missing or non-map entry has no field-level structure to preserve.
+ doc.setIn(path, doc.createNode(entry));
+ }
// `yaml` emits LF, always ends with a trailing newline, and drops a leading
// BOM; restore the source file's encoding so the only byte-level change is
@@ -1430,7 +1468,8 @@ export type McpDeclineReason =
| 'unparseable'
| 'duplicate-container'
| 'oversize'
- | 'no-native-writer';
+ | 'no-native-writer'
+ | McpLauncherDeclineReason;
/**
* Discriminated classification of an existing MCP host config file. Where
diff --git a/packages/cli/src/commands/launch-json-removal.test.ts b/packages/cli/src/commands/launch-json-removal.test.ts
index 002efc05b..379d8c954 100644
--- a/packages/cli/src/commands/launch-json-removal.test.ts
+++ b/packages/cli/src/commands/launch-json-removal.test.ts
@@ -28,7 +28,7 @@ describe('removeOwnLaunchEntry', () => {
{
name: LAUNCH_CONFIG_NAME,
runtimeExecutable: '/bin/sh',
- runtimeArgs: ['-l', '-c', 'x'],
+ runtimeArgs: ['-l', '-c', '# ok-ui-v1\nexec ok start'],
},
],
});
@@ -43,7 +43,7 @@ describe('removeOwnLaunchEntry', () => {
}
});
- test('deletes the whole file when OK’s entry was the only configuration', () => {
+ test('keeps the containing file when OK’s entry was the only configuration', () => {
const dir = project();
try {
const p = writeLaunch(dir, {
@@ -52,13 +52,43 @@ describe('removeOwnLaunchEntry', () => {
{
name: LAUNCH_CONFIG_NAME,
runtimeExecutable: '/bin/sh',
- runtimeArgs: ['-l', '-c', 'x'],
+ runtimeArgs: ['-l', '-c', '# ok-ui-v1\nexec ok start'],
},
],
});
const outcome = removeOwnLaunchEntry(dir);
- expect(outcome.kind).toBe('removed-file');
- expect(existsSync(p)).toBe(false);
+ expect(outcome.kind).toBe('removed');
+ expect(existsSync(p)).toBe(true);
+ expect(JSON.parse(readFileSync(p, 'utf8'))).toEqual({
+ version: '0.2.0',
+ configurations: [],
+ });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test.each([
+ ['@inkeep/open-knowledge', 'ui'],
+ ['-y', '@inkeep/open-knowledge', 'ui'],
+ ['-y', '@inkeep/open-knowledge@latest', 'ui'],
+ ])('removes the historical generated npx form %j', (...runtimeArgs) => {
+ const dir = project();
+ try {
+ const p = writeLaunch(dir, {
+ configurations: [
+ { name: 'My App', type: 'node' },
+ {
+ name: LAUNCH_CONFIG_NAME,
+ runtimeExecutable: 'npx',
+ runtimeArgs,
+ },
+ ],
+ });
+ expect(removeOwnLaunchEntry(dir).kind).toBe('removed');
+ expect(JSON.parse(readFileSync(p, 'utf8')).configurations).toEqual([
+ { name: 'My App', type: 'node' },
+ ]);
} finally {
rmSync(dir, { recursive: true, force: true });
}
@@ -89,7 +119,7 @@ describe('removeOwnLaunchEntry', () => {
{
name: LAUNCH_CONFIG_NAME,
runtimeExecutable: '/bin/sh',
- runtimeArgs: ['-l', '-c', 'x'],
+ runtimeArgs: ['-l', '-c', '# ok-ui-v1\nexec ok start'],
},
],
},
@@ -120,4 +150,24 @@ describe('removeOwnLaunchEntry', () => {
rmSync(dir, { recursive: true, force: true });
}
});
+
+ test('preserves a same-name foreign configuration without a generated marker', () => {
+ const dir = project();
+ try {
+ const p = writeLaunch(dir, {
+ configurations: [
+ {
+ name: LAUNCH_CONFIG_NAME,
+ runtimeExecutable: '/bin/sh',
+ runtimeArgs: ['-l', '-c', 'exec my-own-preview'],
+ },
+ ],
+ });
+ const before = readFileSync(p, 'utf8');
+ expect(removeOwnLaunchEntry(dir).kind).toBe('not-present');
+ expect(readFileSync(p, 'utf8')).toBe(before);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
});
diff --git a/packages/cli/src/commands/launch-json-removal.ts b/packages/cli/src/commands/launch-json-removal.ts
index e16b34b85..3da8f6921 100644
--- a/packages/cli/src/commands/launch-json-removal.ts
+++ b/packages/cli/src/commands/launch-json-removal.ts
@@ -8,14 +8,11 @@
* whole file; it surgically removes only OK's array element, byte-preserving
* every other configuration, comment, and formatting token.
*
- * The one case the whole file IS removed: when OK's entry was the ONLY
- * configuration — the file was scaffolded by `ok init` and holds nothing else
- * of the user's — so deleting it is the clean full reversal (a later `ok init`
- * re-scaffolds it), matching how the fish PATH conf file is deleted when
- * stripping OK's block leaves it empty.
+ * The containing file is never deleted, even when the generated entry was its
+ * only configuration: top-level settings remain user-owned.
*/
-import { existsSync, readFileSync, rmSync } from 'node:fs';
+import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { atomicWriteFileSync } from '@inkeep/open-knowledge-core/server';
import {
@@ -30,7 +27,6 @@ import { existingFileMode, surgicalJsonDelete } from './jsonc-surgical.ts';
export type LaunchRemoveOutcome =
| { kind: 'removed' }
- | { kind: 'removed-file' }
| { kind: 'not-present' }
| { kind: 'declined' };
@@ -76,22 +72,49 @@ export function removeOwnLaunchEntry(projectRoot: string): LaunchRemoveOutcome {
const configs = root.configurations;
if (!Array.isArray(configs)) return { kind: 'not-present' };
- const index = configs.findIndex(
- (c) => isObject(c) && (c as Record<string, unknown>).name === LAUNCH_CONFIG_NAME,
- );
+ const index = configs.findIndex(isOwnLaunchEntry);
if (index === -1) return { kind: 'not-present' };
- // OK's entry is the only configuration → the file is OK-owned; delete it. An
- // I/O failure here propagates (like the atomicWriteFileSync below) so the
- // executor surfaces it as a `failed` op — a permission error is not a
- // `declined (unparseable)`.
- if (configs.length === 1) {
- rmSync(configPath, { force: true });
- return { kind: 'removed-file' };
- }
-
const { text, changed } = surgicalJsonDelete(raw, ['configurations', index]);
if (!changed) return { kind: 'not-present' };
atomicWriteFileSync(configPath, text, { mode: existingFileMode(configPath) });
return { kind: 'removed' };
}
+
+function isOwnLaunchEntry(value: unknown): boolean {
+ if (!isObject(value)) return false;
+ const entry = value as Record<string, unknown>;
+ if (entry.name !== LAUNCH_CONFIG_NAME || !Array.isArray(entry.runtimeArgs)) return false;
+ const args = entry.runtimeArgs;
+ if (entry.runtimeExecutable === '/bin/sh') {
+ return (
+ args.length === 3 &&
+ args[0] === '-l' &&
+ args[1] === '-c' &&
+ typeof args[2] === 'string' &&
+ /^# ok-ui-v[1-9]\d*$/.test(args[2].split(/\r?\n/, 1)[0] ?? '')
+ );
+ }
+ if (entry.runtimeExecutable === 'npx') {
+ return LEGACY_NPX_UI_FORMS.some((form) => argsExactlyMatch(args, form));
+ }
+ return (
+ entry.runtimeExecutable === 'powershell' &&
+ args.length === 4 &&
+ args[0] === '-NoProfile' &&
+ args[1] === '-NonInteractive' &&
+ args[2] === '-Command' &&
+ typeof args[3] === 'string' &&
+ /^# ok-ui-win-v[1-9]\d*$/.test(args[3].split(/\r?\n/, 1)[0] ?? '')
+ );
+}
+
+const LEGACY_NPX_UI_FORMS: ReadonlyArray<readonly string[]> = [
+ ['@inkeep/open-knowledge', 'ui'],
+ ['-y', '@inkeep/open-knowledge', 'ui'],
+ ['-y', '@inkeep/open-knowledge@latest', 'ui'],
+];
+
+function argsExactlyMatch(actual: readonly unknown[], expected: readonly string[]): boolean {
+ return actual.length === expected.length && actual.every((arg, index) => arg === expected[index]);
+}
diff --git a/packages/cli/src/commands/mcp-cross-harness-acceptance.test.ts b/packages/cli/src/commands/mcp-cross-harness-acceptance.test.ts
index ba60a6145..2265d5b1b 100644
--- a/packages/cli/src/commands/mcp-cross-harness-acceptance.test.ts
+++ b/packages/cli/src/commands/mcp-cross-harness-acceptance.test.ts
@@ -11,6 +11,7 @@ import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { parse as parseJsonc } from 'jsonc-parser';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { reconcileTrackedMcpConfig } from '../../../server/src/mcp-config-reconciler.ts';
import { buildPiExtensionSource } from '../integrations/pi-extension.ts';
import {
createTomlConfigEngine,
@@ -416,3 +417,40 @@ describe('pi file-drop write path (whole-file sibling of the entry upserts)', ()
}
});
});
+
+describe('server reconciliation with the CLI native TOML composition seam', () => {
+ it('selects v2 while preserving Codex siblings and unknown entry fields', () => {
+ const engine = createTomlConfigEngine();
+ if (engine.backend !== 'native') {
+ throw new Error('native toml_edit addon must be built for the reconciliation gate');
+ }
+ const toml = (marker: string, keep = 'yes') => `# keep top comment
+model = "gpt-5"
+
+[mcp_servers.other]
+command = "other"
+
+[mcp_servers.open-knowledge]
+command = "/bin/sh"
+args = ["-l", "-c", "${marker}\\nexit 127"]
+startup_timeout_ms = 9000
+
+[mcp_servers.open-knowledge.env]
+KEEP = "${keep}"
+`;
+ const v1 = toml('# ok-mcp-v1');
+ const v2 = toml('# ok-mcp-v2', 'incoming');
+ const plan = reconcileTrackedMcpConfig({
+ target: '.codex/config.toml',
+ layers: { base: v1, head: v1, index: v1, worktree: v1, incoming: v2 },
+ tomlEditor: engine,
+ });
+ expect(plan.kind).toBe('resolved');
+ if (plan.kind !== 'resolved') return;
+ expect(plan.raw).toContain('# keep top comment');
+ expect(plan.raw).toContain('[mcp_servers.other]');
+ expect(plan.raw).toContain('startup_timeout_ms = 9000');
+ expect(plan.raw).toContain('KEEP = "incoming"');
+ expect(plan.raw).toContain('# ok-mcp-v2');
+ });
+});
diff --git a/packages/cli/src/commands/mcp-json-surgical-write.test.ts b/packages/cli/src/commands/mcp-json-surgical-write.test.ts
index d8a20e460..e70078f7b 100644
--- a/packages/cli/src/commands/mcp-json-surgical-write.test.ts
+++ b/packages/cli/src/commands/mcp-json-surgical-write.test.ts
@@ -350,6 +350,75 @@ describe('surgical JSON MCP write', () => {
expect(servers['open-knowledge']).toEqual(PUBLISHED_CHAIN_ENTRY);
});
+ it('updates only standard launch keys and preserves every unknown entry field', () => {
+ const configPath = tempFile('config.jsonc');
+ const original = `{
+ "mcpServers": {
+ "other": { "command": "node", "args": ["other.js"] },
+ "open-knowledge": {
+ "command": "/bin/sh",
+ "args": ["-l", "-c", "# ok-mcp-v1\\nexit 127"],
+ "env": { "KEEP": "yes" },
+ "startup_timeout_ms": 45000,
+ "tools": { "exec": { "approval_mode": "approve" } },
+ // nested policy belongs to the harness, not OK
+ "unknown": { "nested": { "values": [1, 2, 3] } }
+ }
+ },
+ "theme": "dark"
+}
+`;
+ writeFileSync(configPath, original);
+
+ expect(write('cursor', configPath).action).toBe('overwritten');
+
+ const after = readFileSync(configPath, 'utf-8');
+ const entry = (parseConfig(after).mcpServers as Record<string, Record<string, unknown>>)[
+ 'open-knowledge'
+ ];
+ expect(entry).toEqual({
+ ...PUBLISHED_CHAIN_ENTRY,
+ env: { KEEP: 'yes' },
+ startup_timeout_ms: 45000,
+ tools: { exec: { approval_mode: 'approve' } },
+ unknown: { nested: { values: [1, 2, 3] } },
+ });
+ expect(after).toContain('// nested policy belongs to the harness, not OK');
+ expect(after).toContain('"other": { "command": "node", "args": ["other.js"] }');
+ expect(after).toContain('"theme": "dark"');
+ });
+
+ it('updates only OpenCode launch keys without re-enabling a disabled entry', () => {
+ const configPath = tempFile('opencode.json');
+ writeFileSync(
+ configPath,
+ `{
+ "mcp": {
+ "open-knowledge": {
+ "type": "local",
+ "enabled": false,
+ "command": ["/bin/sh", "-l", "-c", "# ok-mcp-v1\\nexit 127"],
+ "environment": { "KEEP": "yes" },
+ "unknown": { "nested": true }
+ }
+ }
+}
+`,
+ );
+
+ expect(write('opencode', configPath).action).toBe('overwritten');
+
+ const entry = (
+ parseConfig(readFileSync(configPath, 'utf-8')).mcp as Record<string, Record<string, unknown>>
+ )['open-knowledge'];
+ expect(entry).toEqual({
+ ...OPENCODE_ENTRY,
+ enabled: false,
+ environment: { KEEP: 'yes' },
+ unknown: { nested: true },
+ });
+ });
+
it('is a byte-identical no-op when our entry is already current', () => {
const configPath = tempFile('config.json');
writeFileSync(
diff --git a/packages/cli/src/commands/mcp-yaml-surgical-write.test.ts b/packages/cli/src/commands/mcp-yaml-surgical-write.test.ts
index 34fb4f698..8859a5d9b 100644
--- a/packages/cli/src/commands/mcp-yaml-surgical-write.test.ts
+++ b/packages/cli/src/commands/mcp-yaml-surgical-write.test.ts
@@ -133,6 +133,47 @@ describe('surgical YAML MCP write', () => {
);
});
+ it('updates only launch keys and preserves unknown fields inside the entry', () => {
+ const configPath = tempFile('config.yaml');
+ const original = [
+ '# hand-written header',
+ 'model: hermes-4',
+ 'mcp_servers:',
+ ' other:',
+ ' command: node',
+ ' args: [other.js]',
+ ' open-knowledge:',
+ ' command: /bin/sh',
+ ' args: [-l, -c, "# ok-mcp-v1\\nexit 127"]',
+ ' env:',
+ ' KEEP: yes',
+ ' startup_timeout_ms: 45000',
+ ' tools:',
+ ' exec:',
+ ' approval_mode: approve',
+ ' unknown: # keep nested policy',
+ ' nested:',
+ ' values: [1, 2, 3]',
+ '',
+ ].join('\n');
+ writeFileSync(configPath, original);
+
+ expect(writeHermes(configPath).action).toBe('overwritten');
+
+ const after = readFileSync(configPath, 'utf-8');
+ const entry = parseYaml(after).mcp_servers['open-knowledge'];
+ expect(entry).toEqual({
+ ...PUBLISHED_CHAIN_ENTRY,
+ env: { KEEP: 'yes' },
+ startup_timeout_ms: 45000,
+ tools: { exec: { approval_mode: 'approve' } },
+ unknown: { nested: { values: [1, 2, 3] } },
+ });
+ expect(after).toContain('# keep nested policy');
+ expect(after).toContain('# hand-written header');
+ expect(parseYaml(after).mcp_servers.other).toEqual({ command: 'node', args: ['other.js'] });
+ });
+
it('is idempotent: a second write does not churn the file', () => {
const configPath = tempFile('config.yaml');
writeHermes(configPath);
diff --git a/packages/cli/src/commands/removal-plan.ts b/packages/cli/src/commands/removal-plan.ts
index bd2019a89..c2cc5d39f 100644
--- a/packages/cli/src/commands/removal-plan.ts
+++ b/packages/cli/src/commands/removal-plan.ts
@@ -596,7 +596,6 @@ async function executeOp(op: RemovalOp, deps: ResolvedDeps): Promise<RemovalOpRe
const outcome = removeOwnLaunchEntry(op.projectRoot);
switch (outcome.kind) {
case 'removed':
- case 'removed-file':
return { op, status: 'removed' };
case 'not-present':
return { op, status: 'not-present' };
diff --git a/packages/cli/src/commands/repair-launch-json.test.ts b/packages/cli/src/commands/repair-launch-json.test.ts
index ecc060f84..beca9a064 100644
--- a/packages/cli/src/commands/repair-launch-json.test.ts
+++ b/packages/cli/src/commands/repair-launch-json.test.ts
@@ -65,14 +65,15 @@ describe('repairLaunchJson (remove sweep)', () => {
expect(logEvents).toContainEqual({ event: 'launch-json-repair-removed', configPath });
});
- it("removes the whole file when OK's entry was the only configuration", () => {
+ it("keeps the file when OK's entry was the only configuration", () => {
const configPath = writeLaunchJson({ version: '0.0.1', configurations: [OK_ENTRY] });
const result = repairLaunchJson({ projectDir, logger });
- expect(result.outcome.outcome).toBe('removed-file');
+ expect(result.outcome.outcome).toBe('removed');
expect(result.repairedCount).toBe(1);
- expect(existsSync(configPath)).toBe(false);
+ expect(existsSync(configPath)).toBe(true);
+ expect(JSON.parse(readFileSync(configPath, 'utf8')).configurations).toEqual([]);
});
it('reports not-present when no launch.json exists, and does not create one', () => {
diff --git a/packages/cli/src/commands/repair-launch-json.ts b/packages/cli/src/commands/repair-launch-json.ts
index a3aafea11..3af6aa8cc 100644
--- a/packages/cli/src/commands/repair-launch-json.ts
+++ b/packages/cli/src/commands/repair-launch-json.ts
@@ -15,25 +15,19 @@ import { removeOwnLaunchEntry } from './launch-json-removal.ts';
export interface LaunchJsonRepairOutcome {
configPath: string;
/**
- * - `removed` / `removed-file` — OK's entry (or the whole OK-only file) was
- * removed from a pre-existing `.claude/launch.json`.
+ * - `removed` — OK's structurally recognized entry was removed from a
+ * pre-existing `.claude/launch.json`; the containing file remains.
* - `not-present` — no file, or no OK entry; nothing to clean up.
* - `declined` — file exists but is malformed; left untouched.
* - `skipped-reclaim-disabled` — `OK_RECLAIM_DISABLE=1` short-circuited.
*/
- outcome:
- | 'removed'
- | 'removed-file'
- | 'not-present'
- | 'declined'
- | 'write-failed'
- | 'skipped-reclaim-disabled';
+ outcome: 'removed' | 'not-present' | 'declined' | 'write-failed' | 'skipped-reclaim-disabled';
error?: string;
}
export interface LaunchJsonRepairResult {
outcome: LaunchJsonRepairOutcome;
- /** 1 when an entry (or the OK-only file) was removed, else 0. */
+ /** 1 when a structurally recognized entry was removed, else 0. */
repairedCount: 0 | 1;
}
@@ -76,7 +70,7 @@ export function repairLaunchJson(ctx: LaunchJsonRepairContext): LaunchJsonRepair
logger({ event: 'launch-json-repair-write-failed', configPath });
return { outcome: { configPath, outcome: 'write-failed', error }, repairedCount: 0 };
}
- const removed = result.kind === 'removed' || result.kind === 'removed-file';
+ const removed = result.kind === 'removed';
if (removed) logger({ event: 'launch-json-repair-removed', configPath });
return { outcome: { configPath, outcome: result.kind }, repairedCount: removed ? 1 : 0 };
}
diff --git a/packages/cli/src/commands/repair-mcp-configs.test.ts b/packages/cli/src/commands/repair-mcp-configs.test.ts
index 16ecc5e72..73defc51b 100644
--- a/packages/cli/src/commands/repair-mcp-configs.test.ts
+++ b/packages/cli/src/commands/repair-mcp-configs.test.ts
@@ -53,6 +53,12 @@ describe('repairMcpConfigs', () => {
return path;
}
+ function writeProjectClaude(entry: Record<string, unknown>): string {
+ const path = join(projectDir, '.mcp.json');
+ writeFileSync(path, JSON.stringify({ mcpServers: { 'open-knowledge': entry } }, null, 2));
+ return path;
+ }
+
it('rewrites legacy bare-npx, npx-@latest, bundle-direct, and symlink entries to the chain', () => {
for (const entry of [LEGACY_BARE, LEGACY_NPX_AT_LATEST, BUNDLE_ABSOLUTE, SYMLINK]) {
const configPath = writeClaude(entry);
@@ -117,6 +123,51 @@ describe('repairMcpConfigs', () => {
expect(readFileSync(configPath, 'utf-8')).toBe(before);
});
+ it('leaves a recognized future launcher byte-unchanged', () => {
+ const configPath = writeClaude({
+ command: '/bin/sh',
+ args: ['-l', '-c', '# ok-mcp-v99\nfuture launcher body'],
+ env: { KEEP: 'yes' },
+ });
+ const before = readFileSync(configPath, 'utf-8');
+
+ const result = repairMcpConfigs({ projectDir, home: fakeHome });
+
+ expect(result.repairedCount).toBe(0);
+ expect(result.outcomes.find((o) => o.editorId === 'claude')?.outcome).toBe('canonical');
+ expect(readFileSync(configPath, 'utf-8')).toBe(before);
+ });
+
+ it('keeps a recognized future project launcher byte-unchanged', () => {
+ const configPath = writeProjectClaude({
+ command: '/bin/sh',
+ args: ['-l', '-c', '# ok-mcp-v99\nfuture launcher body'],
+ unknown: { keep: true },
+ });
+ const before = readFileSync(configPath, 'utf-8');
+
+ const result = repairMcpConfigs({ projectDir, home: fakeHome });
+ const outcome = result.outcomes.find(
+ (item) => item.scope === 'project' && item.editorId === 'claude',
+ );
+
+ expect(outcome?.outcome).toBe('canonical');
+ expect(readFileSync(configPath, 'utf-8')).toBe(before);
+ });
+
+ it('declines a foreign project entry without writing it', () => {
+ const configPath = writeProjectClaude({ command: '/usr/bin/foreign', args: ['server.js'] });
+ const before = readFileSync(configPath, 'utf-8');
+
+ const result = repairMcpConfigs({ projectDir, home: fakeHome });
+ const outcome = result.outcomes.find(
+ (item) => item.scope === 'project' && item.editorId === 'claude',
+ );
+
+ expect(outcome).toMatchObject({ outcome: 'declined', reason: 'foreign-command' });
+ expect(readFileSync(configPath, 'utf-8')).toBe(before);
+ });
+
it('rewrites the hand-fixed cmd workaround shape forward to the local canonical', () => {
const configPath = writeClaude(CMD_WORKAROUND);
diff --git a/packages/cli/src/commands/repair-mcp-configs.ts b/packages/cli/src/commands/repair-mcp-configs.ts
index 2b913aa4c..0e7f299da 100644
--- a/packages/cli/src/commands/repair-mcp-configs.ts
+++ b/packages/cli/src/commands/repair-mcp-configs.ts
@@ -3,6 +3,7 @@
* forward to today's resilient chain shape.
*/
import { homedir } from 'node:os';
+import { classifyMcpLauncherEntry } from '@inkeep/open-knowledge-core';
import {
ALL_EDITOR_IDS,
EDITOR_TARGETS,
@@ -10,7 +11,7 @@ import {
type EditorMcpTarget,
isEntryUpToDate,
} from './editors.ts';
-import { readExistingMcpEntry, writeEditorMcpConfig } from './init.ts';
+import { type McpDeclineReason, readExistingMcpEntry, writeEditorMcpConfig } from './init.ts';
import { buildMcpConfigMigrateEvent } from './mcp-migrate-event.ts';
export interface RepairOutcome {
@@ -18,6 +19,7 @@ export interface RepairOutcome {
editorId: EditorId;
configPath: string;
outcome: 'no-entry' | 'canonical' | 'repaired' | 'write-failed' | 'declined';
+ reason?: McpDeclineReason;
error?: string;
}
@@ -165,7 +167,24 @@ function repairOne(opts: RepairOneOptions): RepairOutcome {
return { ...base, outcome: 'no-entry' };
}
- if (isEntryUpToDate(existing)) return { ...base, outcome: 'canonical' };
+ if (opts.editorId === 'pi') {
+ if (isEntryUpToDate(existing)) return { ...base, outcome: 'canonical' };
+ } else {
+ const launcher = classifyMcpLauncherEntry(existing);
+ if (launcher.kind === 'recognized' && launcher.disposition === 'keep') {
+ return { ...base, outcome: 'canonical' };
+ }
+ if (launcher.kind === 'declined' && opts.scope === 'project') {
+ opts.logger({
+ event: 'mcp-config-repair-declined',
+ scope: opts.scope,
+ editorId: opts.editorId,
+ configPath: opts.configPath,
+ reason: launcher.reason,
+ });
+ return { ...base, outcome: 'declined', reason: launcher.reason };
+ }
+ }
// Emit migrate event BEFORE the rewrite so field observability captures
// every attempted migration — including writes that subsequently fail with
diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.ts
index 4d3e1edd8..a13e4c73d 100644
--- a/packages/cli/src/commands/start.ts
+++ b/packages/cli/src/commands/start.ts
@@ -50,6 +50,7 @@ import { makeLazyEmbeddingsKeyStore } from '../auth/embeddings-key-store.ts';
import { detectGh } from '../auth/gh-detect.ts';
import { makeLazyProbeTokenStore } from '../auth/token-store.ts';
import { PACKAGE_VERSION } from '../constants.ts';
+import { getNativeTomlMcpEditor } from '../native/toml-config-engine.ts';
import { probeOwnManagedEditorMcpEntry } from './acp-harness-probe.ts';
import {
createRealDetectDeps,
@@ -863,6 +864,7 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<Boo
detectGh,
tokenStore,
embeddingsKeyStore,
+ mcpTomlEditor: getNativeTomlMcpEditor(),
// Ephemeral single-file mode: scope content to the one doc, no MCP, no git
// (shadow repo + commits off), and a no-op git preflight so a machine
// without git can still open a loose file. The synthesized config lives at
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 8d330a52c..e0d7bc218 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -138,6 +138,7 @@ export {
removeProjectSkill,
writeProjectSkill,
} from './integrations/write-project-skill.ts';
+export { getNativeTomlMcpEditor } from './native/toml-config-engine.ts';
// Leveled bug-report capture — shared by `ok bug-report` and the desktop
// report-a-bug flow so the two stay in lockstep.
export {
diff --git a/packages/cli/src/native/toml-config-engine.test.ts b/packages/cli/src/native/toml-config-engine.test.ts
index ea5400cf5..919fe3d49 100644
--- a/packages/cli/src/native/toml-config-engine.test.ts
+++ b/packages/cli/src/native/toml-config-engine.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, test } from 'vitest';
-import { createTomlConfigEngine, type NativeTomlBinding } from './toml-config-engine.ts';
+import {
+ createTomlConfigEngine,
+ getNativeTomlMcpEditor,
+ type NativeTomlBinding,
+} from './toml-config-engine.ts';
// A config value that exercises the whole point of the native engine: a 64-bit
// integer past Number.MAX_SAFE_INTEGER, plus a microsecond datetime. smol-toml
@@ -21,6 +25,13 @@ const NOOP_REMOVE: NativeTomlBinding['removeMcpServer'] = () => ({
});
describe('createTomlConfigEngine', () => {
+ test('exposes the native server composition seam when the addon is available', () => {
+ const editor = getNativeTomlMcpEditor();
+ expect(editor?.backend).toBe('native');
+ expect(typeof editor?.upsertEntry).toBe('function');
+ expect(typeof editor?.removeEntry).toBe('function');
+ });
+
test('resolves the native backend and parses values smol-toml rejects', () => {
const engine = createTomlConfigEngine();
expect(engine.backend).toBe('native');
diff --git a/packages/cli/src/native/toml-config-engine.ts b/packages/cli/src/native/toml-config-engine.ts
index 9063f1603..5058f7699 100644
--- a/packages/cli/src/native/toml-config-engine.ts
+++ b/packages/cli/src/native/toml-config-engine.ts
@@ -198,6 +198,16 @@ export function getTomlConfigEngine(): TomlConfigEngine {
return cachedEngine;
}
+/**
+ * Composition-root seam for server-side tracked-config reconciliation.
+ * Returning undefined is an explicit no-native-writer capability result; the
+ * server then declines TOML reconciliation instead of changing fidelity.
+ */
+export function getNativeTomlMcpEditor(): NativeTomlConfigEngine | undefined {
+ const engine = getTomlConfigEngine();
+ return engine.backend === 'native' ? engine : undefined;
+}
+
/**
* Test-only: override the cached engine (pass `null` to reset to lazy default).
* Lets a test exercise the fallback decline path or the native path
diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.ts
index d7a845280..dfd95ef49 100644
--- a/packages/core/src/bridge/bind-frontmatter-doc.ts
+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts
@@ -1,3 +1,4 @@
+
import type * as Y from 'yjs';
import type { Err, Ok, Result } from '../config/result.ts';
import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';
diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.ts
index 005627195..8bfdb40cd 100644
--- a/packages/core/src/bridge/bridge-invariant.ts
+++ b/packages/core/src/bridge/bridge-invariant.ts
@@ -1,3 +1,4 @@
+
import { fnv1aDigest } from './hash-util.ts';
export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';
diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.ts
index f4cc8a286..2a597ec3d 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,3 +1,4 @@
+
import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';
export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';
diff --git a/packages/core/src/bridge/divergence-locate.ts b/packages/core/src/bridge/divergence-locate.ts
index 6b505314d..d979f4b39 100644
--- a/packages/core/src/bridge/divergence-locate.ts
+++ b/packages/core/src/bridge/divergence-locate.ts
@@ -1,3 +1,4 @@
+
import { findFirstDivergenceIndex } from './tolerance-telemetry.ts';
export const BRIDGE_LINE_KINDS = [
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index 8fb428b90..01ef76a9f 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,3 +1,4 @@
+
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';
diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.ts
index 9d9c244b0..463e89595 100644
--- a/packages/core/src/bridge/growth-detect.ts
+++ b/packages/core/src/bridge/growth-detect.ts
@@ -1,3 +1,4 @@
+
const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;
export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;
diff --git a/packages/core/src/bridge/intraline-predicate.ts b/packages/core/src/bridge/intraline-predicate.ts
index c43fdd7e7..0939885bb 100644
--- a/packages/core/src/bridge/intraline-predicate.ts
+++ b/packages/core/src/bridge/intraline-predicate.ts
@@ -1,3 +1,4 @@
+
export function rawLineCounts(doc: string): Map<string, number> {
const counts = new Map<string, number>();
for (const line of doc.split('\n')) {
diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.ts
index 251560a35..c0dc65705 100644
--- a/packages/core/src/bridge/merge-three-way.ts
+++ b/packages/core/src/bridge/merge-three-way.ts
@@ -65,6 +65,7 @@ export function tryLineLevelCombine(
return { clean: true, merged };
}
+
export type BridgeMergeContentLossSide = 'user' | 'agent';
export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';
diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.ts
index 01ac80099..dcc5b0690 100644
--- a/packages/core/src/bridge/normalize.ts
+++ b/packages/core/src/bridge/normalize.ts
@@ -1,3 +1,4 @@
+
import { stripFrontmatter } from '../extensions/frontmatter.ts';
import { bodyEdgeEmpties } from './doc-boundary-space.ts';
diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.ts
index 754dc5cc2..0be5203e4 100644
--- a/packages/core/src/bridge/pm-structural-equivalence.ts
+++ b/packages/core/src/bridge/pm-structural-equivalence.ts
@@ -32,6 +32,7 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };
const BR_LITERAL_RE = /^<br\s*\/?>$/i;
+
interface DegradeEntry {
readonly label: string;
readonly severity: ToleranceClassSeverity;
@@ -127,6 +128,7 @@ export interface ComparePmStructuralOptions {
ignoreAttrs?: (attrKey: string) => boolean;
}
+
/** Rebuild a node with `fn` applied to each child; identity when childless.
* Shared by the degrade canonicalizers so none re-implements the walk. */
function mapChildren(
@@ -248,6 +250,7 @@ function applyDegrades(tree: PmStructuralNode): {
return { normalized: current, fired };
}
+
export function comparePmStructural(
expected: PmStructuralNode,
actual: PmStructuralNode,
diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.ts
index af20de1e2..dca644141 100644
--- a/packages/core/src/bridge/subsequence.ts
+++ b/packages/core/src/bridge/subsequence.ts
@@ -1,3 +1,4 @@
+
/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):
* insertions in `haystack` are free; any dropped or substituted `needle` byte
* fails. */
diff --git a/packages/core/src/constants/mcp-launcher.test.ts b/packages/core/src/constants/mcp-launcher.test.ts
new file mode 100644
index 000000000..1c5ec0fe0
--- /dev/null
+++ b/packages/core/src/constants/mcp-launcher.test.ts
@@ -0,0 +1,220 @@
+import { describe, expect, test } from 'vitest';
+import {
+ classifyMcpLauncherEntry,
+ type McpLauncherFamily,
+ type McpLauncherRevisionCatalog,
+} from './mcp-launcher.ts';
+
+const UNIX_V1_HISTORICAL_CHAIN = `# ok-mcp-v1
+USER_BUNDLE="$HOME/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh"
+[ -f "$USER_BUNDLE" ] && [ -x "$USER_BUNDLE" ] && exec "$USER_BUNDLE" mcp
+BUNDLE="/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh"
+[ -f "$BUNDLE" ] && [ -x "$BUNDLE" ] && exec "$BUNDLE" mcp
+command -v npx >/dev/null 2>&1 && exec npx -y @inkeep/open-knowledge@latest mcp
+for d in "$HOME/.nvm/versions/node"/*/bin "$HOME/.fnm/node-versions"/*/installation/bin "$HOME/.asdf/installs/nodejs"/*/bin /opt/homebrew/bin /usr/local/bin "$HOME/.local/bin" "$HOME/.volta/bin"; do
+ [ -f "$d/npx" ] && [ -x "$d/npx" ] && exec "$d/npx" -y @inkeep/open-knowledge@latest mcp
+done
+echo "OpenKnowledge: install OK Desktop or Node.js 24+, then restart your editor" >&2
+exit 127`;
+
+const WINDOWS_V1_HISTORICAL_CHAIN = `# ok-mcp-win-v1
+if ($env:PATHEXT -notmatch 'CMD') { $env:PATHEXT = '.COM;.EXE;.BAT;.CMD;' + $env:PATHEXT }
+if ($env:APPDATA) {
+ $shim = Join-Path $env:APPDATA 'npm\\ok.cmd'
+ if (Test-Path -LiteralPath $shim -PathType Leaf) { & $shim mcp; exit $LASTEXITCODE }
+}
+$ok = Get-Command ok.cmd -CommandType Application -ErrorAction SilentlyContinue
+if ($ok) { & $ok.Source mcp; exit $LASTEXITCODE }
+$npx = Get-Command npx.cmd -CommandType Application -ErrorAction SilentlyContinue
+if ($npx) { & $npx.Source -y '@inkeep/open-knowledge@latest' mcp; exit $LASTEXITCODE }
+$dirs = @()
+if ($env:ProgramFiles) { $dirs += Join-Path $env:ProgramFiles 'nodejs' }
+if ($env:NVM_SYMLINK) { $dirs += $env:NVM_SYMLINK }
+if ($env:LOCALAPPDATA) {
+ $dirs += Join-Path $env:LOCALAPPDATA 'fnm\\aliases\\default'
+ $dirs += Join-Path $env:LOCALAPPDATA 'Volta\\bin'
+ $dirs += Join-Path $env:LOCALAPPDATA 'pnpm'
+}
+if ($env:USERPROFILE) { $dirs += Join-Path $env:USERPROFILE 'scoop\\shims' }
+foreach ($d in $dirs) {
+ $probe = Join-Path $d 'npx.cmd'
+ if (Test-Path -LiteralPath $probe -PathType Leaf) { & $probe -y '@inkeep/open-knowledge@latest' mcp; exit $LASTEXITCODE }
+}
+[Console]::Error.WriteLine('OpenKnowledge: install Node.js 24+ (npm i -g @inkeep/open-knowledge), then restart your editor')
+exit 127`;
+
+const TEST_CATALOG_WITH_WINDOWS_V2 = {
+ 'unix-chain': {
+ 1: ['macos-bundle', 'npx-fallback'],
+ 2: ['macos-bundle', 'linux-deb-bundle', 'npx-fallback'],
+ },
+ 'windows-chain': {
+ 1: ['windows-global-cli', 'npx-fallback'],
+ 2: ['windows-global-cli', 'npx-fallback'],
+ },
+} as const satisfies McpLauncherRevisionCatalog;
+
+function marker(family: McpLauncherFamily, revision: number): string {
+ return family === 'unix-chain' ? `# ok-mcp-v${revision}` : `# ok-mcp-win-v${revision}`;
+}
+
+const SHAPES = [
+ {
+ name: 'split Unix',
+ family: 'unix-chain',
+ wrap: (body: string): unknown => ({ command: '/bin/sh', args: ['-l', '-c', body] }),
+ },
+ {
+ name: 'split Windows',
+ family: 'windows-chain',
+ wrap: (body: string): unknown => ({
+ command: 'powershell',
+ args: ['-NoProfile', '-NonInteractive', '-Command', body],
+ }),
+ },
+ {
+ name: 'OpenCode Unix',
+ family: 'unix-chain',
+ wrap: (body: string): unknown => ({
+ type: 'local',
+ enabled: true,
+ command: ['/bin/sh', '-l', '-c', body],
+ }),
+ },
+ {
+ name: 'OpenCode Windows',
+ family: 'windows-chain',
+ wrap: (body: string): unknown => ({
+ type: 'local',
+ enabled: true,
+ command: ['powershell', '-NoProfile', '-NonInteractive', '-Command', body],
+ }),
+ },
+] as const;
+
+describe('classifyMcpLauncherEntry', () => {
+ test('keeps the current Unix launcher and describes its recognized contract', () => {
+ expect(
+ classifyMcpLauncherEntry({
+ command: '/bin/sh',
+ args: ['-l', '-c', '# ok-mcp-v2\nexec npx -y @inkeep/open-knowledge@latest mcp'],
+ }),
+ ).toEqual({
+ kind: 'recognized',
+ disposition: 'keep',
+ descriptor: {
+ envelope: 'split-command-args',
+ family: 'unix-chain',
+ revision: 2,
+ knowledge: 'known',
+ capabilities: ['macos-bundle', 'linux-deb-bundle', 'npx-fallback'],
+ },
+ });
+ });
+
+ test.each(SHAPES)('$name keeps its family-local current revision', ({ family, wrap }) => {
+ const currentRevision = family === 'unix-chain' ? 2 : 1;
+ const result = classifyMcpLauncherEntry(wrap(`${marker(family, currentRevision)}\nexit 127`));
+ expect(result).toMatchObject({
+ kind: 'recognized',
+ disposition: 'keep',
+ descriptor: { family, revision: currentRevision, knowledge: 'known' },
+ });
+ });
+
+ test.each(SHAPES)('$name preserves a strictly recognized future revision', ({ family, wrap }) => {
+ const futureRevision = family === 'unix-chain' ? 3 : 2;
+ expect(
+ classifyMcpLauncherEntry(wrap(`${marker(family, futureRevision)}\nexit 127`)),
+ ).toMatchObject({
+ kind: 'recognized',
+ disposition: 'keep',
+ descriptor: {
+ family,
+ revision: futureRevision,
+ knowledge: 'future',
+ capabilities: 'opaque',
+ },
+ });
+ });
+
+ test.each(SHAPES)('$name requires its marker on the first line', ({ family, wrap }) => {
+ expect(
+ classifyMcpLauncherEntry(wrap(`echo preparing\n${marker(family, 99)}\nexit 127`)),
+ ).toEqual({ kind: 'declined', reason: 'malformed-marker' });
+ });
+
+ test('upgrades known older revisions within each family', () => {
+ expect(
+ classifyMcpLauncherEntry({
+ command: '/bin/sh',
+ args: ['-l', '-c', UNIX_V1_HISTORICAL_CHAIN],
+ }),
+ ).toMatchObject({
+ kind: 'recognized',
+ disposition: 'upgrade',
+ descriptor: { family: 'unix-chain', revision: 1, knowledge: 'known' },
+ });
+
+ expect(
+ classifyMcpLauncherEntry(
+ {
+ command: 'powershell',
+ args: ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_V1_HISTORICAL_CHAIN],
+ },
+ TEST_CATALOG_WITH_WINDOWS_V2,
+ ),
+ ).toMatchObject({
+ kind: 'recognized',
+ disposition: 'upgrade',
+ descriptor: { family: 'windows-chain', revision: 1, knowledge: 'known' },
+ });
+ });
+
+ test('orders revisions only within a family', () => {
+ const unixV1Build = {
+ 'unix-chain': { 1: ['macos-bundle', 'npx-fallback'] },
+ 'windows-chain': { 1: ['windows-global-cli', 'npx-fallback'] },
+ } as const satisfies McpLauncherRevisionCatalog;
+
+ expect(
+ classifyMcpLauncherEntry(
+ { command: '/bin/sh', args: ['-l', '-c', '# ok-mcp-v2\nexit 127'] },
+ unixV1Build,
+ ),
+ ).toMatchObject({
+ kind: 'recognized',
+ disposition: 'keep',
+ descriptor: { family: 'unix-chain', revision: 2, knowledge: 'future' },
+ });
+ expect(
+ classifyMcpLauncherEntry({
+ command: '/bin/sh',
+ args: ['-l', '-c', UNIX_V1_HISTORICAL_CHAIN],
+ }),
+ ).toMatchObject({ kind: 'recognized', disposition: 'upgrade' });
+ expect(
+ classifyMcpLauncherEntry({
+ command: 'powershell',
+ args: ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_V1_HISTORICAL_CHAIN],
+ }),
+ ).toMatchObject({
+ kind: 'recognized',
+ disposition: 'keep',
+ descriptor: { family: 'windows-chain', revision: 1 },
+ });
+ });
+
+ test.each([
+ [null, 'not-an-object'],
+ [{ command: '/bin/zsh', args: ['-l', '-c', '# ok-mcp-v2'] }, 'foreign-command'],
+ [{ command: '/bin/sh', args: ['-c', '# ok-mcp-v2'] }, 'malformed-argv'],
+ [{ command: '/bin/sh', args: ['-l', '-c', '# ok-mcp-v2', 'extra'] }, 'malformed-argv'],
+ [{ type: 'remote', command: ['/bin/sh', '-l', '-c', '# ok-mcp-v2'] }, 'unknown-envelope'],
+ [{ command: 'node', args: ['/tmp/cli.mjs', 'mcp'] }, 'dev-mode'],
+ [{ type: 'local', command: ['node', '/tmp/cli.mjs', 'mcp'] }, 'dev-mode'],
+ [{ type: 'local', command: ['/bin/sh', '-l', '-c', '# ok-mcp-v2', 'extra'] }, 'malformed-argv'],
+ ] as const)('declines %j with bounded reason %s', (entry, reason) => {
+ expect(classifyMcpLauncherEntry(entry)).toEqual({ kind: 'declined', reason });
+ });
+});
diff --git a/packages/core/src/constants/mcp-launcher.ts b/packages/core/src/constants/mcp-launcher.ts
new file mode 100644
index 000000000..4daba24c1
--- /dev/null
+++ b/packages/core/src/constants/mcp-launcher.ts
@@ -0,0 +1,177 @@
+export type McpLauncherEnvelope = 'split-command-args' | 'opencode-argv';
+export type McpLauncherFamily = 'unix-chain' | 'windows-chain';
+
+export type McpLauncherCapability =
+ | 'macos-bundle'
+ | 'linux-deb-bundle'
+ | 'windows-global-cli'
+ | 'npx-fallback';
+
+export type KnownMcpLauncherDescriptor = {
+ readonly envelope: McpLauncherEnvelope;
+ readonly family: McpLauncherFamily;
+ readonly revision: number;
+ readonly knowledge: 'known';
+ readonly capabilities: readonly McpLauncherCapability[];
+};
+
+export type FutureMcpLauncherDescriptor = {
+ readonly envelope: McpLauncherEnvelope;
+ readonly family: McpLauncherFamily;
+ readonly revision: number;
+ readonly knowledge: 'future';
+ readonly capabilities: 'opaque';
+};
+
+export type McpLauncherDescriptor = KnownMcpLauncherDescriptor | FutureMcpLauncherDescriptor;
+
+export type McpLauncherDeclineReason =
+ | 'not-an-object'
+ | 'unknown-envelope'
+ | 'foreign-command'
+ | 'malformed-argv'
+ | 'malformed-marker'
+ | 'unknown-revision'
+ | 'dev-mode';
+
+export type McpLauncherClassification =
+ | {
+ readonly kind: 'recognized';
+ readonly disposition: 'keep' | 'upgrade';
+ readonly descriptor: McpLauncherDescriptor;
+ }
+ | { readonly kind: 'declined'; readonly reason: McpLauncherDeclineReason };
+
+export type McpLauncherRevisionCatalog = Readonly<
+ Record<McpLauncherFamily, Readonly<Record<number, readonly McpLauncherCapability[]>>>
+>;
+
+export const DEFAULT_MCP_LAUNCHER_REVISION_CATALOG = {
+ 'unix-chain': {
+ 1: ['macos-bundle', 'npx-fallback'],
+ 2: ['macos-bundle', 'linux-deb-bundle', 'npx-fallback'],
+ },
+ 'windows-chain': {
+ 1: ['windows-global-cli', 'npx-fallback'],
+ },
+} as const satisfies McpLauncherRevisionCatalog;
+
+type ExtractedLauncher = {
+ readonly envelope: McpLauncherEnvelope;
+ readonly family: McpLauncherFamily;
+ readonly body: string;
+};
+
+function decline(reason: McpLauncherDeclineReason): McpLauncherClassification {
+ return { kind: 'declined', reason };
+}
+
+function extractLauncher(
+ entry: Record<string, unknown>,
+): ExtractedLauncher | McpLauncherClassification {
+ if (entry.command === 'node') return decline('dev-mode');
+
+ if (typeof entry.command === 'string') {
+ if (!Array.isArray(entry.args)) return decline('malformed-argv');
+ if (entry.command === '/bin/sh') {
+ if (
+ entry.args.length !== 3 ||
+ entry.args[0] !== '-l' ||
+ entry.args[1] !== '-c' ||
+ typeof entry.args[2] !== 'string'
+ ) {
+ return decline('malformed-argv');
+ }
+ return { envelope: 'split-command-args', family: 'unix-chain', body: entry.args[2] };
+ }
+ if (entry.command === 'powershell') {
+ if (
+ entry.args.length !== 4 ||
+ entry.args[0] !== '-NoProfile' ||
+ entry.args[1] !== '-NonInteractive' ||
+ entry.args[2] !== '-Command' ||
+ typeof entry.args[3] !== 'string'
+ ) {
+ return decline('malformed-argv');
+ }
+ return { envelope: 'split-command-args', family: 'windows-chain', body: entry.args[3] };
+ }
+ return decline('foreign-command');
+ }
+
+ if (entry.type !== 'local' || !Array.isArray(entry.command)) {
+ return decline('unknown-envelope');
+ }
+ const [interpreter, ...args] = entry.command;
+ if (interpreter === 'node') return decline('dev-mode');
+ if (interpreter === '/bin/sh') {
+ if (args.length !== 3 || args[0] !== '-l' || args[1] !== '-c' || typeof args[2] !== 'string') {
+ return decline('malformed-argv');
+ }
+ return { envelope: 'opencode-argv', family: 'unix-chain', body: args[2] };
+ }
+ if (interpreter === 'powershell') {
+ if (
+ args.length !== 4 ||
+ args[0] !== '-NoProfile' ||
+ args[1] !== '-NonInteractive' ||
+ args[2] !== '-Command' ||
+ typeof args[3] !== 'string'
+ ) {
+ return decline('malformed-argv');
+ }
+ return { envelope: 'opencode-argv', family: 'windows-chain', body: args[3] };
+ }
+ return decline('foreign-command');
+}
+
+function revisionFromFirstLine(body: string, family: McpLauncherFamily): number | null {
+ const firstLine = body.split(/\r?\n/, 1)[0];
+ const pattern = family === 'unix-chain' ? /^# ok-mcp-v([1-9]\d*)$/ : /^# ok-mcp-win-v([1-9]\d*)$/;
+ const match = firstLine?.match(pattern);
+ if (match === null || match === undefined) return null;
+ const revision = Number(match[1]);
+ return Number.isSafeInteger(revision) ? revision : null;
+}
+
+export function classifyMcpLauncherEntry(
+ entry: unknown,
+ catalog: McpLauncherRevisionCatalog = DEFAULT_MCP_LAUNCHER_REVISION_CATALOG,
+): McpLauncherClassification {
+ if (typeof entry !== 'object' || entry === null) return decline('not-an-object');
+ const extracted = extractLauncher(entry as Record<string, unknown>);
+ if ('kind' in extracted) return extracted;
+
+ const revision = revisionFromFirstLine(extracted.body, extracted.family);
+ if (revision === null) return decline('malformed-marker');
+
+ const registry = catalog[extracted.family];
+ const highestKnown = Math.max(...Object.keys(registry).map(Number));
+ if (revision > highestKnown) {
+ return {
+ kind: 'recognized',
+ disposition: 'keep',
+ descriptor: {
+ envelope: extracted.envelope,
+ family: extracted.family,
+ revision,
+ knowledge: 'future',
+ capabilities: 'opaque',
+ },
+ };
+ }
+
+ const capabilities: readonly McpLauncherCapability[] | undefined = registry[revision];
+ if (capabilities === undefined) return decline('unknown-revision');
+ return {
+ kind: 'recognized',
+ disposition: revision === highestKnown ? 'keep' : 'upgrade',
+ descriptor: {
+ envelope: extracted.envelope,
+ family: extracted.family,
+ revision,
+ knowledge: 'known',
+ capabilities,
+ },
+ };
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 9f9175f28..d0af6e141 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -379,6 +379,19 @@ export {
READ_DOCUMENT_HISTORY_DEPTH,
resolveIsHostedAgent,
} from './constants/mcp.ts';
+export {
+ classifyMcpLauncherEntry,
+ DEFAULT_MCP_LAUNCHER_REVISION_CATALOG,
+ type FutureMcpLauncherDescriptor,
+ type KnownMcpLauncherDescriptor,
+ type McpLauncherCapability,
+ type McpLauncherClassification,
+ type McpLauncherDeclineReason,
+ type McpLauncherDescriptor,
+ type McpLauncherEnvelope,
+ type McpLauncherFamily,
+ type McpLauncherRevisionCatalog,
+} from './constants/mcp-launcher.ts';
export {
MENU_LABELS,
type MenuLabelKey,
diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.ts
index 83d47404a..a363dfd54 100644
--- a/packages/core/src/markdown/callout-transformer.ts
+++ b/packages/core/src/markdown/callout-transformer.ts
@@ -1,3 +1,4 @@
+
import type { Blockquote, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.ts
index 9807a7e82..4499dbc92 100644
--- a/packages/core/src/markdown/code-fence.ts
+++ b/packages/core/src/markdown/code-fence.ts
@@ -1,3 +1,4 @@
+
export function selectFenceChar(info: string): '`' | '~' {
return info.includes('`') ? '~' : '`';
}
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index 7415c474a..34704165b 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.ts
index ece5c02a1..b6299a948 100644
--- a/packages/core/src/markdown/dedent-block-jsx-close.ts
+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts
@@ -1,3 +1,4 @@
+
import { findFencedRegions, isInsideFence } from './fence-regions.ts';
const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;
diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.ts
index 54774764a..acd398aa6 100644
--- a/packages/core/src/markdown/details-accordion-promoter.ts
+++ b/packages/core/src/markdown/details-accordion-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.ts
index 43ecdc709..ba9b56384 100644
--- a/packages/core/src/markdown/div-align-promoter.ts
+++ b/packages/core/src/markdown/div-align-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.ts
index 6d3f3643e..4513da9bb 100644
--- a/packages/core/src/markdown/fence-regions.ts
+++ b/packages/core/src/markdown/fence-regions.ts
@@ -1,3 +1,4 @@
+
const FENCE_RE = /^(`{3,}|~{3,})/gm;
export function findFencedRegions(src: string): Array<[number, number]> {
diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.ts
index 00f5771ee..6931623c7 100644
--- a/packages/core/src/markdown/fixtures/index.ts
+++ b/packages/core/src/markdown/fixtures/index.ts
@@ -1,3 +1,4 @@
+
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -8,6 +9,7 @@ function fixturePath(...segments: string[]): string {
return resolve(FIXTURES_DIR, ...segments);
}
+
interface GfmExample {
section: string;
markdown: string;
@@ -17,6 +19,7 @@ export function loadGfmExamples(): GfmExample[] {
return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];
}
+
interface MdxCrashEntry {
id: string;
input: string;
@@ -68,6 +71,7 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {
) as LargeEmbedFixture[];
}
+
export function loadPrd6955Before(): string {
return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');
}
@@ -76,6 +80,7 @@ export function loadPrd6955CorruptedTriplicated(): string {
return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');
}
+
export interface NgPinnedCase {
id: string;
name: string;
@@ -92,6 +97,7 @@ export function loadNgPinnedCases(): NgPinnedCase[] {
) as NgPinnedCase[];
}
+
export function loadLargeRealistic(): string {
return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');
}
diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.ts
index 8b1eb8519..daa3ef82b 100644
--- a/packages/core/src/markdown/fixtures/perf/generate.ts
+++ b/packages/core/src/markdown/fixtures/perf/generate.ts
@@ -1,3 +1,4 @@
+
import { writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -10,6 +11,7 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;
const SEED = 0xf1de1117;
+
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
@@ -36,6 +38,7 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {
return items[items.length - 1][0];
}
+
const WORDS = [
'lorem',
'ipsum',
@@ -153,6 +156,7 @@ function mdxBlock(rand: () => number): string {
return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;
}
+
type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';
const MIX: readonly [BlockKind, number][] = [
@@ -191,6 +195,7 @@ function generateDocument(blockCount: number, seed: number): string {
return `${blocks.join('\n\n')}\n`;
}
+
function main(): void {
for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {
const doc = generateDocument(count, SEED);
diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.ts
index 420dc0fe5..32c055c5b 100644
--- a/packages/core/src/markdown/guard-flanking-matrix.ts
+++ b/packages/core/src/markdown/guard-flanking-matrix.ts
@@ -7,6 +7,7 @@ import {
import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';
import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';
+
export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;
export type FlankClass = 'whitespace' | 'punctuation' | 'other';
diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.ts
index 2653473da..283913255 100644
--- a/packages/core/src/markdown/handler-shadow-audit.ts
+++ b/packages/core/src/markdown/handler-shadow-audit.ts
@@ -1,3 +1,4 @@
+
export interface HandlerShadowWitness {
input: string;
expect: 'byte' | 'byte-and-reparse-type';
diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.ts
index da0a81d23..5d1000cc4 100644
--- a/packages/core/src/markdown/highlight-promoter.ts
+++ b/packages/core/src/markdown/highlight-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.ts
index 787315157..9681c0056 100644
--- a/packages/core/src/markdown/html-to-mdast.ts
+++ b/packages/core/src/markdown/html-to-mdast.ts
@@ -1,3 +1,4 @@
+
import type { Element as HastElement, Root as HastRoot } from 'hast';
import type { List, Nodes as MdastNodes, Root as MdastRoot } from 'mdast';
import rehypeParse from 'rehype-parse';
@@ -128,7 +129,8 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRo
throw new HtmlPayloadTooLargeError(html.length, maxBytes);
}
- const processor = unified().use(rehypeParse, { fragment: true });
+ const processor = unified()
+ .use(rehypeParse, { fragment: true });
for (const plugin of cleanupPlugins) {
processor.use(plugin);
diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.ts
index 706fa9afb..994eb6917 100644
--- a/packages/core/src/markdown/image-promoter.ts
+++ b/packages/core/src/markdown/image-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Image, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.ts
index 779e27500..ec1ac1b7e 100644
--- a/packages/core/src/markdown/index.ts
+++ b/packages/core/src/markdown/index.ts
@@ -1,3 +1,4 @@
+
import {
type FromProseMirrorOptions,
fromPmMark,
@@ -206,6 +207,7 @@ export class MarkdownManager {
}
}
+
const registry = createRegistry();
function destructureAttrs(
@@ -254,6 +256,7 @@ function destructureAttrs(
return result;
}
+
function hasDirtyDescendant(node: PmNode): boolean {
let found = false;
node.descendants((child) => {
@@ -276,6 +279,7 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChec
return freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;
}
+
function isEmptyMdastParagraph(node: MdastNodes): boolean {
if (node.type !== 'paragraph') return false;
const children = node.children ?? [];
@@ -344,6 +348,7 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {
return out;
}
+
import {
AUDIO_EXTENSIONS,
FILE_ATTACHMENT_EXTENSIONS,
@@ -596,6 +601,7 @@ function buildMdastToPmHandlers(
}));
}
+
if (m.emphasis) {
handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({
sourceDelimiter: node.data?.sourceDelimiter ?? '*',
@@ -676,6 +682,7 @@ function buildMdastToPmHandlers(
}));
}
+
if (m.link) {
const sourceLiteralMark = m.sourceLiteral;
handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {
@@ -973,6 +980,7 @@ function buildMdastToPmHandlers(
};
}
+
const blockUnknownHandler = (node: {
type: string;
position?: { start: { offset: number }; end: { offset: number } };
@@ -1098,6 +1106,7 @@ function buildMdastToPmHandlers(
return handlers as RemarkProseMirrorOptions['handlers'];
}
+
function buildPmToMdastHandlers(
schema: Schema,
freshness: FreshnessCheckerHolder,
diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.ts
index fa0be9e86..b79e9aef7 100644
--- a/packages/core/src/markdown/lint/applies-to.ts
+++ b/packages/core/src/markdown/lint/applies-to.ts
@@ -1,3 +1,4 @@
+
import picomatch from 'picomatch';
import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';
diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.ts
index 312c9c74b..94b34dee1 100644
--- a/packages/core/src/markdown/lint/config-files.ts
+++ b/packages/core/src/markdown/lint/config-files.ts
@@ -1,3 +1,4 @@
+
const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set([
'.markdownlint.json',
'.markdownlint.jsonc',
diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.ts
index 3d4814597..7d97004fb 100644
--- a/packages/core/src/markdown/lint/config-schemas.ts
+++ b/packages/core/src/markdown/lint/config-schemas.ts
@@ -51,6 +51,7 @@ const fullPluginShape = Object.fromEntries(
LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),
) as z.ZodRawShape;
+
export const LinterConfigSchema = z.object({
enabled: z.boolean(),
plugins: z.object(fullPluginShape),
diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.ts
index d48eea5e4..a51f2ffb0 100644
--- a/packages/core/src/markdown/lint/default-config.ts
+++ b/packages/core/src/markdown/lint/default-config.ts
@@ -6,6 +6,7 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSetting
MD013: false,
};
+
export function resolveMarkdownlintConfig(
rules: Record<string, MarkdownlintRuleSetting> | undefined,
): Configuration {
diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
index ef478e268..9c9542661 100644
--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
@@ -1,3 +1,4 @@
+
import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';
export interface FrontmatterFieldConstraint {
diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.ts
index eba37cee7..ca6eed91c 100644
--- a/packages/core/src/markdown/lint/frontmatter-validate.ts
+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts
@@ -1,3 +1,4 @@
+
import Ajv, { type ValidateFunction } from 'ajv';
import Ajv2019 from 'ajv/dist/2019.js';
import Ajv2020 from 'ajv/dist/2020.js';
diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.ts
index ae5ff2924..9c2a0875e 100644
--- a/packages/core/src/markdown/lint/index.ts
+++ b/packages/core/src/markdown/lint/index.ts
@@ -1,3 +1,4 @@
+
import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';
import type { LintDiagnostic } from './types.ts';
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts b/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts
index 7a5af097e..f438f1b16 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts
@@ -1,3 +1,4 @@
+
import type { OkfRuleId } from '../okf-rule-meta.ts';
import { fileNameFor, OKF_SCHEMA_DIR, okfSchemaPathFor } from './paths.ts';
import { OKF_FRONTMATTER_REGISTRY } from './registry.ts';
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/paths.ts b/packages/core/src/markdown/lint/okf-frontmatter/paths.ts
index 1ee913527..c290b6878 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/paths.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/paths.ts
@@ -1,3 +1,4 @@
+
import type { OkfRuleId } from '../okf-rule-meta.ts';
export const OKF_SCHEMA_DIR = '.ok/okf';
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts b/packages/core/src/markdown/lint/okf-frontmatter/registry.ts
index de09740c5..5168602d5 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/registry.ts
@@ -1,3 +1,4 @@
+
import { compileAppliesTo } from '../applies-to.ts';
import { validateFrontmatterSource } from '../frontmatter-validate.ts';
import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from '../okf-rule-meta.ts';
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts b/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts
index f1c37671b..89845d3d5 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts
@@ -1,3 +1,4 @@
+
// file-level form is deliberate: the sibling `biome-ignore` must sit on the line
// oxlint-disable unicorn/no-thenable
diff --git a/packages/core/src/markdown/lint/okf-project/rules.ts b/packages/core/src/markdown/lint/okf-project/rules.ts
index 6d691ae2b..8b476332e 100644
--- a/packages/core/src/markdown/lint/okf-project/rules.ts
+++ b/packages/core/src/markdown/lint/okf-project/rules.ts
@@ -1,3 +1,4 @@
+
import { SUPPORTED_DOC_EXTENSIONS } from '../../../constants/doc-extensions.ts';
import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from '../okf-rule-meta.ts';
diff --git a/packages/core/src/markdown/lint/okf-rule-meta.ts b/packages/core/src/markdown/lint/okf-rule-meta.ts
index 4de50d79f..44913a9dc 100644
--- a/packages/core/src/markdown/lint/okf-rule-meta.ts
+++ b/packages/core/src/markdown/lint/okf-rule-meta.ts
@@ -1,3 +1,4 @@
+
export const OKF_RULE_IDS = [
'no-wiki-links',
'log-shape',
diff --git a/packages/core/src/markdown/lint/okf-rules.ts b/packages/core/src/markdown/lint/okf-rules.ts
index 1d5538421..d0999b62e 100644
--- a/packages/core/src/markdown/lint/okf-rules.ts
+++ b/packages/core/src/markdown/lint/okf-rules.ts
@@ -1,3 +1,4 @@
+
import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from './okf-rule-meta.ts';
import type { OkfRule } from './okf-runner.ts';
import { indexShape } from './rules/index-shape.ts';
diff --git a/packages/core/src/markdown/lint/okf-runner.ts b/packages/core/src/markdown/lint/okf-runner.ts
index de130e3f4..fabb08d6e 100644
--- a/packages/core/src/markdown/lint/okf-runner.ts
+++ b/packages/core/src/markdown/lint/okf-runner.ts
@@ -1,3 +1,4 @@
+
import type { Root } from 'mdast';
import remarkFrontmatter from 'remark-frontmatter';
import remarkGfm from 'remark-gfm';
diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.ts
index 4b9df9c56..03efcf66c 100644
--- a/packages/core/src/markdown/lint/plugins.ts
+++ b/packages/core/src/markdown/lint/plugins.ts
@@ -1,3 +1,4 @@
+
import { z } from 'zod';
import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';
import {
@@ -17,6 +18,7 @@ import {
type OkfSlice,
} from './types.ts';
+
const MarkdownlintRuleSettingSchema = z.union([
z.boolean(),
z.enum(MARKDOWNLINT_RULE_SEVERITIES),
diff --git a/packages/core/src/markdown/lint/rules/index-shape.ts b/packages/core/src/markdown/lint/rules/index-shape.ts
index 59fe9b87d..fcbb1b56c 100644
--- a/packages/core/src/markdown/lint/rules/index-shape.ts
+++ b/packages/core/src/markdown/lint/rules/index-shape.ts
@@ -1,3 +1,4 @@
+
import type { List, ListItem } from 'mdast';
import { EXIT, visit } from 'unist-util-visit';
import { defineScopedOkfRule } from '../okf-runner.ts';
diff --git a/packages/core/src/markdown/lint/rules/log-shape.ts b/packages/core/src/markdown/lint/rules/log-shape.ts
index e0159519f..431e4e9c8 100644
--- a/packages/core/src/markdown/lint/rules/log-shape.ts
+++ b/packages/core/src/markdown/lint/rules/log-shape.ts
@@ -1,3 +1,4 @@
+
import type { Heading } from 'mdast';
import { toString as headingText } from 'mdast-util-to-string';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/lint/rules/no-wiki-links.ts b/packages/core/src/markdown/lint/rules/no-wiki-links.ts
index 2123e977f..f75a04d15 100644
--- a/packages/core/src/markdown/lint/rules/no-wiki-links.ts
+++ b/packages/core/src/markdown/lint/rules/no-wiki-links.ts
@@ -1,3 +1,4 @@
+
import type { Point } from 'unist';
import { visit } from 'unist-util-visit';
import { defineOkfRule } from '../okf-runner.ts';
diff --git a/packages/core/src/markdown/lint/rules/reserved-casing.ts b/packages/core/src/markdown/lint/rules/reserved-casing.ts
index 89ef3e4a9..c8b4d8f28 100644
--- a/packages/core/src/markdown/lint/rules/reserved-casing.ts
+++ b/packages/core/src/markdown/lint/rules/reserved-casing.ts
@@ -1,3 +1,4 @@
+
import { SUPPORTED_DOC_EXTENSIONS } from '../../../constants/doc-extensions.ts';
import { defineOkfRule } from '../okf-runner.ts';
diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.ts
index 2a8f4a279..4fa9a5a27 100644
--- a/packages/core/src/markdown/lint/types.ts
+++ b/packages/core/src/markdown/lint/types.ts
@@ -1,3 +1,4 @@
+
import type { BrokenLinkReason } from '../../schemas/api/agent-write.ts';
import type { OkfRuleId } from './okf-rule-meta.ts';
@@ -105,6 +106,7 @@ export interface OkfSlice {
generate?: { index?: boolean };
}
+
interface RuleOptionSpecBase {
key: string;
description: string;
diff --git a/packages/core/src/markdown/lint/validation-counts.ts b/packages/core/src/markdown/lint/validation-counts.ts
index 98238656e..437cc539a 100644
--- a/packages/core/src/markdown/lint/validation-counts.ts
+++ b/packages/core/src/markdown/lint/validation-counts.ts
@@ -1,3 +1,4 @@
+
export interface ValidationSourceCounts {
errorCount: number;
warningCount: number;
diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.ts
index a5b511f25..bd79424c7 100644
--- a/packages/core/src/markdown/math-promoter.ts
+++ b/packages/core/src/markdown/math-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Code, Root } from 'mdast';
import type { Math as MdastMath } from 'mdast-util-math';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.ts
index ed89371d0..00fbc0035 100644
--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts
+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, ElementContent, Properties } from 'hast';
import type { FootnoteDefinition, FootnoteReference } from 'mdast';
import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.ts
index 8ce2b2492..df788a80d 100644
--- a/packages/core/src/markdown/mdast-to-html.ts
+++ b/packages/core/src/markdown/mdast-to-html.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root as HastRoot, Text as HastText } from 'hast';
import type { Root as MdastRoot, Text as MdastText } from 'mdast';
import type { Handler } from 'mdast-util-to-hast';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index bfd7e3109..fa3cfcd86 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.ts
index 1a897fca8..17ed2b829 100644
--- a/packages/core/src/markdown/mermaid-promoter.ts
+++ b/packages/core/src/markdown/mermaid-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Code, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.ts
index d988f4b8b..4aa0490c4 100644
--- a/packages/core/src/markdown/parse-with-fallback.ts
+++ b/packages/core/src/markdown/parse-with-fallback.ts
@@ -168,6 +168,7 @@ export function parseRecursive(
}
}
+
interface VFilePlace {
offset?: number;
start?: { offset?: number };
@@ -186,6 +187,7 @@ function extractErrorOffset(err: unknown): number | undefined {
return undefined;
}
+
interface Region {
start: number;
end: number;
@@ -209,6 +211,7 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {
return null;
}
+
export interface TagEvent {
kind: 'open' | 'close' | 'self-close';
name: string;
@@ -355,6 +358,7 @@ function findFallbackRegion(src: string, errorOffset: number): Region {
return { start: blockStart, end: blockEnd };
}
+
interface SourceBlock {
src: string;
start: number;
@@ -452,6 +456,7 @@ function tryPerBlockFallback(
};
}
+
function wholeDocRawText(source: string): JSONContent {
return {
type: 'doc',
diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.ts
index e6ab4fd57..43d420187 100644
--- a/packages/core/src/markdown/parser-drop-closure.ts
+++ b/packages/core/src/markdown/parser-drop-closure.ts
@@ -1,3 +1,4 @@
+
export type DroppedTokenAdjudication =
| {
kind: 'format-dof-axis';
diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.ts
index 0e3224206..55736041c 100644
--- a/packages/core/src/markdown/pipeline.ts
+++ b/packages/core/src/markdown/pipeline.ts
@@ -1,3 +1,4 @@
+
import {
type FromProseMirrorOptions,
fromProseMirror,
diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.ts
index 91cdf658f..ccf06e94d 100644
--- a/packages/core/src/markdown/position-aware-join.ts
+++ b/packages/core/src/markdown/position-aware-join.ts
@@ -1,3 +1,4 @@
+
import type { Join } from 'mdast-util-to-markdown';
import type { Position } from 'unist';
import { isBlankLineParagraph } from './zero-emission-blocks.ts';
diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.ts
index 0f399d34c..e5b4c9eba 100644
--- a/packages/core/src/markdown/position-slice.ts
+++ b/packages/core/src/markdown/position-slice.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Root } from 'mdast';
import { visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
@@ -476,7 +477,8 @@ export function applyPositionSliceToNode(
const first = source[startOff];
if (first !== '[' && first !== '<' && !node.title) {
node.data.sourceStyle = 'gfm-autolink';
- } else if (first === '[') {
+ }
+ else if (first === '[') {
const slice = source.slice(startOff, endOff);
const closeBracketIdx = slice.lastIndexOf('](');
if (closeBracketIdx !== -1) {
diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
index db10fa54b..ca225ce9b 100644
--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, Root, Text } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
index 34068d103..3a2524a9a 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
index 93151d43b..2279a0189 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
index 188f02d83..a0f467c42 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
index 4ba2c3418..4e8542a21 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
index 1a74b1272..a3c96b24a 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
index de35e7b79..e95cf43d6 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
index b4be1b2ea..ffdb4d5b5 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
index 3c8d88b7c..e2a96d1a7 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.ts
index cf2c9da8e..0389575ac 100644
--- a/packages/core/src/markdown/resolve-image-url.ts
+++ b/packages/core/src/markdown/resolve-image-url.ts
@@ -1,3 +1,4 @@
+
import { isRelativeUrl } from './safe-url.ts';
function isDevDiagnosticContext(): boolean {
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 4d3250d3a..8be632ba4 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,3 +1,4 @@
+
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/core/src/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
index 0dd54070e..96304e7a5 100644
--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts
+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
@@ -1,3 +1,4 @@
+
import type { JSONContent } from '@tiptap/core';
import type { Nodes } from 'mdast';
import { expect } from 'vitest';
diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.ts
index 7cac5b042..93798cf83 100644
--- a/packages/core/src/markdown/serialize-helpers.ts
+++ b/packages/core/src/markdown/serialize-helpers.ts
@@ -1,3 +1,4 @@
+
import type { Node as PmNode } from '@tiptap/pm/model';
import type {
MdxJsxAttribute,
diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.ts
index b012a5aff..8c08b7a04 100644
--- a/packages/core/src/markdown/single-dollar-math-promoter.ts
+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts
@@ -1,3 +1,4 @@
+
import type { PhrasingContent, Root, Text } from 'mdast';
import type { InlineMath } from 'mdast-util-math';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.ts
index 3e79f8cb6..959cc0bd2 100644
--- a/packages/core/src/markdown/to-markdown-handlers.ts
+++ b/packages/core/src/markdown/to-markdown-handlers.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parents } from 'mdast';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { Handle, Info, State } from 'mdast-util-to-markdown';
diff --git a/packages/core/src/markdown/underline-promoter.ts b/packages/core/src/markdown/underline-promoter.ts
index 0f1b0f27d..6e6d73400 100644
--- a/packages/core/src/markdown/underline-promoter.ts
+++ b/packages/core/src/markdown/underline-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, Root } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.ts
index 1a082bda7..932d7d2a8 100644
--- a/packages/core/src/markdown/unknown-mdast-guard.ts
+++ b/packages/core/src/markdown/unknown-mdast-guard.ts
@@ -1,3 +1,4 @@
+
import type { Root as MdastRoot } from 'mdast';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.ts
index d578476a7..ac9f5239b 100644
--- a/packages/core/src/markdown/whitespace-char-ref.ts
+++ b/packages/core/src/markdown/whitespace-char-ref.ts
@@ -1,3 +1,4 @@
+
const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([
[0x20, ' '],
[0x09, '\t'],
diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.ts
index 6dad26200..afd9936fe 100644
--- a/packages/core/src/markdown/wiki-link-micromark.ts
+++ b/packages/core/src/markdown/wiki-link-micromark.ts
@@ -17,6 +17,7 @@ declare module 'micromark-util-types' {
}
}
+
const CODE_BANG = 33; // !
const CODE_LBRACKET = 91; // [
const CODE_RBRACKET = 93; // ]
@@ -260,6 +261,7 @@ export function wikiLinkSyntax(): Extension {
};
}
+
function enterWikiLink(this: CompileContext, token: Token) {
this.enter(
{
@@ -385,6 +387,7 @@ export const wikiLinkToMarkdown: {
unsafe: [{ character: '[', inConstruct: ['phrasing'] }],
};
+
const MICROMARK_EXT = wikiLinkSyntax();
export function remarkWikiLink(this: Processor) {
diff --git a/packages/desktop/src/main/claude-readiness.ts b/packages/desktop/src/main/claude-readiness.ts
index e672fb144..f0c6858ae 100644
--- a/packages/desktop/src/main/claude-readiness.ts
+++ b/packages/desktop/src/main/claude-readiness.ts
@@ -21,7 +21,7 @@
*/
import type { McpEntryClassification } from '@inkeep/open-knowledge';
-import { TERMINAL_CLI_IDS, type TerminalCli } from '@inkeep/open-knowledge-core';
+import { TERMINAL_CLI_IDS, TERMINAL_CLIS, type TerminalCli } from '@inkeep/open-knowledge-core';
import type { ClaudeReadiness, CliReadiness } from '../shared/bridge-contract.ts';
import { getLogger } from './desktop-logger.ts';
@@ -274,3 +274,26 @@ export async function resolveCliInstalledMap(
}
return map;
}
+
+export interface ResolvePlatformCliInstalledMapDeps {
+ readonly platform: NodeJS.Platform;
+ readonly probePosix: (args: readonly string[]) => Promise<number | null>;
+ readonly probeWindows: (bin: string) => Promise<boolean>;
+}
+
+/**
+ * Resolve every registered CLI against the host's real executable lookup.
+ * Windows needs `where` so PATHEXT-backed `.cmd` launchers count; POSIX hosts
+ * need the login shell because desktop processes do not inherit its PATH.
+ */
+export function resolvePlatformCliInstalledMap(
+ deps: ResolvePlatformCliInstalledMapDeps,
+): Promise<Partial<Record<TerminalCli, boolean>>> {
+ return resolveCliInstalledMap({
+ probe: async (cli) => {
+ const bin = TERMINAL_CLIS[cli].bin;
+ if (deps.platform === 'win32') return (await deps.probeWindows(bin)) ? 0 : 127;
+ return deps.probePosix(cliProbeArgs(bin));
+ },
+ });
+}
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 6257f49c5..1b83e0384 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -214,8 +214,8 @@ import {
import {
cliProbeArgs,
resolveClaudeReadiness,
- resolveCliInstalledMap,
resolveCliOnPath,
+ resolvePlatformCliInstalledMap,
runLoginShellProbe,
} from './claude-readiness.ts';
import { requestUserConsent, walkExceedsCap } from './consent-dialog.ts';
@@ -4762,8 +4762,10 @@ function resolveTerminalCliInstalledMap(): Promise<Partial<Record<TerminalCli, b
if (cliInstalledMapCache && now - cliInstalledMapCache.at < CLI_INSTALLED_MAP_TTL_MS) {
return cliInstalledMapCache.value;
}
- const value = resolveCliInstalledMap({
- probe: (cli) => probeLoginShellOnPath(cliProbeArgs(TERMINAL_CLIS[cli].bin)),
+ const value = resolvePlatformCliInstalledMap({
+ platform: process.platform,
+ probePosix: (args) => probeLoginShellOnPath(args),
+ probeWindows: (bin) => probeWindowsPath(bin),
}).catch((err) => {
// Don't let a rejected probe stay cached for the full TTL; the next call retries fresh.
cliInstalledMapCache = null;
diff --git a/packages/desktop/src/main/mcp-wiring.test.ts b/packages/desktop/src/main/mcp-wiring.test.ts
index 98ffd1490..3cd66625b 100644
--- a/packages/desktop/src/main/mcp-wiring.test.ts
+++ b/packages/desktop/src/main/mcp-wiring.test.ts
@@ -189,6 +189,38 @@ describe('checkAndRepairMcpWiringOnStartup — migrate event ordering', () => {
expect(order).toEqual([]);
expect(events.some((e) => e.event === 'mcp-config-migrate')).toBe(false);
});
+
+ test('recognized future chain entry → no downgrade and no write', async () => {
+ const futureEntry = {
+ command: '/bin/sh',
+ args: ['-l', '-c', '# ok-mcp-v99\nexit 127'],
+ };
+ const { cli, events, order } = buildStartupCli({
+ classify: { kind: 'present', entry: futureEntry },
+ });
+
+ const result = await checkAndRepairMcpWiringOnStartup({
+ isPackaged: true,
+ executablePath: PACKAGED_EXE,
+ home: '/home',
+ platform: 'darwin',
+ ipcMain: { handle() {}, removeHandler() {} } as unknown as Parameters<
+ typeof checkAndRepairMcpWiringOnStartup
+ >[0]['ipcMain'],
+ cli,
+ logger: {
+ info() {},
+ warn() {},
+ error() {},
+ event: (e) => events.push(e),
+ },
+ });
+
+ expect(result.status).toBe('ok');
+ expect(order).toEqual([]);
+ expect(events).toContainEqual({ event: 'mcp-wiring-repair-healthy-current', editor: 'claude' });
+ expect(events.some((e) => e.event === 'mcp-config-migrate')).toBe(false);
+ });
});
describe('checkAndRepairMcpWiringOnStartup — non-destructive decline', () => {
diff --git a/packages/desktop/src/main/mcp-wiring.ts b/packages/desktop/src/main/mcp-wiring.ts
index 16100b90a..4998872d4 100644
--- a/packages/desktop/src/main/mcp-wiring.ts
+++ b/packages/desktop/src/main/mcp-wiring.ts
@@ -42,10 +42,10 @@ import {
type EditorMcpTarget,
editorConfigPathDisplay,
editorEntryLocator,
- isEntryUpToDate,
type McpDeclineReason,
type McpEntryClassification,
} from '@inkeep/open-knowledge';
+import { classifyMcpLauncherEntry } from '@inkeep/open-knowledge-core';
import type { IpcMain, IpcMainInvokeEvent } from 'electron';
import type {
McpWiringConfirmRequest,
@@ -511,9 +511,12 @@ export function checkAndRepairMcpWiringOnStartup(
continue;
}
- if (classification.kind === 'present' && isEntryUpToDate(classification.entry)) {
- logger.event({ event: 'mcp-wiring-repair-healthy-current', editor });
- continue;
+ if (classification.kind === 'present') {
+ const launcher = classifyMcpLauncherEntry(classification.entry);
+ if (launcher.kind === 'recognized' && launcher.disposition === 'keep') {
+ logger.event({ event: 'mcp-wiring-repair-healthy-current', editor });
+ continue;
+ }
}
if (classification.kind === 'decline') {
@@ -728,8 +731,8 @@ export function runMcpWiringOnFirstLaunch(opts: RunMcpWiringFirstLaunchOpts): Ru
// Namespace ownership means we ALWAYS overwrite that token under the
// user's consent, regardless of whether the existing entry matches
// today's chain shape or a foreign customization. The sentinel-based
- // `isEntryUpToDate` predicate is the authoritative no-op gate at
- // write time (skips byte-identical chain entries); the arming-time
+ // The ordered launcher classifier is the authoritative no-op gate at
+ // write time (including recognized future chains); the arming-time
// probe here is purely a disclosure aid that errs on the side of
// showing the user every row Add would touch. `readExistingMcpEntry`
// returns null when the config file is absent or has no entry for
diff --git a/packages/desktop/src/main/project-mcp-reclaim.test.ts b/packages/desktop/src/main/project-mcp-reclaim.test.ts
index fc34a5bdc..85d768154 100644
--- a/packages/desktop/src/main/project-mcp-reclaim.test.ts
+++ b/packages/desktop/src/main/project-mcp-reclaim.test.ts
@@ -13,6 +13,10 @@ import {
const EXE = '/Applications/OpenKnowledge.app/Contents/MacOS/OpenKnowledge';
const CHAIN_ENTRY = buildManagedServerEntry({ mode: 'published' });
+const KNOWN_OLDER_ENTRY = {
+ command: '/bin/sh',
+ args: ['-l', '-c', '# ok-mcp-v1\nexit 127'],
+};
function fakeTarget(id: McpWiringEditorId, projectConfigPath?: string): EditorMcpTarget {
return {
@@ -201,13 +205,35 @@ describe('checkAndRepairProjectMcpOnProjectOpen', () => {
expect(writes).toEqual([]);
});
- test('incompatible entry → reclaimed (write occurs in place, no rename)', async () => {
+ test('recognized future entry → healthy-current, no downgrade write', async () => {
const { cli, writes } = buildCli({
claude: {
target: fakeTarget('claude' as McpWiringEditorId, '/p/.mcp.json'),
classification: {
kind: 'present',
- entry: { command: 'npx', args: ['-y', '@inkeep/open-knowledge', 'mcp'] },
+ entry: { command: '/bin/sh', args: ['-l', '-c', '# ok-mcp-v99\nfuture body'] },
+ },
+ },
+ });
+ const r = await checkAndRepairProjectMcpOnProjectOpen({
+ projectDir: '/p',
+ executablePath: EXE,
+ isPackaged: true,
+ platform: 'darwin',
+ cli,
+ });
+ expect(r.status).toBe('done');
+ if (r.status === 'done') expect(r.perEditor[0]?.status).toBe('healthy-current');
+ expect(writes).toEqual([]);
+ });
+
+ test('known older entry → reclaimed (write occurs in place, no rename)', async () => {
+ const { cli, writes } = buildCli({
+ claude: {
+ target: fakeTarget('claude' as McpWiringEditorId, '/p/.mcp.json'),
+ classification: {
+ kind: 'present',
+ entry: KNOWN_OLDER_ENTRY,
},
},
});
@@ -223,6 +249,30 @@ describe('checkAndRepairProjectMcpOnProjectOpen', () => {
expect(writes).toEqual(['claude']);
});
+ test('foreign entry → declined without a write', async () => {
+ const { cli, writes } = buildCli({
+ claude: {
+ target: fakeTarget('claude' as McpWiringEditorId, '/p/.mcp.json'),
+ classification: {
+ kind: 'present',
+ entry: { command: '/usr/bin/foreign', args: ['server.js'] },
+ },
+ },
+ });
+ const r = await checkAndRepairProjectMcpOnProjectOpen({
+ projectDir: '/p',
+ executablePath: EXE,
+ isPackaged: true,
+ platform: 'darwin',
+ cli,
+ });
+ expect(r.status).toBe('done');
+ if (r.status === 'done') {
+ expect(r.perEditor[0]).toMatchObject({ status: 'declined', reason: 'foreign-command' });
+ }
+ expect(writes).toEqual([]);
+ });
+
test('write declines (read-then-write race) → declined, not a false reclaimed', async () => {
// The classify pre-pass sees a reclaimable entry, but the lock-time write
// declines (a concurrent harness truncated the file, or it grew past the
@@ -233,7 +283,7 @@ describe('checkAndRepairProjectMcpOnProjectOpen', () => {
target: fakeTarget('claude' as McpWiringEditorId, '/p/.mcp.json'),
classification: {
kind: 'present',
- entry: { command: 'npx', args: ['-y', '@inkeep/open-knowledge', 'mcp'] },
+ entry: KNOWN_OLDER_ENTRY,
},
writeOutcome: { action: 'declined', reason: 'unparseable' },
},
@@ -267,7 +317,7 @@ describe('checkAndRepairProjectMcpOnProjectOpen', () => {
expect(decline).not.toHaveProperty('configPath');
});
- test('incompatible entry emits mcp-config-migrate before the write', async () => {
+ test('known older entry emits mcp-config-migrate before the write', async () => {
// Records the order of (event-emit, write) calls so we can assert the
// migrate event lands BEFORE the writer is invoked — captures "intent to
// migrate" even when the write subsequently fails.
@@ -278,7 +328,7 @@ describe('checkAndRepairProjectMcpOnProjectOpen', () => {
allEditorIds: ['claude' as McpWiringEditorId],
classifyExistingProjectMcpConfig: () => ({
kind: 'present',
- entry: { command: 'npx', args: ['-y', '@inkeep/open-knowledge', 'mcp'] },
+ entry: KNOWN_OLDER_ENTRY,
}),
writeProjectMcpConfig: () => {
order.push('write');
@@ -310,8 +360,8 @@ describe('checkAndRepairProjectMcpOnProjectOpen', () => {
surface: 'desktop-project-open',
editorId: 'claude',
configPath: '/p/.mcp.json',
- priorCommand: 'npx',
- priorArgs: ['-y', '@inkeep/open-knowledge', 'mcp'],
+ priorCommand: '/bin/sh',
+ priorArgs: ['-l', '-c', '# ok-mcp-v1\nexit 127'],
});
});
@@ -367,7 +417,7 @@ describe('checkAndRepairProjectMcpOnProjectOpen', () => {
},
cursor: {
target: fakeTarget('cursor' as McpWiringEditorId, '/p/.cursor/mcp.json'),
- classification: { kind: 'present', entry: { command: 'old' } },
+ classification: { kind: 'present', entry: KNOWN_OLDER_ENTRY },
writeOutcome: { action: 'overwritten' },
},
});
@@ -391,7 +441,7 @@ describe('checkAndRepairProjectMcpOnProjectOpen', () => {
const { cli } = buildCli({
claude: {
target: fakeTarget('claude' as McpWiringEditorId, '/p/.mcp.json'),
- classification: { kind: 'present', entry: { command: 'old' } },
+ classification: { kind: 'present', entry: KNOWN_OLDER_ENTRY },
writeOutcome: { action: 'failed', error: 'EACCES' },
},
});
@@ -417,12 +467,12 @@ describe('checkAndRepairProjectMcpOnProjectOpen', () => {
const { cli, writes } = buildCli({
claude: {
target: fakeTarget('claude' as McpWiringEditorId, '/p/.mcp.json'),
- classification: { kind: 'present', entry: { command: 'old' } },
+ classification: { kind: 'present', entry: KNOWN_OLDER_ENTRY },
writeOutcome: { action: 'failed', error: 'EACCES' },
},
cursor: {
target: fakeTarget('cursor' as McpWiringEditorId, '/p/.cursor/mcp.json'),
- classification: { kind: 'present', entry: { command: 'old' } },
+ classification: { kind: 'present', entry: KNOWN_OLDER_ENTRY },
writeOutcome: { action: 'overwritten' },
},
});
diff --git a/packages/desktop/src/main/project-mcp-reclaim.ts b/packages/desktop/src/main/project-mcp-reclaim.ts
index b8f19d053..c3e5da1a7 100644
--- a/packages/desktop/src/main/project-mcp-reclaim.ts
+++ b/packages/desktop/src/main/project-mcp-reclaim.ts
@@ -14,6 +14,7 @@ import {
type McpEntryClassification,
truncatePriorEntry,
} from '@inkeep/open-knowledge';
+import { classifyMcpLauncherEntry } from '@inkeep/open-knowledge-core';
import type { McpWiringEditorId } from '../shared/ipc-channels.ts';
import { classifyInstallShape } from './install-shape.ts';
@@ -162,16 +163,6 @@ export async function checkAndRepairProjectMcpOnProjectOpen(
continue;
}
- if (classification.kind === 'present' && isEntryUpToDate(classification.entry)) {
- perEditor.push({ editor, status: 'healthy-current', configPath: projectPath });
- logger.event({
- event: 'project-mcp-reclaim-healthy-current',
- editor,
- configPath: projectPath,
- });
- continue;
- }
-
if (classification.kind === 'decline') {
// OpenKnowledge is a guest in another tool's config: a present, non-empty
// file it cannot fully parse is left byte-untouched — never renamed aside
@@ -195,6 +186,48 @@ export async function checkAndRepairProjectMcpOnProjectOpen(
continue;
}
+ if (classification.kind === 'present') {
+ if (editor === 'pi') {
+ if (isEntryUpToDate(classification.entry)) {
+ perEditor.push({ editor, status: 'healthy-current', configPath: projectPath });
+ logger.event({
+ event: 'project-mcp-reclaim-healthy-current',
+ editor,
+ configPath: projectPath,
+ });
+ continue;
+ }
+ } else {
+ const launcher = classifyMcpLauncherEntry(classification.entry);
+ if (launcher.kind === 'recognized' && launcher.disposition === 'keep') {
+ perEditor.push({ editor, status: 'healthy-current', configPath: projectPath });
+ logger.event({
+ event: 'project-mcp-reclaim-healthy-current',
+ editor,
+ configPath: projectPath,
+ });
+ continue;
+ }
+ if (launcher.kind === 'declined') {
+ perEditor.push({
+ editor,
+ status: 'declined',
+ configPath: projectPath,
+ reason: launcher.reason,
+ });
+ logger.event(
+ buildMcpConfigDeclineEvent({
+ scope: 'project',
+ surface: 'desktop-project-open',
+ editorId: editor,
+ reason: launcher.reason,
+ }),
+ );
+ continue;
+ }
+ }
+ }
+
if (classification.kind !== 'present') {
// Exhaustiveness guard: absent / no-entry / healthy-current / decline all
// `continue` above, so only an incompatible `present` reaches here. A new
diff --git a/packages/desktop/src/utility/server-entry.ts b/packages/desktop/src/utility/server-entry.ts
index 52e820a25..943a53a4c 100644
--- a/packages/desktop/src/utility/server-entry.ts
+++ b/packages/desktop/src/utility/server-entry.ts
@@ -24,6 +24,7 @@ import { rename, writeFile } from 'node:fs/promises';
import { isAbsolute, relative, resolve } from 'node:path';
import {
detectGh,
+ getNativeTomlMcpEditor,
loadConfig,
makeLazyProbeTokenStore,
probeOwnManagedEditorMcpEntry,
@@ -372,6 +373,7 @@ export function setupUtility(deps: SetupUtilityDeps): UtilityHandle {
detectGh,
tokenStore,
embeddingsKeyStore,
+ mcpTomlEditor: getNativeTomlMcpEditor(),
// ACP threads skip injecting the `open-knowledge` MCP server when the
// agent's own harness already loads OK's managed editor-config entry
// (same wiring as `ok start`).
diff --git a/packages/desktop/tests/main/claude-readiness.test.ts b/packages/desktop/tests/main/claude-readiness.test.ts
index 634cc4873..398d94388 100644
--- a/packages/desktop/tests/main/claude-readiness.test.ts
+++ b/packages/desktop/tests/main/claude-readiness.test.ts
@@ -10,6 +10,7 @@ import {
resolveClaudeReadiness,
resolveCliInstalledMap,
resolveCliOnPath,
+ resolvePlatformCliInstalledMap,
runLoginShellProbe,
} from '../../src/main/claude-readiness.ts';
@@ -444,3 +445,40 @@ describe('resolveCliInstalledMap', () => {
expect(Object.keys(map).sort()).toEqual([...TERMINAL_CLI_IDS].sort());
});
});
+
+describe('resolvePlatformCliInstalledMap', () => {
+ test('Windows resolves registry binaries with the native PATH probe', async () => {
+ const probePosix = vi.fn(async () => 127);
+ const probeWindows = vi.fn(async (bin: string) => bin === 'codex');
+
+ const map = await resolvePlatformCliInstalledMap({
+ platform: 'win32',
+ probePosix,
+ probeWindows,
+ });
+
+ expect(map.codex).toBe(true);
+ expect(map.cursor).toBe(false);
+ expect(probePosix).not.toHaveBeenCalled();
+ expect(probeWindows).toHaveBeenCalledWith('codex');
+ expect(probeWindows).toHaveBeenCalledWith('cursor-agent');
+ });
+
+ test('POSIX hosts keep using the login-shell probe', async () => {
+ const probePosix = vi.fn(async (args: readonly string[]) =>
+ args.at(-1) === 'command -v cursor-agent' ? 0 : 127,
+ );
+ const probeWindows = vi.fn(async () => false);
+
+ const map = await resolvePlatformCliInstalledMap({
+ platform: 'darwin',
+ probePosix,
+ probeWindows,
+ });
+
+ expect(map.cursor).toBe(true);
+ expect(map.codex).toBe(false);
+ expect(probeWindows).not.toHaveBeenCalled();
+ expect(probePosix).toHaveBeenCalledWith(cliProbeArgs('cursor-agent'));
+ });
+});
diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.ts
index 68b3570ef..ca33c2bf8 100644
--- a/packages/server/src/boot.ts
+++ b/packages/server/src/boot.ts
@@ -217,6 +217,7 @@ export interface BootServerOptions
| 'debounce'
| 'maxDebounce'
| 'gitEnabled'
+ | 'mcpTomlEditor'
| 'commitDebounceMs'
| 'wipRef'
| 'destroyTimeoutMs'
@@ -792,6 +793,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
debounce: opts.debounce,
maxDebounce: opts.maxDebounce,
gitEnabled: opts.gitEnabled,
+ mcpTomlEditor: opts.mcpTomlEditor,
commitDebounceMs: opts.commitDebounceMs,
wipRef: opts.wipRef,
enableTestRoutes: opts.enableTestRoutes,
diff --git a/packages/server/src/mcp-config-reconciler.test.ts b/packages/server/src/mcp-config-reconciler.test.ts
new file mode 100644
index 000000000..74c9d6f4d
--- /dev/null
+++ b/packages/server/src/mcp-config-reconciler.test.ts
@@ -0,0 +1,191 @@
+import { parse as parseJsonc } from 'jsonc-parser';
+import { describe, expect, test } from 'vitest';
+import { type NativeTomlMcpEditor, reconcileTrackedMcpConfig } from './mcp-config-reconciler.ts';
+
+const v1 = { command: '/bin/sh', args: ['-l', '-c', '# ok-mcp-v1\nexit 127'] };
+const v2 = { command: '/bin/sh', args: ['-l', '-c', '# ok-mcp-v2\nexit 127'] };
+const v99 = { command: '/bin/sh', args: ['-l', '-c', '# ok-mcp-v99\nexit 127'] };
+
+function config(entry: unknown, theme = 'dark'): string {
+ return [
+ '{',
+ ` // user setting must survive`,
+ ` "theme": "${theme}",`,
+ ' "mcpServers": {',
+ ' "other": { "command": "other", "env": { "TOKEN": "keep" } },',
+ ` "open-knowledge": ${JSON.stringify(entry)}`,
+ ' }',
+ '}',
+ '',
+ ].join('\n');
+}
+
+describe('reconcileTrackedMcpConfig', () => {
+ test('selects a recognized newer entry and preserves the local unowned shell', () => {
+ const base = config(v1);
+ const local = config(v1, 'light');
+ const incoming = config(v2);
+
+ const plan = reconcileTrackedMcpConfig({
+ target: '.mcp.json',
+ layers: { base, head: base, index: local, worktree: local, incoming },
+ });
+
+ expect(plan.kind).toBe('resolved');
+ if (plan.kind !== 'resolved') return;
+ expect(plan.raw).toContain('"theme": "light"');
+ expect(plan.raw).toContain('"other": { "command": "other", "env": { "TOKEN": "keep" } }');
+ expect(plan.raw).toContain('# ok-mcp-v2');
+ expect(plan.raw).not.toContain('# ok-mcp-v1');
+ });
+
+ test('never downgrades a recognized future entry', () => {
+ const base = config(v1);
+ const future = config(v99);
+ const plan = reconcileTrackedMcpConfig({
+ target: '.cursor/mcp.json',
+ layers: { base, head: base, index: future, worktree: future, incoming: config(v2) },
+ });
+
+ expect(plan.kind).toBe('resolved');
+ if (plan.kind !== 'resolved') return;
+ expect(plan.raw).toContain('# ok-mcp-v99');
+ expect(plan.winner.revision).toBe(99);
+ });
+
+ test('preserves an incoming user field while upgrading the launcher', () => {
+ const base = config({ ...v1, env: { MODE: 'base' } });
+ const incoming = config({ ...v2, env: { MODE: 'incoming' } });
+ const plan = reconcileTrackedMcpConfig({
+ target: '.mcp.json',
+ layers: { base, head: base, index: base, worktree: base, incoming },
+ });
+
+ expect(plan.kind).toBe('resolved');
+ if (plan.kind !== 'resolved') return;
+ expect(parseJsonc(plan.raw).mcpServers['open-knowledge']).toMatchObject({
+ env: { MODE: 'incoming' },
+ });
+ expect(plan.raw).toContain('# ok-mcp-v2');
+ });
+
+ test('preserves a local user field while accepting an incoming launcher upgrade', () => {
+ const base = config({ ...v1, env: { MODE: 'base' } });
+ const local = config({ ...v1, env: { MODE: 'local' } });
+ const incoming = config({ ...v2, env: { MODE: 'base' } });
+ const plan = reconcileTrackedMcpConfig({
+ target: '.mcp.json',
+ layers: { base, head: base, index: local, worktree: local, incoming },
+ });
+
+ expect(plan.kind).toBe('resolved');
+ if (plan.kind !== 'resolved') return;
+ expect(parseJsonc(plan.raw).mcpServers['open-knowledge']).toMatchObject({
+ env: { MODE: 'local' },
+ });
+ expect(plan.raw).toContain('# ok-mcp-v2');
+ });
+
+ test('declines when both sides change the same user-owned entry field', () => {
+ const base = config({ ...v1, env: { MODE: 'base' } });
+ const local = config({ ...v1, env: { MODE: 'local' } });
+ const incoming = config({ ...v2, env: { MODE: 'incoming' } });
+
+ expect(
+ reconcileTrackedMcpConfig({
+ target: '.mcp.json',
+ layers: { base, head: base, index: local, worktree: local, incoming },
+ }),
+ ).toEqual({ kind: 'declined', reason: 'unowned-shell-conflict' });
+ });
+
+ test('declines incompatible unrelated edits instead of choosing ours or theirs', () => {
+ const base = config(v1, 'base');
+ const plan = reconcileTrackedMcpConfig({
+ target: '.mcp.json',
+ layers: {
+ base,
+ head: base,
+ index: config(v1, 'local'),
+ worktree: config(v1, 'local'),
+ incoming: config(v2, 'incoming'),
+ },
+ });
+
+ expect(plan).toEqual({ kind: 'declined', reason: 'unowned-shell-conflict' });
+ });
+
+ test('declines staged/unstaged divergence outside the owned entry', () => {
+ const base = config(v1, 'base');
+ const plan = reconcileTrackedMcpConfig({
+ target: '.mcp.json',
+ layers: {
+ base,
+ head: base,
+ index: config(v1, 'staged'),
+ worktree: config(v2, 'unstaged'),
+ incoming: config(v2, 'base'),
+ },
+ });
+
+ expect(plan).toEqual({ kind: 'declined', reason: 'index-worktree-divergence' });
+ });
+
+ test('declines a foreign same-name entry', () => {
+ const base = config(v1);
+ const foreign = config({ command: 'my-wrapper', args: [] });
+ expect(
+ reconcileTrackedMcpConfig({
+ target: '.mcp.json',
+ layers: { base, head: base, index: foreign, worktree: foreign, incoming: config(v2) },
+ }),
+ ).toEqual({ kind: 'declined', reason: 'foreign-entry' });
+ });
+
+ test('declines truthfully when every layer lacks the managed entry', () => {
+ const withoutEntry = JSON.stringify({ mcpServers: { other: { command: 'keep-me' } } });
+ expect(
+ reconcileTrackedMcpConfig({
+ target: '.mcp.json',
+ layers: {
+ base: withoutEntry,
+ head: withoutEntry,
+ index: withoutEntry,
+ worktree: withoutEntry,
+ incoming: withoutEntry,
+ },
+ }),
+ ).toEqual({ kind: 'declined', reason: 'no-entry' });
+ });
+
+ test('reports a native TOML write failure as unparseable', () => {
+ let upsertCalls = 0;
+ const editor: NativeTomlMcpEditor = {
+ parseToObject: () => ({ mcp_servers: { 'open-knowledge': v1 } }),
+ removeEntry: (raw) => ({ text: raw, existed: true }),
+ upsertEntry: (raw) => {
+ upsertCalls++;
+ if (upsertCalls > 5) throw new Error('synthetic native write failure');
+ return { text: raw, existed: true };
+ },
+ };
+ const raw = '[mcp_servers.open-knowledge]\ncommand = "/bin/sh"\n';
+
+ expect(
+ reconcileTrackedMcpConfig({
+ target: '.codex/config.toml',
+ layers: { base: raw, head: raw, index: raw, worktree: raw, incoming: raw },
+ tomlEditor: editor,
+ }),
+ ).toEqual({ kind: 'declined', reason: 'unparseable' });
+ });
+
+ test('Pi is not a tracked entry target', () => {
+ expect(
+ reconcileTrackedMcpConfig({
+ target: '.pi/mcp.json',
+ layers: { base: null, head: null, index: null, worktree: null, incoming: null },
+ }),
+ ).toEqual({ kind: 'declined', reason: 'unsupported-target' });
+ });
+});
diff --git a/packages/server/src/mcp-config-reconciler.ts b/packages/server/src/mcp-config-reconciler.ts
new file mode 100644
index 000000000..8d475b7c1
--- /dev/null
+++ b/packages/server/src/mcp-config-reconciler.ts
@@ -0,0 +1,396 @@
+import { classifyMcpLauncherEntry, type McpLauncherDescriptor } from '@inkeep/open-knowledge-core';
+import {
+ applyEdits,
+ findNodeAtLocation,
+ getNodeValue,
+ type Node as JsonNode,
+ modify,
+ type ParseError,
+ parseTree,
+} from 'jsonc-parser';
+
+const MAX_CONFIG_BYTES = 10 * 1024 * 1024;
+
+export const TRACKED_MCP_CONFIG_TARGETS = [
+ '.mcp.json',
+ '.cursor/mcp.json',
+ '.codex/config.toml',
+ 'opencode.json',
+] as const;
+
+type TrackedMcpConfigTarget = (typeof TRACKED_MCP_CONFIG_TARGETS)[number];
+
+export interface RawMcpConfigLayers {
+ readonly base: string | null;
+ readonly head: string | null;
+ readonly index: string | null;
+ readonly worktree: string | null;
+ readonly incoming: string | null;
+}
+
+export interface NativeTomlMcpEditor {
+ parseToObject(raw: string): Record<string, unknown>;
+ removeEntry(raw: string, serverName: string): { text: string; existed: boolean };
+ upsertEntry(
+ raw: string,
+ serverName: string,
+ entry: Record<string, unknown>,
+ ): { text: string; existed: boolean };
+}
+
+type McpConfigReconcileDeclineReason =
+ | 'unsupported-target'
+ | 'oversize'
+ | 'unparseable'
+ | 'duplicate-container'
+ | 'no-native-writer'
+ | 'no-entry'
+ | 'foreign-entry'
+ | 'mixed-launcher-family'
+ | 'file-deletion-ambiguity'
+ | 'entry-deletion-ambiguity'
+ | 'index-worktree-divergence'
+ | 'merge-base-unavailable'
+ | 'unowned-shell-conflict';
+
+export type McpConfigReconcilePlan =
+ | {
+ kind: 'resolved';
+ raw: string;
+ winner: McpLauncherDescriptor;
+ winnerEntry: Record<string, unknown>;
+ }
+ | { kind: 'unchanged' }
+ | { kind: 'declined'; reason: McpConfigReconcileDeclineReason };
+
+interface TargetShape {
+ readonly format: 'json' | 'toml';
+ readonly topLevelKey: 'mcpServers' | 'mcp_servers' | 'mcp';
+ readonly managedKeys: readonly string[];
+}
+
+interface ClassifiedRaw {
+ readonly raw: string;
+ readonly shell: string;
+ readonly entry: Record<string, unknown>;
+ readonly descriptor: McpLauncherDescriptor;
+}
+
+type RawClassification =
+ | { kind: 'absent' }
+ | { kind: 'no-entry'; raw: string; shell: string }
+ | ({ kind: 'managed' } & ClassifiedRaw)
+ | { kind: 'declined'; reason: McpConfigReconcileDeclineReason };
+
+const TARGET_SHAPES: Record<TrackedMcpConfigTarget, TargetShape> = {
+ '.mcp.json': { format: 'json', topLevelKey: 'mcpServers', managedKeys: ['command', 'args'] },
+ '.cursor/mcp.json': {
+ format: 'json',
+ topLevelKey: 'mcpServers',
+ managedKeys: ['command', 'args'],
+ },
+ '.codex/config.toml': {
+ format: 'toml',
+ topLevelKey: 'mcp_servers',
+ managedKeys: ['command', 'args'],
+ },
+ 'opencode.json': { format: 'json', topLevelKey: 'mcp', managedKeys: ['type', 'command'] },
+};
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function targetShape(target: string): TargetShape | null {
+ return Object.hasOwn(TARGET_SHAPES, target)
+ ? TARGET_SHAPES[target as TrackedMcpConfigTarget]
+ : null;
+}
+
+function splitBom(raw: string): { bom: string; body: string } {
+ return raw.charCodeAt(0) === 0xfeff
+ ? { bom: '\uFEFF', body: raw.slice(1) }
+ : { bom: '', body: raw };
+}
+
+function formattingOptions(raw: string): {
+ insertSpaces: boolean;
+ tabSize: number;
+ eol: string;
+} {
+ const indent = raw.match(/\n([ \t]+)["}]/)?.[1] ?? ' ';
+ return {
+ insertSpaces: !indent.includes('\t'),
+ tabSize: indent.includes('\t') ? 1 : Math.max(1, indent.length),
+ eol: raw.includes('\r\n') ? '\r\n' : '\n',
+ };
+}
+
+function countRootProperties(root: JsonNode, key: string): number {
+ if (root.type !== 'object') return 0;
+ return (root.children ?? []).filter(
+ (property) => property.type === 'property' && property.children?.[0]?.value === key,
+ ).length;
+}
+
+function normalizeNativeTomlResult(source: string, edited: string): string {
+ const { bom, body } = splitBom(source);
+ const crlf = (body.match(/\r\n/g)?.length ?? 0) > (body.match(/(?<!\r)\n/g)?.length ?? 0);
+ const trailingNewline = body.endsWith('\n');
+ let normalized = edited.replace(/\r\n/g, '\n');
+ normalized = trailingNewline
+ ? `${normalized.replace(/\n+$/, '')}\n`
+ : normalized.replace(/\n+$/, '');
+ if (crlf) normalized = normalized.replace(/\n/g, '\r\n');
+ return `${bom}${normalized}`;
+}
+
+function classifyJson(raw: string, shape: TargetShape): RawClassification {
+ const { bom, body } = splitBom(raw);
+ const errors: ParseError[] = [];
+ const root = parseTree(body, errors, { allowTrailingComma: true, disallowComments: false });
+ if (!root || errors.length > 0 || root.type !== 'object') {
+ return { kind: 'declined', reason: 'unparseable' };
+ }
+ if (countRootProperties(root, shape.topLevelKey) > 1) {
+ return { kind: 'declined', reason: 'duplicate-container' };
+ }
+ const entryPath = [shape.topLevelKey, 'open-knowledge'];
+ const entryNode = findNodeAtLocation(root, entryPath);
+ if (!entryNode) return { kind: 'no-entry', raw, shell: raw };
+ const entry = getNodeValue(entryNode) as unknown;
+ if (!isRecord(entry)) return { kind: 'declined', reason: 'foreign-entry' };
+ const launcher = classifyMcpLauncherEntry(entry);
+ if (launcher.kind === 'declined') return { kind: 'declined', reason: 'foreign-entry' };
+
+ // Mask only the launcher fields OK owns. Unknown fields inside our named
+ // entry (env, timeout, host policy, etc.) remain part of the unowned shell,
+ // just like sibling servers and top-level settings. This makes a change to
+ // one of those fields visible to the three-way safety proof instead of
+ // silently dropping it while selecting a newer launcher.
+ let shellBody = body;
+ const managedNodes = shape.managedKeys
+ .map((key) => ({ key, node: findNodeAtLocation(root, [...entryPath, key]) }))
+ .filter((item): item is { key: string; node: JsonNode } => item.node !== undefined)
+ .sort((left, right) => right.node.offset - left.node.offset);
+ for (const { key, node } of managedNodes) {
+ const sentinel = JSON.stringify(managedFieldSentinel(shape, key));
+ shellBody = `${shellBody.slice(0, node.offset)}${sentinel}${shellBody.slice(node.offset + node.length)}`;
+ }
+ const shell = `${bom}${shellBody}`;
+ return { kind: 'managed', raw, shell, entry, descriptor: launcher.descriptor };
+}
+
+function managedFieldSentinel(shape: TargetShape, key: string): unknown {
+ if (shape.topLevelKey === 'mcp' && key === 'type') return '__ok_managed_type__';
+ if (key === 'command' && shape.topLevelKey === 'mcp') return ['__ok_managed_command__'];
+ if (key === 'command') return '__ok_managed_command__';
+ return ['__ok_managed_args__'];
+}
+
+function classifyToml(
+ raw: string,
+ shape: TargetShape,
+ editor: NativeTomlMcpEditor | undefined,
+): RawClassification {
+ if (!editor) return { kind: 'declined', reason: 'no-native-writer' };
+ const { bom, body } = splitBom(raw);
+ let parsed: Record<string, unknown>;
+ try {
+ parsed = editor.parseToObject(body);
+ } catch {
+ return { kind: 'declined', reason: 'unparseable' };
+ }
+ const container = parsed[shape.topLevelKey];
+ const entry = isRecord(container) ? container['open-knowledge'] : undefined;
+ if (entry === undefined) return { kind: 'no-entry', raw, shell: raw };
+ if (!isRecord(entry)) return { kind: 'declined', reason: 'foreign-entry' };
+ const launcher = classifyMcpLauncherEntry(entry);
+ if (launcher.kind === 'declined') return { kind: 'declined', reason: 'foreign-entry' };
+ let masked: { text: string; existed: boolean };
+ try {
+ masked = editor.upsertEntry(
+ body,
+ 'open-knowledge',
+ Object.fromEntries(shape.managedKeys.map((key) => [key, managedFieldSentinel(shape, key)])),
+ );
+ } catch {
+ return { kind: 'declined', reason: 'unparseable' };
+ }
+ const shell = normalizeNativeTomlResult(raw, masked.text);
+ return { kind: 'managed', raw: `${bom}${body}`, shell, entry, descriptor: launcher.descriptor };
+}
+
+function classifyRaw(
+ raw: string | null,
+ shape: TargetShape,
+ editor: NativeTomlMcpEditor | undefined,
+): RawClassification {
+ if (raw === null) return { kind: 'absent' };
+ if (Buffer.byteLength(raw, 'utf8') > MAX_CONFIG_BYTES) {
+ return { kind: 'declined', reason: 'oversize' };
+ }
+ return shape.format === 'json' ? classifyJson(raw, shape) : classifyToml(raw, shape, editor);
+}
+
+function upsertJsonManagedFields(
+ raw: string,
+ shape: TargetShape,
+ entry: Record<string, unknown>,
+): string {
+ const { bom, body } = splitBom(raw);
+ let edited = body;
+ for (const key of shape.managedKeys) {
+ const currentRoot = parseTree(edited, [], {
+ allowTrailingComma: true,
+ disallowComments: false,
+ });
+ const currentNode = currentRoot
+ ? findNodeAtLocation(currentRoot, [shape.topLevelKey, 'open-knowledge', key])
+ : undefined;
+ if (currentNode && JSON.stringify(getNodeValue(currentNode)) === JSON.stringify(entry[key])) {
+ continue;
+ }
+ edited = applyEdits(
+ edited,
+ modify(edited, [shape.topLevelKey, 'open-knowledge', key], entry[key], {
+ formattingOptions: formattingOptions(body),
+ }),
+ );
+ }
+ return `${bom}${edited}`;
+}
+
+function upsertManagedFields(
+ raw: string,
+ shape: TargetShape,
+ entry: Record<string, unknown>,
+ editor: NativeTomlMcpEditor | undefined,
+): string | null {
+ if (shape.format === 'json') return upsertJsonManagedFields(raw, shape, entry);
+ if (!editor) return null;
+ const { body } = splitBom(raw);
+ const managedEntry = Object.fromEntries(shape.managedKeys.map((key) => [key, entry[key]]));
+ try {
+ return normalizeNativeTomlResult(
+ raw,
+ editor.upsertEntry(body, 'open-knowledge', managedEntry).text,
+ );
+ } catch {
+ return null;
+ }
+}
+
+export function applyManagedMcpEntry(input: {
+ target: string;
+ raw: string;
+ entry: Record<string, unknown>;
+ tomlEditor?: NativeTomlMcpEditor;
+}): string | null {
+ const shape = targetShape(input.target);
+ if (!shape) return null;
+ return upsertManagedFields(input.raw, shape, input.entry, input.tomlEditor);
+}
+
+export function getMcpUnownedShell(input: {
+ target: string;
+ raw: string;
+ tomlEditor?: NativeTomlMcpEditor;
+}): string | null {
+ const shape = targetShape(input.target);
+ if (!shape) return null;
+ const classified = classifyRaw(input.raw, shape, input.tomlEditor);
+ return classified.kind === 'managed' || classified.kind === 'no-entry' ? classified.shell : null;
+}
+
+function chooseShell(
+ base: ClassifiedRaw,
+ worktree: ClassifiedRaw,
+ incoming: ClassifiedRaw,
+): string | null {
+ if (worktree.shell === incoming.shell) return worktree.shell;
+ if (worktree.shell === base.shell) return incoming.shell;
+ if (incoming.shell === base.shell) return worktree.shell;
+ return null;
+}
+
+/**
+ * Produce a mutation-free reconciliation plan for one tracked MCP config.
+ * The caller owns Git/filesystem transactions; this function owns only entry
+ * classification, winner selection, and the proof that unowned bytes combine.
+ */
+export function reconcileTrackedMcpConfig(input: {
+ target: string;
+ layers: RawMcpConfigLayers;
+ runningEntry?: Record<string, unknown>;
+ tomlEditor?: NativeTomlMcpEditor;
+}): McpConfigReconcilePlan {
+ const shape = targetShape(input.target);
+ if (!shape) return { kind: 'declined', reason: 'unsupported-target' };
+
+ const classified = {
+ base: classifyRaw(input.layers.base, shape, input.tomlEditor),
+ head: classifyRaw(input.layers.head, shape, input.tomlEditor),
+ index: classifyRaw(input.layers.index, shape, input.tomlEditor),
+ worktree: classifyRaw(input.layers.worktree, shape, input.tomlEditor),
+ incoming: classifyRaw(input.layers.incoming, shape, input.tomlEditor),
+ };
+ const states = Object.values(classified);
+ const declined = states.find((state) => state.kind === 'declined');
+ if (declined?.kind === 'declined') return declined;
+ if (states.some((state) => state.kind === 'absent')) {
+ return states.every((state) => state.kind === 'absent')
+ ? { kind: 'unchanged' }
+ : { kind: 'declined', reason: 'file-deletion-ambiguity' };
+ }
+ if (states.some((state) => state.kind === 'no-entry')) {
+ return states.every((state) => state.kind === 'no-entry')
+ ? { kind: 'declined', reason: 'no-entry' }
+ : { kind: 'declined', reason: 'entry-deletion-ambiguity' };
+ }
+
+ const managed = classified as Record<keyof RawMcpConfigLayers, ClassifiedRaw>;
+ if (managed.index.shell !== managed.worktree.shell) {
+ return { kind: 'declined', reason: 'index-worktree-divergence' };
+ }
+ const shell = chooseShell(managed.base, managed.worktree, managed.incoming);
+ if (shell === null) return { kind: 'declined', reason: 'unowned-shell-conflict' };
+
+ const candidates = Object.values(managed).map((state) => ({
+ entry: state.entry,
+ descriptor: state.descriptor,
+ }));
+ if (input.runningEntry) {
+ const running = classifyMcpLauncherEntry(input.runningEntry);
+ if (running.kind === 'recognized') {
+ candidates.push({ entry: input.runningEntry, descriptor: running.descriptor });
+ }
+ }
+ const families = new Set(candidates.map((candidate) => candidate.descriptor.family));
+ if (families.size !== 1) return { kind: 'declined', reason: 'mixed-launcher-family' };
+ const winner = candidates.reduce((best, candidate) =>
+ candidate.descriptor.revision > best.descriptor.revision ? candidate : best,
+ );
+
+ const shellSource = [
+ managed.worktree,
+ managed.index,
+ managed.head,
+ managed.incoming,
+ managed.base,
+ ].find((state) => state.shell === shell);
+ if (!shellSource) return { kind: 'declined', reason: 'unowned-shell-conflict' };
+ const raw = upsertManagedFields(shellSource.raw, shape, winner.entry, input.tomlEditor);
+ if (raw === null) {
+ return {
+ kind: 'declined',
+ reason: input.tomlEditor ? 'unparseable' : 'no-native-writer',
+ };
+ }
+ return {
+ kind: 'resolved',
+ raw,
+ winner: winner.descriptor,
+ winnerEntry: winner.entry,
+ };
+}
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index de5c969da..66b11408d 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -190,6 +190,7 @@ import {
} from './managed-artifact-persistence.ts';
import { startManagedArtifactWatcher } from './managed-artifact-watcher.ts';
import { recoverPendingManagedRename } from './managed-rename-journal.ts';
+import type { NativeTomlMcpEditor } from './mcp-config-reconciler.ts';
import { mdManager, schema } from './md-manager.ts';
import {
incrementBatch,
@@ -292,6 +293,8 @@ export interface ServerOptions {
minEvictableIdleMs?: number;
};
gitEnabled?: boolean;
+ /** Injected native TOML capability for entry-preserving sync reconciliation. */
+ mcpTomlEditor?: NativeTomlMcpEditor;
commitDebounceMs?: number;
wipRef?: string;
/**
@@ -5402,6 +5405,7 @@ export function createServer(options: ServerOptions): ServerInstance {
contentDir,
contentFilter,
contentRoot,
+ mcpTomlEditor: options.mcpTomlEditor,
mode: bootAutoSyncMode.mode,
pullIntervalSeconds: options.pullIntervalSeconds,
pushIntervalSeconds: options.pushIntervalSeconds,
diff --git a/packages/server/src/sync-engine.test.ts b/packages/server/src/sync-engine.test.ts
index bca6ddba1..dcb7029c4 100644
--- a/packages/server/src/sync-engine.test.ts
+++ b/packages/server/src/sync-engine.test.ts
@@ -771,6 +771,287 @@ describe('SyncEngine ConflictStore admission (content-only)', () => {
});
});
+describe('SyncEngine tracked MCP overlap preparation', () => {
+ test('matching newer local and incoming launchers do not pause full sync', async () => {
+ const bareDir = join(tmpDir, 'mcp-overlap.git');
+ const sisterDir = join(tmpDir, 'mcp-overlap-sister');
+ mkdirSync(bareDir, { recursive: true });
+ mkdirSync(sisterDir, { recursive: true });
+ const bare = simpleGit(bareDir);
+ await bare.init(true);
+ await bare.raw('symbolic-ref', 'HEAD', 'refs/heads/main');
+
+ const v1 = JSON.stringify({
+ mcpServers: {
+ other: { command: 'keep-me' },
+ 'open-knowledge': { command: '/bin/sh', args: ['-l', '-c', '# ok-mcp-v1\nexit 127'] },
+ },
+ });
+ const v2 = v1.replace('# ok-mcp-v1', '# ok-mcp-v2');
+ const sister = simpleGit(sisterDir);
+ await sister.init(['--initial-branch=main']);
+ await sister.raw('config', 'user.name', 'Sister');
+ await sister.raw('config', 'user.email', '[email protected]');
+ writeFileSync(join(sisterDir, '.mcp.json'), `${v1}\n`, 'utf-8');
+ await sister.add('.mcp.json');
+ await sister.commit('base');
+ await sister.addRemote('origin', bareDir);
+ await sister.push('origin', 'main');
+
+ rmSync(projectDir, { recursive: true, force: true });
+ await simpleGit(tmpDir).clone(bareDir, projectDir);
+ mkdirSync(okDir, { recursive: true });
+
+ writeFileSync(join(sisterDir, '.mcp.json'), `${v2}\n`, 'utf-8');
+ await sister.add('.mcp.json');
+ await sister.commit('incoming v2');
+ await sister.push('origin', 'main');
+
+ // This is the reported conflict shape: startup repair generated the same
+ // v2 bytes locally before Git fetched the teammate's v2 commit.
+ writeFileSync(join(projectDir, '.mcp.json'), `${v2}\n`, 'utf-8');
+
+ const engine = new SyncEngine({
+ projectDir,
+ contentDir: projectDir,
+ contentFilter: {
+ ...stubContentFilter,
+ isExcluded: (path: string) => path === '.mcp.json',
+ },
+ syncEnabled: true,
+ });
+ try {
+ await engine.start();
+ const outcome = await engine.pullOnce();
+ expect(outcome).toBe('succeeded');
+ expect(engine.getStatus().pausedReason).toBeUndefined();
+ expect(readFileSync(join(projectDir, '.mcp.json'), 'utf-8')).toBe(`${v2}\n`);
+ expect((await simpleGit(projectDir).status()).isClean()).toBe(true);
+ } finally {
+ await engine.destroy();
+ }
+ });
+
+ test('full sync keeps a locally newer launcher without stash conflicts', async () => {
+ const bareDir = join(tmpDir, 'mcp-newer-overlap.git');
+ const sisterDir = join(tmpDir, 'mcp-newer-overlap-sister');
+ mkdirSync(bareDir, { recursive: true });
+ mkdirSync(sisterDir, { recursive: true });
+ const bare = simpleGit(bareDir);
+ await bare.init(true);
+ await bare.raw('symbolic-ref', 'HEAD', 'refs/heads/main');
+
+ const config = (marker: string, theme: string) =>
+ `${JSON.stringify({
+ theme,
+ mcpServers: {
+ other: { command: 'keep-me' },
+ 'open-knowledge': {
+ command: '/bin/sh',
+ args: ['-l', '-c', `${marker}\nexit 127`],
+ },
+ },
+ })}\n`;
+ const sister = simpleGit(sisterDir);
+ await sister.init(['--initial-branch=main']);
+ await sister.raw('config', 'user.name', 'Sister');
+ await sister.raw('config', 'user.email', '[email protected]');
+ writeFileSync(join(sisterDir, '.mcp.json'), config('# ok-mcp-v1', 'base'), 'utf8');
+ await sister.add('.mcp.json');
+ await sister.commit('base');
+ await sister.addRemote('origin', bareDir);
+ await sister.push('origin', 'main');
+
+ rmSync(projectDir, { recursive: true, force: true });
+ await simpleGit(tmpDir).clone(bareDir, projectDir);
+ mkdirSync(okDir, { recursive: true });
+
+ writeFileSync(join(sisterDir, '.mcp.json'), config('# ok-mcp-v2', 'incoming'), 'utf8');
+ await sister.add('.mcp.json');
+ await sister.commit('incoming launcher');
+ await sister.push('origin', 'main');
+ writeFileSync(join(projectDir, '.mcp.json'), config('# ok-mcp-v99', 'base'), 'utf8');
+
+ const engine = new SyncEngine({
+ projectDir,
+ contentDir: projectDir,
+ contentFilter: {
+ ...stubContentFilter,
+ isExcluded: (path: string) => path === '.mcp.json',
+ },
+ syncEnabled: true,
+ });
+ try {
+ await engine.start();
+ expect(await engine.pullOnce()).toBe('succeeded');
+
+ const project = simpleGit(projectDir);
+ const raw = readFileSync(join(projectDir, '.mcp.json'), 'utf8');
+ expect(raw).not.toContain('<<<<<<<');
+ expect(JSON.parse(raw)).toEqual(JSON.parse(config('# ok-mcp-v99', 'incoming')));
+ expect((await project.raw(['diff', '--name-only', '--diff-filter=U'])).trim()).toBe('');
+ expect((await project.status()).isClean()).toBe(true);
+ expect((await project.log({ maxCount: 1 })).latest?.message).toBe(
+ 'Update OpenKnowledge MCP launcher',
+ );
+ expect((await project.raw(['stash', 'list'])).trim()).toBe('');
+ } finally {
+ await engine.destroy();
+ }
+ });
+
+ test('full sync persists a newer winner in an entry-only generated commit', async () => {
+ const project = simpleGit(projectDir);
+ await project.init(['--initial-branch=main']);
+ await project.raw('config', 'user.name', 'Project');
+ await project.raw('config', 'user.email', '[email protected]');
+ const entry = (marker: string) => ({
+ command: '/bin/sh',
+ args: ['-l', '-c', `${marker}\nexit 127`],
+ });
+ const config = (marker: string) =>
+ `${JSON.stringify({
+ theme: 'keep',
+ mcpServers: {
+ other: { command: 'keep-me' },
+ 'open-knowledge': entry(marker),
+ },
+ })}\n`;
+ writeFileSync(join(projectDir, '.mcp.json'), config('# ok-mcp-v2'), 'utf8');
+ await project.add('.mcp.json');
+ await project.commit('base');
+ writeFileSync(join(projectDir, '.mcp.json'), config('# ok-mcp-v99'), 'utf8');
+
+ const engine = new SyncEngine({
+ projectDir,
+ contentDir: projectDir,
+ contentFilter: stubContentFilter,
+ syncEnabled: true,
+ });
+ await (
+ engine as unknown as {
+ persistReconciledMcpEntries: (
+ entries: Array<{ path: string; raw: string; winnerEntry: Record<string, unknown> }>,
+ ) => Promise<void>;
+ }
+ ).persistReconciledMcpEntries([
+ {
+ path: '.mcp.json',
+ raw: config('# ok-mcp-v99'),
+ winnerEntry: entry('# ok-mcp-v99'),
+ },
+ ]);
+
+ expect((await project.log({ maxCount: 1 })).latest?.message).toBe(
+ 'Update OpenKnowledge MCP launcher',
+ );
+ expect(await project.show(['--format=', '--name-only', 'HEAD'])).toBe('.mcp.json\n');
+ expect(JSON.parse(readFileSync(join(projectDir, '.mcp.json'), 'utf8'))).toEqual(
+ JSON.parse(config('# ok-mcp-v99')),
+ );
+ expect((await project.status()).files).toEqual([]);
+ const committed = JSON.parse(await project.show(['HEAD:.mcp.json'])) as {
+ theme: string;
+ mcpServers: Record<string, unknown>;
+ };
+ expect(committed.theme).toBe('keep');
+ expect(committed.mcpServers.other).toEqual({ command: 'keep-me' });
+ });
+
+ test('push retry persists a locally newer launcher after a non-fast-forward rejection', async () => {
+ const bareDir = join(tmpDir, 'mcp-push-retry.git');
+ const sisterDir = join(tmpDir, 'mcp-push-retry-sister');
+ mkdirSync(bareDir, { recursive: true });
+ mkdirSync(sisterDir, { recursive: true });
+ const bare = simpleGit(bareDir);
+ await bare.init(true);
+ await bare.raw('symbolic-ref', 'HEAD', 'refs/heads/main');
+
+ const config = (marker: string) =>
+ `${JSON.stringify({
+ mcpServers: {
+ other: { command: 'keep-me' },
+ 'open-knowledge': {
+ command: '/bin/sh',
+ args: ['-l', '-c', `${marker}\nexit 127`],
+ },
+ },
+ })}\n`;
+ const sister = simpleGit(sisterDir);
+ await sister.init(['--initial-branch=main']);
+ await sister.raw('config', 'user.name', 'Sister');
+ await sister.raw('config', 'user.email', '[email protected]');
+ // Real OK projects ignore per-machine runtime state. Keep the synthetic
+ // repo faithful so SyncEngine state files cannot make the clean-tree
+ // assertion timing-dependent under a loaded CI runner.
+ writeFileSync(join(sisterDir, '.gitignore'), '/.ok/*\n', 'utf8');
+ writeFileSync(join(sisterDir, '.mcp.json'), config('# ok-mcp-v1'), 'utf8');
+ writeFileSync(join(sisterDir, 'shared.md'), 'base\n', 'utf8');
+ await sister.add(['.gitignore', '.mcp.json', 'shared.md']);
+ await sister.commit('base');
+ await sister.addRemote('origin', bareDir);
+ await sister.push('origin', 'main');
+
+ rmSync(projectDir, { recursive: true, force: true });
+ await simpleGit(tmpDir).clone(bareDir, projectDir);
+ mkdirSync(okDir, { recursive: true });
+ // A fresh OK user may not have configured Git identity yet. Blank local
+ // values override any identity inherited from the developer/CI host and
+ // force the engine's non-interactive fallback path deterministically.
+ await simpleGit(projectDir).raw(['config', 'user.name', '']);
+ await simpleGit(projectDir).raw(['config', 'user.email', '']);
+
+ writeFileSync(join(sisterDir, '.mcp.json'), config('# ok-mcp-v2'), 'utf8');
+ await sister.add('.mcp.json');
+ await sister.commit('incoming launcher');
+ await sister.push('origin', 'main');
+
+ writeFileSync(join(projectDir, '.mcp.json'), config('# ok-mcp-v99'), 'utf8');
+ writeFileSync(join(projectDir, 'local.md'), 'local content\n', 'utf8');
+ const engine = new SyncEngine({
+ projectDir,
+ contentDir: projectDir,
+ contentFilter: {
+ ...stubContentFilter,
+ isExcluded: (path: string) => path === '.mcp.json',
+ },
+ syncEnabled: true,
+ pullIntervalSeconds: 99999,
+ pushIntervalSeconds: 99999,
+ });
+ try {
+ await engine.start();
+ await engine.trigger('push');
+
+ const project = simpleGit(projectDir);
+ const raw = readFileSync(join(projectDir, '.mcp.json'), 'utf8');
+ expect(raw).not.toContain('<<<<<<<');
+ expect(JSON.parse(raw)).toEqual(JSON.parse(config('# ok-mcp-v99')));
+ expect((await project.raw(['diff', '--name-only', '--diff-filter=U'])).trim()).toBe('');
+ const status = await project.status();
+ // The generated commit is entry-only. Git may retain a byte-distinct,
+ // semantically equivalent worktree overlay (for example, formatting or
+ // line-ending bytes) rather than rewriting the rest of the guest-owned
+ // config. That overlay is safe; collateral dirt is not.
+ expect(status.files.filter((file) => file.path !== '.mcp.json')).toEqual([]);
+ expect(status.files.find((file) => file.path === '.mcp.json')?.index ?? ' ').toBe(' ');
+ expect((await project.raw(['stash', 'list'])).trim()).toBe('');
+ // Inspect the remote itself. A push to a local-path remote does not
+ // consistently refresh the clone's origin/main tracking ref across Git
+ // versions, even when the remote branch advanced successfully.
+ expect(JSON.parse(await bare.show(['main:.mcp.json']))).toEqual(
+ JSON.parse(config('# ok-mcp-v99')),
+ );
+ expect(await bare.show(['main:local.md'])).toBe('local content\n');
+ expect((await project.log({ maxCount: 1 })).latest?.message).toBe(
+ 'Update OpenKnowledge MCP launcher',
+ );
+ } finally {
+ await engine.destroy();
+ }
+ });
+});
+
// ─── Delete-vs-modify conflict from dirty working tree ───────────────────────
describe('SyncEngine delete/modify dirty content conflicts', () => {
@@ -3579,6 +3860,65 @@ describe('SyncEngine pull-only B1 fast-forward cycle', () => {
}
});
+ test('tracked MCP overlay upgrades to the incoming newer launcher without a commit', async () => {
+ const mcp = (marker: string) =>
+ `${JSON.stringify({
+ mcpServers: {
+ other: { command: 'keep-me' },
+ 'open-knowledge': { command: '/bin/sh', args: ['-l', '-c', `${marker}\nexit 127`] },
+ },
+ })}\n`;
+ const { originTip } = await cloneBehindOrigin({
+ seed: { '.mcp.json': mcp('# ok-mcp-v1') },
+ advance: { '.mcp.json': mcp('# ok-mcp-v2') },
+ });
+ writeFileSync(join(projectDir, '.mcp.json'), mcp('# ok-mcp-v1'), 'utf8');
+
+ const engine = makePullEngine();
+ try {
+ await engine.start();
+ await engine.trigger('pull');
+ const project = simpleGit(projectDir);
+ expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
+ expect(readFileSync(join(projectDir, '.mcp.json'), 'utf8')).toBe(mcp('# ok-mcp-v2'));
+ expect(await listNames(project, ['diff-index', '--name-only', 'HEAD'])).toEqual([]);
+ expect(
+ (await project.log()).all.filter((commit) => commit.message.includes('MCP launcher')),
+ ).toEqual([]);
+ } finally {
+ await engine.destroy();
+ }
+ });
+
+ test('tracked MCP overlay preserves a recognized future launcher over incoming v2', async () => {
+ const mcp = (marker: string) =>
+ `${JSON.stringify({
+ mcpServers: {
+ other: { command: 'keep-me' },
+ 'open-knowledge': { command: '/bin/sh', args: ['-l', '-c', `${marker}\nexit 127`] },
+ },
+ })}\n`;
+ const { originTip } = await cloneBehindOrigin({
+ seed: { '.mcp.json': mcp('# ok-mcp-v1') },
+ advance: { '.mcp.json': mcp('# ok-mcp-v2') },
+ });
+ writeFileSync(join(projectDir, '.mcp.json'), mcp('# ok-mcp-v99'), 'utf8');
+
+ const engine = makePullEngine();
+ try {
+ await engine.start();
+ await engine.trigger('pull');
+ const project = simpleGit(projectDir);
+ expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
+ expect(readFileSync(join(projectDir, '.mcp.json'), 'utf8')).toBe(mcp('# ok-mcp-v99'));
+ expect(await listNames(project, ['diff-index', '--name-only', 'HEAD'])).toEqual([
+ '.mcp.json',
+ ]);
+ } finally {
+ await engine.destroy();
+ }
+ });
+
test('a locally-deleted content file the tip modifies is restored from origin', async () => {
// Pull-only follows upstream: a locally-deleted content doc the tip modified
// yields to the remote's change and is restored at origin's version (nothing
diff --git a/packages/server/src/sync-engine.ts b/packages/server/src/sync-engine.ts
index 76ae9d576..669146753 100644
--- a/packages/server/src/sync-engine.ts
+++ b/packages/server/src/sync-engine.ts
@@ -53,6 +53,13 @@ import {
type PushPermission,
} from './github-permissions.ts';
import { getLogger } from './logger.ts';
+import {
+ applyManagedMcpEntry,
+ getMcpUnownedShell,
+ type NativeTomlMcpEditor,
+ reconcileTrackedMcpConfig,
+ TRACKED_MCP_CONFIG_TARGETS,
+} from './mcp-config-reconciler.ts';
import { toPosix } from './path-utils.ts';
import {
originGitHubHost,
@@ -68,6 +75,7 @@ import {
} from './sync-timing.ts';
const log = getLogger('sync-engine');
+const TRACKED_MCP_CONFIG_TARGET_SET: ReadonlySet<string> = new Set(TRACKED_MCP_CONFIG_TARGETS);
/**
* Git SHA-1 object IDs are 40 lowercase hex chars. `commit-tree` and similar
@@ -259,6 +267,18 @@ interface ContentFileEntry {
projectRelPath: string;
}
+interface PreparedMcpReconciliation {
+ path: string;
+ raw: string;
+ winnerEntry: Record<string, unknown>;
+}
+
+interface MergePreparation {
+ proceed: boolean;
+ needsStashPop: boolean;
+ reconciled: PreparedMcpReconciliation[];
+}
+
/**
* ContentFilter read-opts for the two staging-path consultations
* (`gatherContentFilesSync`, `listHeadContentPaths`): admits the shareable
@@ -364,6 +384,8 @@ interface SyncEngineOptions {
branch: string;
paths: number;
}) => void | Promise<void>;
+ /** Native, token-preserving TOML capability supplied by a composition root. */
+ mcpTomlEditor?: NativeTomlMcpEditor;
/**
* Tier A token detector. Honors the existing three-tier model (see
* `packages/cli/src/auth/resolve-auth.ts`) without `packages/server`
@@ -481,6 +503,7 @@ export class SyncEngine {
private checkpointBeforeOverlayRestore:
| ((context: { branch: string; paths: number }) => void | Promise<void>)
| undefined;
+ private mcpTomlEditor: NativeTomlMcpEditor | undefined;
private detectGh: DetectGhFn | undefined;
/**
* Resolves + caches the gh token relayed to the credential helper so sync
@@ -566,6 +589,7 @@ export class SyncEngine {
this.onAutoDisable = options.onAutoDisable;
this.checkpointBeforeStrandedConversion = options.checkpointBeforeStrandedConversion;
this.checkpointBeforeOverlayRestore = options.checkpointBeforeOverlayRestore;
+ this.mcpTomlEditor = options.mcpTomlEditor;
this.detectGh = options.detectGh;
this.ghTokenSource = createGhTokenSource(options.detectGh);
this.tokenStore = options.tokenStore;
@@ -1260,6 +1284,30 @@ export class SyncEngine {
}
}
+ /**
+ * Apply the resolved Git identity, or OpenKnowledge's non-interactive
+ * fallback, to every engine-authored commit path. `git merge` creates its
+ * own commit and therefore needs the same environment as `commit-tree`;
+ * otherwise a machine without user.name/user.email aborts after a
+ * non-fast-forward push and never reaches MCP reconciliation.
+ */
+ private async applyCommitIdentity(handle: GitHandle): Promise<void> {
+ const identity = await resolveGitIdentity(this.projectDir);
+ const nextUnresolved = identity === null;
+ if (this.identityUnresolved !== nextUnresolved) {
+ this.identityUnresolved = nextUnresolved;
+ this.cc1Broadcaster?.signal('sync-status');
+ }
+ const name = identity?.name ?? 'OpenKnowledge';
+ const email = identity?.email ?? '[email protected]';
+ applyGitEnv(handle, {
+ GIT_AUTHOR_NAME: name,
+ GIT_AUTHOR_EMAIL: email,
+ GIT_COMMITTER_NAME: name,
+ GIT_COMMITTER_EMAIL: email,
+ });
+ }
+
/**
* Drive the push-permission probe and apply its consequences:
* - record the result in `this.pushPermission`
@@ -1797,14 +1845,23 @@ export class SyncEngine {
await this.commitDirtyContentFilesToHead(handle);
const mergePrep = await this.prepareForMerge(handle, branch);
if (!mergePrep.proceed) return 'refused';
+ let stashRestored = true;
+ let overlaysRestored = true;
try {
+ await this.applyCommitIdentity(handle);
await handle.git.merge([`origin/${branch}`]);
this.lastSyncUtc = new Date().toISOString();
this.behind = 0;
this.transitionTo('idle');
} finally {
- if (mergePrep.needsStashPop) await this.popPreMergeStash(handle);
+ if (mergePrep.needsStashPop) {
+ stashRestored = await this.popPreMergeStash(handle);
+ }
+ overlaysRestored = this.restoreReconciledMcpOverlays(mergePrep.reconciled);
}
+ if (!stashRestored) throw new Error('failed to replay pre-merge working-tree state');
+ if (!overlaysRestored) throw new Error('failed to restore reconciled MCP overlays');
+ await this.persistReconciledMcpEntries(mergePrep.reconciled);
this.scheduleSaveState();
return 'succeeded';
} catch (e) {
@@ -2238,6 +2295,43 @@ export class SyncEngine {
continue;
}
+ if (theirsStr !== null && TRACKED_MCP_CONFIG_TARGET_SET.has(p)) {
+ const head = await this.readMcpGitBlob(handle, oldHead, p);
+ const index = await this.readMcpGitBlob(handle, '', p);
+ const mcpPlan = reconcileTrackedMcpConfig({
+ target: p,
+ layers: {
+ base: head,
+ head,
+ index,
+ worktree: mineStr,
+ incoming: theirsStr,
+ },
+ tomlEditor: this.mcpTomlEditor,
+ });
+ if (mcpPlan.kind === 'resolved') {
+ if (mcpPlan.raw !== theirsStr) {
+ writes.push({ path: p, bytes: Buffer.from(mcpPlan.raw, 'utf8') });
+ }
+ log.info(
+ { event: 'mcp-config-reconcile', target: p, outcome: 'auto-resolved' },
+ '[sync] pull-only: auto-resolved OpenKnowledge MCP entry overlap',
+ );
+ continue;
+ }
+ if (mcpPlan.kind === 'declined') {
+ log.warn(
+ {
+ event: 'mcp-config-reconcile',
+ target: p,
+ outcome: 'declined',
+ reason: mcpPlan.reason,
+ },
+ '[sync] pull-only: declined OpenKnowledge MCP entry reconciliation',
+ );
+ }
+ }
+
if (theirsStr === null || !this.isContentConflictPath(p)) {
// Non-content or unreadable tip blob: keep the overlay verbatim, never
// line-merge or escalate (matches adjacent-config behavior).
@@ -2576,22 +2670,8 @@ export class SyncEngine {
// hard-coded "OpenKnowledge" default. We never error on unresolved
// identity — attribution silently degrades to the default and the UI
// surfaces a non-blocking nudge via `status.identityUnresolved`.
- const identity = await resolveGitIdentity(this.projectDir);
- const nextUnresolved = identity === null;
- if (this.identityUnresolved !== nextUnresolved) {
- this.identityUnresolved = nextUnresolved;
- this.cc1Broadcaster?.signal('sync-status');
- }
- const authorName = identity?.name ?? 'OpenKnowledge';
- const authorEmail = identity?.email ?? '[email protected]';
-
- // Set author/committer env vars on the handle for commit-tree
- applyGitEnv(handle, {
- GIT_AUTHOR_NAME: authorName,
- GIT_AUTHOR_EMAIL: authorEmail,
- GIT_COMMITTER_NAME: authorName,
- GIT_COMMITTER_EMAIL: authorEmail,
- });
+ // Set author/committer env vars on the handle for commit-tree.
+ await this.applyCommitIdentity(handle);
// ── 10. Create squash commit (one parent per push cycle) ───────────────
const newCommitSha = (
@@ -2686,11 +2766,20 @@ export class SyncEngine {
this.setBatchInProgress?.(false);
return;
}
+ let stashRestored = true;
+ let overlaysRestored = true;
try {
+ await this.applyCommitIdentity(retryHandle);
await retryHandle.git.merge([`origin/${this.currentBranch}`]);
} finally {
- if (mergePrep.needsStashPop) await this.popPreMergeStash(retryHandle);
+ if (mergePrep.needsStashPop) {
+ stashRestored = await this.popPreMergeStash(retryHandle);
+ }
+ overlaysRestored = this.restoreReconciledMcpOverlays(mergePrep.reconciled);
}
+ if (!stashRestored) throw new Error('failed to replay pre-merge working-tree state');
+ if (!overlaysRestored) throw new Error('failed to restore reconciled MCP overlays');
+ await this.persistReconciledMcpEntries(mergePrep.reconciled);
} catch (mergeErr) {
const mc = classifyGitError(
mergeErr instanceof Error ? mergeErr : new Error(String(mergeErr)),
@@ -2778,15 +2867,7 @@ export class SyncEngine {
changedProjectRelPaths = contentFiles.map((f) => f.projectRelPath).concat(deleted);
}
- const identity = await resolveGitIdentity(this.projectDir);
- const authorName = identity?.name ?? 'OpenKnowledge';
- const authorEmail = identity?.email ?? '[email protected]';
- applyGitEnv(isoHandle, {
- GIT_AUTHOR_NAME: authorName,
- GIT_AUTHOR_EMAIL: authorEmail,
- GIT_COMMITTER_NAME: authorName,
- GIT_COMMITTER_EMAIL: authorEmail,
- });
+ await this.applyCommitIdentity(isoHandle);
const message = 'Auto-save: interim before merge';
const newCommitSha = (
@@ -2845,10 +2926,55 @@ export class SyncEngine {
* If either git diff call fails, fall back to "proceed without stash" —
* the merge will surface any real failure via its own error class.
*/
- private async prepareForMerge(
+ private async readMcpGitBlob(
+ handle: GitHandle,
+ revision: string,
+ path: string,
+ ): Promise<string | null> {
+ try {
+ await handle.git.raw(['cat-file', '-e', `${revision}:${path}`]);
+ return await handle.git.raw(['show', `${revision}:${path}`]);
+ } catch {
+ return null;
+ }
+ }
+
+ private async planTrackedMcpOverlap(
handle: GitHandle,
branch: string,
- ): Promise<{ proceed: boolean; needsStashPop: boolean }> {
+ path: string,
+ ): Promise<ReturnType<typeof reconcileTrackedMcpConfig>> {
+ let baseRevision: string;
+ try {
+ baseRevision = (await handle.git.raw(['merge-base', 'HEAD', `origin/${branch}`])).trim();
+ } catch (err) {
+ log.warn(
+ { err, branch, path },
+ '[sync] MCP reconciliation merge-base unavailable — declining',
+ );
+ return { kind: 'declined', reason: 'merge-base-unavailable' };
+ }
+ const [base, head, index, incoming] = await Promise.all([
+ this.readMcpGitBlob(handle, baseRevision, path),
+ this.readMcpGitBlob(handle, 'HEAD', path),
+ this.readMcpGitBlob(handle, '', path),
+ this.readMcpGitBlob(handle, `origin/${branch}`, path),
+ ]);
+ let worktree: string | null = null;
+ try {
+ worktree = readFileSync(join(this.projectDir, path), 'utf8');
+ } catch {
+ // A missing worktree path is a deletion layer, not an empty file.
+ }
+ return reconcileTrackedMcpConfig({
+ target: path,
+ layers: { base, head, index, worktree, incoming },
+ tomlEditor: this.mcpTomlEditor,
+ });
+ }
+
+ private async prepareForMerge(handle: GitHandle, branch: string): Promise<MergePreparation> {
+ const reconciled: PreparedMcpReconciliation[] = [];
// `diff-index --name-only HEAD` lists only TRACKED files whose working-
// tree OR index content differs from HEAD's. Untracked files are
// intentionally excluded: `git merge` only refuses on untracked when
@@ -2863,9 +2989,9 @@ export class SyncEngine {
// log so triage can spot a degraded pre-check (stale remote ref,
// index corruption, etc.) rather than seeing the gate vanish silently.
log.warn({ err, branch }, '[sync] diff-index failed — allowing merge attempt');
- return { proceed: true, needsStashPop: false };
+ return { proceed: true, needsStashPop: false, reconciled };
}
- if (dirtyPaths.length === 0) return { proceed: true, needsStashPop: false };
+ if (dirtyPaths.length === 0) return { proceed: true, needsStashPop: false, reconciled };
// Intersect with the set of paths the incoming merge actually touches.
// `diff --name-only HEAD..origin/<branch>` reports every path differing
@@ -2881,9 +3007,57 @@ export class SyncEngine {
);
} catch (err) {
log.warn({ err, branch }, '[sync] merge-path diff failed — allowing merge attempt');
- return { proceed: true, needsStashPop: false };
+ return { proceed: true, needsStashPop: false, reconciled };
+ }
+ let blocking = dirtyPaths.filter((p) => mergePaths.has(p));
+
+ // Tracked MCP configs are guest-owned at entry granularity. Before the
+ // generic path-name gate pauses, prove that every overlapping config can
+ // preserve its unowned shell and select a non-downgrading launcher. Plan
+ // the whole batch first: one decline means zero reconciliation writes.
+ const trackedTargets = TRACKED_MCP_CONFIG_TARGET_SET;
+ const mcpOverlaps = blocking.filter((path) => trackedTargets.has(path));
+ if (mcpOverlaps.length > 0) {
+ const plans = await Promise.all(
+ mcpOverlaps.map(async (path) => ({
+ path,
+ plan: await this.planTrackedMcpOverlap(handle, branch, path),
+ })),
+ );
+ const declined = plans.find(({ plan }) => plan.kind === 'declined');
+ const hasOtherBlockingPath = blocking.some((path) => !trackedTargets.has(path));
+ if (!declined && !hasOtherBlockingPath) {
+ for (const { path, plan } of plans) {
+ if (plan.kind !== 'resolved') continue;
+ reconciled.push({ path, raw: plan.raw, winnerEntry: plan.winnerEntry });
+ log.info(
+ { event: 'mcp-config-reconcile', target: path, outcome: 'auto-resolved' },
+ '[sync] auto-resolved OpenKnowledge MCP entry overlap',
+ );
+ }
+ blocking = blocking.filter((path) => !trackedTargets.has(path));
+ } else if (declined) {
+ log.warn(
+ {
+ event: 'mcp-config-reconcile',
+ target: declined.path,
+ outcome: 'declined',
+ reason: declined.plan.kind === 'declined' ? declined.plan.reason : undefined,
+ },
+ '[sync] declined OpenKnowledge MCP entry reconciliation',
+ );
+ } else if (hasOtherBlockingPath) {
+ log.info(
+ {
+ event: 'mcp-config-reconcile',
+ targets: mcpOverlaps,
+ outcome: 'suppressed',
+ reason: 'other-blocking-path',
+ },
+ '[sync] suppressed MCP entry reconciliation because another path blocks the merge',
+ );
+ }
}
- const blocking = dirtyPaths.filter((p) => mergePaths.has(p));
if (blocking.length > 0) {
const display = blocking.slice(0, 3).join(', ');
@@ -2895,7 +3069,38 @@ export class SyncEngine {
this.transitionTo('idle');
this.scheduleSaveState();
log.warn({ files: blocking }, '[sync] paused — dirty paths overlap incoming merge');
- return { proceed: false, needsStashPop: false };
+ return { proceed: false, needsStashPop: false, reconciled: [] };
+ }
+
+ // The reconciler has captured the exact post-merge overlay for these
+ // paths. Restore them to HEAD before stashing so Git never tries to replay
+ // an MCP launcher change across the incoming commit. The caller reapplies
+ // the captured bytes after the merge (including failure paths) and then
+ // persists the managed entry on a successful merge.
+ if (reconciled.length > 0) {
+ try {
+ await handle.git.raw([
+ 'restore',
+ '--source=HEAD',
+ '--staged',
+ '--worktree',
+ '--',
+ ...reconciled.map((item) => item.path),
+ ]);
+ } catch (err) {
+ log.warn({ err }, '[sync] could not isolate reconciled MCP paths from pre-merge stash');
+ this.pullError =
+ 'Sync paused — OpenKnowledge could not safely isolate local MCP launcher changes before merging.';
+ this.pausedReason = 'external-changes-pending';
+ this.transitionTo('idle');
+ this.scheduleSaveState();
+ return { proceed: false, needsStashPop: false, reconciled: [] };
+ }
+ }
+
+ const reconciledPaths = new Set(reconciled.map((item) => item.path));
+ if (dirtyPaths.every((path) => reconciledPaths.has(path))) {
+ return { proceed: true, needsStashPop: false, reconciled };
}
// No overlap with the incoming merge, but tracked dirt remains. Stash
@@ -2907,9 +3112,33 @@ export class SyncEngine {
await handle.git.raw(['stash', 'push', '-m', stashMessage]);
} catch (err) {
log.warn({ err }, '[sync] stash push failed — proceeding without stash');
- return { proceed: true, needsStashPop: false };
+ return { proceed: true, needsStashPop: false, reconciled };
}
- return { proceed: true, needsStashPop: true };
+ return { proceed: true, needsStashPop: true, reconciled };
+ }
+
+ private restoreReconciledMcpOverlays(reconciled: PreparedMcpReconciliation[]): boolean {
+ let restored = true;
+ for (const item of reconciled) {
+ try {
+ const absolutePath = join(this.projectDir, item.path);
+ assertRealpathWithinDir(absolutePath, this.projectDir);
+ let existing: string | null = null;
+ try {
+ existing = readFileSync(absolutePath, 'utf8');
+ } catch (err) {
+ log.warn(
+ { err, path: item.path },
+ '[sync] could not read MCP config before restoring reconciled overlay',
+ );
+ }
+ if (existing !== item.raw) tracedWriteFileSync(absolutePath, item.raw, 'utf8');
+ } catch (err) {
+ restored = false;
+ log.warn({ err, path: item.path }, '[sync] could not restore reconciled MCP overlay');
+ }
+ }
+ return restored;
}
/**
@@ -2919,12 +3148,165 @@ export class SyncEngine {
* the stash stays on the stack — we log so the user can recover via
* `git stash list` / `git stash pop` manually.
*/
- private async popPreMergeStash(handle: GitHandle): Promise<void> {
+ private async popPreMergeStash(handle: GitHandle): Promise<boolean> {
try {
await handle.git.raw(['stash', 'pop']);
+ return true;
} catch (err) {
log.warn({ err }, '[sync] stash pop failed — stash remains on stack');
+ return false;
+ }
+ }
+
+ private hasGitOperationInProgress(): boolean {
+ const gitDir = resolveGitDir(this.projectDir);
+ if (!gitDir) return true;
+ return ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'rebase-merge', 'rebase-apply'].some(
+ (marker) => existsSync(join(gitDir, marker)),
+ );
+ }
+
+ private async persistReconciledMcpEntries(
+ reconciled: PreparedMcpReconciliation[],
+ ): Promise<void> {
+ if (reconciled.length === 0) return;
+ if (this.hasGitOperationInProgress()) {
+ throw new Error('refusing MCP entry commit while a Git operation is in progress');
}
+
+ await withParentLock(async () => {
+ const tmpIndex = join(tmpdir(), `ok-mcp-sync-idx-${process.pid}-${Date.now()}.idx`);
+ const tempBlobs: string[] = [];
+ try {
+ const realHandle = this.gitHandle();
+ const isolated = this.gitHandle(tmpIndex);
+ const headSha = (await isolated.git.revparse('HEAD')).trim();
+ const branch = (await isolated.git.revparse(['--abbrev-ref', 'HEAD'])).trim();
+ if (branch === 'HEAD') throw new Error('refusing MCP entry commit on detached HEAD');
+ await isolated.git.raw(['read-tree', headSha]);
+
+ const replayEntries: Array<{ path: string; mode: string; blobSha: string; raw: string }> =
+ [];
+ for (let i = 0; i < reconciled.length; i++) {
+ const item = reconciled[i];
+ if (!item) continue;
+ const headRaw = await this.readMcpGitBlob(isolated, headSha, item.path);
+ if (headRaw === null) throw new Error(`tracked MCP path disappeared: ${item.path}`);
+ const commitRaw = applyManagedMcpEntry({
+ target: item.path,
+ raw: headRaw,
+ entry: item.winnerEntry,
+ tomlEditor: this.mcpTomlEditor,
+ });
+ if (commitRaw === null) throw new Error(`cannot edit tracked MCP path: ${item.path}`);
+
+ const treeLine = await isolated.git.raw(['ls-tree', headSha, '--', item.path]);
+ const mode = treeLine.match(/^(100644|100755)\s/)?.[1];
+ if (!mode) throw new Error(`unsafe tracked MCP mode: ${item.path}`);
+
+ const commitBlobPath = `${tmpIndex}.commit-${i}`;
+ tempBlobs.push(commitBlobPath);
+ writeFileSync(commitBlobPath, commitRaw, 'utf8');
+ const commitBlobSha = (
+ await isolated.git.raw(['hash-object', '-w', commitBlobPath])
+ ).trim();
+ await isolated.git.raw([
+ 'update-index',
+ '--add',
+ '--cacheinfo',
+ `${mode},${commitBlobSha},${item.path}`,
+ ]);
+
+ const committedShell = getMcpUnownedShell({
+ target: item.path,
+ raw: commitRaw,
+ tomlEditor: this.mcpTomlEditor,
+ });
+ const overlayShell = getMcpUnownedShell({
+ target: item.path,
+ raw: item.raw,
+ tomlEditor: this.mcpTomlEditor,
+ });
+ const replayRaw =
+ committedShell !== null && committedShell === overlayShell ? commitRaw : item.raw;
+ const replayBlobPath = `${tmpIndex}.replay-${i}`;
+ tempBlobs.push(replayBlobPath);
+ writeFileSync(replayBlobPath, replayRaw, 'utf8');
+ const replayBlobSha = (
+ await isolated.git.raw(['hash-object', '-w', replayBlobPath])
+ ).trim();
+ replayEntries.push({ path: item.path, mode, blobSha: replayBlobSha, raw: replayRaw });
+ }
+
+ const newTree = (await isolated.git.raw(['write-tree'])).trim();
+ const headTree = (await isolated.git.raw(['rev-parse', `${headSha}^{tree}`])).trim();
+ if (newTree === headTree) return;
+
+ await this.applyCommitIdentity(isolated);
+ const commitSha = (
+ await isolated.git.raw([
+ 'commit-tree',
+ newTree,
+ '-p',
+ headSha,
+ '-m',
+ 'Update OpenKnowledge MCP launcher',
+ ])
+ ).trim();
+ if (!SHA_HEX_40.test(commitSha)) throw new Error('commit-tree returned an invalid SHA');
+ try {
+ await isolated.git.raw(['update-ref', `refs/heads/${branch}`, commitSha, headSha]);
+ } catch (err) {
+ log.info(
+ { event: 'mcp-config-reconcile', outcome: 'ref-race', branch, err },
+ '[sync] skipped MCP launcher commit because the branch moved',
+ );
+ return;
+ }
+
+ // Rebase the user's real index/worktree layers onto the new HEAD. The
+ // replay bytes are the reconciler's entry-only result over the original
+ // index/worktree shell, so unrelated staged intent remains staged.
+ try {
+ for (const replay of replayEntries) {
+ await realHandle.git.raw([
+ 'update-index',
+ '--add',
+ '--cacheinfo',
+ `${replay.mode},${replay.blobSha},${replay.path}`,
+ ]);
+ const absolutePath = join(this.projectDir, replay.path);
+ assertRealpathWithinDir(absolutePath, this.projectDir);
+ if (readFileSync(absolutePath, 'utf8') !== replay.raw) {
+ tracedWriteFileSync(absolutePath, replay.raw, 'utf8');
+ }
+ }
+ } catch (err) {
+ // The commit already landed, so recover the entire batch rather than
+ // leaving a partly replayed index. Resetting to the new HEAD turns
+ // the preserved overlay bytes into ordinary unstaged changes.
+ log.warn(
+ { event: 'mcp-config-reconcile', outcome: 'overlay-replay-failed', err },
+ '[sync] MCP overlay replay failed; resetting the affected index entries',
+ );
+ await this.resetRealIndexForPaths(replayEntries.map((entry) => entry.path));
+ this.restoreReconciledMcpOverlays(reconciled);
+ }
+ log.info(
+ { event: 'mcp-config-reconcile', outcome: 'persisted-entry-commit' },
+ '[sync] persisted OpenKnowledge MCP launcher entry commit',
+ );
+ } finally {
+ for (const path of tempBlobs) {
+ try {
+ unlinkSync(path);
+ } catch {}
+ }
+ try {
+ unlinkSync(tmpIndex);
+ } catch {}
+ }
+ });
}
/**
@@ -3306,6 +3688,7 @@ export class SyncEngine {
// would otherwise be reported as a successful pull over a half-merged tree.
let committed = false;
try {
+ await this.applyCommitIdentity(handle);
await handle.git.raw(['commit', '--no-edit']);
const gitDir = resolveGitDir(this.projectDir);
committed = gitDir === null || !existsSync(join(gitDir, 'MERGE_HEAD'));