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(loop-sandbox): add opt-in advisory lock for scheduled-loop safety (#399)

JonyT Agentic1d4e9e6e7810
diff --git a/docs/multi-loop.md b/docs/multi-loop.md
index 1dcd514..8e1e0f6 100644
--- a/docs/multi-loop.md
+++ b/docs/multi-loop.md
@@ -58,6 +58,11 @@ hand-checked convention: a loop's control script runs `loop-worktree lock --path
paired by convention in the control script, the same way `loop-context --check` and
`loop-worktree mark --status escalated` are paired.
+[`loop-sandbox`](../tools/loop-sandbox) follows the same convention through its own
+`--lock-paths` option, since a one-shot sandboxed agent run is just another kind of
+control script that can collide with a scheduled loop's files. It is opt-in — an
+unadorned `loop-sandbox run` is not lock-protected.
+
## Human inbox
Use a shared section in `STATE.md`:
diff --git a/tools/loop-sandbox/README.md b/tools/loop-sandbox/README.md
index beab86c..c05e9d1 100644
--- a/tools/loop-sandbox/README.md
+++ b/tools/loop-sandbox/README.md
@@ -51,6 +51,10 @@ loop-sandbox <command> [options]
|--------|-------------|
| `--shell` | Forces `shell: true` (for `bash -c`, etc.). On Windows, npm-installed `.cmd` shims (`npx`, `tsc`, ...) that fail with `ENOENT` are automatically retried through a shell, so this is rarely needed there. |
| `--base <branch>` | The base branch for the worktree (defaults to current HEAD) |
+| `--lock-paths <globs>` | Comma-separated globs to hold a [`loop-worktree`](../loop-worktree) advisory lock on for the run's duration, so a scheduled loop can't touch the same paths concurrently. Off by default -- see [Multi-loop safety](#multi-loop-safety) below. |
+| `--lock-owner <name>` | Lock owner name (defaults to the run's generated id) |
+| `--lock-ttl <dur>` | e.g. `30m` -- passed through to `loop-worktree`'s `--ttl` |
+| `--lock-wait <dur>` | e.g. `5m` -- passed through to `loop-worktree`'s `--wait` |
### Examples
@@ -65,6 +69,11 @@ npx @cobusgreyling/loop-sandbox run -- npx my-agent
npx @cobusgreyling/loop-sandbox run --shell -- bash -c "echo 'hello' > test.txt"
```
+**Running alongside a scheduled loop that touches the same files:**
+```bash
+npx @cobusgreyling/loop-sandbox run --lock-paths "src/**,docs/**" -- npx my-agent
+```
+
**Reviewing and applying patches:**
```bash
# List all patches the sandbox caught
@@ -79,3 +88,13 @@ npx @cobusgreyling/loop-sandbox review
## 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.
+
+## Multi-loop safety
+
+A sandbox run is not, by itself, protected against a scheduled loop editing
+the same files at the same time -- `--lock-paths` opts a run into
+`loop-worktree`'s advisory lock (acquired before the worktree is created,
+released once the run finishes) so a colliding scheduled loop's own `lock`
+call fails loudly instead of racing silently. See
+[docs/multi-loop.md](../../docs/multi-loop.md) for the wider convention this
+follows.
diff --git a/tools/loop-sandbox/dist/cli.js b/tools/loop-sandbox/dist/cli.js
index c80c100..9b6dc5f 100644
--- a/tools/loop-sandbox/dist/cli.js
+++ b/tools/loop-sandbox/dist/cli.js
@@ -24,6 +24,10 @@ async function main() {
}
let shell = false;
let base;
+ let lockPaths;
+ let lockOwner;
+ let lockTtl;
+ let lockWait;
for (let i = 0; i < sandboxOptionsArgs.length; i++) {
const arg = sandboxOptionsArgs[i];
if (arg === '--shell') {
@@ -32,6 +36,22 @@ async function main() {
else if (arg === '--base') {
base = sandboxOptionsArgs[++i];
}
+ else if (arg === '--lock-paths') {
+ lockPaths = (sandboxOptionsArgs[++i] ?? '').split(',').map((p) => p.trim()).filter(Boolean);
+ if (lockPaths.length === 0) {
+ console.error('❌ --lock-paths requires at least one non-empty, comma-separated glob.');
+ process.exit(1);
+ }
+ }
+ else if (arg === '--lock-owner') {
+ lockOwner = sandboxOptionsArgs[++i];
+ }
+ else if (arg === '--lock-ttl') {
+ lockTtl = sandboxOptionsArgs[++i];
+ }
+ else if (arg === '--lock-wait') {
+ lockWait = sandboxOptionsArgs[++i];
+ }
else {
console.error(`❌ Unknown option: ${arg}`);
process.exit(1);
@@ -40,7 +60,7 @@ async function main() {
const exe = targetCommandArgs[0];
const exeArgs = targetCommandArgs.slice(1);
try {
- const result = await runInSandbox(root, exe, exeArgs, { shell, base });
+ const result = await runInSandbox(root, exe, exeArgs, { shell, base, lockPaths, lockOwner, lockTtl, lockWait });
if (result.hasChanges && result.patchFile) {
console.log('\n==================================================');
console.log(`🎉 Run completed. Changes isolated successfully!`);
@@ -100,10 +120,17 @@ Options for 'run':
npm-installed .cmd shims like npx/tsc retry through a shell
automatically on ENOENT, so this is rarely needed there)
--base The base branch to branch the worktree from (default: current HEAD)
-
+ --lock-paths Comma-separated globs to hold a loop-worktree advisory
+ lock on for the run's duration, so a scheduled loop can't
+ touch the same paths concurrently. Off by default.
+ --lock-owner Lock owner name (default: the run's generated id)
+ --lock-ttl e.g. 30m -- passed through to loop-worktree's --ttl
+ --lock-wait e.g. 5m -- passed through to loop-worktree's --wait
+
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 run --lock-paths "src/**,docs/**" -- npx my-agent
npx @cobusgreyling/loop-sandbox review
`);
}
diff --git a/tools/loop-sandbox/dist/sandbox.d.ts b/tools/loop-sandbox/dist/sandbox.d.ts
index 2a88b73..f46b4b9 100644
--- a/tools/loop-sandbox/dist/sandbox.d.ts
+++ b/tools/loop-sandbox/dist/sandbox.d.ts
@@ -1,6 +1,18 @@
export interface SandboxOptions {
shell?: boolean;
base?: string;
+ /**
+ * Glob(s) to hold an advisory loop-worktree lock on for the run's duration,
+ * so a scheduled loop can't touch the same paths concurrently. Unset by
+ * default -- sandbox runs are unprotected unless the caller opts in.
+ */
+ lockPaths?: string[];
+ /** Lock owner name; defaults to the run's generated id. */
+ lockOwner?: string;
+ /** e.g. "30m" -- passed straight through to loop-worktree's --ttl. */
+ lockTtl?: string;
+ /** e.g. "5m" -- passed straight through to loop-worktree's --wait. */
+ lockWait?: string;
}
export interface SandboxResult {
runId: string;
diff --git a/tools/loop-sandbox/dist/sandbox.js b/tools/loop-sandbox/dist/sandbox.js
index e007dbf..886d67d 100644
--- a/tools/loop-sandbox/dist/sandbox.js
+++ b/tools/loop-sandbox/dist/sandbox.js
@@ -4,6 +4,16 @@ 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';
+// loop-worktree's package.json has no "exports" map restricting subpaths, so
+// this resolves cleanly; a re-export from the package's main entry was tried
+// first but creates a module-load cycle (lock.js reads MANIFEST_DIR from
+// worktree.js, which would need lock.js's own export to finish first).
+//
+// This reaches into loop-worktree's compiled internals rather than a public
+// subpath export, since none exists yet -- a supported `loop-worktree/lock`
+// entry point would be a better long-term home for this, tracked as a
+// follow-up rather than done here to keep this change scoped to sandbox.ts.
+import { lockPaths, unlockOwner } from '@cobusgreyling/loop-worktree/dist/lock.js';
const runExec = promisify(execFile);
/** Run a git command in cwd, returning stdout trimmed. Throws on error. */
async function git(args, cwd) {
@@ -35,40 +45,62 @@ export async function runInSandbox(root, command, args, options = {}) {
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;
+ const lockOwner = options.lockOwner ?? runId;
+ // Whether a lock was *requested*, not whether it was confirmed acquired --
+ // lockPaths() can be interrupted mid-wait (e.g. by a signal during
+ // --lock-wait), leaving only a `<owner>.wait.json` file with no matching
+ // lock. unlockOwner() removes either or both and is a safe no-op if
+ // neither exists, so gating cleanup on the original request (rather than
+ // on successful acquisition) also sweeps up that stray wait file.
+ const lockRequested = Boolean(options.lockPaths && options.lockPaths.length > 0);
+ let worktreeAbsPath = 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;
+ let activeChild = null;
+ // Cleanup must run on every exit path, including Ctrl+C mid-run, and
+ // exactly once even if a signal lands twice: the previous shape re-invoked
+ // cleanup() on every signal and let it no-op past a boolean guard while
+ // still calling process.exit(1) right after -- a second Ctrl+C during a
+ // slow `git worktree remove` would exit before the *first* cleanup's lock
+ // release ever ran, stranding a no-TTL lock. Sharing one promise across
+ // every caller means every signal (first or repeated) waits on the same
+ // in-flight cleanup before exiting.
+ let cleanupPromise = null;
+ const cleanup = () => {
+ if (!cleanupPromise) {
+ cleanupPromise = (async () => {
+ // Stop the sandboxed command first so it can't keep writing into the
+ // worktree (or racing the lock's protected paths) after cleanup has
+ // started tearing things down around it.
+ activeChild?.kill();
+ // Release the lock before worktree teardown: it's the resource other
+ // loops are blocked on, and a slow worktree removal shouldn't delay
+ // it.
+ if (lockRequested) {
+ console.log(`🔓 Releasing lock held by "${lockOwner}"...`);
+ await unlockOwner(root, lockOwner).catch((err) => {
+ console.error(`❌ Failed to release lock for "${lockOwner}". Run \`loop-worktree unlock --owner ${lockOwner}\` manually:`, err);
+ });
+ }
+ if (worktreeAbsPath) {
+ if (extractionFailed) {
+ console.log(`⚠️ Patch extraction failed. The worktree at ${worktreeAbsPath} and branch loop/${runId} were left on disk for manual recovery.`);
+ }
+ else {
+ 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;
+ }
+ }
+ }
+ })();
}
+ return cleanupPromise;
};
const sigHandler = () => {
cleanup().finally(() => process.exit(1));
@@ -76,6 +108,23 @@ export async function runInSandbox(root, command, args, options = {}) {
process.on('SIGINT', sigHandler);
process.on('SIGTERM', sigHandler);
try {
+ if (lockRequested) {
+ console.log(`\n🔒 Locking ${options.lockPaths.join(', ')} as "${lockOwner}"...`);
+ await lockPaths({ root, owner: lockOwner, paths: options.lockPaths, ttl: options.lockTtl, wait: options.lockWait });
+ }
+ console.log(`\n📦 Creating ephemeral worktree isolation: ${runId}`);
+ // 2. Create the worktree
+ const entry = await createWorktree({
+ root,
+ runId,
+ pattern: 'sandbox', // dummy pattern
+ base: baseBranch
+ });
+ worktreeAbsPath = path.resolve(root, entry.path);
+ console.log(`🚀 Executing inside sandbox: ${command} ${args.join(' ')}`);
+ let exitCode = null;
+ let hasChanges = false;
+ let patchFilePath = null;
// 3. Execute the user's command
try {
exitCode = await new Promise((resolve) => {
@@ -91,9 +140,11 @@ export async function runInSandbox(root, command, args, options = {}) {
stdio: 'inherit',
shell: useShell
});
+ activeChild = child;
child.on('close', (code) => {
if (!useShell && supersededByRetry)
return;
+ activeChild = null;
resolve(code);
});
child.on('error', (err) => {
@@ -110,6 +161,7 @@ export async function runInSandbox(root, command, args, options = {}) {
attempt(true);
return;
}
+ activeChild = null;
resolve(1);
});
};
@@ -140,18 +192,18 @@ export async function runInSandbox(root, command, args, options = {}) {
console.error(`❌ Failed to extract patch from sandbox:`, err);
extractionFailed = true;
}
+ return {
+ runId,
+ patchFile: patchFilePath,
+ exitCode,
+ hasChanges
+ };
}
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) {
diff --git a/tools/loop-sandbox/src/cli.ts b/tools/loop-sandbox/src/cli.ts
index 72f0d9e..f8c2d99 100644
--- a/tools/loop-sandbox/src/cli.ts
+++ b/tools/loop-sandbox/src/cli.ts
@@ -33,6 +33,10 @@ async function main() {
let shell = false;
let base: string | undefined;
+ let lockPaths: string[] | undefined;
+ let lockOwner: string | undefined;
+ let lockTtl: string | undefined;
+ let lockWait: string | undefined;
for (let i = 0; i < sandboxOptionsArgs.length; i++) {
const arg = sandboxOptionsArgs[i];
@@ -40,6 +44,18 @@ async function main() {
shell = true;
} else if (arg === '--base') {
base = sandboxOptionsArgs[++i];
+ } else if (arg === '--lock-paths') {
+ lockPaths = (sandboxOptionsArgs[++i] ?? '').split(',').map((p) => p.trim()).filter(Boolean);
+ if (lockPaths.length === 0) {
+ console.error('❌ --lock-paths requires at least one non-empty, comma-separated glob.');
+ process.exit(1);
+ }
+ } else if (arg === '--lock-owner') {
+ lockOwner = sandboxOptionsArgs[++i];
+ } else if (arg === '--lock-ttl') {
+ lockTtl = sandboxOptionsArgs[++i];
+ } else if (arg === '--lock-wait') {
+ lockWait = sandboxOptionsArgs[++i];
} else {
console.error(`❌ Unknown option: ${arg}`);
process.exit(1);
@@ -50,7 +66,7 @@ async function main() {
const exeArgs = targetCommandArgs.slice(1);
try {
- const result = await runInSandbox(root, exe, exeArgs, { shell, base });
+ const result = await runInSandbox(root, exe, exeArgs, { shell, base, lockPaths, lockOwner, lockTtl, lockWait });
if (result.hasChanges && result.patchFile) {
console.log('\n==================================================');
@@ -111,10 +127,17 @@ Options for 'run':
npm-installed .cmd shims like npx/tsc retry through a shell
automatically on ENOENT, so this is rarely needed there)
--base The base branch to branch the worktree from (default: current HEAD)
-
+ --lock-paths Comma-separated globs to hold a loop-worktree advisory
+ lock on for the run's duration, so a scheduled loop can't
+ touch the same paths concurrently. Off by default.
+ --lock-owner Lock owner name (default: the run's generated id)
+ --lock-ttl e.g. 30m -- passed through to loop-worktree's --ttl
+ --lock-wait e.g. 5m -- passed through to loop-worktree's --wait
+
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 run --lock-paths "src/**,docs/**" -- npx my-agent
npx @cobusgreyling/loop-sandbox review
`);
}
diff --git a/tools/loop-sandbox/src/sandbox.ts b/tools/loop-sandbox/src/sandbox.ts
index 5c074a4..cbc9d1d 100644
--- a/tools/loop-sandbox/src/sandbox.ts
+++ b/tools/loop-sandbox/src/sandbox.ts
@@ -4,12 +4,34 @@ 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';
+// loop-worktree's package.json has no "exports" map restricting subpaths, so
+// this resolves cleanly; a re-export from the package's main entry was tried
+// first but creates a module-load cycle (lock.js reads MANIFEST_DIR from
+// worktree.js, which would need lock.js's own export to finish first).
+//
+// This reaches into loop-worktree's compiled internals rather than a public
+// subpath export, since none exists yet -- a supported `loop-worktree/lock`
+// entry point would be a better long-term home for this, tracked as a
+// follow-up rather than done here to keep this change scoped to sandbox.ts.
+import { lockPaths, unlockOwner } from '@cobusgreyling/loop-worktree/dist/lock.js';
const runExec = promisify(execFile);
export interface SandboxOptions {
shell?: boolean;
base?: string;
+ /**
+ * Glob(s) to hold an advisory loop-worktree lock on for the run's duration,
+ * so a scheduled loop can't touch the same paths concurrently. Unset by
+ * default -- sandbox runs are unprotected unless the caller opts in.
+ */
+ lockPaths?: string[];
+ /** Lock owner name; defaults to the run's generated id. */
+ lockOwner?: string;
+ /** e.g. "30m" -- passed straight through to loop-worktree's --ttl. */
+ lockTtl?: string;
+ /** e.g. "5m" -- passed straight through to loop-worktree's --wait. */
+ lockWait?: string;
}
export interface SandboxResult {
@@ -45,7 +67,7 @@ export async function runInSandbox(root: string, command: string, args: string[]
}
const runId = `sandbox-${crypto.randomBytes(4).toString('hex')}`;
-
+
// 1. Setup paths
const sandboxDir = path.join(root, '.loop-sandbox');
const patchesDir = path.join(sandboxDir, 'patches');
@@ -53,45 +75,63 @@ export async function runInSandbox(root: string, command: string, args: string[]
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;
+ const lockOwner = options.lockOwner ?? runId;
+ // Whether a lock was *requested*, not whether it was confirmed acquired --
+ // lockPaths() can be interrupted mid-wait (e.g. by a signal during
+ // --lock-wait), leaving only a `<owner>.wait.json` file with no matching
+ // lock. unlockOwner() removes either or both and is a safe no-op if
+ // neither exists, so gating cleanup on the original request (rather than
+ // on successful acquisition) also sweeps up that stray wait file.
+ const lockRequested = Boolean(options.lockPaths && options.lockPaths.length > 0);
+ let worktreeAbsPath: string | null = null;
let extractionFailed = false;
+ let activeChild: ReturnType<typeof spawn> | null = null;
- // Signal handlers for graceful cleanup if user ctrl+c's during run
- let isCleaningUp = false;
- const cleanup = async () => {
- if (isCleaningUp) return;
- isCleaningUp = true;
+ // Cleanup must run on every exit path, including Ctrl+C mid-run, and
+ // exactly once even if a signal lands twice: the previous shape re-invoked
+ // cleanup() on every signal and let it no-op past a boolean guard while
+ // still calling process.exit(1) right after -- a second Ctrl+C during a
+ // slow `git worktree remove` would exit before the *first* cleanup's lock
+ // release ever ran, stranding a no-TTL lock. Sharing one promise across
+ // every caller means every signal (first or repeated) waits on the same
+ // in-flight cleanup before exiting.
+ let cleanupPromise: Promise<void> | null = null;
+ const cleanup = (): Promise<void> => {
+ if (!cleanupPromise) {
+ cleanupPromise = (async () => {
+ // Stop the sandboxed command first so it can't keep writing into the
+ // worktree (or racing the lock's protected paths) after cleanup has
+ // started tearing things down around it.
+ activeChild?.kill();
- if (extractionFailed) {
- console.log(`⚠️ Patch extraction failed. The worktree at ${worktreeAbsPath} and branch loop/${runId} were left on disk for manual recovery.`);
- return;
- }
+ // Release the lock before worktree teardown: it's the resource other
+ // loops are blocked on, and a slow worktree removal shouldn't delay
+ // it.
+ if (lockRequested) {
+ console.log(`🔓 Releasing lock held by "${lockOwner}"...`);
+ await unlockOwner(root, lockOwner).catch((err) => {
+ console.error(`❌ Failed to release lock for "${lockOwner}". Run \`loop-worktree unlock --owner ${lockOwner}\` manually:`, err);
+ });
+ }
- 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;
+ if (worktreeAbsPath) {
+ if (extractionFailed) {
+ console.log(`⚠️ Patch extraction failed. The worktree at ${worktreeAbsPath} and branch loop/${runId} were left on disk for manual recovery.`);
+ } else {
+ 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;
+ }
+ }
+ }
+ })();
}
+ return cleanupPromise;
};
const sigHandler = () => {
@@ -102,6 +142,29 @@ export async function runInSandbox(root: string, command: string, args: string[]
process.on('SIGTERM', sigHandler);
try {
+ if (lockRequested) {
+ console.log(`\n🔒 Locking ${options.lockPaths!.join(', ')} as "${lockOwner}"...`);
+ await lockPaths({ root, owner: lockOwner, paths: options.lockPaths!, ttl: options.lockTtl, wait: options.lockWait });
+ }
+
+ console.log(`\n📦 Creating ephemeral worktree isolation: ${runId}`);
+
+ // 2. Create the worktree
+ const entry = await createWorktree({
+ root,
+ runId,
+ pattern: 'sandbox', // dummy pattern
+ base: baseBranch
+ });
+
+ 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;
+
// 3. Execute the user's command
try {
exitCode = await new Promise<number | null>((resolve) => {
@@ -114,13 +177,15 @@ export async function runInSandbox(root: string, command: string, args: string[]
const attempt = (useShell: boolean) => {
const child = spawn(command, args, {
- cwd: worktreeAbsPath,
+ cwd: worktreeAbsPath!,
stdio: 'inherit',
shell: useShell
});
+ activeChild = child;
child.on('close', (code) => {
if (!useShell && supersededByRetry) return;
+ activeChild = null;
resolve(code);
});
child.on('error', (err: NodeJS.ErrnoException) => {
@@ -136,6 +201,7 @@ export async function runInSandbox(root: string, command: string, args: string[]
attempt(true);
return;
}
+ activeChild = null;
resolve(1);
});
};
@@ -152,7 +218,7 @@ export async function runInSandbox(root: string, command: string, args: string[]
try {
await git(['add', '-A'], worktreeAbsPath);
const diffStat = await git(['diff', '--cached', '--stat'], worktreeAbsPath);
-
+
if (diffStat) {
hasChanges = true;
patchFilePath = path.join(patchesDir, `${runId}.patch`);
@@ -167,18 +233,17 @@ export async function runInSandbox(root: string, command: string, args: string[]
extractionFailed = true;
}
+ return {
+ runId,
+ patchFile: patchFilePath,
+ exitCode,
+ hasChanges
+ };
} finally {
process.removeListener('SIGINT', sigHandler);
process.removeListener('SIGTERM', sigHandler);
await cleanup();
}
-
- return {
- runId,
- patchFile: patchFilePath,
- exitCode,
- hasChanges
- };
}
export interface ReviewItem {
diff --git a/tools/loop-sandbox/test/sandbox.test.mjs b/tools/loop-sandbox/test/sandbox.test.mjs
index 1f232e5..afccdb9 100644
--- a/tools/loop-sandbox/test/sandbox.test.mjs
+++ b/tools/loop-sandbox/test/sandbox.test.mjs
@@ -2,10 +2,15 @@ import test from 'node:test';
import assert from 'node:assert';
import { runInSandbox, listPatches } from '../dist/sandbox.js';
import path from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
import { tmpdir } from 'node:os';
-import { mkdir, rm, writeFile, stat, readFile } from 'node:fs/promises';
-import { execSync } from 'node:child_process';
+import { mkdir, rm, writeFile, stat, readFile, readdir } from 'node:fs/promises';
+import { execSync, spawn } from 'node:child_process';
import { createWorktree } from '@cobusgreyling/loop-worktree';
+import { lockPaths, listLocks } from '@cobusgreyling/loop-worktree/dist/lock.js';
+
+const testDir = path.dirname(fileURLToPath(import.meta.url));
+const sandboxDistUrl = pathToFileURL(path.join(testDir, '../dist/sandbox.js')).href;
async function setupTestRepo() {
const dir = path.join(tmpdir(), `sandbox-test-${Date.now()}-${Math.floor(Math.random()*1000)}`);
@@ -110,3 +115,188 @@ test('binary patch captures exactly without utf8 corruption', async () => {
await rm(root, { recursive: true, force: true }).catch(() => {});
}
});
+
+test('lockPaths option holds and releases a loop-worktree lock around the run', async () => {
+ const root = await setupTestRepo();
+ try {
+ const result = await runInSandbox(root, 'node', ['-e', 'require("fs").writeFileSync("locked.txt", "x");'], {
+ lockPaths: ['src/**'],
+ lockOwner: 'lock-test-owner',
+ });
+ assert.ok(result.hasChanges);
+
+ // The lock must be released once the run completes -- otherwise it would
+ // strand future loops out of src/** indefinitely with no TTL set.
+ const locks = await listLocks(root);
+ assert.equal(locks.length, 0);
+ } finally {
+ await rm(root, { recursive: true, force: true }).catch(() => {});
+ }
+});
+
+test('lockPaths option refuses to run when another owner holds an overlapping lock', async () => {
+ const root = await setupTestRepo();
+ try {
+ await lockPaths({ root, owner: 'other-loop', paths: ['src/**'] });
+
+ await assert.rejects(
+ runInSandbox(root, 'node', ['-e', 'require("fs").writeFileSync("should-not-run.txt", "x");'], {
+ lockPaths: ['src/nested/**'],
+ lockOwner: 'sandbox-test-owner',
+ }),
+ /locked by owner "other-loop"/,
+ );
+
+ // Blocked before the worktree was ever created -- nothing to clean up.
+ const worktreeList = execSync('git worktree list --porcelain', { cwd: root, encoding: 'utf8' });
+ assert.equal(worktreeList.match(/^worktree /gm)?.length, 1, 'only the main worktree should exist');
+ // The other loop's lock is untouched by the rejected attempt.
+ const locks = await listLocks(root);
+ assert.equal(locks.length, 1);
+ assert.equal(locks[0].owner, 'other-loop');
+ } finally {
+ await rm(root, { recursive: true, force: true }).catch(() => {});
+ }
+});
+
+test('lockPaths option holds the lock while the run is still in progress, not just after', async () => {
+ const root = await setupTestRepo();
+ try {
+ const startedMarker = path.join(root, 'started.txt');
+ const goMarker = path.join(root, 'go.txt');
+
+ const runPromise = runInSandbox(root, 'node', [
+ '-e',
+ `require("fs").writeFileSync(${JSON.stringify(startedMarker)}, "x");` +
+ `const iv = setInterval(() => { if (require("fs").existsSync(${JSON.stringify(goMarker)})) { clearInterval(iv); process.exit(0); } }, 50);`,
+ ], { lockPaths: ['src/**'], lockOwner: 'midrun-owner' });
+
+ while (!(await stat(startedMarker).catch(() => null))) {
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+
+ // The lock must be visible while the sandboxed command is still running,
+ // not only after runInSandbox() resolves.
+ const locksMidRun = await listLocks(root);
+ assert.equal(locksMidRun.length, 1);
+ assert.equal(locksMidRun[0].owner, 'midrun-owner');
+
+ await writeFile(goMarker, 'go');
+ await runPromise;
+
+ const locksAfter = await listLocks(root);
+ assert.equal(locksAfter.length, 0);
+ } finally {
+ await rm(root, { recursive: true, force: true }).catch(() => {});
+ }
+});
+
+test('lock is released even when patch extraction fails and the worktree is left behind', async () => {
+ const root = await setupTestRepo();
+ try {
+ 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});',
+ ], { lockPaths: ['src/**'], lockOwner: 'extract-fail-owner' });
+
+ assert.equal(result.hasChanges, false);
+
+ // The worktree is deliberately left on disk for manual recovery when
+ // extraction fails...
+ const statObj = await stat(path.join(root, '.loop-worktrees', result.runId));
+ assert.ok(statObj.isDirectory(), 'worktree should remain on disk');
+
+ // ...but lock release has nothing to do with whether patch extraction
+ // succeeded, so it must still happen.
+ const locks = await listLocks(root);
+ assert.equal(locks.length, 0);
+ } finally {
+ await rm(root, { recursive: true, force: true }).catch(() => {});
+ }
+});
+
+test('a second SIGINT while cleanup is in flight does not exit before the lock is released', async () => {
+ const root = await setupTestRepo();
+ try {
+ // Same self-emitting-SIGINT approach as the test above, but fires SIGINT
+ // twice in quick succession. The bug this guards against: the first cut
+ // re-ran cleanup() on every signal and let a boolean guard turn repeat
+ // calls into instant no-ops, so the *second* signal's
+ // `.finally(() => process.exit(1))` could fire before the *first*
+ // signal's cleanup (lock release, worktree removal) ever finished.
+ const child = spawn(process.execPath, ['--input-type=module', '-e', `
+ const mod = await import(${JSON.stringify(sandboxDistUrl)});
+ mod.runInSandbox(${JSON.stringify(root)}, 'node', ['-e', 'setInterval(() => {}, 1000)'], {
+ lockPaths: ['src/**'],
+ lockOwner: 'double-sigint-owner',
+ }).catch(() => {});
+ setTimeout(() => process.emit('SIGINT'), 1000);
+ setTimeout(() => process.emit('SIGINT'), 1030);
+ `], { stdio: 'ignore' });
+
+ const exited = await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => resolve(false), 10_000);
+ child.on('exit', () => { clearTimeout(timer); resolve(true); });
+ child.on('error', (err) => { clearTimeout(timer); reject(err); });
+ });
+ if (!exited) {
+ child.kill('SIGKILL');
+ assert.fail('child did not exit after a double synthetic SIGINT within 10s -- the lock is likely stranded');
+ }
+
+ const locks = await listLocks(root);
+ assert.equal(locks.length, 0, 'a second SIGINT during cleanup must not exit before the lock is released');
+
+ // The lock release itself is a fast fs.unlink and tends to finish inside
+ // the race window regardless of this bug -- the sharper signal is
+ // whether the *slower* worktree teardown (spawns `git worktree remove`)
+ // also got to finish. Under the old guard-based cleanup, the second
+ // signal's process.exit() could cut that off mid-flight and leave a
+ // `sandbox-*` directory behind under .loop-worktrees (confirmed by
+ // reproducing this against the pre-fix code before writing this test).
+ const worktreeEntries = await readdir(path.join(root, '.loop-worktrees')).catch(() => []);
+ assert.ok(
+ !worktreeEntries.some((name) => name.startsWith('sandbox-')),
+ `worktree cleanup must finish even under a double signal, found: ${worktreeEntries.join(', ')}`,
+ );
+ } finally {
+ await rm(root, { recursive: true, force: true }).catch(() => {});
+ }
+});
+
+test('SIGINT mid-run releases the lock instead of stranding it', async () => {
+ const root = await setupTestRepo();
+ try {
+ // Run in a dedicated child process and self-trigger SIGINT via
+ // process.emit from inside it -- real OS signal delivery to a spawned
+ // process is unreliable to script from a test (especially on Windows),
+ // but process.emit('SIGINT') exercises the exact same registered
+ // listener a real signal would, without that flakiness. The sandboxed
+ // "user command" (setInterval) never exits on its own, so this also
+ // covers cleanup() running while the child it's meant to clean up after
+ // is still alive.
+ const child = spawn(process.execPath, ['--input-type=module', '-e', `
+ const mod = await import(${JSON.stringify(sandboxDistUrl)});
+ mod.runInSandbox(${JSON.stringify(root)}, 'node', ['-e', 'setInterval(() => {}, 1000)'], {
+ lockPaths: ['src/**'],
+ lockOwner: 'sigint-test-owner',
+ }).catch(() => {});
+ setTimeout(() => process.emit('SIGINT'), 1000);
+ `], { stdio: 'ignore' });
+
+ const exited = await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => resolve(false), 10_000);
+ child.on('exit', () => { clearTimeout(timer); resolve(true); });
+ child.on('error', (err) => { clearTimeout(timer); reject(err); });
+ });
+ if (!exited) {
+ child.kill('SIGKILL');
+ assert.fail('child did not exit after synthetic SIGINT within 10s -- the lock is likely stranded');
+ }
+
+ const locks = await listLocks(root);
+ assert.equal(locks.length, 0, 'lock must be released after SIGINT, not left stranded with no TTL');
+ } finally {
+ await rm(root, { recursive: true, force: true }).catch(() => {});
+ }
+});