@foundocs/foundocs-setup 0.3.3 → 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,23 +2,24 @@
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.3** omits routine configuration-file and pathname announcements in the bundled skills and generated agent instructions. Configuration is still resolved and validated internally; agents mention it when asked or when explaining a configuration problem. 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
9
9
  node src/cli.mjs doctor --root /absolute/project
10
10
  node src/cli.mjs rollback --root /absolute/project
11
+ node src/cli.mjs migrate --root /absolute/project
11
12
  ```
12
13
 
13
- 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.
14
15
 
15
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.
16
17
 
17
- 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; 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.
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.
18
19
 
19
- 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. Durable authentication helpers are copied there; MCP settings use the absolute Node executable and these helpers, independent of npm cache lifetime. Claude Code uses its HTTP `headersHelper`. Codex 0.149.1 reserves `Authorization` in its HTTP helper, so Codex uses a bundled local stdio adapter that 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.
20
21
 
21
- 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.
22
23
 
23
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.
24
25
 
@@ -28,9 +29,66 @@ Doctor performs MCP initialize, tool discovery, and `get_project_context` with t
28
29
 
29
30
  For response loss or failure before private key storage, the error reports the attempt ID and guide recovery route: inspect/revoke only that attempt's issued key and generate a new code. After key storage, rerun the same installation input. `rollback` restores only files still matching the installer-written content; concurrent edits are retained and reported. It preserves private credentials for retry. A stale operation lock after process interruption is never automatically deleted: confirm no installer is running before removing the reported private lock file.
30
31
 
32
+ ## Shared Codex projects
33
+
34
+ Commit `foundocs.json`, the project `.codex/config.toml`, and the managed instructions/skills when the team shares them. A newly generated entry uses this transport (the actual file also lists supported environment variable **names**, never their values):
35
+
36
+ ```toml
37
+ [mcp_servers.foundocs]
38
+ command = "npx"
39
+ args = ["--yes", "@foundocs/foundocs-setup@0.3.5", "mcp", "--project-id", "YOUR-PROJECT-UUID"]
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
+ startup_timeout_sec = 60
42
+ ```
43
+
44
+ Each teammate runs the integration prompt once for their own clone. This creates a local private manifest/key scoped to that canonical checkout; it retains the existing valid portable TOML byte for byte. Copying, moving or cloning a checkout does not transfer its authentication. A missing local installation returns a redacted error explaining how to install or diagnose it. No `.env` loader is needed, and the agent never reads the API key.
45
+
46
+ The host must have Node.js 22.19.0+ and npm/npx on its PATH. A desktop launched without your shell's PATH may need its environment configured or a restart. The first uncached `npx` launch requires npm registry access; later launches use npm's normal cache. The runtime version is pinned to an exact release for reproducibility. Reinstalling/authenticating with a newer installer preserves an existing valid pin; `update-skills` never upgrades the MCP runtime. An intentional runtime update is a reviewed change to the shared pin, followed by local install/migrate and host verification. A pinned registry command requires that release to have been published; local pre-release verification uses a packed artifact installed in an isolated fixture.
47
+
48
+ The runtime starts from the host's working directory and selects the nearest `foundocs.json`. It stops at a Git checkout boundary, a malformed nearer file or a project-ID mismatch. It never searches another checkout for a working credential. It validates the canonical root, project/workspace IDs, endpoint, recorded attempt, expected private credential path and file permissions before opening the remote connection. The explicit `--project-id` protects a nested project from silently inheriting its parent's transport. These are startup identity checks: tool calls still pass their explicit `project_id` unchanged and the remote server retains its existing workspace authorization rules.
49
+
50
+ `FOUNDOCS_SETUP_HOME` selects custom private storage through the host environment. Keep the same value when installing, starting Codex, diagnosing, migrating and rolling back. Supported scoped API-key override names and historical equivalents are forwarded through `env_vars`; values stay outside Git. Per-server `cwd`, `env` and URL overrides are rejected by setup/doctor because they can silently change installation selection. Tool allowlists and timeouts are preserved.
51
+
52
+ ### Existing Codex installations
53
+
54
+ After this release is published:
55
+
56
+ ```text
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
+ ```
60
+
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
+
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
+
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
+
31
89
  ## Verification status
32
90
 
33
- 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. These automated tests use isolated host capability fixtures and do not claim that a real host connected successfully.
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.
34
92
 
35
93
  Development: `npm ci`, `npm test`, and `npm run typecheck`.
36
94
 
@@ -45,7 +103,7 @@ Existing recorded installations can update the skill and managed instructions wi
45
103
  node /absolute/path/to/foundocs-setup/src/cli.mjs update-skills --root /absolute/project
46
104
  ```
47
105
 
48
- The equivalent command for this release is `npx --yes @foundocs/foundocs-setup@0.3.3 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.
49
107
 
50
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.
51
109
 
package/dist/bridge.mjs CHANGED
@@ -3481,7 +3481,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
3481
3481
  var NONE = 0;
3482
3482
  var ASSUMED = 1;
3483
3483
  var PROVEN = 2;
3484
- function isRecursive(inst, stack, resolve2) {
3484
+ function isRecursive(inst, stack, resolve3) {
3485
3485
  const cached2 = recursive.get(inst);
3486
3486
  if (cached2 !== void 0)
3487
3487
  return cached2 ? PROVEN : NONE;
@@ -3491,7 +3491,7 @@ function isRecursive(inst, stack, resolve2) {
3491
3491
  let result = NONE;
3492
3492
  const check = (child) => {
3493
3493
  if (result !== PROVEN && child?._zod) {
3494
- const answer = isRecursive(child, stack, resolve2);
3494
+ const answer = isRecursive(child, stack, resolve3);
3495
3495
  if (answer > result)
3496
3496
  result = answer;
3497
3497
  }
@@ -3502,7 +3502,7 @@ function isRecursive(inst, stack, resolve2) {
3502
3502
  const desc = Object.getOwnPropertyDescriptor(sh, key);
3503
3503
  if (spread && !desc.enumerable)
3504
3504
  continue;
3505
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve2) : NONE;
3505
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve3) : NONE;
3506
3506
  if (child > answer)
3507
3507
  answer = child;
3508
3508
  }
@@ -3566,7 +3566,7 @@ function isRecursive(inst, stack, resolve2) {
3566
3566
  break;
3567
3567
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
3568
3568
  case "lazy": {
3569
- const inner = def._cachedInner ?? (resolve2 ? inst._zod.innerType : void 0);
3569
+ const inner = def._cachedInner ?? (resolve3 ? inst._zod.innerType : void 0);
3570
3570
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
3571
3571
  break;
3572
3572
  }
@@ -11084,8 +11084,8 @@ function datetimeReferenceSchemas(pattern) {
11084
11084
  0
11085
11085
  ];
11086
11086
  if (fractionDigits) precisions.push(Number(fractionDigits[1]));
11087
- return [false, true].flatMap((local2) => [false, true].flatMap((offset) => precisions.map((precision) => iso_exports.datetime({
11088
- local: local2,
11087
+ return [false, true].flatMap((local) => [false, true].flatMap((offset) => precisions.map((precision) => iso_exports.datetime({
11088
+ local,
11089
11089
  offset,
11090
11090
  precision
11091
11091
  }))));
@@ -11266,14 +11266,14 @@ function inputRequiredRoundsExceededMessage(method, maxRounds) {
11266
11266
  return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`;
11267
11267
  }
11268
11268
  function sleep(ms, signal) {
11269
- return new Promise((resolve2, reject) => {
11269
+ return new Promise((resolve3, reject) => {
11270
11270
  if (signal?.aborted) {
11271
11271
  reject(signal.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal.reason)));
11272
11272
  return;
11273
11273
  }
11274
11274
  const timer = setTimeout(() => {
11275
11275
  signal?.removeEventListener("abort", onAbort);
11276
- resolve2();
11276
+ resolve3();
11277
11277
  }, ms);
11278
11278
  const onAbort = () => {
11279
11279
  clearTimeout(timer);
@@ -12117,7 +12117,7 @@ var Protocol = class {
12117
12117
  const flowStartedAt = Date.now();
12118
12118
  let onAbort;
12119
12119
  let cleanupMessageId;
12120
- return new Promise((resolve2, reject) => {
12120
+ return new Promise((resolve3, reject) => {
12121
12121
  const earlyReject = (error2) => {
12122
12122
  reject(error2);
12123
12123
  };
@@ -12186,7 +12186,7 @@ var Protocol = class {
12186
12186
  }
12187
12187
  if (decoded.kind === "invalid") return reject(decoded.error);
12188
12188
  if (decoded.kind === "input_required") {
12189
- if (options?.allowInputRequired === true) return resolve2(manualInputRequiredValue(decoded));
12189
+ if (options?.allowInputRequired === true) return resolve3(manualInputRequiredValue(decoded));
12190
12190
  const flow = {
12191
12191
  codec,
12192
12192
  request,
@@ -12198,11 +12198,11 @@ var Protocol = class {
12198
12198
  params
12199
12199
  }, resultSchema, legOptions)
12200
12200
  };
12201
- return resolve2(this._resolveNonCompleteResult(decoded, flow));
12201
+ return resolve3(this._resolveNonCompleteResult(decoded, flow));
12202
12202
  }
12203
12203
  const result = decoded.result;
12204
12204
  validateStandardSchema(resultSchema, result).then((parseResult) => {
12205
- if (parseResult.success) resolve2(parseResult.data);
12205
+ if (parseResult.success) resolve3(parseResult.data);
12206
12206
  else reject(new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`));
12207
12207
  }, reject);
12208
12208
  });
@@ -15186,7 +15186,7 @@ var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => {
15186
15186
  ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
15187
15187
  const schOrFunc = root.refs[ref];
15188
15188
  if (schOrFunc) return schOrFunc;
15189
- let _sch = resolve2.call(this, root, ref);
15189
+ let _sch = resolve3.call(this, root, ref);
15190
15190
  if (_sch === void 0) {
15191
15191
  const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref];
15192
15192
  const { schemaId } = this.opts;
@@ -15212,7 +15212,7 @@ var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => {
15212
15212
  function sameSchemaEnv(s1, s2) {
15213
15213
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
15214
15214
  }
15215
- function resolve2(root, ref) {
15215
+ function resolve3(root, ref) {
15216
15216
  let sch;
15217
15217
  while (typeof (sch = this.refs[ref]) == "string") ref = sch;
15218
15218
  return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
@@ -15662,7 +15662,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
15662
15662
  else if (typeof uri === "object") uri = parse2(serialize(uri, options), options);
15663
15663
  return uri;
15664
15664
  }
15665
- function resolve2(baseURI, relativeURI, options) {
15665
+ function resolve3(baseURI, relativeURI, options) {
15666
15666
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
15667
15667
  const resolved = resolveComponent(parse2(baseURI, schemelessOptions), parse2(relativeURI, schemelessOptions), schemelessOptions, true);
15668
15668
  schemelessOptions.skipEscape = true;
@@ -15836,7 +15836,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
15836
15836
  const fastUri = {
15837
15837
  SCHEMES,
15838
15838
  normalize,
15839
- resolve: resolve2,
15839
+ resolve: resolve3,
15840
15840
  resolveComponent,
15841
15841
  equal,
15842
15842
  serialize,
@@ -21404,14 +21404,14 @@ var ProbeWindow = class ProbeWindow2 {
21404
21404
  */
21405
21405
  async exchange(buildRequest, timeoutMs) {
21406
21406
  const id = `server-discover-probe-${++this._probeCounter}`;
21407
- return new Promise((resolve2) => {
21407
+ return new Promise((resolve3) => {
21408
21408
  let settled = false;
21409
21409
  const settle2 = (reply) => {
21410
21410
  if (settled) return;
21411
21411
  settled = true;
21412
21412
  clearTimeout(timer);
21413
21413
  if (this._pending?.id === id) this._pending = void 0;
21414
- resolve2(reply);
21414
+ resolve3(reply);
21415
21415
  };
21416
21416
  const timer = setTimeout(() => settle2({ kind: "timeout" }), timeoutMs);
21417
21417
  this._pending = {
@@ -22625,13 +22625,13 @@ var Client = class extends Protocol {
22625
22625
  let onCallerAbort;
22626
22626
  let resolveOpening;
22627
22627
  let rejectOpening;
22628
- const opening = new Promise((resolve2, reject) => {
22629
- resolveOpening = resolve2;
22628
+ const opening = new Promise((resolve3, reject) => {
22629
+ resolveOpening = resolve3;
22630
22630
  rejectOpening = reject;
22631
22631
  });
22632
22632
  let resolveClosed;
22633
- const closed = new Promise((resolve2) => {
22634
- resolveClosed = resolve2;
22633
+ const closed = new Promise((resolve3) => {
22634
+ resolveClosed = resolve3;
22635
22635
  });
22636
22636
  const settle2 = (outcome) => {
22637
22637
  if (state === "closed") return;
@@ -22660,7 +22660,7 @@ var Client = class extends Protocol {
22660
22660
  }).catch(() => {
22661
22661
  });
22662
22662
  };
22663
- const close2 = async () => {
22663
+ const close = async () => {
22664
22664
  if (state === "closed") return;
22665
22665
  settle2({ cause: "local" });
22666
22666
  await wireTeardown();
@@ -22717,7 +22717,7 @@ var Client = class extends Protocol {
22717
22717
  }
22718
22718
  return {
22719
22719
  honoredFilter: await opening,
22720
- close: close2,
22720
+ close,
22721
22721
  closed
22722
22722
  };
22723
22723
  }
@@ -26865,8 +26865,8 @@ function datetimeReferenceSchemas2(pattern) {
26865
26865
  0
26866
26866
  ];
26867
26867
  if (fractionDigits) precisions.push(Number(fractionDigits[1]));
26868
- return [false, true].flatMap((local2) => [false, true].flatMap((offset) => precisions.map((precision) => iso_exports.datetime({
26869
- local: local2,
26868
+ return [false, true].flatMap((local) => [false, true].flatMap((offset) => precisions.map((precision) => iso_exports.datetime({
26869
+ local,
26870
26870
  offset,
26871
26871
  precision
26872
26872
  }))));
@@ -27030,14 +27030,14 @@ function inputRequiredRoundsExceededMessage2(method, maxRounds) {
27030
27030
  return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`;
27031
27031
  }
27032
27032
  function sleep2(ms, signal) {
27033
- return new Promise((resolve2, reject) => {
27033
+ return new Promise((resolve3, reject) => {
27034
27034
  if (signal?.aborted) {
27035
27035
  reject(signal.reason instanceof SdkError2 ? signal.reason : new SdkError2(SdkErrorCode2.RequestTimeout, String(signal.reason)));
27036
27036
  return;
27037
27037
  }
27038
27038
  const timer = setTimeout(() => {
27039
27039
  signal?.removeEventListener("abort", onAbort);
27040
- resolve2();
27040
+ resolve3();
27041
27041
  }, ms);
27042
27042
  const onAbort = () => {
27043
27043
  clearTimeout(timer);
@@ -27833,7 +27833,7 @@ var Protocol2 = class {
27833
27833
  const flowStartedAt = Date.now();
27834
27834
  let onAbort;
27835
27835
  let cleanupMessageId;
27836
- return new Promise((resolve2, reject) => {
27836
+ return new Promise((resolve3, reject) => {
27837
27837
  const earlyReject = (error2) => {
27838
27838
  reject(error2);
27839
27839
  };
@@ -27902,7 +27902,7 @@ var Protocol2 = class {
27902
27902
  }
27903
27903
  if (decoded.kind === "invalid") return reject(decoded.error);
27904
27904
  if (decoded.kind === "input_required") {
27905
- if (options?.allowInputRequired === true) return resolve2(manualInputRequiredValue2(decoded));
27905
+ if (options?.allowInputRequired === true) return resolve3(manualInputRequiredValue2(decoded));
27906
27906
  const flow = {
27907
27907
  codec,
27908
27908
  request,
@@ -27914,11 +27914,11 @@ var Protocol2 = class {
27914
27914
  params
27915
27915
  }, resultSchema, legOptions)
27916
27916
  };
27917
- return resolve2(this._resolveNonCompleteResult(decoded, flow));
27917
+ return resolve3(this._resolveNonCompleteResult(decoded, flow));
27918
27918
  }
27919
27919
  const result = decoded.result;
27920
27920
  validateStandardSchema2(resultSchema, result).then((parseResult) => {
27921
- if (parseResult.success) resolve2(parseResult.data);
27921
+ if (parseResult.success) resolve3(parseResult.data);
27922
27922
  else reject(new SdkError2(SdkErrorCode2.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`));
27923
27923
  }, reject);
27924
27924
  });
@@ -30777,7 +30777,7 @@ var require_compile2 = /* @__PURE__ */ __commonJSMin2(((exports) => {
30777
30777
  ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
30778
30778
  const schOrFunc = root.refs[ref];
30779
30779
  if (schOrFunc) return schOrFunc;
30780
- let _sch = resolve2.call(this, root, ref);
30780
+ let _sch = resolve3.call(this, root, ref);
30781
30781
  if (_sch === void 0) {
30782
30782
  const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref];
30783
30783
  const { schemaId } = this.opts;
@@ -30803,7 +30803,7 @@ var require_compile2 = /* @__PURE__ */ __commonJSMin2(((exports) => {
30803
30803
  function sameSchemaEnv(s1, s2) {
30804
30804
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
30805
30805
  }
30806
- function resolve2(root, ref) {
30806
+ function resolve3(root, ref) {
30807
30807
  let sch;
30808
30808
  while (typeof (sch = this.refs[ref]) == "string") ref = sch;
30809
30809
  return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
@@ -31253,7 +31253,7 @@ var require_fast_uri2 = /* @__PURE__ */ __commonJSMin2(((exports, module) => {
31253
31253
  else if (typeof uri === "object") uri = parse2(serialize(uri, options), options);
31254
31254
  return uri;
31255
31255
  }
31256
- function resolve2(baseURI, relativeURI, options) {
31256
+ function resolve3(baseURI, relativeURI, options) {
31257
31257
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
31258
31258
  const resolved = resolveComponent(parse2(baseURI, schemelessOptions), parse2(relativeURI, schemelessOptions), schemelessOptions, true);
31259
31259
  schemelessOptions.skipEscape = true;
@@ -31427,7 +31427,7 @@ var require_fast_uri2 = /* @__PURE__ */ __commonJSMin2(((exports, module) => {
31427
31427
  const fastUri = {
31428
31428
  SCHEMES,
31429
31429
  normalize,
31430
- resolve: resolve2,
31430
+ resolve: resolve3,
31431
31431
  resolveComponent,
31432
31432
  equal,
31433
31433
  serialize,
@@ -36050,7 +36050,7 @@ var StdioServerTransport = class {
36050
36050
  }
36051
36051
  send(message) {
36052
36052
  if (this._closed) return Promise.reject(/* @__PURE__ */ new Error("StdioServerTransport is closed"));
36053
- return new Promise((resolve2, reject) => {
36053
+ return new Promise((resolve3, reject) => {
36054
36054
  const json = serializeMessage2(message);
36055
36055
  let settled = false;
36056
36056
  const onError = (error2) => {
@@ -36065,14 +36065,14 @@ var StdioServerTransport = class {
36065
36065
  settled = true;
36066
36066
  this._stdout.off("error", onError);
36067
36067
  this._stdout.off("drain", onDrain);
36068
- resolve2();
36068
+ resolve3();
36069
36069
  };
36070
36070
  this._stdout.once("error", onError);
36071
36071
  if (this._stdout.write(json)) {
36072
36072
  if (settled) return;
36073
36073
  settled = true;
36074
36074
  this._stdout.off("error", onError);
36075
- resolve2();
36075
+ resolve3();
36076
36076
  } else if (!settled) this._stdout.once("drain", onDrain);
36077
36077
  });
36078
36078
  }
@@ -36096,8 +36096,8 @@ var legacy = Object.freeze({
36096
36096
  projectEnv: "STEERDOCS_PROJECT_ID",
36097
36097
  workspaceEnv: "STEERDOCS_WORKSPACE_ID"
36098
36098
  });
36099
- function legacyCredential(env, projectId2, workspaceId2) {
36100
- return env[legacy.projectEnv] === projectId2 && env[legacy.workspaceEnv] === workspaceId2 ? env[legacy.keyEnv] : void 0;
36099
+ function legacyCredential(env, projectId, workspaceId) {
36100
+ return env[legacy.projectEnv] === projectId && env[legacy.workspaceEnv] === workspaceId ? env[legacy.keyEnv] : void 0;
36101
36101
  }
36102
36102
 
36103
36103
  // src/auth.mjs
@@ -36106,23 +36106,23 @@ async function windowsPrivateAcl(path, { directory = false, apply = false, execu
36106
36106
  const script = `$ErrorActionPreference='Stop'; $p=[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('${target}')); $sid=[Security.Principal.WindowsIdentity]::GetCurrent().User; $acl=Get-Acl -LiteralPath $p; ${apply ? `$acl.SetAccessRuleProtection($true,$false); foreach($rule in @($acl.Access)) { [void]$acl.RemoveAccessRuleSpecific($rule) }; $acl.SetOwner($sid); $rule=New-Object Security.AccessControl.FileSystemAccessRule($sid,'FullControl','${directory ? "ContainerInherit,ObjectInherit" : "None"}','None','Allow'); $acl.AddAccessRule($rule); Set-Acl -LiteralPath $p -AclObject $acl; $acl=Get-Acl -LiteralPath $p;` : ""} if(!$acl.AreAccessRulesProtected -or $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $sid.Value) { throw 'Unsafe owner or inheritance' }; $rules=@($acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])); if($rules.Count -eq 0) { throw 'Missing private access' }; foreach($rule in $rules) { if($rule.IdentityReference.Value -ne $sid.Value -or $rule.AccessControlType -ne 'Allow' -or $rule.IsInherited -or ($rule.FileSystemRights -band [Security.AccessControl.FileSystemRights]::FullControl) -ne [Security.AccessControl.FileSystemRights]::FullControl) { throw 'Unsafe access rule' } };`;
36107
36107
  await execute("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { timeout: 1e4, windowsHide: true, maxBuffer: 65536 });
36108
36108
  }
36109
- async function readCredential(path, projectId2, workspaceId2) {
36109
+ async function readCredential(path, projectId, workspaceId) {
36110
36110
  const info = await lstat(path);
36111
36111
  if (!info.isFile() || info.isSymbolicLink() || process.platform !== "win32" && info.mode & 63) throw new Error("Credential permissions are unsafe.");
36112
36112
  if (process.platform === "win32") await windowsPrivateAcl(path);
36113
36113
  const saved = JSON.parse(await readFile(path, "utf8"));
36114
- if (saved.projectId !== projectId2 || saved.workspaceId !== workspaceId2 || typeof saved.value !== "string" || !saved.value || /[\r\n]/.test(saved.value)) throw new Error("Credential identity is invalid.");
36115
- const envMatches = process.env.FOUNDOCS_PROJECT_ID === projectId2 && process.env.FOUNDOCS_WORKSPACE_ID === workspaceId2;
36114
+ if (saved.projectId !== projectId || saved.workspaceId !== workspaceId || typeof saved.value !== "string" || !saved.value || /[\r\n]/.test(saved.value)) throw new Error("Credential identity is invalid.");
36115
+ const envMatches = process.env.FOUNDOCS_PROJECT_ID === projectId && process.env.FOUNDOCS_WORKSPACE_ID === workspaceId;
36116
36116
  const hasCurrentScope = ["FOUNDOCS_API_KEY", "FOUNDOCS_PROJECT_ID", "FOUNDOCS_WORKSPACE_ID"].some((name) => process.env[name] !== void 0);
36117
- const override = hasCurrentScope ? envMatches ? process.env.FOUNDOCS_API_KEY : void 0 : legacyCredential(process.env, projectId2, workspaceId2);
36117
+ const override = hasCurrentScope ? envMatches ? process.env.FOUNDOCS_API_KEY : void 0 : legacyCredential(process.env, projectId, workspaceId);
36118
36118
  const value = override || saved.value;
36119
36119
  if (/[\r\n]/.test(value)) throw new Error("Credential is invalid.");
36120
36120
  return value;
36121
36121
  }
36122
36122
  if (process.argv[1] && process.argv[2] === "--headers" && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
36123
36123
  try {
36124
- const [path, projectId2, workspaceId2] = process.argv.slice(3);
36125
- const key = await readCredential(path, projectId2, workspaceId2);
36124
+ const [path, projectId, workspaceId] = process.argv.slice(3);
36125
+ const key = await readCredential(path, projectId, workspaceId);
36126
36126
  process.stdout.write(JSON.stringify({ Authorization: `Bearer ${key}` }));
36127
36127
  } catch {
36128
36128
  process.stderr.write("Foundocs authentication unavailable. Run foundocs-setup doctor.\n");
@@ -36131,55 +36131,64 @@ if (process.argv[1] && process.argv[2] === "--headers" && import.meta.url === pa
36131
36131
  }
36132
36132
 
36133
36133
  // src/bridge.mjs
36134
- var [credentialPath, projectId, workspaceId, endpoint] = process.argv.slice(2);
36135
- var remote;
36136
- var local;
36137
- async function close() {
36138
- await remote?.close().catch(() => {
36139
- });
36140
- await local?.close().catch(() => {
36141
- });
36142
- }
36143
- try {
36144
- const url2 = new URL(endpoint);
36145
- if (url2.protocol !== "https:" && !(url2.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url2.hostname)) || url2.username || url2.password || url2.search || url2.hash) throw new Error();
36146
- const key = await readCredential(credentialPath, projectId, workspaceId);
36147
- remote = new Client({ name: "foundocs-local-auth", version: "0.2.0" });
36148
- const transport = new StreamableHTTPClientTransport(url2, {
36149
- requestInit: { headers: { Authorization: `Bearer ${key}` } },
36150
- fetch: (target, init) => {
36151
- if (new URL(typeof target === "string" || target instanceof URL ? target : target.url).origin !== url2.origin) throw new Error("Origin changed");
36152
- return fetch(target, { ...init, redirect: "error", signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(2e4)]) : AbortSignal.timeout(2e4) });
36153
- }
36154
- });
36155
- await remote.connect(transport, { timeout: 2e4 });
36156
- local = new Server({ name: "foundocs", version: "0.2.0" }, { capabilities: { tools: {} }, instructions: remote.getInstructions() });
36157
- local.setRequestHandler("tools/list", async (request) => {
36158
- try {
36159
- return await remote.listTools(request.params);
36160
- } catch {
36161
- throw new ProtocolError3(ProtocolErrorCode2.InternalError, "Foundocs tool discovery failed. Run foundocs-setup doctor.");
36162
- }
36163
- });
36164
- local.setRequestHandler("tools/call", async (request) => {
36165
- if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(request.params.arguments?.project_id)) throw new ProtocolError3(ProtocolErrorCode2.InvalidParams, "Read and pass the explicit project_id from the governing foundocs.json.");
36166
- try {
36167
- return await remote.callTool(request.params);
36168
- } catch {
36169
- throw new ProtocolError3(ProtocolErrorCode2.InternalError, "Foundocs request failed. Check authentication and connectivity. Retry writes only with the same requestId and input.");
36170
- }
36171
- });
36172
- local.onerror = () => process.stderr.write("Foundocs local MCP transport error.\n");
36173
- remote.onerror = () => process.stderr.write("Foundocs remote MCP transport error.\n");
36174
- process.stdin.on("end", () => {
36175
- void close();
36176
- });
36177
- for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => {
36178
- void close().finally(() => process.exit(0));
36179
- });
36180
- await local.connect(new StdioServerTransport());
36181
- } catch {
36182
- process.stderr.write("Foundocs authentication bridge unavailable. Run foundocs-setup doctor.\n");
36183
- await close();
36184
- process.exitCode = 1;
36134
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
36135
+ import { resolve as resolve2 } from "node:path";
36136
+ async function runBridge({ credentialPath, projectId, workspaceId, mcpUrl: endpoint }) {
36137
+ let remote, local;
36138
+ async function close() {
36139
+ await remote?.close().catch(() => {
36140
+ });
36141
+ await local?.close().catch(() => {
36142
+ });
36143
+ }
36144
+ try {
36145
+ const url2 = new URL(endpoint);
36146
+ if (url2.protocol !== "https:" && !(url2.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url2.hostname)) || url2.username || url2.password || url2.search || url2.hash) throw new Error();
36147
+ const key = await readCredential(credentialPath, projectId, workspaceId);
36148
+ remote = new Client({ name: "foundocs-local-auth", version: "0.2.0" });
36149
+ const transport = new StreamableHTTPClientTransport(url2, {
36150
+ requestInit: { headers: { Authorization: `Bearer ${key}` } },
36151
+ fetch: (target, init) => {
36152
+ if (new URL(typeof target === "string" || target instanceof URL ? target : target.url).origin !== url2.origin) throw new Error("Origin changed");
36153
+ return fetch(target, { ...init, redirect: "error", signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(2e4)]) : AbortSignal.timeout(2e4) });
36154
+ }
36155
+ });
36156
+ await remote.connect(transport, { timeout: 2e4 });
36157
+ local = new Server({ name: "foundocs", version: "0.2.0" }, { capabilities: { tools: {} }, instructions: remote.getInstructions() });
36158
+ local.setRequestHandler("tools/list", async (request) => {
36159
+ try {
36160
+ return await remote.listTools(request.params);
36161
+ } catch {
36162
+ throw new ProtocolError3(ProtocolErrorCode2.InternalError, "Foundocs tool discovery failed. Run foundocs-setup doctor.");
36163
+ }
36164
+ });
36165
+ local.setRequestHandler("tools/call", async (request) => {
36166
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(request.params.arguments?.project_id)) throw new ProtocolError3(ProtocolErrorCode2.InvalidParams, "Read and pass the explicit project_id from the governing foundocs.json.");
36167
+ try {
36168
+ return await remote.callTool(request.params);
36169
+ } catch {
36170
+ throw new ProtocolError3(ProtocolErrorCode2.InternalError, "Foundocs request failed. Check authentication and connectivity. Retry writes only with the same requestId and input.");
36171
+ }
36172
+ });
36173
+ local.onerror = () => process.stderr.write("Foundocs local MCP transport error.\n");
36174
+ remote.onerror = () => process.stderr.write("Foundocs remote MCP transport error.\n");
36175
+ process.stdin.on("end", () => {
36176
+ void close();
36177
+ });
36178
+ for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => {
36179
+ void close().finally(() => process.exit(0));
36180
+ });
36181
+ await local.connect(new StdioServerTransport());
36182
+ } catch {
36183
+ process.stderr.write("Foundocs authentication bridge unavailable. Run foundocs-setup doctor.\n");
36184
+ await close();
36185
+ process.exitCode = 1;
36186
+ }
36187
+ }
36188
+ if (process.argv[1] && import.meta.url === pathToFileURL2(resolve2(process.argv[1])).href) {
36189
+ const [credentialPath, projectId, workspaceId, mcpUrl] = process.argv.slice(2);
36190
+ await runBridge({ credentialPath, projectId, workspaceId, mcpUrl });
36185
36191
  }
36192
+ export {
36193
+ runBridge
36194
+ };
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@foundocs/foundocs-setup",
3
- "version": "0.3.3",
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": "Omit routine configuration-file and pathname announcements in Foundocs skills and generated agent instructions; keep project resolution and validation unchanged."
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": {
@@ -26,7 +26,7 @@
26
26
  "build": "node build.mjs",
27
27
  "prepack": "node build.mjs",
28
28
  "test": "node build.mjs && node --test test/*.test.mjs",
29
- "typecheck": "node --check src/cli.mjs && node --check src/setup.mjs && node --check src/auth.mjs && node --check src/bridge.mjs && node --check src/legacy-compat.mjs && node --check src/skill-assets.mjs"
29
+ "typecheck": "node --check src/cli.mjs && node --check src/setup.mjs && node --check src/auth.mjs && node --check src/bridge.mjs && node --check src/legacy-compat.mjs && node --check src/skill-assets.mjs && node --check src/runtime.mjs"
30
30
  },
31
31
  "dependencies": {
32
32
  "@modelcontextprotocol/client": "2.3.1",
package/src/bridge.mjs CHANGED
@@ -5,8 +5,10 @@ import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/cli
5
5
  import { Server, ProtocolError, ProtocolErrorCode } from '@modelcontextprotocol/server';
6
6
  import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
7
7
  import { readCredential } from './auth.mjs';
8
+ import { pathToFileURL } from 'node:url';
9
+ import { resolve } from 'node:path';
8
10
 
9
- const [credentialPath, projectId, workspaceId, endpoint] = process.argv.slice(2);
11
+ export async function runBridge({ credentialPath, projectId, workspaceId, mcpUrl: endpoint }) {
10
12
  let remote, local;
11
13
  async function close() {
12
14
  await remote?.close().catch(() => {});
@@ -44,3 +46,10 @@ try {
44
46
  process.stderr.write('Foundocs authentication bridge unavailable. Run foundocs-setup doctor.\n');
45
47
  await close(); process.exitCode = 1;
46
48
  }
49
+
50
+ }
51
+
52
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
53
+ const [credentialPath, projectId, workspaceId, mcpUrl] = process.argv.slice(2);
54
+ await runBridge({ credentialPath, projectId, workspaceId, mcpUrl });
55
+ }
package/src/cli.mjs CHANGED
@@ -1,12 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import { install, doctor, rollback, updateSkills, SetupError } from './setup.mjs';
2
+ import { install, doctor, rollback, updateSkills, migrate, SetupError } from './setup.mjs';
3
3
 
4
4
  const [command, ...args] = process.argv.slice(2);
5
5
  try {
6
6
  if (command === '--help' || command === '-h') {
7
- process.stdout.write('foundocs-setup install --root ABSOLUTE_PATH < private-input.json\nfoundocs-setup doctor --root ABSOLUTE_PATH\nfoundocs-setup update-skills --root ABSOLUTE_PATH\nfoundocs-setup rollback --root ABSOLUTE_PATH\nInstall reads the one-time code from private stdin only. Never put credentials in argv or shell command text.\n');
7
+ process.stdout.write('foundocs-setup install --root ABSOLUTE_PATH < private-input.json\nfoundocs-setup doctor --root ABSOLUTE_PATH\nfoundocs-setup update-skills --root ABSOLUTE_PATH\nfoundocs-setup rollback --root ABSOLUTE_PATH\nfoundocs-setup migrate --root ABSOLUTE_PATH\nfoundocs-setup mcp --project-id UUID\nInstall reads the one-time code from private stdin only. Never put credentials in argv or shell command text.\n');
8
+ } else if (command === 'mcp') {
9
+ if (args.length !== 2 || args[0] !== '--project-id') throw new SetupError('runtime', 'Use mcp --project-id UUID from the configured project directory.');
10
+ const { startRuntime } = await import('./runtime.mjs');
11
+ await startRuntime(args[1]);
8
12
  } else {
9
- if (!['install', 'doctor', 'rollback', 'update-skills'].includes(command) || args.length !== 2 || args[0] !== '--root') throw new SetupError('input', 'Use install, doctor, rollback, or update-skills with --root ABSOLUTE_PATH.');
13
+ if (!['install', 'doctor', 'rollback', 'update-skills', 'migrate'].includes(command) || args.length !== 2 || args[0] !== '--root') throw new SetupError('input', 'Use install, doctor, rollback, migrate, or update-skills with --root ABSOLUTE_PATH.');
10
14
  let result;
11
15
  if (command === 'install') {
12
16
  if (process.stdin.isTTY) throw new SetupError('input', 'Supply installation JSON through private stdin.');
@@ -17,7 +21,7 @@ try {
17
21
  }
18
22
  try { input = JSON.parse(input); } catch { throw new SetupError('input', 'Installation input must be JSON.'); }
19
23
  result = await install(args[1], input);
20
- } else result = await (command === 'doctor' ? doctor : command === 'update-skills' ? updateSkills : rollback)(args[1]);
24
+ } else result = await (command === 'doctor' ? doctor : command === 'update-skills' ? updateSkills : command === 'migrate' ? migrate : rollback)(args[1]);
21
25
  process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
22
26
  }
23
27
  } catch (error) {
@@ -0,0 +1,68 @@
1
+ import { lstat, realpath } from 'node:fs/promises';
2
+ import { dirname, join, isAbsolute } from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { isDeepStrictEqual } from 'node:util';
5
+ import { legacy } from './legacy-compat.mjs';
6
+ import { readCredential, windowsPrivateAcl } from './auth.mjs';
7
+ import { loadInstallation, textFile, parseJson, validateUrl, SetupError } from './setup.mjs';
8
+ import { runBridge } from './bridge.mjs';
9
+
10
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
11
+ const digest = value => createHash('sha256').update(value).digest('hex');
12
+ const unavailable = () => new SetupError('runtime', 'Foundocs is not configured safely for this project and local user. Run the Foundocs integration install for this clone, or foundocs-setup doctor --root with the governing project root. No other installation was used.');
13
+
14
+ async function privateFile(path) {
15
+ const stat = await lstat(path);
16
+ if (!stat.isFile() || stat.isSymbolicLink() || (process.platform !== 'win32' && ((stat.mode & 0o077) || (typeof process.getuid === 'function' && stat.uid !== process.getuid())))) throw unavailable();
17
+ if (process.platform === 'win32') await windowsPrivateAcl(path);
18
+ let parent = dirname(path);
19
+ while (dirname(parent) !== parent) {
20
+ const info = await lstat(parent);
21
+ if (info.isSymbolicLink() || !info.isDirectory()) throw unavailable();
22
+ parent = dirname(parent);
23
+ }
24
+ }
25
+
26
+ export async function validateInstallation(root, directory, manifest) {
27
+ const base = dirname(dirname(directory));
28
+ await privateFile(join(directory, 'installation.json'));
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
+ validateUrl(manifest.mcpUrl);
31
+ const expected = join(base, 'credentials', manifest.workspaceId, manifest.projectId, digest(root), 'key.json');
32
+ if (!isAbsolute(manifest.credentialPath) || manifest.credentialPath !== expected) throw unavailable();
33
+ await privateFile(expected);
34
+ const saved = parseJson(await textFile(expected), 'private credential');
35
+ if (saved.projectId !== manifest.projectId || saved.workspaceId !== manifest.workspaceId || saved.mcpUrl !== manifest.mcpUrl || saved.attemptId !== manifest.attemptId) throw unavailable();
36
+ await readCredential(expected, manifest.projectId, manifest.workspaceId);
37
+ return manifest;
38
+ }
39
+
40
+ export async function resolveRuntime(projectId, options = {}) {
41
+ try {
42
+ if (!UUID.test(projectId)) throw unavailable();
43
+ let root = await realpath(options.cwd ?? process.cwd());
44
+ while (true) {
45
+ const text = await textFile(join(root, 'foundocs.json'));
46
+ const historical = await textFile(join(root, legacy.config));
47
+ if (historical !== null && text === null) throw unavailable();
48
+ if (text !== null) {
49
+ const config = parseJson(text, 'foundocs.json');
50
+ if (!UUID.test(config.project_id) || config.project_id !== projectId) throw unavailable();
51
+ if (historical !== null && !isDeepStrictEqual(config, parseJson(historical, legacy.config))) throw unavailable();
52
+ break;
53
+ }
54
+ let boundary = false;
55
+ try { await lstat(join(root, '.git')); boundary = true; } catch (error) { if (error.code !== 'ENOENT') throw error; }
56
+ if (boundary || dirname(root) === root) throw unavailable();
57
+ root = dirname(root);
58
+ }
59
+ const { directory, manifest } = await loadInstallation(root, options);
60
+ if (manifest.projectId !== projectId) throw unavailable();
61
+ return await validateInstallation(root, directory, manifest);
62
+ } catch { throw unavailable(); }
63
+ }
64
+
65
+ export async function startRuntime(projectId, options = {}) {
66
+ const manifest = await resolveRuntime(projectId, options);
67
+ await runBridge(manifest);
68
+ }
package/src/setup.mjs CHANGED
@@ -13,6 +13,7 @@ import { legacy, legacyInstructions } from './legacy-compat.mjs';
13
13
  import { knowledgePolicy, dreamingPolicy, updatePolicy, skillAssets } from './skill-assets.mjs';
14
14
 
15
15
  const exec = promisify(execFile);
16
+ const PACKAGE_VERSION = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')).version;
16
17
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
17
18
  const START = '<!-- foundocs:setup:start -->';
18
19
  const END = '<!-- foundocs:setup:end -->';
@@ -75,7 +76,7 @@ export function markedBlock(existing, content, oldFormat = false) {
75
76
  return existing.slice(0, existing.indexOf(start)) + block + existing.slice(existing.indexOf(end) + end.length);
76
77
  }
77
78
 
78
- async function textFile(path) {
79
+ export async function textFile(path) {
79
80
  try {
80
81
  const stat = await lstat(path);
81
82
  if (!stat.isFile() || stat.isSymbolicLink()) fail('preflight', 'Configuration must be a regular file.', { path });
@@ -84,7 +85,7 @@ async function textFile(path) {
84
85
  } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
85
86
  }
86
87
 
87
- function parseJson(text, path) {
88
+ export function parseJson(text, path) {
88
89
  let value;
89
90
  try { value = JSON.parse(text); } catch { fail('preflight', 'Malformed JSON; existing content was preserved.', { path }); }
90
91
  if (!plainObject(value)) fail('preflight', 'Configuration must be a JSON object.', { path });
@@ -164,7 +165,7 @@ async function atomicWrite(path, content, mode = 0o600) {
164
165
 
165
166
  async function run(client, args, options = {}) {
166
167
  try { return await exec(client, args, { timeout: 20000, maxBuffer: 4 * 1024 * 1024, ...options }); }
167
- 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.`); }
168
169
  }
169
170
 
170
171
  export async function probeClient(client) {
@@ -177,17 +178,17 @@ export async function probeClient(client) {
177
178
  const directory = await mkdtemp(join(tmpdir(), 'foundocs-client-probe-'));
178
179
  const options = { cwd: directory, env: { ...process.env, CLAUDE_CONFIG_DIR: join(directory, 'home') } };
179
180
  try {
180
- const configuration = { type: 'http', url: 'https://example.invalid/mcp', headersHelper: 'echo {}' };
181
+ const configuration = { type: 'stdio', command: 'npx', args: ['--version'] };
181
182
  await run('claude', ['mcp', 'add-json', '--scope', 'project', 'foundocs_setup_probe', JSON.stringify(configuration)], options);
182
183
  const saved = parseJson(await readFile(join(directory, '.mcp.json'), 'utf8'), '.mcp.json');
183
- 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.');
184
185
  let rejected = false;
185
- 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 }); }
186
187
  catch { rejected = true; }
187
- 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.');
188
189
  } finally { await rm(directory, { recursive: true, force: true }); }
189
190
  }
190
- 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 };
191
192
  }
192
193
 
193
194
  function sameConfig(a, b) {
@@ -196,8 +197,143 @@ function sameConfig(a, b) {
196
197
  return JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));
197
198
  }
198
199
 
199
- export async function plan(root, input, credentialPath, helperPath, { oldFormat = false, owned = false, includeSkills = false } = {}) {
200
- const command = helperCommand([process.execPath, helperPath, '--headers', credentialPath, input.projectId, input.workspaceId]);
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
+
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] };
204
+ return { command: 'npx', args: ['--yes', `@foundocs/foundocs-setup@${version}`, 'mcp', '--project-id', projectId], env_vars: [...RUNTIME_ENV], startup_timeout_sec: 60 };
205
+ }
206
+
207
+ function transportOf(server) { return server && { command: server.command, args: server.args }; }
208
+
209
+ export function portableVersion(server, projectId, client = 'codex') {
210
+ if (!plainObject(server) || server.command !== 'npx' || !Array.isArray(server.args) || server.args.length !== 5) 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;
215
+ const [major, minor, patch] = version.split('.').map(Number);
216
+ if (major === 0 && (minor < 3 || (minor === 3 && patch < (client === 'claude' ? 5 : 4)))) return null;
217
+ return version;
218
+ }
219
+
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.
251
+ async function recordedTransport(root, directory, manifest) {
252
+ const previous = manifest.previousTransport;
253
+ if (matchesLegacyTransport(previous, manifest)) return oldTransportOf(previous, manifest.client);
254
+ const text = await textFile(join(directory, 'rollback.json'));
255
+ if (text === null) return null;
256
+ const journal = parseJson(text, 'rollback.json');
257
+ if (journal.root !== root || !Array.isArray(journal.entries)) fail('preflight', 'Invalid rollback journal.');
258
+ const entry = journal.entries.find(entry => entry.path === join(root, clientConfigName(manifest.client)));
259
+ if (!entry) return null;
260
+ for (const [source, candidate] of [['after', entry.after], ['before', entry.before]]) {
261
+ if (typeof candidate !== 'string') continue;
262
+ let servers; try { servers = clientServers(candidate, manifest.client); } catch { continue; }
263
+ for (const name of ['foundocs', legacy.name]) {
264
+ const server = servers?.[name];
265
+ if ((source === 'after' || sameConfig(oldTransportOf(server, manifest.client), previous)) && matchesLegacyTransport(server, manifest)) return oldTransportOf(server, manifest.client);
266
+ }
267
+ }
268
+ return null;
269
+ }
270
+
271
+ // Edit standalone assignments only; retain unrelated tables, custom server
272
+ // settings, and comments. Reject unusual TOML forms instead of reserializing.
273
+ function replaceTransport(text, oldName, newName, desired, path) {
274
+ const lines = text.split(/(?<=\n)/);
275
+ const heading = new RegExp(`^\\s*\\[mcp_servers\\.${oldName}\\]\\s*(?:#[^\\n]*)?(?:\\n)?$`);
276
+ const start = lines.findIndex(line => heading.test(line));
277
+ if (start < 0) fail('preflight', 'Use a standalone MCP server table before migration; existing TOML was preserved.', { path });
278
+ let end = start + 1;
279
+ while (end < lines.length && !/^\s*\[/.test(lines[end])) end++;
280
+ const original = parseToml(text).mcp_servers[oldName];
281
+ const body = lines.slice(start + 1, end);
282
+ if (original.cwd !== undefined || original.env !== undefined || original.url !== undefined) fail('preflight', 'Custom cwd, env or URL overrides must be reconciled before migration; existing configuration was preserved.', { path });
283
+ if (original.env_vars !== undefined && !Array.isArray(original.env_vars)) fail('preflight', 'MCP env_vars must be an array.', { path });
284
+ const envVars = [...new Set([...(original.env_vars ?? []), ...RUNTIME_ENV])];
285
+ desired = { ...desired, env_vars: envVars };
286
+ for (const key of ['command', 'args', ...(original.env_vars ? ['env_vars'] : [])]) {
287
+ const index = body.findIndex(line => new RegExp(`^\\s*${key}\\s*=`).test(line));
288
+ if (index < 0) fail('preflight', 'MCP command and args must be standalone assignments before migration.', { path });
289
+ let count = 1, value;
290
+ for (; index + count <= body.length; count++) {
291
+ try { value = parseToml(body.slice(index, index + count).join('')); if (Object.hasOwn(value, key)) break; } catch {}
292
+ }
293
+ if (!value || !sameConfig(value[key], original[key])) fail('preflight', 'MCP assignment cannot be migrated safely.', { path });
294
+ const comments = body.slice(index, index + count).flatMap(line => {
295
+ // Comments outside quoted strings survive replacement, including multiline arrays.
296
+ let quote = null, escaped = false;
297
+ for (let i = 0; i < line.length; i++) {
298
+ const c = line[i];
299
+ if (escaped) { escaped = false; continue; }
300
+ if (quote === '"' && c === '\\') { escaped = true; continue; }
301
+ if (quote) { if (c === quote) quote = null; continue; }
302
+ if (c === '"' || c === "'") quote = c;
303
+ else if (c === '#') return [line.slice(i).replace(/\r?\n$/, '') + '\n'];
304
+ }
305
+ return [];
306
+ });
307
+ body.splice(index, count, ...comments, `${key} = ${JSON.stringify(desired[key])}\n`);
308
+ }
309
+ if (body.length && !body.at(-1).endsWith('\n')) body[body.length - 1] += '\n';
310
+ if (!Object.hasOwn(original, 'env_vars')) body.push(`env_vars = ${JSON.stringify(envVars)}\n`);
311
+ if (!Object.hasOwn(original, 'startup_timeout_sec')) body.push('startup_timeout_sec = 60\n');
312
+ const after = [...lines.slice(0, start), lines[start].replace(`[mcp_servers.${oldName}]`, `[mcp_servers.${newName}]`), ...body, ...lines.slice(end)].join('');
313
+ const expected = { ...original, ...transportOf(desired), env_vars: envVars, startup_timeout_sec: original.startup_timeout_sec ?? desired.startup_timeout_sec };
314
+ const parsed = parseToml(after);
315
+ if (!sameConfig(parsed.mcp_servers?.[newName], expected) || (oldName !== newName && parsed.mcp_servers?.[oldName])) fail('preflight', 'TOML migration verification failed; existing content was preserved.', { path });
316
+ return after;
317
+ }
318
+
319
+ export async function migrate(rootPath, options = {}) {
320
+ const { root, directory, manifest } = await loadInstallation(rootPath, options);
321
+ await checkGitRoot(root);
322
+ return withLock(directory, async () => {
323
+ if (await installedFormat(root, manifest)) fail('preflight', 'First rerun install to migrate the historical project configuration.');
324
+ const { validateInstallation } = await import('./runtime.mjs');
325
+ await validateInstallation(root, directory, manifest, options);
326
+ const ownedTransport = await recordedTransport(root, directory, manifest);
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);
329
+ const updated = { ...manifest, runtimeVersion: version, ...(ownedTransport ? { previousTransport: ownedTransport } : {}) };
330
+ await atomicWrite(join(directory, 'installation.json'), json(updated));
331
+ const changes = await applyProjectChanges(root, directory, entries);
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.' };
333
+ });
334
+ }
335
+
336
+ export async function plan(root, input, credentialPath, helperPath, { oldFormat = false, owned = false, includeSkills = false, ownedTransport = null } = {}) {
201
337
  const entries = [];
202
338
  const add = async (name, transform) => {
203
339
  const path = join(root, name); await safeParent(root, path);
@@ -232,39 +368,43 @@ export async function plan(root, input, credentialPath, helperPath, { oldFormat
232
368
  const config = text === null ? {} : parseJson(text, path);
233
369
  if (config.mcpServers !== undefined && !plainObject(config.mcpServers)) fail('preflight', 'mcpServers must be an object.', { path });
234
370
  config.mcpServers ??= {};
235
- const desired = { type: 'http', url: input.mcpUrl, headersHelper: command };
236
371
  const old = config.mcpServers[serverName];
237
372
  const historicalServer = oldFormat ? undefined : config.mcpServers[legacy.name];
238
- if (historicalServer !== undefined) {
239
- 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 });
240
- delete config.mcpServers[legacy.name];
241
- }
242
- if (old !== undefined && !sameConfig(old, desired)) fail('preflight', 'An existing Foundocs MCP server differs. Preserve it and resolve the name conflict before retrying.', { path });
243
- if (old) return text;
244
- 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);
245
386
  });
246
387
  } else {
247
388
  await add('.codex/config.toml', (text, path) => {
248
389
  let config;
249
390
  try { config = text === null ? {} : parseToml(text); } catch { fail('preflight', 'Malformed TOML; existing content was preserved.', { path }); }
250
391
  if (config.mcp_servers !== undefined && !plainObject(config.mcp_servers)) fail('preflight', 'mcp_servers must be a TOML table.', { path });
251
- const desired = { command: process.execPath, args: [join(dirname(helperPath), 'bridge-v1.mjs'), credentialPath, input.projectId, input.workspaceId, input.mcpUrl] };
252
392
  const old = config.mcp_servers?.[serverName];
253
393
  const historicalServer = oldFormat ? undefined : config.mcp_servers?.[legacy.name];
254
- if (historicalServer !== undefined) {
255
- 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 });
256
- // Old installers emitted this exact table form. Refuse inline/quoted forms
257
- // rather than reserialize and discard unrelated TOML comments or values.
258
- const heading = new RegExp(`^(\\s*)\\[mcp_servers\\.${legacy.name}\\](\\s*(?:#[^\\n]*)?)$`, 'gm');
259
- const after = text.replace(heading, '$1[mcp_servers.foundocs]$2');
260
- try {
261
- const parsed = parseToml(after);
262
- if (parsed.mcp_servers?.[legacy.name] !== undefined || !sameConfig(parsed.mcp_servers?.foundocs, desired)) throw new Error();
263
- } catch { fail('preflight', 'Historical TOML table cannot be renamed safely. Use a standalone server table before retrying.', { path }); }
264
- return after;
394
+ if (historicalServer !== undefined && old !== undefined) fail('preflight', 'Both current and historical MCP servers exist. Preserve them and resolve the conflict.', { path });
395
+ const existing = old ?? historicalServer;
396
+ const existingName = old === undefined && historicalServer !== undefined ? legacy.name : serverName;
397
+ const pinned = portableVersion(existing, input.projectId);
398
+ const desired = portableTransport(input.projectId, pinned ?? input.runtimeVersion ?? PACKAGE_VERSION);
399
+ if (existing !== undefined) {
400
+ if (pinned) {
401
+ if (existingName === serverName) return text;
402
+ if (!owned) fail('preflight', 'Historical MCP configuration is not owned by this installation.', { path });
403
+ return replaceTransport(text, existingName, serverName, desired, path);
404
+ }
405
+ if (!ownedTransport || !sameConfig(transportOf(existing), ownedTransport)) fail('preflight', 'An existing Foundocs MCP server is not a verified installer-owned transport. Preserve it and resolve the conflict before retrying.', { path });
406
+ return replaceTransport(text, existingName, serverName, desired, path);
265
407
  }
266
- if (old !== undefined && !sameConfig(old, desired)) fail('preflight', 'An existing Foundocs MCP server differs. Preserve it and resolve the name conflict before retrying.', { path });
267
- if (old) return text;
268
408
  const after = `${text ?? ''}${text?.endsWith('\n') ? '' : '\n'}\n${stringifyToml({ mcp_servers: { [serverName]: desired } })}`;
269
409
  try { const parsed = parseToml(after); if (!sameConfig(parsed.mcp_servers[serverName], desired)) throw new Error(); }
270
410
  catch { fail('preflight', 'TOML cannot be extended safely (possibly an inline mcp_servers table). Convert that table or use the manual guide.', { path }); }
@@ -361,7 +501,7 @@ async function skillPlan(root, client, directory) {
361
501
  await safeParent(root, path);
362
502
  await writableParent(path);
363
503
  const before = await textFile(path), owned = state.files[asset.name];
364
- if (before !== null && (!owned || ![owned.installedHash, owned.pendingHash].includes(digest(before)))) {
504
+ if (before !== null && before !== asset.content && (!owned || ![owned.installedHash, owned.pendingHash].includes(digest(before)))) {
365
505
  fail('preflight', 'A Foundocs skill file is unowned or modified. Preserve your changes and move or reconcile this file before retrying.', { path, skills: { status: 'conflict' } });
366
506
  }
367
507
  const afterHash = digest(asset.content);
@@ -485,7 +625,8 @@ export async function install(rootPath, rawInput, options = {}) {
485
625
  && previousManifest.mcpUrl === input.mcpUrl && previousManifest.credentialPath === credentialPath && previousManifest.helperPath === helperPath;
486
626
  if (previousManifest !== null && !owned) fail('preflight', 'Saved installation identity differs. Preserve the existing installation and resolve the conflict before retrying.');
487
627
  const skills = await skillPlan(root, input.client, rootDirectory);
488
- const entries = [...await plan(root, input, credentialPath, helperPath, { owned, includeSkills: true }), ...skills.entries];
628
+ const ownedTransport = owned ? await recordedTransport(root, rootDirectory, previousManifest) : null;
629
+ const entries = [...await plan(root, input, credentialPath, helperPath, { owned, ownedTransport, includeSkills: true }), ...skills.entries];
489
630
  let bridgeSource;
490
631
  if (input.client === 'codex') {
491
632
  try { bridgeSource = await readFile(BRIDGE_SOURCE, 'utf8'); } catch { fail('preflight', 'The packaged authentication adapter is missing. Reinstall the published package. No code was exchanged.'); }
@@ -517,7 +658,8 @@ export async function install(rootPath, rawInput, options = {}) {
517
658
  await atomicWrite(join(base, 'legacy-compat.mjs'), await readFile(COMPAT_SOURCE, 'utf8'));
518
659
  await atomicWrite(helperPath, await readFile(AUTH_SOURCE, 'utf8'));
519
660
  if (bridgeSource) await atomicWrite(join(base, 'bridge-v1.mjs'), bridgeSource);
520
- const manifest = { version: 1, brandingVersion: 2, 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 };
521
663
  // Persist metadata before project writes so doctor and rollback survive interruption.
522
664
  await atomicWrite(manifestPath, json(manifest));
523
665
  await stageSkills(skills);
@@ -532,7 +674,7 @@ export async function install(rootPath, rawInput, options = {}) {
532
674
  });
533
675
  }
534
676
 
535
- async function loadInstallation(rootPath, options) {
677
+ export async function loadInstallation(rootPath, options) {
536
678
  await runtime(); const root = await canonicalRoot(rootPath);
537
679
  const base = await storageBase(options, root);
538
680
  const storageRelative = relative(root, base);
@@ -547,10 +689,26 @@ async function loadInstallation(rootPath, options) {
547
689
 
548
690
  export async function doctor(rootPath, options = {}) {
549
691
  const { root, directory, manifest } = await loadInstallation(rootPath, options);
550
- const runtimeFiles = [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')] : [])];
551
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 });
552
694
  const oldFormat = await textFile(join(root, 'foundocs.json')) === null && await textFile(join(root, legacy.config)) !== null;
553
695
  const skills = await checkSkills(root, directory, manifest, oldFormat);
696
+ {
697
+ let servers;
698
+ try { servers = clientServers(await textFile(join(root, clientConfigName(manifest.client))) ?? '{}', manifest.client); }
699
+ catch { fail('diagnostic', 'MCP configuration is malformed or unsafe. Resolve the configuration conflict before retrying.'); }
700
+ const server = servers?.foundocs;
701
+ const version = portableVersion(server, manifest.projectId, manifest.client);
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.');
703
+ if (!version) {
704
+ const ownedTransport = await recordedTransport(root, directory, manifest);
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.');
708
+ }
709
+ const { resolveRuntime } = await import('./runtime.mjs');
710
+ await resolveRuntime(manifest.projectId, { ...options, cwd: root });
711
+ }
554
712
  const entries = await plan(root, manifest, manifest.credentialPath, manifest.helperPath, { oldFormat, owned: true, includeSkills: true });
555
713
  if (entries.some((entry) => entry.before !== entry.after)) fail('diagnostic', 'Installation files are incomplete or modified. Rerun install to repair them.');
556
714
  const client = await (options.probeClient ?? probeClient)(manifest.client);