@myrialabs/clopen 0.4.43 → 0.4.45

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.
Files changed (72) hide show
  1. package/backend/artifacts/project/bridge.ts +218 -0
  2. package/backend/artifacts/project/edit.ts +243 -0
  3. package/backend/artifacts/project/index.ts +38 -0
  4. package/backend/artifacts/project/project.test.ts +181 -0
  5. package/backend/artifacts/project/scan.ts +368 -0
  6. package/backend/artifacts/project/sources.ts +100 -0
  7. package/backend/artifacts/sync.ts +1 -1
  8. package/backend/auth/permissions.ts +15 -0
  9. package/backend/chat/stream-manager.ts +26 -8
  10. package/backend/database/migrations/083_create_project_mcp_trust.ts +32 -0
  11. package/backend/database/migrations/index.ts +7 -0
  12. package/backend/database/queries/index.ts +2 -0
  13. package/backend/database/queries/project-mcp-trust-queries.ts +43 -0
  14. package/backend/engine/adapters/claude/message-converter.ts +6 -2
  15. package/backend/engine/adapters/claude/stream.ts +36 -8
  16. package/backend/engine/adapters/cline/mcp-tools.ts +26 -4
  17. package/backend/engine/adapters/cline/stream.ts +20 -6
  18. package/backend/engine/adapters/codex/stream.ts +21 -4
  19. package/backend/engine/adapters/copilot/stream.ts +6 -3
  20. package/backend/engine/adapters/cursor/stream.ts +19 -8
  21. package/backend/engine/adapters/opencode/server.ts +14 -4
  22. package/backend/engine/adapters/opencode/stream.ts +18 -3
  23. package/backend/engine/adapters/pi/mcp-tools.ts +26 -4
  24. package/backend/engine/adapters/pi/stream.ts +35 -3
  25. package/backend/engine/adapters/qwen/message-converter.ts +2 -2
  26. package/backend/engine/adapters/qwen/stream.ts +8 -0
  27. package/backend/engine/artifact-sync.ts +12 -5
  28. package/backend/engine/docs/lessons-learned.md +118 -0
  29. package/backend/files/file-watcher.test.ts +77 -0
  30. package/backend/files/file-watcher.ts +92 -60
  31. package/backend/files/watch-ignore.test.ts +182 -0
  32. package/backend/files/watch-ignore.ts +244 -0
  33. package/backend/git/git-executor.ts +14 -4
  34. package/backend/index.ts +11 -1
  35. package/backend/instructions/service.ts +5 -3
  36. package/backend/instructions/sync.ts +10 -27
  37. package/backend/mcp/external/config.ts +65 -23
  38. package/backend/mcp/external/project.ts +124 -0
  39. package/backend/mcp/external/proxy.ts +65 -11
  40. package/backend/mcp/index.ts +14 -9
  41. package/backend/mcp/internal/remote-server.ts +11 -1
  42. package/backend/skills/marketplace.ts +1 -1
  43. package/backend/snapshot/blob-store.ts +9 -5
  44. package/backend/snapshot/git-attribution.test.ts +42 -0
  45. package/backend/snapshot/git-attribution.ts +306 -0
  46. package/backend/snapshot/gitignore.test.ts +62 -0
  47. package/backend/snapshot/gitignore.ts +158 -78
  48. package/backend/snapshot/snapshot-service.test.ts +270 -0
  49. package/backend/snapshot/snapshot-service.ts +412 -136
  50. package/backend/snapshot/turn-activity.test.ts +52 -0
  51. package/backend/snapshot/turn-activity.ts +83 -0
  52. package/backend/snapshot/turn-changes.test.ts +58 -1
  53. package/backend/snapshot/turn-changes.ts +66 -0
  54. package/backend/worktrees/tree.ts +1 -1
  55. package/backend/ws/chat/composer.ts +504 -0
  56. package/backend/ws/chat/index.ts +3 -1
  57. package/backend/ws/chat/stream.ts +252 -440
  58. package/backend/ws/index.ts +4 -0
  59. package/backend/ws/project-artifacts/index.ts +236 -0
  60. package/backend/ws/snapshot/changes.ts +66 -31
  61. package/dist/assets/{index-BeUKiRiY.js → index-Am-rJRxA.js} +1 -1
  62. package/dist/assets/{index-B6u8cait.js → index-D-Ad1N96.js} +1 -1
  63. package/dist/assets/main--PLCDxSy.css +1 -0
  64. package/dist/assets/main-DelPm2Xt.js +1239 -0
  65. package/dist/index.html +2 -2
  66. package/package.json +5 -5
  67. package/shared/types/stores/settings.ts +5 -0
  68. package/shared/types/unified/index.ts +2 -0
  69. package/shared/types/unified/message.ts +2 -0
  70. package/shared/types/unified/stream.ts +38 -1
  71. package/dist/assets/main-CMRXlv2f.js +0 -1215
  72. package/dist/assets/main-DzCY0n-j.css +0 -1
@@ -0,0 +1,244 @@
1
+ /**
2
+ * What the file watcher ignores.
3
+ *
4
+ * The rule of thumb: ignore what a tool writes and nobody edits by hand —
5
+ * dependency stores, build output, caches, VCS internals — because it is large
6
+ * (on Linux every watched directory costs an inotify handle) and noisy (a build
7
+ * would reload the explorer hundreds of times). Everything else is watched,
8
+ * dot-directories included: `.agents/`, `.claude/`, `.github/` and `.vscode/`
9
+ * hold files people and agents edit, and ignoring every dot path left the
10
+ * explorer stale until a reload.
11
+ *
12
+ * A bare list of names cannot get there on its own: names match at any depth,
13
+ * so a common one (`bin`, `target`, `out`, `Library`) would hide real source in
14
+ * some other ecosystem — Clopen's own `bin/` is source. So there are three
15
+ * layers, and a directory is ignored when any of them matches:
16
+ *
17
+ * 1. Names that mean "generated" wherever they appear ({@link IGNORED_DIRS}).
18
+ * 2. Ambiguous names, ignored only next to the manifest of the ecosystem that
19
+ * generates them ({@link MARKED_OUTPUT_DIRS}): `target/` beside
20
+ * `Cargo.toml`, `bin/` beside a `.csproj`.
21
+ * 3. Directories that describe themselves, whatever they are called
22
+ * ({@link SIGNATURE_ENTRIES}): the cross-tool `CACHEDIR.TAG` standard, and
23
+ * Python / conda environments.
24
+ *
25
+ * `.gitignore` is deliberately NOT a source. People commonly ignore folders
26
+ * they edit every day — `.claude/`, `.vscode/`, `.agents/`, local config — and
27
+ * pruning by it would bring back exactly the stale-explorer bug this fixes.
28
+ */
29
+
30
+ import { readdir } from 'node:fs/promises';
31
+ import { basename, dirname, join, sep } from 'node:path';
32
+
33
+ /** Layer 1: names that are machine-written wherever they appear. */
34
+ const IGNORED_DIRS = new Set([
35
+ // Version control internals
36
+ '.git', '.hg', '.svn', '.jj', '.bzr',
37
+ // JavaScript / TypeScript
38
+ 'node_modules', 'bower_components', 'jspm_packages', '.pnpm-store', '.yarn',
39
+ 'dist', 'build', 'coverage', '.nyc_output',
40
+ '.next', '.nuxt', '.output', '.svelte-kit', '.angular', '.astro', '.expo',
41
+ '.react-router', '.vinxi', '.nitro', '.vite', '.parcel-cache', '.turbo', '.nx',
42
+ '.docusaurus', '.vercel', '.netlify', '.wrangler', '.serverless', '.sass-cache',
43
+ // Python
44
+ '__pycache__', '__pypackages__', '.venv', '.tox', '.nox', '.eggs', '.pytest_cache',
45
+ '.mypy_cache', '.ruff_cache', '.pytype', '.pyre', '.hypothesis', 'htmlcov',
46
+ '.ipynb_checkpoints', '.pdm-build',
47
+ // JVM / Android / native
48
+ '.gradle', '.kotlin', '.cxx', '.externalNativeBuild',
49
+ // Apple
50
+ 'DerivedData', '.build', '.swiftpm', 'xcuserdata',
51
+ // Dart / Flutter
52
+ '.dart_tool', '.pub-cache',
53
+ // Haskell, OCaml, Elm, Zig, Nim
54
+ '.stack-work', 'dist-newstyle', '_opam', '_esy', 'elm-stuff',
55
+ '.zig-cache', 'zig-cache', 'zig-out', 'nimcache',
56
+ // Game engines, R
57
+ '.godot', '.Rproj.user',
58
+ // Monorepo build systems
59
+ 'buck-out', '.pants.d',
60
+ // Infrastructure
61
+ '.terraform', '.terragrunt-cache', '.aws-sam',
62
+ // Editors and IDEs (state churn, not settings people hand-edit)
63
+ '.idea', '.vs',
64
+ // PHP / Go / Ruby dependency copies
65
+ 'vendor',
66
+ // Generic caches and scratch space
67
+ '.cache', '.temp', '.tmp'
68
+ ]);
69
+
70
+ /** Layer 1, by prefix: names that carry a variable suffix. */
71
+ const IGNORED_DIR_PREFIXES = [
72
+ 'cmake-build-' // CLion: cmake-build-debug, cmake-build-release, …
73
+ ];
74
+
75
+ /** Files that change constantly and never matter to the explorer. */
76
+ const IGNORED_FILES = new Set([
77
+ '.DS_Store',
78
+ 'Thumbs.db',
79
+ '.gitkeep',
80
+ '.gitignore~',
81
+ '.eslintcache',
82
+ '.stylelintcache'
83
+ ]);
84
+
85
+ /** Vim swap files (`.name.swp`, `.swo`, …) — rewritten on every keystroke. */
86
+ const EDITOR_SWAP_FILE = /^\..+\.sw[a-p]$/;
87
+
88
+ /**
89
+ * Layer 2: a name that is output only in the ecosystem whose manifest sits
90
+ * beside it. `marker` is tested against every sibling entry name.
91
+ */
92
+ interface MarkedOutputDir {
93
+ dir: RegExp;
94
+ marker: RegExp;
95
+ }
96
+
97
+ const MARKED_OUTPUT_DIRS: MarkedOutputDir[] = [
98
+ // Rust, Maven, sbt, Leiningen
99
+ { dir: /^target$/, marker: /^(Cargo\.toml|pom\.xml|build\.sbt|project\.clj)$/ },
100
+ // .NET (Unity generates .csproj files at its root too)
101
+ { dir: /^(bin|obj)$/, marker: /\.(cs|fs|vb)proj$/ },
102
+ // Elixir, Erlang (rebar3), OCaml (dune)
103
+ { dir: /^_build$/, marker: /^(mix\.exs|rebar\.config|dune-project)$/ },
104
+ { dir: /^deps$/, marker: /^mix\.exs$/ },
105
+ // Next.js static export
106
+ { dir: /^out$/, marker: /^next\.config\.(js|cjs|mjs|ts)$/ },
107
+ // CocoaPods
108
+ { dir: /^Pods$/, marker: /^Podfile$/ },
109
+ // Unity
110
+ { dir: /^(Library|Temp|Logs|UserSettings)$/, marker: /^ProjectSettings$/ },
111
+ // Unreal Engine
112
+ { dir: /^(Binaries|Intermediate|Saved|DerivedDataCache)$/, marker: /\.uproject$/ },
113
+ // Bazel output symlinks: bazel-bin, bazel-out, bazel-<workspace>, …
114
+ { dir: /^bazel-/, marker: /^(WORKSPACE|WORKSPACE\.bazel|MODULE\.bazel)$/ }
115
+ ];
116
+
117
+ /**
118
+ * Layer 3: an entry that marks the directory CONTAINING it as generated.
119
+ *
120
+ * - `CACHEDIR.TAG` is the cross-tool cache-directory standard
121
+ * (bford.info/cachedir); Cargo's `target/` and the pytest, mypy and ruff
122
+ * caches all write one.
123
+ * - `pyvenv.cfg` sits at the root of every Python virtualenv, whatever the
124
+ * folder is called (`env`, `venv`, `.env3`, `myenv`, …).
125
+ * - `conda-meta` does the same for conda environments.
126
+ */
127
+ const SIGNATURE_ENTRIES = new Set(['CACHEDIR.TAG', 'pyvenv.cfg', 'conda-meta']);
128
+
129
+ /** Whether one path segment is ignored by name alone (layer 1). */
130
+ export function isIgnoredName(name: string): boolean {
131
+ if (IGNORED_DIRS.has(name) || IGNORED_FILES.has(name)) return true;
132
+ if (EDITOR_SWAP_FILE.test(name)) return true;
133
+ return IGNORED_DIR_PREFIXES.some((prefix) => name.startsWith(prefix));
134
+ }
135
+
136
+ /** Whether a project-relative path crosses a segment ignored by name. */
137
+ export function isIgnoredPath(relativePath: string): boolean {
138
+ return relativePath.split('/').some(isIgnoredName);
139
+ }
140
+
141
+ /** Layer 2: whether `name` is generated output given its sibling entries. */
142
+ export function isMarkedOutputDir(name: string, siblingNames: readonly string[]): boolean {
143
+ return MARKED_OUTPUT_DIRS.some(
144
+ (rule) => rule.dir.test(name) && siblingNames.some((sibling) => rule.marker.test(sibling))
145
+ );
146
+ }
147
+
148
+ /** Layer 3: whether a directory's own entries declare it generated. */
149
+ export function hasGeneratedSignature(entryNames: readonly string[]): boolean {
150
+ return entryNames.some((name) => SIGNATURE_ENTRIES.has(name));
151
+ }
152
+
153
+ /** A signature entry: its arrival or removal re-decides its parent directory. */
154
+ export function isSignatureEntry(name: string): boolean {
155
+ return SIGNATURE_ENTRIES.has(name);
156
+ }
157
+
158
+ /** A manifest: its arrival or removal re-decides its sibling directories. */
159
+ export function isOutputMarker(name: string): boolean {
160
+ return MARKED_OUTPUT_DIRS.some((rule) => rule.marker.test(name));
161
+ }
162
+
163
+ /** Whether a directory name could be output under some manifest (layer 2). */
164
+ export function isMarkableDirName(name: string): boolean {
165
+ return MARKED_OUTPUT_DIRS.some((rule) => rule.dir.test(name));
166
+ }
167
+
168
+ async function listNames(dir: string): Promise<string[]> {
169
+ try {
170
+ return await readdir(dir);
171
+ } catch {
172
+ return [];
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Layers 2 and 3 need the disk, so their answers are cached per directory.
178
+ * The cache is kept honest by events rather than a clock: the watcher calls
179
+ * {@link forget} when a signature or manifest appears or disappears, and
180
+ * {@link forgetTree} when a directory is removed.
181
+ */
182
+ export class GeneratedDirClassifier {
183
+ private readonly decisions = new Map<string, Promise<boolean>>();
184
+
185
+ constructor(private readonly root: string) {}
186
+
187
+ /**
188
+ * Whether `absDir` is generated by layer 2 or 3. `siblingNames` and
189
+ * `ownNames` skip the directory reads when the caller already listed them.
190
+ */
191
+ isGenerated(absDir: string, siblingNames?: readonly string[], ownNames?: readonly string[]): Promise<boolean> {
192
+ const cached = this.decisions.get(absDir);
193
+ if (cached) return cached;
194
+ const decision = (async () => {
195
+ if (absDir === this.root) return false;
196
+ const name = basename(absDir);
197
+ if (isMarkableDirName(name)) {
198
+ const siblings = siblingNames ?? (await listNames(dirname(absDir)));
199
+ if (isMarkedOutputDir(name, siblings)) return true;
200
+ }
201
+ return hasGeneratedSignature(ownNames ?? (await listNames(absDir)));
202
+ })();
203
+ this.decisions.set(absDir, decision);
204
+ return decision;
205
+ }
206
+
207
+ /**
208
+ * Whether a project-relative path lies under a generated directory. Only
209
+ * ancestors are judged: the path itself is reported even when it is such a
210
+ * directory, so a freshly created `target/` still appears in the explorer.
211
+ */
212
+ async isInsideGenerated(relativePath: string): Promise<boolean> {
213
+ const segments = relativePath.split('/');
214
+ let dir = this.root;
215
+ for (let i = 0; i < segments.length - 1; i++) {
216
+ dir = join(dir, segments[i]);
217
+ if (await this.isGenerated(dir)) return true;
218
+ }
219
+ return false;
220
+ }
221
+
222
+ /** Drop the decision for one directory so the next query re-reads the disk. */
223
+ forget(absDir: string): void {
224
+ this.decisions.delete(absDir);
225
+ }
226
+
227
+ /**
228
+ * Drop the decisions a manifest in `parentDir` could change: its children
229
+ * whose names some ecosystem treats as output.
230
+ */
231
+ forgetMarkableChildren(parentDir: string): void {
232
+ for (const dir of this.decisions.keys()) {
233
+ if (dirname(dir) === parentDir && isMarkableDirName(basename(dir))) this.decisions.delete(dir);
234
+ }
235
+ }
236
+
237
+ /** Drop decisions for a directory and everything under it (it was removed). */
238
+ forgetTree(absDir: string): void {
239
+ const prefix = absDir.endsWith(sep) ? absDir : absDir + sep;
240
+ for (const dir of this.decisions.keys()) {
241
+ if (dir === absDir || dir.startsWith(prefix)) this.decisions.delete(dir);
242
+ }
243
+ }
244
+ }
@@ -20,6 +20,8 @@ export interface GitExecResult {
20
20
  stdout: string;
21
21
  stderr: string;
22
22
  exitCode: number;
23
+ /** Undecoded stdout, only when the call asked for `raw` output. */
24
+ stdoutBytes?: Buffer;
23
25
  }
24
26
 
25
27
  export interface GitExecOptions {
@@ -47,6 +49,12 @@ export interface GitExecOptions {
47
49
  * future variable might.
48
50
  */
49
51
  env?: Record<string, string>;
52
+ /**
53
+ * Keep stdout as bytes as well. Needed whenever stdout is file content
54
+ * (`cat-file`, `show`): decoding a binary blob as UTF-8 is lossy, and a
55
+ * hash of the decoded text would never match the file on disk.
56
+ */
57
+ raw?: boolean;
50
58
  }
51
59
 
52
60
  /**
@@ -60,7 +68,7 @@ export async function execGit(
60
68
  ): Promise<GitExecResult> {
61
69
  const options: GitExecOptions =
62
70
  typeof timeoutOrOptions === 'number' ? { timeout: timeoutOrOptions } : timeoutOrOptions;
63
- const { timeout = 30000, stdin, okExitCodes = [], env: extraEnv } = options;
71
+ const { timeout = 30000, stdin, okExitCodes = [], env: extraEnv, raw = false } = options;
64
72
  debug.log('git', `Executing: git ${args.join(' ')} in ${cwd}`);
65
73
 
66
74
  const gitPath = resolveBinary('git');
@@ -106,10 +114,12 @@ export async function execGit(
106
114
  }, timeout);
107
115
 
108
116
  try {
109
- const [stdout, stderr] = await Promise.all([
110
- new Response(proc.stdout).text(),
117
+ const [stdoutBuffer, stderr] = await Promise.all([
118
+ new Response(proc.stdout).arrayBuffer(),
111
119
  new Response(proc.stderr).text()
112
120
  ]);
121
+ const stdoutBytes = Buffer.from(stdoutBuffer);
122
+ const stdout = stdoutBytes.toString('utf8');
113
123
 
114
124
  const exitCode = await proc.exited;
115
125
  clearTimeout(timeoutId);
@@ -118,7 +128,7 @@ export async function execGit(
118
128
  debug.warn('git', `Command failed (exit ${exitCode}): git ${args.join(' ')}\n${stderr}`);
119
129
  }
120
130
 
121
- return { stdout, stderr, exitCode };
131
+ return raw ? { stdout, stderr, exitCode, stdoutBytes } : { stdout, stderr, exitCode };
122
132
  } catch (err) {
123
133
  clearTimeout(timeoutId);
124
134
  throw err;
package/backend/index.ts CHANGED
@@ -78,7 +78,7 @@ import { integrationHooksRoute } from './http/integration-hooks';
78
78
  import { browserPreviewServiceManager } from './preview';
79
79
 
80
80
  // MCP remote server for Open Code custom tools
81
- import { handleMcpRequest, handleExternalMcpRequest, closeMcpServer, completeAuthorization } from './mcp';
81
+ import { handleMcpRequest, handleExternalMcpRequest, handleProjectMcpRequest, closeMcpServer, completeAuthorization } from './mcp';
82
82
 
83
83
  // Auth middleware
84
84
  import { checkRouteAccess, PUBLIC_ROUTES } from './auth/permissions';
@@ -188,6 +188,16 @@ const app = new Elysia()
188
188
  return handleExternalMcpRequest(request, params.slug);
189
189
  })
190
190
 
191
+ // Per-project proxy for servers a repository declares in `.agents/mcp.json`.
192
+ // Only served while an admin has approved the file's current content — see
193
+ // backend/mcp/external/project.ts.
194
+ .all('/mcp/proj/:projectId/:name', async ({ request, params, server }) => {
195
+ server?.timeout(request, 0);
196
+ let name = params.name;
197
+ try { name = decodeURIComponent(name); } catch { /* already decoded */ }
198
+ return handleProjectMcpRequest(request, params.projectId, name);
199
+ })
200
+
191
201
  // Stable OAuth redirect target for centralized MCP sign-in. The browser is
192
202
  // redirected here after the user consents; we exchange the code for tokens
193
203
  // (stored against the server) and show a self-closing confirmation page. The
@@ -1,8 +1,10 @@
1
1
  /**
2
2
  * Instruction service — reads/writes the Clopen-managed instruction block for
3
- * the single global scope and per project. The content is materialized into each
4
- * engine's memory file as a MARKER-REGION (see `sync.ts`), so hand-written parts
5
- * of `CLAUDE.md` / `AGENTS.md` are never touched.
3
+ * the single global scope and per project. The global block is materialized into
4
+ * each engine's memory file as a MARKER-REGION (see `sync.ts`), so hand-written
5
+ * parts of `CLAUDE.md` / `AGENTS.md` are never touched. The per-project block is
6
+ * the Clopen-only layer: never committed, delivered per session by the project
7
+ * bridge (`backend/artifacts/project/bridge.ts`).
6
8
  *
7
9
  * This is distinct from Skills/Commands/Subagents (which are discrete
8
10
  * installable artifacts): Instructions is one managed block of prose per scope.
@@ -1,13 +1,11 @@
1
1
  /**
2
2
  * Engine sync for Instructions — writes the managed instruction block into each
3
3
  * engine's memory file as a marker-region (`<!-- CLOPEN:INSTRUCTIONS:START … -->`).
4
- * Global scope always applies; project scope applies to the repo memory file
5
- * when a project is being streamed.
4
+ * Global scope only — see {@link syncInstructions} for where project
5
+ * instructions go.
6
6
  *
7
7
  * Ownership is MARKER-REGION: only the delimited block is Clopen's; the rest of
8
8
  * `CLAUDE.md` / `AGENTS.md` (hand-written by the user) is preserved verbatim.
9
- * Writing into a project's `CLAUDE.md` touches the repo working tree, so callers
10
- * pass the repo path explicitly — this is never silent guesswork.
11
9
  *
12
10
  * Never throws — a stream never breaks because instructions couldn't sync.
13
11
  */
@@ -36,13 +34,14 @@ export function buildInstructionsPromptContext(): string {
36
34
  }
37
35
 
38
36
  /**
39
- * Sync the global (and, when a project is provided, project) instruction block
40
- * into one engine's memory file(s).
37
+ * Sync the global instruction block into one engine's memory file.
38
+ *
39
+ * The per-project block is deliberately NOT written anywhere: it is the
40
+ * Clopen-only layer (never committed), delivered per session by the project
41
+ * bridge (`backend/artifacts/project/bridge.ts`). The committed project layer is
42
+ * the managed block of the repo's `AGENTS.md`, edited explicitly from Settings.
41
43
  */
42
- export async function syncInstructions(
43
- engine: ArtifactEngine,
44
- project?: { id: string; path: string }
45
- ): Promise<void> {
44
+ export async function syncInstructions(engine: ArtifactEngine): Promise<void> {
46
45
  try {
47
46
  // Global scope → engine's isolated global memory file, but ONLY for engines
48
47
  // that actually read one. Writing `AGENTS.md` into Cline's or Cursor's
@@ -57,23 +56,7 @@ export async function syncInstructions(
57
56
  if (globalTarget) await writeManagedBlock(globalTarget, globalBlock, MARKERS);
58
57
  }
59
58
 
60
- // Project scope → repo memory file (touches the working tree).
61
- if (project) {
62
- const row = instructionQueries.getForProject(project.id);
63
- const projectTarget = resolveArtifact('instruction', { engine, scope: 'project', projectPath: project.path }).locateEffective({
64
- engine,
65
- scope: 'project',
66
- projectPath: project.path
67
- });
68
- const projectBlock = row && row.is_enabled === 1 ? row.content : '';
69
- // Only write when there is a managed block to add/update or a prior one to
70
- // clear — avoids creating an empty repo memory file for nothing.
71
- if (projectTarget && (projectBlock || row)) {
72
- await writeManagedBlock(projectTarget, projectBlock, MARKERS);
73
- }
74
- }
75
-
76
- debug.log('instructions', `📝 Synced instructions → ${engine}${project ? ' (+project)' : ''}`);
59
+ debug.log('instructions', `📝 Synced instructions → ${engine}`);
77
60
  } catch (error) {
78
61
  debug.warn('instructions', `⚠️ Instruction sync for ${engine} failed (continuing without):`, error);
79
62
  }
@@ -32,6 +32,7 @@ import { SERVER_ENV } from '../../utils/env';
32
32
  import type { McpServerRow } from '$backend/database/queries';
33
33
  import type { EngineType } from '$shared/types/unified';
34
34
  import type { ResolvedExternalServer } from './types';
35
+ import { getTrustedProjectServers, knownProjectNamespaces } from './project';
35
36
 
36
37
  /**
37
38
  * Codex `mcp_servers.<name>` config, flattened by the SDK to `--config` flags.
@@ -56,6 +57,28 @@ function bridgeUrl(slug: string, engine: EngineType): string {
56
57
  return `http://localhost:${SERVER_ENV.PORT}/mcp/ext/${slug}?engine=${engine}`;
57
58
  }
58
59
 
60
+ /** Loopback URL of the per-project bridge for a server in `.agents/mcp.json`. */
61
+ function projectBridgeUrl(projectId: string, name: string, engine: EngineType): string {
62
+ return `http://localhost:${SERVER_ENV.PORT}/mcp/proj/${encodeURIComponent(projectId)}/${encodeURIComponent(name)}?engine=${engine}`;
63
+ }
64
+
65
+ /**
66
+ * Every bridge an engine should receive for this stream: the enabled installed
67
+ * servers (profile-filtered) plus, when the stream has a project, the servers of
68
+ * its APPROVED `.agents/mcp.json`. Project servers are not profile-filtered —
69
+ * they belong to the repository, not to a bundle — and never shadow an
70
+ * installed server that happens to share the namespace.
71
+ */
72
+ function bridgesFor(engine: EngineType, profileFilter?: Set<string>, projectId?: string | null): { namespace: string; url: string }[] {
73
+ const out = getEnabledExternalServers(profileFilter).map(s => ({ namespace: s.namespace, url: bridgeUrl(s.slug, engine) }));
74
+ const taken = new Set(out.map(b => b.namespace));
75
+ for (const s of getTrustedProjectServers(projectId)) {
76
+ if (taken.has(s.namespace)) continue;
77
+ out.push({ namespace: s.namespace, url: projectBridgeUrl(s.projectId, s.name, engine) });
78
+ }
79
+ return out;
80
+ }
81
+
59
82
  /** The service-token bearer header every engine→bridge hop carries. */
60
83
  function serviceAuthHeaders(): Record<string, string> {
61
84
  return { Authorization: `Bearer ${getMcpServiceToken()}` };
@@ -145,22 +168,22 @@ export function remoteNeedsOAuth(s: ResolvedExternalServer): boolean {
145
168
  // ---------------------------------------------------------------------------
146
169
 
147
170
  /** Claude Agent SDK: Streamable-HTTP remote keyed by namespace. */
148
- export function getClaudeExternalMcpConfig(profileFilter?: Set<string>): Record<string, McpServerConfig> {
171
+ export function getClaudeExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, McpServerConfig> {
149
172
  const out: Record<string, McpServerConfig> = {};
150
- for (const s of getEnabledExternalServers(profileFilter)) {
151
- out[s.namespace] = { type: 'http', url: bridgeUrl(s.slug, 'claude-code'), headers: serviceAuthHeaders() };
173
+ for (const b of bridgesFor('claude-code', profileFilter, projectId)) {
174
+ out[b.namespace] = { type: 'http', url: b.url, headers: serviceAuthHeaders() };
152
175
  }
153
176
  logBuilt('Claude', out);
154
177
  return out;
155
178
  }
156
179
 
157
180
  /** Open Code: `McpRemoteConfig` pointing at the bridge proxy. */
158
- export function getOpenCodeExternalMcpConfig(profileFilter?: Set<string>): Record<string, McpRemoteConfig> {
181
+ export function getOpenCodeExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, McpRemoteConfig> {
159
182
  const out: Record<string, McpRemoteConfig> = {};
160
- for (const s of getEnabledExternalServers(profileFilter)) {
161
- out[s.namespace] = {
183
+ for (const b of bridgesFor('opencode', profileFilter, projectId)) {
184
+ out[b.namespace] = {
162
185
  type: 'remote',
163
- url: bridgeUrl(s.slug, 'opencode'),
186
+ url: b.url,
164
187
  enabled: true,
165
188
  timeout: MCP_TOOL_CALL_TIMEOUT_MS,
166
189
  headers: serviceAuthHeaders()
@@ -170,6 +193,25 @@ export function getOpenCodeExternalMcpConfig(profileFilter?: Set<string>): Recor
170
193
  return out;
171
194
  }
172
195
 
196
+ /**
197
+ * Open Code entries for the project's approved `.agents/mcp.json` ONLY. The
198
+ * server pool caches the installed-server config per scope, so project servers
199
+ * are layered on at spawn-assembly time instead (see opencode/server.ts).
200
+ */
201
+ export function getOpenCodeProjectMcpConfig(projectId: string | null | undefined): Record<string, McpRemoteConfig> {
202
+ const out: Record<string, McpRemoteConfig> = {};
203
+ for (const s of getTrustedProjectServers(projectId)) {
204
+ out[s.namespace] = {
205
+ type: 'remote',
206
+ url: projectBridgeUrl(s.projectId, s.name, 'opencode'),
207
+ enabled: true,
208
+ timeout: MCP_TOOL_CALL_TIMEOUT_MS,
209
+ headers: serviceAuthHeaders()
210
+ };
211
+ }
212
+ return out;
213
+ }
214
+
173
215
  /**
174
216
  * Codex: `mcp_servers.<name>.url` pointing at the bridge proxy.
175
217
  *
@@ -179,26 +221,26 @@ export function getOpenCodeExternalMcpConfig(profileFilter?: Set<string>): Recor
179
221
  * The server is registered so interactive/known-tool flows work; this limit is
180
222
  * unchanged by the proxy.
181
223
  */
182
- export function getCodexExternalMcpConfig(profileFilter?: Set<string>): Record<string, CodexMcpServerConfig> {
224
+ export function getCodexExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, CodexMcpServerConfig> {
183
225
  const out: Record<string, CodexMcpServerConfig> = {};
184
- for (const s of getEnabledExternalServers(profileFilter)) {
185
- out[s.namespace] = { url: bridgeUrl(s.slug, 'codex'), http_headers: serviceAuthHeaders() };
226
+ for (const b of bridgesFor('codex', profileFilter, projectId)) {
227
+ out[b.namespace] = { url: b.url, http_headers: serviceAuthHeaders() };
186
228
  }
187
229
  logBuilt('Codex', out);
188
230
  return out;
189
231
  }
190
232
 
191
233
  /** Copilot: `MCPHTTPServerConfig` pointing at the bridge proxy. */
192
- export function getCopilotExternalMcpConfig(profileFilter?: Set<string>): Record<string, CopilotMcpServerConfig> {
234
+ export function getCopilotExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, CopilotMcpServerConfig> {
193
235
  const out: Record<string, CopilotMcpServerConfig> = {};
194
- for (const s of getEnabledExternalServers(profileFilter)) {
236
+ for (const b of bridgesFor('copilot', profileFilter, projectId)) {
195
237
  // `tools: ['*']` makes the Copilot runtime expose ALL of the proxy's
196
238
  // tools. Leaving it unset relies on the SDK's documented "undefined =
197
239
  // all" default, which the bundled CLI does not honour for dynamically
198
240
  // discovered servers — the tools never reach the model.
199
- out[s.namespace] = {
241
+ out[b.namespace] = {
200
242
  type: 'http',
201
- url: bridgeUrl(s.slug, 'copilot'),
243
+ url: b.url,
202
244
  tools: ['*'],
203
245
  timeout: MCP_TOOL_CALL_TIMEOUT_MS,
204
246
  headers: serviceAuthHeaders()
@@ -210,20 +252,20 @@ export function getCopilotExternalMcpConfig(profileFilter?: Set<string>): Record
210
252
 
211
253
  /** Qwen Code: `CLIMcpServerConfig` Streamable-HTTP (`httpUrl`) at the bridge proxy. */
212
254
  /** Cursor: `McpServerConfig` (http variant) pointing at the bridge proxy. */
213
- export function getCursorExternalMcpConfig(profileFilter?: Set<string>): Record<string, CursorMcpServerConfig> {
255
+ export function getCursorExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, CursorMcpServerConfig> {
214
256
  const out: Record<string, CursorMcpServerConfig> = {};
215
- for (const s of getEnabledExternalServers(profileFilter)) {
216
- out[s.namespace] = { type: 'http', url: bridgeUrl(s.slug, 'cursor'), headers: serviceAuthHeaders() };
257
+ for (const b of bridgesFor('cursor', profileFilter, projectId)) {
258
+ out[b.namespace] = { type: 'http', url: b.url, headers: serviceAuthHeaders() };
217
259
  }
218
260
  logBuilt('Cursor', out);
219
261
  return out;
220
262
  }
221
263
 
222
- export function getQwenExternalMcpConfig(profileFilter?: Set<string>): Record<string, QwenMcpServerConfig> {
264
+ export function getQwenExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, QwenMcpServerConfig> {
223
265
  const out: Record<string, QwenMcpServerConfig> = {};
224
- for (const s of getEnabledExternalServers(profileFilter)) {
225
- out[s.namespace] = {
226
- httpUrl: bridgeUrl(s.slug, 'qwen'),
266
+ for (const b of bridgesFor('qwen', profileFilter, projectId)) {
267
+ out[b.namespace] = {
268
+ httpUrl: b.url,
227
269
  timeout: MCP_TOOL_CALL_TIMEOUT_MS,
228
270
  trust: true,
229
271
  headers: serviceAuthHeaders()
@@ -251,8 +293,8 @@ export function getQwenExternalMcpConfig(profileFilter?: Set<string>): Record<st
251
293
  * Returns null if the name doesn't belong to any enabled external server.
252
294
  */
253
295
  export function resolveExternalToolName(toolName: string): string | null {
254
- for (const s of getEnabledExternalServers()) {
255
- const ns = s.namespace;
296
+ const namespaces = [...getEnabledExternalServers().map(s => s.namespace), ...knownProjectNamespaces()];
297
+ for (const ns of namespaces) {
256
298
  if (toolName.startsWith(`mcp__${ns}__`)) return toolName;
257
299
  for (const sep of ['_', '-']) {
258
300
  const prefix = `${ns}${sep}`;