@foundocs/foundocs-setup 0.3.29 → 0.4.0

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:
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 {
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.0",
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": "Install a workspace once in Codex or Claude Code and create or link projects from new 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/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 --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,236 @@
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 { homedir } from 'node:os';
5
+ import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path';
6
+ import { isDeepStrictEqual, parseArgs, promisify } from 'node:util';
7
+ import { parse as parseToml } from 'smol-toml';
8
+ import { readCredential } from './auth.mjs';
9
+ import { skillAssets } from './skill-assets.mjs';
10
+ import { SetupError, atomicWrite, canonicalRoot, checkGitRoot, exchange, parseJson, privateDirectory, safeParent, textFile, validateUrl, withLock } from './setup.mjs';
11
+
12
+ const version = JSON.parse(await readFile(new URL('../package.json', import.meta.url))).version;
13
+ 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;
14
+ const digest = value => createHash('sha256').update(value).digest('hex');
15
+ const json = value => JSON.stringify(value, null, 2) + '\n';
16
+ const fail = message => { throw new SetupError('global', message); };
17
+ const serverName = id => 'foundocs_' + digest(id).slice(0, 12);
18
+ const execute = promisify(execFile);
19
+
20
+ function contains(parent, child) {
21
+ const path = relative(parent, child);
22
+ return path !== '..' && !path.startsWith('..' + sep) && !isAbsolute(path);
23
+ }
24
+
25
+ function globalDirectory(storage) {
26
+ const base = storage ?? process.env.FOUNDOCS_SETUP_HOME ?? join(homedir(), '.local', 'share', 'foundocs', 'setup');
27
+ if (!isAbsolute(base)) fail('Use an absolute private storage location.');
28
+ return join(base, 'global');
29
+ }
30
+
31
+ async function readJson(path) {
32
+ const text = await textFile(path);
33
+ return text === null ? null : parseJson(text, path);
34
+ }
35
+
36
+ function registryPath(dir, client) {
37
+ if (!['codex', 'claude'].includes(client)) fail('Choose --client codex or claude.');
38
+ return join(dir, client + '.json');
39
+ }
40
+
41
+ function selectWorkspace(registry, target) {
42
+ const id = target ?? registry?.defaultId;
43
+ const workspaces = registry?.workspaces ?? [];
44
+ const exactId = workspaces.find(item => item.id === id);
45
+ if (exactId) return exactId;
46
+ const matches = workspaces.filter(item => item.name === id);
47
+ if (matches.length === 1) return matches[0];
48
+ 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 })) });
49
+ }
50
+
51
+ function keyPath(dir, client, workspace) {
52
+ if (!uuid.test(workspace.id) || !uuid.test(workspace.attemptId)) fail('Invalid private installation record.');
53
+ return join(dir, client + '-' + workspace.id + '-' + workspace.attemptId + '.json');
54
+ }
55
+
56
+ async function requestProjects(dir, client, ws, input, fetcher = fetch) {
57
+ const url = new URL('/api/setup/workspaces/' + ws.id + '/projects', validateUrl(ws.exchangeUrl));
58
+ const key = await readCredential(keyPath(dir, client, ws), null, ws.id);
59
+ const response = await fetcher(url, { method: input ? 'POST' : 'GET', redirect: 'error', signal: AbortSignal.timeout(20000),
60
+ headers: { Authorization: 'Bearer ' + key, 'Content-Type': 'application/json' }, body: input && JSON.stringify(input) });
61
+ const body = await response.json();
62
+ if (!response.ok) throw new SetupError('workspace', 'Workspace request failed (HTTP ' + response.status + '). Check access, plan limits and workspace registration.', { code: body.error?.code });
63
+ return body;
64
+ }
65
+
66
+ async function prepareHost(input, dir) {
67
+ const { client, workspaceId } = input;
68
+ const home = homedir();
69
+ const configHome = client === 'codex' ? process.env.CODEX_HOME ?? join(home, '.codex') : process.env.CLAUDE_CONFIG_DIR ?? join(home, '.claude');
70
+ if (!isAbsolute(configHome)) fail('Client configuration must have an absolute location.');
71
+ const name = serverName(workspaceId);
72
+ const args = ['--yes', '@foundocs/foundocs-setup@' + version, 'mcp-global', '--client', client, '--workspace', workspaceId, '--storage', dirname(dir)];
73
+ const configPath = client === 'codex' ? join(configHome, 'config.toml') : process.env.CLAUDE_CONFIG_DIR ? join(configHome, '.claude.json') : join(home, '.claude.json');
74
+ const current = await textFile(configPath);
75
+ const configured = client === 'codex' ? parseToml(current ?? '').mcp_servers?.[name] : JSON.parse(current ?? '{}').mcpServers?.[name];
76
+ if (configured && (configured.command !== 'npx' || !isDeepStrictEqual(configured.args, args) ||
77
+ Object.keys(configured).some(key => !['command', 'args', 'type'].includes(key)) || (configured.type && configured.type !== 'stdio'))) fail('Conflicting user MCP entry: ' + name);
78
+ await execute(client, ['--version'], { cwd: dir, timeout: 15000 });
79
+ const skillRoot = join(configHome, 'skills', 'foundocs-workspace');
80
+ const source = await readFile(new URL('../templates/workspace-skill.md', import.meta.url), 'utf8');
81
+ const files = [{ name: 'SKILL.md', content: source.replaceAll('{{CLIENT}}', client).replaceAll('{{VERSION}}', version).replaceAll('{{STORAGE}}', JSON.stringify(dirname(dir))) }];
82
+ for (const asset of skillAssets(client)) {
83
+ const name = asset.name.split('/skills/')[1];
84
+ const content = name === 'foundocs/references/configuration.md'
85
+ ? await readFile(new URL('../templates/workspace-configuration.md', import.meta.url), 'utf8')
86
+ : asset.content;
87
+ files.push({ name, content });
88
+ }
89
+ const changes = [];
90
+ for (const file of files) {
91
+ const path = join(skillRoot, file.name);
92
+ await safeParent(dirname(configHome), path);
93
+ const before = await textFile(path);
94
+ if (before === file.content) continue;
95
+ if (before !== null) fail('A different global skill file already exists at ' + path);
96
+ changes.push({ path, content: file.content });
97
+ }
98
+ return async () => {
99
+ for (const { path, content } of changes) {
100
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
101
+ if (await textFile(path) !== null) fail('Global skill changed during installation.');
102
+ await atomicWrite(path, content);
103
+ }
104
+ if (!configured) {
105
+ if (await textFile(configPath) !== current) fail('Client configuration changed. Rerun the same installation.');
106
+ const command = client === 'codex' ? ['mcp', 'add', name, '--', 'npx', ...args] :
107
+ ['mcp', 'add-json', '--scope', 'user', name, JSON.stringify({ type: 'stdio', command: 'npx', args })];
108
+ await execute(client, command, { cwd: dir, timeout: 20000 });
109
+ }
110
+ };
111
+ }
112
+
113
+ export async function installGlobal(input, options = {}) {
114
+ if (input?.version !== 2 || input.projectId !== null || !uuid.test(input.workspaceId) || !uuid.test(input.attemptId) ||
115
+ 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.');
116
+ validateUrl(input.exchangeUrl); validateUrl(input.mcpUrl);
117
+ const dir = globalDirectory(options.storage);
118
+ const path = registryPath(dir, input.client);
119
+ await privateDirectory(dir);
120
+ return withLock(dir, async () => {
121
+ const ws = { id: input.workspaceId, name: input.workspaceName, attemptId: input.attemptId, exchangeUrl: input.exchangeUrl, mcpUrl: input.mcpUrl };
122
+ const registry = await readJson(path) ?? { defaultId: ws.id, workspaces: [] };
123
+ const finishHost = await (options.prepareHost ?? prepareHost)(input, dir);
124
+ const credential = keyPath(dir, input.client, ws);
125
+ const saved = await readJson(credential);
126
+ if (!saved) await atomicWrite(credential, json({ ...await exchange(input, options.fetch ?? fetch), exchangeUrl: ws.exchangeUrl }));
127
+ else if (saved.attemptId !== ws.attemptId || saved.workspaceId !== ws.id || saved.mcpUrl !== ws.mcpUrl || saved.exchangeUrl !== ws.exchangeUrl) fail('Installation identity changed.');
128
+ const catalog = await requestProjects(dir, input.client, ws, undefined, options.fetch);
129
+ if (catalog.workspace?.id !== ws.id) fail('Workspace identity mismatch.');
130
+ ws.name = catalog.workspace.name;
131
+ await finishHost();
132
+ registry.workspaces = [...registry.workspaces.filter(item => item.id !== ws.id), ws];
133
+ await atomicWrite(path, json(registry));
134
+ 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.' };
135
+ });
136
+ }
137
+
138
+ function verifyCatalog(catalog, ws) {
139
+ 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.');
140
+ }
141
+
142
+ export async function bindProject(action, args, options = {}) {
143
+ if (!['create', 'link'].includes(action)) fail('Use project create or project link.');
144
+ if (args.id && (!uuid.test(args.id) || args.name || action !== 'link')) fail('Select an existing project by ID or by name.');
145
+ const root = await canonicalRoot(args.root ?? '');
146
+ await checkGitRoot(root);
147
+ const dir = globalDirectory(args.storage);
148
+ if (contains(root, dir) || contains(dir, root)) fail('Choose a project folder separate from private storage.');
149
+ const path = registryPath(dir, args.client);
150
+ await privateDirectory(dir);
151
+ return withLock(dir, async () => {
152
+ const ws = selectWorkspace(await readJson(path), args.workspace);
153
+ const configPath = join(root, 'foundocs.json');
154
+ if (await textFile(join(root, 'steerdocs.json')) !== null) fail('Migrate the existing historical project installation before binding this folder.');
155
+ const previous = await textFile(configPath);
156
+ const binding = previous === null ? null : parseJson(previous, configPath);
157
+ if (binding && !uuid.test(binding.project_id)) fail('Invalid existing foundocs.json.');
158
+ const catalog = await requestProjects(dir, args.client, ws, undefined, options.fetch);
159
+ verifyCatalog(catalog, ws);
160
+ const name = (args.name ?? basename(root)).trim();
161
+ if (!name || [...name].length > 80) fail('Provide a project name of 1–80 characters.');
162
+ let project;
163
+ if (action === 'link') {
164
+ const matches = catalog.projects.filter(item => args.id ? item.id === args.id : item.name === name);
165
+ if (matches.length !== 1) throw new SetupError('selection', matches.length ? 'Choose one project by ID.' : 'No project matches that name or ID.', { candidates: matches });
166
+ project = matches[0];
167
+ }
168
+ const journal = join(dir, 'bind-' + digest(root) + '.json');
169
+ let pending = await readJson(journal);
170
+ if (pending?.createdId && pending.createdId === binding?.project_id && pending.workspaceId === binding.workspace_id) {
171
+ await unlink(journal);
172
+ pending = null;
173
+ }
174
+ if (pending && (action !== 'create' || pending.workspaceId !== ws.id || pending.client !== args.client || pending.name !== name || pending.previous !== previous)) {
175
+ throw new SetupError('recovery', 'Resume the interrupted project creation with its original target.', { workspaceId: pending.workspaceId, name: pending.name, client: pending.client });
176
+ }
177
+ if (binding) {
178
+ const current = catalog.projects.find(item => item.id === binding.project_id);
179
+ if (current && (!binding.workspace_id || binding.workspace_id === ws.id) && (current.id === project?.id || (action === 'create' && current.name === name))) {
180
+ return { status: 'already_linked', workspace: catalog.workspace, project: current, server: serverName(ws.id) };
181
+ }
182
+ 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.', {
183
+ previous: { projectId: binding.project_id }, target: { workspace: catalog.workspace, project: project ?? { name } },
184
+ });
185
+ 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 } } });
186
+ } else if (args.replace) fail('The previous folder binding changed; recheck the target.');
187
+ if (action === 'create') {
188
+ if (!pending) {
189
+ pending = { workspaceId: ws.id, client: args.client, name, previous, requestId: randomUUID() };
190
+ await atomicWrite(journal, json(pending));
191
+ }
192
+ const result = await requestProjects(dir, args.client, ws, { name, requestId: pending.requestId }, options.fetch);
193
+ project = result.workspace?.project;
194
+ if (result.workspace?.id !== ws.id || !uuid.test(project?.id) || project.name !== name) fail('Unexpected created project identity. Retry with the same target.');
195
+ pending.createdId = project.id;
196
+ await atomicWrite(journal, json(pending));
197
+ }
198
+ if (await textFile(configPath) !== previous) fail('The folder binding changed during this request. Review it before retrying.');
199
+ const mode = previous === null ? 0o644 : (await lstat(configPath)).mode & 0o777;
200
+ await atomicWrite(configPath, json({ ...binding, workspace_id: ws.id, project_id: project.id }), mode);
201
+ if (pending) await unlink(journal);
202
+ return { status: 'linked', workspace: catalog.workspace, project: { id: project.id, name: project.name }, server: serverName(ws.id) };
203
+ });
204
+ }
205
+
206
+ export async function globalCommand(command, argv) {
207
+ if (command === 'install-global') {
208
+ if (argv.length || process.stdin.isTTY) fail('Provide the installation JSON on private stdin.');
209
+ let input = '';
210
+ for await (const chunk of process.stdin) { input += chunk; if (Buffer.byteLength(input) > 16384) fail('Installation input is too large.'); }
211
+ return installGlobal(JSON.parse(input));
212
+ }
213
+ const action = command === 'mcp-global' ? null : argv.shift();
214
+ const options = Object.fromEntries(['client', 'workspace', 'root', 'name', 'id', 'replace', 'storage'].map(key => [key, { type: 'string' }]));
215
+ const { values } = parseArgs({ args: argv, options });
216
+ if (command === 'project') return bindProject(action, values);
217
+ const dir = globalDirectory(values.storage);
218
+ const path = registryPath(dir, values.client);
219
+ await privateDirectory(dir);
220
+ const registry = await readJson(path);
221
+ if (command === 'workspace' && action === 'list') return { defaultId: registry?.defaultId, workspaces: (registry?.workspaces ?? []).map(({ id, name }) => ({ id, name, server: serverName(id) })) };
222
+ if (command === 'workspace' && action === 'default') {
223
+ if (!values.workspace) fail('Choose --workspace NAME_OR_ID.');
224
+ return withLock(dir, async () => {
225
+ const current = await readJson(path);
226
+ const selected = selectWorkspace(current, values.workspace);
227
+ current.defaultId = selected.id;
228
+ await atomicWrite(path, json(current));
229
+ return { defaultId: current.defaultId };
230
+ });
231
+ }
232
+ if (command !== 'mcp-global' || !uuid.test(values.workspace)) fail('Unknown workspace operation.');
233
+ const ws = selectWorkspace(registry, values.workspace);
234
+ const { runBridge } = await import('./bridge.mjs');
235
+ await runBridge({ credentialPath: keyPath(dir, values.client, ws), projectId: null, workspaceId: ws.id, mcpUrl: ws.mcpUrl });
236
+ }
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,17 @@
1
+ ---
2
+ name: foundocs-workspace
3
+ description: Connect a folder to Foundocs, create a Foundocs project, select a registered workspace, or use Foundocs documents and knowledge in a globally linked folder. Use for “Foundocs 프로젝트 생성하자”, “프로젝트로 연결”, and explicit Foundocs requests. For ordinary work, use the document and capture guidance only in a Foundocs-bound project.
4
+ ---
5
+
6
+ # Foundocs workspace
7
+
8
+ 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.
9
+
10
+ - 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.
11
+ - 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.
12
+ - 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.
13
+ - `workspace list` shows registered workspaces. Use `workspace default --workspace ID_OR_NAME` only when asked to change the default.
14
+ - 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.
15
+ - 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 server has just been installed and is unavailable, ask the user to reload the host; distinguish a saved folder binding from host verification.
16
+ - 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.
17
+ - Once bound, follow [Foundocs](foundocs/SKILL.md), [knowledge capture](foundocs-capture-knowledge/SKILL.md), and [episode capture](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.