@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
@@ -30,6 +30,9 @@ import {
30
30
  getEnabledExternalServers,
31
31
  listExternalServerTools,
32
32
  callExternalServerTool,
33
+ getTrustedProjectServers,
34
+ listProjectServerTools,
35
+ callProjectServerTool,
33
36
  projectContextService,
34
37
  serverMetadata,
35
38
  } from '../../../mcp';
@@ -102,12 +105,31 @@ export async function buildPiMcpTools(
102
105
  }
103
106
 
104
107
  // ── External servers (proxied upstream) ──
105
- for (const server of getEnabledExternalServers(profileFilter)) {
108
+ // Installed servers (profile-filtered) plus the project's approved
109
+ // `.agents/mcp.json` servers, which never shadow an installed namespace.
110
+ const upstreams: { label: string; namespace: string; list: () => ReturnType<typeof listExternalServerTools>; call: (tool: string, args: unknown) => Promise<unknown> }[] =
111
+ getEnabledExternalServers(profileFilter).map(s => ({
112
+ label: s.slug,
113
+ namespace: s.namespace,
114
+ list: () => listExternalServerTools(s.slug),
115
+ call: (tool: string, args: unknown) => callExternalServerTool(s.slug, tool, args)
116
+ }));
117
+ const taken = new Set(upstreams.map(u => u.namespace));
118
+ for (const s of getTrustedProjectServers(context?.projectId)) {
119
+ if (taken.has(s.namespace)) continue;
120
+ upstreams.push({
121
+ label: s.namespace,
122
+ namespace: s.namespace,
123
+ list: () => listProjectServerTools(s.projectId, s.name),
124
+ call: (tool: string, args: unknown) => callProjectServerTool(s.projectId, s.name, tool, args)
125
+ });
126
+ }
127
+ for (const server of upstreams) {
106
128
  let externalTools;
107
129
  try {
108
- externalTools = await listExternalServerTools(server.slug);
130
+ externalTools = await server.list();
109
131
  } catch (error) {
110
- debug.warn('mcp', `Pi MCP bridge: could not list tools for "${server.slug}" (skipping):`, error);
132
+ debug.warn('mcp', `Pi MCP bridge: could not list tools for "${server.label}" (skipping):`, error);
111
133
  continue;
112
134
  }
113
135
  for (const tool of externalTools) {
@@ -119,7 +141,7 @@ export async function buildPiMcpTools(
119
141
  description: `${tool.description ?? tool.name}${schemaText}`,
120
142
  parameters: OPEN_PARAMS,
121
143
  execute: async (_toolCallId: string, params: unknown) => {
122
- const result = (await callExternalServerTool(server.slug, tool.name, params ?? {})) as { content?: unknown } | undefined;
144
+ const result = (await server.call(tool.name, params ?? {})) as { content?: unknown } | undefined;
123
145
  return { content: toPiContent(result?.content), details: {} };
124
146
  },
125
147
  } as ToolDefinition);
@@ -36,6 +36,9 @@ import { subagentQueries } from '$backend/database/queries';
36
36
  import { readSubagentMd } from '$backend/subagents/store';
37
37
  import { syncSkills } from '$backend/skills';
38
38
  import { syncEngineArtifacts } from '$backend/engine/artifact-sync';
39
+ import { resolveProjectBridge, buildProjectPromptContext } from '$backend/artifacts/project';
40
+ import { homedir } from 'node:os';
41
+ import { join, sep } from 'node:path';
39
42
  import { artifactFilter } from '$backend/profiles';
40
43
  import { resolvePermissionsFromDb, isToolAllowed } from '$backend/permissions';
41
44
  import { buildJsonPrompt, extractJson, emptyGenerationError } from '../../structured-helpers';
@@ -165,6 +168,13 @@ export class PiEngine implements AIEngine {
165
168
  await syncSkills('pi', profileId);
166
169
  await syncEngineArtifacts('pi', profileId);
167
170
 
171
+ // Repository artifacts Pi doesn't read natively (it reads `.pi/*`,
172
+ // `.agents/skills` and AGENTS.md itself): skills go in as extra skill
173
+ // paths, instructions as an appended system prompt, subagents join the
174
+ // dispatch tool below.
175
+ const projectBridge = await resolveProjectBridge('pi', resolvedProjectPath, options.mcpContext?.projectId);
176
+ const projectInstructions = buildProjectPromptContext(projectBridge, { instructions: true });
177
+
168
178
  // ── Permissions (enforced at the `tool_call` extension hook) ──
169
179
  const permissions = resolvePermissionsFromDb('pi', options.mcpContext?.projectId, profileId);
170
180
  const permissionBlocker = (pi: ExtensionAPI) => {
@@ -194,13 +204,24 @@ export class PiEngine implements AIEngine {
194
204
  // Subagent dispatch — Pi has no native Agent tool, so materialising the
195
205
  // "Available Subagents" preamble isn't enough; expose a tool that actually
196
206
  // spawns a sub-session with the chosen subagent's system prompt.
197
- const subagents: SubagentInfo[] = subagentQueries.getEnabled().map((s) => ({ slug: s.slug, name: s.name, description: s.description }));
207
+ // Project subagents Pi can't read natively (`.agents/agents`, `.claude/agents`,
208
+ // …) join the same dispatch tool; an installed subagent wins a slug clash.
209
+ const installedSubagents = subagentQueries.getEnabled();
210
+ const installedSlugs = new Set(installedSubagents.map((s) => s.slug));
211
+ const projectSubagents = new Map(projectBridge.subagents.filter((s) => !installedSlugs.has(s.slug)).map((s) => [s.slug, s]));
212
+ const subagents: SubagentInfo[] = [
213
+ ...installedSubagents.map((s) => ({ slug: s.slug, name: s.name, description: s.description })),
214
+ ...[...projectSubagents.values()].map((s) => ({ slug: s.slug, name: s.name, description: s.description })),
215
+ ];
198
216
  if (subagents.length > 0) {
199
217
  const agentTool = createAgentDispatchTool({
200
218
  subagents,
201
219
  run: async (subagent, subPrompt, toolCallId, signal) => {
202
- const md = (await readSubagentMd(subagent.slug)) ?? '';
203
- const instructions = stripFrontmatter(md) || `You are the ${subagent.name} subagent. ${subagent.description}`;
220
+ const projectSubagent = projectSubagents.get(subagent.slug);
221
+ const md = projectSubagent ? '' : ((await readSubagentMd(subagent.slug)) ?? '');
222
+ const instructions = projectSubagent?.prompt
223
+ || stripFrontmatter(md)
224
+ || `You are the ${subagent.name} subagent. ${subagent.description}`;
204
225
  // APPEND the subagent instructions to Pi's base coding prompt —
205
226
  // replacing it wholesale strips the tool-use scaffolding and the
206
227
  // sub-agent then produces nothing. Keep the sub-session bounded:
@@ -264,10 +285,21 @@ export class PiEngine implements AIEngine {
264
285
  }
265
286
 
266
287
  // ── Resource loader (discovers synced skills/prompts/AGENTS.md) ──
288
+ // Pi also scans the REAL `~/.agents/skills` (via $HOME, with no override),
289
+ // which leaks the user's personal CLI skills past Clopen's per-engine
290
+ // isolation. Drop anything loaded from there; project `.agents/skills`
291
+ // and Clopen's own synced dir are unaffected.
292
+ const userAgentsSkillsDir = join(process.env.HOME || homedir(), '.agents', 'skills') + sep;
267
293
  const resourceLoader = new DefaultResourceLoader({
268
294
  cwd: resolvedProjectPath,
269
295
  agentDir,
270
296
  extensionFactories: [permissionBlocker],
297
+ ...(projectBridge.skills.length > 0 && { additionalSkillPaths: projectBridge.skills.map((s) => s.skillMd) }),
298
+ ...(projectInstructions && { appendSystemPrompt: [projectInstructions] }),
299
+ skillsOverride: (base) => ({
300
+ ...base,
301
+ skills: base.skills.filter((skill) => !skill.filePath.startsWith(userAgentsSkillsDir)),
302
+ }),
271
303
  });
272
304
  await resourceLoader.reload();
273
305
 
@@ -51,6 +51,7 @@ import { EngineRuns } from '../run-registry';
51
51
  import { artifactFilter } from '$backend/profiles';
52
52
  import { syncSkills } from '$backend/skills';
53
53
  import { syncEngineArtifacts } from '$backend/engine/artifact-sync';
54
+ import { resolveProjectBridge, buildProjectPromptContext } from '$backend/artifacts/project';
54
55
  import { resolvePermissionsFromDb, isToolAllowed, excludedBuiltinTools } from '$backend/permissions';
55
56
  import { forkQwenSessionState, sessionStateExists } from './session-fork';
56
57
 
@@ -165,6 +166,12 @@ export class QwenEngine implements AIEngine {
165
166
  await syncSkills('qwen', profileId);
166
167
  await syncEngineArtifacts('qwen', profileId);
167
168
  const mcpConfig = getQwenMcpConfig(mcpProfileFilter, options.mcpContext);
169
+ // Repository artifacts Qwen doesn't read natively (it reads `.qwen/*`,
170
+ // QWEN.md and AGENTS.md itself) — appended to its preset system prompt,
171
+ // which is per query. Qwen has no delegation surface Clopen can register
172
+ // with, so project subagents are never advertised to it.
173
+ const projectBridge = await resolveProjectBridge('qwen', resolvedProjectPath, options.mcpContext?.projectId);
174
+ const projectContext = buildProjectPromptContext(projectBridge, { skills: true, instructions: true });
168
175
 
169
176
  // Resolve the permission policy once per stream; canUseTool enforces it
170
177
  // (Qwen otherwise auto-allows everything). Tool names arrive snake_cased.
@@ -313,6 +320,7 @@ export class QwenEngine implements AIEngine {
313
320
  // Auto-allow everything else.
314
321
  return { behavior: 'allow' as const, updatedInput: input };
315
322
  },
323
+ ...(projectContext ? { systemPrompt: { type: 'preset' as const, preset: 'qwen_code' as const, append: projectContext } } : {}),
316
324
  ...(maxTurns !== undefined ? { maxSessionTurns: maxTurns } : {}),
317
325
  ...(resumeId ? { resume: resumeId } : {}),
318
326
  ...(Object.keys(mcpConfig).length > 0 ? { mcpServers: mcpConfig } : {}),
@@ -7,9 +7,10 @@
7
7
  * the features share the exact same trigger point without each adapter growing
8
8
  * separate calls.
9
9
  *
10
- * GLOBAL scope only: writing project-scoped instructions into a repo's
11
- * `CLAUDE.md` / `AGENTS.md` touches the working tree, which the project's rules
12
- * require to be an explicit, user-visible action — never silent at stream start.
10
+ * GLOBAL scope only: nothing here writes into a repository. A project's own
11
+ * artifacts reach the engine through the per-stream project bridge
12
+ * (`backend/artifacts/project/bridge.ts`), and edits to repo files are explicit
13
+ * actions in Settings — never a side effect of starting a chat.
13
14
  * Each underlying sync swallows its own errors, so this never throws.
14
15
  */
15
16
 
@@ -17,6 +18,7 @@ import { syncSubagents, buildSubagentsPromptContext } from '$backend/subagents';
17
18
  import { syncInstructions, buildInstructionsPromptContext } from '$backend/instructions';
18
19
  import { buildSkillsPromptContext, stripLegacyCommandArtifacts } from '$backend/skills';
19
20
  import { readsGlobalMemoryFile, type ArtifactEngine } from '$backend/artifacts';
21
+ import { buildProjectPromptContext, type ProjectBridge } from '$backend/artifacts/project';
20
22
 
21
23
  export async function syncEngineArtifacts(engine: ArtifactEngine, profileId?: number): Promise<void> {
22
24
  // Sequential, NOT Promise.all: on synthetic engines (Codex/OpenCode) these
@@ -47,11 +49,16 @@ export async function syncEngineArtifacts(engine: ArtifactEngine, profileId?: nu
47
49
  * same thing twice. Cline and Cursor read no such file — for them the prompt is
48
50
  * the ONLY channel, and before this parameter existed their Instructions were
49
51
  * written to a file nothing opened and silently never applied.
52
+ *
53
+ * `project` appends the repository's bridged artifacts (see
54
+ * `resolveProjectBridge`) — only what this engine can't read from the repo.
50
55
  */
51
- export function buildArtifactsPromptContext(engine: ArtifactEngine, profileId?: number): string {
56
+ export function buildArtifactsPromptContext(engine: ArtifactEngine, profileId?: number, project?: ProjectBridge): string {
52
57
  return [
53
58
  readsGlobalMemoryFile(engine) ? '' : buildInstructionsPromptContext(),
54
59
  buildSkillsPromptContext(profileId),
55
- buildSubagentsPromptContext(engine, profileId)
60
+ buildSubagentsPromptContext(engine, profileId),
61
+ // The repository's own artifacts this engine doesn't read natively.
62
+ project ? buildProjectPromptContext(project) : ''
56
63
  ].filter(Boolean).join('\n\n');
57
64
  }
@@ -149,6 +149,83 @@ describe('FileWatcherManager', () => {
149
149
  expect(paths.some((p) => p.includes('.git'))).toBe(false);
150
150
  });
151
151
 
152
+ test('reports changes inside dot-directories people and agents edit', async () => {
153
+ // `.agents/` is written by Settings → Artifacts; ignoring every dot path
154
+ // left the explorer stale until a reload while root `AGENTS.md` updated live.
155
+ const root = await makeProject();
156
+ await mkdir(join(root, '.agents', 'skills', 'demo'), { recursive: true });
157
+ expect(await fileWatcher.startWatching('p10', root)).toBe(true);
158
+ // Let the mkdir's own event drain first, or the platform watcher folds the
159
+ // write into it and reports only `.agents`.
160
+ await new Promise((r) => setTimeout(r, 400));
161
+
162
+ await writeFile(join(root, '.agents', 'skills', 'demo', 'SKILL.md'), '---\nname: demo\n---\n');
163
+
164
+ await waitFor(() => changesFor('p10').some((p) => p.endsWith('SKILL.md')));
165
+ });
166
+
167
+ test('never reports changes inside heavy dot-directories', async () => {
168
+ const root = await makeProject();
169
+ await mkdir(join(root, '.venv', 'lib'), { recursive: true });
170
+ expect(await fileWatcher.startWatching('p11', root)).toBe(true);
171
+
172
+ await writeFile(join(root, '.venv', 'lib', 'site.py'), '# noise');
173
+ await writeFile(join(root, '.notes.md.swp'), 'swap');
174
+ // Spaced out for the same reason as the ignored-directories test above.
175
+ await new Promise((r) => setTimeout(r, 400));
176
+
177
+ await writeFile(join(root, 'app.ts'), 'export {}');
178
+ await waitFor(() => changesFor('p11').some((p) => p.endsWith('app.ts')));
179
+
180
+ const paths = changesFor('p11');
181
+ expect(paths.some((p) => p.includes('.venv'))).toBe(false);
182
+ expect(paths.some((p) => p.endsWith('.swp'))).toBe(false);
183
+ });
184
+
185
+ test('ignores output recognised by its manifest or its contents, not by name', async () => {
186
+ const root = await makeProject();
187
+ await writeFile(join(root, 'Cargo.toml'), '[package]');
188
+ await mkdir(join(root, 'target', 'debug'), { recursive: true });
189
+ await mkdir(join(root, 'myenv', 'lib'), { recursive: true });
190
+ await writeFile(join(root, 'myenv', 'pyvenv.cfg'), 'home = /usr/bin');
191
+ // No `.csproj` here, so `bin/` is source (as Clopen's own is).
192
+ await mkdir(join(root, 'bin'), { recursive: true });
193
+ expect(await fileWatcher.startWatching('p12', root)).toBe(true);
194
+ await new Promise((r) => setTimeout(r, 400));
195
+
196
+ await writeFile(join(root, 'target', 'debug', 'app'), 'binary');
197
+ await new Promise((r) => setTimeout(r, 400));
198
+ await writeFile(join(root, 'myenv', 'lib', 'site.py'), '# noise');
199
+ await new Promise((r) => setTimeout(r, 400));
200
+
201
+ await writeFile(join(root, 'bin', 'cli.ts'), 'export {}');
202
+ await waitFor(() => changesFor('p12').some((p) => p.endsWith('cli.ts')));
203
+
204
+ const paths = changesFor('p12');
205
+ expect(paths.some((p) => p.includes(join('target', 'debug')))).toBe(false);
206
+ expect(paths.some((p) => p.includes(join('myenv', 'lib')))).toBe(false);
207
+ });
208
+
209
+ test('stops reporting a directory once it declares itself a cache', async () => {
210
+ const root = await makeProject();
211
+ await mkdir(join(root, 'scratch'), { recursive: true });
212
+ expect(await fileWatcher.startWatching('p13', root)).toBe(true);
213
+ await new Promise((r) => setTimeout(r, 400));
214
+
215
+ await writeFile(join(root, 'scratch', 'before.txt'), 'seen');
216
+ await waitFor(() => changesFor('p13').some((p) => p.endsWith('before.txt')));
217
+
218
+ await writeFile(join(root, 'scratch', 'CACHEDIR.TAG'), 'Signature: 8a477f597d28d172789f06886806bc55');
219
+ await new Promise((r) => setTimeout(r, 400));
220
+ await writeFile(join(root, 'scratch', 'after.txt'), 'noise');
221
+ await new Promise((r) => setTimeout(r, 400));
222
+
223
+ await writeFile(join(root, 'app.ts'), 'export {}');
224
+ await waitFor(() => changesFor('p13').some((p) => p.endsWith('app.ts')));
225
+
226
+ expect(changesFor('p13').some((p) => p.endsWith('after.txt'))).toBe(false);
227
+ });
228
+
152
229
  test('does not emit an empty change list', async () => {
153
230
  const root = await makeProject();
154
231
  expect(await fileWatcher.startWatching('p4', root)).toBe(true);
@@ -23,6 +23,9 @@
23
23
  * a file change, made clients reload every few seconds with nothing actually
24
24
  * changing. So on Linux we walk the tree ourselves and never watch an ignored
25
25
  * directory, which removes the overwhelming majority of the watch descriptors.
26
+ *
27
+ * What counts as ignored — by name, by manifest, by signature — lives in
28
+ * `watch-ignore.ts`.
26
29
  */
27
30
 
28
31
  /** Whether the platform's recursive `fs.watch` is a single cheap OS handle. */
@@ -30,7 +33,7 @@ const USE_NATIVE_RECURSIVE_WATCH = process.platform !== 'linux';
30
33
 
31
34
  import { watch, type FSWatcher, existsSync } from 'node:fs';
32
35
  import { stat, readdir } from 'node:fs/promises';
33
- import { join, relative, normalize, sep } from 'node:path';
36
+ import { basename, dirname, join, relative, normalize, sep } from 'node:path';
34
37
  import { ws } from '$backend/utils/ws';
35
38
  import { debug } from '$shared/utils/logger';
36
39
  import { isScopeOfProject, scopeProjectId } from '$shared/utils/workspace-scope';
@@ -42,6 +45,13 @@ import {
42
45
  notifyPathChanged
43
46
  } from '$backend/git/nested-repos';
44
47
  import type { FileChange } from '$shared/types/filesystem';
48
+ import {
49
+ GeneratedDirClassifier,
50
+ isIgnoredPath,
51
+ isMarkableDirName,
52
+ isOutputMarker,
53
+ isSignatureEntry
54
+ } from './watch-ignore';
45
55
 
46
56
  /**
47
57
  * Debounce configuration
@@ -63,39 +73,6 @@ const RESTART_DELAYS_MS = [1000, 2000, 4000, 8000];
63
73
  /** How long a rebuilt watcher must survive before its fault count is forgiven. */
64
74
  const FAULT_FORGIVENESS_MS = 60_000;
65
75
 
66
- /**
67
- * Directories to ignore when watching
68
- */
69
- const IGNORED_DIRS = new Set([
70
- 'node_modules',
71
- '.git',
72
- '.svelte-kit',
73
- 'dist',
74
- 'build',
75
- '.next',
76
- '.nuxt',
77
- '.output',
78
- '__pycache__',
79
- '.pytest_cache',
80
- 'coverage',
81
- '.nyc_output',
82
- '.turbo',
83
- '.cache',
84
- '.temp',
85
- '.tmp',
86
- 'vendor'
87
- ]);
88
-
89
- /**
90
- * Files to ignore
91
- */
92
- const IGNORED_FILES = new Set([
93
- '.DS_Store',
94
- 'Thumbs.db',
95
- '.gitkeep',
96
- '.gitignore~'
97
- ]);
98
-
99
76
  /**
100
77
  * Entries inside a git directory that never change what the Git panel renders.
101
78
  *
@@ -185,6 +162,8 @@ interface ProjectWatcher {
185
162
  faults: number;
186
163
  /** Flipped by stopWatching so in-flight async tree walks bail out. */
187
164
  closed: boolean;
165
+ /** Cached "is this directory generated output" decisions (see watch-ignore). */
166
+ generated: GeneratedDirClassifier;
188
167
  /**
189
168
  * Every known git directory -> the working tree it belongs to. Covers the
190
169
  * project's own repo and each sub-repo, and is the attribution table for
@@ -228,15 +207,25 @@ class FileWatcherManager {
228
207
 
229
208
  /**
230
209
  * Per-project dirty file tracking for snapshot system.
231
- * Accumulates changed file relative paths between snapshot captures.
210
+ * Accumulates changed file relative paths between snapshot captures, with
211
+ * the time of each path's latest event.
232
212
  */
233
- private dirtyFiles = new Map<string, Set<string>>();
213
+ private dirtyFiles = new Map<string, Map<string, number>>();
234
214
 
235
215
  /**
236
216
  * Get dirty files accumulated since last clear for a project.
237
217
  */
238
218
  getDirtyFiles(projectId: string): Set<string> {
239
- return this.dirtyFiles.get(projectId) || new Set();
219
+ return new Set(this.dirtyFiles.get(projectId)?.keys() ?? []);
220
+ }
221
+
222
+ /**
223
+ * When the watcher last saw a path change (epoch ms), or undefined when it
224
+ * saw nothing — the only record of WHEN a file was deleted, since a deleted
225
+ * file has no mtime left to read.
226
+ */
227
+ getLastChangeAt(projectId: string, relativePath: string): number | undefined {
228
+ return this.dirtyFiles.get(projectId)?.get(relativePath);
240
229
  }
241
230
 
242
231
  /**
@@ -251,9 +240,9 @@ class FileWatcherManager {
251
240
  */
252
241
  private trackDirtyFile(projectId: string, relativePath: string): void {
253
242
  if (!this.dirtyFiles.has(projectId)) {
254
- this.dirtyFiles.set(projectId, new Set());
243
+ this.dirtyFiles.set(projectId, new Map());
255
244
  }
256
- this.dirtyFiles.get(projectId)!.add(relativePath);
245
+ this.dirtyFiles.get(projectId)!.set(relativePath, Date.now());
257
246
  }
258
247
 
259
248
  /**
@@ -347,6 +336,7 @@ class FileWatcherManager {
347
336
  truncated: false,
348
337
  faults,
349
338
  closed: false,
339
+ generated: new GeneratedDirClassifier(normalizedPath),
350
340
  gitDirOwners: new Map(),
351
341
  gitWatchers: new Map(),
352
342
  rejectedGitDirs: new Set(),
@@ -502,6 +492,7 @@ class FileWatcherManager {
502
492
  } catch {
503
493
  return; // Directory vanished or is unreadable — nothing to watch.
504
494
  }
495
+ const names = entries.map((entry) => entry.name);
505
496
 
506
497
  for (const entry of entries) {
507
498
  if (pw.closed) return;
@@ -509,12 +500,16 @@ class FileWatcherManager {
509
500
 
510
501
  const childPath = join(dir, entry.name);
511
502
  const relativePath = relative(pw.projectPath, childPath).replace(/\\/g, '/');
512
- if (this.shouldIgnore(relativePath)) {
503
+ if (isIgnoredPath(relativePath)) {
513
504
  if (announceGitDirs && entry.name === '.git') {
514
505
  this.routeGitEvent(pw, relativePath, childPath);
515
506
  }
516
507
  continue;
517
508
  }
509
+ // Output that is only recognisable by its manifest or its own contents
510
+ // (`target/` beside `Cargo.toml`, a virtualenv under any name).
511
+ if (await pw.generated.isGenerated(childPath, names)) continue;
512
+ if (pw.closed) return;
518
513
 
519
514
  if (!this.watchDir(pw, childPath)) {
520
515
  // Ceiling reached — stop descending entirely rather than watching an
@@ -641,19 +636,29 @@ class FileWatcherManager {
641
636
  if (relativePath.startsWith('..')) return;
642
637
 
643
638
  // Git metadata is not a working-tree change — it drives the Git panel
644
- // instead. This runs BEFORE `shouldIgnore`, which discards every `.git`
639
+ // instead. This runs BEFORE `isIgnoredPath`, which discards every `.git`
645
640
  // path: where the root watch is recursive it is the only thing that sees
646
641
  // a sub-repo's git dir, so dropping it here is what left a commit made
647
642
  // inside a nested repo completely unreported.
648
643
  // Tell sub-repo discovery before anything below filters the path away.
649
644
  // It decides for itself what a path means: `routeGitEvent` swallows every
650
- // `.git` path and `shouldIgnore` every dotfile, so `.gitignore` — which
651
- // moves the reported repo set — would otherwise never reach it.
645
+ // `.git` path, so `.git/info/exclude` — which moves the reported repo set
646
+ // just like `.gitignore` — would otherwise never reach it.
652
647
  notifyPathChanged(projectWatcher.projectPath, fullPath);
653
648
 
654
649
  if (this.routeGitEvent(projectWatcher, relativePath, fullPath)) return;
655
650
 
656
- if (this.shouldIgnore(relativePath)) return;
651
+ if (isIgnoredPath(relativePath)) return;
652
+
653
+ // A signature or manifest appearing or vanishing changes what counts as
654
+ // generated, so re-decide before judging this very event by it.
655
+ const entryName = basename(fullPath);
656
+ if (isSignatureEntry(entryName) || isOutputMarker(entryName)) {
657
+ this.reclassify(projectWatcher, entryName, dirname(fullPath));
658
+ }
659
+
660
+ if (await projectWatcher.generated.isInsideGenerated(relativePath)) return;
661
+ if (projectWatcher.closed) return;
657
662
 
658
663
  // Determine change type
659
664
  let changeType: 'created' | 'modified' | 'deleted';
@@ -676,7 +681,7 @@ class FileWatcherManager {
676
681
  // descendants' watchers so they can't leak.
677
682
  if (!USE_NATIVE_RECURSIVE_WATCH) {
678
683
  if (isDirectory && changeType === 'created') {
679
- if (this.watchDir(projectWatcher, fullPath)) {
684
+ if (!(await projectWatcher.generated.isGenerated(fullPath)) && this.watchDir(projectWatcher, fullPath)) {
680
685
  // Announce pruned git dirs: this subtree existed before we could
681
686
  // watch it, so anything already inside it emitted no event.
682
687
  void this.watchSubtree(projectWatcher, fullPath, true);
@@ -685,6 +690,7 @@ class FileWatcherManager {
685
690
  this.unwatchDir(projectWatcher, fullPath);
686
691
  }
687
692
  }
693
+ if (changeType === 'deleted') projectWatcher.generated.forgetTree(fullPath);
688
694
 
689
695
  // Track dirty file for snapshot system
690
696
  this.trackDirtyFile(projectId, relativePath);
@@ -710,25 +716,51 @@ class FileWatcherManager {
710
716
  }
711
717
 
712
718
  /**
713
- * Check if a file/directory should be ignored
719
+ * Re-decide the directories a signature or manifest describes: its parent
720
+ * for a signature (`CACHEDIR.TAG`, `pyvenv.cfg`), the output-named siblings
721
+ * for a manifest (`Cargo.toml` → `target/`). The cached decisions are dropped
722
+ * synchronously so the triggering event is already judged by the new state.
723
+ *
724
+ * Where recursion is emulated the watch set follows: a directory that just
725
+ * became generated releases its handles, and one that stopped being generated
726
+ * (its manifest was deleted) is walked and watched like a new directory.
714
727
  */
715
- private shouldIgnore(filename: string): boolean {
716
- const parts = filename.split('/');
717
-
718
- // Check each path segment
719
- for (const part of parts) {
720
- if (IGNORED_DIRS.has(part) || IGNORED_FILES.has(part)) {
721
- return true;
722
- }
723
- // Ignore hidden files and directories (except .env files)
724
- if (part.startsWith('.') && !part.startsWith('.env')) {
725
- return true;
728
+ private reclassify(pw: ProjectWatcher, entryName: string, parentDir: string): void {
729
+ const signature = isSignatureEntry(entryName);
730
+ if (signature) pw.generated.forget(parentDir);
731
+ const manifest = isOutputMarker(entryName);
732
+ if (manifest) pw.generated.forgetMarkableChildren(parentDir);
733
+ if (USE_NATIVE_RECURSIVE_WATCH) return;
734
+
735
+ void (async () => {
736
+ const dirs: string[] = signature ? [parentDir] : [];
737
+ if (manifest) {
738
+ try {
739
+ const entries = await readdir(parentDir, { withFileTypes: true });
740
+ for (const entry of entries) {
741
+ if (entry.isDirectory() && isMarkableDirName(entry.name)) dirs.push(join(parentDir, entry.name));
742
+ }
743
+ } catch {
744
+ // The directory went away; its own deletion event cleans up.
745
+ }
726
746
  }
727
- }
728
-
729
- return false;
747
+ for (const dir of dirs) await this.syncWatchState(pw, dir);
748
+ })();
730
749
  }
731
750
 
751
+ /** Linux only: make `dir`'s watch match its current generated decision. */
752
+ private async syncWatchState(pw: ProjectWatcher, dir: string): Promise<void> {
753
+ if (dir === pw.projectPath) return;
754
+ const generated = await pw.generated.isGenerated(dir);
755
+ if (pw.closed) return;
756
+ if (generated) {
757
+ if (pw.dirWatchers.has(dir)) this.unwatchDir(pw, dir);
758
+ return;
759
+ }
760
+ const relativePath = relative(pw.projectPath, dir).replace(/\\/g, '/');
761
+ if (pw.dirWatchers.has(dir) || !pw.dirWatchers.has(dirname(dir)) || isIgnoredPath(relativePath)) return;
762
+ if (this.watchDir(pw, dir)) void this.watchSubtree(pw, dir, true);
763
+ }
732
764
 
733
765
  /**
734
766
  * Flush pending changes to clients