@foundocs/foundocs-setup 0.3.9 → 0.3.11

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
@@ -117,9 +117,11 @@ Dreaming adversarial fixtures and trace checks live in `eval/`; see `eval/README
117
117
 
118
118
  The bundled capture skill reuses existing topic folders beneath the fixed `knowledge/rules/`, `knowledge/learnings/` and `knowledge/decisions/` roots. Nested topic folders and files directly under a root are both valid. Related facts stay together rather than becoming fragments or duplicate shallow folders. Verified, reusable lessons from correcting the agent’s own mistakes are captured in the same turn; typo-only and unverified fixes are excluded.
119
119
 
120
- Dreaming inspects dispersed knowledge and similar folders within its existing six stages. Only a server-verified path-only update within the same category may be applied automatically: body, title, TL;DR, ordered tags, creation date and other metadata must stay unchanged. Semantic, category and mixed changes retain owner review. Older servers without explicit automatic-move support receive review candidates. Prior moves and proposal history guide deduplication so repeated runs avoid cosmetic renames.
120
+ Dreaming inspects dispersed knowledge and similar folders within its existing six stages. Consolidation compares concrete topic groups, destination folders and retrieval benefits, including files still directly under a category root. Clear filenames alone do not justify skipping that assessment; justified moves are submitted, while a zero-move result records why the candidate groups should stay in place. The review avoids fragmentation and cosmetic churn rather than requiring a move quota.
121
121
 
122
- The skills explain stable IDs, previous-path aliases, relative-link bases, move receipts and versioned requests. Ordinary move undo uses the discovered `get_content_moves` / `undo_content_move` tools on explicit request; a Dreaming move returns to the exact saved proposal’s owner review for `revert`. New server tools are discovered dynamically. This release updates guidance, not an older server’s capabilities, and existing installed skills still require the consent-based update flow.
122
+ Only a server-verified path-only update within the same category may be applied automatically: body, title, TL;DR, ordered tags, creation date and other metadata must stay unchanged. Semantic, category and mixed changes retain owner review. Older servers without explicit automatic-move support receive review candidates. Prior moves and proposal history guide deduplication so repeated runs avoid cosmetic renames.
123
+
124
+ The skills explain stable IDs, previous-path aliases, relative-link bases, move receipts and versioned requests. Ordinary move undo uses the discovered `get_content_moves` / `undo_content_move` tools on explicit request; a Dreaming move returns to the exact saved proposal’s owner review for `revert`. New server tools are discovered dynamically. This release updates guidance, not an older server’s capabilities. Existing installations receive the guidance through `update-skills` or their enabled SessionStart update hook.
123
125
 
124
126
  ## Session discovery
125
127
 
package/dist/bridge.mjs CHANGED
@@ -36133,6 +36133,53 @@ if (process.argv[1] && process.argv[2] === "--headers" && import.meta.url === pa
36133
36133
  // src/bridge.mjs
36134
36134
  import { pathToFileURL as pathToFileURL2 } from "node:url";
36135
36135
  import { resolve as resolve2 } from "node:path";
36136
+ function requestError(error2, name) {
36137
+ const tool = typeof name === "string" && /^[a-z][a-z0-9_]{0,63}$/i.test(name) ? name : void 0;
36138
+ let code = "REQUEST_FAILED", retryable = false, message = "The MCP request failed. Run foundocs-setup doctor for connection diagnostics.";
36139
+ let httpStatus, remoteCode;
36140
+ const schemaError = error2 instanceof ProtocolError3 && (error2.code === ProtocolErrorCode2.InvalidParams && (error2.message.startsWith("Structured content does not match the tool's output schema:") || error2.message.startsWith("Failed to validate structured content:") || /^Tool '[^']+' has an invalid outputSchema:/.test(error2.message)) || error2.code === ProtocolErrorCode2.InvalidRequest && /^Tool .+ has an output schema but did not return structured content$/.test(error2.message));
36141
+ if (schemaError) {
36142
+ code = "OUTPUT_VALIDATION_ERROR";
36143
+ message = "The server response does not match the advertised tool output schema. Update the server tool contract; changing credentials will not fix this error.";
36144
+ } else if (error2 instanceof SdkHttpError || error2 instanceof UnauthorizedError) {
36145
+ httpStatus = error2 instanceof UnauthorizedError ? 401 : error2.status;
36146
+ if (httpStatus === 401) {
36147
+ code = "UNAUTHENTICATED";
36148
+ message = "Authentication failed (HTTP 401). Run foundocs-setup doctor and check the configured workspace key.";
36149
+ } else if (httpStatus === 403) {
36150
+ code = "FORBIDDEN";
36151
+ message = "Access was denied (HTTP 403). Check the workspace key permissions for this project.";
36152
+ } else if (httpStatus === 429) {
36153
+ code = "RATE_LIMITED";
36154
+ retryable = true;
36155
+ message = "The server rate limit was reached (HTTP 429). Wait before retrying.";
36156
+ } else {
36157
+ code = "REMOTE_HTTP_ERROR";
36158
+ retryable = httpStatus >= 500;
36159
+ message = `The remote MCP server returned HTTP ${httpStatus}. Check the server status.`;
36160
+ }
36161
+ } else if (error2 instanceof SdkError && error2.code === SdkErrorCode.RequestTimeout) {
36162
+ code = "REQUEST_TIMEOUT";
36163
+ retryable = true;
36164
+ message = "The remote MCP request timed out.";
36165
+ } else if (error2 instanceof SdkError && [SdkErrorCode.InvalidResult, SdkErrorCode.UnsupportedResultType].includes(error2.code)) {
36166
+ code = "INVALID_REMOTE_RESPONSE";
36167
+ message = "The remote MCP response is malformed. Check the server protocol and response schema.";
36168
+ } else if (error2 instanceof SdkError && [SdkErrorCode.NotConnected, SdkErrorCode.ConnectionClosed, SdkErrorCode.SendFailed].includes(error2.code) || error2 instanceof TypeError && error2.message === "fetch failed" || ["AbortError", "TimeoutError"].includes(error2?.name)) {
36169
+ code = "CONNECTION_ERROR";
36170
+ retryable = true;
36171
+ message = "The remote MCP connection failed or was interrupted. Check connectivity and the server status.";
36172
+ } else if (error2 instanceof ProtocolError3) {
36173
+ code = "REMOTE_PROTOCOL_ERROR";
36174
+ remoteCode = error2.code;
36175
+ message = "The remote MCP server returned a protocol error. Check the requested tool and arguments.";
36176
+ }
36177
+ return new ProtocolError3(
36178
+ ProtocolErrorCode2.InternalError,
36179
+ `Foundocs ${tool ?? "request"} [${code}]: ${message} Writes may already have succeeded; retry only with the same requestId and input.`,
36180
+ { code, retryable, ...tool ? { tool } : {}, ...httpStatus !== void 0 ? { httpStatus } : {}, ...remoteCode !== void 0 ? { remoteCode } : {} }
36181
+ );
36182
+ }
36136
36183
  async function runBridge({ credentialPath, projectId, workspaceId, mcpUrl: endpoint }) {
36137
36184
  let remote, local;
36138
36185
  async function close() {
@@ -36158,16 +36205,16 @@ async function runBridge({ credentialPath, projectId, workspaceId, mcpUrl: endpo
36158
36205
  local.setRequestHandler("tools/list", async (request) => {
36159
36206
  try {
36160
36207
  return await remote.listTools(request.params);
36161
- } catch {
36162
- throw new ProtocolError3(ProtocolErrorCode2.InternalError, "Foundocs tool discovery failed. Run foundocs-setup doctor.");
36208
+ } catch (error2) {
36209
+ throw requestError(error2, "tools_list");
36163
36210
  }
36164
36211
  });
36165
36212
  local.setRequestHandler("tools/call", async (request) => {
36166
36213
  if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(request.params.arguments?.project_id)) throw new ProtocolError3(ProtocolErrorCode2.InvalidParams, "Read and pass the explicit project_id from the governing foundocs.json.");
36167
36214
  try {
36168
36215
  return await remote.callTool(request.params);
36169
- } catch {
36170
- throw new ProtocolError3(ProtocolErrorCode2.InternalError, "Foundocs request failed. Check authentication and connectivity. Retry writes only with the same requestId and input.");
36216
+ } catch (error2) {
36217
+ throw requestError(error2, request.params.name);
36171
36218
  }
36172
36219
  });
36173
36220
  local.onerror = () => process.stderr.write("Foundocs local MCP transport error.\n");
@@ -36179,8 +36226,9 @@ async function runBridge({ credentialPath, projectId, workspaceId, mcpUrl: endpo
36179
36226
  void close().finally(() => process.exit(0));
36180
36227
  });
36181
36228
  await local.connect(new StdioServerTransport());
36182
- } catch {
36183
- process.stderr.write("Foundocs authentication bridge unavailable. Run foundocs-setup doctor.\n");
36229
+ } catch (error2) {
36230
+ process.stderr.write(`Foundocs MCP bridge unavailable. ${requestError(error2, "initialize").message}
36231
+ `);
36184
36232
  await close();
36185
36233
  process.exitCode = 1;
36186
36234
  }
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@foundocs/foundocs-setup",
3
- "version": "0.3.9",
3
+ "version": "0.3.11",
4
4
  "description": "Repeatable project setup and agent skills for the Foundocs remote MCP server",
5
5
  "foundocsRelease": {
6
- "summary": "Automatically update Foundocs skills on Codex and Claude Code session start; preserve local edits, existing hooks, MCP settings and credentials, with bounded non-blocking checks."
6
+ "summary": "Assess concrete Dreaming topic groups and retrieval benefits before skipping folder organization; submit justified path-only moves and explain valid zero-move outcomes."
7
7
  },
8
8
  "type": "module",
9
9
  "bin": {
@@ -38,3 +38,5 @@ On an explicit Dreaming request, read [the Dreaming protocol](references/dreamin
38
38
  Dreaming analyzes this project's knowledge, including dispersed or similar topical folders under the fixed `rules`, `learnings` and `decisions` roots. Documents and change events are read-only evidence. Only server-permitted exact duplicate representative links, non-authoritative related_to links and same-category path-only knowledge moves can be applied automatically. The server must verify that all non-path content and metadata remain unchanged; semantic, category or mixed changes require owner review. Inspect current capabilities rather than assuming an older server supports automatic moves. Never approve proposals yourself, permanently delete memories, or rewrite project instructions and tools.
39
39
 
40
40
  Persist progress and report server-confirmed results in the user's language. Analysis can finish with review still pending. A blocked, interrupted, or partly inspected run must not be presented as a successful full review.
41
+
42
+ Include a concrete folder-organization assessment in consolidation; follow the protocol's folder review criteria before concluding that no moves are useful. Valid root-level paths alone do not settle that assessment.
@@ -7,3 +7,9 @@ Read that exact file and validate a JSON object with a UUID project_id. Pass tha
7
7
  If that exact file is missing, malformed, or lacks a valid project_id, stop all Foundocs calls and ask for corrected configuration. A failed read does not change which AGENTS.md governs the task: never reinterpret the root, search for another configuration file, or try a relative-path or shell fallback. If the project is inaccessible, stop and ask; never guess another project. A client without local file access must ask the user for an explicit project_id.
8
8
 
9
9
  Use the existing MCP connection and private authentication helper. FOUNDOCS_API_KEY is a supported scoped process-environment alternative. Never read, print, commit or copy credentials into reports, memories, prompts, AGENTS.md or the project configuration.
10
+
11
+ ## Tool response errors
12
+
13
+ `OUTPUT_VALIDATION_ERROR` means a tool response does not match its advertised output schema; `INVALID_REMOTE_RESPONSE` means the MCP result is malformed. Check the server tool contract and runtime version. These errors do not establish an authentication failure: do not rotate keys, switch projects or repeat unchanged requests as a remedy. Another read tool in the same configured project may still work. Authentication (`UNAUTHENTICATED`), authorization (`FORBIDDEN`) and project-configuration errors still follow the stop rules above. Never bypass a denial with another tool or key.
14
+
15
+ The bridge reports safe error categories and tool names without forwarding raw response bodies, credentials or provider error data. A failed write response can follow a successful mutation; any identical retry must preserve the original requestId and input.
@@ -27,13 +27,22 @@ To read a complete proposal, use get_dream `{project_id, runId, changeId, offset
27
27
 
28
28
  Use these 1-based numbers when explaining stages or reporting progress. The server retains stable API IDs for existing runs: display stages 1, 2, 3, 4, 5, 6 map to API IDs 3, 4, 5, 6, 7, 8 respectively. Use the API IDs in checkpoint `stage` and candidate `stages`; preserve IDs from saved runs.
29
29
 
30
- - **1 — Memory Consolidation:** Distinguish byte-identical, same-scope duplicates from similar assertions. Find related knowledge dispersed across topical folders and propose placing it in an existing suitable folder within its category. Direct-root files are valid; nesting is useful only when it improves retrieval. A path-only consolidation may qualify below; differences in environment, exceptions, provenance, metadata, or applicability disqualify automatic duplicate linking. A semantic merge is a reviewed rewrite; preserve every unique condition and source.
30
+ - **1 — Memory Consolidation:** Distinguish byte-identical, same-scope duplicates from similar assertions. Assess topical placement using the folder review below, including knowledge still stored directly under a category root. Submit justified moves through the permitted Dreaming path; related links do not replace folder organization. Differences in environment, exceptions, provenance, metadata, or applicability disqualify automatic duplicate linking. A semantic merge is a reviewed rewrite; preserve every unique condition and source.
31
31
  - **2 — Conflict Resolution:** Compare matching subjects, scope, environment, and time period. Distinguish historical evolution from contradiction. Cite both sources and recommend a reviewed replacement, narrower scopes, or retaining the current state. A newer date never outranks an explicit rule by itself.
32
32
  - **3 — Knowledge Abstraction:** Identify recurring causes across independent experiences. Cite supporting cases, shared conditions, counterexamples, and limits. Prefer at least two independent cases; copied retellings count as one. Observations may describe patterns; activating generalized knowledge requires a reviewed create mutation.
33
33
  - **4 — Forgetting & Decay:** Require concrete evidence of obsolescence or lost applicability. Age and low retrieval frequency alone do not justify archival or lower importance, especially for rules and decisions. Explain retrieval impact and reversibility. Propose recoverable archive or importance changes for review; never permanent deletion.
34
34
  - **5 — Memory Linking:** Link supported shared subject matter without claiming causality or authority. Deduplicate existing relations. Only related_to and eligible duplicate_of are auto candidates. supersedes, contradicts, supports, and derived_from need review and source evidence.
35
35
  - **6 — Reflection:** State documented outcome, supported explanation, useful next action, and applicability. Positive retrieval feedback measures retrieval usefulness, not task success. One incident can support a bounded lesson, never an unsupported universal rule.
36
36
 
37
+ ## Folder organization review
38
+
39
+ For inspected targets, compare plausible same-category topic groups with their current placement and nearby existing folders. Keep the run's selected scope: listing nearby paths does not make their bodies inspected or authorize mutations outside the frozen targets.
40
+
41
+ - Group by shared subject and applicability, using the inspected content as evidence. Reuse a suitable existing folder, or choose a coherent topic folder when it makes related knowledge easier to find together. A folder does not need to exist already to be useful.
42
+ - For each plausible group, record the affected paths, proposed destination and retrieval benefit in its candidate or consolidation checkpoint reason. If retaining the paths, explain the specific scope mismatch, mixed topic or other reason that makes the group unhelpful. Clear filenames and valid root-level storage alone are insufficient reasons to skip this comparison.
43
+ - When a move is justified, submit it using the server-permitted disposition below. Do not stop at mentioning a possible folder or substitute only a related_to link. Preserve independent scopes and avoid one-file folders, cosmetic renames and repeated moves without a retrieval benefit.
44
+ - Zero moves remain valid when the comparison supports retaining the current placement. Report that conclusion and its concrete basis; do not create folders or proposals just to fill a quota. If the assessment remains unprocessed, defer the stage and report the remaining scope rather than marking it completed.
45
+
37
46
  ## Folder moves and undo
38
47
 
39
48
  Knowledge has fixed `knowledge/rules/`, `knowledge/learnings/` and `knowledge/decisions/` roots, with arbitrary topical nesting below them. Use the existing six stages for folder findings; do not add another stage or create empty folder records. Inspect live dream_memory policy before requesting an automatic move. If the connected server does not explicitly support server-verified same-category path-only updates, submit a review candidate instead. Tool presence or a client-side claim that a move is harmless is insufficient. Do not retry a missing capability with generic content writes.
package/src/bridge.mjs CHANGED
@@ -1,13 +1,50 @@
1
1
  // Bundled once at publication, copied into private storage at installation.
2
2
  // Codex reserves Authorization in http_headers_helper. Its stdio transport
3
3
  // therefore uses this local adapter to authenticate to the unchanged remote MCP.
4
- import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
4
+ import { Client, StreamableHTTPClientTransport, SdkError, SdkErrorCode, SdkHttpError, UnauthorizedError } from '@modelcontextprotocol/client';
5
5
  import { Server, ProtocolError, ProtocolErrorCode } from '@modelcontextprotocol/server';
6
6
  import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
7
7
  import { readCredential } from './auth.mjs';
8
8
  import { pathToFileURL } from 'node:url';
9
9
  import { resolve } from 'node:path';
10
10
 
11
+ // Forward only a stable category and safe context, never raw remote messages or data.
12
+ function requestError(error, name) {
13
+ const tool = typeof name === 'string' && /^[a-z][a-z0-9_]{0,63}$/i.test(name) ? name : undefined;
14
+ let code = 'REQUEST_FAILED', retryable = false, message = 'The MCP request failed. Run foundocs-setup doctor for connection diagnostics.';
15
+ let httpStatus, remoteCode;
16
+ const schemaError = error instanceof ProtocolError && (
17
+ (error.code === ProtocolErrorCode.InvalidParams && (
18
+ error.message.startsWith("Structured content does not match the tool's output schema:") ||
19
+ error.message.startsWith('Failed to validate structured content:') ||
20
+ /^Tool '[^']+' has an invalid outputSchema:/.test(error.message)
21
+ )) || (error.code === ProtocolErrorCode.InvalidRequest && /^Tool .+ has an output schema but did not return structured content$/.test(error.message))
22
+ );
23
+ if (schemaError) {
24
+ code = 'OUTPUT_VALIDATION_ERROR';
25
+ message = 'The server response does not match the advertised tool output schema. Update the server tool contract; changing credentials will not fix this error.';
26
+ } else if (error instanceof SdkHttpError || error instanceof UnauthorizedError) {
27
+ httpStatus = error instanceof UnauthorizedError ? 401 : error.status;
28
+ if (httpStatus === 401) { code = 'UNAUTHENTICATED'; message = 'Authentication failed (HTTP 401). Run foundocs-setup doctor and check the configured workspace key.'; }
29
+ else if (httpStatus === 403) { code = 'FORBIDDEN'; message = 'Access was denied (HTTP 403). Check the workspace key permissions for this project.'; }
30
+ else if (httpStatus === 429) { code = 'RATE_LIMITED'; retryable = true; message = 'The server rate limit was reached (HTTP 429). Wait before retrying.'; }
31
+ else { code = 'REMOTE_HTTP_ERROR'; retryable = httpStatus >= 500; message = `The remote MCP server returned HTTP ${httpStatus}. Check the server status.`; }
32
+ } else if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) {
33
+ code = 'REQUEST_TIMEOUT'; retryable = true; message = 'The remote MCP request timed out.';
34
+ } else if ((error instanceof SdkError && [SdkErrorCode.InvalidResult, SdkErrorCode.UnsupportedResultType].includes(error.code))) {
35
+ code = 'INVALID_REMOTE_RESPONSE'; message = 'The remote MCP response is malformed. Check the server protocol and response schema.';
36
+ } else if ((error instanceof SdkError && [SdkErrorCode.NotConnected, SdkErrorCode.ConnectionClosed, SdkErrorCode.SendFailed].includes(error.code)) ||
37
+ (error instanceof TypeError && error.message === 'fetch failed') || ['AbortError', 'TimeoutError'].includes(error?.name)) {
38
+ code = 'CONNECTION_ERROR'; retryable = true; message = 'The remote MCP connection failed or was interrupted. Check connectivity and the server status.';
39
+ } else if (error instanceof ProtocolError) {
40
+ code = 'REMOTE_PROTOCOL_ERROR'; remoteCode = error.code;
41
+ message = 'The remote MCP server returned a protocol error. Check the requested tool and arguments.';
42
+ }
43
+ return new ProtocolError(ProtocolErrorCode.InternalError,
44
+ `Foundocs ${tool ?? 'request'} [${code}]: ${message} Writes may already have succeeded; retry only with the same requestId and input.`,
45
+ { code, retryable, ...(tool ? { tool } : {}), ...(httpStatus !== undefined ? { httpStatus } : {}), ...(remoteCode !== undefined ? { remoteCode } : {}) });
46
+ }
47
+
11
48
  export async function runBridge({ credentialPath, projectId, workspaceId, mcpUrl: endpoint }) {
12
49
  let remote, local;
13
50
  async function close() {
@@ -30,20 +67,20 @@ try {
30
67
  local = new Server({ name: 'foundocs', version: '0.2.0' }, { capabilities: { tools: {} }, instructions: remote.getInstructions() });
31
68
  local.setRequestHandler('tools/list', async (request) => {
32
69
  try { return await remote.listTools(request.params); }
33
- catch { throw new ProtocolError(ProtocolErrorCode.InternalError, 'Foundocs tool discovery failed. Run foundocs-setup doctor.'); }
70
+ catch (error) { throw requestError(error, 'tools_list'); }
34
71
  });
35
72
  local.setRequestHandler('tools/call', async (request) => {
36
73
  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.');
37
74
  try { return await remote.callTool(request.params); }
38
- catch { throw new ProtocolError(ProtocolErrorCode.InternalError, 'Foundocs request failed. Check authentication and connectivity. Retry writes only with the same requestId and input.'); }
75
+ catch (error) { throw requestError(error, request.params.name); }
39
76
  });
40
77
  local.onerror = () => process.stderr.write('Foundocs local MCP transport error.\n');
41
78
  remote.onerror = () => process.stderr.write('Foundocs remote MCP transport error.\n');
42
79
  process.stdin.on('end', () => { void close(); });
43
80
  for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { void close().finally(() => process.exit(0)); });
44
81
  await local.connect(new StdioServerTransport());
45
- } catch {
46
- process.stderr.write('Foundocs authentication bridge unavailable. Run foundocs-setup doctor.\n');
82
+ } catch (error) {
83
+ process.stderr.write(`Foundocs MCP bridge unavailable. ${requestError(error, 'initialize').message}\n`);
47
84
  await close(); process.exitCode = 1;
48
85
  }
49
86