Skip to content

Practical patterns, starters & CLI tools for loop engineering with AI coding agents. Design systems that prompt and orchestrate agents (inspired by Addy Osmani and Boris Cherny). Includes loop-audit, loop-init, loop-cost.

feat: introduce loop-sandbox for isolated worktree execution (#370)

THRISHAL DOMAf02f5043b2d3
diff --git a/package.json b/package.json
index 43f2356..6250038 100644
--- a/package.json
+++ b/package.json
@@ -13,11 +13,12 @@
"test:loop-gate": "cd tools/loop-gate && npm test",
"test:mcp-server": "cd tools/mcp-server && npm test",
"test:loop-worktree": "cd tools/loop-worktree && npm test",
+ "test:loop-sandbox": "cd tools/loop-sandbox && npm test",
"test:goal-init": "cd tools/goal-init && npm test",
"test:readiness-core": "cd tools/readiness-core && npm test",
"test:goal-audit": "cd tools/goal-audit && npm test",
- "test:tools": "npm run test:readiness-core && npm run test:loop-audit && npm run test:loop-init && npm run test:loop-cost && npm run test:loop-sync && npm run test:loop-context && npm run test:loop-gate && npm run test:mcp-server && npm run test:loop-worktree && npm run test:goal-audit && npm run test:goal-init",
- "build:tools": "cd tools/readiness-core && npm run build && cd ../loop-audit && npm run build && cd ../loop-init && npm run build && cd ../loop-cost && npm run build && cd ../loop-sync && npm run build && cd ../loop-context && npm run build && cd ../loop-gate && npm run build && cd ../mcp-server && npm run build && cd ../loop-worktree && npm run build && cd ../goal-audit && npm run build && cd ../goal-init && npm run build",
+ "test:tools": "npm run test:readiness-core && npm run test:loop-audit && npm run test:loop-init && npm run test:loop-cost && npm run test:loop-sync && npm run test:loop-context && npm run test:loop-gate && npm run test:mcp-server && npm run test:loop-worktree && npm run test:loop-sandbox && npm run test:goal-audit && npm run test:goal-init",
+ "build:tools": "cd tools/readiness-core && npm run build && cd ../loop-audit && npm run build && cd ../loop-init && npm run build && cd ../loop-cost && npm run build && cd ../loop-sync && npm run build && cd ../loop-context && npm run build && cd ../loop-gate && npm run build && cd ../mcp-server && npm run build && cd ../loop-worktree && npm run build && cd ../loop-sandbox && npm run build && cd ../goal-audit && npm run build && cd ../goal-init && npm run build",
"contributors:generate": "node scripts/generate-contributors.mjs",
"contributors:check": "node scripts/generate-contributors.mjs --check"
},
diff --git a/tools/loop-sandbox/README.md b/tools/loop-sandbox/README.md
new file mode 100644
index 0000000..104f69f
--- /dev/null
+++ b/tools/loop-sandbox/README.md
@@ -0,0 +1,81 @@
+# loop-sandbox
+
+Ephemeral worktree isolation for Loop Engineering. Divert agent execution into an isolated git worktree, capture their changes as a reviewable `.patch` file, and instantly destroy the sandbox.
+
+## Why loop-sandbox?
+
+Unattended AI agents (loops) running directly in your main working tree can cause damage, overwrite untracked files, or make it incredibly tedious to untangle failed execution attempts.
+
+`loop-sandbox` solves this by providing **ephemeral worktree isolation**:
+1. It automatically creates an isolated git worktree for the agent to run in.
+2. The agent runs its command, interacting with the codebase completely naturally.
+3. When the command finishes, `loop-sandbox` automatically captures the agent's edits (including new untracked files) into a clean `.patch` file.
+4. It nukes the worktree, keeping your main repo completely clean.
+
+A human can then safely review the patch and apply it with one keystroke.
+
+> [!WARNING]
+> **Isolation Limits:** This is not a containerized air-gap. The agent process retains full filesystem and network access. It can escape the worktree (e.g. `../../`), and changes outside the worktree or to `.gitignored` files will **not** be captured in the patch. This tool is complementary to [docs/safety.md](../../docs/safety.md) and does not replace OS-level sandboxing for hostile code.
+
+## Installation
+
+```bash
+npm install -g @cobusgreyling/loop-sandbox
+# or run directly via npx
+npx @cobusgreyling/loop-sandbox run -- <command>
+```
+
+> [!IMPORTANT]
+> **Required Gitignores:** You must add the following to your project's `.gitignore` to prevent patches and worktree manifests from being committed:
+> ```
+> .loop-sandbox/
+> .loop-worktrees/
+> ```
+
+## Usage
+
+```bash
+loop-sandbox <command> [options]
+```
+
+### Commands
+
+| Command | Description |
+|---------|-------------|
+| `run [opts] -- <cmd>` | Run an agent command inside the isolated sandbox |
+| `review` / `list` | List isolated patches ready for human review |
+
+### Options for `run`
+
+| Option | Description |
+|--------|-------------|
+| `--shell` | Spawns the command using `shell: true` (for bash -c, etc.) |
+| `--base <branch>` | The base branch for the worktree (defaults to current HEAD) |
+
+### Examples
+
+**Running a tool via an agent:**
+```bash
+# Safely let an agent run your linter/formatter without polluting your working tree
+npx @cobusgreyling/loop-sandbox run -- npx my-agent
+```
+
+**Running a shell command:**
+```bash
+npx @cobusgreyling/loop-sandbox run --shell -- bash -c "echo 'hello' > test.txt"
+```
+
+**Reviewing and applying patches:**
+```bash
+# List all patches the sandbox caught
+npx @cobusgreyling/loop-sandbox review
+
+# Example output:
+# === Loop Sandbox Patches ===
+# 📄 sandbox-82f1e394.patch (1.2 KB)
+# Apply: git apply .loop-sandbox/patches/sandbox-82f1e394.patch
+```
+
+## How it works
+
+Under the hood, `loop-sandbox` leverages `@cobusgreyling/loop-worktree` and native `git worktree` primitives. It creates a temporary branch from your current HEAD, spawns your process with its `cwd` set to the isolated tree, runs `git diff --cached` to generate the patch, and uses `git worktree remove --force` to clean up.
diff --git a/tools/loop-sandbox/dist/cli.d.ts b/tools/loop-sandbox/dist/cli.d.ts
new file mode 100644
index 0000000..b798801
--- /dev/null
+++ b/tools/loop-sandbox/dist/cli.d.ts
@@ -0,0 +1,2 @@
+#!/usr/bin/env node
+export {};
diff --git a/tools/loop-sandbox/dist/cli.js b/tools/loop-sandbox/dist/cli.js
new file mode 100644
index 0000000..5721526
--- /dev/null
+++ b/tools/loop-sandbox/dist/cli.js
@@ -0,0 +1,110 @@
+#!/usr/bin/env node
+import path from 'node:path';
+import { runInSandbox, listPatches } from './sandbox.js';
+async function main() {
+ const args = process.argv.slice(2);
+ if (args.length === 0 || args[0] === 'help' || args[0] === '--help') {
+ printHelp();
+ process.exit(0);
+ }
+ const command = args[0];
+ const root = process.cwd();
+ if (command === 'run') {
+ const runArgs = args.slice(1);
+ let targetCommandIndex = runArgs.findIndex(a => a === '--');
+ if (targetCommandIndex === -1) {
+ console.error('❌ Missing `--` separator before the command. Usage: loop-sandbox run [options] -- <command>');
+ process.exit(1);
+ }
+ const sandboxOptionsArgs = runArgs.slice(0, targetCommandIndex);
+ const targetCommandArgs = runArgs.slice(targetCommandIndex + 1);
+ if (targetCommandArgs.length === 0) {
+ console.error('❌ Missing command to run. Usage: loop-sandbox run [options] -- <command>');
+ process.exit(1);
+ }
+ let shell = false;
+ let base;
+ for (let i = 0; i < sandboxOptionsArgs.length; i++) {
+ const arg = sandboxOptionsArgs[i];
+ if (arg === '--shell') {
+ shell = true;
+ }
+ else if (arg === '--base') {
+ base = sandboxOptionsArgs[++i];
+ }
+ else {
+ console.error(`❌ Unknown option: ${arg}`);
+ process.exit(1);
+ }
+ }
+ const exe = targetCommandArgs[0];
+ const exeArgs = targetCommandArgs.slice(1);
+ try {
+ const result = await runInSandbox(root, exe, exeArgs, { shell, base });
+ if (result.hasChanges && result.patchFile) {
+ console.log('\n==================================================');
+ console.log(`🎉 Run completed. Changes isolated successfully!`);
+ console.log(`To review the changes, run:`);
+ console.log(` npx @cobusgreyling/loop-sandbox review`);
+ console.log(`\nTo apply the changes immediately, run:`);
+ console.log(` git apply ${path.relative(root, result.patchFile)}`);
+ console.log('==================================================\n');
+ }
+ else {
+ console.log(`\nℹ️ Run completed with exit code ${result.exitCode ?? 0}. No changes detected.`);
+ }
+ process.exit(result.exitCode ?? 0);
+ }
+ catch (err) {
+ console.error(`❌ sandbox error: ${err.message}`);
+ process.exit(1);
+ }
+ }
+ else if (command === 'review' || command === 'list') {
+ try {
+ const patches = await listPatches(root);
+ if (patches.length === 0) {
+ console.log('No sandbox patches found in .loop-sandbox/patches/');
+ return;
+ }
+ console.log('\n=== Loop Sandbox Patches ===\n');
+ for (const p of patches) {
+ const kb = (p.size / 1024).toFixed(1);
+ console.log(`📄 ${p.patchName} (${kb} KB)`);
+ console.log(` Apply: git apply ${path.relative(root, p.patchPath)}`);
+ }
+ console.log('');
+ }
+ catch (err) {
+ console.error(`❌ sandbox error: ${err.message}`);
+ process.exit(1);
+ }
+ }
+ else {
+ console.error(`❌ Unknown command: ${command}`);
+ printHelp();
+ process.exit(1);
+ }
+}
+function printHelp() {
+ console.log(`
+loop-sandbox — Ephemeral worktree isolation for agents.
+
+Usage:
+ loop-sandbox run [options] -- <command> Run an agent command inside an isolated worktree.
+ loop-sandbox review List isolated patches ready for human review.
+
+Options for 'run':
+ --shell Run the command inside a shell environment (shell: true)
+ --base The base branch to branch the worktree from (default: current HEAD)
+
+Examples:
+ npx @cobusgreyling/loop-sandbox run -- node script.js
+ npx @cobusgreyling/loop-sandbox run --shell -- bash -c "echo 'hello' > test.txt"
+ npx @cobusgreyling/loop-sandbox review
+`);
+}
+main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/tools/loop-sandbox/dist/sandbox.d.ts b/tools/loop-sandbox/dist/sandbox.d.ts
new file mode 100644
index 0000000..2a88b73
--- /dev/null
+++ b/tools/loop-sandbox/dist/sandbox.d.ts
@@ -0,0 +1,22 @@
+export interface SandboxOptions {
+ shell?: boolean;
+ base?: string;
+}
+export interface SandboxResult {
+ runId: string;
+ patchFile: string | null;
+ exitCode: number | null;
+ hasChanges: boolean;
+}
+/**
+ * Wraps an agent command in a temporary git worktree sandbox.
+ * Returns the patch file path if changes were made.
+ */
+export declare function runInSandbox(root: string, command: string, args: string[], options?: SandboxOptions): Promise<SandboxResult>;
+export interface ReviewItem {
+ patchName: string;
+ patchPath: string;
+ size: number;
+}
+/** Lists all available patches in the .loop-sandbox/patches/ directory. */
+export declare function listPatches(root: string): Promise<ReviewItem[]>;
diff --git a/tools/loop-sandbox/dist/sandbox.js b/tools/loop-sandbox/dist/sandbox.js
new file mode 100644
index 0000000..73d60a6
--- /dev/null
+++ b/tools/loop-sandbox/dist/sandbox.js
@@ -0,0 +1,150 @@
+import { spawn, execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+import { mkdir, writeFile, readdir, stat } from 'node:fs/promises';
+import path from 'node:path';
+import crypto from 'node:crypto';
+import { createWorktree, isGitRepo, gc } from '@cobusgreyling/loop-worktree';
+const runExec = promisify(execFile);
+/** Run a git command in cwd, returning stdout trimmed. Throws on error. */
+async function git(args, cwd) {
+ const { stdout } = await runExec('git', args, { cwd, maxBuffer: 50 * 1024 * 1024 });
+ return stdout.trim();
+}
+/** Run a git command in cwd, returning raw untrimmed Buffer (for binary patches). Throws on error. */
+async function gitRaw(args, cwd) {
+ return new Promise((resolve, reject) => {
+ execFile('git', args, { cwd, encoding: 'buffer', maxBuffer: 50 * 1024 * 1024 }, (err, stdout) => {
+ if (err)
+ reject(err);
+ else
+ resolve(stdout);
+ });
+ });
+}
+/**
+ * Wraps an agent command in a temporary git worktree sandbox.
+ * Returns the patch file path if changes were made.
+ */
+export async function runInSandbox(root, command, args, options = {}) {
+ if (!(await isGitRepo(root))) {
+ throw new Error('loop-sandbox must be run inside a git repository.');
+ }
+ const runId = `sandbox-${crypto.randomBytes(4).toString('hex')}`;
+ // 1. Setup paths
+ const sandboxDir = path.join(root, '.loop-sandbox');
+ const patchesDir = path.join(sandboxDir, 'patches');
+ await mkdir(patchesDir, { recursive: true });
+ const baseBranch = options.base || await git(['rev-parse', '--abbrev-ref', 'HEAD'], root).catch(() => 'main');
+ console.log(`\n📦 Creating ephemeral worktree isolation: ${runId}`);
+ // 2. Create the worktree
+ const entry = await createWorktree({
+ root,
+ runId,
+ pattern: 'sandbox', // dummy pattern
+ base: baseBranch
+ });
+ const worktreeAbsPath = path.resolve(root, entry.path);
+ console.log(`🚀 Executing inside sandbox: ${command} ${args.join(' ')}`);
+ let exitCode = null;
+ let hasChanges = false;
+ let patchFilePath = null;
+ let extractionFailed = false;
+ // Signal handlers for graceful cleanup if user ctrl+c's during run
+ let isCleaningUp = false;
+ const cleanup = async () => {
+ if (isCleaningUp)
+ return;
+ isCleaningUp = true;
+ if (extractionFailed) {
+ console.log(`⚠️ Patch extraction failed. The worktree at ${worktreeAbsPath} and branch loop/${runId} were left on disk for manual recovery.`);
+ return;
+ }
+ console.log(`🧹 Cleaning up sandbox worktree...`);
+ try {
+ await git(['worktree', 'remove', '--force', worktreeAbsPath], root);
+ await git(['branch', '-D', `loop/${runId}`], root).catch(() => { });
+ await gc({ root, force: false });
+ }
+ catch (err) {
+ console.error(`❌ Failed to cleanup sandbox worktree. It may need manual removal:`, err);
+ process.exitCode = 1;
+ }
+ };
+ const sigHandler = () => {
+ cleanup().finally(() => process.exit(1));
+ };
+ process.on('SIGINT', sigHandler);
+ process.on('SIGTERM', sigHandler);
+ try {
+ // 3. Execute the user's command
+ try {
+ const child = spawn(command, args, {
+ cwd: worktreeAbsPath,
+ stdio: 'inherit',
+ shell: options.shell ?? false
+ });
+ exitCode = await new Promise((resolve) => {
+ child.on('close', (code) => resolve(code));
+ child.on('error', () => resolve(1));
+ });
+ }
+ catch (err) {
+ console.error(`❌ Execution failed inside sandbox:`, err);
+ exitCode = 1;
+ }
+ console.log(`\n🔍 Scanning sandbox for changes...`);
+ // 4. Extract diff as a patch
+ try {
+ await git(['add', '-A'], worktreeAbsPath);
+ const diffStat = await git(['diff', '--cached', '--stat'], worktreeAbsPath);
+ if (diffStat) {
+ hasChanges = true;
+ patchFilePath = path.join(patchesDir, `${runId}.patch`);
+ const diffOutput = await gitRaw(['diff', '--cached', '--binary'], worktreeAbsPath);
+ await writeFile(patchFilePath, diffOutput);
+ console.log(`✅ Sandbox changes captured to patch: ${patchFilePath}`);
+ }
+ else {
+ console.log(`ℹ️ No changes were made in the sandbox.`);
+ }
+ }
+ catch (err) {
+ console.error(`❌ Failed to extract patch from sandbox:`, err);
+ extractionFailed = true;
+ }
+ }
+ finally {
+ process.removeListener('SIGINT', sigHandler);
+ process.removeListener('SIGTERM', sigHandler);
+ await cleanup();
+ }
+ return {
+ runId,
+ patchFile: patchFilePath,
+ exitCode,
+ hasChanges
+ };
+}
+/** Lists all available patches in the .loop-sandbox/patches/ directory. */
+export async function listPatches(root) {
+ const patchesDir = path.join(root, '.loop-sandbox', 'patches');
+ try {
+ const files = await readdir(patchesDir, { withFileTypes: true });
+ const patches = [];
+ for (const f of files) {
+ if (f.isFile() && f.name.endsWith('.patch')) {
+ const patchPath = path.join(patchesDir, f.name);
+ const s = await stat(patchPath);
+ patches.push({
+ patchName: f.name,
+ patchPath,
+ size: s.size
+ });
+ }
+ }
+ return patches;
+ }
+ catch {
+ return [];
+ }
+}
diff --git a/tools/loop-sandbox/package-lock.json b/tools/loop-sandbox/package-lock.json
new file mode 100644
index 0000000..b625959
--- /dev/null
+++ b/tools/loop-sandbox/package-lock.json
@@ -0,0 +1,76 @@
+{
+ "name": "@cobusgreyling/loop-sandbox",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@cobusgreyling/loop-sandbox",
+ "version": "1.0.0",
+ "license": "MIT",
+ "dependencies": {
+ "@cobusgreyling/loop-worktree": "file:../loop-worktree"
+ },
+ "bin": {
+ "loop-sandbox": "dist/cli.js"
+ },
+ "devDependencies": {
+ "@types/node": "^20.0.0",
+ "typescript": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "../loop-worktree": {
+ "name": "@cobusgreyling/loop-worktree",
+ "version": "1.2.0",
+ "license": "MIT",
+ "bin": {
+ "loop-worktree": "dist/cli.js"
+ },
+ "devDependencies": {
+ "@types/node": "^20.0.0",
+ "typescript": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@cobusgreyling/loop-worktree": {
+ "resolved": "../loop-worktree",
+ "link": true
+ },
+ "node_modules/@types/node": {
+ "version": "20.19.43",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz",
+ "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~6.21.0"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
+ "dev": true,
+ "license": "MIT"
+ }
+ }
+}
diff --git a/tools/loop-sandbox/package.json b/tools/loop-sandbox/package.json
new file mode 100644
index 0000000..224803b
--- /dev/null
+++ b/tools/loop-sandbox/package.json
@@ -0,0 +1,47 @@
+{
+ "name": "@cobusgreyling/loop-sandbox",
+ "version": "1.0.0",
+ "description": "The ultimate L2 safety mechanism. Diverts agent execution into an ephemeral git worktree, captures their changes as a .patch file, and destroys the sandbox.",
+ "type": "module",
+ "bin": {
+ "loop-sandbox": "./dist/cli.js"
+ },
+ "files": [
+ "dist",
+ "README.md"
+ ],
+ "scripts": {
+ "build": "tsc",
+ "test": "npm run build && node --test test/*.test.mjs",
+ "prepublishOnly": "npm test",
+ "start": "node dist/cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "keywords": [
+ "loop-engineering",
+ "ai-agents",
+ "coding-agents",
+ "sandbox",
+ "security"
+ ],
+ "author": "Cobus Greyling",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/cobusgreyling/loop-engineering.git",
+ "directory": "tools/loop-sandbox"
+ },
+ "homepage": "https://cobusgreyling.github.io/loop-engineering/",
+ "publishConfig": {
+ "access": "public"
+ },
+ "dependencies": {
+ "@cobusgreyling/loop-worktree": "^1.2.0"
+ },
+ "devDependencies": {
+ "@types/node": "^20.0.0",
+ "typescript": "^5.0.0"
+ }
+}
diff --git a/tools/loop-sandbox/src/cli.ts b/tools/loop-sandbox/src/cli.ts
new file mode 100644
index 0000000..de04871
--- /dev/null
+++ b/tools/loop-sandbox/src/cli.ts
@@ -0,0 +1,122 @@
+#!/usr/bin/env node
+
+import path from 'node:path';
+import { runInSandbox, listPatches } from './sandbox.js';
+
+async function main() {
+ const args = process.argv.slice(2);
+
+ if (args.length === 0 || args[0] === 'help' || args[0] === '--help') {
+ printHelp();
+ process.exit(0);
+ }
+
+ const command = args[0];
+ const root = process.cwd();
+
+ if (command === 'run') {
+ const runArgs = args.slice(1);
+
+ let targetCommandIndex = runArgs.findIndex(a => a === '--');
+ if (targetCommandIndex === -1) {
+ console.error('❌ Missing `--` separator before the command. Usage: loop-sandbox run [options] -- <command>');
+ process.exit(1);
+ }
+
+ const sandboxOptionsArgs = runArgs.slice(0, targetCommandIndex);
+ const targetCommandArgs = runArgs.slice(targetCommandIndex + 1);
+
+ if (targetCommandArgs.length === 0) {
+ console.error('❌ Missing command to run. Usage: loop-sandbox run [options] -- <command>');
+ process.exit(1);
+ }
+
+ let shell = false;
+ let base: string | undefined;
+
+ for (let i = 0; i < sandboxOptionsArgs.length; i++) {
+ const arg = sandboxOptionsArgs[i];
+ if (arg === '--shell') {
+ shell = true;
+ } else if (arg === '--base') {
+ base = sandboxOptionsArgs[++i];
+ } else {
+ console.error(`❌ Unknown option: ${arg}`);
+ process.exit(1);
+ }
+ }
+
+ const exe = targetCommandArgs[0];
+ const exeArgs = targetCommandArgs.slice(1);
+
+ try {
+ const result = await runInSandbox(root, exe, exeArgs, { shell, base });
+
+ if (result.hasChanges && result.patchFile) {
+ console.log('\n==================================================');
+ console.log(`🎉 Run completed. Changes isolated successfully!`);
+ console.log(`To review the changes, run:`);
+ console.log(` npx @cobusgreyling/loop-sandbox review`);
+ console.log(`\nTo apply the changes immediately, run:`);
+ console.log(` git apply ${path.relative(root, result.patchFile)}`);
+ console.log('==================================================\n');
+ } else {
+ console.log(`\nℹ️ Run completed with exit code ${result.exitCode ?? 0}. No changes detected.`);
+ }
+
+ process.exit(result.exitCode ?? 0);
+ } catch (err) {
+ console.error(`❌ sandbox error: ${(err as Error).message}`);
+ process.exit(1);
+ }
+ }
+ else if (command === 'review' || command === 'list') {
+ try {
+ const patches = await listPatches(root);
+ if (patches.length === 0) {
+ console.log('No sandbox patches found in .loop-sandbox/patches/');
+ return;
+ }
+
+ console.log('\n=== Loop Sandbox Patches ===\n');
+ for (const p of patches) {
+ const kb = (p.size / 1024).toFixed(1);
+ console.log(`📄 ${p.patchName} (${kb} KB)`);
+ console.log(` Apply: git apply ${path.relative(root, p.patchPath)}`);
+ }
+ console.log('');
+ } catch (err) {
+ console.error(`❌ sandbox error: ${(err as Error).message}`);
+ process.exit(1);
+ }
+ }
+ else {
+ console.error(`❌ Unknown command: ${command}`);
+ printHelp();
+ process.exit(1);
+ }
+}
+
+function printHelp() {
+ console.log(`
+loop-sandbox — Ephemeral worktree isolation for agents.
+
+Usage:
+ loop-sandbox run [options] -- <command> Run an agent command inside an isolated worktree.
+ loop-sandbox review List isolated patches ready for human review.
+
+Options for 'run':
+ --shell Run the command inside a shell environment (shell: true)
+ --base The base branch to branch the worktree from (default: current HEAD)
+
+Examples:
+ npx @cobusgreyling/loop-sandbox run -- node script.js
+ npx @cobusgreyling/loop-sandbox run --shell -- bash -c "echo 'hello' > test.txt"
+ npx @cobusgreyling/loop-sandbox review
+`);
+}
+
+main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/tools/loop-sandbox/src/sandbox.ts b/tools/loop-sandbox/src/sandbox.ts
new file mode 100644
index 0000000..16e02a9
--- /dev/null
+++ b/tools/loop-sandbox/src/sandbox.ts
@@ -0,0 +1,185 @@
+import { spawn, execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+import { mkdir, writeFile, readdir, stat } from 'node:fs/promises';
+import path from 'node:path';
+import crypto from 'node:crypto';
+import { createWorktree, isGitRepo, gc } from '@cobusgreyling/loop-worktree';
+
+const runExec = promisify(execFile);
+
+export interface SandboxOptions {
+ shell?: boolean;
+ base?: string;
+}
+
+export interface SandboxResult {
+ runId: string;
+ patchFile: string | null;
+ exitCode: number | null;
+ hasChanges: boolean;
+}
+
+/** Run a git command in cwd, returning stdout trimmed. Throws on error. */
+async function git(args: string[], cwd: string): Promise<string> {
+ const { stdout } = await runExec('git', args, { cwd, maxBuffer: 50 * 1024 * 1024 });
+ return stdout.trim();
+}
+
+/** Run a git command in cwd, returning raw untrimmed Buffer (for binary patches). Throws on error. */
+async function gitRaw(args: string[], cwd: string): Promise<Buffer> {
+ return new Promise((resolve, reject) => {
+ execFile('git', args, { cwd, encoding: 'buffer', maxBuffer: 50 * 1024 * 1024 }, (err, stdout) => {
+ if (err) reject(err);
+ else resolve(stdout);
+ });
+ });
+}
+
+/**
+ * Wraps an agent command in a temporary git worktree sandbox.
+ * Returns the patch file path if changes were made.
+ */
+export async function runInSandbox(root: string, command: string, args: string[], options: SandboxOptions = {}): Promise<SandboxResult> {
+ if (!(await isGitRepo(root))) {
+ throw new Error('loop-sandbox must be run inside a git repository.');
+ }
+
+ const runId = `sandbox-${crypto.randomBytes(4).toString('hex')}`;
+
+ // 1. Setup paths
+ const sandboxDir = path.join(root, '.loop-sandbox');
+ const patchesDir = path.join(sandboxDir, 'patches');
+ await mkdir(patchesDir, { recursive: true });
+
+ const baseBranch = options.base || await git(['rev-parse', '--abbrev-ref', 'HEAD'], root).catch(() => 'main');
+
+ console.log(`\n📦 Creating ephemeral worktree isolation: ${runId}`);
+
+ // 2. Create the worktree
+ const entry = await createWorktree({
+ root,
+ runId,
+ pattern: 'sandbox', // dummy pattern
+ base: baseBranch
+ });
+
+ const worktreeAbsPath = path.resolve(root, entry.path);
+
+ console.log(`🚀 Executing inside sandbox: ${command} ${args.join(' ')}`);
+
+ let exitCode: number | null = null;
+ let hasChanges = false;
+ let patchFilePath: string | null = null;
+ let extractionFailed = false;
+
+ // Signal handlers for graceful cleanup if user ctrl+c's during run
+ let isCleaningUp = false;
+ const cleanup = async () => {
+ if (isCleaningUp) return;
+ isCleaningUp = true;
+
+ if (extractionFailed) {
+ console.log(`⚠️ Patch extraction failed. The worktree at ${worktreeAbsPath} and branch loop/${runId} were left on disk for manual recovery.`);
+ return;
+ }
+
+ console.log(`🧹 Cleaning up sandbox worktree...`);
+ try {
+ await git(['worktree', 'remove', '--force', worktreeAbsPath], root);
+ await git(['branch', '-D', `loop/${runId}`], root).catch(() => {});
+ await gc({ root, force: false });
+ } catch (err) {
+ console.error(`❌ Failed to cleanup sandbox worktree. It may need manual removal:`, err);
+ process.exitCode = 1;
+ }
+ };
+
+ const sigHandler = () => {
+ cleanup().finally(() => process.exit(1));
+ };
+
+ process.on('SIGINT', sigHandler);
+ process.on('SIGTERM', sigHandler);
+
+ try {
+ // 3. Execute the user's command
+ try {
+ const child = spawn(command, args, {
+ cwd: worktreeAbsPath,
+ stdio: 'inherit',
+ shell: options.shell ?? false
+ });
+
+ exitCode = await new Promise<number | null>((resolve) => {
+ child.on('close', (code) => resolve(code));
+ child.on('error', () => resolve(1));
+ });
+ } catch (err) {
+ console.error(`❌ Execution failed inside sandbox:`, err);
+ exitCode = 1;
+ }
+
+ console.log(`\n🔍 Scanning sandbox for changes...`);
+
+ // 4. Extract diff as a patch
+ try {
+ await git(['add', '-A'], worktreeAbsPath);
+ const diffStat = await git(['diff', '--cached', '--stat'], worktreeAbsPath);
+
+ if (diffStat) {
+ hasChanges = true;
+ patchFilePath = path.join(patchesDir, `${runId}.patch`);
+ const diffOutput = await gitRaw(['diff', '--cached', '--binary'], worktreeAbsPath);
+ await writeFile(patchFilePath, diffOutput);
+ console.log(`✅ Sandbox changes captured to patch: ${patchFilePath}`);
+ } else {
+ console.log(`ℹ️ No changes were made in the sandbox.`);
+ }
+ } catch (err) {
+ console.error(`❌ Failed to extract patch from sandbox:`, err);
+ extractionFailed = true;
+ }
+
+ } finally {
+ process.removeListener('SIGINT', sigHandler);
+ process.removeListener('SIGTERM', sigHandler);
+ await cleanup();
+ }
+
+ return {
+ runId,
+ patchFile: patchFilePath,
+ exitCode,
+ hasChanges
+ };
+}
+
+export interface ReviewItem {
+ patchName: string;
+ patchPath: string;
+ size: number;
+}
+
+/** Lists all available patches in the .loop-sandbox/patches/ directory. */
+export async function listPatches(root: string): Promise<ReviewItem[]> {
+ const patchesDir = path.join(root, '.loop-sandbox', 'patches');
+ try {
+ const files = await readdir(patchesDir, { withFileTypes: true });
+ const patches: ReviewItem[] = [];
+
+ for (const f of files) {
+ if (f.isFile() && f.name.endsWith('.patch')) {
+ const patchPath = path.join(patchesDir, f.name);
+ const s = await stat(patchPath);
+ patches.push({
+ patchName: f.name,
+ patchPath,
+ size: s.size
+ });
+ }
+ }
+ return patches;
+ } catch {
+ return [];
+ }
+}
diff --git a/tools/loop-sandbox/test/sandbox.test.mjs b/tools/loop-sandbox/test/sandbox.test.mjs
new file mode 100644
index 0000000..1f232e5
--- /dev/null
+++ b/tools/loop-sandbox/test/sandbox.test.mjs
@@ -0,0 +1,112 @@
+import test from 'node:test';
+import assert from 'node:assert';
+import { runInSandbox, listPatches } from '../dist/sandbox.js';
+import path from 'node:path';
+import { tmpdir } from 'node:os';
+import { mkdir, rm, writeFile, stat, readFile } from 'node:fs/promises';
+import { execSync } from 'node:child_process';
+import { createWorktree } from '@cobusgreyling/loop-worktree';
+
+async function setupTestRepo() {
+ const dir = path.join(tmpdir(), `sandbox-test-${Date.now()}-${Math.floor(Math.random()*1000)}`);
+ await mkdir(dir, { recursive: true });
+ execSync('git init -b main', { cwd: dir });
+ execSync('git config user.name "Test"', { cwd: dir });
+ execSync('git config user.email "[email protected]"', { cwd: dir });
+ await writeFile(path.join(dir, 'README.md'), '# Test repo');
+ execSync('git add README.md', { cwd: dir });
+ execSync('git commit -m "init"', { cwd: dir });
+ return dir;
+}
+
+test('sandbox run captures patch and cleans up', async () => {
+ const root = await setupTestRepo();
+ const scriptPath = path.join(root, 'test-script.js');
+ await writeFile(scriptPath, 'require("fs").writeFileSync("new-file.txt", "hello sandbox");');
+ try {
+ const result = await runInSandbox(root, 'node', [scriptPath]);
+
+ assert.ok(result.hasChanges);
+ assert.ok(result.patchFile);
+ assert.equal(result.exitCode, 0);
+
+ const patchStat = await stat(result.patchFile);
+ assert.ok(patchStat.size > 0);
+
+ await assert.rejects(stat(path.join(root, 'new-file.txt')));
+
+ const patches = await listPatches(root);
+ assert.equal(patches.length, 1);
+ assert.equal(patches[0].patchPath, result.patchFile);
+
+ } finally {
+ await rm(root, { recursive: true, force: true }).catch(() => {});
+ }
+});
+
+test('cleanup is scoped and leaves other active worktrees alone', async () => {
+ const root = await setupTestRepo();
+ try {
+ // Pre-create an active worktree via loop-worktree API
+ const other = await createWorktree({ root, runId: 'other-run', pattern: 'test', base: 'main' });
+ const otherPathAbs = path.join(root, other.path);
+ await stat(otherPathAbs); // verifies it exists
+
+ // Run sandbox
+ const result = await runInSandbox(root, 'node', ['-e', 'require("fs").writeFileSync("foo.txt", "bar");']);
+ assert.ok(result.hasChanges);
+
+ // Verify the other worktree STILL exists
+ await stat(otherPathAbs);
+ } finally {
+ await rm(root, { recursive: true, force: true }).catch(() => {});
+ }
+});
+
+test('extract failure prevents cleanup to avoid data loss', async () => {
+ const root = await setupTestRepo();
+ try {
+ // Sabotage git by deleting the worktree's metadata inside the parent repo.
+ // This makes git add -A fail because the worktree is completely broken.
+ const result = await runInSandbox(root, 'node', [
+ '-e',
+ 'const fs = require("fs"); const gitdir = fs.readFileSync(".git", "utf8").trim().replace("gitdir: ", ""); fs.rmSync(gitdir, {recursive: true, force: true});'
+ ]);
+
+ assert.equal(result.hasChanges, false);
+
+ // The worktree branch and directory should still be on disk
+ const statObj = await stat(path.join(root, '.loop-worktrees', result.runId));
+ assert.ok(statObj.isDirectory(), 'worktree should remain on disk');
+
+ } finally {
+ await rm(root, { recursive: true, force: true }).catch(() => {});
+ }
+});
+
+test('binary patch captures exactly without utf8 corruption', async () => {
+ const root = await setupTestRepo();
+ try {
+ // Write a binary sequence
+ const scriptPath = path.join(root, 'binary-script.js');
+ await writeFile(scriptPath, 'require("fs").writeFileSync("binary.bin", Buffer.from([0x00, 0xFF, 0xFE, 0xFD]));');
+
+ const result = await runInSandbox(root, 'node', [scriptPath]);
+ assert.ok(result.hasChanges);
+
+ const patchContent = await readFile(result.patchFile);
+ assert.ok(patchContent.toString('ascii').includes('GIT binary patch'));
+
+ // Apply the patch to the main repo
+ execSync(`git apply ${result.patchFile}`, { cwd: root });
+
+ // Verify exact bytes
+ const appliedContent = await readFile(path.join(root, 'binary.bin'));
+ assert.equal(appliedContent[0], 0x00);
+ assert.equal(appliedContent[1], 0xFF);
+ assert.equal(appliedContent[2], 0xFE);
+ assert.equal(appliedContent[3], 0xFD);
+ } finally {
+ await rm(root, { recursive: true, force: true }).catch(() => {});
+ }
+});
diff --git a/tools/loop-sandbox/tsconfig.json b/tools/loop-sandbox/tsconfig.json
new file mode 100644
index 0000000..ee786cd
--- /dev/null
+++ b/tools/loop-sandbox/tsconfig.json
@@ -0,0 +1,14 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "outDir": "dist",
+ "rootDir": "src",
+ "strict": true,
+ "declaration": true,
+ "skipLibCheck": true,
+ "types": ["node"]
+ },
+ "include": ["src/**/*"]
+}
diff --git a/tools/loop-worktree/package.json b/tools/loop-worktree/package.json
index 9dd0e4e..c6441c4 100644
--- a/tools/loop-worktree/package.json
+++ b/tools/loop-worktree/package.json
@@ -6,6 +6,8 @@
"bin": {
"loop-worktree": "dist/cli.js"
},
+ "main": "dist/worktree.js",
+ "types": "dist/worktree.d.ts",
"files": [
"dist",
"README.md"