@foundocs/foundocs-setup 0.3.4 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Use the installation prompt from your project's Foundocs integration guide. It contains a ten-minute, one-use connection code, never an API key. The coding agent fixes an absolute project root and sends the prompt's JSON to the installer's **private stdin** using a process tool. Do not paste the JSON into shell command text, argv, logs, or a committed file.
4
4
 
5
- Version **0.3.4** makes Codex MCP settings portable across teammates while keeping each installation key in private local storage. Existing owned absolute-path configurations can migrate without exchanging a code or rotating a key. For local development verification, build this package and run from its directory:
5
+ Version **0.3.5** extends portable project MCP settings to Claude Code. Both clients run the shared exact-version npm runtime while each installation key stays in private local storage. Existing owned Codex absolute-path and Claude HTTP helper configurations can migrate without exchanging a code or rotating a key. For local development verification, build this package and run from its directory:
6
6
 
7
7
  ```text
8
8
  node src/cli.mjs install --root /absolute/project
@@ -11,15 +11,15 @@ node src/cli.mjs rollback --root /absolute/project
11
11
  node src/cli.mjs migrate --root /absolute/project
12
12
  ```
13
13
 
14
- The install command reads stdin until EOF. Commands never take codes or API keys as arguments. This package requires Node.js 22.19.0+ and a locally installed Claude Code or Codex CLI. Before exchanging the code it inspects the installed CLI's actual helper support, parses existing settings and checks private storage permissions. Missing or incompatible CLIs require installation/update or the manual guide. Codex's desktop app without its CLI cannot pass this automatic feature check.
14
+ The install command reads stdin until EOF. Commands never take codes or API keys as arguments. This package requires Node.js 22.19.0+ and a locally installed Claude Code or Codex CLI. Before exchanging the code it inspects the installed CLI's project stdio MCP support, parses existing settings and checks private storage permissions. Missing or incompatible CLIs require installation/update or the manual guide. Codex's desktop app without its CLI cannot pass this automatic feature check.
15
15
 
16
16
  Input JSON follows `SetupInstallInput` version 1: `client` (`claude` or `codex`), `projectId`, `workspaceId`, `attemptId`, `code`, `exchangeUrl`, `mcpUrl`, and `version: 1`. The code is exchanged once for an installation key; same-attempt reruns reuse that private key. A newly issued attempt can replace a revoked key while retaining the previous key privately. Existing keys are never automatically revoked.
17
17
 
18
18
  Configuration is local to the exact `--root`: `foundocs.json`, a marked `AGENTS.md` block, and either `.codex/config.toml` or `.mcp.json`. Claude additionally receives a marked `CLAUDE.md` reference to `AGENTS.md`. The package also installs its English Foundocs skill at `.agents/skills/foundocs/` for Codex or `.claude/skills/foundocs/` for Claude, including the Dreaming protocol reference. The managed instruction block points to the selected client’s discoverable skill. Existing instructions and foreign MCP entries are preserved. Skill files are updated only when unchanged from the installer’s recorded version. Byte-identical packaged files in a new clone are adopted locally; other foreign or user-edited skills stop preflight, and rollback preserves later user edits. Run `update-skills` to add the bundled skills to an older installation without a new connection code. Dreaming itself requires the connected server to expose `dream_memory` and `get_dream`; installation does not enable unavailable server capabilities. Conflicting project IDs, malformed files, symlinks, or a different same-name `foundocs` server stop installation before exchanging the code. Resolve a conflict explicitly; this installer does not overwrite it.
19
19
 
20
- Keys, backups and installation journals live in `~/.local/share/foundocs/setup`, outside the project. `FOUNDOCS_SETUP_HOME` may select another absolute private directory outside the target project, including isolated test fixtures. Keep using that same value for doctor/rollback. Credentials are isolated by workspace, project, and canonical project root. Claude Code continues using a durable copied HTTP `headersHelper` with its original absolute Node and helper paths. Codex uses the exact-version npm package’s `mcp` command through `npx` on PATH; its project settings contain no user-specific path. Its stdio adapter forwards MCP tool discovery and calls to the same Remote HTTP endpoint with the saved Bearer key. This adapter preserves remote schemas, annotations, structured results and errors, and requires an explicit valid project ID on every call. A changed valid project ID is forwarded unchanged; the remote server enforces workspace access. It adds no remote service. macOS/Linux use user-only directories/files (0700/0600). Windows uses PowerShell to apply and verify a protected current-user-only ACL; unsupported ACL filesystems stop before code exchange.
20
+ Keys, backups and installation journals live in `~/.local/share/foundocs/setup`, outside the project. `FOUNDOCS_SETUP_HOME` may select another absolute private directory outside the target project, including isolated test fixtures. Keep using that same value for doctor/rollback. Credentials are isolated by workspace, project, and canonical project root. Both clients use the exact-version npm package’s `mcp` command through `npx` on PATH; their project settings contain no user-specific path. Older copied helpers remain in private storage for compatibility and rollback, but portable MCP does not depend on them. Its stdio adapter forwards MCP tool discovery and calls to the same Remote HTTP endpoint with the saved Bearer key. This adapter preserves remote schemas, annotations, structured results and errors, and requires an explicit valid project ID on every call. A changed valid project ID is forwarded unchanged; the remote server enforces workspace access. It adds no remote service. macOS/Linux use user-only directories/files (0700/0600). Windows uses PowerShell to apply and verify a protected current-user-only ACL; unsupported ACL filesystems stop before code exchange.
21
21
 
22
- The helper prefers the saved installation credential. To explicitly use a process-provided `FOUNDOCS_API_KEY`, also provide matching `FOUNDOCS_PROJECT_ID` and `FOUNDOCS_WORKSPACE_ID`. An unrelated shell key never silently overrides the saved workspace key. The helper's stdout contains authentication headers solely for the host MCP client; do not invoke it through tools that log stdout.
22
+ The helper prefers the saved installation credential. To explicitly use a process-provided `FOUNDOCS_API_KEY`, also provide matching `FOUNDOCS_PROJECT_ID` and `FOUNDOCS_WORKSPACE_ID`. An unrelated shell key never silently overrides the saved workspace key. The legacy HTTP helper’s stdout contains authentication headers solely for the host MCP client; do not invoke it through tools that log stdout. The shared portable runtime writes only MCP messages to stdout.
23
23
 
24
24
  Version 0.2.0 recognizes recorded 0.1.x installations in their original private location. Reinstalling migrates their project filename, managed instruction markers and selected client's server name while retaining credential paths and the rollback journal. Existing doctor and rollback commands can discover the old location. Two recorded default locations are treated as a conflict; choose the intended location explicitly with `FOUNDOCS_SETUP_HOME`. A historical custom storage override remains supported when no current override is supplied. Credentials and helper directories are never moved automatically.
25
25
 
@@ -36,7 +36,7 @@ Commit `foundocs.json`, the project `.codex/config.toml`, and the managed instru
36
36
  ```toml
37
37
  [mcp_servers.foundocs]
38
38
  command = "npx"
39
- args = ["--yes", "@foundocs/foundocs-setup@0.3.4", "mcp", "--project-id", "YOUR-PROJECT-UUID"]
39
+ args = ["--yes", "@foundocs/foundocs-setup@0.3.5", "mcp", "--project-id", "YOUR-PROJECT-UUID"]
40
40
  env_vars = ["FOUNDOCS_SETUP_HOME", "FOUNDOCS_API_KEY", "FOUNDOCS_PROJECT_ID", "FOUNDOCS_WORKSPACE_ID", "STEERDOCS_SETUP_HOME", "STEERDOCS_API_KEY", "STEERDOCS_PROJECT_ID", "STEERDOCS_WORKSPACE_ID"]
41
41
  startup_timeout_sec = 60
42
42
  ```
@@ -54,14 +54,38 @@ The runtime starts from the host's working directory and selects the nearest `fo
54
54
  After this release is published:
55
55
 
56
56
  ```text
57
- npx --yes @foundocs/foundocs-setup@0.3.4 migrate --root /absolute/project
58
- npx --yes @foundocs/foundocs-setup@0.3.4 doctor --root /absolute/project
57
+ npx --yes @foundocs/foundocs-setup@0.3.5 migrate --root /absolute/project
58
+ npx --yes @foundocs/foundocs-setup@0.3.5 doctor --root /absolute/project
59
59
  ```
60
60
 
61
61
  `migrate` is offline, requires no connection code, and retains the credential bytes. It verifies the private manifest and journal against the original absolute transport, edits only the owned server's transport fields and preserves unrelated TOML, comments, tool settings and timeouts. Missing ownership evidence, changed execution settings and unsupported inline tables stop with the original file intact. An install rerun can perform the same migration while reusing its saved same-attempt key. `update-skills` remains skill-only.
62
62
 
63
63
  Writes use the existing lock, atomic replacement, concurrency check and rollback journal. If interrupted, retain the journal and rerun the same command; confirm no process is running before clearing a stale lock. `rollback` restores unchanged setup edits to the recorded baseline and preserves later user edits and credentials. The baseline may predate migration when an installation already has a journal. After migration, restart/reconnect the trusted Codex project and call `get_project_context` through its MCP server. Doctor reports legacy transport migration separately from conflicting portable configuration; an independent doctor call does not prove the host connected.
64
64
 
65
+ ## Shared Claude Code projects (0.3.5)
66
+
67
+ Commit the project `.mcp.json` alongside `foundocs.json`, instructions and `.claude/skills` when sharing a Claude project. A fresh Claude installation generates:
68
+
69
+ ```json
70
+ {
71
+ "mcpServers": {
72
+ "foundocs": {
73
+ "type": "stdio",
74
+ "command": "npx",
75
+ "args": ["--yes", "@foundocs/foundocs-setup@0.3.5", "mcp", "--project-id", "YOUR-PROJECT-UUID"]
76
+ }
77
+ }
78
+ }
79
+ ```
80
+
81
+ Every teammate runs the integration prompt once in their clone to save their own installation key. The shared JSON remains byte-identical when it already has a valid supported pin. Claude’s stdio process inherits the host environment: start Claude with Node/npm/npx on PATH and, when applicable, the same `FOUNDOCS_SETUP_HOME` and matching scoped credential override variables. No private environment value belongs in `.mcp.json`. The first uncached launch can require registry access. Approve the project MCP server in Claude before connecting.
82
+
83
+ Claude uses the same working-directory resolution, project ID guard, private manifest/credential checks and redacted errors as Codex. `CLAUDE_PROJECT_DIR` does not override root selection. Runtime 0.3.5 is the first version that accepts Claude installation manifests; a Claude pin to 0.3.4 is rejected. Existing Codex 0.3.4 pins remain supported and are not upgraded by reinstall or `update-skills`.
84
+
85
+ For an existing Claude HTTP `headersHelper` installation, run the same `migrate --root /absolute/project` command above with 0.3.5. Migration verifies the recorded helper command, private credential scope and endpoint before converting it to stdio. It performs no key exchange or remote request, retains unrelated JSON values and server settings, and supports retry and rollback. Modified endpoints/helpers, extra authentication or execution overrides, and missing ownership evidence are conflicts. JSON whitespace may be normalized during conversion; an already-portable configuration is left byte for byte unchanged. `doctor` points owned HTTP installs to migration, distinguishes configuration conflicts, and independently checks MCP connectivity. `update-skills` changes neither connection settings nor keys.
86
+
87
+ Before release, the 0.3.5 tarball was tested through both clients’ private installation records and real HTTP MCP. The macOS Claude CLI loaded the generated `.mcp.json` at project scope and reported Connected; a protocol client using the same generated command completed discovery and `get_project_context`. The real Codex host also discovered the tools and completed a read call. Claude was not logged in, so model-driven Claude tool selection was not verified. Public npm publication and Linux/Windows host verification are separate release checks.
88
+
65
89
  ## Verification status
66
90
 
67
91
  The implementation includes unit/integration tests for both configuration formats, preservation, reruns, conflicts, credential isolation, redaction, recovery, rollback, protocol diagnostics, path quoting and ACL command generation. Local feature checks pass on macOS with Codex CLI 0.149.1 and Claude Code 2.1.284. Windows/Linux command paths are implemented, but real runtime verification on those operating systems is still required before claiming them verified. Package automated tests use isolated host capability fixtures. The 0.3.4 packed artifact was additionally verified in the product repository on macOS with a real Codex host, an isolated trusted CODEX_HOME, the generated project configuration, and an actual HTTP MCP get_project_context call. This does not verify Linux/Windows or a public npm release.
@@ -79,7 +103,7 @@ Existing recorded installations can update the skill and managed instructions wi
79
103
  node /absolute/path/to/foundocs-setup/src/cli.mjs update-skills --root /absolute/project
80
104
  ```
81
105
 
82
- The equivalent command for this release is `npx --yes @foundocs/foundocs-setup@0.3.4 update-skills --root /absolute/project`. The local commands above run this checkout; a pinned npm command requires that registry release to exist.
106
+ The equivalent command for this release is `npx --yes @foundocs/foundocs-setup@0.3.5 update-skills --root /absolute/project`. The local commands above run this checkout; a pinned npm command requires that registry release to exist.
83
107
 
84
108
  Updates preserve MCP settings, project configuration, authentication helpers and private keys, including installations that still use the historical configuration filename. The private `skills.json` records installed/pending asset hashes for interruption recovery. Foreign same-name files and local skill edits stop installation/update before project writes; move or reconcile the reported file explicitly, then retry. Unrelated skills and instructions are retained. `rollback` includes skill assets and preserves concurrent edits.
85
109
 
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@foundocs/foundocs-setup",
3
- "version": "0.3.4",
3
+ "version": "0.3.5",
4
4
  "description": "Repeatable project setup and agent skills for the Foundocs remote MCP server",
5
5
  "foundocsRelease": {
6
- "summary": "Make Codex MCP configuration portable across teammates with a pinned npm runtime and private per-installation credentials; migrate existing owned configurations without rotating keys."
6
+ "summary": "Make Claude Code project MCP settings portable with the shared pinned npm runtime; migrate owned HTTP helpers offline while retaining private credentials."
7
7
  },
8
8
  "type": "module",
9
9
  "bin": {
package/src/runtime.mjs CHANGED
@@ -26,7 +26,7 @@ async function privateFile(path) {
26
26
  export async function validateInstallation(root, directory, manifest) {
27
27
  const base = dirname(dirname(directory));
28
28
  await privateFile(join(directory, 'installation.json'));
29
- if (manifest.version !== 1 || manifest.client !== 'codex' || manifest.root !== root || !UUID.test(manifest.projectId) || !UUID.test(manifest.workspaceId) || !UUID.test(manifest.attemptId)) throw unavailable();
29
+ if (manifest.version !== 1 || !['codex', 'claude'].includes(manifest.client) || manifest.root !== root || !UUID.test(manifest.projectId) || !UUID.test(manifest.workspaceId) || !UUID.test(manifest.attemptId)) throw unavailable();
30
30
  validateUrl(manifest.mcpUrl);
31
31
  const expected = join(base, 'credentials', manifest.workspaceId, manifest.projectId, digest(root), 'key.json');
32
32
  if (!isAbsolute(manifest.credentialPath) || manifest.credentialPath !== expected) throw unavailable();
package/src/setup.mjs CHANGED
@@ -165,7 +165,7 @@ async function atomicWrite(path, content, mode = 0o600) {
165
165
 
166
166
  async function run(client, args, options = {}) {
167
167
  try { return await exec(client, args, { timeout: 20000, maxBuffer: 4 * 1024 * 1024, ...options }); }
168
- catch { fail('preflight', `${client} must be installed locally and support HTTP authentication helpers. Update the client or use the manual guide.`); }
168
+ catch { fail('preflight', `${client} must be installed locally and support project stdio MCP configuration. Update the client or use the manual guide.`); }
169
169
  }
170
170
 
171
171
  export async function probeClient(client) {
@@ -178,17 +178,17 @@ export async function probeClient(client) {
178
178
  const directory = await mkdtemp(join(tmpdir(), 'foundocs-client-probe-'));
179
179
  const options = { cwd: directory, env: { ...process.env, CLAUDE_CONFIG_DIR: join(directory, 'home') } };
180
180
  try {
181
- const configuration = { type: 'http', url: 'https://example.invalid/mcp', headersHelper: 'echo {}' };
181
+ const configuration = { type: 'stdio', command: 'npx', args: ['--version'] };
182
182
  await run('claude', ['mcp', 'add-json', '--scope', 'project', 'foundocs_setup_probe', JSON.stringify(configuration)], options);
183
183
  const saved = parseJson(await readFile(join(directory, '.mcp.json'), 'utf8'), '.mcp.json');
184
- if (saved.mcpServers?.foundocs_setup_probe?.headersHelper !== 'echo {}') fail('preflight', 'Claude Code did not preserve headersHelper. Update Claude Code first.');
184
+ if (!sameConfig(saved.mcpServers?.foundocs_setup_probe, configuration)) fail('preflight', 'Claude Code did not preserve stdio MCP configuration. Update Claude Code first.');
185
185
  let rejected = false;
186
- try { await exec('claude', ['mcp', 'add-json', '--scope', 'project', 'foundocs_invalid_probe', JSON.stringify({ ...configuration, headersHelper: 123 })], { ...options, timeout: 20000 }); }
186
+ try { await exec('claude', ['mcp', 'add-json', '--scope', 'project', 'foundocs_invalid_probe', JSON.stringify({ ...configuration, args: 123 })], { ...options, timeout: 20000 }); }
187
187
  catch { rejected = true; }
188
- if (!rejected) fail('preflight', 'Claude Code does not validate headersHelper. Update Claude Code first.');
188
+ if (!rejected) fail('preflight', 'Claude Code does not validate stdio arguments. Update Claude Code first.');
189
189
  } finally { await rm(directory, { recursive: true, force: true }); }
190
190
  }
191
- return { client, version, helper: client === 'codex' ? 'stdio_auth_bridge' : 'headers_helper', platform: process.platform };
191
+ return { client, version, helper: 'stdio_auth_bridge', platform: process.platform };
192
192
  }
193
193
 
194
194
  function sameConfig(a, b) {
@@ -199,42 +199,70 @@ function sameConfig(a, b) {
199
199
 
200
200
  export const RUNTIME_ENV = ['FOUNDOCS_SETUP_HOME', 'FOUNDOCS_API_KEY', 'FOUNDOCS_PROJECT_ID', 'FOUNDOCS_WORKSPACE_ID', 'STEERDOCS_SETUP_HOME', 'STEERDOCS_API_KEY', 'STEERDOCS_PROJECT_ID', 'STEERDOCS_WORKSPACE_ID'];
201
201
 
202
- export function portableTransport(projectId, version = PACKAGE_VERSION) {
202
+ export function portableTransport(projectId, version = PACKAGE_VERSION, client = 'codex') {
203
+ if (client === 'claude') return { type: 'stdio', command: 'npx', args: ['--yes', `@foundocs/foundocs-setup@${version}`, 'mcp', '--project-id', projectId] };
203
204
  return { command: 'npx', args: ['--yes', `@foundocs/foundocs-setup@${version}`, 'mcp', '--project-id', projectId], env_vars: [...RUNTIME_ENV], startup_timeout_sec: 60 };
204
205
  }
205
206
 
206
207
  function transportOf(server) { return server && { command: server.command, args: server.args }; }
207
208
 
208
- export function portableVersion(server, projectId) {
209
+ export function portableVersion(server, projectId, client = 'codex') {
209
210
  if (!plainObject(server) || server.command !== 'npx' || !Array.isArray(server.args) || server.args.length !== 5) return null;
210
- if (server.cwd !== undefined || server.env !== undefined || server.url !== undefined || !Array.isArray(server.env_vars) || !RUNTIME_ENV.every(name => server.env_vars.includes(name))) return null;
211
- const version = /^@foundocs\/foundocs-setup@(\d+\.\d+\.\d+)$/.exec(server.args[1])?.[1];
212
- if (!version || !sameConfig(transportOf(server), transportOf(portableTransport(projectId, version)))) return null;
211
+ if (server.cwd !== undefined || server.env !== undefined || server.url !== undefined || server.headersHelper !== undefined) return null;
212
+ if (client === 'claude' ? server.type !== 'stdio' : (!Array.isArray(server.env_vars) || !RUNTIME_ENV.every(name => server.env_vars.includes(name)))) return null;
213
+ const version = /^@foundocs\/foundocs-setup@((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*))$/.exec(server.args[1])?.[1];
214
+ if (!version || !sameConfig(transportOf(server), transportOf(portableTransport(projectId, version, client)))) return null;
213
215
  const [major, minor, patch] = version.split('.').map(Number);
214
- if (major === 0 && (minor < 3 || (minor === 3 && patch < 4))) return null;
216
+ if (major === 0 && (minor < 3 || (minor === 3 && patch < (client === 'claude' ? 5 : 4)))) return null;
215
217
  return version;
216
218
  }
217
219
 
218
- // The journal must record this installation's exact absolute transport. A server
219
- // name or an instruction marker alone never authorizes replacing it.
220
+ const clientConfigName = client => client === 'claude' ? '.mcp.json' : '.codex/config.toml';
221
+ const clientServers = (text, client) => client === 'claude' ? parseJson(text, '.mcp.json').mcpServers : parseToml(text).mcp_servers;
222
+ const oldTransportOf = (server, client) => client === 'claude' && server ? { type: server.type, url: server.url, headersHelper: server.headersHelper } : transportOf(server);
223
+
224
+ function matchesLegacyTransport(server, manifest) {
225
+ if (manifest.client === 'codex') return isAbsolute(server?.command ?? '') && sameConfig(server?.args, [join(dirname(manifest.helperPath), 'bridge-v1.mjs'), manifest.credentialPath, manifest.projectId, manifest.workspaceId, manifest.mcpUrl]);
226
+ if (server?.type !== 'http' || server.url !== manifest.mcpUrl || typeof server.headersHelper !== 'string') return false;
227
+ const args = [manifest.helperPath, '--headers', manifest.credentialPath, manifest.projectId, manifest.workspaceId];
228
+ const suffix = ' ' + helperCommand(args, 'linux');
229
+ if (server.headersHelper.endsWith(suffix)) {
230
+ const first = server.headersHelper.slice(0, -suffix.length);
231
+ if (first.startsWith("'") && first.endsWith("'")) {
232
+ const node = first.slice(1, -1).replaceAll("'\\''", "'");
233
+ if (isAbsolute(node) && server.headersHelper === helperCommand([node, ...args], 'linux')) return true;
234
+ }
235
+ }
236
+ const encoded = /^powershell\.exe -NoProfile -NonInteractive -EncodedCommand ([A-Za-z0-9+/=]+)$/.exec(server.headersHelper)?.[1];
237
+ if (!encoded) return false;
238
+ const script = Buffer.from(encoded, 'base64').toString('utf16le');
239
+ const first = /^& '((?:[^']|'')*)' /.exec(script)?.[1];
240
+ const node = first?.replaceAll("''", "'");
241
+ return typeof node === 'string' && isAbsolute(node) && server.headersHelper === helperCommand([node, ...args], 'win32');
242
+ }
243
+
244
+ function unsafeLegacyOverrides(server, client) {
245
+ return server?.cwd !== undefined || server?.env !== undefined || (client === 'claude'
246
+ ? ['command', 'args', 'headers', 'oauth', 'auth'].some(key => server?.[key] !== undefined)
247
+ : server?.url !== undefined);
248
+ }
249
+
250
+ // Only exact manifest-scoped transports recorded as installer output may migrate.
220
251
  async function recordedTransport(root, directory, manifest) {
221
- const text = await textFile(join(directory, 'rollback.json'));
222
- if (manifest.client !== 'codex') return null;
223
- // A completed rollback removes its journal. Keep using the exact transport
224
- // previously verified and saved privately by migration, never current file data.
225
252
  const previous = manifest.previousTransport;
226
- if (isAbsolute(previous?.command ?? '') && sameConfig(previous?.args, [join(dirname(manifest.helperPath), 'bridge-v1.mjs'), manifest.credentialPath, manifest.projectId, manifest.workspaceId, manifest.mcpUrl])) return transportOf(previous);
253
+ if (matchesLegacyTransport(previous, manifest)) return oldTransportOf(previous, manifest.client);
254
+ const text = await textFile(join(directory, 'rollback.json'));
227
255
  if (text === null) return null;
228
256
  const journal = parseJson(text, 'rollback.json');
229
257
  if (journal.root !== root || !Array.isArray(journal.entries)) fail('preflight', 'Invalid rollback journal.');
230
- const entry = journal.entries.find(entry => entry.path === join(root, '.codex/config.toml'));
258
+ const entry = journal.entries.find(entry => entry.path === join(root, clientConfigName(manifest.client)));
231
259
  if (!entry) return null;
232
260
  for (const [source, candidate] of [['after', entry.after], ['before', entry.before]]) {
233
261
  if (typeof candidate !== 'string') continue;
234
- let config; try { config = parseToml(candidate); } catch { continue; }
262
+ let servers; try { servers = clientServers(candidate, manifest.client); } catch { continue; }
235
263
  for (const name of ['foundocs', legacy.name]) {
236
- const server = config.mcp_servers?.[name];
237
- if ((source === 'after' || sameConfig(transportOf(server), manifest.previousTransport)) && isAbsolute(server?.command ?? '') && sameConfig(server?.args, [join(dirname(manifest.helperPath), 'bridge-v1.mjs'), manifest.credentialPath, manifest.projectId, manifest.workspaceId, manifest.mcpUrl])) return transportOf(server);
264
+ const server = servers?.[name];
265
+ if ((source === 'after' || sameConfig(oldTransportOf(server, manifest.client), previous)) && matchesLegacyTransport(server, manifest)) return oldTransportOf(server, manifest.client);
238
266
  }
239
267
  }
240
268
  return null;
@@ -290,24 +318,22 @@ function replaceTransport(text, oldName, newName, desired, path) {
290
318
 
291
319
  export async function migrate(rootPath, options = {}) {
292
320
  const { root, directory, manifest } = await loadInstallation(rootPath, options);
293
- if (manifest.client !== 'codex') return { ok: true, status: 'not_required', changedFiles: [] };
294
321
  await checkGitRoot(root);
295
322
  return withLock(directory, async () => {
296
323
  if (await installedFormat(root, manifest)) fail('preflight', 'First rerun install to migrate the historical project configuration.');
297
324
  const { validateInstallation } = await import('./runtime.mjs');
298
325
  await validateInstallation(root, directory, manifest, options);
299
326
  const ownedTransport = await recordedTransport(root, directory, manifest);
300
- const entries = (await plan(root, manifest, manifest.credentialPath, manifest.helperPath, { owned: true, ownedTransport })).filter(entry => entry.path === join(root, '.codex/config.toml'));
301
- const version = portableVersion(parseToml(entries[0].after).mcp_servers.foundocs, manifest.projectId);
327
+ const entries = (await plan(root, manifest, manifest.credentialPath, manifest.helperPath, { owned: true, ownedTransport })).filter(entry => entry.path === join(root, clientConfigName(manifest.client)));
328
+ const version = portableVersion(clientServers(entries[0].after, manifest.client).foundocs, manifest.projectId, manifest.client);
302
329
  const updated = { ...manifest, runtimeVersion: version, ...(ownedTransport ? { previousTransport: ownedTransport } : {}) };
303
330
  await atomicWrite(join(directory, 'installation.json'), json(updated));
304
331
  const changes = await applyProjectChanges(root, directory, entries);
305
- return { ok: true, status: changes.length ? 'migrated' : 'already_portable', changedFiles: changes.map(entry => entry.path), credentialRetained: true, next: 'Restart or reconnect Codex MCP, then call get_project_context to verify the host connection.' };
332
+ return { ok: true, status: changes.length ? 'migrated' : 'already_portable', changedFiles: changes.map(entry => entry.path), credentialRetained: true, next: 'Restart or reconnect the selected client MCP, then call get_project_context to verify the host connection.' };
306
333
  });
307
334
  }
308
335
 
309
336
  export async function plan(root, input, credentialPath, helperPath, { oldFormat = false, owned = false, includeSkills = false, ownedTransport = null } = {}) {
310
- const command = helperCommand([process.execPath, helperPath, '--headers', credentialPath, input.projectId, input.workspaceId]);
311
337
  const entries = [];
312
338
  const add = async (name, transform) => {
313
339
  const path = join(root, name); await safeParent(root, path);
@@ -342,16 +368,21 @@ export async function plan(root, input, credentialPath, helperPath, { oldFormat
342
368
  const config = text === null ? {} : parseJson(text, path);
343
369
  if (config.mcpServers !== undefined && !plainObject(config.mcpServers)) fail('preflight', 'mcpServers must be an object.', { path });
344
370
  config.mcpServers ??= {};
345
- const desired = { type: 'http', url: input.mcpUrl, headersHelper: command };
346
371
  const old = config.mcpServers[serverName];
347
372
  const historicalServer = oldFormat ? undefined : config.mcpServers[legacy.name];
348
- if (historicalServer !== undefined) {
349
- if (!owned || old !== undefined || !sameConfig(historicalServer, desired)) fail('preflight', 'Historical MCP configuration is not exclusively owned by this installation. Preserve it and resolve the conflict before retrying.', { path });
350
- delete config.mcpServers[legacy.name];
351
- }
352
- if (old !== undefined && !sameConfig(old, desired)) fail('preflight', 'An existing Foundocs MCP server differs. Preserve it and resolve the name conflict before retrying.', { path });
353
- if (old) return text;
354
- config.mcpServers[serverName] = desired; return json(config);
373
+ if (historicalServer !== undefined && old !== undefined) fail('preflight', 'Both current and historical MCP servers exist. Preserve them and resolve the conflict.', { path });
374
+ const existing = old ?? historicalServer;
375
+ const existingName = old === undefined && historicalServer !== undefined ? legacy.name : serverName;
376
+ const pinned = portableVersion(existing, input.projectId, 'claude');
377
+ const desired = portableTransport(input.projectId, pinned ?? input.runtimeVersion ?? PACKAGE_VERSION, 'claude');
378
+ if (existing !== undefined) {
379
+ if (pinned && existingName === serverName) return text;
380
+ if (pinned ? !owned : (!ownedTransport || !sameConfig(oldTransportOf(existing, 'claude'), ownedTransport) || unsafeLegacyOverrides(existing, 'claude'))) fail('preflight', 'An existing Foundocs MCP server is not a verified installer-owned transport. Preserve it and resolve the conflict before retrying.', { path });
381
+ const { type, url, headersHelper, ...custom } = existing;
382
+ config.mcpServers[serverName] = { ...custom, ...desired };
383
+ if (existingName !== serverName) delete config.mcpServers[existingName];
384
+ } else config.mcpServers[serverName] = desired;
385
+ return json(config);
355
386
  });
356
387
  } else {
357
388
  await add('.codex/config.toml', (text, path) => {
@@ -627,8 +658,8 @@ export async function install(rootPath, rawInput, options = {}) {
627
658
  await atomicWrite(join(base, 'legacy-compat.mjs'), await readFile(COMPAT_SOURCE, 'utf8'));
628
659
  await atomicWrite(helperPath, await readFile(AUTH_SOURCE, 'utf8'));
629
660
  if (bridgeSource) await atomicWrite(join(base, 'bridge-v1.mjs'), bridgeSource);
630
- const portable = input.client === 'codex' ? parseToml(entries.find(entry => entry.path === join(root, '.codex/config.toml')).after).mcp_servers.foundocs : null;
631
- const manifest = { version: 1, brandingVersion: 2, ...(portable ? { runtimeVersion: portableVersion(portable, input.projectId) } : {}), ...(ownedTransport ? { previousTransport: ownedTransport } : previousManifest?.previousTransport ? { previousTransport: previousManifest.previousTransport } : {}), root, client: input.client, projectId: input.projectId, workspaceId: input.workspaceId, attemptId: saved.attemptId, mcpUrl: input.mcpUrl, credentialPath, helperPath };
661
+ const portable = clientServers(entries.find(entry => entry.path === join(root, clientConfigName(input.client))).after, input.client).foundocs;
662
+ const manifest = { version: 1, brandingVersion: 2, ...(portable ? { runtimeVersion: portableVersion(portable, input.projectId, input.client) } : {}), ...(ownedTransport ? { previousTransport: ownedTransport } : previousManifest?.previousTransport ? { previousTransport: previousManifest.previousTransport } : {}), root, client: input.client, projectId: input.projectId, workspaceId: input.workspaceId, attemptId: saved.attemptId, mcpUrl: input.mcpUrl, credentialPath, helperPath };
632
663
  // Persist metadata before project writes so doctor and rollback survive interruption.
633
664
  await atomicWrite(manifestPath, json(manifest));
634
665
  await stageSkills(skills);
@@ -658,22 +689,22 @@ export async function loadInstallation(rootPath, options) {
658
689
 
659
690
  export async function doctor(rootPath, options = {}) {
660
691
  const { root, directory, manifest } = await loadInstallation(rootPath, options);
661
- const runtimeFiles = manifest.client === 'codex' && manifest.runtimeVersion ? [] : [manifest.helperPath, ...(manifest.brandingVersion === 2 ? [join(dirname(manifest.helperPath), 'legacy-compat.mjs')] : []), ...(manifest.client === 'codex' ? [join(dirname(manifest.helperPath), 'bridge-v1.mjs')] : [])];
692
+ const runtimeFiles = manifest.runtimeVersion ? [] : [manifest.helperPath, ...(manifest.brandingVersion === 2 ? [join(dirname(manifest.helperPath), 'legacy-compat.mjs')] : []), ...(manifest.client === 'codex' ? [join(dirname(manifest.helperPath), 'bridge-v1.mjs')] : [])];
662
693
  for (const path of runtimeFiles) if (await textFile(path) === null) fail('diagnostic', 'A durable authentication helper is missing. Rerun install to repair it.', { path });
663
694
  const oldFormat = await textFile(join(root, 'foundocs.json')) === null && await textFile(join(root, legacy.config)) !== null;
664
695
  const skills = await checkSkills(root, directory, manifest, oldFormat);
665
- if (manifest.client === 'codex') {
666
- let config;
667
- try { config = parseToml(await textFile(join(root, '.codex/config.toml')) ?? ''); }
696
+ {
697
+ let servers;
698
+ try { servers = clientServers(await textFile(join(root, clientConfigName(manifest.client))) ?? '{}', manifest.client); }
668
699
  catch { fail('diagnostic', 'MCP configuration is malformed or unsafe. Resolve the configuration conflict before retrying.'); }
669
- const server = config.mcp_servers?.foundocs;
670
- const version = portableVersion(server, manifest.projectId);
700
+ const server = servers?.foundocs;
701
+ const version = portableVersion(server, manifest.projectId, manifest.client);
671
702
  if (server?.command === 'npx' && (!version || version !== manifest.runtimeVersion)) fail('diagnostic', 'Portable MCP configuration differs from the recorded runtime or contains unsupported execution overrides. Reconcile this configuration before retrying.');
672
703
  if (!version) {
673
704
  const ownedTransport = await recordedTransport(root, directory, manifest);
674
- const legacyServer = server ?? config.mcp_servers?.[legacy.name];
675
- if (!ownedTransport || !sameConfig(transportOf(legacyServer), ownedTransport) || legacyServer.cwd !== undefined || legacyServer.env !== undefined || legacyServer.url !== undefined) fail('diagnostic', 'MCP configuration differs from the recorded transport. Resolve the configuration conflict before retrying.');
676
- fail('diagnostic', 'This Codex installation uses a machine-specific transport. Run foundocs-setup migrate --root with this exact root; no new connection code is needed.');
705
+ const legacyServer = server ?? servers?.[legacy.name];
706
+ if (!ownedTransport || !sameConfig(oldTransportOf(legacyServer, manifest.client), ownedTransport) || unsafeLegacyOverrides(legacyServer, manifest.client)) fail('diagnostic', 'MCP configuration differs from the recorded transport. Resolve the configuration conflict before retrying.');
707
+ fail('diagnostic', 'This installation uses a machine-specific transport. Run foundocs-setup migrate --root with this exact root; no new connection code is needed.');
677
708
  }
678
709
  const { resolveRuntime } = await import('./runtime.mjs');
679
710
  await resolveRuntime(manifest.projectId, { ...options, cwd: root });