@myrialabs/clopen 0.4.44 → 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 (67) 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 +20 -3
  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/stream.ts +27 -1
  15. package/backend/engine/adapters/cline/mcp-tools.ts +26 -4
  16. package/backend/engine/adapters/cline/stream.ts +20 -6
  17. package/backend/engine/adapters/codex/stream.ts +21 -4
  18. package/backend/engine/adapters/copilot/stream.ts +6 -3
  19. package/backend/engine/adapters/cursor/stream.ts +19 -8
  20. package/backend/engine/adapters/opencode/server.ts +14 -4
  21. package/backend/engine/adapters/opencode/stream.ts +18 -3
  22. package/backend/engine/adapters/pi/mcp-tools.ts +26 -4
  23. package/backend/engine/adapters/pi/stream.ts +35 -3
  24. package/backend/engine/adapters/qwen/stream.ts +8 -0
  25. package/backend/engine/artifact-sync.ts +12 -5
  26. package/backend/files/file-watcher.test.ts +77 -0
  27. package/backend/files/file-watcher.ts +92 -60
  28. package/backend/files/watch-ignore.test.ts +182 -0
  29. package/backend/files/watch-ignore.ts +244 -0
  30. package/backend/git/git-executor.ts +14 -4
  31. package/backend/index.ts +11 -1
  32. package/backend/instructions/service.ts +5 -3
  33. package/backend/instructions/sync.ts +10 -27
  34. package/backend/mcp/external/config.ts +65 -23
  35. package/backend/mcp/external/project.ts +124 -0
  36. package/backend/mcp/external/proxy.ts +65 -11
  37. package/backend/mcp/index.ts +14 -9
  38. package/backend/mcp/internal/remote-server.ts +11 -1
  39. package/backend/skills/marketplace.ts +1 -1
  40. package/backend/snapshot/blob-store.ts +9 -5
  41. package/backend/snapshot/git-attribution.test.ts +42 -0
  42. package/backend/snapshot/git-attribution.ts +306 -0
  43. package/backend/snapshot/gitignore.test.ts +62 -0
  44. package/backend/snapshot/gitignore.ts +158 -78
  45. package/backend/snapshot/snapshot-service.test.ts +270 -0
  46. package/backend/snapshot/snapshot-service.ts +412 -136
  47. package/backend/snapshot/turn-activity.test.ts +52 -0
  48. package/backend/snapshot/turn-activity.ts +83 -0
  49. package/backend/snapshot/turn-changes.test.ts +58 -1
  50. package/backend/snapshot/turn-changes.ts +66 -0
  51. package/backend/worktrees/tree.ts +1 -1
  52. package/backend/ws/chat/composer.ts +504 -0
  53. package/backend/ws/chat/index.ts +3 -1
  54. package/backend/ws/chat/stream.ts +252 -440
  55. package/backend/ws/index.ts +4 -0
  56. package/backend/ws/project-artifacts/index.ts +236 -0
  57. package/backend/ws/snapshot/changes.ts +66 -31
  58. package/dist/assets/{index-BWyhqUi5.js → index-Am-rJRxA.js} +1 -1
  59. package/dist/assets/{index-DX5OwLOc.js → index-D-Ad1N96.js} +1 -1
  60. package/dist/assets/main--PLCDxSy.css +1 -0
  61. package/dist/assets/main-DelPm2Xt.js +1239 -0
  62. package/dist/index.html +2 -2
  63. package/package.json +1 -1
  64. package/shared/types/stores/settings.ts +5 -0
  65. package/shared/types/unified/message.ts +2 -0
  66. package/dist/assets/main-DOkwqXRU.js +0 -1215
  67. package/dist/assets/main-DzCY0n-j.css +0 -1
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Watch ignore policy tests.
3
+ *
4
+ * The negative cases matter as much as the positive ones: a name ignored in
5
+ * the wrong ecosystem hides real source from the explorer (Clopen's own `bin/`
6
+ * is source), and a dot-directory ignored by default is the stale-panel bug
7
+ * this policy replaced.
8
+ */
9
+
10
+ import { describe, expect, test, afterEach } from 'bun:test';
11
+ import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
12
+ import { tmpdir } from 'node:os';
13
+ import { join } from 'node:path';
14
+ import {
15
+ GeneratedDirClassifier,
16
+ isIgnoredName,
17
+ isIgnoredPath,
18
+ isMarkedOutputDir,
19
+ hasGeneratedSignature,
20
+ isOutputMarker,
21
+ isSignatureEntry
22
+ } from './watch-ignore';
23
+
24
+ const tempRoots: string[] = [];
25
+
26
+ async function makeProject(): Promise<string> {
27
+ const dir = await mkdtemp(join(tmpdir(), 'clopen-ignore-'));
28
+ tempRoots.push(dir);
29
+ return dir;
30
+ }
31
+
32
+ afterEach(async () => {
33
+ await Promise.all(tempRoots.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
34
+ });
35
+
36
+ describe('isIgnoredPath (by name)', () => {
37
+ test('ignores dependency stores, build output and caches at any depth', () => {
38
+ for (const path of [
39
+ 'node_modules/pkg/index.js',
40
+ 'packages/web/node_modules/x',
41
+ '.git/HEAD',
42
+ '.venv/lib/site.py',
43
+ 'app/.dart_tool/package_config.json',
44
+ 'ios/.build/debug',
45
+ '.stack-work/dist',
46
+ 'cmake-build-debug/CMakeCache.txt',
47
+ '.zig-cache/o'
48
+ ]) {
49
+ expect(isIgnoredPath(path)).toBe(true);
50
+ }
51
+ });
52
+
53
+ test('watches dot-directories people and agents edit', () => {
54
+ for (const path of [
55
+ '.agents/skills/demo/SKILL.md',
56
+ '.agents/mcp.json',
57
+ '.claude/settings.json',
58
+ '.github/workflows/ci.yml',
59
+ '.vscode/settings.json',
60
+ '.env.local',
61
+ '.gitignore'
62
+ ]) {
63
+ expect(isIgnoredPath(path)).toBe(false);
64
+ }
65
+ });
66
+
67
+ test('does not ignore names that are source in some ecosystem', () => {
68
+ for (const name of ['bin', 'obj', 'target', 'out', 'deps', '_build', 'Library', 'Pods', 'env', 'venv']) {
69
+ expect(isIgnoredName(name)).toBe(false);
70
+ }
71
+ });
72
+
73
+ test('ignores noise files but not their look-alikes', () => {
74
+ expect(isIgnoredPath('src/.DS_Store')).toBe(true);
75
+ expect(isIgnoredPath('.eslintcache')).toBe(true);
76
+ expect(isIgnoredPath('src/.notes.md.swp')).toBe(true);
77
+ expect(isIgnoredPath('src/notes.swp')).toBe(false);
78
+ });
79
+ });
80
+
81
+ describe('isMarkedOutputDir (by manifest)', () => {
82
+ test('treats an ambiguous name as output only beside its manifest', () => {
83
+ expect(isMarkedOutputDir('target', ['Cargo.toml', 'src'])).toBe(true);
84
+ expect(isMarkedOutputDir('target', ['pom.xml'])).toBe(true);
85
+ expect(isMarkedOutputDir('target', ['package.json'])).toBe(false);
86
+
87
+ expect(isMarkedOutputDir('bin', ['App.csproj'])).toBe(true);
88
+ expect(isMarkedOutputDir('obj', ['Lib.fsproj'])).toBe(true);
89
+ expect(isMarkedOutputDir('bin', ['package.json', 'bunfig.toml'])).toBe(false);
90
+
91
+ expect(isMarkedOutputDir('_build', ['mix.exs'])).toBe(true);
92
+ expect(isMarkedOutputDir('deps', ['mix.exs'])).toBe(true);
93
+ expect(isMarkedOutputDir('deps', ['package.json'])).toBe(false);
94
+
95
+ expect(isMarkedOutputDir('out', ['next.config.mjs'])).toBe(true);
96
+ expect(isMarkedOutputDir('out', ['vite.config.ts'])).toBe(false);
97
+
98
+ expect(isMarkedOutputDir('Pods', ['Podfile'])).toBe(true);
99
+ expect(isMarkedOutputDir('Library', ['ProjectSettings', 'Assets'])).toBe(true);
100
+ expect(isMarkedOutputDir('Library', ['Sources'])).toBe(false);
101
+ expect(isMarkedOutputDir('Intermediate', ['Game.uproject'])).toBe(true);
102
+ expect(isMarkedOutputDir('bazel-out', ['MODULE.bazel'])).toBe(true);
103
+ });
104
+
105
+ test('knows which entries re-decide their siblings', () => {
106
+ expect(isOutputMarker('Cargo.toml')).toBe(true);
107
+ expect(isOutputMarker('App.csproj')).toBe(true);
108
+ expect(isOutputMarker('README.md')).toBe(false);
109
+ });
110
+ });
111
+
112
+ describe('hasGeneratedSignature (by contents)', () => {
113
+ test('recognises cache dirs and environments whatever they are called', () => {
114
+ expect(hasGeneratedSignature(['CACHEDIR.TAG', 'debug'])).toBe(true);
115
+ expect(hasGeneratedSignature(['bin', 'lib', 'pyvenv.cfg'])).toBe(true);
116
+ expect(hasGeneratedSignature(['conda-meta', 'lib'])).toBe(true);
117
+ expect(hasGeneratedSignature(['index.ts', 'utils'])).toBe(false);
118
+ expect(isSignatureEntry('pyvenv.cfg')).toBe(true);
119
+ });
120
+ });
121
+
122
+ describe('GeneratedDirClassifier', () => {
123
+ test('classifies from the disk by manifest and by signature', async () => {
124
+ const root = await makeProject();
125
+ await writeFile(join(root, 'Cargo.toml'), '[package]');
126
+ await mkdir(join(root, 'target', 'debug'), { recursive: true });
127
+ await mkdir(join(root, 'myenv', 'lib'), { recursive: true });
128
+ await writeFile(join(root, 'myenv', 'pyvenv.cfg'), 'home = /usr/bin');
129
+ await mkdir(join(root, 'bin'), { recursive: true });
130
+
131
+ const classifier = new GeneratedDirClassifier(root);
132
+ expect(await classifier.isGenerated(join(root, 'target'))).toBe(true);
133
+ expect(await classifier.isGenerated(join(root, 'myenv'))).toBe(true);
134
+ expect(await classifier.isGenerated(join(root, 'bin'))).toBe(false);
135
+ expect(await classifier.isGenerated(root)).toBe(false);
136
+ });
137
+
138
+ test('judges ancestors only, so a new output folder itself is still reported', async () => {
139
+ const root = await makeProject();
140
+ await writeFile(join(root, 'Cargo.toml'), '[package]');
141
+ await mkdir(join(root, 'target', 'debug'), { recursive: true });
142
+
143
+ const classifier = new GeneratedDirClassifier(root);
144
+ expect(await classifier.isInsideGenerated('target')).toBe(false);
145
+ expect(await classifier.isInsideGenerated('target/debug/app')).toBe(true);
146
+ expect(await classifier.isInsideGenerated('src/main.rs')).toBe(false);
147
+ });
148
+
149
+ test('re-reads the disk once told a manifest or signature moved', async () => {
150
+ const root = await makeProject();
151
+ await mkdir(join(root, 'bin'), { recursive: true });
152
+ await mkdir(join(root, 'env'), { recursive: true });
153
+
154
+ const classifier = new GeneratedDirClassifier(root);
155
+ expect(await classifier.isGenerated(join(root, 'bin'))).toBe(false);
156
+ expect(await classifier.isGenerated(join(root, 'env'))).toBe(false);
157
+
158
+ await writeFile(join(root, 'Tool.csproj'), '<Project />');
159
+ await writeFile(join(root, 'env', 'pyvenv.cfg'), 'home = /usr/bin');
160
+ // Cached until told otherwise…
161
+ expect(await classifier.isGenerated(join(root, 'bin'))).toBe(false);
162
+
163
+ classifier.forgetMarkableChildren(root);
164
+ classifier.forget(join(root, 'env'));
165
+ expect(await classifier.isGenerated(join(root, 'bin'))).toBe(true);
166
+ expect(await classifier.isGenerated(join(root, 'env'))).toBe(true);
167
+ });
168
+
169
+ test('forgets a removed directory and everything under it', async () => {
170
+ const root = await makeProject();
171
+ await mkdir(join(root, 'env', 'lib'), { recursive: true });
172
+ await writeFile(join(root, 'env', 'pyvenv.cfg'), 'home = /usr/bin');
173
+
174
+ const classifier = new GeneratedDirClassifier(root);
175
+ expect(await classifier.isGenerated(join(root, 'env'))).toBe(true);
176
+
177
+ await rm(join(root, 'env'), { recursive: true, force: true });
178
+ await mkdir(join(root, 'env'), { recursive: true });
179
+ classifier.forgetTree(join(root, 'env'));
180
+ expect(await classifier.isGenerated(join(root, 'env'))).toBe(false);
181
+ });
182
+ });
@@ -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
  }