@myrialabs/clopen 0.4.44 → 0.4.46

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 (118) 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/models.test.ts +49 -0
  15. package/backend/engine/adapters/claude/models.ts +81 -562
  16. package/backend/engine/adapters/claude/stream.ts +32 -5
  17. package/backend/engine/adapters/cline/credential.ts +42 -18
  18. package/backend/engine/adapters/cline/mcp-tools.ts +26 -4
  19. package/backend/engine/adapters/cline/message-converter.ts +31 -1
  20. package/backend/engine/adapters/cline/models.test.ts +77 -0
  21. package/backend/engine/adapters/cline/models.ts +89 -3
  22. package/backend/engine/adapters/cline/presets.ts +5 -0
  23. package/backend/engine/adapters/cline/stream.ts +29 -8
  24. package/backend/engine/adapters/codex/message-converter.ts +1 -1
  25. package/backend/engine/adapters/codex/models.ts +54 -31
  26. package/backend/engine/adapters/codex/patch-rollout.test.ts +36 -1
  27. package/backend/engine/adapters/codex/patch-rollout.ts +60 -29
  28. package/backend/engine/adapters/codex/session-fork.ts +5 -0
  29. package/backend/engine/adapters/codex/stream.ts +29 -11
  30. package/backend/engine/adapters/copilot/models.test.ts +40 -0
  31. package/backend/engine/adapters/copilot/models.ts +51 -24
  32. package/backend/engine/adapters/copilot/permissions.test.ts +47 -0
  33. package/backend/engine/adapters/copilot/permissions.ts +72 -0
  34. package/backend/engine/adapters/copilot/stream.ts +83 -70
  35. package/backend/engine/adapters/cursor/stream.ts +27 -12
  36. package/backend/engine/adapters/opencode/server.ts +14 -4
  37. package/backend/engine/adapters/opencode/stream.ts +18 -3
  38. package/backend/engine/adapters/pi/credential.test.ts +83 -0
  39. package/backend/engine/adapters/pi/credential.ts +68 -12
  40. package/backend/engine/adapters/pi/environment.ts +9 -5
  41. package/backend/engine/adapters/pi/mcp.test.ts +194 -0
  42. package/backend/engine/adapters/pi/mcp.ts +88 -0
  43. package/backend/engine/adapters/pi/message-converter.ts +6 -4
  44. package/backend/engine/adapters/pi/presets.ts +10 -5
  45. package/backend/engine/adapters/pi/stream.ts +77 -41
  46. package/backend/engine/adapters/qwen/environment.ts +39 -2
  47. package/backend/engine/adapters/qwen/message-converter.test.ts +64 -0
  48. package/backend/engine/adapters/qwen/message-converter.ts +40 -23
  49. package/backend/engine/adapters/qwen/models.test.ts +25 -0
  50. package/backend/engine/adapters/qwen/models.ts +42 -5
  51. package/backend/engine/adapters/qwen/session-store.test.ts +39 -0
  52. package/backend/engine/adapters/qwen/session-store.ts +66 -0
  53. package/backend/engine/adapters/qwen/stream.ts +118 -87
  54. package/backend/engine/artifact-sync.ts +12 -5
  55. package/backend/engine/docs/adapter-contract.md +7 -4
  56. package/backend/engine/docs/lessons-learned.md +405 -62
  57. package/backend/engine/docs/quick-reference.md +2 -2
  58. package/backend/engine/docs/stack.md +17 -4
  59. package/backend/engine/docs/websocket-routes.md +5 -5
  60. package/backend/engine/install-recipes.test.ts +105 -5
  61. package/backend/engine/install-recipes.ts +102 -42
  62. package/backend/engine/install-runner.ts +56 -2
  63. package/backend/engine/stack-project.ts +71 -1
  64. package/backend/files/file-watcher.test.ts +77 -0
  65. package/backend/files/file-watcher.ts +92 -60
  66. package/backend/files/watch-ignore.test.ts +182 -0
  67. package/backend/files/watch-ignore.ts +244 -0
  68. package/backend/git/git-executor.ts +14 -4
  69. package/backend/index.ts +16 -1
  70. package/backend/instructions/service.ts +5 -3
  71. package/backend/instructions/sync.ts +10 -27
  72. package/backend/mcp/README.md +2 -2
  73. package/backend/mcp/external/config.ts +83 -23
  74. package/backend/mcp/external/project.ts +124 -0
  75. package/backend/mcp/external/proxy.ts +65 -11
  76. package/backend/mcp/index.ts +22 -9
  77. package/backend/mcp/internal/config.ts +42 -3
  78. package/backend/mcp/internal/remote-server.ts +11 -1
  79. package/backend/memory/embedding/install.ts +29 -1
  80. package/backend/skills/marketplace.ts +1 -1
  81. package/backend/snapshot/blob-store.ts +9 -5
  82. package/backend/snapshot/git-attribution.test.ts +42 -0
  83. package/backend/snapshot/git-attribution.ts +306 -0
  84. package/backend/snapshot/gitignore.test.ts +62 -0
  85. package/backend/snapshot/gitignore.ts +158 -78
  86. package/backend/snapshot/snapshot-service.test.ts +270 -0
  87. package/backend/snapshot/snapshot-service.ts +412 -136
  88. package/backend/snapshot/turn-activity.test.ts +52 -0
  89. package/backend/snapshot/turn-activity.ts +83 -0
  90. package/backend/snapshot/turn-changes.test.ts +58 -1
  91. package/backend/snapshot/turn-changes.ts +66 -0
  92. package/backend/utils/keyed-lock.test.ts +33 -0
  93. package/backend/utils/keyed-lock.ts +17 -0
  94. package/backend/utils/port-utils.test.ts +29 -0
  95. package/backend/utils/port-utils.ts +19 -0
  96. package/backend/worktrees/tree.ts +1 -1
  97. package/backend/ws/chat/composer.ts +504 -0
  98. package/backend/ws/chat/index.ts +3 -1
  99. package/backend/ws/chat/stream.ts +252 -440
  100. package/backend/ws/engine/cline/accounts.ts +26 -6
  101. package/backend/ws/engine/codex/accounts.test.ts +49 -0
  102. package/backend/ws/engine/codex/accounts.ts +17 -13
  103. package/backend/ws/engine/pi/accounts.ts +61 -6
  104. package/backend/ws/index.ts +4 -0
  105. package/backend/ws/project-artifacts/index.ts +236 -0
  106. package/backend/ws/snapshot/changes.ts +66 -31
  107. package/dist/assets/{index-DX5OwLOc.js → index-BTcR1byF.js} +1 -1
  108. package/dist/assets/{index-BWyhqUi5.js → index-CwuKQelV.js} +1 -1
  109. package/dist/assets/main-BiDNMWb3.css +1 -0
  110. package/dist/assets/main-BlhKWz2B.js +1241 -0
  111. package/dist/index.html +2 -2
  112. package/package.json +19 -15
  113. package/shared/types/stores/settings.ts +5 -0
  114. package/shared/types/unified/message.ts +2 -0
  115. package/backend/engine/adapters/pi/mcp-tools.ts +0 -131
  116. package/backend/engine/adapters/qwen/session-fork.ts +0 -109
  117. package/dist/assets/main-DOkwqXRU.js +0 -1215
  118. package/dist/assets/main-DzCY0n-j.css +0 -1
@@ -9,10 +9,12 @@
9
9
  */
10
10
 
11
11
  import fs from 'fs/promises';
12
+ import type { Dirent } from 'fs';
12
13
  import path from 'path';
13
14
  import { debug } from '$shared/utils/logger';
14
15
  import { execGit } from '../git/git-executor';
15
16
  import { findNestedRepoPaths } from '../git/nested-repos';
17
+ import { hasGeneratedSignature, isIgnoredName, isMarkedOutputDir } from '../files/watch-ignore';
16
18
 
17
19
  /**
18
20
  * Safety-net directories to always exclude regardless of .gitignore.
@@ -24,26 +26,61 @@ const ALWAYS_EXCLUDE_DIRS = new Set([
24
26
  ]);
25
27
 
26
28
 
29
+ /**
30
+ * The result of a scan, including what it could NOT see.
31
+ *
32
+ * `incomplete` lists the project-relative directories (with a trailing slash,
33
+ * or '' for the whole project) whose listing failed. That distinction is load
34
+ * bearing for snapshots: a file that was not listed because its directory
35
+ * could not be read is not a deleted file, and treating it as one recorded
36
+ * deletions that a later restore would then carry out on a perfectly healthy
37
+ * file.
38
+ */
39
+ export interface SnapshotScan {
40
+ files: string[];
41
+ incomplete: string[];
42
+ }
43
+
44
+ export interface SnapshotScanOptions {
45
+ /**
46
+ * Skip generated directories (dependency stores, build output, caches) in
47
+ * projects that have no git to say what is ignored. Uses the same layered
48
+ * policy as the file watcher, so the two agree on what "generated" means.
49
+ * Git projects are unaffected: `.gitignore` is the authority there.
50
+ */
51
+ pruneGenerated?: boolean;
52
+ }
53
+
27
54
  /**
28
55
  * Get list of snapshot-eligible files using git (preferred) or manual scan.
29
- * Returns full absolute paths.
56
+ * Returns full absolute paths. Unreadable parts are silently left out — use
57
+ * {@link scanSnapshotFiles} when the difference between "absent" and "not
58
+ * seen" matters.
30
59
  */
31
60
  export async function getSnapshotFiles(projectPath: string): Promise<string[]> {
61
+ return (await scanSnapshotFiles(projectPath)).files;
62
+ }
63
+
64
+ /** Scan snapshot-eligible files and report which parts could not be read. */
65
+ export async function scanSnapshotFiles(
66
+ projectPath: string,
67
+ options: SnapshotScanOptions = {}
68
+ ): Promise<SnapshotScan> {
32
69
  // Try git-based scan first (handles all .gitignore rules perfectly)
33
- const gitFiles = await scanWithGit(projectPath);
34
- if (gitFiles !== null) {
35
- return gitFiles;
70
+ const gitScan = await scanWithGit(projectPath);
71
+ if (gitScan !== null) {
72
+ return gitScan;
36
73
  }
37
74
 
38
75
  // Fallback: manual scan with .gitignore parsing
39
- return scanWithGitignoreParsing(projectPath);
76
+ return scanWithGitignoreParsing(projectPath, options);
40
77
  }
41
78
 
42
79
  // ============================================================================
43
80
  // Strategy 1: Git-based scanning
44
81
  // ============================================================================
45
82
 
46
- async function scanWithGit(dirPath: string): Promise<string[] | null> {
83
+ async function scanWithGit(dirPath: string): Promise<SnapshotScan | null> {
47
84
  // Check if this is a git repo
48
85
  try {
49
86
  await fs.access(path.join(dirPath, '.git'));
@@ -51,58 +88,69 @@ async function scanWithGit(dirPath: string): Promise<string[] | null> {
51
88
  return null;
52
89
  }
53
90
 
91
+ let files: string[];
54
92
  try {
55
93
  // Scan the outer repo
56
- const files = await scanSingleGitRepo(dirPath);
57
-
58
- // Find and scan nested git repos — separate repositories living inside
59
- // the project (e.g. a theme extracted into its own repo). The parent
60
- // repo's `git ls-files --exclude-standard` skips these because git treats
61
- // a nested repo as a single gitlink entry (or excludes it entirely when
62
- // it's listed in the parent's .gitignore). Without this step, files
63
- // inside nested repos are invisible to the snapshot system, so AI
64
- // changes to them never appear in the checkpoint banner.
65
- const nestedFiles = await findAndScanNestedRepos(dirPath);
66
-
67
- const allFiles = [...files, ...nestedFiles];
68
- debug.log('snapshot', `Git scan found ${allFiles.length} files (${files.length} outer, ${nestedFiles.length} nested)`);
69
- return allFiles;
94
+ files = await scanSingleGitRepo(dirPath);
70
95
  } catch (err) {
71
- debug.warn('snapshot', 'git ls-files failed, falling back to manual scan:', err);
72
- return null;
96
+ // Deliberately NOT a fallback to the manual scan: its ignore semantics
97
+ // differ from git's, so switching strategy mid-session would report
98
+ // every file the two disagree on as added or deleted.
99
+ debug.warn('snapshot', 'git ls-files failed for the project root:', err);
100
+ return { files: [], incomplete: [''] };
73
101
  }
102
+
103
+ // Find and scan nested git repos — separate repositories living inside
104
+ // the project (e.g. a theme extracted into its own repo). The parent
105
+ // repo's `git ls-files --exclude-standard` skips these because git treats
106
+ // a nested repo as a single gitlink entry (or excludes it entirely when
107
+ // it's listed in the parent's .gitignore). Without this step, files
108
+ // inside nested repos are invisible to the snapshot system, so AI
109
+ // changes to them never appear in the checkpoint banner.
110
+ const nested = await findAndScanNestedRepos(dirPath);
111
+
112
+ const allFiles = [...files, ...nested.files];
113
+ debug.log('snapshot', `Git scan found ${allFiles.length} files (${files.length} outer, ${nested.files.length} nested)`);
114
+ return { files: allFiles, incomplete: nested.incomplete };
74
115
  }
75
116
 
76
117
  /**
77
- * Run `git ls-files -co --exclude-standard` in a single git repo and return
118
+ * Run `git ls-files -z -co --exclude-standard` in a single git repo and return
78
119
  * absolute paths. Used for both the outer repo and nested repos.
120
+ *
121
+ * Throws when git cannot answer. An empty list would be indistinguishable from
122
+ * a repository whose every file was just deleted.
79
123
  */
80
124
  async function scanSingleGitRepo(dirPath: string): Promise<string[]> {
81
- try {
82
- const result = await execGit(['ls-files', '-co', '--exclude-standard'], dirPath, 60_000);
83
- if (result.exitCode !== 0) return [];
125
+ // -z: without it git C-quotes any path with a non-ASCII byte
126
+ // ("caf\303\251.ts"), which then names no file on disk.
127
+ const result = await execGit(['ls-files', '-z', '-co', '--exclude-standard'], dirPath, 60_000);
128
+ if (result.exitCode !== 0) {
129
+ throw new Error(`git ls-files exited ${result.exitCode}: ${result.stderr.trim()}`);
130
+ }
84
131
 
85
- const files: string[] = [];
86
- for (const line of result.stdout.split('\n')) {
87
- const relativePath = line.trim();
88
- if (!relativePath) continue;
132
+ const files: string[] = [];
133
+ for (const relativePath of result.stdout.split('\0')) {
134
+ if (!relativePath) continue;
89
135
 
90
- // Skip always-excluded directories
91
- const firstSegment = relativePath.split('/')[0];
92
- if (ALWAYS_EXCLUDE_DIRS.has(firstSegment)) continue;
136
+ // Skip always-excluded directories
137
+ const firstSegment = relativePath.split('/')[0];
138
+ if (ALWAYS_EXCLUDE_DIRS.has(firstSegment)) continue;
93
139
 
94
- // Skip directory entries — git emits nested repos as a single
95
- // entry with a trailing slash (e.g. `theme/`). These are handled
96
- // by findAndScanNestedRepos, not here.
97
- if (relativePath.endsWith('/')) continue;
140
+ // Skip directory entries — git emits nested repos as a single
141
+ // entry with a trailing slash (e.g. `theme/`). These are handled
142
+ // by findAndScanNestedRepos, not here.
143
+ if (relativePath.endsWith('/')) continue;
98
144
 
99
- files.push(path.join(dirPath, relativePath));
100
- }
101
- return files;
102
- } catch (err) {
103
- debug.warn('snapshot', `git ls-files failed for ${dirPath}:`, err);
104
- return [];
145
+ files.push(path.join(dirPath, relativePath));
105
146
  }
147
+ return files;
148
+ }
149
+
150
+ /** A directory as an `incomplete` entry: project-relative, trailing slash. */
151
+ function incompleteEntry(rootPath: string, dirPath: string): string {
152
+ const relative = path.relative(rootPath, dirPath).replace(/\\/g, '/');
153
+ return relative ? `${relative}/` : '';
106
154
  }
107
155
 
108
156
  /**
@@ -113,12 +161,18 @@ async function scanSingleGitRepo(dirPath: string): Promise<string[]> {
113
161
  * is then scanned with its own `git ls-files --exclude-standard`, which applies
114
162
  * that repo's .gitignore rules.
115
163
  */
116
- async function findAndScanNestedRepos(rootPath: string): Promise<string[]> {
164
+ async function findAndScanNestedRepos(rootPath: string): Promise<SnapshotScan> {
117
165
  const files: string[] = [];
166
+ const incomplete: string[] = [];
118
167
  for (const repoPath of await findNestedRepoPaths(rootPath)) {
119
- files.push(...await scanSingleGitRepo(repoPath));
168
+ try {
169
+ files.push(...await scanSingleGitRepo(repoPath));
170
+ } catch (err) {
171
+ debug.warn('snapshot', `git ls-files failed for nested repo ${repoPath}:`, err);
172
+ incomplete.push(incompleteEntry(rootPath, repoPath));
173
+ }
120
174
  }
121
- return files;
175
+ return { files, incomplete };
122
176
  }
123
177
 
124
178
  // ============================================================================
@@ -304,58 +358,84 @@ class GitignoreFilter {
304
358
  /**
305
359
  * Scan directory manually, parsing .gitignore files at each level.
306
360
  */
307
- async function scanWithGitignoreParsing(projectPath: string): Promise<string[]> {
361
+ async function scanWithGitignoreParsing(
362
+ projectPath: string,
363
+ options: SnapshotScanOptions
364
+ ): Promise<SnapshotScan> {
308
365
  const files: string[] = [];
366
+ const incomplete: string[] = [];
309
367
  const filter = new GitignoreFilter();
310
368
 
311
369
  // Load root .gitignore
312
370
  await filter.loadFromFile(path.join(projectPath, '.gitignore'), '');
313
371
 
314
372
  const scan = async (currentPath: string): Promise<void> => {
373
+ let entries: Dirent[];
315
374
  try {
316
- const entries = await fs.readdir(currentPath, { withFileTypes: true });
317
- const relativeDir = path.relative(projectPath, currentPath).replace(/\\/g, '/');
375
+ entries = await fs.readdir(currentPath, { withFileTypes: true });
376
+ } catch (err) {
377
+ debug.warn('snapshot', `Could not read directory ${currentPath}:`, err);
378
+ incomplete.push(incompleteEntry(projectPath, currentPath));
379
+ return;
380
+ }
318
381
 
319
- // Load .gitignore in this directory (if not root - root already loaded)
320
- if (relativeDir) {
321
- await filter.loadFromFile(path.join(currentPath, '.gitignore'), relativeDir);
322
- }
382
+ const relativeDir = path.relative(projectPath, currentPath).replace(/\\/g, '/');
383
+ const names = entries.map((entry) => entry.name);
323
384
 
324
- for (const entry of entries) {
325
- const fullPath = path.join(currentPath, entry.name);
326
- const relativePath = path.relative(projectPath, fullPath).replace(/\\/g, '/');
385
+ // A directory that declares itself generated (a virtualenv, a cache
386
+ // with CACHEDIR.TAG) is skipped whole, whatever it is called.
387
+ if (options.pruneGenerated && relativeDir && hasGeneratedSignature(names)) return;
327
388
 
328
- // Always exclude certain directories
329
- if (ALWAYS_EXCLUDE_DIRS.has(entry.name)) continue;
389
+ // Load .gitignore in this directory (if not root - root already loaded)
390
+ if (relativeDir) {
391
+ await filter.loadFromFile(path.join(currentPath, '.gitignore'), relativeDir);
392
+ }
330
393
 
331
- if (entry.isDirectory()) {
332
- // Check if this is a nested git repo — scan it independently
333
- // and bypass the .gitignore filter so files inside a
334
- // gitignored nested repo are still tracked.
394
+ for (const entry of entries) {
395
+ const fullPath = path.join(currentPath, entry.name);
396
+ const relativePath = path.relative(projectPath, fullPath).replace(/\\/g, '/');
397
+
398
+ // Always exclude certain directories
399
+ if (ALWAYS_EXCLUDE_DIRS.has(entry.name)) continue;
400
+
401
+ if (entry.isDirectory()) {
402
+ // Check if this is a nested git repo — scan it independently
403
+ // and bypass the .gitignore filter so files inside a
404
+ // gitignored nested repo are still tracked.
405
+ let isNestedRepo = false;
406
+ try {
407
+ await fs.access(path.join(fullPath, '.git'));
408
+ isNestedRepo = true;
409
+ } catch {
410
+ // Not a git repo — apply gitignore filter and recurse
411
+ }
412
+ if (isNestedRepo) {
335
413
  try {
336
- await fs.access(path.join(fullPath, '.git'));
337
- const nestedFiles = await scanSingleGitRepo(fullPath);
338
- files.push(...nestedFiles);
339
- continue;
340
- } catch {
341
- // Not a git repo — apply gitignore filter and recurse
414
+ files.push(...await scanSingleGitRepo(fullPath));
415
+ } catch (err) {
416
+ debug.warn('snapshot', `git ls-files failed for nested repo ${fullPath}:`, err);
417
+ incomplete.push(incompleteEntry(projectPath, fullPath));
342
418
  }
419
+ continue;
420
+ }
343
421
 
344
- if (!filter.isIgnored(relativePath, true)) {
345
- await scan(fullPath);
346
- }
347
- } else if (entry.isFile()) {
348
- if (!filter.isIgnored(relativePath, false)) {
349
- files.push(fullPath);
350
- }
422
+ if (options.pruneGenerated && (isIgnoredName(entry.name) || isMarkedOutputDir(entry.name, names))) {
423
+ continue;
424
+ }
425
+
426
+ if (!filter.isIgnored(relativePath, true)) {
427
+ await scan(fullPath);
428
+ }
429
+ } else if (entry.isFile()) {
430
+ if (options.pruneGenerated && isIgnoredName(entry.name)) continue;
431
+ if (!filter.isIgnored(relativePath, false)) {
432
+ files.push(fullPath);
351
433
  }
352
434
  }
353
- } catch (err) {
354
- debug.warn('snapshot', `Could not read directory ${currentPath}:`, err);
355
435
  }
356
436
  };
357
437
 
358
438
  await scan(projectPath);
359
439
  debug.log('snapshot', `Manual scan found ${files.length} files`);
360
- return files;
440
+ return { files, incomplete };
361
441
  }
@@ -0,0 +1,270 @@
1
+ /**
2
+ * What a turn's snapshot is allowed to claim.
3
+ *
4
+ * A snapshot is a disk diff, and a disk diff sees every writer. Each case here
5
+ * is a writer that used to land in the turn: the user's edit while the chat
6
+ * sat idle, a `git merge` while the model worked (one real turn recorded 50
7
+ * merged files as its own), another chat in the same folder, and the scan
8
+ * itself failing to read a file and calling that a deletion. The other half
9
+ * of each case is the edit that must survive — the turn's own write, and an
10
+ * agent that commits its work.
11
+ */
12
+
13
+ import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
14
+ import { mkdtemp, rm, writeFile, readFile, chmod, mkdir } from 'node:fs/promises';
15
+ import { tmpdir } from 'node:os';
16
+ import path from 'node:path';
17
+
18
+ import { initializeDatabase, closeDatabase, getDatabase } from '../database/index';
19
+ import { projectQueries, sessionQueries, messageQueries } from '../database/queries';
20
+ import { execGit } from '../git/git-executor';
21
+ import { blobStore } from './blob-store';
22
+ import { snapshotService } from './snapshot-service';
23
+ import type { SessionScopedChanges } from '$shared/types/database/schema';
24
+ import type { UnifiedMessage } from '$shared/types/unified';
25
+
26
+ let root: string;
27
+ let projectId: string;
28
+
29
+ async function git(...args: string[]): Promise<string> {
30
+ const result = await execGit(args, root);
31
+ if (result.exitCode !== 0) throw new Error(`git ${args.join(' ')}: ${result.stderr}`);
32
+ return result.stdout;
33
+ }
34
+
35
+ async function write(file: string, content: string): Promise<void> {
36
+ await mkdir(path.dirname(path.join(root, file)), { recursive: true });
37
+ await writeFile(path.join(root, file), content);
38
+ }
39
+
40
+ function newSession(): string {
41
+ return sessionQueries.create({
42
+ project_id: projectId,
43
+ title: 'snapshot test',
44
+ started_at: new Date().toISOString()
45
+ } as Parameters<typeof sessionQueries.create>[0]).id;
46
+ }
47
+
48
+ function userMessage(sessionId: string): string {
49
+ return messageQueries.create({
50
+ session_id: sessionId,
51
+ message: { type: 'user', content: [{ type: 'text', text: 'do it' }] } as unknown as UnifiedMessage
52
+ }).id;
53
+ }
54
+
55
+ /**
56
+ * Run `work` as one tool call of a session's turn: the call, whatever the
57
+ * tool does, then its result — what the stream would feed the service.
58
+ */
59
+ async function asTool(sessionId: string, id: string, work: () => Promise<void>): Promise<void> {
60
+ snapshotService.observeEngineOutput(sessionId, { type: 'stream_event' });
61
+ snapshotService.observeEngineOutput(sessionId, {
62
+ type: 'assistant',
63
+ content: [{ type: 'tool_use', id, name: 'Bash', input: { command: 'anything' } }]
64
+ });
65
+ await work();
66
+ snapshotService.observeEngineOutput(sessionId, {
67
+ type: 'user',
68
+ content: [{ type: 'tool_result', toolUseId: id, content: '', isError: false }]
69
+ });
70
+ }
71
+
72
+ /** Longer than the window slack, so two tool calls cannot overlap. */
73
+ const apart = () => new Promise((resolve) => setTimeout(resolve, 1500));
74
+
75
+ async function capture(sessionId: string): Promise<SessionScopedChanges> {
76
+ const snapshot = await snapshotService.captureSnapshot(root, projectId, sessionId, userMessage(sessionId));
77
+ const raw = snapshot.session_changes as unknown;
78
+ return typeof raw === 'string' && raw ? JSON.parse(raw) as SessionScopedChanges : {};
79
+ }
80
+
81
+ /** Two writes in the same millisecond share an mtime, which the hash cache keys on. */
82
+ const tick = () => new Promise((resolve) => setTimeout(resolve, 15));
83
+
84
+ beforeAll(async () => {
85
+ await initializeDatabase();
86
+ });
87
+
88
+ afterAll(() => {
89
+ closeDatabase();
90
+ });
91
+
92
+ beforeEach(async () => {
93
+ root = await mkdtemp(path.join(tmpdir(), 'clopen-snapshot-'));
94
+ await git('init', '-b', 'main', '.');
95
+ await git('config', 'user.email', 'test@example.com');
96
+ await git('config', 'user.name', 'Test');
97
+ await git('config', 'commit.gpgsign', 'false');
98
+ await write('a.ts', 'a\n');
99
+ await write('b.ts', 'b\n');
100
+ await git('add', '.');
101
+ await git('commit', '-m', 'init');
102
+
103
+ projectId = projectQueries.create({
104
+ name: 'snapshot-test',
105
+ path: root,
106
+ created_at: new Date().toISOString(),
107
+ last_opened_at: new Date().toISOString()
108
+ }).id;
109
+ });
110
+
111
+ afterEach(async () => {
112
+ const db = getDatabase();
113
+ const sessions = `SELECT id FROM chat_sessions WHERE project_id = ?`;
114
+ db.prepare(`DELETE FROM message_snapshots WHERE project_id = ?`).run(projectId);
115
+ db.prepare(`DELETE FROM messages WHERE session_id IN (${sessions})`).run(projectId);
116
+ db.prepare(`DELETE FROM chat_sessions WHERE project_id = ?`).run(projectId);
117
+ projectQueries.deleteProject(projectId);
118
+ await chmod(path.join(root, 'b.ts'), 0o644).catch(() => {});
119
+ await rm(root, { recursive: true, force: true });
120
+ });
121
+
122
+ describe('turn baseline', () => {
123
+ it('does not charge an idle-time edit to the next turn', async () => {
124
+ const session = newSession();
125
+ await snapshotService.beginTurn(root, projectId, session);
126
+ await capture(session);
127
+
128
+ await tick();
129
+ await write('b.ts', 'edited by the user between turns\n');
130
+
131
+ await snapshotService.beginTurn(root, projectId, session);
132
+ await tick();
133
+ await write('a.ts', 'a\nfrom the turn\n');
134
+ const changes = await capture(session);
135
+
136
+ expect(Object.keys(changes)).toEqual(['a.ts']);
137
+ });
138
+ });
139
+
140
+ describe('git during a turn', () => {
141
+ async function prepareBranch(): Promise<void> {
142
+ await git('checkout', '-b', 'feature');
143
+ await write('merged-1.ts', 'one\n');
144
+ await write('merged-2.ts', 'two\n');
145
+ await write('b.ts', 'b\nfrom feature\n');
146
+ await git('add', '.');
147
+ await git('commit', '-m', 'feature work');
148
+ await git('checkout', 'main');
149
+ await tick();
150
+ }
151
+
152
+ it('leaves out what a merge brought in, and keeps the turn\'s own edit', async () => {
153
+ await prepareBranch();
154
+ const session = newSession();
155
+ await snapshotService.beginTurn(root, projectId, session);
156
+
157
+ await tick();
158
+ await write('a.ts', 'a\nfrom the turn\n');
159
+ await git('merge', '--ff-only', 'feature');
160
+ const changes = await capture(session);
161
+
162
+ expect(Object.keys(changes)).toEqual(['a.ts']);
163
+ });
164
+
165
+ it('keeps only the turn\'s part of a file it edited on top of the merge', async () => {
166
+ await prepareBranch();
167
+ const session = newSession();
168
+ await snapshotService.beginTurn(root, projectId, session);
169
+
170
+ await git('merge', '--ff-only', 'feature');
171
+ await tick();
172
+ await write('b.ts', 'b\nfrom feature\nfrom the turn\n');
173
+ const changes = await capture(session);
174
+
175
+ expect(Object.keys(changes)).toEqual(['b.ts']);
176
+ const before = (await blobStore.readBlob(changes['b.ts'].oldHash)).toString('utf8');
177
+ expect(before).toBe('b\nfrom feature\n');
178
+ });
179
+
180
+ it('keeps work the agent committed during the turn', async () => {
181
+ const session = newSession();
182
+ await snapshotService.beginTurn(root, projectId, session);
183
+
184
+ await tick();
185
+ await write('a.ts', 'a\ncommitted by the agent\n');
186
+ await git('commit', '-am', 'agent work');
187
+ const changes = await capture(session);
188
+
189
+ expect(Object.keys(changes)).toEqual(['a.ts']);
190
+ });
191
+ });
192
+
193
+ describe('scan failures', () => {
194
+ it('does not record an unreadable file as deleted', async () => {
195
+ const session = newSession();
196
+ await snapshotService.beginTurn(root, projectId, session);
197
+
198
+ await tick();
199
+ await write('a.ts', 'a\nfrom the turn\n');
200
+ await write('b.ts', 'b\nchanged, then unreadable\n');
201
+ await chmod(path.join(root, 'b.ts'), 0o000);
202
+ const changes = await capture(session);
203
+
204
+ expect(changes['b.ts']).toBeUndefined();
205
+ expect(Object.keys(changes)).toEqual(['a.ts']);
206
+ });
207
+
208
+ it('does not record a file that grew past the size cap as deleted', async () => {
209
+ const session = newSession();
210
+ await snapshotService.beginTurn(root, projectId, session);
211
+
212
+ await tick();
213
+ await write('a.ts', 'a\nfrom the turn\n');
214
+ await write('b.ts', 'x'.repeat(5 * 1024 * 1024 + 1));
215
+ const changes = await capture(session);
216
+
217
+ expect(Object.keys(changes)).toEqual(['a.ts']);
218
+ });
219
+
220
+ it('reads files with non-ASCII names', async () => {
221
+ await write('café.ts', 'v1\n');
222
+ await git('add', '.');
223
+ await git('commit', '-m', 'unicode');
224
+
225
+ const session = newSession();
226
+ await snapshotService.beginTurn(root, projectId, session);
227
+ await tick();
228
+ await write('café.ts', 'v2\n');
229
+ const changes = await capture(session);
230
+
231
+ expect(Object.keys(changes)).toEqual(['café.ts']);
232
+ });
233
+ });
234
+
235
+ describe('two chats in one folder', () => {
236
+ it('hands each write to the chat whose tool was running, shell commands included', async () => {
237
+ await write('sub/c.ts', 'c\n');
238
+ await git('add', '.');
239
+ await git('commit', '-m', 'sub');
240
+
241
+ const mine = newSession();
242
+ const theirs = newSession();
243
+ await snapshotService.beginTurn(root, projectId, mine);
244
+ await snapshotService.beginTurn(root, projectId, theirs);
245
+
246
+ await asTool(mine, 'm1', () => write('a.ts', 'a\nmine, via a shell command\n'));
247
+ await apart();
248
+ await asTool(theirs, 't1', async () => {
249
+ await write('b.ts', 'b\ntheirs\n');
250
+ await rm(path.join(root, 'sub/c.ts'));
251
+ });
252
+
253
+ expect(Object.keys(await capture(mine))).toEqual(['a.ts']);
254
+ expect(Object.keys(await capture(theirs)).sort()).toEqual(['b.ts', 'sub/c.ts']);
255
+ });
256
+
257
+ it('does not count a change twice when no tool of either chat was running', async () => {
258
+ const first = newSession();
259
+ const second = newSession();
260
+ await snapshotService.beginTurn(root, projectId, first);
261
+ await snapshotService.beginTurn(root, projectId, second);
262
+
263
+ await tick();
264
+ await write('a.ts', 'a\nwritten by a formatter\n');
265
+
266
+ expect(Object.keys(await capture(first))).toEqual(['a.ts']);
267
+ expect(await capture(second)).toEqual({});
268
+ expect(await readFile(path.join(root, 'a.ts'), 'utf8')).toBe('a\nwritten by a formatter\n');
269
+ });
270
+ });