@foundocs/foundocs-setup 0.3.29 → 0.4.1

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
@@ -1,5 +1,14 @@
1
1
  # Foundocs setup
2
2
 
3
+ ## One installation for multiple projects
4
+
5
+ In the Foundocs web agent guide, choose **글로벌로 적용** for Codex or Claude Code and copy the installation prompt. The default **이 프로젝트에만 적용** installs into a single checkout. Global installation registers the current workspace for the selected OS user and client. Reload the client to discover its MCP server and the `foundocs-workspace` skill.
6
+
7
+ Open your first project folder and paste the separate connection prompt from the web guide. In a new folder, ask “Foundocs 프로젝트 생성하자” to create a project named after the folder, or “Foundocs의 쇼핑몰 프로젝트에 연결해 줘” to link an existing project. Both commands return the workspace and project for the agent to verify with `get_project_context`. Name collisions require selecting an ID. Switching a global binding requires confirmation of its previous project.
8
+
9
+ Register another workspace with its own web prompt and name it in a request to use it. The first registered workspace remains the default until you explicitly change it. Each client keeps its own registrations and private credentials. The shared folder binding in `foundocs.json` contains only workspace and project IDs. Existing project-scoped installations retain their own MCP entry.
10
+
11
+
3
12
  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
13
 
5
14
  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:
@@ -153,6 +162,12 @@ The bundled Foundocs skill uses live tool discovery for `set_content_status` (at
153
162
 
154
163
  Manual identified targets execute on explicit request. Dreaming never archives automatically: the 168-hour/four-negative-evaluation threshold selects review candidates, current bodies and beneficial uses must also be assessed, and only specific current human approval applies a proposal. Content-grounded low future reuse value is also a reason to propose archiving unnecessary knowledge, even if it is factually correct and has no retrieval history; rare but useful rules, decision context and recovery lessons remain protected. Documents gain archive proposals only. See the [Dreaming protocol](skills/foundocs/references/dreaming.md) and [evaluation cases](eval/README.md). Test new installs and skill updates in isolated fixtures; do not overwrite a developer's edited installed skills.
155
164
 
165
+ ### Upgrade an existing global installation
166
+
167
+ Run `npx --yes @foundocs/foundocs-setup@latest workspace update --client codex` (or `--client claude`) and reopen the host. If you registered with a custom storage directory, pass the same `--storage` path. This refreshes the host configuration and skills using the existing workspace registrations and credentials.
168
+
169
+ Ordinary chats in unlinked folders have no Foundocs tools or automatic knowledge or episode capture. You can still explicitly ask to create or link a Foundocs project there. In a linked folder the global bridge serves only that folder’s workspace and project. Reopen the chat after linking if the host cached the empty tool list.
170
+
156
171
  ## Source and releases
157
172
 
158
173
  This repository contains the installer, bundled agent skills, templates and tests for `@foundocs/foundocs-setup`. The Foundocs application and server are maintained separately. Use this repository for installer changes and releases.
package/dist/bridge.mjs CHANGED
@@ -36269,6 +36269,7 @@ async function saveJson(path, value, exclusive = false) {
36269
36269
 
36270
36270
  // src/effect-automatic.mjs
36271
36271
  var effectReads = /* @__PURE__ */ new Set(["get_project_context", "search_docs", "explore_docs", "get_doc", "get_docs"]);
36272
+ var evaluationTools = /* @__PURE__ */ new Set(["report_retrieval_evaluation", "report_retrieval_evaluations"]);
36272
36273
  var reasons = /* @__PURE__ */ new Set(["consent_required", "missing_preparation", "late_preparation", "working_model_unavailable", "unsupported_runner", "runner_not_configured", "isolation_unavailable", "connection_unavailable", "permission_denied", "snapshot_unavailable", "context_unavailable", "budget_admission_denied", "concurrency_limit", "daily_run_limit", "not_sampled", "disabled", "no_beneficial_retrieval", "expired_preparation", "duplicate_task", "report_pending", "local_failure", "incomplete_evaluation"]);
36273
36274
  var safeReason = (e) => reasons.has(e?.reason ?? e?.code?.toLowerCase()) ? e.reason ?? e.code.toLowerCase() : ["EACCES", "EPERM"].includes(e?.code) ? "permission_denied" : "local_failure";
36274
36275
  var dataOf = (r) => r?.structuredContent ?? (() => {
@@ -36287,7 +36288,7 @@ function retrievalIds(value, found = /* @__PURE__ */ new Set()) {
36287
36288
  return found;
36288
36289
  }
36289
36290
  function automaticTool(tool) {
36290
- if (!effectReads.has(tool.name) && tool.name !== "report_retrieval_evaluation") return tool;
36291
+ if (!effectReads.has(tool.name) && !evaluationTools.has(tool.name)) return tool;
36291
36292
  const properties = { ...tool.inputSchema.properties };
36292
36293
  if (effectReads.has(tool.name)) properties.effectTask = {
36293
36294
  type: "object",
@@ -36461,8 +36462,10 @@ var AutomaticMeasurement = class {
36461
36462
  }
36462
36463
  return result2;
36463
36464
  }
36465
+ const isBatch = params.name === "report_retrieval_evaluations";
36466
+ if (isBatch && effectTaskId && args.taskId !== effectTaskId) throw new Error("Conflicting measurement task");
36464
36467
  const result = await forward();
36465
- if (params.name !== "report_retrieval_evaluation" || !effectTaskId || !dataOf(result)?.ok) return result;
36468
+ if (!evaluationTools.has(params.name) || !effectTaskId || !dataOf(result)?.ok) return result;
36466
36469
  if (!UUID.test(effectTaskId)) return result;
36467
36470
  let state;
36468
36471
  try {
@@ -36471,9 +36474,12 @@ var AutomaticMeasurement = class {
36471
36474
  this.warn("Foundocs evaluation tracking unavailable.");
36472
36475
  return result;
36473
36476
  }
36474
- if (!state || state.closed || !state.retrievals.includes(args.retrievalId)) return result;
36475
- state.evaluated = [.../* @__PURE__ */ new Set([...state.evaluated, args.retrievalId])];
36476
- if (args.verdict === "beneficial") state.beneficial = true;
36477
+ if (!state || state.closed) return result;
36478
+ const submitted = isBatch ? args.items : [args];
36479
+ const tracked = submitted.filter((item) => state.retrievals.includes(item.retrievalId));
36480
+ if (!tracked.length) return result;
36481
+ state.evaluated = [.../* @__PURE__ */ new Set([...state.evaluated, ...tracked.map((item) => item.retrievalId)])];
36482
+ if (tracked.some((item) => item.verdict === "beneficial")) state.beneficial = true;
36477
36483
  try {
36478
36484
  await this.store.save(state);
36479
36485
  } catch {
@@ -36825,7 +36831,7 @@ function requestError(error2, name) {
36825
36831
  { code, retryable, ...tool ? { tool } : {}, ...httpStatus !== void 0 ? { httpStatus } : {}, ...remoteCode !== void 0 ? { remoteCode } : {} }
36826
36832
  );
36827
36833
  }
36828
- async function runBridge({ credentialPath, projectId, workspaceId, mcpUrl: endpoint, root, client, automaticFactory, automaticBase }) {
36834
+ async function runBridge({ credentialPath, projectId, workspaceId, mcpUrl: endpoint, root, client, automaticFactory, automaticBase, folderProject }) {
36829
36835
  let automatic, automaticSupported = false, recovered = false;
36830
36836
  let remote, local, checkpointRoute = "remote", checkpointWasLocal = false;
36831
36837
  let argumentDefaults, inventoryRequest;
@@ -36889,16 +36895,31 @@ async function runBridge({ credentialPath, projectId, workspaceId, mcpUrl: endpo
36889
36895
  try {
36890
36896
  const url2 = new URL(endpoint);
36891
36897
  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();
36892
- const key = await readCredential(credentialPath, projectId, workspaceId);
36893
- remote = new Client({ name: "foundocs-local-auth", version: "0.2.0" }, { listMaxPages: 20 });
36894
- const transport = new StreamableHTTPClientTransport(url2, {
36895
- requestInit: { headers: { Authorization: `Bearer ${key}` } },
36896
- fetch: (target, init) => {
36897
- if (new URL(typeof target === "string" || target instanceof URL ? target : target.url).origin !== url2.origin) throw new Error("Origin changed");
36898
- return fetch(target, { ...init, redirect: "error", signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(2e4)]) : AbortSignal.timeout(2e4) });
36898
+ const connectRemote = async () => {
36899
+ const key = await readCredential(credentialPath, projectId, workspaceId);
36900
+ const next = new Client({ name: "foundocs-local-auth", version: "0.2.0" }, { listMaxPages: 20 });
36901
+ const transport = new StreamableHTTPClientTransport(url2, {
36902
+ requestInit: { headers: { Authorization: `Bearer ${key}` } },
36903
+ fetch: (target, init) => {
36904
+ if (new URL(typeof target === "string" || target instanceof URL ? target : target.url).origin !== url2.origin) throw new Error("Origin changed");
36905
+ return fetch(target, { ...init, redirect: "error", signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(2e4)]) : AbortSignal.timeout(2e4) });
36906
+ }
36907
+ });
36908
+ try {
36909
+ await next.connect(transport, { timeout: 2e4 });
36910
+ } catch (error2) {
36911
+ await next.close().catch(() => {
36912
+ });
36913
+ throw error2;
36899
36914
  }
36900
- });
36901
- await remote.connect(transport, { timeout: 2e4 });
36915
+ remote = next;
36916
+ remote.onerror = () => process.stderr.write("Foundocs remote MCP transport error.\n");
36917
+ };
36918
+ let connecting;
36919
+ const ensureConnected = () => remote || (connecting ??= connectRemote().finally(() => {
36920
+ connecting = void 0;
36921
+ }));
36922
+ if (!folderProject) await ensureConnected();
36902
36923
  if (automaticFactory && automaticBase) automatic = new AutomaticMeasurement({
36903
36924
  projectId,
36904
36925
  factory: automaticFactory,
@@ -36916,9 +36937,13 @@ async function runBridge({ credentialPath, projectId, workspaceId, mcpUrl: endpo
36916
36937
  return body.data;
36917
36938
  }
36918
36939
  });
36919
- local = new Server({ name: "foundocs", version: "0.2.0" }, { capabilities: { tools: {} }, instructions: remote.getInstructions() });
36940
+ local = new Server({ name: "foundocs", version: "0.2.0" }, { capabilities: { tools: {} }, instructions: remote?.getInstructions() });
36920
36941
  local.setRequestHandler("tools/list", async () => {
36921
36942
  try {
36943
+ if (folderProject) {
36944
+ if (!await folderProject(local)) return { tools: [] };
36945
+ await ensureConnected();
36946
+ }
36922
36947
  const tools = await refreshToolInventory();
36923
36948
  const collision = tools.some((tool) => tool.name === checkpointTool.name);
36924
36949
  const supported = !!root && ["codex", "claude"].includes(client) && tools.some((tool) => tool.name === "capture_episode") && !collision;
@@ -36932,6 +36957,12 @@ async function runBridge({ credentialPath, projectId, workspaceId, mcpUrl: endpo
36932
36957
  });
36933
36958
  local.setRequestHandler("tools/call", async (request) => {
36934
36959
  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.");
36960
+ if (folderProject) {
36961
+ if (await folderProject(local) !== request.params.arguments.project_id) {
36962
+ throw new ProtocolError3(ProtocolErrorCode2.InvalidParams, "No matching Foundocs binding in this folder.");
36963
+ }
36964
+ await ensureConnected();
36965
+ }
36935
36966
  if (checkpointRoute !== "remote" && request.params.name === checkpointTool.name) {
36936
36967
  const args = request.params.arguments;
36937
36968
  if (args.project_id !== projectId) throw new ProtocolError3(ProtocolErrorCode2.InvalidParams, "Local checkpoint project differs from this installation.");
@@ -36954,7 +36985,7 @@ async function runBridge({ credentialPath, projectId, workspaceId, mcpUrl: endpo
36954
36985
  if (args?.view !== "index") delete defaults.includeRetrievalContext;
36955
36986
  const params = Object.keys(defaults).length > 0 ? { ...request.params, arguments: { ...defaults, ...args } } : request.params;
36956
36987
  if (automaticSupported) return await automatic.call(params);
36957
- if (args && ["effectTask", "effectTaskId", "effectTaskComplete"].some((key2) => Object.hasOwn(args, key2))) {
36988
+ if (args && ["effectTask", "effectTaskId", "effectTaskComplete"].some((key) => Object.hasOwn(args, key))) {
36958
36989
  throw new ProtocolError3(ProtocolErrorCode2.InvalidParams, "Automatic measurement metadata requires the current installer and server.");
36959
36990
  }
36960
36991
  return await remote.callTool(params);
@@ -36963,7 +36994,6 @@ async function runBridge({ credentialPath, projectId, workspaceId, mcpUrl: endpo
36963
36994
  }
36964
36995
  });
36965
36996
  local.onerror = () => process.stderr.write("Foundocs local MCP transport error.\n");
36966
- remote.onerror = () => process.stderr.write("Foundocs remote MCP transport error.\n");
36967
36997
  process.stdin.on("end", () => {
36968
36998
  void close();
36969
36999
  });
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@foundocs/foundocs-setup",
3
- "version": "0.3.29",
3
+ "version": "0.4.1",
4
4
  "description": "Repeatable project setup and agent skills for the Foundocs remote MCP server",
5
5
  "foundocsRelease": {
6
- "summary": "Use document search and exploration for project questions. The installer no longer recommends or instruments the retired evidence lookup tool."
6
+ "summary": "Keep global Foundocs tools and capture inactive in unlinked folders."
7
7
  },
8
8
  "type": "module",
9
9
  "bin": {
@@ -47,9 +47,9 @@ When deciding what to open, use `search_docs` with `view: "preview"` if the live
47
47
 
48
48
  When you need original excerpts in the search response, omit `view` to use the existing excerpt search. Use that same request form on a server that lacks preview. If a cached schema yields a validation error specifically for the preview option, refresh the tool list and use excerpt search from its first page. Preserve the view, filters and scope on every continuation. Metadata-only previews and skipped candidates never receive retrieval evaluations or contribute search shortcut evidence. Evaluate any original body or excerpt actually delivered and read.
49
49
 
50
- Before a content read, supply a fresh UUID `readId` and a short `purpose` when supported. State the question or decision the content might help with, for example "Identify which service tier to inspect when retries alternate between 429 and 503." Keep the same readId and purpose for retries and continuations of that logical read.
50
+ Generate a fresh UUID taskId for each information task and pass it on every content read, including when effect measurement is off. Reuse the same UUID for effectTask when measuring. Keep simultaneous tasks distinct, including tasks sharing a key. Before a content read, supply a fresh UUID `readId` and a short `purpose` when supported. State the question or decision the content might help with, for example "Identify which service tier to inspect when retries alternate between 429 and 503." Keep the same readId and purpose for retries and continuations of that logical read.
51
51
 
52
- After using the delivered content, send `report_retrieval_evaluation` once for each returned `retrievalId` you actually read, using the same workspace key. Choose `beneficial` or `not_beneficial` when you can judge the effect. In `reason` (up to 500 characters), state which detail changed your decision or what you already knew or still needed. If the original purpose was missing or changed, add the actual situation in that reason. For example, "The distinction between 429 and 503 pointed me to the gateway metrics" or "I already knew the failing tier and needed recovery steps the excerpt did not cover." Send only the minimum task context, without full prompts, conversation text, credentials or private identifiers. Use a fresh UUID `requestId` for each evaluation, replay the same ID and payload after an uncertain response, and use a new ID for a correction.
52
+ When you can judge the reads and before finishing the task, use `list_pending_retrievals` with the same project, key and taskId. Submit `report_retrieval_evaluations` with that taskId and 1–50 items (retrievalId, requestId, verdict, reason, optional category). Use the list to recover IDs across reconnects without rereading. Each judgment applies to one actual read. For more pages use nextAfter as after with the same taskId; recheck from the beginning if reads continued. Retry an uncertain batch with the identical items and request IDs. A rejected batch writes nothing; refresh pending IDs on ALREADY_EVALUATED. Leave genuinely unknown results pending. Historical rows without a taskId are ungrouped. On older servers without the batch tools, or for an intentional correction, use `report_retrieval_evaluation` with the known retrievalId. If using automatic measurement with a bridge that only advertises effectTaskId on the single tool, use that tool for the measured task. Choose `beneficial` or `not_beneficial` when you can judge the effect. In `reason` (up to 500 characters), state which detail changed your decision or what you already knew or still needed. If the original purpose was missing or changed, add the actual situation in that reason. For example, "The distinction between 429 and 503 pointed me to the gateway metrics" or "I already knew the failing tier and needed recovery steps the excerpt did not cover." Send only the minimum task context, without full prompts, conversation text, credentials or private identifiers. Use a fresh UUID `requestId` for each evaluation, replay the same ID and payload after an uncertain response, and use a new ID for a correction.
53
53
 
54
54
  ## Batch reads and directory moves
55
55
 
@@ -4,7 +4,7 @@ Inspect the live read schema first. If it advertises `effectTask`, use the insta
4
4
 
5
5
  1. Before the first index/TL;DR/search/content read for a new information question, pass `effectTask: {taskId, question, knownContext, criteria, host}` with the same brief constraints below. Use the trusted SessionStart host object (or the current CODEX_THREAD_ID); never choose another session or a guessed model. Do not send an answer or reconstruct a brief after exposure.
6
6
  2. On every subsequent read/cursor/chunk, pass `effectTask: {taskId}`. Do not supply effectPreparationId yourself. The bridge checks policy, reads installation consent, freezes original sources and identifies the working model BEFORE forwarding the first read. OFF or unsupported/unconsented preparation continues ordinary reads with a diagnostic, never a replacement model.
7
- 3. Evaluate each actual content retrieval normally, adding `effectTaskId: taskId`. Index entries, candidate previews and skipped candidates have no retrieval to evaluate. On the final evaluation after all information reads/evaluations, add `effectTaskComplete: true`. This is the explicit information-acquisition boundary, not an individual useful read. The bridge automatically executes at most once in the background after a successful final evaluation. Never keep reading the same question under a new task ID to create a second sample. If evaluation is incomplete, finish the missing evaluations and mark the final one.
7
+ 3. Evaluate each actual content retrieval normally, adding `effectTaskId: taskId`. Index entries, candidate previews and skipped candidates have no retrieval to evaluate. For a supported batch use the same UUID for taskId and effectTaskId. On the final successful batch (or single evaluation) after all information reads/evaluations, add `effectTaskComplete: true`. This is the explicit information-acquisition boundary, not an individual useful read. The bridge automatically executes at most once in the background after a successful final evaluation. Never keep reading the same question under a new task ID to create a second sample. If evaluation is incomplete, finish the missing evaluations and mark the final one.
8
8
  4. The bridge persists normalized status and reports skip/failure reasons for Insights. Reconnection flushes observed reports/status only; it never respawns interrupted probes. A host process shutdown can interrupt a comparison; missing usage stays unknown. Do not claim an MCP evaluation response means the comparison has completed.
9
9
 
10
10
  ## One-time installation consent and readiness
package/src/bridge.mjs CHANGED
@@ -64,7 +64,7 @@ function requestError(error, name) {
64
64
  { code, retryable, ...(tool ? { tool } : {}), ...(httpStatus !== undefined ? { httpStatus } : {}), ...(remoteCode !== undefined ? { remoteCode } : {}) });
65
65
  }
66
66
 
67
- export async function runBridge({ credentialPath, projectId, workspaceId, mcpUrl: endpoint, root, client, automaticFactory, automaticBase }) {
67
+ export async function runBridge({ credentialPath, projectId, workspaceId, mcpUrl: endpoint, root, client, automaticFactory, automaticBase, folderProject }) {
68
68
  let automatic, automaticSupported = false, recovered = false;
69
69
  let remote, local, checkpointRoute = 'remote', checkpointWasLocal = false;
70
70
  let argumentDefaults, inventoryRequest;
@@ -116,16 +116,24 @@ function refreshToolInventory() {
116
116
  try {
117
117
  const url = new URL(endpoint);
118
118
  if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))) || url.username || url.password || url.search || url.hash) throw new Error();
119
- const key = await readCredential(credentialPath, projectId, workspaceId);
120
- remote = new Client({ name: 'foundocs-local-auth', version: '0.2.0' }, { listMaxPages: 20 });
121
- const transport = new StreamableHTTPClientTransport(url, {
122
- requestInit: { headers: { Authorization: `Bearer ${key}` } },
123
- fetch: (target, init) => {
124
- if (new URL(typeof target === 'string' || target instanceof URL ? target : target.url).origin !== url.origin) throw new Error('Origin changed');
125
- return fetch(target, { ...init, redirect: 'error', signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(20000)]) : AbortSignal.timeout(20000) });
126
- },
127
- });
128
- await remote.connect(transport, { timeout: 20000 });
119
+ const connectRemote = async () => {
120
+ const key = await readCredential(credentialPath, projectId, workspaceId);
121
+ const next = new Client({ name: 'foundocs-local-auth', version: '0.2.0' }, { listMaxPages: 20 });
122
+ const transport = new StreamableHTTPClientTransport(url, {
123
+ requestInit: { headers: { Authorization: `Bearer ${key}` } },
124
+ fetch: (target, init) => {
125
+ if (new URL(typeof target === 'string' || target instanceof URL ? target : target.url).origin !== url.origin) throw new Error('Origin changed');
126
+ return fetch(target, { ...init, redirect: 'error', signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(20000)]) : AbortSignal.timeout(20000) });
127
+ },
128
+ });
129
+ try { await next.connect(transport, { timeout: 20000 }); }
130
+ catch (error) { await next.close().catch(() => {}); throw error; }
131
+ remote = next;
132
+ remote.onerror = () => process.stderr.write('Foundocs remote MCP transport error.\n');
133
+ };
134
+ let connecting;
135
+ const ensureConnected = () => remote || (connecting ??= connectRemote().finally(() => { connecting = undefined; }));
136
+ if (!folderProject) await ensureConnected();
129
137
  if (automaticFactory && automaticBase) automatic = new AutomaticMeasurement({ projectId,
130
138
  factory: automaticFactory, store: automaticStore(automaticBase), warn: message => process.stderr.write(message + '\n'),
131
139
  remote: async (name, args, raw = false) => {
@@ -136,9 +144,13 @@ try {
136
144
  return body.data;
137
145
  },
138
146
  });
139
- local = new Server({ name: 'foundocs', version: '0.2.0' }, { capabilities: { tools: {} }, instructions: remote.getInstructions() });
147
+ local = new Server({ name: 'foundocs', version: '0.2.0' }, { capabilities: { tools: {} }, instructions: remote?.getInstructions() });
140
148
  local.setRequestHandler('tools/list', async () => {
141
149
  try {
150
+ if (folderProject) {
151
+ if (!await folderProject(local)) return { tools: [] };
152
+ await ensureConnected();
153
+ }
142
154
  // The SDK collects all pages before we consider adding a local name.
143
155
  const tools = await refreshToolInventory();
144
156
  const collision = tools.some(tool => tool.name === checkpointTool.name);
@@ -152,6 +164,12 @@ try {
152
164
  });
153
165
  local.setRequestHandler('tools/call', async (request) => {
154
166
  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 ProtocolError(ProtocolErrorCode.InvalidParams, 'Read and pass the explicit project_id from the governing foundocs.json.');
167
+ if (folderProject) {
168
+ if (await folderProject(local) !== request.params.arguments.project_id) {
169
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'No matching Foundocs binding in this folder.');
170
+ }
171
+ await ensureConnected();
172
+ }
155
173
  if (checkpointRoute !== 'remote' && request.params.name === checkpointTool.name) {
156
174
  const args = request.params.arguments;
157
175
  if (args.project_id !== projectId) throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Local checkpoint project differs from this installation.');
@@ -181,7 +199,6 @@ try {
181
199
  catch (error) { throw requestError(error, request.params.name); }
182
200
  });
183
201
  local.onerror = () => process.stderr.write('Foundocs local MCP transport error.\n');
184
- remote.onerror = () => process.stderr.write('Foundocs remote MCP transport error.\n');
185
202
  process.stdin.on('end', () => { void close(); });
186
203
  for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { void close().finally(() => process.exit(0)); });
187
204
  await local.connect(new StdioServerTransport());
package/src/cli.mjs CHANGED
@@ -4,7 +4,11 @@ import { install, doctor, rollback, updateInstallation, migrate, upgradeRuntime,
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 --root ABSOLUTE_PATH\nfoundocs-setup update-skills --root ABSOLUTE_PATH (alias for update)\nfoundocs-setup rollback --root ABSOLUTE_PATH\nfoundocs-setup migrate --root ABSOLUTE_PATH\nfoundocs-setup upgrade-runtime --root ABSOLUTE_PATH\nfoundocs-setup mcp --project-id UUID\nfoundocs-setup measure prepare|run|flush|configure|status --root ABSOLUTE_PATH < private-task.json\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 --root ABSOLUTE_PATH\nfoundocs-setup update-skills --root ABSOLUTE_PATH (alias for update)\nfoundocs-setup rollback --root ABSOLUTE_PATH\nfoundocs-setup migrate --root ABSOLUTE_PATH\nfoundocs-setup upgrade-runtime --root ABSOLUTE_PATH\nfoundocs-setup mcp --project-id UUID\nfoundocs-setup measure prepare|run|flush|configure|status --root ABSOLUTE_PATH < private-task.json\nfoundocs-setup install-global < private-input.json\nfoundocs-setup project create|link --client CLIENT --root ABSOLUTE_PATH [--workspace NAME_OR_ID] [--name NAME | --id UUID] [--replace OLD_UUID]\nfoundocs-setup workspace list|default|update --client CLIENT [--workspace NAME_OR_ID]\nInstall reads the one-time code from private stdin only. Never put credentials in argv or shell command text.\n');
8
+ } else if (['install-global', 'project', 'workspace', 'mcp-global'].includes(command)) {
9
+ const { globalCommand } = await import('./global.mjs');
10
+ const result = await globalCommand(command, args);
11
+ if (result) process.stdout.write(JSON.stringify(result, null, 2) + '\n');
8
12
  } else if (command === 'measure') {
9
13
  if (args.length !== 3 || !['prepare', 'run', 'flush', 'configure', 'status'].includes(args[0]) || args[1] !== '--root') throw new SetupError('input', 'Use measure prepare|run|flush|configure|status --root ABSOLUTE_PATH with JSON on stdin.');
10
14
  let input = '';
@@ -5,6 +5,7 @@ import { readJson, saveJson, privateDir } from './effect-storage.mjs';
5
5
  import { UUID, hash, validateBrief } from './effect-core.mjs';
6
6
 
7
7
  export const effectReads = new Set(['get_project_context', 'search_docs', 'explore_docs', 'get_doc', 'get_docs']);
8
+ const evaluationTools = new Set(['report_retrieval_evaluation', 'report_retrieval_evaluations']);
8
9
  const reasons = new Set(['consent_required', 'missing_preparation', 'late_preparation', 'working_model_unavailable', 'unsupported_runner', 'runner_not_configured', 'isolation_unavailable', 'connection_unavailable', 'permission_denied', 'snapshot_unavailable', 'context_unavailable', 'budget_admission_denied', 'concurrency_limit', 'daily_run_limit', 'not_sampled', 'disabled', 'no_beneficial_retrieval', 'expired_preparation', 'duplicate_task', 'report_pending', 'local_failure', 'incomplete_evaluation']);
9
10
  const safeReason = e => reasons.has(e?.reason ?? e?.code?.toLowerCase()) ? (e.reason ?? e.code.toLowerCase()) : ['EACCES', 'EPERM'].includes(e?.code) ? 'permission_denied' : 'local_failure';
10
11
  const dataOf = r => r?.structuredContent ?? (() => { try { return JSON.parse(r?.content?.find(c => c.type === 'text')?.text); } catch { return null; } })();
@@ -15,7 +16,7 @@ function retrievalIds(value, found = new Set()) {
15
16
  return found;
16
17
  }
17
18
  export function automaticTool(tool) {
18
- if (!effectReads.has(tool.name) && tool.name !== 'report_retrieval_evaluation') return tool;
19
+ if (!effectReads.has(tool.name) && !evaluationTools.has(tool.name)) return tool;
19
20
  const properties = { ...tool.inputSchema.properties };
20
21
  if (effectReads.has(tool.name)) properties.effectTask = { type: 'object', additionalProperties: false,
21
22
  description: 'Local automatic measurement. First read: pre-exposure brief and current trusted host identity; following reads: same taskId only. Never reconstruct a brief after exposure. Source allowlist and consent come from installation, not this call.',
@@ -138,14 +139,19 @@ export class AutomaticMeasurement {
138
139
  }
139
140
  return result;
140
141
  }
142
+ const isBatch = params.name === 'report_retrieval_evaluations';
143
+ if (isBatch && effectTaskId && args.taskId !== effectTaskId) throw new Error('Conflicting measurement task');
141
144
  const result = await forward();
142
- if (params.name !== 'report_retrieval_evaluation' || !effectTaskId || !dataOf(result)?.ok) return result;
145
+ if (!evaluationTools.has(params.name) || !effectTaskId || !dataOf(result)?.ok) return result;
143
146
  if (!UUID.test(effectTaskId)) return result;
144
147
  let state;
145
148
  try { state = await this.store.load(effectTaskId); } catch { this.warn('Foundocs evaluation tracking unavailable.'); return result; }
146
- if (!state || state.closed || !state.retrievals.includes(args.retrievalId)) return result;
147
- state.evaluated = [...new Set([...state.evaluated, args.retrievalId])];
148
- if (args.verdict === 'beneficial') state.beneficial = true;
149
+ if (!state || state.closed) return result;
150
+ const submitted = isBatch ? args.items : [args];
151
+ const tracked = submitted.filter(item => state.retrievals.includes(item.retrievalId));
152
+ if (!tracked.length) return result;
153
+ state.evaluated = [...new Set([...state.evaluated, ...tracked.map(item => item.retrievalId)])];
154
+ if (tracked.some(item => item.verdict === 'beneficial')) state.beneficial = true;
149
155
  try { await this.store.save(state); } catch { this.warn('Foundocs evaluation tracking could not be saved; no comparison started.'); return result; }
150
156
  if (!effectTaskComplete) return result;
151
157
  if (state.retrievals.some(id => !state.evaluated.includes(id))) {
package/src/global.mjs ADDED
@@ -0,0 +1,314 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { lstat, mkdir, readFile, unlink } from 'node:fs/promises';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { homedir } from 'node:os';
6
+ import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path';
7
+ import { isDeepStrictEqual, parseArgs, promisify } from 'node:util';
8
+ import { parse as parseToml } from 'smol-toml';
9
+ import { readCredential } from './auth.mjs';
10
+ import { skillAssets } from './skill-assets.mjs';
11
+ import { SetupError, atomicWrite, canonicalRoot, checkGitRoot, exchange, parseJson, privateDirectory, safeParent, textFile, validateUrl, withLock } from './setup.mjs';
12
+
13
+ const version = JSON.parse(await readFile(new URL('../package.json', import.meta.url))).version;
14
+ 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;
15
+ const digest = value => createHash('sha256').update(value).digest('hex');
16
+ const json = value => JSON.stringify(value, null, 2) + '\n';
17
+ const fail = message => { throw new SetupError('global', message); };
18
+ const serverName = id => 'foundocs_' + digest(id).slice(0, 12);
19
+ const execute = promisify(execFile);
20
+
21
+ function contains(parent, child) {
22
+ const path = relative(parent, child);
23
+ return path !== '..' && !path.startsWith('..' + sep) && !isAbsolute(path);
24
+ }
25
+
26
+ function globalDirectory(storage) {
27
+ const base = storage ?? process.env.FOUNDOCS_SETUP_HOME ?? join(homedir(), '.local', 'share', 'foundocs', 'setup');
28
+ if (!isAbsolute(base)) fail('Use an absolute private storage location.');
29
+ return join(base, 'global');
30
+ }
31
+
32
+ async function readJson(path) {
33
+ const text = await textFile(path);
34
+ return text === null ? null : parseJson(text, path);
35
+ }
36
+
37
+ function registryPath(dir, client) {
38
+ if (!['codex', 'claude'].includes(client)) fail('Choose --client codex or claude.');
39
+ return join(dir, client + '.json');
40
+ }
41
+
42
+ function selectWorkspace(registry, target) {
43
+ const id = target ?? registry?.defaultId;
44
+ const workspaces = registry?.workspaces ?? [];
45
+ const exactId = workspaces.find(item => item.id === id);
46
+ if (exactId) return exactId;
47
+ const matches = workspaces.filter(item => item.name === id);
48
+ if (matches.length === 1) return matches[0];
49
+ throw new SetupError('workspace', matches.length ? 'Choose a workspace by ID.' : 'Register the requested workspace using its web installation prompt.', { workspaces: (registry?.workspaces ?? []).map(({ id, name }) => ({ id, name })) });
50
+ }
51
+
52
+ function keyPath(dir, client, workspace) {
53
+ if (!uuid.test(workspace.id) || !uuid.test(workspace.attemptId)) fail('Invalid private installation record.');
54
+ return join(dir, client + '-' + workspace.id + '-' + workspace.attemptId + '.json');
55
+ }
56
+
57
+ async function requestProjects(dir, client, ws, input, fetcher = fetch) {
58
+ const url = new URL('/api/setup/workspaces/' + ws.id + '/projects', validateUrl(ws.exchangeUrl));
59
+ const key = await readCredential(keyPath(dir, client, ws), null, ws.id);
60
+ const response = await fetcher(url, { method: input ? 'POST' : 'GET', redirect: 'error', signal: AbortSignal.timeout(20000),
61
+ headers: { Authorization: 'Bearer ' + key, 'Content-Type': 'application/json' }, body: input && JSON.stringify(input) });
62
+ const body = await response.json();
63
+ if (!response.ok) throw new SetupError('workspace', 'Workspace request failed (HTTP ' + response.status + '). Check access, plan limits and workspace registration.', { code: body.error?.code });
64
+ return body;
65
+ }
66
+
67
+ async function prepareHost(input, dir) {
68
+ const { client, workspaceId } = input;
69
+ const home = homedir();
70
+ const configHome = client === 'codex' ? process.env.CODEX_HOME ?? join(home, '.codex') : process.env.CLAUDE_CONFIG_DIR ?? join(home, '.claude');
71
+ if (!isAbsolute(configHome)) fail('Client configuration must have an absolute location.');
72
+ const name = serverName(workspaceId);
73
+ const args = ['--yes', '@foundocs/foundocs-setup@' + version, 'mcp-global', '--client', client, '--workspace', workspaceId, '--storage', dirname(dir)];
74
+ const configPath = client === 'codex' ? join(configHome, 'config.toml') : process.env.CLAUDE_CONFIG_DIR ? join(configHome, '.claude.json') : join(home, '.claude.json');
75
+ const current = await textFile(configPath);
76
+ const parseHost = text => client === 'codex' ? parseToml(text ?? '') : JSON.parse(text ?? '{}');
77
+ const entry = config => (client === 'codex' ? config.mcp_servers : config.mcpServers)?.[name];
78
+ const expected = parseHost(current);
79
+ const configured = entry(expected);
80
+ let updatedConfig;
81
+ if (configured) {
82
+ const oldPackage = configured.args?.[1];
83
+ const oldArgs = [...args];
84
+ oldArgs[1] = oldPackage;
85
+ if (configured.command !== 'npx' || !/^@foundocs\/foundocs-setup@\d+\.\d+\.\d+$/.test(oldPackage) ||
86
+ !isDeepStrictEqual(configured.args, oldArgs) || Object.keys(configured).some(key => !['command', 'args', 'type'].includes(key)) ||
87
+ (configured.type && configured.type !== 'stdio')) fail('Conflicting user MCP entry: ' + name);
88
+ if (oldPackage !== args[1]) {
89
+ // Keep comments, unrelated entries and formatting intact in either host format.
90
+ configured.args = args;
91
+ for (let i = current.indexOf(oldPackage); i >= 0; i = current.indexOf(oldPackage, i + oldPackage.length)) {
92
+ const candidate = current.slice(0, i) + args[1] + current.slice(i + oldPackage.length);
93
+ if (isDeepStrictEqual(parseHost(candidate), expected)) { updatedConfig = candidate; break; }
94
+ }
95
+ if (!updatedConfig) fail('Cannot safely update the MCP entry: ' + name);
96
+ }
97
+ }
98
+ await execute(client, ['--version'], { cwd: dir, timeout: 15000 });
99
+ const skillRoot = join(configHome, 'skills', 'foundocs-workspace');
100
+ const guideRoot = join(dir, 'guides', version, client);
101
+ const skillPath = join(skillRoot, 'SKILL.md');
102
+ const receipt = join(dir, client + '-workspace-skill.sha256');
103
+ const source = await readFile(new URL('../templates/workspace-skill.md', import.meta.url), 'utf8');
104
+ const storageArg = JSON.stringify(dirname(dir));
105
+ const bootstrap = source.replaceAll('{{CLIENT}}', client).replaceAll('{{VERSION}}', version)
106
+ .replaceAll('{{STORAGE}}', storageArg).replaceAll('{{GUIDES}}', JSON.stringify(guideRoot));
107
+ await safeParent(dirname(configHome), skillPath);
108
+ const before = await textFile(skillPath);
109
+ // 0.4.0 predates receipts. Recognize only its exact template for this client and storage.
110
+ const legacyHash = client === 'codex' ? 'caeed0744464166dd0772882e965fd9b9464c06d160ffa9f002e5385276f5f91' : 'cccf248e38dbea2d0328dc29c403ef2baba3816250a58894f64754c92f621083';
111
+ if (before !== null && before !== bootstrap && digest(before) !== (await textFile(receipt))?.trim() &&
112
+ digest(before.replace(storageArg, '{{STORAGE}}')) !== legacyHash) fail('Global workspace skill has local edits: ' + skillPath);
113
+ const guides = [];
114
+ const legacySkills = [];
115
+ for (const asset of skillAssets(client)) {
116
+ const name = asset.name.split('/skills/')[1];
117
+ const path = join(guideRoot, name);
118
+ await safeParent(dir, path);
119
+ const content = name === 'foundocs/references/configuration.md'
120
+ ? await readFile(new URL('../templates/workspace-configuration.md', import.meta.url), 'utf8') : asset.content;
121
+ const existing = await textFile(path);
122
+ if (existing === null) guides.push({ path, content });
123
+ else if (existing !== content) fail('Global guide has local edits: ' + path);
124
+ if (name.endsWith('/SKILL.md')) {
125
+ const legacy = join(skillRoot, name);
126
+ await safeParent(dirname(configHome), legacy);
127
+ const descriptor = await textFile(legacy);
128
+ if (descriptor !== null && descriptor !== content) fail('Global skill has local edits: ' + legacy);
129
+ if (descriptor !== null) legacySkills.push({ path: legacy, content });
130
+ }
131
+ }
132
+ return async () => {
133
+ for (const { path, content } of guides) {
134
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
135
+ await atomicWrite(path, content);
136
+ }
137
+ if (before !== bootstrap) {
138
+ if (await textFile(skillPath) !== before) fail('Workspace skill changed during installation.');
139
+ await mkdir(skillRoot, { recursive: true, mode: 0o700 });
140
+ await atomicWrite(skillPath, bootstrap);
141
+ }
142
+ await atomicWrite(receipt, digest(bootstrap) + '\n');
143
+ for (const { path, content } of legacySkills) {
144
+ if (await textFile(path) !== content) fail('Global skill changed during migration: ' + path);
145
+ await unlink(path);
146
+ }
147
+ if (updatedConfig) {
148
+ if (await textFile(configPath) !== current) fail('Client configuration changed. Retry the update.');
149
+ await atomicWrite(configPath, updatedConfig, (await lstat(configPath)).mode & 0o777);
150
+ }
151
+ if (!configured) {
152
+ if (await textFile(configPath) !== current) fail('Client configuration changed. Rerun the same installation.');
153
+ const command = client === 'codex' ? ['mcp', 'add', name, '--', 'npx', ...args] :
154
+ ['mcp', 'add-json', '--scope', 'user', name, JSON.stringify({ type: 'stdio', command: 'npx', args })];
155
+ await execute(client, command, { cwd: dir, timeout: 20000 });
156
+ }
157
+ };
158
+ }
159
+
160
+ export async function installGlobal(input, options = {}) {
161
+ if (input?.version !== 2 || input.projectId !== null || !uuid.test(input.workspaceId) || !uuid.test(input.attemptId) ||
162
+ typeof input.workspaceName !== 'string' || !input.workspaceName.trim() || typeof input.code !== 'string' || !/^sd_setup_[A-Za-z0-9_-]{43}$/.test(input.code)) fail('Expected a workspace installation prompt.');
163
+ validateUrl(input.exchangeUrl); validateUrl(input.mcpUrl);
164
+ const dir = globalDirectory(options.storage);
165
+ const path = registryPath(dir, input.client);
166
+ await privateDirectory(dir);
167
+ return withLock(dir, async () => {
168
+ const ws = { id: input.workspaceId, name: input.workspaceName, attemptId: input.attemptId, exchangeUrl: input.exchangeUrl, mcpUrl: input.mcpUrl };
169
+ const registry = await readJson(path) ?? { defaultId: ws.id, workspaces: [] };
170
+ const finishHost = await (options.prepareHost ?? prepareHost)(input, dir);
171
+ const credential = keyPath(dir, input.client, ws);
172
+ const saved = await readJson(credential);
173
+ if (!saved) await atomicWrite(credential, json({ ...await exchange(input, options.fetch ?? fetch), exchangeUrl: ws.exchangeUrl }));
174
+ else if (saved.attemptId !== ws.attemptId || saved.workspaceId !== ws.id || saved.mcpUrl !== ws.mcpUrl || saved.exchangeUrl !== ws.exchangeUrl) fail('Installation identity changed.');
175
+ const catalog = await requestProjects(dir, input.client, ws, undefined, options.fetch);
176
+ if (catalog.workspace?.id !== ws.id) fail('Workspace identity mismatch.');
177
+ ws.name = catalog.workspace.name;
178
+ await finishHost();
179
+ for (const other of registry.workspaces.filter(item => item.id !== ws.id)) {
180
+ const update = await (options.prepareHost ?? prepareHost)({ client: input.client, workspaceId: other.id }, dir);
181
+ await update();
182
+ }
183
+ registry.workspaces = [...registry.workspaces.filter(item => item.id !== ws.id), ws];
184
+ await atomicWrite(path, json(registry));
185
+ return { status: 'workspace_registered', workspace: catalog.workspace, server: serverName(ws.id), next: 'Reload the client, open your project folder and ask Foundocs to create or link its project.' };
186
+ });
187
+ }
188
+
189
+ function verifyCatalog(catalog, ws) {
190
+ if (catalog.workspace?.id !== ws.id || !Array.isArray(catalog.projects) || catalog.projects.some(p => !uuid.test(p.id) || typeof p.name !== 'string')) fail('Unexpected workspace project listing.');
191
+ }
192
+
193
+ export async function bindProject(action, args, options = {}) {
194
+ if (!['create', 'link'].includes(action)) fail('Use project create or project link.');
195
+ if (args.id && (!uuid.test(args.id) || args.name || action !== 'link')) fail('Select an existing project by ID or by name.');
196
+ const root = await canonicalRoot(args.root ?? '');
197
+ await checkGitRoot(root);
198
+ const dir = globalDirectory(args.storage);
199
+ if (contains(root, dir) || contains(dir, root)) fail('Choose a project folder separate from private storage.');
200
+ const path = registryPath(dir, args.client);
201
+ await privateDirectory(dir);
202
+ return withLock(dir, async () => {
203
+ const ws = selectWorkspace(await readJson(path), args.workspace);
204
+ const configPath = join(root, 'foundocs.json');
205
+ if (await textFile(join(root, 'steerdocs.json')) !== null) fail('Migrate the existing historical project installation before binding this folder.');
206
+ const previous = await textFile(configPath);
207
+ const binding = previous === null ? null : parseJson(previous, configPath);
208
+ if (binding && !uuid.test(binding.project_id)) fail('Invalid existing foundocs.json.');
209
+ const catalog = await requestProjects(dir, args.client, ws, undefined, options.fetch);
210
+ verifyCatalog(catalog, ws);
211
+ const name = (args.name ?? basename(root)).trim();
212
+ if (!name || [...name].length > 80) fail('Provide a project name of 1–80 characters.');
213
+ let project;
214
+ if (action === 'link') {
215
+ const matches = catalog.projects.filter(item => args.id ? item.id === args.id : item.name === name);
216
+ if (matches.length !== 1) throw new SetupError('selection', matches.length ? 'Choose one project by ID.' : 'No project matches that name or ID.', { candidates: matches });
217
+ project = matches[0];
218
+ }
219
+ const journal = join(dir, 'bind-' + digest(root) + '.json');
220
+ let pending = await readJson(journal);
221
+ if (pending?.createdId && pending.createdId === binding?.project_id && pending.workspaceId === binding.workspace_id) {
222
+ await unlink(journal);
223
+ pending = null;
224
+ }
225
+ if (pending && (action !== 'create' || pending.workspaceId !== ws.id || pending.client !== args.client || pending.name !== name || pending.previous !== previous)) {
226
+ throw new SetupError('recovery', 'Resume the interrupted project creation with its original target.', { workspaceId: pending.workspaceId, name: pending.name, client: pending.client });
227
+ }
228
+ if (binding) {
229
+ const current = catalog.projects.find(item => item.id === binding.project_id);
230
+ if (current && (!binding.workspace_id || binding.workspace_id === ws.id) && (current.id === project?.id || (action === 'create' && current.name === name))) {
231
+ return { status: 'already_linked', workspace: catalog.workspace, project: current, server: serverName(ws.id) };
232
+ }
233
+ if (!binding.workspace_id) throw new SetupError('project_installation', 'This folder has a project-scoped installation. Confirm the switch before rolling back that installation and linking the new target.', {
234
+ previous: { projectId: binding.project_id }, target: { workspace: catalog.workspace, project: project ?? { name } },
235
+ });
236
+ if (args.replace !== binding.project_id) throw new SetupError('confirmation', 'Confirm switching the folder, then retry with --replace OLD_PROJECT_ID.', { previous: { workspaceId: binding.workspace_id, projectId: binding.project_id }, target: { workspace: catalog.workspace, project: project ?? { name } } });
237
+ } else if (args.replace) fail('The previous folder binding changed; recheck the target.');
238
+ if (action === 'create') {
239
+ if (!pending) {
240
+ pending = { workspaceId: ws.id, client: args.client, name, previous, requestId: randomUUID() };
241
+ await atomicWrite(journal, json(pending));
242
+ }
243
+ const result = await requestProjects(dir, args.client, ws, { name, requestId: pending.requestId }, options.fetch);
244
+ project = result.workspace?.project;
245
+ if (result.workspace?.id !== ws.id || !uuid.test(project?.id) || project.name !== name) fail('Unexpected created project identity. Retry with the same target.');
246
+ pending.createdId = project.id;
247
+ await atomicWrite(journal, json(pending));
248
+ }
249
+ if (await textFile(configPath) !== previous) fail('The folder binding changed during this request. Review it before retrying.');
250
+ const mode = previous === null ? 0o644 : (await lstat(configPath)).mode & 0o777;
251
+ await atomicWrite(configPath, json({ ...binding, workspace_id: ws.id, project_id: project.id }), mode);
252
+ if (pending) await unlink(journal);
253
+ return { status: 'linked', workspace: catalog.workspace, project: { id: project.id, name: project.name }, server: serverName(ws.id) };
254
+ });
255
+ }
256
+
257
+ // Respect the host's selected folder. A default workspace is never a document binding.
258
+ async function folderProject(server, workspaceId) {
259
+ try {
260
+ let folder = process.cwd();
261
+ if (server.getClientCapabilities()?.roots) {
262
+ const { roots } = await server.listRoots({}, { timeout: 3000 });
263
+ if (roots.length !== 1) return null;
264
+ folder = fileURLToPath(roots[0].uri);
265
+ }
266
+ let root = folder;
267
+ try { root = (await execute('git', ['-C', folder, 'rev-parse', '--show-toplevel'], { timeout: 3000 })).stdout.trim(); }
268
+ catch { /* Plain folders are bound at the selected directory. */ }
269
+ const binding = await readJson(join(root, 'foundocs.json'));
270
+ return binding?.workspace_id === workspaceId && uuid.test(binding.project_id) ? binding.project_id : null;
271
+ } catch { return null; }
272
+ }
273
+
274
+ export async function globalCommand(command, argv) {
275
+ if (command === 'install-global') {
276
+ if (argv.length || process.stdin.isTTY) fail('Provide the installation JSON on private stdin.');
277
+ let input = '';
278
+ for await (const chunk of process.stdin) { input += chunk; if (Buffer.byteLength(input) > 16384) fail('Installation input is too large.'); }
279
+ return installGlobal(JSON.parse(input));
280
+ }
281
+ const action = command === 'mcp-global' ? null : argv.shift();
282
+ const options = Object.fromEntries(['client', 'workspace', 'root', 'name', 'id', 'replace', 'storage'].map(key => [key, { type: 'string' }]));
283
+ const { values } = parseArgs({ args: argv, options });
284
+ if (command === 'project') return bindProject(action, values);
285
+ const dir = globalDirectory(values.storage);
286
+ const path = registryPath(dir, values.client);
287
+ await privateDirectory(dir);
288
+ const registry = await readJson(path);
289
+ if (command === 'workspace' && action === 'list') return { defaultId: registry?.defaultId, workspaces: (registry?.workspaces ?? []).map(({ id, name }) => ({ id, name, server: serverName(id) })) };
290
+ if (command === 'workspace' && action === 'update') {
291
+ return withLock(dir, async () => {
292
+ const registered = (await readJson(path))?.workspaces ?? [];
293
+ for (const ws of registered) {
294
+ const update = await prepareHost({ client: values.client, workspaceId: ws.id }, dir);
295
+ await update();
296
+ }
297
+ return { status: 'updated', workspaces: registered.length, version };
298
+ });
299
+ }
300
+ if (command === 'workspace' && action === 'default') {
301
+ if (!values.workspace) fail('Choose --workspace NAME_OR_ID.');
302
+ return withLock(dir, async () => {
303
+ const current = await readJson(path);
304
+ const selected = selectWorkspace(current, values.workspace);
305
+ current.defaultId = selected.id;
306
+ await atomicWrite(path, json(current));
307
+ return { defaultId: current.defaultId };
308
+ });
309
+ }
310
+ if (command !== 'mcp-global' || !uuid.test(values.workspace)) fail('Unknown workspace operation.');
311
+ const ws = selectWorkspace(registry, values.workspace);
312
+ const { runBridge } = await import('./bridge.mjs');
313
+ await runBridge({ credentialPath: keyPath(dir, values.client, ws), projectId: null, workspaceId: ws.id, mcpUrl: ws.mcpUrl, folderProject: server => folderProject(server, ws.id) });
314
+ }
package/src/setup.mjs CHANGED
@@ -115,7 +115,7 @@ export function parseJson(text, path) {
115
115
  return value;
116
116
  }
117
117
 
118
- async function canonicalRoot(root) {
118
+ export async function canonicalRoot(root) {
119
119
  if (!isAbsolute(root)) fail('preflight', '--root must be an absolute project directory.');
120
120
  let canonical;
121
121
  try { canonical = await realpath(root); if (!(await lstat(canonical)).isDirectory()) throw new Error(); }
@@ -124,14 +124,14 @@ async function canonicalRoot(root) {
124
124
  return canonical;
125
125
  }
126
126
 
127
- async function checkGitRoot(root) {
127
+ export async function checkGitRoot(root) {
128
128
  let reported;
129
129
  try { reported = (await exec('git', ['-C', root, 'rev-parse', '--show-toplevel'], { timeout: 5000 })).stdout.trim(); }
130
130
  catch { return; } // Git is optional for a plain project directory.
131
131
  if (await realpath(reported) !== root) fail('preflight', 'The selected root differs from the Git root. Confirm the governing project root; use the manual guide for an intentionally nested project.', { root, gitRoot: reported });
132
132
  }
133
133
 
134
- async function safeParent(root, path) {
134
+ export async function safeParent(root, path) {
135
135
  const rel = relative(root, path);
136
136
  if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) fail('preflight', 'Configuration is outside the project root.');
137
137
  let current = root;
@@ -156,7 +156,7 @@ export async function storageBase(options, root) {
156
156
  return existing[0] ?? current;
157
157
  }
158
158
 
159
- async function privateDirectory(path) {
159
+ export async function privateDirectory(path) {
160
160
  // Reject symlink ancestors before creating or reading credentials.
161
161
  let current = path;
162
162
  while (dirname(current) !== current) {
@@ -175,7 +175,7 @@ async function privateDirectory(path) {
175
175
  if ((stat.mode & 0o077) || (typeof process.getuid === 'function' && stat.uid !== process.getuid())) fail('preflight', 'Private storage is not owned exclusively by the current user.');
176
176
  }
177
177
 
178
- async function atomicWrite(path, content, mode = 0o600) {
178
+ export async function atomicWrite(path, content, mode = 0o600) {
179
179
  const temporary = `${path}.${randomUUID()}.tmp`;
180
180
  let handle;
181
181
  try {
@@ -480,13 +480,13 @@ export async function plan(root, input, credentialPath, helperPath, { oldFormat
480
480
  }
481
481
 
482
482
  function recovery(input) {
483
- return { attemptId: input.attemptId, recoveryUrl: `/app/projects/${input.projectId}/agents`, recovery: 'Open this project’s integration guide, inspect this attempt, revoke only its installation key if issued, then copy a newly issued code. Lost key plaintext cannot be recovered.' };
483
+ return { attemptId: input.attemptId, ...(input.projectId ? { recoveryUrl: `/app/projects/${input.projectId}/agents` } : {}), recovery: 'Open this project’s integration guide, inspect this attempt, revoke only its installation key if issued, then copy a newly issued code. Lost key plaintext cannot be recovered.' };
484
484
  }
485
485
 
486
- async function exchange(input, fetcher) {
486
+ export async function exchange(input, fetcher) {
487
487
  let response;
488
488
  try {
489
- response = await fetcher(input.exchangeUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ attemptId: input.attemptId, projectId: input.projectId, code: input.code }), redirect: 'error', signal: AbortSignal.timeout(20000) });
489
+ response = await fetcher(input.exchangeUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ attemptId: input.attemptId, projectId: input.projectId, ...(input.projectId === null ? { workspaceId: input.workspaceId } : {}), code: input.code }), redirect: 'error', signal: AbortSignal.timeout(20000) });
490
490
  } catch { fail('exchange', 'Code exchange did not return a usable response. The code may have been consumed; do not retry blindly.', recovery(input)); }
491
491
  if (!response.ok) fail('exchange', `Code exchange was rejected (HTTP ${response.status}). Request a new code if expired, cancelled or consumed.`, recovery(input));
492
492
  let result;
@@ -527,7 +527,7 @@ async function runtime() {
527
527
  if (major < 22 || (major === 22 && minor < 19)) fail('preflight', 'Node.js 22.19.0 or newer is required. No code was exchanged.');
528
528
  }
529
529
 
530
- async function withLock(directory, operation) {
530
+ export async function withLock(directory, operation) {
531
531
  const path = join(directory, 'operation.lock');
532
532
  let handle;
533
533
  try { handle = await open(path, 'wx', 0o600); }
@@ -0,0 +1,5 @@
1
+ # Global installation project selection
2
+
3
+ For an explicit create or connect request follow the workspace skill before making project MCP calls. For ordinary work use the current governing project root supplied by the host, or its Git checkout root when working in a subdirectory. In a plain folder use its explicitly selected root. Read that root’s exact `foundocs.json`, including when there is no AGENTS.md. Stop on malformed configuration, missing binding, or an inaccessible project.
4
+
5
+ A global binding has UUID fields `workspace_id` and `project_id`. Use the MCP server for that exact registered workspace, found through the workspace skill’s `workspace list` command. Pass the file’s project ID explicitly to each tool. Check the binding again after a folder or project switch. Use the project-local instructions for project-scoped installations. Never scan other checkouts, borrow a default project, or expose a credential.
@@ -0,0 +1,19 @@
1
+ ---
2
+ name: foundocs-workspace
3
+ description: Use when the user explicitly asks to create or link a Foundocs project or manage a Foundocs workspace. For ordinary work, use only when the current project context already identifies a Foundocs binding. An unlinked folder needs no Foundocs lookup, capture, or setup prompt.
4
+ ---
5
+
6
+ # Foundocs workspace
7
+
8
+ For ordinary chat or coding, stay silent when the governing folder has no valid `foundocs.json`. Do not search the filesystem for a binding during unrelated chat, call Foundocs tools, list workspaces, load the guides, ask for configuration, or suggest installing it. A registered global workspace alone never activates document lookup or capture. Explicit Foundocs creation and linking requests below work from an unlinked folder.
9
+
10
+ Use the selected {{CLIENT}} installation. Run the pinned CLI as an argument array with prefix `npx --yes @foundocs/foundocs-setup@{{VERSION}}`. Append `--client {{CLIENT}}` and the two arguments `--storage` and {{STORAGE}} to the commands below. Treat names and folder paths as literal arguments.
11
+
12
+ - On an explicit request to create a project, run `project create --root ABSOLUTE_PROJECT_ROOT`. Use the current governing project root. The folder name is the default. Pass `--name NAME` when requested.
13
+ - To connect an existing project, run `project link --root ABSOLUTE_PROJECT_ROOT --name NAME`, or use `--id UUID` when the web guide supplied an ID. Pass `--workspace ID_OR_NAME` for an explicitly named workspace; otherwise use the registered default. On ambiguous matches show names and IDs and ask which one to use. On no match, check the name.
14
+ - On a switch confirmation show both targets and wait for the user's decision. Once confirmed, repeat the same command with `--replace OLD_PROJECT_ID`. Retry interrupted creation with the same root and name.
15
+ - `workspace list` shows registered workspaces. Use `workspace default --workspace ID_OR_NAME` only when asked to change the default.
16
+ - A `project_installation` result means the folder has a separate project-scoped install. Show the previous project and requested target. Only after explicit approval to remove that installation, run its existing `rollback --root ABSOLUTE_PROJECT_ROOT` workflow. Proceed with the requested global link when rollback succeeds and the folder is clear. If rollback reports conflicts or restores an older binding, preserve it and report the conflict.
17
+ - After binding, use the MCP server named in the CLI result. Call `get_project_context` for the exact project ID and report the workspace and project names. If the host cached an empty tool list before binding, reopen the chat in the linked folder; distinguish a saved folder binding from host verification.
18
+ - For ordinary Foundocs work, use the exact governing project’s `foundocs.json`. A global binding contains `workspace_id` and `project_id`. Use this workspace's MCP server (use the server name returned by `workspace list` for that exact workspace ID). Use the project’s existing instructions and MCP connection when it has its own installation. Never guess a binding in an unlinked folder.
19
+ - Once bound, read the appropriate guide under {{GUIDES}}: `foundocs/SKILL.md`, `foundocs-capture-knowledge/SKILL.md`, or `foundocs-capture-episode/SKILL.md` for the requested activity. For a global binding the explicit workspace and project in the governing folder are the configuration. Global setup installs no project-scoped update or checkpoint hooks. The private bootstrap CLI handles workspace registration and linking before any project is selected.