forked from ProverCoderAI/docker-git
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession-backup-gist.js
More file actions
686 lines (597 loc) · 18.9 KB
/
session-backup-gist.js
File metadata and controls
686 lines (597 loc) · 18.9 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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
#!/usr/bin/env node
/**
* Session Backup to a private GitHub repository
*
* This script backs up AI agent session files (~/.codex, ~/.claude, ~/.qwen, ~/.gemini)
* to a dedicated private repository and optionally posts a comment to the
* associated PR with direct links to the uploaded files.
*
* Usage:
* node scripts/session-backup-gist.js [options]
*
* Options:
* --session-dir <path> Path to session directory under $HOME (default: auto-detect ~/.codex, ~/.claude, ~/.qwen, or ~/.gemini)
* --pr-number <number> Open PR number to post comment to (optional, auto-detected from branch)
* --repo <owner/repo> Source repository (optional, auto-detected from git remote)
* --no-comment Skip posting PR comment
* --dry-run Show what would be uploaded without actually uploading
* --verbose Enable verbose logging
*
* Environment:
* DOCKER_GIT_SKIP_SESSION_BACKUP=1 Skip session backup entirely
*
* @pure false - contains IO effects (file system, network, git commands)
* @effect FileSystem, ProcessExec, GitHubRepo
*/
const fs = require("node:fs");
const path = require("node:path");
const { execSync, spawnSync } = require("node:child_process");
const os = require("node:os");
const GH_MAX_BUFFER_BYTES = 32 * 1024 * 1024;
const {
buildBlobUrl,
buildSnapshotRef,
ensureBackupRepo,
resolveGhEnvironment,
prepareUploadArtifacts,
uploadSnapshot,
} = require("./session-backup-repo.js");
const SESSION_DIR_NAMES = [".codex", ".claude", ".qwen", ".gemini"];
const SESSION_WALK_IGNORE_DIR_NAMES = new Set([".git", "node_modules", "tmp"]);
const toLogicalRelativePath = (relativePath) =>
relativePath.split(path.sep).join(path.posix.sep);
const shouldIgnoreSessionPath = (relativePath) => {
const logicalPath = toLogicalRelativePath(relativePath);
return logicalPath === "tmp" || logicalPath.startsWith("tmp/") || logicalPath.includes("/tmp/");
};
const isPathWithinParent = (targetPath, parentPath) => {
const relative = path.relative(parentPath, targetPath);
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
};
const getAllowedSessionRoots = () => {
const homeDir = os.homedir();
return SESSION_DIR_NAMES.map((dirName) => ({
name: dirName,
path: path.join(homeDir, dirName),
})).filter((entry) => fs.existsSync(entry.path));
};
const resolveAllowedSessionDir = (candidatePath, verbose) => {
const resolvedPath = path.resolve(candidatePath);
if (!fs.existsSync(resolvedPath)) {
return null;
}
for (const root of getAllowedSessionRoots()) {
if (isPathWithinParent(resolvedPath, root.path)) {
return resolvedPath;
}
}
log(verbose, `Skipping non-session directory: ${candidatePath}`);
return null;
};
const parseArgs = () => {
const args = process.argv.slice(2);
const result = {
sessionDir: null,
prNumber: null,
repo: null,
postComment: true,
dryRun: false,
verbose: false,
};
for (let i = 0; i < args.length; i++) {
const arg = args[i];
switch (arg) {
case "--session-dir":
result.sessionDir = args[++i];
break;
case "--pr-number":
result.prNumber = parseInt(args[++i], 10);
break;
case "--repo":
result.repo = args[++i];
break;
case "--no-comment":
result.postComment = false;
break;
case "--dry-run":
result.dryRun = true;
break;
case "--verbose":
result.verbose = true;
break;
case "--help":
console.log(`Usage: session-backup-gist.js [options]
Options:
--session-dir <path> Path to session directory under $HOME
--pr-number <number> Open PR number to post comment to
--repo <owner/repo> Source repository
--no-comment Skip posting PR comment
--dry-run Show what would be uploaded
--verbose Enable verbose logging
--help Show this help message`);
process.exit(0);
}
}
return result;
};
const log = (verbose, message) => {
if (verbose) {
console.log(`[session-backup] ${message}`);
}
};
const execCommand = (command, options = {}) => {
try {
return execSync(command, {
encoding: "utf8",
stdio: ["pipe", "pipe", "pipe"],
...options,
}).trim();
} catch {
return null;
}
};
const getGitStatus = () => {
const status = execCommand("git status");
if (status === null) {
return null;
}
if (!status) {
return "clean";
}
return status;
};
const printGitStatus = (status) => {
console.log("[session-backup] git status:");
if (status === null) {
console.log("[session-backup] (unavailable)");
return;
}
for (const line of status.split("\n")) {
console.log(`[session-backup] ${line}`);
}
};
const ghCommand = (args, ghEnv) => {
const result = spawnSync("gh", args, {
encoding: "utf8",
stdio: ["pipe", "pipe", "pipe"],
maxBuffer: GH_MAX_BUFFER_BYTES,
env: ghEnv,
});
return {
success: result.status === 0,
stdout: (result.stdout || "").trim(),
stderr: (result.stderr || "").trim(),
};
};
const parseGitHubRepoFromRemoteUrl = (remoteUrl) => {
if (!remoteUrl) {
return null;
}
const sshMatch = remoteUrl.match(/git@github\.com:([^/]+\/[^.]+)(?:\.git)?$/);
if (sshMatch) {
return sshMatch[1];
}
const httpsMatch = remoteUrl.match(/https:\/\/github\.com\/([^/]+\/[^.]+)(?:\.git)?$/);
if (httpsMatch) {
return httpsMatch[1];
}
return null;
};
const rankRemoteName = (remoteName) => {
if (remoteName === "upstream") {
return 0;
}
if (remoteName === "origin") {
return 1;
}
return 2;
};
const getCurrentBranch = () => execCommand("git rev-parse --abbrev-ref HEAD");
const getHeadCommitSha = () => execCommand("git rev-parse HEAD");
const getRepoCandidates = (explicitRepo, verbose) => {
if (explicitRepo) {
return [explicitRepo];
}
const remoteOutput = execCommand("git remote -v");
if (!remoteOutput) {
return [];
}
const remotes = [];
const seenRepos = new Set();
for (const line of remoteOutput.split("\n")) {
const match = line.match(/^(\S+)\s+(\S+)\s+\((fetch|push)\)$/);
if (!match || match[3] !== "fetch") {
continue;
}
const [, remoteName, remoteUrl] = match;
const repo = parseGitHubRepoFromRemoteUrl(remoteUrl);
if (!repo || seenRepos.has(repo)) {
continue;
}
remotes.push({ remoteName, repo });
seenRepos.add(repo);
}
remotes.sort((left, right) => {
const rankDiff = rankRemoteName(left.remoteName) - rankRemoteName(right.remoteName);
return rankDiff !== 0 ? rankDiff : left.remoteName.localeCompare(right.remoteName);
});
const repos = remotes.map(({ repo }) => repo);
if (repos.length > 0) {
log(verbose, `Repository candidates: ${repos.join(", ")}`);
}
return repos;
};
const getPrNumberFromBranch = (repo, branch, ghEnv) => {
const result = ghCommand([
"pr",
"list",
"--repo",
repo,
"--head",
branch,
"--json",
"number",
"--jq",
".[0].number",
], ghEnv);
if (result.success && result.stdout && !Number.isNaN(parseInt(result.stdout, 10))) {
return parseInt(result.stdout, 10);
}
return null;
};
const getPrState = (repo, prNumber, ghEnv) => {
const result = ghCommand([
"pr",
"view",
prNumber.toString(),
"--repo",
repo,
"--json",
"state",
"--jq",
".state",
], ghEnv);
return result.success ? result.stdout : null;
};
const prIsOpen = (repo, prNumber, ghEnv) => {
return getPrState(repo, prNumber, ghEnv) === "OPEN";
};
const getPrNumberFromWorkspaceBranch = (branch) => {
const match = branch.match(/^pr-refs-pull-([0-9]+)-head$/);
if (!match) {
return null;
}
const prNumber = parseInt(match[1], 10);
return Number.isNaN(prNumber) ? null : prNumber;
};
const findPrContext = (repos, branch, verbose, ghEnv) => {
for (const repo of repos) {
log(verbose, `Checking open PR in ${repo} for branch ${branch}`);
const prNumber = getPrNumberFromBranch(repo, branch, ghEnv);
if (prNumber !== null && prIsOpen(repo, prNumber, ghEnv)) {
return { repo, prNumber };
}
if (prNumber !== null) {
log(verbose, `Skipping PR #${prNumber} in ${repo}: PR is not open`);
}
}
const workspacePrNumber = getPrNumberFromWorkspaceBranch(branch);
if (workspacePrNumber === null) {
return null;
}
for (const repo of repos) {
log(verbose, `Checking workspace PR #${workspacePrNumber} in ${repo} for branch ${branch}`);
if (prIsOpen(repo, workspacePrNumber, ghEnv)) {
return { repo, prNumber: workspacePrNumber };
}
}
return null;
};
const findSessionDirs = (explicitPath, verbose) => {
const dirs = [];
if (explicitPath) {
const allowedPath = resolveAllowedSessionDir(path.resolve(explicitPath), verbose);
if (allowedPath === null) {
console.error(
`[session-backup] --session-dir must point to a directory under ${SESSION_DIR_NAMES
.map((dirName) => `~/${dirName}`)
.join(", ")}`
);
process.exit(1);
}
dirs.push({ name: path.basename(allowedPath), path: allowedPath });
return dirs;
}
for (const root of getAllowedSessionRoots()) {
const allowedPath = resolveAllowedSessionDir(root.path, verbose);
if (allowedPath !== null) {
log(verbose, `Found session directory: ${allowedPath}`);
dirs.push({ name: root.name, path: allowedPath });
}
}
return dirs;
};
const collectSessionFiles = (dirPath, baseName, verbose) => {
const files = [];
const walk = (currentPath, relativePath) => {
const entries = fs.readdirSync(currentPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(currentPath, entry.name);
const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
const logicalRelPath = toLogicalRelativePath(relPath);
if (shouldIgnoreSessionPath(logicalRelPath)) {
log(verbose, `Skipping tmp path: ${path.posix.join(baseName, logicalRelPath)}`);
continue;
}
if (entry.isDirectory()) {
if (SESSION_WALK_IGNORE_DIR_NAMES.has(entry.name)) {
continue;
}
walk(fullPath, relPath);
} else if (entry.isFile()) {
try {
const stats = fs.statSync(fullPath);
const logicalName = path.posix.join(baseName, logicalRelPath);
files.push({
logicalName,
sourcePath: fullPath,
size: stats.size,
});
log(verbose, `Collected file: ${logicalName} (${stats.size} bytes)`);
} catch (error) {
log(verbose, `Error reading file ${fullPath}: ${error.message}`);
}
}
}
};
walk(dirPath, "");
return files;
};
const buildManifest = ({ backupRepo, snapshotRef, source, files, createdAt }) => ({
version: 1,
createdAt,
storage: {
repo: backupRepo.fullName,
branch: backupRepo.defaultBranch,
snapshotRef,
},
source,
files,
});
const formatBytes = (bytes) => {
if (bytes >= 1_000_000_000) {
return `${(bytes / 1_000_000_000).toFixed(2)} GB`;
}
if (bytes >= 1_000_000) {
return `${(bytes / 1_000_000).toFixed(2)} MB`;
}
if (bytes >= 1_000) {
return `${(bytes / 1_000).toFixed(2)} KB`;
}
return `${bytes} B`;
};
const summarizeFiles = (files) => ({
fileCount: files.length,
totalBytes: files.reduce(
(sum, file) => sum + (file.type === "chunked" ? (file.originalSize ?? 0) : (file.size ?? 0)),
0
),
});
const buildSnapshotReadme = ({ backupRepo, source, manifestUrl, summary, sessionRoots }) =>
[
"# AI Session Backup",
"",
"This snapshot contains AI session data used during development.",
"",
`- Backup Repo: \`${backupRepo.fullName}\``,
`- Source Repo: \`${source.repo}\``,
`- Source Branch: \`${source.branch}\``,
`- Source Commit: \`${source.commitSha}\``,
source.prNumber === null ? "- Pull Request: none" : `- Pull Request: #${source.prNumber}`,
`- Created At: \`${source.createdAt}\``,
`- Files: \`${summary.fileCount}\``,
`- Total Size: \`${formatBytes(summary.totalBytes)}\``,
`- Session Roots: \`${sessionRoots.join("`, `")}\``,
"",
`- Manifest: ${manifestUrl}`,
"",
"Generated automatically by the docker-git `git push` post-action.",
"",
].join("\n");
const buildCommentBody = ({ source, manifestUrl, readmeUrl, summary, gitStatus }) => {
const statusText = gitStatus === null ? "(unavailable)" : gitStatus;
const lines = [
"## AI Session Backup",
`Commit: ${source.commitSha}`,
`Files: ${summary.fileCount} (${formatBytes(summary.totalBytes)})`,
`Links: [README](${readmeUrl}) | [Manifest](${manifestUrl})`,
"",
"`git status`",
"```",
statusText,
"```",
];
lines.push(`<!-- docker-git-session-backup:${source.commitSha}:${source.createdAt} -->`);
return lines.join("\n");
};
const postPrComment = (repo, prNumber, comment, verbose, ghEnv) => {
log(verbose, `Posting comment to PR #${prNumber}`);
const result = ghCommand([
"pr",
"comment",
prNumber.toString(),
"--repo",
repo,
"--body",
comment,
], ghEnv);
if (!result.success) {
console.error(`[session-backup] Failed to post PR comment: ${result.stderr}`);
return false;
}
log(verbose, "Comment posted successfully");
return true;
};
const main = () => {
if (process.env.DOCKER_GIT_SKIP_SESSION_BACKUP === "1") {
console.log("[session-backup] Skipped (DOCKER_GIT_SKIP_SESSION_BACKUP=1)");
return;
}
const args = parseArgs();
const verbose = args.verbose;
const ghEnv = resolveGhEnvironment(process.cwd(), (message) => log(verbose, message));
log(verbose, "Starting session backup...");
const repoCandidates = getRepoCandidates(args.repo, verbose);
if (repoCandidates.length === 0) {
console.error("[session-backup] Could not determine source repository. Use --repo option.");
process.exit(1);
}
const sourceRepo = repoCandidates[0];
log(verbose, `Repository: ${sourceRepo}`);
const branch = getCurrentBranch();
if (!branch) {
console.error("[session-backup] Could not determine current branch.");
process.exit(1);
}
log(verbose, `Branch: ${branch}`);
const commitSha = getHeadCommitSha();
if (!commitSha) {
console.error("[session-backup] Could not determine current commit.");
process.exit(1);
}
let prContext = null;
if (args.prNumber !== null) {
if (prIsOpen(sourceRepo, args.prNumber, ghEnv)) {
prContext = { repo: sourceRepo, prNumber: args.prNumber };
} else {
log(verbose, `Skipping PR comment: PR #${args.prNumber} is not open`);
}
} else if (args.postComment) {
prContext = findPrContext(repoCandidates, branch, verbose, ghEnv);
}
if (prContext !== null) {
log(verbose, `PR number: ${prContext.prNumber} (${prContext.repo})`);
} else if (args.postComment) {
log(verbose, "No PR found for current branch, skipping comment");
}
const sessionDirs = findSessionDirs(args.sessionDir, verbose);
if (sessionDirs.length === 0) {
log(verbose, "No session directories found");
return;
}
const sessionFiles = [];
for (const dir of sessionDirs) {
sessionFiles.push(...collectSessionFiles(dir.path, dir.name, verbose));
}
if (sessionFiles.length === 0) {
log(verbose, "No session files found to backup");
return;
}
log(verbose, `Total files to backup: ${sessionFiles.length}`);
const backupRepo = ensureBackupRepo(ghEnv, (message) => log(verbose, message), !args.dryRun);
if (backupRepo === null) {
console.error("[session-backup] Failed to resolve or create the private session backup repository");
process.exit(1);
}
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "session-backup-repo-"));
try {
const snapshotCreatedAt = new Date().toISOString();
const snapshotRef = buildSnapshotRef(sourceRepo, prContext?.prNumber ?? null, commitSha, snapshotCreatedAt);
const prepared = prepareUploadArtifacts(
sessionFiles,
snapshotRef,
backupRepo.fullName,
backupRepo.defaultBranch,
tmpDir,
(message) => log(verbose, message)
);
const source = {
repo: sourceRepo,
branch,
prNumber: prContext?.prNumber ?? null,
commitSha,
createdAt: snapshotCreatedAt,
};
const summary = summarizeFiles(prepared.manifestFiles);
const sessionRoots = sessionDirs.map((dir) => `~/${dir.name}`);
const manifestUrl = buildBlobUrl(backupRepo.fullName, backupRepo.defaultBranch, `${snapshotRef}/manifest.json`);
const readmeRepoPath = `${snapshotRef}/README.md`;
const readmeUrl = buildBlobUrl(backupRepo.fullName, backupRepo.defaultBranch, readmeRepoPath);
const gitStatus = getGitStatus();
const manifest = buildManifest({
backupRepo,
snapshotRef,
source,
files: prepared.manifestFiles,
createdAt: snapshotCreatedAt,
});
const readmePath = path.join(tmpDir, "README.md");
fs.writeFileSync(
readmePath,
buildSnapshotReadme({
backupRepo,
source,
manifestUrl,
summary,
sessionRoots,
}),
"utf8"
);
const uploadEntries = [
...prepared.uploadEntries,
{
repoPath: readmeRepoPath,
sourcePath: readmePath,
type: "readme",
size: fs.statSync(readmePath).size,
},
];
if (args.dryRun) {
console.log(
`[session-backup] dry-run: ${source.commitSha.slice(0, 12)} (${summary.fileCount} files, ${formatBytes(summary.totalBytes)})`
);
printGitStatus(gitStatus);
log(verbose, `[dry-run] Upload target: ${backupRepo.fullName}:${snapshotRef}`);
log(verbose, `[dry-run] README URL: ${readmeUrl}`);
log(verbose, `[dry-run] Manifest URL: ${manifestUrl}`);
if (args.postComment && prContext !== null) {
log(verbose, `Would post comment to PR #${prContext.prNumber} in ${prContext.repo}:`);
log(verbose, buildCommentBody({ source, manifestUrl, readmeUrl, summary, gitStatus }));
}
return;
}
log(verbose, `Uploading snapshot to ${backupRepo.fullName}:${snapshotRef}`);
const uploadResult = uploadSnapshot(
backupRepo,
snapshotRef,
manifest,
uploadEntries,
ghEnv
);
console.log(
`[session-backup] ok: ${source.commitSha.slice(0, 12)} (${summary.fileCount} files, ${formatBytes(summary.totalBytes)})`
);
printGitStatus(gitStatus);
log(verbose, `[session-backup] Uploaded snapshot to ${backupRepo.fullName}:${snapshotRef}`);
log(verbose, `[session-backup] Manifest: ${uploadResult.manifestUrl}`);
if (args.postComment && prContext !== null) {
const comment = buildCommentBody({
source,
manifestUrl: uploadResult.manifestUrl,
readmeUrl,
summary,
gitStatus,
});
postPrComment(prContext.repo, prContext.prNumber, comment, verbose, ghEnv);
}
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
};
if (require.main === module) {
main();
}
module.exports = {
collectSessionFiles,
shouldIgnoreSessionPath,
};