|
| 1 | +import { spawn, execFile } from 'node:child_process'; |
| 2 | +import { promisify } from 'node:util'; |
| 3 | +import { mkdir, writeFile, readdir, stat } from 'node:fs/promises'; |
| 4 | +import path from 'node:path'; |
| 5 | +import crypto from 'node:crypto'; |
| 6 | +import { createWorktree, isGitRepo, gc } from '@cobusgreyling/loop-worktree'; |
| 7 | +const runExec = promisify(execFile); |
| 8 | +/** Run a git command in cwd, returning stdout trimmed. Throws on error. */ |
| 9 | +async function git(args, cwd) { |
| 10 | + const { stdout } = await runExec('git', args, { cwd, maxBuffer: 50 * 1024 * 1024 }); |
| 11 | + return stdout.trim(); |
| 12 | +} |
| 13 | +/** Run a git command in cwd, returning raw untrimmed Buffer (for binary patches). Throws on error. */ |
| 14 | +async function gitRaw(args, cwd) { |
| 15 | + return new Promise((resolve, reject) => { |
| 16 | + execFile('git', args, { cwd, encoding: 'buffer', maxBuffer: 50 * 1024 * 1024 }, (err, stdout) => { |
| 17 | + if (err) |
| 18 | + reject(err); |
| 19 | + else |
| 20 | + resolve(stdout); |
| 21 | + }); |
| 22 | + }); |
| 23 | +} |
| 24 | +/** |
| 25 | + * Wraps an agent command in a temporary git worktree sandbox. |
| 26 | + * Returns the patch file path if changes were made. |
| 27 | + */ |
| 28 | +export async function runInSandbox(root, command, args, options = {}) { |
| 29 | + if (!(await isGitRepo(root))) { |
| 30 | + throw new Error('loop-sandbox must be run inside a git repository.'); |
| 31 | + } |
| 32 | + const runId = `sandbox-${crypto.randomBytes(4).toString('hex')}`; |
| 33 | + // 1. Setup paths |
| 34 | + const sandboxDir = path.join(root, '.loop-sandbox'); |
| 35 | + const patchesDir = path.join(sandboxDir, 'patches'); |
| 36 | + await mkdir(patchesDir, { recursive: true }); |
| 37 | + const baseBranch = options.base || await git(['rev-parse', '--abbrev-ref', 'HEAD'], root).catch(() => 'main'); |
| 38 | + console.log(`\n📦 Creating ephemeral worktree isolation: ${runId}`); |
| 39 | + // 2. Create the worktree |
| 40 | + const entry = await createWorktree({ |
| 41 | + root, |
| 42 | + runId, |
| 43 | + pattern: 'sandbox', // dummy pattern |
| 44 | + base: baseBranch |
| 45 | + }); |
| 46 | + const worktreeAbsPath = path.resolve(root, entry.path); |
| 47 | + console.log(`🚀 Executing inside sandbox: ${command} ${args.join(' ')}`); |
| 48 | + let exitCode = null; |
| 49 | + let hasChanges = false; |
| 50 | + let patchFilePath = null; |
| 51 | + let extractionFailed = false; |
| 52 | + // Signal handlers for graceful cleanup if user ctrl+c's during run |
| 53 | + let isCleaningUp = false; |
| 54 | + const cleanup = async () => { |
| 55 | + if (isCleaningUp) |
| 56 | + return; |
| 57 | + isCleaningUp = true; |
| 58 | + if (extractionFailed) { |
| 59 | + console.log(`⚠️ Patch extraction failed. The worktree at ${worktreeAbsPath} and branch loop/${runId} were left on disk for manual recovery.`); |
| 60 | + return; |
| 61 | + } |
| 62 | + console.log(`🧹 Cleaning up sandbox worktree...`); |
| 63 | + try { |
| 64 | + await git(['worktree', 'remove', '--force', worktreeAbsPath], root); |
| 65 | + await git(['branch', '-D', `loop/${runId}`], root).catch(() => { }); |
| 66 | + await gc({ root, force: false }); |
| 67 | + } |
| 68 | + catch (err) { |
| 69 | + console.error(`❌ Failed to cleanup sandbox worktree. It may need manual removal:`, err); |
| 70 | + process.exitCode = 1; |
| 71 | + } |
| 72 | + }; |
| 73 | + const sigHandler = () => { |
| 74 | + cleanup().finally(() => process.exit(1)); |
| 75 | + }; |
| 76 | + process.on('SIGINT', sigHandler); |
| 77 | + process.on('SIGTERM', sigHandler); |
| 78 | + try { |
| 79 | + // 3. Execute the user's command |
| 80 | + try { |
| 81 | + const child = spawn(command, args, { |
| 82 | + cwd: worktreeAbsPath, |
| 83 | + stdio: 'inherit', |
| 84 | + shell: options.shell ?? false |
| 85 | + }); |
| 86 | + exitCode = await new Promise((resolve) => { |
| 87 | + child.on('close', (code) => resolve(code)); |
| 88 | + child.on('error', () => resolve(1)); |
| 89 | + }); |
| 90 | + } |
| 91 | + catch (err) { |
| 92 | + console.error(`❌ Execution failed inside sandbox:`, err); |
| 93 | + exitCode = 1; |
| 94 | + } |
| 95 | + console.log(`\n🔍 Scanning sandbox for changes...`); |
| 96 | + // 4. Extract diff as a patch |
| 97 | + try { |
| 98 | + await git(['add', '-A'], worktreeAbsPath); |
| 99 | + const diffStat = await git(['diff', '--cached', '--stat'], worktreeAbsPath); |
| 100 | + if (diffStat) { |
| 101 | + hasChanges = true; |
| 102 | + patchFilePath = path.join(patchesDir, `${runId}.patch`); |
| 103 | + const diffOutput = await gitRaw(['diff', '--cached', '--binary'], worktreeAbsPath); |
| 104 | + await writeFile(patchFilePath, diffOutput); |
| 105 | + console.log(`✅ Sandbox changes captured to patch: ${patchFilePath}`); |
| 106 | + } |
| 107 | + else { |
| 108 | + console.log(`ℹ️ No changes were made in the sandbox.`); |
| 109 | + } |
| 110 | + } |
| 111 | + catch (err) { |
| 112 | + console.error(`❌ Failed to extract patch from sandbox:`, err); |
| 113 | + extractionFailed = true; |
| 114 | + } |
| 115 | + } |
| 116 | + finally { |
| 117 | + process.removeListener('SIGINT', sigHandler); |
| 118 | + process.removeListener('SIGTERM', sigHandler); |
| 119 | + await cleanup(); |
| 120 | + } |
| 121 | + return { |
| 122 | + runId, |
| 123 | + patchFile: patchFilePath, |
| 124 | + exitCode, |
| 125 | + hasChanges |
| 126 | + }; |
| 127 | +} |
| 128 | +/** Lists all available patches in the .loop-sandbox/patches/ directory. */ |
| 129 | +export async function listPatches(root) { |
| 130 | + const patchesDir = path.join(root, '.loop-sandbox', 'patches'); |
| 131 | + try { |
| 132 | + const files = await readdir(patchesDir, { withFileTypes: true }); |
| 133 | + const patches = []; |
| 134 | + for (const f of files) { |
| 135 | + if (f.isFile() && f.name.endsWith('.patch')) { |
| 136 | + const patchPath = path.join(patchesDir, f.name); |
| 137 | + const s = await stat(patchPath); |
| 138 | + patches.push({ |
| 139 | + patchName: f.name, |
| 140 | + patchPath, |
| 141 | + size: s.size |
| 142 | + }); |
| 143 | + } |
| 144 | + } |
| 145 | + return patches; |
| 146 | + } |
| 147 | + catch { |
| 148 | + return []; |
| 149 | + } |
| 150 | +} |
0 commit comments