@myrialabs/clopen 0.4.36 → 0.4.38

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 (115) hide show
  1. package/README.md +2 -2
  2. package/backend/auth/permissions.ts +14 -0
  3. package/backend/bootstrap.ts +16 -0
  4. package/backend/database/crypto/envelope.test.ts +93 -0
  5. package/backend/database/crypto/envelope.ts +127 -0
  6. package/backend/database/crypto/index.ts +22 -0
  7. package/backend/database/crypto/master-key.ts +129 -0
  8. package/backend/database/crypto/secret-columns.ts +147 -0
  9. package/backend/database/migrations/071_create_notes_tables.ts +90 -0
  10. package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
  11. package/backend/database/migrations/073_create_integration_tables.ts +119 -0
  12. package/backend/database/migrations/074_create_work_tables.ts +94 -0
  13. package/backend/database/migrations/index.ts +28 -0
  14. package/backend/database/queries/db-client-connection-queries.ts +23 -12
  15. package/backend/database/queries/engine-queries.ts +23 -10
  16. package/backend/database/queries/index.ts +6 -1
  17. package/backend/database/queries/integration-queries.ts +297 -0
  18. package/backend/database/queries/mcp-server-queries.ts +38 -11
  19. package/backend/database/queries/note-queries.test.ts +190 -0
  20. package/backend/database/queries/note-queries.ts +269 -0
  21. package/backend/database/queries/profile-queries.ts +1 -1
  22. package/backend/database/queries/ssh-connection-queries.ts +19 -8
  23. package/backend/database/queries/work-queries.ts +210 -0
  24. package/backend/engine/docs/artifacts.md +22 -9
  25. package/backend/files/os-clipboard.test.ts +209 -0
  26. package/backend/files/os-clipboard.ts +567 -0
  27. package/backend/git/conflict-state.test.ts +396 -0
  28. package/backend/git/git-executor.ts +6 -0
  29. package/backend/git/git-parser.ts +144 -48
  30. package/backend/git/git-service.ts +727 -57
  31. package/backend/git/push-target.test.ts +264 -0
  32. package/backend/http/integration-hooks.ts +42 -0
  33. package/backend/http/notes-images.test.ts +228 -0
  34. package/backend/http/notes-images.ts +196 -0
  35. package/backend/index.ts +9 -0
  36. package/backend/integrations/accounts.ts +229 -0
  37. package/backend/integrations/health.ts +146 -0
  38. package/backend/integrations/index.ts +36 -0
  39. package/backend/integrations/projections/index.ts +120 -0
  40. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  41. package/backend/integrations/projections/mcp-projector.ts +159 -0
  42. package/backend/integrations/projections/types.ts +51 -0
  43. package/backend/integrations/registry/define.ts +38 -0
  44. package/backend/integrations/registry/index.ts +56 -0
  45. package/backend/integrations/registry/providers/context7.ts +44 -0
  46. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  47. package/backend/integrations/registry/providers/github.ts +78 -0
  48. package/backend/integrations/registry/types.ts +96 -0
  49. package/backend/integrations/webhooks/gateway.ts +160 -0
  50. package/backend/integrations/webhooks/verify.ts +65 -0
  51. package/backend/mcp/README.md +25 -3
  52. package/backend/mcp/external/config.ts +35 -1
  53. package/backend/mcp/index.ts +1 -1
  54. package/backend/mcp/internal/config.ts +1 -1
  55. package/backend/notes/access.test.ts +82 -0
  56. package/backend/notes/access.ts +27 -0
  57. package/backend/notes/storage.test.ts +77 -0
  58. package/backend/notes/storage.ts +114 -0
  59. package/backend/permissions/service.ts +2 -2
  60. package/backend/profiles/service.ts +1 -1
  61. package/backend/project/status-manager.ts +20 -0
  62. package/backend/projects/project-cleanup.ts +6 -0
  63. package/backend/work/bindings.ts +124 -0
  64. package/backend/work/index.ts +42 -0
  65. package/backend/work/prompts.ts +150 -0
  66. package/backend/work/providers/github/actions-logs.ts +180 -0
  67. package/backend/work/providers/github/adapter.test.ts +88 -0
  68. package/backend/work/providers/github/adapter.ts +1255 -0
  69. package/backend/work/providers/github/client.ts +280 -0
  70. package/backend/work/providers/github/list-range.test.ts +158 -0
  71. package/backend/work/providers/github/token-kind.test.ts +42 -0
  72. package/backend/work/pull-requests.ts +242 -0
  73. package/backend/work/registry.ts +27 -0
  74. package/backend/work/service.ts +436 -0
  75. package/backend/work/start-work.test.ts +71 -0
  76. package/backend/work/start-work.ts +232 -0
  77. package/backend/work/types.ts +180 -0
  78. package/backend/ws/files/clipboard.ts +78 -0
  79. package/backend/ws/files/index.ts +5 -0
  80. package/backend/ws/git/branch-name.ts +6 -5
  81. package/backend/ws/git/branch.ts +43 -1
  82. package/backend/ws/git/commit-message.ts +13 -10
  83. package/backend/ws/git/conflict.ts +106 -3
  84. package/backend/ws/git/diff-budget.test.ts +125 -0
  85. package/backend/ws/git/diff-budget.ts +279 -0
  86. package/backend/ws/git/log.ts +25 -0
  87. package/backend/ws/git/remote.ts +75 -1
  88. package/backend/ws/index.ts +11 -1
  89. package/backend/ws/integrations/crud.ts +219 -0
  90. package/backend/ws/integrations/index.ts +22 -0
  91. package/backend/ws/mcp/crud.ts +25 -1
  92. package/backend/ws/notes/index.ts +278 -0
  93. package/backend/ws/profiles/crud.ts +1 -1
  94. package/backend/ws/work/actions.ts +206 -0
  95. package/backend/ws/work/context.ts +51 -0
  96. package/backend/ws/work/crud.ts +347 -0
  97. package/backend/ws/work/index.ts +17 -0
  98. package/backend/ws/work/pull-requests.ts +177 -0
  99. package/backend/ws/work/schemas.ts +226 -0
  100. package/dist/assets/{index-Bg-SUCFg.js → index-CyH7fSbR.js} +1 -1
  101. package/dist/assets/{index-Cz4YpHVi.js → index-DSHIANSy.js} +1 -1
  102. package/dist/assets/main-D2IOjftb.css +1 -0
  103. package/dist/assets/main-DM-tHKbW.js +1152 -0
  104. package/dist/index.html +2 -2
  105. package/package.json +1 -1
  106. package/shared/constants/engine-tools.ts +1 -1
  107. package/shared/constants/tool-icons.ts +33 -0
  108. package/shared/types/database/schema.ts +41 -0
  109. package/shared/types/git.ts +123 -0
  110. package/shared/types/integrations.ts +140 -0
  111. package/shared/types/stores/settings.ts +8 -0
  112. package/shared/types/work.ts +426 -0
  113. package/shared/utils/logger.ts +3 -0
  114. package/dist/assets/main-9G7IpQpK.css +0 -1
  115. package/dist/assets/main-BofFsH8E.js +0 -1085
@@ -6,7 +6,7 @@
6
6
 
7
7
  import { t } from 'elysia';
8
8
  import { createRouter } from '$shared/utils/ws-server';
9
- import { execGit } from '../../git/git-executor';
9
+ import { buildBudgetedStagedDiff, COMMIT_MESSAGE_BUDGET } from './diff-budget';
10
10
  import { initializeEngine } from '../../engine';
11
11
  import { resolveGenerationTarget } from '../../engine/resolve-model';
12
12
  import type { EngineType } from '$shared/types/unified';
@@ -77,11 +77,9 @@ export const commitMessageHandler = createRouter()
77
77
  const { root } = requireProjectWorkspace(conn, data.projectId);
78
78
  const cwd = resolveRepoCwd(root, data.repoPath);
79
79
 
80
- // Get raw staged diff text
81
- const diffResult = await execGit(['diff', '--cached'], cwd);
82
- const rawDiff = diffResult.stdout;
83
-
84
- if (!rawDiff.trim()) {
80
+ // A budgeted view of the staged change, not the raw diff — see diff-budget.ts.
81
+ const diff = await buildBudgetedStagedDiff(cwd, COMMIT_MESSAGE_BUDGET);
82
+ if (diff.isEmpty) {
85
83
  throw new Error('No staged changes to generate a commit message for');
86
84
  }
87
85
 
@@ -96,16 +94,21 @@ export const commitMessageHandler = createRouter()
96
94
  ? 'Generate a multi-line conventional commit message with type, scope, subject, AND body fields. The body should explain WHY the change was made.'
97
95
  : 'Generate a single-line conventional commit message with type, optional scope, and subject. Leave body empty.';
98
96
 
99
- const defaultPrompt = `Analyze the following git diff and generate a conventional commit message.
97
+ // When the diff was sampled, say so: without this the model describes only
98
+ // the files it happened to see and writes a subject that misses the change.
99
+ const coverageNote = diff.truncated
100
+ ? '\n- The diff below is a sample. Describe the change as a whole using the file list, not just the visible hunks.'
101
+ : '';
102
+
103
+ const defaultPrompt = `Analyze the following staged git change and generate a conventional commit message.
100
104
 
101
105
  Rules:
102
106
  - type: one of feat, fix, refactor, docs, test, chore, style, perf, ci, build
103
107
  - scope: optional, the area of the codebase affected (e.g., git, settings, engine)
104
108
  - subject: imperative mood, lowercase, no period at end, max 72 characters
105
- - ${formatInstruction}
109
+ - ${formatInstruction}${coverageNote}
106
110
 
107
- Git diff:
108
- ${rawDiff}`;
111
+ ${diff.text}`;
109
112
 
110
113
  const extra = data.customPrompt?.trim();
111
114
  const prompt = extra
@@ -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,7 +74,15 @@ 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
88
  const { root } = requireProjectWorkspace(conn, data.projectId);
@@ -75,7 +115,14 @@ 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() })
@@ -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(),
@@ -102,6 +205,6 @@ export const conflictHandler = createRouter()
102
205
  }, async ({ data, conn }) => {
103
206
  const { root } = requireProjectWorkspace(conn, data.projectId);
104
207
  const cwd = resolveRepoCwd(root, data.repoPath) ?? root;
105
- await gitService.abortMerge(cwd);
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,279 @@
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
+ * Budget for pull-request descriptions. The most generous of the three: a PR
56
+ * description covers a whole branch rather than one commit, and a description
57
+ * written from a heavily sampled diff is the one that invents changes.
58
+ */
59
+ export const PR_DESCRIPTION_BUDGET: DiffBudget = {
60
+ perFileBytes: 8 * 1024,
61
+ totalBytes: 40 * 1024,
62
+ maxFiles: 60,
63
+ contextLines: 3
64
+ };
65
+
66
+ /**
67
+ * WHICH diff to budget.
68
+ *
69
+ * Extracted when the pull-request composer needed `base...head` instead of
70
+ * `--cached`. Everything below is identical for both — the file walk, the
71
+ * skip list, the per-file clipping — so the scope is a parameter rather than a
72
+ * second copy of the builder that would drift from this one.
73
+ */
74
+ export interface DiffScope {
75
+ /** Operands inserted into every `git diff` invocation. */
76
+ args: string[];
77
+ /** How the patch section is introduced. */
78
+ label: string;
79
+ /** Wording when nothing changed, used by the caller's empty check. */
80
+ emptyLabel: string;
81
+ }
82
+
83
+ export const STAGED_SCOPE: DiffScope = {
84
+ args: ['--cached'],
85
+ label: 'Staged diff',
86
+ emptyLabel: 'staged changes'
87
+ };
88
+
89
+ /**
90
+ * Everything on `head` that is not on `base`.
91
+ *
92
+ * Three dots, not two: `base..head` would also show changes made to base since
93
+ * the branch left it, which are not this pull request's changes and are exactly
94
+ * what makes an AI-written description claim work someone else did.
95
+ */
96
+ export function rangeScope(base: string, head: string): DiffScope {
97
+ return {
98
+ args: [`${base}...${head}`],
99
+ label: `Diff (${base}...${head})`,
100
+ emptyLabel: `changes between ${base} and ${head}`
101
+ };
102
+ }
103
+
104
+ /**
105
+ * Paths whose diff is machine-generated: enormous, uninformative, and the single
106
+ * biggest source of wasted context. They still appear in the `--stat` header, so
107
+ * the model can see they changed.
108
+ */
109
+ const GENERATED_PATH_PATTERNS: RegExp[] = [
110
+ /(^|\/)(bun\.lock|bun\.lockb|package-lock\.json|yarn\.lock|pnpm-lock\.yaml)$/,
111
+ /(^|\/)(Cargo\.lock|composer\.lock|Gemfile\.lock|poetry\.lock|go\.sum)$/,
112
+ /(^|\/)(dist|build|out|vendor|node_modules|coverage)\//,
113
+ /\.(min\.js|min\.css|map|snap)$/,
114
+ /(^|\/)__snapshots__\//
115
+ ];
116
+
117
+ function isGeneratedPath(filePath: string): boolean {
118
+ return GENERATED_PATH_PATTERNS.some(pattern => pattern.test(filePath));
119
+ }
120
+
121
+ interface NumstatEntry {
122
+ path: string;
123
+ isBinary: boolean;
124
+ }
125
+
126
+ /**
127
+ * `git diff --cached --numstat -z` emits `adds\tdels\tpath\0`, with `-` counts
128
+ * for binary files. Renames add two extra NUL-separated path fields after an
129
+ * empty path slot, which is why the parser advances through the stream rather
130
+ * than splitting it into fixed records.
131
+ */
132
+ function parseNumstat(output: string): NumstatEntry[] {
133
+ const entries: NumstatEntry[] = [];
134
+ const fields = output.split('\0');
135
+
136
+ for (let i = 0; i < fields.length; i++) {
137
+ const field = fields[i];
138
+ if (!field.trim()) continue;
139
+ const parts = field.split('\t');
140
+ if (parts.length < 3) continue;
141
+
142
+ const [adds, dels, rawPath] = parts;
143
+ let filePath = rawPath;
144
+ if (filePath === '') {
145
+ // Rename/copy: the old and new paths follow as their own fields.
146
+ const newPath = fields[i + 2];
147
+ if (newPath) filePath = newPath;
148
+ i += 2;
149
+ }
150
+ if (!filePath) continue;
151
+
152
+ entries.push({ path: filePath, isBinary: adds === '-' && dels === '-' });
153
+ }
154
+
155
+ return entries;
156
+ }
157
+
158
+ function truncate(text: string, limit: number): { text: string; truncated: boolean } {
159
+ if (text.length <= limit) return { text, truncated: false };
160
+ const clipped = text.slice(0, limit);
161
+ // Cut on a line boundary so the model never sees half a diff line.
162
+ const lastNewline = clipped.lastIndexOf('\n');
163
+ const body = lastNewline > 0 ? clipped.slice(0, lastNewline) : clipped;
164
+ const droppedLines = text.slice(body.length).split('\n').length;
165
+ return {
166
+ text: `${body}\n… truncated, ${droppedLines} more line${droppedLines === 1 ? '' : 's'} in this file`,
167
+ truncated: true
168
+ };
169
+ }
170
+
171
+ export interface BudgetedDiff {
172
+ /** The rendered prompt section, ready to append. */
173
+ text: string;
174
+ /** True when any file's patch was clipped or dropped. */
175
+ truncated: boolean;
176
+ /** True when the scope contains no change at all. */
177
+ isEmpty: boolean;
178
+ }
179
+
180
+ /**
181
+ * Build the diff section of an AI prompt under `budget`, for `scope`.
182
+ *
183
+ * We deliberately spawn one `git diff` per file rather than one for everything:
184
+ * it lets us stop as soon as the budget is spent, so a 200 MB blob is never read
185
+ * into memory in the first place.
186
+ */
187
+ export async function buildBudgetedDiff(
188
+ cwd: string,
189
+ budget: DiffBudget,
190
+ scope: DiffScope = STAGED_SCOPE
191
+ ): Promise<BudgetedDiff> {
192
+ const numstat = await execGit(['diff', ...scope.args, '--numstat', '-z', '-M'], cwd);
193
+ const entries = parseNumstat(numstat.stdout);
194
+
195
+ if (entries.length === 0) {
196
+ return { text: '', truncated: false, isEmpty: true };
197
+ }
198
+
199
+ const statResult = await execGit(['diff', ...scope.args, '--stat=200', '-M'], cwd);
200
+ const stat = statResult.stdout.trim();
201
+
202
+ const skipped: string[] = [];
203
+ const candidates: string[] = [];
204
+ for (const entry of entries) {
205
+ if (entry.isBinary || isGeneratedPath(entry.path)) {
206
+ skipped.push(entry.path);
207
+ continue;
208
+ }
209
+ candidates.push(entry.path);
210
+ }
211
+
212
+ const patches: string[] = [];
213
+ let used = 0;
214
+ let truncated = false;
215
+ let filesOmitted = 0;
216
+
217
+ for (const [index, filePath] of candidates.entries()) {
218
+ if (index >= budget.maxFiles || used >= budget.totalBytes) {
219
+ filesOmitted = candidates.length - index;
220
+ truncated = true;
221
+ break;
222
+ }
223
+
224
+ try {
225
+ assertSafeGitPathOperand(filePath, 'diff path');
226
+ } catch {
227
+ skipped.push(filePath);
228
+ continue;
229
+ }
230
+
231
+ const result = await execGit(
232
+ [
233
+ 'diff',
234
+ ...scope.args,
235
+ '--no-color',
236
+ `--unified=${budget.contextLines}`,
237
+ '-M',
238
+ '--',
239
+ filePath
240
+ ],
241
+ cwd
242
+ );
243
+ if (result.exitCode !== 0 || !result.stdout.trim()) continue;
244
+
245
+ const remaining = budget.totalBytes - used;
246
+ const limit = Math.min(budget.perFileBytes, remaining);
247
+ const clipped = truncate(result.stdout.trimEnd(), limit);
248
+ if (clipped.truncated) truncated = true;
249
+ patches.push(clipped.text);
250
+ used += clipped.text.length;
251
+ }
252
+
253
+ const sections: string[] = [];
254
+ if (stat) sections.push(`Files changed:\n${stat}`);
255
+ if (skipped.length > 0) {
256
+ const shown = skipped.slice(0, 10).join(', ');
257
+ const rest = skipped.length > 10 ? `, and ${skipped.length - 10} more` : '';
258
+ sections.push(`Binary or generated files (diff omitted): ${shown}${rest}`);
259
+ }
260
+ if (patches.length > 0) {
261
+ const header = truncated
262
+ ? `${scope.label} (sampled — some files or lines were omitted to fit context):`
263
+ : `${scope.label}:`;
264
+ sections.push(`${header}\n${patches.join('\n')}`);
265
+ }
266
+ if (filesOmitted > 0) {
267
+ sections.push(`${filesOmitted} further changed file(s) were omitted; see the file list above.`);
268
+ }
269
+
270
+ return { text: sections.join('\n\n'), truncated, isEmpty: false };
271
+ }
272
+
273
+ /** The staged diff. Kept as its own name because two callers read better for it. */
274
+ export async function buildBudgetedStagedDiff(
275
+ cwd: string,
276
+ budget: DiffBudget
277
+ ): Promise<BudgetedDiff> {
278
+ return buildBudgetedDiff(cwd, budget, STAGED_SCOPE);
279
+ }
@@ -59,4 +59,29 @@ export const logHandler = createRouter()
59
59
  data.branch,
60
60
  data.allBranches ?? false
61
61
  );
62
+ })
63
+
64
+ /**
65
+ * The repo's undo journal. Unlike `git log` this still lists commits that a
66
+ * reset, a branch delete or a rebase orphaned, so it is the recovery path for
67
+ * every destructive action the panel offers.
68
+ */
69
+ .http('git:reflog', {
70
+ data: t.Object({
71
+ projectId: t.String(),
72
+ limit: t.Optional(t.Number()),
73
+ repoPath: t.Optional(t.String())
74
+ }),
75
+ response: t.Array(t.Object({
76
+ hash: t.String(),
77
+ hashShort: t.String(),
78
+ selector: t.String(),
79
+ action: t.String(),
80
+ subject: t.String(),
81
+ date: t.String()
82
+ }))
83
+ }, async ({ data, conn }) => {
84
+ const { root } = requireProjectWorkspace(conn, data.projectId);
85
+ const cwd = resolveRepoCwd(root, data.repoPath);
86
+ return await gitService.getReflog(cwd, data.limit ?? 100);
62
87
  });