@myrialabs/clopen 0.4.35 → 0.4.37

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 (91) hide show
  1. package/backend/artifacts/sync.test.ts +63 -0
  2. package/backend/artifacts/sync.ts +56 -3
  3. package/backend/database/migrations/070_create_worktrees_table.ts +67 -0
  4. package/backend/database/migrations/index.ts +7 -0
  5. package/backend/database/queries/index.ts +1 -0
  6. package/backend/database/queries/session-queries.ts +50 -11
  7. package/backend/database/queries/worktree-queries.ts +148 -0
  8. package/backend/engine/adapters/opencode/server.ts +389 -83
  9. package/backend/engine/adapters/opencode/stream.ts +14 -14
  10. package/backend/engine/hot-reload.ts +25 -10
  11. package/backend/files/file-watcher.ts +35 -9
  12. package/backend/git/conflict-state.test.ts +396 -0
  13. package/backend/git/git-executor.ts +6 -0
  14. package/backend/git/git-parser.ts +144 -48
  15. package/backend/git/git-service.ts +727 -57
  16. package/backend/git/push-target.test.ts +264 -0
  17. package/backend/host/metrics.test.ts +110 -0
  18. package/backend/host/metrics.ts +235 -0
  19. package/backend/index.ts +5 -2
  20. package/backend/mcp/internal/servers/browser-automation/context.ts +16 -2
  21. package/backend/ports/attribute.test.ts +3 -2
  22. package/backend/ports/attribute.ts +5 -44
  23. package/backend/preview/browser/browser-pool.ts +81 -0
  24. package/backend/preview/browser/browser-preview-service.ts +142 -32
  25. package/backend/preview/browser/browser-tab-manager.ts +350 -113
  26. package/backend/preview/browser/types.ts +9 -0
  27. package/backend/project/status-manager.ts +20 -0
  28. package/backend/projects/project-cleanup.integration.test.ts +1 -1
  29. package/backend/projects/project-cleanup.ts +7 -1
  30. package/backend/projects/shell-ownership.ts +65 -0
  31. package/backend/snapshot/snapshot-service.ts +6 -2
  32. package/backend/terminal/ptykit.ts +35 -6
  33. package/backend/utils/ws.ts +21 -1
  34. package/backend/worktrees/clone.ts +222 -0
  35. package/backend/worktrees/index.ts +29 -0
  36. package/backend/worktrees/merge.test.ts +93 -0
  37. package/backend/worktrees/merge.ts +232 -0
  38. package/backend/worktrees/paths.test.ts +60 -0
  39. package/backend/worktrees/paths.ts +60 -0
  40. package/backend/worktrees/resolve.ts +67 -0
  41. package/backend/worktrees/service.ts +315 -0
  42. package/backend/worktrees/tree.ts +59 -0
  43. package/backend/ws/access.ts +18 -0
  44. package/backend/ws/artifacts/generate.ts +2 -2
  45. package/backend/ws/chat/stream.ts +9 -2
  46. package/backend/ws/files/panel-state-scope.test.ts +102 -0
  47. package/backend/ws/files/path-access.test.ts +93 -1
  48. package/backend/ws/files/path-access.ts +54 -5
  49. package/backend/ws/files/read.ts +15 -10
  50. package/backend/ws/files/search.ts +7 -7
  51. package/backend/ws/files/state.ts +70 -8
  52. package/backend/ws/files/watch.ts +16 -14
  53. package/backend/ws/git/branch-name.ts +9 -8
  54. package/backend/ws/git/branch.ts +58 -16
  55. package/backend/ws/git/commit-message.ts +16 -13
  56. package/backend/ws/git/commit.ts +17 -17
  57. package/backend/ws/git/conflict.ts +116 -13
  58. package/backend/ws/git/diff-budget.test.ts +125 -0
  59. package/backend/ws/git/diff-budget.ts +220 -0
  60. package/backend/ws/git/diff.ts +9 -9
  61. package/backend/ws/git/ignored.ts +9 -9
  62. package/backend/ws/git/log.ts +28 -3
  63. package/backend/ws/git/remote.ts +118 -44
  64. package/backend/ws/git/staging.ts +16 -16
  65. package/backend/ws/git/status.ts +13 -13
  66. package/backend/ws/index.ts +4 -0
  67. package/backend/ws/preview/access.ts +11 -3
  68. package/backend/ws/projects/index.ts +5 -1
  69. package/backend/ws/projects/info.test.ts +54 -0
  70. package/backend/ws/projects/info.ts +398 -0
  71. package/backend/ws/sessions/crud.ts +21 -6
  72. package/backend/ws/snapshot/restore.ts +11 -14
  73. package/backend/ws/system/device-info.ts +62 -144
  74. package/backend/ws/worktrees/crud.ts +187 -0
  75. package/backend/ws/worktrees/index.ts +33 -0
  76. package/backend/ws/worktrees/transfer.ts +88 -0
  77. package/dist/assets/{index-BRJqss6F.js → index-Bik9TCBi.js} +1 -1
  78. package/dist/assets/{index-B0iIhSO9.js → index-sJmS_CCm.js} +1 -1
  79. package/dist/assets/main-DLqolBI2.css +1 -0
  80. package/dist/assets/main-Df1I3hnw.js +1096 -0
  81. package/dist/index.html +2 -2
  82. package/package.json +1 -1
  83. package/shared/types/database/schema.ts +26 -0
  84. package/shared/types/git.ts +123 -0
  85. package/shared/utils/logger.ts +1 -0
  86. package/shared/utils/workspace-scope.test.ts +80 -0
  87. package/shared/utils/workspace-scope.ts +57 -0
  88. package/shared/utils/ws-client.ts +25 -5
  89. package/shared/utils/ws-server.ts +19 -3
  90. package/dist/assets/main-Buko4D0t.css +0 -1
  91. package/dist/assets/main-C_iGUZyL.js +0 -1078
@@ -6,7 +6,7 @@ import { t } from 'elysia';
6
6
  import path from 'node:path';
7
7
  import { createRouter } from '$shared/utils/ws-server';
8
8
  import { gitService } from '../../git/git-service';
9
- import { requireProjectAccess } from '../access';
9
+ import { requireProjectWorkspace } from '../access';
10
10
  import { debug } from '$shared/utils/logger';
11
11
 
12
12
  /**
@@ -36,8 +36,8 @@ export const commitHandler = createRouter()
36
36
  hash: t.String()
37
37
  })
38
38
  }, async ({ data, conn }) => {
39
- const project = requireProjectAccess(conn, data.projectId);
40
- const cwd = resolveRepoCwd(project.path, data.repoPath);
39
+ const { root } = requireProjectWorkspace(conn, data.projectId);
40
+ const cwd = resolveRepoCwd(root, data.repoPath);
41
41
  const hash = await gitService.commit(cwd, data.message);
42
42
  return { hash };
43
43
  })
@@ -52,8 +52,8 @@ export const commitHandler = createRouter()
52
52
  hash: t.String()
53
53
  })
54
54
  }, async ({ data, conn }) => {
55
- const project = requireProjectAccess(conn, data.projectId);
56
- const cwd = resolveRepoCwd(project.path, data.repoPath);
55
+ const { root } = requireProjectWorkspace(conn, data.projectId);
56
+ const cwd = resolveRepoCwd(root, data.repoPath);
57
57
  const hash = await gitService.amendCommit(cwd, data.message);
58
58
  return { hash };
59
59
  })
@@ -66,8 +66,8 @@ export const commitHandler = createRouter()
66
66
  }),
67
67
  response: t.Object({ ok: t.Boolean() })
68
68
  }, async ({ data, conn }) => {
69
- const project = requireProjectAccess(conn, data.projectId);
70
- const cwd = resolveRepoCwd(project.path, data.repoPath);
69
+ const { root } = requireProjectWorkspace(conn, data.projectId);
70
+ const cwd = resolveRepoCwd(root, data.repoPath);
71
71
  await gitService.undoLastCommit(cwd, data.mode);
72
72
  return { ok: true };
73
73
  })
@@ -83,8 +83,8 @@ export const commitHandler = createRouter()
83
83
  message: t.String()
84
84
  })
85
85
  }, async ({ data, conn }) => {
86
- const project = requireProjectAccess(conn, data.projectId);
87
- const cwd = resolveRepoCwd(project.path, data.repoPath);
86
+ const { root } = requireProjectWorkspace(conn, data.projectId);
87
+ const cwd = resolveRepoCwd(root, data.repoPath);
88
88
  return await gitService.revertCommit(cwd, data.ref);
89
89
  })
90
90
 
@@ -99,8 +99,8 @@ export const commitHandler = createRouter()
99
99
  message: t.String()
100
100
  })
101
101
  }, async ({ data, conn }) => {
102
- const project = requireProjectAccess(conn, data.projectId);
103
- const cwd = resolveRepoCwd(project.path, data.repoPath);
102
+ const { root } = requireProjectWorkspace(conn, data.projectId);
103
+ const cwd = resolveRepoCwd(root, data.repoPath);
104
104
  return await gitService.cherryPick(cwd, data.hashes);
105
105
  })
106
106
 
@@ -111,8 +111,8 @@ export const commitHandler = createRouter()
111
111
  }),
112
112
  response: t.Object({ message: t.String() })
113
113
  }, async ({ data, conn }) => {
114
- const project = requireProjectAccess(conn, data.projectId);
115
- const cwd = resolveRepoCwd(project.path, data.repoPath);
114
+ const { root } = requireProjectWorkspace(conn, data.projectId);
115
+ const cwd = resolveRepoCwd(root, data.repoPath);
116
116
  const message = await gitService.cleanUntracked(cwd);
117
117
  return { message };
118
118
  })
@@ -124,8 +124,8 @@ export const commitHandler = createRouter()
124
124
  }),
125
125
  response: t.Object({ message: t.String() })
126
126
  }, async ({ data, conn }) => {
127
- const project = requireProjectAccess(conn, data.projectId);
128
- const cwd = resolveRepoCwd(project.path, data.repoPath);
127
+ const { root } = requireProjectWorkspace(conn, data.projectId);
128
+ const cwd = resolveRepoCwd(root, data.repoPath);
129
129
  const message = await gitService.optimize(cwd);
130
130
  return { message };
131
131
  })
@@ -142,7 +142,7 @@ export const commitHandler = createRouter()
142
142
  message: t.String()
143
143
  })
144
144
  }, async ({ data, conn }) => {
145
- const project = requireProjectAccess(conn, data.projectId);
146
- const cwd = resolveRepoCwd(project.path, data.repoPath);
145
+ const { root } = requireProjectWorkspace(conn, data.projectId);
146
+ const cwd = resolveRepoCwd(root, data.repoPath);
147
147
  return await gitService.npmVersion(cwd, data.bump);
148
148
  });
@@ -7,7 +7,7 @@ import path from 'node:path';
7
7
  import { createRouter } from '$shared/utils/ws-server';
8
8
  import { gitService } from '../../git/git-service';
9
9
  import { findNestedRepoPaths, findRepoForFile } from '../../git/nested-repos';
10
- import { requireProjectAccess } from '../access';
10
+ import { requireProjectWorkspace } from '../access';
11
11
  import { debug } from '$shared/utils/logger';
12
12
 
13
13
  function resolveRepoCwd(projectPath: string, repoPath: string | undefined): string | null {
@@ -22,6 +22,38 @@ function resolveRepoCwd(projectPath: string, repoPath: string | undefined): stri
22
22
  return resolved;
23
23
  }
24
24
 
25
+ const ConflictKindSchema = t.Union([
26
+ t.Literal('both-modified'),
27
+ t.Literal('both-added'),
28
+ t.Literal('added-by-us'),
29
+ t.Literal('added-by-them'),
30
+ t.Literal('deleted-by-us'),
31
+ t.Literal('deleted-by-them'),
32
+ t.Literal('both-deleted')
33
+ ]);
34
+
35
+ const OperationSchema = t.Union([
36
+ t.Literal('rebase'),
37
+ t.Literal('merge'),
38
+ t.Literal('cherry-pick'),
39
+ t.Literal('revert'),
40
+ t.Literal('bisect'),
41
+ t.Null()
42
+ ]);
43
+
44
+ const OperationStateSchema = t.Object({
45
+ operation: OperationSchema,
46
+ step: t.Optional(t.Number()),
47
+ total: t.Optional(t.Number()),
48
+ oursLabel: t.String(),
49
+ theirsLabel: t.String(),
50
+ currentCommit: t.Optional(t.String()),
51
+ unmergedCount: t.Number(),
52
+ canContinue: t.Boolean(),
53
+ canSkip: t.Boolean(),
54
+ stashConflict: t.Boolean()
55
+ });
56
+
25
57
  const ConflictMarkerSchema = t.Object({
26
58
  ourStart: t.Number(),
27
59
  ourEnd: t.Number(),
@@ -42,18 +74,26 @@ export const conflictHandler = createRouter()
42
74
  response: t.Array(t.Object({
43
75
  path: t.String(),
44
76
  content: t.String(),
45
- markers: t.Array(ConflictMarkerSchema)
77
+ markers: t.Array(ConflictMarkerSchema),
78
+ kind: ConflictKindSchema,
79
+ contentOmitted: t.Boolean(),
80
+ omitReason: t.Optional(t.Union([
81
+ t.Literal('binary'),
82
+ t.Literal('missing'),
83
+ t.Literal('too-large')
84
+ ])),
85
+ size: t.Optional(t.Number())
46
86
  }))
47
87
  }, async ({ data, conn }) => {
48
- const project = requireProjectAccess(conn, data.projectId);
49
- const conflicts = await gitService.getConflictFiles(project.path);
88
+ const { root } = requireProjectWorkspace(conn, data.projectId);
89
+ const conflicts = await gitService.getConflictFiles(root);
50
90
 
51
91
  try {
52
- const nestedRepoPaths = await findNestedRepoPaths(project.path);
92
+ const nestedRepoPaths = await findNestedRepoPaths(root);
53
93
  for (const repoPath of nestedRepoPaths) {
54
94
  try {
55
95
  const nestedConflicts = await gitService.getConflictFiles(repoPath);
56
- const prefix = path.relative(project.path, repoPath).replace(/\\/g, '/') + '/';
96
+ const prefix = path.relative(root, repoPath).replace(/\\/g, '/') + '/';
57
97
  for (const conflict of nestedConflicts) {
58
98
  conflicts.push({
59
99
  ...conflict,
@@ -75,14 +115,21 @@ export const conflictHandler = createRouter()
75
115
  data: t.Object({
76
116
  projectId: t.String(),
77
117
  filePath: t.String(),
78
- resolution: t.Union([t.Literal('ours'), t.Literal('theirs'), t.Literal('custom')]),
118
+ resolution: t.Union([
119
+ t.Literal('ours'),
120
+ t.Literal('theirs'),
121
+ t.Literal('custom'),
122
+ t.Literal('keep'),
123
+ t.Literal('delete'),
124
+ t.Literal('reset')
125
+ ]),
79
126
  customContent: t.Optional(t.String())
80
127
  }),
81
128
  response: t.Object({ ok: t.Boolean() })
82
129
  }, async ({ data, conn }) => {
83
- const project = requireProjectAccess(conn, data.projectId);
84
- const repo = await findRepoForFile(project.path, data.filePath);
85
- const cwd = repo?.repoPath ?? project.path;
130
+ const { root } = requireProjectWorkspace(conn, data.projectId);
131
+ const repo = await findRepoForFile(root, data.filePath);
132
+ const cwd = repo?.repoPath ?? root;
86
133
  const filePath = repo?.relativeFilePath ?? data.filePath;
87
134
  await gitService.resolveConflict(
88
135
  cwd,
@@ -93,6 +140,62 @@ export const conflictHandler = createRouter()
93
140
  return { ok: true };
94
141
  })
95
142
 
143
+ /**
144
+ * Everything needed to describe (and finish) an in-progress merge/rebase.
145
+ * Scoped to one repo: a project with nested repos can be mid-rebase in a
146
+ * sub-repo while the outer tree is clean, so the caller passes `repoPath`
147
+ * rather than us guessing from whichever conflict happens to be first.
148
+ */
149
+ .http('git:operation-state', {
150
+ data: t.Object({
151
+ projectId: t.String(),
152
+ repoPath: t.Optional(t.String())
153
+ }),
154
+ response: OperationStateSchema
155
+ }, async ({ data, conn }) => {
156
+ const { root } = requireProjectWorkspace(conn, data.projectId);
157
+ const cwd = resolveRepoCwd(root, data.repoPath) ?? root;
158
+ return await gitService.getOperationState(cwd);
159
+ })
160
+
161
+ .http('git:continue-operation', {
162
+ data: t.Object({
163
+ projectId: t.String(),
164
+ repoPath: t.Optional(t.String())
165
+ }),
166
+ response: t.Object({ success: t.Boolean(), message: t.String() })
167
+ }, async ({ data, conn }) => {
168
+ const { root } = requireProjectWorkspace(conn, data.projectId);
169
+ const cwd = resolveRepoCwd(root, data.repoPath) ?? root;
170
+ return await gitService.continueOperation(cwd);
171
+ })
172
+
173
+ .http('git:skip-operation', {
174
+ data: t.Object({
175
+ projectId: t.String(),
176
+ repoPath: t.Optional(t.String())
177
+ }),
178
+ response: t.Object({ success: t.Boolean(), message: t.String() })
179
+ }, async ({ data, conn }) => {
180
+ const { root } = requireProjectWorkspace(conn, data.projectId);
181
+ const cwd = resolveRepoCwd(root, data.repoPath) ?? root;
182
+ return await gitService.skipOperation(cwd);
183
+ })
184
+
185
+ .http('git:abort-operation', {
186
+ data: t.Object({
187
+ projectId: t.String(),
188
+ repoPath: t.Optional(t.String())
189
+ }),
190
+ response: t.Object({ ok: t.Boolean() })
191
+ }, async ({ data, conn }) => {
192
+ const { root } = requireProjectWorkspace(conn, data.projectId);
193
+ const cwd = resolveRepoCwd(root, data.repoPath) ?? root;
194
+ await gitService.abortOperation(cwd);
195
+ return { ok: true };
196
+ })
197
+
198
+ /** Retained under the old name so existing clients keep working. */
96
199
  .http('git:abort-merge', {
97
200
  data: t.Object({
98
201
  projectId: t.String(),
@@ -100,8 +203,8 @@ export const conflictHandler = createRouter()
100
203
  }),
101
204
  response: t.Object({ ok: t.Boolean() })
102
205
  }, async ({ data, conn }) => {
103
- const project = requireProjectAccess(conn, data.projectId);
104
- const cwd = resolveRepoCwd(project.path, data.repoPath) ?? project.path;
105
- await gitService.abortMerge(cwd);
206
+ const { root } = requireProjectWorkspace(conn, data.projectId);
207
+ const cwd = resolveRepoCwd(root, data.repoPath) ?? root;
208
+ await gitService.abortOperation(cwd);
106
209
  return { ok: true };
107
210
  });
@@ -0,0 +1,125 @@
1
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
2
+ import { mkdtemp, rm, writeFile, mkdir } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { execGit } from '../../git/git-executor';
6
+ import { buildBudgetedStagedDiff, COMMIT_MESSAGE_BUDGET, type DiffBudget } from './diff-budget';
7
+
8
+ /**
9
+ * The AI generators used to inline the raw `git diff --cached` output, which had
10
+ * no upper bound at all. These assert the replacement stays inside its budget
11
+ * while still describing the whole change.
12
+ */
13
+
14
+ let repo: string;
15
+
16
+ async function git(...args: string[]) {
17
+ const result = await execGit(args, repo);
18
+ if (result.exitCode !== 0) throw new Error(`git ${args.join(' ')}: ${result.stderr}`);
19
+ return result.stdout;
20
+ }
21
+
22
+ const TINY_BUDGET: DiffBudget = {
23
+ perFileBytes: 400,
24
+ totalBytes: 900,
25
+ maxFiles: 3,
26
+ contextLines: 1
27
+ };
28
+
29
+ beforeEach(async () => {
30
+ repo = await mkdtemp(path.join(tmpdir(), 'clopen-diffbudget-'));
31
+ await git('init', '-b', 'main', '.');
32
+ await git('config', 'user.email', 'test@example.com');
33
+ await git('config', 'user.name', 'Test');
34
+ await git('config', 'commit.gpgsign', 'false');
35
+ });
36
+
37
+ afterEach(async () => {
38
+ await rm(repo, { recursive: true, force: true });
39
+ });
40
+
41
+ describe('buildBudgetedStagedDiff', () => {
42
+ test('reports an empty staging area', async () => {
43
+ const result = await buildBudgetedStagedDiff(repo, COMMIT_MESSAGE_BUDGET);
44
+ expect(result.isEmpty).toBe(true);
45
+ expect(result.text).toBe('');
46
+ });
47
+
48
+ test('includes the stat header and the patch for a small change', async () => {
49
+ await writeFile(path.join(repo, 'a.ts'), 'export const a = 1;\n');
50
+ await git('add', '-A');
51
+
52
+ const result = await buildBudgetedStagedDiff(repo, COMMIT_MESSAGE_BUDGET);
53
+ expect(result.isEmpty).toBe(false);
54
+ expect(result.truncated).toBe(false);
55
+ expect(result.text).toContain('Files changed:');
56
+ expect(result.text).toContain('a.ts');
57
+ expect(result.text).toContain('export const a = 1;');
58
+ });
59
+
60
+ test('skips lockfiles and generated output but still names them', async () => {
61
+ await writeFile(path.join(repo, 'bun.lock'), 'x'.repeat(50_000));
62
+ await mkdir(path.join(repo, 'dist'), { recursive: true });
63
+ await writeFile(path.join(repo, 'dist', 'bundle.js'), 'y'.repeat(50_000));
64
+ await writeFile(path.join(repo, 'src.ts'), 'export const keep = true;\n');
65
+ await git('add', '-A');
66
+
67
+ const result = await buildBudgetedStagedDiff(repo, COMMIT_MESSAGE_BUDGET);
68
+ expect(result.text).toContain('Binary or generated files (diff omitted)');
69
+ expect(result.text).toContain('bun.lock');
70
+ expect(result.text).toContain('dist/bundle.js');
71
+ // The real source file still gets its patch.
72
+ expect(result.text).toContain('export const keep = true;');
73
+ // And none of the 100 KB of noise made it into the prompt.
74
+ expect(result.text).not.toContain('x'.repeat(200));
75
+ expect(result.text).not.toContain('y'.repeat(200));
76
+ });
77
+
78
+ test('omits a binary file from the patch body', async () => {
79
+ await writeFile(path.join(repo, 'image.dat'), Buffer.from([0, 1, 2, 0, 255, 0]));
80
+ await git('add', '-A');
81
+
82
+ const result = await buildBudgetedStagedDiff(repo, COMMIT_MESSAGE_BUDGET);
83
+ expect(result.text).toContain('Binary or generated files (diff omitted)');
84
+ expect(result.text).toContain('image.dat');
85
+ });
86
+
87
+ test('clips an oversized file and says so', async () => {
88
+ const big = Array.from({ length: 400 }, (_, i) => `line ${i}`).join('\n');
89
+ await writeFile(path.join(repo, 'big.ts'), `${big}\n`);
90
+ await git('add', '-A');
91
+
92
+ const result = await buildBudgetedStagedDiff(repo, TINY_BUDGET);
93
+ expect(result.truncated).toBe(true);
94
+ expect(result.text).toContain('… truncated');
95
+ expect(result.text).toContain('sampled');
96
+ // The whole point: the prompt stays near the budget, not the file size.
97
+ expect(result.text.length).toBeLessThan(TINY_BUDGET.totalBytes * 3);
98
+ });
99
+
100
+ test('stops opening files once the budget is spent, and reports the remainder', async () => {
101
+ for (let i = 0; i < 8; i++) {
102
+ const body = Array.from({ length: 60 }, (_, n) => `const v${i}_${n} = ${n};`).join('\n');
103
+ await writeFile(path.join(repo, `f${i}.ts`), `${body}\n`);
104
+ }
105
+ await git('add', '-A');
106
+
107
+ const result = await buildBudgetedStagedDiff(repo, TINY_BUDGET);
108
+ expect(result.truncated).toBe(true);
109
+ expect(result.text).toContain('were omitted');
110
+ // Every file is still visible in the stat header, so the model can
111
+ // describe the change as a whole.
112
+ expect(result.text).toContain('f7.ts');
113
+ });
114
+
115
+ test('handles a rename without losing the path', async () => {
116
+ await writeFile(path.join(repo, 'old.ts'), 'export const x = 1;\n');
117
+ await git('add', '-A');
118
+ await git('commit', '-m', 'init');
119
+ await git('mv', 'old.ts', 'new.ts');
120
+
121
+ const result = await buildBudgetedStagedDiff(repo, COMMIT_MESSAGE_BUDGET);
122
+ expect(result.isEmpty).toBe(false);
123
+ expect(result.text).toContain('new.ts');
124
+ });
125
+ });
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Budgeted staged-diff builder for the AI generators.
3
+ *
4
+ * The commit-message and branch-name handlers used to inline the raw output of
5
+ * `git diff --cached` into the prompt. That has no upper bound: a lockfile
6
+ * refresh or a vendored bundle turns one "generate commit message" click into
7
+ * hundreds of thousands of tokens, and on strict-context models it fails
8
+ * outright instead of degrading.
9
+ *
10
+ * This builds the same information under a hard budget: the `--stat` header
11
+ * always survives (it is small and describes the *whole* change), noisy paths
12
+ * are skipped by name, and the patch body is filled file by file until the
13
+ * budget runs out. Truncation is announced in the text so the model knows it is
14
+ * looking at a sample rather than the complete change.
15
+ */
16
+
17
+ import { execGit } from '../../git/git-executor';
18
+ import { assertSafeGitPathOperand } from '../../git/git-spawn-validation';
19
+
20
+ export interface DiffBudget {
21
+ /** Max bytes of patch text kept for any single file. */
22
+ perFileBytes: number;
23
+ /** Max bytes of patch text across all files. */
24
+ totalBytes: number;
25
+ /** Max number of files we spawn a `git diff` for. */
26
+ maxFiles: number;
27
+ /** Lines of surrounding context per hunk. */
28
+ contextLines: number;
29
+ }
30
+
31
+ /**
32
+ * Budget for commit messages. Big enough that a normal feature change arrives
33
+ * whole, small enough that a lockfile-sized diff cannot blow up the request.
34
+ */
35
+ export const COMMIT_MESSAGE_BUDGET: DiffBudget = {
36
+ perFileBytes: 6 * 1024,
37
+ totalBytes: 24 * 1024,
38
+ maxFiles: 40,
39
+ contextLines: 3
40
+ };
41
+
42
+ /**
43
+ * Budget for branch names. A branch name is one to three words about the *topic*
44
+ * of the change, so the file list carries almost all the signal and the patch is
45
+ * only there to disambiguate.
46
+ */
47
+ export const BRANCH_NAME_BUDGET: DiffBudget = {
48
+ perFileBytes: 2 * 1024,
49
+ totalBytes: 4 * 1024,
50
+ maxFiles: 15,
51
+ contextLines: 0
52
+ };
53
+
54
+ /**
55
+ * Paths whose diff is machine-generated: enormous, uninformative, and the single
56
+ * biggest source of wasted context. They still appear in the `--stat` header, so
57
+ * the model can see they changed.
58
+ */
59
+ const GENERATED_PATH_PATTERNS: RegExp[] = [
60
+ /(^|\/)(bun\.lock|bun\.lockb|package-lock\.json|yarn\.lock|pnpm-lock\.yaml)$/,
61
+ /(^|\/)(Cargo\.lock|composer\.lock|Gemfile\.lock|poetry\.lock|go\.sum)$/,
62
+ /(^|\/)(dist|build|out|vendor|node_modules|coverage)\//,
63
+ /\.(min\.js|min\.css|map|snap)$/,
64
+ /(^|\/)__snapshots__\//
65
+ ];
66
+
67
+ function isGeneratedPath(filePath: string): boolean {
68
+ return GENERATED_PATH_PATTERNS.some(pattern => pattern.test(filePath));
69
+ }
70
+
71
+ interface NumstatEntry {
72
+ path: string;
73
+ isBinary: boolean;
74
+ }
75
+
76
+ /**
77
+ * `git diff --cached --numstat -z` emits `adds\tdels\tpath\0`, with `-` counts
78
+ * for binary files. Renames add two extra NUL-separated path fields after an
79
+ * empty path slot, which is why the parser advances through the stream rather
80
+ * than splitting it into fixed records.
81
+ */
82
+ function parseNumstat(output: string): NumstatEntry[] {
83
+ const entries: NumstatEntry[] = [];
84
+ const fields = output.split('\0');
85
+
86
+ for (let i = 0; i < fields.length; i++) {
87
+ const field = fields[i];
88
+ if (!field.trim()) continue;
89
+ const parts = field.split('\t');
90
+ if (parts.length < 3) continue;
91
+
92
+ const [adds, dels, rawPath] = parts;
93
+ let filePath = rawPath;
94
+ if (filePath === '') {
95
+ // Rename/copy: the old and new paths follow as their own fields.
96
+ const newPath = fields[i + 2];
97
+ if (newPath) filePath = newPath;
98
+ i += 2;
99
+ }
100
+ if (!filePath) continue;
101
+
102
+ entries.push({ path: filePath, isBinary: adds === '-' && dels === '-' });
103
+ }
104
+
105
+ return entries;
106
+ }
107
+
108
+ function truncate(text: string, limit: number): { text: string; truncated: boolean } {
109
+ if (text.length <= limit) return { text, truncated: false };
110
+ const clipped = text.slice(0, limit);
111
+ // Cut on a line boundary so the model never sees half a diff line.
112
+ const lastNewline = clipped.lastIndexOf('\n');
113
+ const body = lastNewline > 0 ? clipped.slice(0, lastNewline) : clipped;
114
+ const droppedLines = text.slice(body.length).split('\n').length;
115
+ return {
116
+ text: `${body}\n… truncated, ${droppedLines} more line${droppedLines === 1 ? '' : 's'} in this file`,
117
+ truncated: true
118
+ };
119
+ }
120
+
121
+ export interface BudgetedDiff {
122
+ /** The rendered prompt section, ready to append. */
123
+ text: string;
124
+ /** True when any file's patch was clipped or dropped. */
125
+ truncated: boolean;
126
+ /** True when there is nothing staged at all. */
127
+ isEmpty: boolean;
128
+ }
129
+
130
+ /**
131
+ * Build the staged-diff section of an AI prompt under `budget`.
132
+ *
133
+ * We deliberately spawn one `git diff` per file rather than one for everything:
134
+ * it lets us stop as soon as the budget is spent, so a 200 MB staged blob is
135
+ * never read into memory in the first place.
136
+ */
137
+ export async function buildBudgetedStagedDiff(
138
+ cwd: string,
139
+ budget: DiffBudget
140
+ ): Promise<BudgetedDiff> {
141
+ const numstat = await execGit(['diff', '--cached', '--numstat', '-z', '-M'], cwd);
142
+ const entries = parseNumstat(numstat.stdout);
143
+
144
+ if (entries.length === 0) {
145
+ return { text: '', truncated: false, isEmpty: true };
146
+ }
147
+
148
+ const statResult = await execGit(['diff', '--cached', '--stat=200', '-M'], cwd);
149
+ const stat = statResult.stdout.trim();
150
+
151
+ const skipped: string[] = [];
152
+ const candidates: string[] = [];
153
+ for (const entry of entries) {
154
+ if (entry.isBinary || isGeneratedPath(entry.path)) {
155
+ skipped.push(entry.path);
156
+ continue;
157
+ }
158
+ candidates.push(entry.path);
159
+ }
160
+
161
+ const patches: string[] = [];
162
+ let used = 0;
163
+ let truncated = false;
164
+ let filesOmitted = 0;
165
+
166
+ for (const [index, filePath] of candidates.entries()) {
167
+ if (index >= budget.maxFiles || used >= budget.totalBytes) {
168
+ filesOmitted = candidates.length - index;
169
+ truncated = true;
170
+ break;
171
+ }
172
+
173
+ try {
174
+ assertSafeGitPathOperand(filePath, 'diff path');
175
+ } catch {
176
+ skipped.push(filePath);
177
+ continue;
178
+ }
179
+
180
+ const result = await execGit(
181
+ [
182
+ 'diff',
183
+ '--cached',
184
+ '--no-color',
185
+ `--unified=${budget.contextLines}`,
186
+ '-M',
187
+ '--',
188
+ filePath
189
+ ],
190
+ cwd
191
+ );
192
+ if (result.exitCode !== 0 || !result.stdout.trim()) continue;
193
+
194
+ const remaining = budget.totalBytes - used;
195
+ const limit = Math.min(budget.perFileBytes, remaining);
196
+ const clipped = truncate(result.stdout.trimEnd(), limit);
197
+ if (clipped.truncated) truncated = true;
198
+ patches.push(clipped.text);
199
+ used += clipped.text.length;
200
+ }
201
+
202
+ const sections: string[] = [];
203
+ if (stat) sections.push(`Files changed:\n${stat}`);
204
+ if (skipped.length > 0) {
205
+ const shown = skipped.slice(0, 10).join(', ');
206
+ const rest = skipped.length > 10 ? `, and ${skipped.length - 10} more` : '';
207
+ sections.push(`Binary or generated files (diff omitted): ${shown}${rest}`);
208
+ }
209
+ if (patches.length > 0) {
210
+ const header = truncated
211
+ ? 'Staged diff (sampled — some files or lines were omitted to fit context):'
212
+ : 'Staged diff:';
213
+ sections.push(`${header}\n${patches.join('\n')}`);
214
+ }
215
+ if (filesOmitted > 0) {
216
+ sections.push(`${filesOmitted} further changed file(s) were omitted; see the file list above.`);
217
+ }
218
+
219
+ return { text: sections.join('\n\n'), truncated, isEmpty: false };
220
+ }
@@ -7,7 +7,7 @@ import path from 'node:path';
7
7
  import { createRouter } from '$shared/utils/ws-server';
8
8
  import { gitService } from '../../git/git-service';
9
9
  import { findRepoForFile } from '../../git/nested-repos';
10
- import { requireProjectAccess } from '../access';
10
+ import { requireProjectWorkspace } from '../access';
11
11
  import { debug } from '$shared/utils/logger';
12
12
 
13
13
  const DiffHunkLineSchema = t.Object({
@@ -58,14 +58,14 @@ export const diffHandler = createRouter()
58
58
  }),
59
59
  response: t.Array(FileDiffSchema)
60
60
  }, async ({ data, conn }) => {
61
- const project = requireProjectAccess(conn, data.projectId);
61
+ const { root } = requireProjectWorkspace(conn, data.projectId);
62
62
  // Route the diff to the nested repo that owns the file (if any) —
63
63
  // the outer repo's `git diff` returns nothing for files that are
64
64
  // tracked inside a nested repo and gitignored by the parent.
65
65
  const repo = data.filePath
66
- ? await findRepoForFile(project.path, data.filePath)
66
+ ? await findRepoForFile(root, data.filePath)
67
67
  : null;
68
- const cwd = repo?.repoPath ?? project.path;
68
+ const cwd = repo?.repoPath ?? root;
69
69
  const filePath = repo?.relativeFilePath ?? data.filePath;
70
70
  return await gitService.getDiffUnstaged(cwd, filePath);
71
71
  })
@@ -77,11 +77,11 @@ export const diffHandler = createRouter()
77
77
  }),
78
78
  response: t.Array(FileDiffSchema)
79
79
  }, async ({ data, conn }) => {
80
- const project = requireProjectAccess(conn, data.projectId);
80
+ const { root } = requireProjectWorkspace(conn, data.projectId);
81
81
  const repo = data.filePath
82
- ? await findRepoForFile(project.path, data.filePath)
82
+ ? await findRepoForFile(root, data.filePath)
83
83
  : null;
84
- const cwd = repo?.repoPath ?? project.path;
84
+ const cwd = repo?.repoPath ?? root;
85
85
  const filePath = repo?.relativeFilePath ?? data.filePath;
86
86
  return await gitService.getDiffStaged(cwd, filePath);
87
87
  })
@@ -98,7 +98,7 @@ export const diffHandler = createRouter()
98
98
  body: t.String()
99
99
  })
100
100
  }, async ({ data, conn }) => {
101
- const project = requireProjectAccess(conn, data.projectId);
102
- const cwd = resolveRepoCwd(project.path, data.repoPath);
101
+ const { root } = requireProjectWorkspace(conn, data.projectId);
102
+ const cwd = resolveRepoCwd(root, data.repoPath);
103
103
  return await gitService.getDiffCommit(cwd, data.commitHash);
104
104
  });