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.
TypeScript agentic-aiai-agentsai-codinganthropicautomationclaudeclaude-codecodexcoding-agentsdevops-automationdevtoolsgithub-actionsgrokllmloop-engineeringmcpprompt-engineering
feat(loop-worktree): add advisory path locking to prevent multi-loop collisions (#274)
JonyT Agentic6327550bb418
diff --git a/docs/multi-loop.md b/docs/multi-loop.mdindex 1832031..1dcd514 100644--- a/docs/multi-loop.md+++ b/docs/multi-loop.md@@ -51,6 +51,13 @@ Each action loop should write `acting_on: branch-or-pr-id` in its state file. Be1. Read all other pattern state files2. If another loop `acting_on` matches → skip and log to `loop-run-log.md`+[`loop-worktree`](../tools/loop-worktree) codifies this as an advisory lock instead of a+hand-checked convention: a loop's control script runs `loop-worktree lock --paths+<globs> --owner <pattern>` before spawning a worktree, and `loop-worktree unlock --owner+<pattern>` once done. `loop-worktree create` does not check locks itself — the two stay+paired by convention in the control script, the same way `loop-context --check` and+`loop-worktree mark --status escalated` are paired.+## Human inboxUse a shared section in `STATE.md`:diff --git a/tools/loop-worktree/README.md b/tools/loop-worktree/README.mdindex 0589488..f910b07 100644--- a/tools/loop-worktree/README.md+++ b/tools/loop-worktree/README.md@@ -38,6 +38,15 @@ loop-worktree gc [--force] [--json]# report-only by default; --force removes orphansloop-worktree list [--status active] [--json]++loop-worktree lock --paths <glob1,glob2,...> --owner <name> [--ttl 6h]+ # advisory lock: fails if another (non-expired) owner already holds an overlapping path++loop-worktree unlock --owner <name>+ # releases that owner's lock; no-op if it didn't hold one++loop-worktree locks [--sweep] [--force] [--json]+ # lists active locks; --sweep reports expired ones (report-only; --force deletes them)```## Status@@ -52,6 +61,47 @@ An entry is one of: `active`, `rejected`, `escalated`, `merged`, `stale`.- `cleanup` runs `git worktree remove` without `--force` first, so git refuses to delete a worktree with uncommitted or untracked changes; that entry is reported as skipped. Pass `--force` only when you accept the data loss.- `gc` is report-only by default, matching the repo's convention that anything scanning broadly reports rather than acts.+## Preventing multi-loop collisions++Independently-scheduled loops can race on the same files -- see+[stories/multi-loop-collision.md](../../stories/multi-loop-collision.md) and+[stories/dependency-vs-ci-sweeper-collision.md](../../stories/dependency-vs-ci-sweeper-collision.md)+for real incidents this caused. `lock`/`unlock` give+[`docs/multi-loop.md`](../../docs/multi-loop.md)'s `acting_on` convention a+mechanical form:++```bash+loop-worktree lock --paths package.json,package-lock.json --owner dependency-sweeper --ttl 6h \+ || exit 2 # another owner holds an overlapping path -- skip this run+loop-worktree create --run-id "$RUN_ID" --pattern dependency-sweeper+# ... do the work ...+loop-worktree unlock --owner dependency-sweeper+```++It's deliberately advisory, not enforced by `create` itself -- a loop that+skips the `lock` call is not physically blocked, matching this repo's+existing "prose plus tooling" philosophy rather than hard sandboxing.+Locking is keyed on path globs, not run ids, so it also catches collisions+*across* different patterns (e.g. CI Sweeper and Dependency Sweeper both+touching `package.json`), not just within one.++`--paths` overlap is compared segment by segment (split on `/`): a wildcard+segment (`*` or `**`) is compatible with anything at that position, so+`src/**` overlaps `src/foo.ts`, but `docs/api` does not overlap+`docs/apidocs.md` (different literal segments, not just a shorter string).+This is intentionally simple (an advisory lock, not a full glob engine),+matching how `--older-than` already parses durations elsewhere in this tool.++Locks never expire on their own unless you pass `--ttl`; an orphaned lock+(owner crashed without unlocking) is surfaced -- not silently ignored -- by+`loop-worktree locks --sweep`, and only deleted with `--force`, mirroring+`gc`'s existing report-only-by-default convention for anything that scans+broadly instead of acting on one named target. `--owner` is restricted to+letters, digits, `.`, `_`, `-` (no path separators), since it names the lock+file directly. Concurrent `lock` calls are serialized through a short-lived+mutex file so two racing invocations can't both pass the overlap check+before either writes.+## Pairing with loop-contextA loop's control script that calls [`loop-context`](../loop-context) `--check` and escalates should also mark its worktree:@@ -83,4 +133,20 @@ The two tools stay independent: `loop-worktree` does not read the ledger, and `l}```+## Locks++`.loop-worktrees/locks/<owner>.json`, one file per owner (also add+`.loop-worktrees/` to `.gitignore` -- it already covers this):++```json+{+ "owner": "dependency-sweeper",+ "paths": ["package.json", "package-lock.json"],+ "lockedAt": "2026-07-14T08:00:00.000Z",+ "expiresAt": "2026-07-14T14:00:00.000Z"+}+```++`expiresAt` is absent when no `--ttl` was given.+See [docs/primitives.md](../../docs/primitives.md) for where worktrees fit in the Five Building Blocks + Memory model.diff --git a/tools/loop-worktree/dist/cli.js b/tools/loop-worktree/dist/cli.jsindex 87516cd..4a401ae 100644--- a/tools/loop-worktree/dist/cli.js+++ b/tools/loop-worktree/dist/cli.js@@ -1,7 +1,8 @@#!/usr/bin/env nodeimport { createWorktree, markWorktree, cleanupWorktrees, gc, listWorktrees, VALID_STATUSES, } from './worktree.js';+import { lockPaths, unlockOwner, listLocks, sweepExpiredLocks, isExpired } from './lock.js';function parseFlags(argv) {- const flags = { root: process.cwd(), force: false, json: false };+ const flags = { root: process.cwd(), force: false, json: false, sweep: false };for (let i = 0; i < argv.length; i++) {const a = argv[i];if (a === '--run-id')@@ -20,6 +21,14 @@ function parseFlags(argv) {flags.force = true;else if (a === '--json')flags.json = true;+ else if (a === '--paths')+ flags.paths = argv[++i];+ else if (a === '--owner')+ flags.owner = argv[++i];+ else if (a === '--ttl')+ flags.ttl = argv[++i];+ else if (a === '--sweep')+ flags.sweep = true;}return flags;}@@ -40,14 +49,25 @@ Usage:loop-worktree cleanup [--status rejected,escalated] [--older-than 24h] [--force]loop-worktree gc [--force] [--json]loop-worktree list [--status <s>] [--json]+ loop-worktree lock --paths <glob1,glob2,...> --owner <name> [--ttl 6h]+ loop-worktree unlock --owner <name>+ loop-worktree locks [--sweep] [--force] [--json]Common flags:--root <dir> Repo root to operate in (default: cwd)- --json Machine-readable output (list, gc)- --force Allow removing worktrees with uncommitted changes / orphans+ --json Machine-readable output (list, gc, locks)+ --force Allow removing worktrees with uncommitted changes / orphans,+ or (with locks --sweep) deleting expired lock files++Locking (advisory, not enforced by create -- pair it in your control script):+ --paths <csv> Comma-separated path globs this owner is about to touch+ --owner <name> Lock/unlock identity, typically the pattern name+ --ttl <dur> Optional expiry (e.g. 30m, 6h, 1d); omit for no auto-expiry+ locks --sweep Report expired locks (report-only; --force deletes them)Worktrees live under .loop-worktrees/, tracked in .loop-worktrees/manifest.json.-Add .loop-worktrees/ to .gitignore.`;+Locks live under .loop-worktrees/locks/<owner>.json. Add .loop-worktrees/ to+.gitignore.`;async function main() {const argv = process.argv.slice(2);const command = argv[0];@@ -129,6 +149,52 @@ async function main() {}return 0;}+ case 'lock': {+ if (!flags.paths || !flags.owner) {+ throw new Error('lock requires --paths and --owner.');+ }+ const paths = flags.paths.split(',').map((p) => p.trim()).filter(Boolean);+ const entry = await lockPaths({ root: flags.root, owner: flags.owner, paths, ttl: flags.ttl });+ console.log(`locked ${entry.paths.join(', ')} for ${entry.owner}` + (entry.expiresAt ? ` (expires ${entry.expiresAt})` : ''));+ return 0;+ }+ case 'unlock': {+ if (!flags.owner) {+ throw new Error('unlock requires --owner.');+ }+ const released = await unlockOwner(flags.root, flags.owner);+ console.log(released ? `unlocked ${flags.owner}` : `${flags.owner} held no lock`);+ return 0;+ }+ case 'locks': {+ if (flags.sweep) {+ const result = await sweepExpiredLocks(flags.root, { force: flags.force });+ if (flags.json) {+ console.log(JSON.stringify(result, null, 2));+ return 0;+ }+ for (const l of result.expired) {+ console.log(result.removed.includes(l.owner) ? `removed expired lock ${l.owner}` : `expired lock ${l.owner}`);+ }+ console.log(`locks --sweep: ${result.expired.length} expired` ++ (flags.force ? `, ${result.removed.length} removed` : ' (report-only; use --force to remove)'));+ return 0;+ }+ const locks = await listLocks(flags.root);+ if (flags.json) {+ console.log(JSON.stringify(locks.map((l) => ({ ...l, expired: isExpired(l) })), null, 2));+ return 0;+ }+ if (locks.length === 0) {+ console.log('no active locks');+ return 0;+ }+ for (const l of locks) {+ const expiryNote = l.expiresAt ? `, expires ${l.expiresAt}${isExpired(l) ? ' (expired)' : ''}` : '';+ console.log(`${l.owner} ${l.paths.join(', ')} (locked ${l.lockedAt}${expiryNote})`);+ }+ return 0;+ }default:console.error(`Unknown command "${command}".\n\n${HELP}`);return 1;diff --git a/tools/loop-worktree/dist/lock.d.ts b/tools/loop-worktree/dist/lock.d.tsnew file mode 100644index 0000000..e65d6ab--- /dev/null+++ b/tools/loop-worktree/dist/lock.d.ts@@ -0,0 +1,44 @@+export declare const LOCKS_DIR: string;+export interface LockEntry {+ owner: string;+ paths: string[];+ lockedAt: string;+ /** Absent means the lock never expires automatically; must be explicitly unlocked. */+ expiresAt?: string;+}+export declare function isExpired(lock: LockEntry, now?: number): boolean;+/**+ * Two path globs "overlap" if, segment by segment, every position where both+ * have a literal (non-wildcard) segment agrees -- a wildcard segment (`*` or+ * `**`) is treated as compatible with anything at that position. If one glob+ * has fewer segments, it only "covers" the longer, more specific path when+ * its last segment is itself a wildcard (e.g. "src/**" covers+ * "src/nested/foo.ts"); otherwise a shorter path is a distinct, shallower+ * file and does not overlap. Deliberately simple -- an advisory lock, not a+ * full glob engine.+ */+export declare function pathsOverlap(a: string, b: string): boolean;+export declare function listLocks(root: string): Promise<LockEntry[]>;+export interface LockPathsInput {+ root: string;+ owner: string;+ paths: string[];+ /** e.g. "6h" -- if omitted, the lock never expires automatically. */+ ttl?: string;+}+/**+ * Acquire an advisory lock on `paths` for `owner`. Fails if any *other*,+ * non-expired owner already holds an overlapping path. Re-locking as the+ * same owner replaces that owner's own previous lock (paths and TTL both).+ */+export declare function lockPaths(input: LockPathsInput): Promise<LockEntry>;+/** Release `owner`'s lock. Returns false (no-op) if it didn't hold one. */+export declare function unlockOwner(root: string, owner: string): Promise<boolean>;+export interface SweepExpiredLocksResult {+ expired: LockEntry[];+ removed: string[];+}+/** Report (and, with force, delete) locks past their own TTL. Never touches an active lock. */+export declare function sweepExpiredLocks(root: string, opts?: {+ force?: boolean;+}): Promise<SweepExpiredLocksResult>;diff --git a/tools/loop-worktree/dist/lock.js b/tools/loop-worktree/dist/lock.jsnew file mode 100644index 0000000..3138e17--- /dev/null+++ b/tools/loop-worktree/dist/lock.js@@ -0,0 +1,188 @@+import { readFile, writeFile, mkdir, readdir, unlink, access, open } from 'node:fs/promises';+import path from 'node:path';+import { MANIFEST_DIR, parseDurationMs } from './worktree.js';+export const LOCKS_DIR = path.posix.join(MANIFEST_DIR, 'locks');+const MUTEX_FILE = path.posix.join(LOCKS_DIR, '.mutex');+const OWNER_PATTERN = /^[A-Za-z0-9._-]+$/;+function assertValidOwner(owner) {+ if (!OWNER_PATTERN.test(owner)) {+ throw new Error(`Invalid --owner "${owner}". Use only letters, digits, ".", "_", "-" (no path separators).`);+ }+}+async function exists(p) {+ try {+ await access(p);+ return true;+ }+ catch {+ return false;+ }+}+async function readdirSafely(dir) {+ try {+ return await readdir(dir);+ }+ catch {+ return [];+ }+}+function lockFile(root, owner) {+ return path.join(root, LOCKS_DIR, `${owner}.json`);+}+async function readLock(root, owner) {+ const file = lockFile(root, owner);+ if (!(await exists(file)))+ return null;+ const raw = await readFile(file, 'utf8');+ try {+ return JSON.parse(raw);+ }+ catch {+ throw new Error(`Corrupt lock file ${file}: not valid JSON. Inspect it and delete it manually if it's stale.`);+ }+}+export function isExpired(lock, now = Date.now()) {+ return lock.expiresAt !== undefined && Date.parse(lock.expiresAt) <= now;+}+function isWildcardSegment(segment) {+ return /[*?]/.test(segment);+}+/**+ * Two path globs "overlap" if, segment by segment, every position where both+ * have a literal (non-wildcard) segment agrees -- a wildcard segment (`*` or+ * `**`) is treated as compatible with anything at that position. If one glob+ * has fewer segments, it only "covers" the longer, more specific path when+ * its last segment is itself a wildcard (e.g. "src/**" covers+ * "src/nested/foo.ts"); otherwise a shorter path is a distinct, shallower+ * file and does not overlap. Deliberately simple -- an advisory lock, not a+ * full glob engine.+ */+export function pathsOverlap(a, b) {+ if (a === b)+ return true;+ const segA = a.split('/').filter(Boolean);+ const segB = b.split('/').filter(Boolean);+ const len = Math.min(segA.length, segB.length);+ for (let i = 0; i < len; i++) {+ const sa = segA[i];+ const sb = segB[i];+ if (sa === sb)+ continue;+ if (isWildcardSegment(sa) || isWildcardSegment(sb))+ continue;+ return false;+ }+ if (segA.length === segB.length)+ return true;+ const shorter = segA.length < segB.length ? segA : segB;+ return isWildcardSegment(shorter[shorter.length - 1]);+}+export async function listLocks(root) {+ const files = await readdirSafely(path.join(root, LOCKS_DIR));+ const locks = [];+ for (const file of files) {+ if (!file.endsWith('.json'))+ continue;+ const lock = await readLock(root, file.slice(0, -'.json'.length));+ if (lock)+ locks.push(lock);+ }+ return locks;+}+/**+ * Serialize the check-then-write critical section across processes using an+ * exclusive-create mutex file (atomic on POSIX and Windows). Without this,+ * two `lock` calls racing close together could both pass the overlap check+ * before either writes -- exactly the collision this feature exists to+ * prevent.+ */+async function withLocksMutex(root, fn) {+ const dir = path.join(root, LOCKS_DIR);+ await mkdir(dir, { recursive: true });+ const mutexPath = path.join(root, MUTEX_FILE);+ const deadline = Date.now() + 5000;+ for (;;) {+ try {+ const handle = await open(mutexPath, 'wx');+ await handle.close();+ break;+ }+ catch (err) {+ if (err.code !== 'EEXIST')+ throw err;+ if (Date.now() > deadline) {+ throw new Error(`Timed out waiting for the lock mutex (${MUTEX_FILE}). If no other loop-worktree ` ++ 'process is running, delete it manually.');+ }+ await new Promise((resolve) => setTimeout(resolve, 25 + Math.random() * 50));+ }+ }+ try {+ return await fn();+ }+ finally {+ await unlink(mutexPath).catch(() => { });+ }+}+/**+ * Acquire an advisory lock on `paths` for `owner`. Fails if any *other*,+ * non-expired owner already holds an overlapping path. Re-locking as the+ * same owner replaces that owner's own previous lock (paths and TTL both).+ */+export async function lockPaths(input) {+ const { root, owner, paths } = input;+ assertValidOwner(owner);+ if (paths.length === 0) {+ throw new Error('--paths requires at least one path or glob.');+ }+ return withLocksMutex(root, async () => {+ const now = Date.now();+ for (const other of await listLocks(root)) {+ if (other.owner === owner || isExpired(other, now))+ continue;+ for (const p of paths) {+ const clash = other.paths.find((op) => pathsOverlap(p, op));+ if (clash) {+ throw new Error(`Path "${p}" is locked by owner "${other.owner}" (locked at ${other.lockedAt}` ++ (other.expiresAt ? `, expires at ${other.expiresAt}` : '') ++ `). Use --paths that don't overlap, or wait for the lock to clear.`);+ }+ }+ }+ const entry = { owner, paths, lockedAt: new Date(now).toISOString() };+ if (input.ttl) {+ entry.expiresAt = new Date(now + parseDurationMs(input.ttl, '--ttl')).toISOString();+ }+ await writeFile(lockFile(root, owner), `${JSON.stringify(entry, null, 2)}\n`);+ return entry;+ });+}+/** Release `owner`'s lock. Returns false (no-op) if it didn't hold one. */+export async function unlockOwner(root, owner) {+ assertValidOwner(owner);+ const file = lockFile(root, owner);+ if (!(await exists(file)))+ return false;+ await unlink(file);+ return true;+}+/** Report (and, with force, delete) locks past their own TTL. Never touches an active lock. */+export async function sweepExpiredLocks(root, opts = {}) {+ return withLocksMutex(root, async () => {+ const now = Date.now();+ const expired = (await listLocks(root)).filter((l) => isExpired(l, now));+ const removed = [];+ if (opts.force) {+ for (const l of expired) {+ try {+ await unlink(lockFile(root, l.owner));+ removed.push(l.owner);+ }+ catch {+ // Already gone; nothing to report.+ }+ }+ }+ return { expired, removed };+ });+}diff --git a/tools/loop-worktree/dist/worktree.d.ts b/tools/loop-worktree/dist/worktree.d.tsindex a27ee4c..d5bfc30 100644--- a/tools/loop-worktree/dist/worktree.d.ts+++ b/tools/loop-worktree/dist/worktree.d.ts@@ -34,6 +34,8 @@ export interface MarkInput {status: WorktreeStatus;}export declare function markWorktree(input: MarkInput): Promise<WorktreeEntry>;+/** Parse a duration like "30m", "24h", "7d" into milliseconds. Shared with lock.ts's --ttl. */+export declare function parseDurationMs(token: string, flag: string): number;export interface CleanupInput {root: string;statuses?: WorktreeStatus[];diff --git a/tools/loop-worktree/dist/worktree.js b/tools/loop-worktree/dist/worktree.jsindex 4294365..73a8a2c 100644--- a/tools/loop-worktree/dist/worktree.js+++ b/tools/loop-worktree/dist/worktree.js@@ -111,10 +111,11 @@ export async function markWorktree(input) {await writeManifest(root, manifest);return entry;}-function parseInterval(token) {+/** Parse a duration like "30m", "24h", "7d" into milliseconds. Shared with lock.ts's --ttl. */+export function parseDurationMs(token, flag) {const m = /^(\d+)([mhd])$/.exec(token.trim());if (!m) {- throw new Error(`Invalid --older-than "${token}". Use e.g. 30m, 24h, 7d.`);+ throw new Error(`Invalid ${flag} "${token}". Use e.g. 30m, 24h, 7d.`);}const n = Number(m[1]);const unit = m[2];@@ -125,7 +126,7 @@ export async function cleanupWorktrees(input) {const { root } = input;await assertGitRepo(root);const statuses = input.statuses ?? CLEANUP_DEFAULT_STATUSES;- const cutoff = input.olderThan ? Date.now() - parseInterval(input.olderThan) : undefined;+ const cutoff = input.olderThan ? Date.now() - parseDurationMs(input.olderThan, '--older-than') : undefined;const manifest = await readManifest(root);const removed = [];const skipped = [];diff --git a/tools/loop-worktree/package-lock.json b/tools/loop-worktree/package-lock.jsonindex b227b85..b586b43 100644--- a/tools/loop-worktree/package-lock.json+++ b/tools/loop-worktree/package-lock.json@@ -1,12 +1,12 @@{"name": "@cobusgreyling/loop-worktree",- "version": "1.0.0",+ "version": "1.1.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@cobusgreyling/loop-worktree",- "version": "1.0.0",+ "version": "1.1.0","license": "MIT","bin": {"loop-worktree": "dist/cli.js"diff --git a/tools/loop-worktree/package.json b/tools/loop-worktree/package.jsonindex 2c1181b..42b30dd 100644--- a/tools/loop-worktree/package.json+++ b/tools/loop-worktree/package.json@@ -1,6 +1,6 @@{"name": "@cobusgreyling/loop-worktree",- "version": "1.0.0",+ "version": "1.1.0","description": "Manage isolated git worktrees for loop engineering attempts: create, mark, cleanup, and reconcile one worktree per fix attempt.","type": "module","bin": {@@ -12,7 +12,7 @@],"scripts": {"build": "tsc && chmod +x dist/cli.js",- "test": "npm run build && node --test test/worktree.test.mjs",+ "test": "npm run build && node --test test/*.test.mjs","prepublishOnly": "npm test","start": "node dist/cli.js"},diff --git a/tools/loop-worktree/src/cli.ts b/tools/loop-worktree/src/cli.tsindex 8510aaa..a84f0ce 100644--- a/tools/loop-worktree/src/cli.ts+++ b/tools/loop-worktree/src/cli.ts@@ -8,6 +8,7 @@ import {VALID_STATUSES,type WorktreeStatus,} from './worktree.js';+import { lockPaths, unlockOwner, listLocks, sweepExpiredLocks, isExpired } from './lock.js';interface Flags {root: string;@@ -18,10 +19,14 @@ interface Flags {olderThan?: string;force: boolean;json: boolean;+ paths?: string;+ owner?: string;+ ttl?: string;+ sweep: boolean;}function parseFlags(argv: string[]): Flags {- const flags: Flags = { root: process.cwd(), force: false, json: false };+ const flags: Flags = { root: process.cwd(), force: false, json: false, sweep: false };for (let i = 0; i < argv.length; i++) {const a = argv[i];if (a === '--run-id') flags.runId = argv[++i];@@ -32,6 +37,10 @@ function parseFlags(argv: string[]): Flags {else if (a === '--root') flags.root = argv[++i];else if (a === '--force') flags.force = true;else if (a === '--json') flags.json = true;+ else if (a === '--paths') flags.paths = argv[++i];+ else if (a === '--owner') flags.owner = argv[++i];+ else if (a === '--ttl') flags.ttl = argv[++i];+ else if (a === '--sweep') flags.sweep = true;}return flags;}@@ -54,14 +63,25 @@ Usage:loop-worktree cleanup [--status rejected,escalated] [--older-than 24h] [--force]loop-worktree gc [--force] [--json]loop-worktree list [--status <s>] [--json]+ loop-worktree lock --paths <glob1,glob2,...> --owner <name> [--ttl 6h]+ loop-worktree unlock --owner <name>+ loop-worktree locks [--sweep] [--force] [--json]Common flags:--root <dir> Repo root to operate in (default: cwd)- --json Machine-readable output (list, gc)- --force Allow removing worktrees with uncommitted changes / orphans+ --json Machine-readable output (list, gc, locks)+ --force Allow removing worktrees with uncommitted changes / orphans,+ or (with locks --sweep) deleting expired lock files++Locking (advisory, not enforced by create -- pair it in your control script):+ --paths <csv> Comma-separated path globs this owner is about to touch+ --owner <name> Lock/unlock identity, typically the pattern name+ --ttl <dur> Optional expiry (e.g. 30m, 6h, 1d); omit for no auto-expiry+ locks --sweep Report expired locks (report-only; --force deletes them)Worktrees live under .loop-worktrees/, tracked in .loop-worktrees/manifest.json.-Add .loop-worktrees/ to .gitignore.`;+Locks live under .loop-worktrees/locks/<owner>.json. Add .loop-worktrees/ to+.gitignore.`;async function main(): Promise<number> {const argv = process.argv.slice(2);@@ -145,6 +165,54 @@ async function main(): Promise<number> {}return 0;}+ case 'lock': {+ if (!flags.paths || !flags.owner) {+ throw new Error('lock requires --paths and --owner.');+ }+ const paths = flags.paths.split(',').map((p) => p.trim()).filter(Boolean);+ const entry = await lockPaths({ root: flags.root, owner: flags.owner, paths, ttl: flags.ttl });+ console.log(`locked ${entry.paths.join(', ')} for ${entry.owner}` + (entry.expiresAt ? ` (expires ${entry.expiresAt})` : ''));+ return 0;+ }+ case 'unlock': {+ if (!flags.owner) {+ throw new Error('unlock requires --owner.');+ }+ const released = await unlockOwner(flags.root, flags.owner);+ console.log(released ? `unlocked ${flags.owner}` : `${flags.owner} held no lock`);+ return 0;+ }+ case 'locks': {+ if (flags.sweep) {+ const result = await sweepExpiredLocks(flags.root, { force: flags.force });+ if (flags.json) {+ console.log(JSON.stringify(result, null, 2));+ return 0;+ }+ for (const l of result.expired) {+ console.log(result.removed.includes(l.owner) ? `removed expired lock ${l.owner}` : `expired lock ${l.owner}`);+ }+ console.log(+ `locks --sweep: ${result.expired.length} expired` ++ (flags.force ? `, ${result.removed.length} removed` : ' (report-only; use --force to remove)'),+ );+ return 0;+ }+ const locks = await listLocks(flags.root);+ if (flags.json) {+ console.log(JSON.stringify(locks.map((l) => ({ ...l, expired: isExpired(l) })), null, 2));+ return 0;+ }+ if (locks.length === 0) {+ console.log('no active locks');+ return 0;+ }+ for (const l of locks) {+ const expiryNote = l.expiresAt ? `, expires ${l.expiresAt}${isExpired(l) ? ' (expired)' : ''}` : '';+ console.log(`${l.owner} ${l.paths.join(', ')} (locked ${l.lockedAt}${expiryNote})`);+ }+ return 0;+ }default:console.error(`Unknown command "${command}".\n\n${HELP}`);return 1;diff --git a/tools/loop-worktree/src/lock.ts b/tools/loop-worktree/src/lock.tsnew file mode 100644index 0000000..4f0d922--- /dev/null+++ b/tools/loop-worktree/src/lock.ts@@ -0,0 +1,222 @@+import { readFile, writeFile, mkdir, readdir, unlink, access, open } from 'node:fs/promises';+import path from 'node:path';+import { MANIFEST_DIR, parseDurationMs } from './worktree.js';++export const LOCKS_DIR = path.posix.join(MANIFEST_DIR, 'locks');+const MUTEX_FILE = path.posix.join(LOCKS_DIR, '.mutex');++export interface LockEntry {+ owner: string;+ paths: string[];+ lockedAt: string;+ /** Absent means the lock never expires automatically; must be explicitly unlocked. */+ expiresAt?: string;+}++const OWNER_PATTERN = /^[A-Za-z0-9._-]+$/;++function assertValidOwner(owner: string): void {+ if (!OWNER_PATTERN.test(owner)) {+ throw new Error(+ `Invalid --owner "${owner}". Use only letters, digits, ".", "_", "-" (no path separators).`,+ );+ }+}++async function exists(p: string): Promise<boolean> {+ try {+ await access(p);+ return true;+ } catch {+ return false;+ }+}++async function readdirSafely(dir: string): Promise<string[]> {+ try {+ return await readdir(dir);+ } catch {+ return [];+ }+}++function lockFile(root: string, owner: string): string {+ return path.join(root, LOCKS_DIR, `${owner}.json`);+}++async function readLock(root: string, owner: string): Promise<LockEntry | null> {+ const file = lockFile(root, owner);+ if (!(await exists(file))) return null;+ const raw = await readFile(file, 'utf8');+ try {+ return JSON.parse(raw) as LockEntry;+ } catch {+ throw new Error(+ `Corrupt lock file ${file}: not valid JSON. Inspect it and delete it manually if it's stale.`,+ );+ }+}++export function isExpired(lock: LockEntry, now: number = Date.now()): boolean {+ return lock.expiresAt !== undefined && Date.parse(lock.expiresAt) <= now;+}++function isWildcardSegment(segment: string): boolean {+ return /[*?]/.test(segment);+}++/**+ * Two path globs "overlap" if, segment by segment, every position where both+ * have a literal (non-wildcard) segment agrees -- a wildcard segment (`*` or+ * `**`) is treated as compatible with anything at that position. If one glob+ * has fewer segments, it only "covers" the longer, more specific path when+ * its last segment is itself a wildcard (e.g. "src/**" covers+ * "src/nested/foo.ts"); otherwise a shorter path is a distinct, shallower+ * file and does not overlap. Deliberately simple -- an advisory lock, not a+ * full glob engine.+ */+export function pathsOverlap(a: string, b: string): boolean {+ if (a === b) return true;+ const segA = a.split('/').filter(Boolean);+ const segB = b.split('/').filter(Boolean);+ const len = Math.min(segA.length, segB.length);+ for (let i = 0; i < len; i++) {+ const sa = segA[i];+ const sb = segB[i];+ if (sa === sb) continue;+ if (isWildcardSegment(sa) || isWildcardSegment(sb)) continue;+ return false;+ }+ if (segA.length === segB.length) return true;+ const shorter = segA.length < segB.length ? segA : segB;+ return isWildcardSegment(shorter[shorter.length - 1]);+}++export async function listLocks(root: string): Promise<LockEntry[]> {+ const files = await readdirSafely(path.join(root, LOCKS_DIR));+ const locks: LockEntry[] = [];+ for (const file of files) {+ if (!file.endsWith('.json')) continue;+ const lock = await readLock(root, file.slice(0, -'.json'.length));+ if (lock) locks.push(lock);+ }+ return locks;+}++/**+ * Serialize the check-then-write critical section across processes using an+ * exclusive-create mutex file (atomic on POSIX and Windows). Without this,+ * two `lock` calls racing close together could both pass the overlap check+ * before either writes -- exactly the collision this feature exists to+ * prevent.+ */+async function withLocksMutex<T>(root: string, fn: () => Promise<T>): Promise<T> {+ const dir = path.join(root, LOCKS_DIR);+ await mkdir(dir, { recursive: true });+ const mutexPath = path.join(root, MUTEX_FILE);+ const deadline = Date.now() + 5000;+ for (;;) {+ try {+ const handle = await open(mutexPath, 'wx');+ await handle.close();+ break;+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;+ if (Date.now() > deadline) {+ throw new Error(+ `Timed out waiting for the lock mutex (${MUTEX_FILE}). If no other loop-worktree ` ++ 'process is running, delete it manually.',+ );+ }+ await new Promise((resolve) => setTimeout(resolve, 25 + Math.random() * 50));+ }+ }+ try {+ return await fn();+ } finally {+ await unlink(mutexPath).catch(() => {});+ }+}++export interface LockPathsInput {+ root: string;+ owner: string;+ paths: string[];+ /** e.g. "6h" -- if omitted, the lock never expires automatically. */+ ttl?: string;+}++/**+ * Acquire an advisory lock on `paths` for `owner`. Fails if any *other*,+ * non-expired owner already holds an overlapping path. Re-locking as the+ * same owner replaces that owner's own previous lock (paths and TTL both).+ */+export async function lockPaths(input: LockPathsInput): Promise<LockEntry> {+ const { root, owner, paths } = input;+ assertValidOwner(owner);+ if (paths.length === 0) {+ throw new Error('--paths requires at least one path or glob.');+ }++ return withLocksMutex(root, async () => {+ const now = Date.now();+ for (const other of await listLocks(root)) {+ if (other.owner === owner || isExpired(other, now)) continue;+ for (const p of paths) {+ const clash = other.paths.find((op) => pathsOverlap(p, op));+ if (clash) {+ throw new Error(+ `Path "${p}" is locked by owner "${other.owner}" (locked at ${other.lockedAt}` ++ (other.expiresAt ? `, expires at ${other.expiresAt}` : '') ++ `). Use --paths that don't overlap, or wait for the lock to clear.`,+ );+ }+ }+ }++ const entry: LockEntry = { owner, paths, lockedAt: new Date(now).toISOString() };+ if (input.ttl) {+ entry.expiresAt = new Date(now + parseDurationMs(input.ttl, '--ttl')).toISOString();+ }++ await writeFile(lockFile(root, owner), `${JSON.stringify(entry, null, 2)}\n`);+ return entry;+ });+}++/** Release `owner`'s lock. Returns false (no-op) if it didn't hold one. */+export async function unlockOwner(root: string, owner: string): Promise<boolean> {+ assertValidOwner(owner);+ const file = lockFile(root, owner);+ if (!(await exists(file))) return false;+ await unlink(file);+ return true;+}++export interface SweepExpiredLocksResult {+ expired: LockEntry[];+ removed: string[];+}++/** Report (and, with force, delete) locks past their own TTL. Never touches an active lock. */+export async function sweepExpiredLocks(+ root: string,+ opts: { force?: boolean } = {},+): Promise<SweepExpiredLocksResult> {+ return withLocksMutex(root, async () => {+ const now = Date.now();+ const expired = (await listLocks(root)).filter((l) => isExpired(l, now));+ const removed: string[] = [];+ if (opts.force) {+ for (const l of expired) {+ try {+ await unlink(lockFile(root, l.owner));+ removed.push(l.owner);+ } catch {+ // Already gone; nothing to report.+ }+ }+ }+ return { expired, removed };+ });+}diff --git a/tools/loop-worktree/src/worktree.ts b/tools/loop-worktree/src/worktree.tsindex cbd7bb5..5226cce 100644--- a/tools/loop-worktree/src/worktree.ts+++ b/tools/loop-worktree/src/worktree.ts@@ -157,10 +157,11 @@ export async function markWorktree(input: MarkInput): Promise<WorktreeEntry> {return entry;}-function parseInterval(token: string): number {+/** Parse a duration like "30m", "24h", "7d" into milliseconds. Shared with lock.ts's --ttl. */+export function parseDurationMs(token: string, flag: string): number {const m = /^(\d+)([mhd])$/.exec(token.trim());if (!m) {- throw new Error(`Invalid --older-than "${token}". Use e.g. 30m, 24h, 7d.`);+ throw new Error(`Invalid ${flag} "${token}". Use e.g. 30m, 24h, 7d.`);}const n = Number(m[1]);const unit = m[2];@@ -185,7 +186,7 @@ export async function cleanupWorktrees(input: CleanupInput): Promise<CleanupResuconst { root } = input;await assertGitRepo(root);const statuses = input.statuses ?? CLEANUP_DEFAULT_STATUSES;- const cutoff = input.olderThan ? Date.now() - parseInterval(input.olderThan) : undefined;+ const cutoff = input.olderThan ? Date.now() - parseDurationMs(input.olderThan, '--older-than') : undefined;const manifest = await readManifest(root);const removed: WorktreeEntry[] = [];diff --git a/tools/loop-worktree/test/cli.test.mjs b/tools/loop-worktree/test/cli.test.mjsnew file mode 100644index 0000000..2e056be--- /dev/null+++ b/tools/loop-worktree/test/cli.test.mjs@@ -0,0 +1,85 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { spawnSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { mkdtemp } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++const cli = path.join(path.dirname(fileURLToPath(import.meta.url)), '../dist/cli.js');++async function freshDir() {+ return mkdtemp(path.join(tmpdir(), 'loop-worktree-cli-'));+}++function runCli(args, root) {+ return spawnSync(process.execPath, [cli, ...args, '--root', root], { encoding: 'utf8' });+}++test('cli lock requires --paths and --owner', async () => {+ const dir = await freshDir();+ const r = runCli(['lock', '--owner', 'ci-sweeper'], dir);+ assert.equal(r.status, 1);+ assert.match(r.stderr, /lock requires --paths and --owner/);+});++test('cli lock/locks/unlock round-trip', async () => {+ const dir = await freshDir();++ const locked = runCli(['lock', '--paths', 'package.json,package-lock.json', '--owner', 'dependency-sweeper'], dir);+ assert.equal(locked.status, 0);+ assert.match(locked.stdout, /locked package\.json, package-lock\.json for dependency-sweeper/);++ const listed = runCli(['locks', '--json'], dir);+ assert.equal(listed.status, 0);+ const locks = JSON.parse(listed.stdout);+ assert.equal(locks.length, 1);+ assert.equal(locks[0].owner, 'dependency-sweeper');++ const unlocked = runCli(['unlock', '--owner', 'dependency-sweeper'], dir);+ assert.equal(unlocked.status, 0);+ assert.match(unlocked.stdout, /unlocked dependency-sweeper/);++ const listedAfter = runCli(['locks', '--json'], dir);+ assert.deepEqual(JSON.parse(listedAfter.stdout), []);+});++test('cli lock surfaces an overlap error from a different owner', () => {+ return freshDir().then((dir) => {+ const first = runCli(['lock', '--paths', 'package.json', '--owner', 'dependency-sweeper'], dir);+ assert.equal(first.status, 0);++ const second = runCli(['lock', '--paths', 'package.json', '--owner', 'ci-sweeper'], dir);+ assert.equal(second.status, 1);+ assert.match(second.stderr, /locked by owner "dependency-sweeper"/);+ });+});++test('cli unlock on an owner with no lock is a no-op, not an error', async () => {+ const dir = await freshDir();+ const r = runCli(['unlock', '--owner', 'nobody'], dir);+ assert.equal(r.status, 0);+ assert.match(r.stdout, /nobody held no lock/);+});++test('cli locks --sweep reports expired locks report-only, removes with --force', async () => {+ const dir = await freshDir();+ const locked = runCli(['lock', '--paths', 'package.json', '--owner', 'ci-sweeper', '--ttl', '30m'], dir);+ assert.equal(locked.status, 0);++ const { readFile, writeFile } = await import('node:fs/promises');+ const file = path.join(dir, '.loop-worktrees', 'locks', 'ci-sweeper.json');+ const stale = JSON.parse(await readFile(file, 'utf8'));+ stale.expiresAt = new Date(Date.now() - 1000).toISOString();+ await writeFile(file, JSON.stringify(stale));++ const reported = runCli(['locks', '--sweep', '--json'], dir);+ assert.equal(reported.status, 0);+ const reportedResult = JSON.parse(reported.stdout);+ assert.equal(reportedResult.expired.length, 1);+ assert.equal(reportedResult.removed.length, 0);++ const swept = runCli(['locks', '--sweep', '--force', '--json'], dir);+ const sweptResult = JSON.parse(swept.stdout);+ assert.deepEqual(sweptResult.removed, ['ci-sweeper']);+});diff --git a/tools/loop-worktree/test/lock.test.mjs b/tools/loop-worktree/test/lock.test.mjsnew file mode 100644index 0000000..205368b--- /dev/null+++ b/tools/loop-worktree/test/lock.test.mjs@@ -0,0 +1,158 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { lockPaths, unlockOwner, listLocks, sweepExpiredLocks, pathsOverlap, isExpired } from '../dist/lock.js';++async function freshDir() {+ return mkdtemp(path.join(tmpdir(), 'loop-worktree-lock-'));+}++test('pathsOverlap: exact match, glob prefix, and distinct files', () => {+ assert.equal(pathsOverlap('package.json', 'package.json'), true);+ assert.equal(pathsOverlap('src/**', 'src/foo.ts'), true);+ assert.equal(pathsOverlap('src/foo.ts', 'src/**'), true);+ assert.equal(pathsOverlap('package.json', 'package-lock.json'), false);+});++test('pathsOverlap respects path-segment boundaries, not raw string prefixes', () => {+ // A shared literal character prefix across segments must not count as overlap.+ assert.equal(pathsOverlap('docs/api', 'docs/apidocs.md'), false);+ assert.equal(pathsOverlap('src/foo', 'src/foobar.ts'), false);+ // But a wildcard segment still covers a deeper, more specific path.+ assert.equal(pathsOverlap('src/**', 'src/nested/foo.ts'), true);+});++test('lockPaths acquires a lock with no TTL by default', async () => {+ const dir = await freshDir();+ const entry = await lockPaths({ root: dir, owner: 'ci-sweeper', paths: ['package.json'] });+ assert.equal(entry.owner, 'ci-sweeper');+ assert.deepEqual(entry.paths, ['package.json']);+ assert.equal(entry.expiresAt, undefined);+ assert.equal(isExpired(entry), false);+});++test('lockPaths sets expiresAt from --ttl', async () => {+ const dir = await freshDir();+ const entry = await lockPaths({ root: dir, owner: 'ci-sweeper', paths: ['package.json'], ttl: '30m' });+ assert.ok(entry.expiresAt);+ assert.ok(Date.parse(entry.expiresAt) > Date.now());+});++test('lockPaths rejects an overlapping path already locked by another owner', async () => {+ const dir = await freshDir();+ await lockPaths({ root: dir, owner: 'dependency-sweeper', paths: ['package.json', 'package-lock.json'] });+ await assert.rejects(+ () => lockPaths({ root: dir, owner: 'ci-sweeper', paths: ['package.json'] }),+ /locked by owner "dependency-sweeper"/,+ );+});++test('lockPaths allows non-overlapping paths from a different owner', async () => {+ const dir = await freshDir();+ await lockPaths({ root: dir, owner: 'dependency-sweeper', paths: ['package.json'] });+ const entry = await lockPaths({ root: dir, owner: 'ci-sweeper', paths: ['tests/**'] });+ assert.equal(entry.owner, 'ci-sweeper');+});++test('lockPaths lets the same owner re-lock (replace, not stack)', async () => {+ const dir = await freshDir();+ await lockPaths({ root: dir, owner: 'ci-sweeper', paths: ['package.json'] });+ const second = await lockPaths({ root: dir, owner: 'ci-sweeper', paths: ['tests/**'] });+ assert.deepEqual(second.paths, ['tests/**']);+ const locks = await listLocks(dir);+ assert.equal(locks.length, 1);+});++test('an expired lock no longer blocks a new lock on the same paths', async () => {+ const dir = await freshDir();+ await lockPaths({ root: dir, owner: 'dependency-sweeper', paths: ['package.json'], ttl: '30m' });+ // Force the just-written lock into the past instead of waiting 30 minutes.+ const { writeFile, readFile } = await import('node:fs/promises');+ const file = path.join(dir, '.loop-worktrees', 'locks', 'dependency-sweeper.json');+ const stale = JSON.parse(await readFile(file, 'utf8'));+ stale.expiresAt = new Date(Date.now() - 1000).toISOString();+ await writeFile(file, JSON.stringify(stale));++ const entry = await lockPaths({ root: dir, owner: 'ci-sweeper', paths: ['package.json'] });+ assert.equal(entry.owner, 'ci-sweeper');+});++test('lockPaths rejects an owner name that would escape the locks directory', async () => {+ const dir = await freshDir();+ await assert.rejects(+ () => lockPaths({ root: dir, owner: '../../escaped', paths: ['package.json'] }),+ /Invalid --owner/,+ );+});++test('unlockOwner rejects an invalid owner name the same way', async () => {+ const dir = await freshDir();+ await assert.rejects(() => unlockOwner(dir, '../../escaped'), /Invalid --owner/);+});++test('a corrupt lock file surfaces a clear error instead of crashing every owner', async () => {+ const dir = await freshDir();+ await lockPaths({ root: dir, owner: 'ci-sweeper', paths: ['package.json'] });+ const { writeFile } = await import('node:fs/promises');+ await writeFile(path.join(dir, '.loop-worktrees', 'locks', 'dependency-sweeper.json'), '{not valid json');++ await assert.rejects(() => listLocks(dir), /Corrupt lock file/);+ await assert.rejects(+ () => lockPaths({ root: dir, owner: 'pr-babysitter', paths: ['tests/**'] }),+ /Corrupt lock file/,+ );+});++test('concurrent lockPaths calls on overlapping paths: exactly one wins', async () => {+ const dir = await freshDir();+ const owners = ['ci-sweeper', 'dependency-sweeper', 'pr-babysitter'];+ const results = await Promise.allSettled(+ owners.map((owner) => lockPaths({ root: dir, owner, paths: ['package.json'] })),+ );+ const fulfilled = results.filter((r) => r.status === 'fulfilled');+ assert.equal(fulfilled.length, 1, 'exactly one racing lock call should succeed');+ const locks = await listLocks(dir);+ assert.equal(locks.length, 1);+});++test('unlockOwner releases a lock; is a no-op if none held', async () => {+ const dir = await freshDir();+ await lockPaths({ root: dir, owner: 'ci-sweeper', paths: ['package.json'] });+ assert.equal(await unlockOwner(dir, 'ci-sweeper'), true);+ assert.equal((await listLocks(dir)).length, 0);+ assert.equal(await unlockOwner(dir, 'ci-sweeper'), false);+});++test('sweepExpiredLocks reports but does not delete without --force', async () => {+ const dir = await freshDir();+ await lockPaths({ root: dir, owner: 'ci-sweeper', paths: ['package.json'], ttl: '30m' });+ const { writeFile, readFile } = await import('node:fs/promises');+ const file = path.join(dir, '.loop-worktrees', 'locks', 'ci-sweeper.json');+ const stale = JSON.parse(await readFile(file, 'utf8'));+ stale.expiresAt = new Date(Date.now() - 1000).toISOString();+ await writeFile(file, JSON.stringify(stale));++ const result = await sweepExpiredLocks(dir);+ assert.equal(result.expired.length, 1);+ assert.equal(result.removed.length, 0);+ assert.equal((await listLocks(dir)).length, 1);+});++test('sweepExpiredLocks removes with --force, leaves active locks untouched', async () => {+ const dir = await freshDir();+ await lockPaths({ root: dir, owner: 'ci-sweeper', paths: ['package.json'], ttl: '30m' });+ await lockPaths({ root: dir, owner: 'dependency-sweeper', paths: ['tests/**'] });+ const { writeFile, readFile } = await import('node:fs/promises');+ const file = path.join(dir, '.loop-worktrees', 'locks', 'ci-sweeper.json');+ const stale = JSON.parse(await readFile(file, 'utf8'));+ stale.expiresAt = new Date(Date.now() - 1000).toISOString();+ await writeFile(file, JSON.stringify(stale));++ const result = await sweepExpiredLocks(dir, { force: true });+ assert.deepEqual(result.removed, ['ci-sweeper']);+ const remaining = await listLocks(dir);+ assert.deepEqual(remaining.map((l) => l.owner), ['dependency-sweeper']);+});