forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitBundle.ts
More file actions
292 lines (268 loc) · 9.59 KB
/
Copy pathgitBundle.ts
File metadata and controls
292 lines (268 loc) · 9.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/**
* Git bundle creation + upload for CCR seed-bundle seeding.
*
* Flow:
* 1. git stash create → update-ref refs/seed/stash (makes it reachable)
* 2. git bundle create --all (packs refs/seed/stash + its objects)
* 3. Upload to /v1/files
* 4. Cleanup refs/seed/stash (don't pollute user's repo)
* 5. Caller sets seed_bundle_file_id on SessionContext
*/
import { stat, unlink } from 'fs/promises'
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
logEvent,
} from 'src/services/analytics/index.js'
import { getFeatureValue_CACHED_MAY_BE_STALE } from '../../services/analytics/growthbook.js'
import { type FilesApiConfig, uploadFile } from '../../services/api/filesApi.js'
import { getCwd } from '../cwd.js'
import { logForDebugging } from '../debug.js'
import { execFileNoThrowWithCwd } from '../execFileNoThrow.js'
import { findGitRoot, gitExe } from '../git.js'
import { generateTempFilePath } from '../tempfile.js'
// Tunable via tengu_ccr_bundle_max_bytes.
const DEFAULT_BUNDLE_MAX_BYTES = 100 * 1024 * 1024
type BundleScope = 'all' | 'head' | 'squashed'
export type BundleUploadResult =
| {
success: true
fileId: string
bundleSizeBytes: number
scope: BundleScope
hasWip: boolean
}
| { success: false; error: string; failReason?: BundleFailReason }
type BundleFailReason = 'git_error' | 'too_large' | 'empty_repo'
type BundleCreateResult =
| { ok: true; size: number; scope: BundleScope }
| { ok: false; error: string; failReason: BundleFailReason }
// Bundle --all → HEAD → squashed-root. HEAD drops side branches/tags but
// keeps full current-branch history. Squashed-root is a single parentless
// commit of HEAD's tree (or the stash tree if WIP exists) — no history,
// just the snapshot. Receiver needs refs/seed/root handling for that tier.
async function _bundleWithFallback(
gitRoot: string,
bundlePath: string,
maxBytes: number,
hasStash: boolean,
signal: AbortSignal | undefined,
): Promise<BundleCreateResult> {
// --all picks up refs/seed/stash; HEAD needs it explicit.
const extra = hasStash ? ['refs/seed/stash'] : []
const mkBundle = (base: string) =>
execFileNoThrowWithCwd(
gitExe(),
['bundle', 'create', bundlePath, base, ...extra],
{ cwd: gitRoot, abortSignal: signal },
)
const allResult = await mkBundle('--all')
if (allResult.code !== 0) {
return {
ok: false,
error: `git bundle create --all failed (${allResult.code}): ${allResult.stderr.slice(0, 200)}`,
failReason: 'git_error',
}
}
const { size: allSize } = await stat(bundlePath)
if (allSize <= maxBytes) {
return { ok: true, size: allSize, scope: 'all' }
}
// bundle create overwrites in place.
logForDebugging(
`[gitBundle] --all bundle is ${(allSize / 1024 / 1024).toFixed(1)}MB (> ${(maxBytes / 1024 / 1024).toFixed(0)}MB), retrying HEAD-only`,
)
const headResult = await mkBundle('HEAD')
if (headResult.code !== 0) {
return {
ok: false,
error: `git bundle create HEAD failed (${headResult.code}): ${headResult.stderr.slice(0, 200)}`,
failReason: 'git_error',
}
}
const { size: headSize } = await stat(bundlePath)
if (headSize <= maxBytes) {
return { ok: true, size: headSize, scope: 'head' }
}
// Last resort: squash to a single parentless commit. Uses the stash tree
// when WIP exists (bakes uncommitted changes in — can't bundle the stash
// ref separately since its parents would drag history back).
logForDebugging(
`[gitBundle] HEAD bundle is ${(headSize / 1024 / 1024).toFixed(1)}MB, retrying squashed-root`,
)
const treeRef = hasStash ? 'refs/seed/stash^{tree}' : 'HEAD^{tree}'
const commitTree = await execFileNoThrowWithCwd(
gitExe(),
['commit-tree', treeRef, '-m', 'seed'],
{ cwd: gitRoot, abortSignal: signal },
)
if (commitTree.code !== 0) {
return {
ok: false,
error: `git commit-tree failed (${commitTree.code}): ${commitTree.stderr.slice(0, 200)}`,
failReason: 'git_error',
}
}
const squashedSha = commitTree.stdout.trim()
await execFileNoThrowWithCwd(
gitExe(),
['update-ref', 'refs/seed/root', squashedSha],
{ cwd: gitRoot },
)
const squashResult = await execFileNoThrowWithCwd(
gitExe(),
['bundle', 'create', bundlePath, 'refs/seed/root'],
{ cwd: gitRoot, abortSignal: signal },
)
if (squashResult.code !== 0) {
return {
ok: false,
error: `git bundle create refs/seed/root failed (${squashResult.code}): ${squashResult.stderr.slice(0, 200)}`,
failReason: 'git_error',
}
}
const { size: squashSize } = await stat(bundlePath)
if (squashSize <= maxBytes) {
return { ok: true, size: squashSize, scope: 'squashed' }
}
return {
ok: false,
error:
'Repo is too large to bundle. Please setup GitHub on https://claude.ai/code',
failReason: 'too_large',
}
}
// Bundle the repo and upload to Files API; return file_id for
// seed_bundle_file_id. --all → HEAD → squashed-root fallback chain.
// Tracked WIP via stash create → refs/seed/stash (or baked into the
// squashed tree); untracked not captured.
export async function createAndUploadGitBundle(
config: FilesApiConfig,
opts?: { cwd?: string; signal?: AbortSignal },
): Promise<BundleUploadResult> {
const workdir = opts?.cwd ?? getCwd()
const gitRoot = findGitRoot(workdir)
if (!gitRoot) {
return { success: false, error: 'Not in a git repository' }
}
// Sweep stale refs from a crashed prior run before --all bundles them.
// Runs before the empty-repo check so it's never skipped by an early return.
for (const ref of ['refs/seed/stash', 'refs/seed/root']) {
await execFileNoThrowWithCwd(gitExe(), ['update-ref', '-d', ref], {
cwd: gitRoot,
})
}
// `git bundle create` refuses to create an empty bundle (exit 128), and
// `stash create` fails with "You do not have the initial commit yet".
// Check for any refs (not just HEAD) so orphan branches with commits
// elsewhere still bundle — `--all` packs those refs regardless of HEAD.
const refCheck = await execFileNoThrowWithCwd(
gitExe(),
['for-each-ref', '--count=1', 'refs/'],
{ cwd: gitRoot },
)
if (refCheck.code === 0 && refCheck.stdout.trim() === '') {
logEvent('tengu_ccr_bundle_upload', {
outcome:
'empty_repo' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
return {
success: false,
error: 'Repository has no commits yet',
failReason: 'empty_repo',
}
}
// stash create writes a dangling commit — doesn't touch refs/stash or
// the working tree. Untracked files intentionally excluded.
const stashResult = await execFileNoThrowWithCwd(
gitExe(),
['stash', 'create'],
{ cwd: gitRoot, abortSignal: opts?.signal },
)
// exit 0 + empty stdout = nothing to stash. Nonzero is rare; non-fatal.
const wipStashSha = stashResult.code === 0 ? stashResult.stdout.trim() : ''
const hasWip = wipStashSha !== ''
if (stashResult.code !== 0) {
logForDebugging(
`[gitBundle] git stash create failed (${stashResult.code}), proceeding without WIP: ${stashResult.stderr.slice(0, 200)}`,
)
} else if (hasWip) {
logForDebugging(`[gitBundle] Captured WIP as stash ${wipStashSha}`)
// env-runner reads the SHA via bundle list-heads refs/seed/stash.
await execFileNoThrowWithCwd(
gitExe(),
['update-ref', 'refs/seed/stash', wipStashSha],
{ cwd: gitRoot },
)
}
const bundlePath = generateTempFilePath('ccr-seed', '.bundle')
// git leaves a partial file on nonzero exit (e.g. empty-repo 128).
try {
const maxBytes =
getFeatureValue_CACHED_MAY_BE_STALE<number | null>(
'tengu_ccr_bundle_max_bytes',
null,
) ?? DEFAULT_BUNDLE_MAX_BYTES
const bundle = await _bundleWithFallback(
gitRoot,
bundlePath,
maxBytes,
hasWip,
opts?.signal,
)
if (!bundle.ok) {
logForDebugging(`[gitBundle] ${bundle.error}`)
logEvent('tengu_ccr_bundle_upload', {
outcome:
bundle.failReason as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
max_bytes: maxBytes,
})
return {
success: false,
error: bundle.error,
failReason: bundle.failReason,
}
}
// Fixed relativePath so CCR can locate it.
const upload = await uploadFile(bundlePath, '_source_seed.bundle', config, {
signal: opts?.signal,
})
if (!upload.success) {
logEvent('tengu_ccr_bundle_upload', {
outcome:
'failed' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
return { success: false, error: upload.error }
}
logForDebugging(
`[gitBundle] Uploaded ${upload.size} bytes as file_id ${upload.fileId}`,
)
logEvent('tengu_ccr_bundle_upload', {
outcome:
'success' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
size_bytes: upload.size,
scope:
bundle.scope as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
has_wip: hasWip,
})
return {
success: true,
fileId: upload.fileId,
bundleSizeBytes: upload.size,
scope: bundle.scope,
hasWip,
}
} finally {
try {
await unlink(bundlePath)
} catch {
logForDebugging(`[gitBundle] Could not delete ${bundlePath} (non-fatal)`)
}
// Always delete — also sweeps a stale ref from a crashed prior run.
// update-ref -d on a missing ref exits 0.
for (const ref of ['refs/seed/stash', 'refs/seed/root']) {
await execFileNoThrowWithCwd(gitExe(), ['update-ref', '-d', ref], {
cwd: gitRoot,
})
}
}
}