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-swarm): implement multi-agent consensus sandboxing (#398)

THRISHAL DOMA30a4c109bfdd
diff --git a/package.json b/package.json
index 442c0db..4299712 100644
--- a/package.json
+++ b/package.json
@@ -14,12 +14,13 @@
"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:loop-swarm": "cd tools/loop-swarm && npm test",
"test:loop": "cd tools/loop && 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:loop-sandbox && npm run test:loop && 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 ../loop && 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:loop-swarm && npm run test:loop && 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 ../loop-swarm && npm run build && cd ../loop && 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/package.json b/tools/loop-sandbox/package.json
index 224803b..c257a2d 100644
--- a/tools/loop-sandbox/package.json
+++ b/tools/loop-sandbox/package.json
@@ -6,6 +6,8 @@
"bin": {
"loop-sandbox": "./dist/cli.js"
},
+ "main": "./dist/sandbox.js",
+ "types": "./dist/sandbox.d.ts",
"files": [
"dist",
"README.md"
diff --git a/tools/loop-swarm/README.md b/tools/loop-swarm/README.md
new file mode 100644
index 0000000..a213028
--- /dev/null
+++ b/tools/loop-swarm/README.md
@@ -0,0 +1,36 @@
+# loop-swarm
+
+Multi-agent consensus sandboxing for extreme high-confidence loop operations.
+
+`loop-swarm` runs an agent command multiple times sequentially in separate, isolated `loop-sandbox` worktrees. It then extracts the resulting `.patch` files from each run, hashes them, and automatically determines if a majority consensus was reached.
+
+If an agent produces non-deterministic results, `loop-swarm` acts as an L3 safety net by ensuring that only changes verified by multiple sequential agent runs are proposed.
+
+> [!IMPORTANT]
+> This tool implements an **ephemeral git worktree isolation** safety boundary. It is NOT an OS-level sandbox or container. For full details on the threat model, please read [Safety Boundaries](../../docs/safety.md).
+
+## Usage
+
+```bash
+npx @cobusgreyling/loop-swarm run --count 3 -- npx my-agent run --task "Refactor utils.ts"
+```
+
+## How it works
+
+1. Spawns `N` (default: 3) instances of `loop-sandbox` sequentially (to prevent git worktree and signal handler races).
+2. Waits for all sandboxes to finish executing the agent and extract their diffs. Any agent that fails (non-zero exit code) is disqualified from voting.
+3. Hashes the raw byte contents of each `.patch` file.
+4. If a strict majority (`Math.floor(N / 2) + 1` of the total launched agents) produce the exact same byte-for-byte patch, it copies the winning patch to `.loop-sandbox/patches/consensus.patch`.
+5. Cleans up all the ephemeral worktrees.
+
+## Exit Codes & Behavior
+
+- **`0`**: Consensus reached successfully (either on a specific patch, or on "no changes needed" if the majority of agents succeeded without producing a patch).
+- **`1`**: Failure to reach consensus, or internal tool failure.
+
+## Limitations
+
+- **Byte-Identical Consensus**: Consensus relies on exact `SHA-256` hashing of the patch bytes. If two agents arrive at semantically identical code but with different whitespace or comment ordering, `loop-swarm` will consider them divergent.
+- **Shared Stdio**: The sequential agents share the parent process's standard IO.
+- **Time Penalty**: Because execution is currently serialized to maintain safety guarantees on the manifest, running an agent with `--count 3` will take roughly 3x as long as running it once.
+- **SIGINT Handling**: Because `loop-sandbox` runs in-process, its signal handler will exit the entire process on `SIGINT`. A signal during an agent run exits the entire swarm rather than allowing swarm-owned cleanup. This is a v1 limitation until subprocessing is implemented.
diff --git a/tools/loop-swarm/dist/cli.d.ts b/tools/loop-swarm/dist/cli.d.ts
new file mode 100644
index 0000000..b798801
--- /dev/null
+++ b/tools/loop-swarm/dist/cli.d.ts
@@ -0,0 +1,2 @@
+#!/usr/bin/env node
+export {};
diff --git a/tools/loop-swarm/dist/cli.js b/tools/loop-swarm/dist/cli.js
new file mode 100644
index 0000000..b25fadf
--- /dev/null
+++ b/tools/loop-swarm/dist/cli.js
@@ -0,0 +1,68 @@
+#!/usr/bin/env node
+import { parseArgs } from 'node:util';
+import { runSwarm } from './swarm.js';
+async function main() {
+ const { values, positionals } = parseArgs({
+ args: process.argv.slice(2),
+ options: {
+ count: { type: 'string', short: 'n', default: '3' },
+ shell: { type: 'boolean', default: false },
+ help: { type: 'boolean', short: 'h', default: false },
+ },
+ strict: false, // Allow extra args after --
+ allowPositionals: true
+ });
+ if (positionals.length === 0 || positionals[0] !== 'run' || values.help) {
+ const isHelp = values.help;
+ const msg = `
+Usage: loop-swarm run [options] -- <command>
+
+Options:
+ --count, -n Number of parallel agents to spawn (default: 3)
+ --shell Execute the command inside a shell
+ --help, -h Show this help message
+`;
+ if (!isHelp) {
+ console.error('❌ Missing or invalid subcommand. Must use "run".');
+ console.error(msg);
+ process.exit(1);
+ }
+ else {
+ console.log(msg);
+ process.exit(0);
+ }
+ }
+ // Find the -- separator manually if parseArgs doesn't handle it easily
+ const args = process.argv.slice(2);
+ const separatorIndex = args.indexOf('--');
+ if (separatorIndex === -1 || separatorIndex === args.length - 1) {
+ console.error('❌ Missing command. Use -- to separate options from the command.');
+ console.error('Example: loop-swarm run --count 3 -- echo "hello"');
+ process.exit(1);
+ }
+ const agentCommandParts = args.slice(separatorIndex + 1);
+ const command = agentCommandParts[0];
+ const commandArgs = agentCommandParts.slice(1);
+ const count = parseInt(values.count, 10);
+ if (isNaN(count) || count < 1) {
+ console.error('❌ --count must be a positive integer.');
+ process.exit(1);
+ }
+ try {
+ const result = await runSwarm(process.cwd(), command, commandArgs, {
+ count,
+ shell: values.shell
+ });
+ if (result.reached) {
+ process.exit(0);
+ }
+ else {
+ process.exit(1);
+ }
+ }
+ catch (err) {
+ console.error('❌ loop-swarm failed:', err);
+ process.exit(1);
+ }
+}
+main();
diff --git a/tools/loop-swarm/dist/swarm.d.ts b/tools/loop-swarm/dist/swarm.d.ts
new file mode 100644
index 0000000..f2af5bc
--- /dev/null
+++ b/tools/loop-swarm/dist/swarm.d.ts
@@ -0,0 +1,13 @@
+import { SandboxOptions } from '@cobusgreyling/loop-sandbox';
+export interface SwarmOptions extends SandboxOptions {
+ count: number;
+}
+export interface ConsensusResult {
+ reached: boolean;
+ majorityHash: string | null;
+ majorityCount: number;
+ totalPatches: number;
+ consensusPatchFile: string | null;
+ divergentPatches: string[];
+}
+export declare function runSwarm(root: string, command: string, args: string[], options: SwarmOptions): Promise<ConsensusResult>;
diff --git a/tools/loop-swarm/dist/swarm.js b/tools/loop-swarm/dist/swarm.js
new file mode 100644
index 0000000..48807b7
--- /dev/null
+++ b/tools/loop-swarm/dist/swarm.js
@@ -0,0 +1,83 @@
+import { readFile, copyFile } from 'node:fs/promises';
+import { createHash } from 'node:crypto';
+import path from 'node:path';
+import { runInSandbox } from '@cobusgreyling/loop-sandbox';
+export async function runSwarm(root, command, args, options) {
+ const { count, ...sandboxOptions } = options;
+ console.log(`\n🐝 Launching loop-swarm with ${count} sequential agents (serialized to prevent worktree races)...`);
+ const results = [];
+ for (let i = 0; i < count; i++) {
+ console.log(`\n▶️ Agent ${i + 1}/${count}`);
+ results.push(await runInSandbox(root, command, args, sandboxOptions));
+ }
+ console.log(`\n🧠 Analyzing swarm results...`);
+ // Filter out runs that failed (non-zero exitCode)
+ const successfulRuns = results.filter(r => r.exitCode === 0);
+ const failedRuns = count - successfulRuns.length;
+ if (failedRuns > 0) {
+ console.log(`⚠️ ${failedRuns} agent(s) failed with non-zero exit codes. They are excluded from consensus voting.`);
+ }
+ // Count identical patches among successful runs
+ const hashCounts = {};
+ let noChangeCount = 0;
+ for (const r of successfulRuns) {
+ if (!r.hasChanges || !r.patchFile) {
+ noChangeCount++;
+ continue;
+ }
+ const buffer = await readFile(r.patchFile);
+ const hash = createHash('sha256').update(buffer).digest('hex');
+ if (!hashCounts[hash]) {
+ hashCounts[hash] = { count: 0, files: [] };
+ }
+ hashCounts[hash].count++;
+ hashCounts[hash].files.push(r.patchFile);
+ }
+ const threshold = Math.floor(count / 2) + 1; // Strict majority of total launched agents
+ if (noChangeCount >= threshold) {
+ console.log(`✅ Consensus reached! ${noChangeCount}/${count} agents produced NO changes (success).`);
+ return {
+ reached: true,
+ majorityHash: null,
+ majorityCount: noChangeCount,
+ totalPatches: successfulRuns.length - noChangeCount,
+ consensusPatchFile: null,
+ divergentPatches: []
+ };
+ }
+ // Find majority among patches
+ let maxCount = 0;
+ let majorityHash = null;
+ for (const [hash, data] of Object.entries(hashCounts)) {
+ if (data.count > maxCount) {
+ maxCount = data.count;
+ majorityHash = hash;
+ }
+ }
+ const divergentPatches = Object.values(hashCounts).flatMap(d => d.files);
+ if (maxCount >= threshold && majorityHash) {
+ console.log(`✅ Consensus reached! ${maxCount}/${count} agents produced the exact same patch.`);
+ const representativePatch = hashCounts[majorityHash].files[0];
+ const consensusPatchFile = path.join(path.dirname(representativePatch), 'consensus.patch');
+ await copyFile(representativePatch, consensusPatchFile);
+ console.log(`🎉 Consensus patch saved to: ${consensusPatchFile}`);
+ return {
+ reached: true,
+ majorityHash,
+ majorityCount: maxCount,
+ totalPatches: successfulRuns.length - noChangeCount,
+ consensusPatchFile,
+ divergentPatches: divergentPatches.filter(f => !hashCounts[majorityHash].files.includes(f))
+ };
+ }
+ const maxAgreement = Math.max(maxCount, noChangeCount);
+ console.log(`❌ Swarm failed to reach consensus. (Highest agreement: ${maxAgreement}/${count})`);
+ return {
+ reached: false,
+ majorityHash: null,
+ majorityCount: maxAgreement,
+ totalPatches: successfulRuns.length - noChangeCount,
+ consensusPatchFile: null,
+ divergentPatches
+ };
+}
diff --git a/tools/loop-swarm/package-lock.json b/tools/loop-swarm/package-lock.json
new file mode 100644
index 0000000..6449466
--- /dev/null
+++ b/tools/loop-swarm/package-lock.json
@@ -0,0 +1,95 @@
+{
+ "name": "@cobusgreyling/loop-swarm",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@cobusgreyling/loop-swarm",
+ "version": "1.0.0",
+ "license": "MIT",
+ "dependencies": {
+ "@cobusgreyling/loop-sandbox": "file:../loop-sandbox"
+ },
+ "bin": {
+ "loop-swarm": "dist/cli.js"
+ },
+ "devDependencies": {
+ "@types/node": "^20.0.0",
+ "typescript": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "../loop-sandbox": {
+ "name": "@cobusgreyling/loop-sandbox",
+ "version": "1.0.0",
+ "license": "MIT",
+ "dependencies": {
+ "@cobusgreyling/loop-worktree": "^1.2.0"
+ },
+ "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",
+ "extraneous": true,
+ "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-sandbox": {
+ "resolved": "../loop-sandbox",
+ "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-swarm/package.json b/tools/loop-swarm/package.json
new file mode 100644
index 0000000..70c816a
--- /dev/null
+++ b/tools/loop-swarm/package.json
@@ -0,0 +1,49 @@
+{
+ "name": "@cobusgreyling/loop-swarm",
+ "version": "1.0.0",
+ "description": "Multi-agent consensus sandboxing for extreme high-confidence loop operations.",
+ "type": "module",
+ "bin": {
+ "loop-swarm": "dist/cli.js"
+ },
+ "main": "dist/swarm.js",
+ "types": "dist/swarm.d.ts",
+ "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",
+ "swarm",
+ "consensus"
+ ],
+ "author": "Cobus Greyling",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/cobusgreyling/loop-engineering.git",
+ "directory": "tools/loop-swarm"
+ },
+ "homepage": "https://cobusgreyling.github.io/loop-engineering/",
+ "publishConfig": {
+ "access": "public"
+ },
+ "dependencies": {
+ "@cobusgreyling/loop-sandbox": "file:../loop-sandbox"
+ },
+ "devDependencies": {
+ "@types/node": "^20.0.0",
+ "typescript": "^5.0.0"
+ }
+}
diff --git a/tools/loop-swarm/src/cli.ts b/tools/loop-swarm/src/cli.ts
new file mode 100644
index 0000000..bda416d
--- /dev/null
+++ b/tools/loop-swarm/src/cli.ts
@@ -0,0 +1,75 @@
+#!/usr/bin/env node
+
+import { parseArgs } from 'node:util';
+import { runSwarm } from './swarm.js';
+
+async function main() {
+ const { values, positionals } = parseArgs({
+ args: process.argv.slice(2),
+ options: {
+ count: { type: 'string', short: 'n', default: '3' },
+ shell: { type: 'boolean', default: false },
+ help: { type: 'boolean', short: 'h', default: false },
+ },
+ strict: false, // Allow extra args after --
+ allowPositionals: true
+ });
+
+ if (positionals.length === 0 || positionals[0] !== 'run' || values.help) {
+ const isHelp = values.help;
+ const msg = `
+Usage: loop-swarm run [options] -- <command>
+
+Options:
+ --count, -n Number of sequential agents to spawn (default: 3)
+ --shell Execute the command inside a shell
+ --help, -h Show this help message
+`;
+ if (!isHelp) {
+ console.error('❌ Missing or invalid subcommand. Must use "run".');
+ console.error(msg);
+ process.exit(1);
+ } else {
+ console.log(msg);
+ process.exit(0);
+ }
+ }
+
+ // Find the -- separator manually if parseArgs doesn't handle it easily
+ const args = process.argv.slice(2);
+ const separatorIndex = args.indexOf('--');
+
+ if (separatorIndex === -1 || separatorIndex === args.length - 1) {
+ console.error('❌ Missing command. Use -- to separate options from the command.');
+ console.error('Example: loop-swarm run --count 3 -- echo "hello"');
+ process.exit(1);
+ }
+
+ const agentCommandParts = args.slice(separatorIndex + 1);
+ const command = agentCommandParts[0];
+ const commandArgs = agentCommandParts.slice(1);
+
+ const count = parseInt(values.count as string, 10);
+ if (isNaN(count) || count < 1) {
+ console.error('❌ --count must be a positive integer.');
+ process.exit(1);
+ }
+
+ try {
+ const result = await runSwarm(process.cwd(), command, commandArgs, {
+ count,
+ shell: values.shell as boolean
+ });
+
+ if (result.reached) {
+ process.exit(0);
+ } else {
+ process.exit(1);
+ }
+ } catch (err) {
+ console.error('❌ loop-swarm failed:', err);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/tools/loop-swarm/src/swarm.ts b/tools/loop-swarm/src/swarm.ts
new file mode 100644
index 0000000..abef436
--- /dev/null
+++ b/tools/loop-swarm/src/swarm.ts
@@ -0,0 +1,116 @@
+import { readFile, copyFile } from 'node:fs/promises';
+import { createHash } from 'node:crypto';
+import path from 'node:path';
+import { runInSandbox, SandboxOptions, SandboxResult } from '@cobusgreyling/loop-sandbox';
+
+export interface SwarmOptions extends SandboxOptions {
+ count: number;
+}
+
+export interface ConsensusResult {
+ reached: boolean;
+ majorityHash: string | null;
+ majorityCount: number;
+ totalPatches: number;
+ consensusPatchFile: string | null;
+ divergentPatches: string[];
+}
+
+export async function runSwarm(root: string, command: string, args: string[], options: SwarmOptions): Promise<ConsensusResult> {
+ const { count, ...sandboxOptions } = options;
+
+ console.log(`\n🐝 Launching loop-swarm with ${count} sequential agents (serialized to prevent worktree races)...`);
+
+ const results: SandboxResult[] = [];
+ for (let i = 0; i < count; i++) {
+ console.log(`\n▶️ Agent ${i + 1}/${count}`);
+ results.push(await runInSandbox(root, command, args, sandboxOptions));
+ }
+
+ console.log(`\n🧠 Analyzing swarm results...`);
+
+ // Filter out runs that failed (non-zero exitCode)
+ const successfulRuns = results.filter(r => r.exitCode === 0);
+ const failedRuns = count - successfulRuns.length;
+
+ if (failedRuns > 0) {
+ console.log(`⚠️ ${failedRuns} agent(s) failed with non-zero exit codes. They are excluded from consensus voting.`);
+ }
+
+ // Count identical patches among successful runs
+ const hashCounts: Record<string, { count: number; files: string[] }> = {};
+
+ let noChangeCount = 0;
+
+ for (const r of successfulRuns) {
+ if (!r.hasChanges || !r.patchFile) {
+ noChangeCount++;
+ continue;
+ }
+ const buffer = await readFile(r.patchFile);
+ const hash = createHash('sha256').update(buffer).digest('hex');
+
+ if (!hashCounts[hash]) {
+ hashCounts[hash] = { count: 0, files: [] };
+ }
+ hashCounts[hash].count++;
+ hashCounts[hash].files.push(r.patchFile);
+ }
+
+ const threshold = Math.floor(count / 2) + 1; // Strict majority of total launched agents
+
+ if (noChangeCount >= threshold) {
+ console.log(`✅ Consensus reached! ${noChangeCount}/${count} agents produced NO changes (success).`);
+ return {
+ reached: true,
+ majorityHash: null,
+ majorityCount: noChangeCount,
+ totalPatches: successfulRuns.length - noChangeCount,
+ consensusPatchFile: null,
+ divergentPatches: []
+ };
+ }
+
+ // Find majority among patches
+ let maxCount = 0;
+ let majorityHash: string | null = null;
+ for (const [hash, data] of Object.entries(hashCounts)) {
+ if (data.count > maxCount) {
+ maxCount = data.count;
+ majorityHash = hash;
+ }
+ }
+
+ const divergentPatches = Object.values(hashCounts).flatMap(d => d.files);
+
+ if (maxCount >= threshold && majorityHash) {
+ console.log(`✅ Consensus reached! ${maxCount}/${count} agents produced the exact same patch.`);
+
+ const representativePatch = hashCounts[majorityHash].files[0];
+ const consensusPatchFile = path.join(path.dirname(representativePatch), 'consensus.patch');
+
+ await copyFile(representativePatch, consensusPatchFile);
+ console.log(`🎉 Consensus patch saved to: ${consensusPatchFile}`);
+
+ return {
+ reached: true,
+ majorityHash,
+ majorityCount: maxCount,
+ totalPatches: successfulRuns.length - noChangeCount,
+ consensusPatchFile,
+ divergentPatches: divergentPatches.filter(f => !hashCounts[majorityHash!].files.includes(f))
+ };
+ }
+
+ const maxAgreement = Math.max(maxCount, noChangeCount);
+ console.log(`❌ Swarm failed to reach consensus. (Highest agreement: ${maxAgreement}/${count})`);
+
+ return {
+ reached: false,
+ majorityHash: null,
+ majorityCount: maxAgreement,
+ totalPatches: successfulRuns.length - noChangeCount,
+ consensusPatchFile: null,
+ divergentPatches
+ };
+}
diff --git a/tools/loop-swarm/test/swarm.test.mjs b/tools/loop-swarm/test/swarm.test.mjs
new file mode 100644
index 0000000..e5fa2f7
--- /dev/null
+++ b/tools/loop-swarm/test/swarm.test.mjs
@@ -0,0 +1,155 @@
+import { test } from 'node:test';
+import assert from 'node:assert';
+import { spawnSync } from 'node:child_process';
+import { mkdtemp, rm, writeFile, stat } from 'node:fs/promises';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { fileURLToPath } from 'node:url';
+
+async function setupGit(root) {
+ spawnSync('git', ['init', '-b', 'main'], { cwd: root });
+ spawnSync('git', ['config', 'user.name', 'Test User'], { cwd: root });
+ spawnSync('git', ['config', 'user.email', '[email protected]'], { cwd: root });
+ spawnSync('git', ['commit', '--allow-empty', '-m', 'init'], { cwd: root });
+}
+
+const cliUrl = new URL('../dist/cli.js', import.meta.url);
+const cliPath = fileURLToPath(cliUrl);
+
+test('loop-swarm run handles simple deterministic command', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'loop-swarm-test-'));
+ try {
+ await setupGit(root);
+
+ const scriptPath = join(root, 'agent.cjs');
+ await writeFile(scriptPath, "require('fs').writeFileSync('changes.txt', 'swarm data\\n');");
+
+ const result = spawnSync('node', [cliPath, 'run', '--count', '2', '--', 'node', scriptPath], {
+ cwd: root,
+ encoding: 'utf8'
+ });
+
+ assert.strictEqual(result.status, 0, `CLI failed: ${result.stderr || result.stdout}`);
+ assert.match(result.stdout, /Consensus reached! 2\/2/);
+
+ const patchStat = await stat(join(root, '.loop-sandbox', 'patches', 'consensus.patch'));
+ assert.ok(patchStat.size > 0, 'consensus.patch should be created');
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test('loop-swarm run fails on divergent patches', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'loop-swarm-test-'));
+ try {
+ await setupGit(root);
+
+ const scriptPath = join(root, 'agent.cjs');
+ // Non-deterministic agent
+ await writeFile(scriptPath, "require('fs').writeFileSync('changes.txt', 'swarm data ' + Math.random() + '\\n');");
+
+ const result = spawnSync('node', [cliPath, 'run', '--count', '2', '--', 'node', scriptPath], {
+ cwd: root,
+ encoding: 'utf8'
+ });
+
+ assert.notStrictEqual(result.status, 0, 'CLI should fail on divergent patches');
+ assert.match(result.stdout, /Swarm failed to reach consensus/);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test('loop-swarm handles all-failed agents properly', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'loop-swarm-test-'));
+ try {
+ await setupGit(root);
+
+ const scriptPath = join(root, 'agent.cjs');
+ // Agent that fails
+ await writeFile(scriptPath, "process.exit(1);");
+
+ const result = spawnSync('node', [cliPath, 'run', '--count', '3', '--', 'node', scriptPath], {
+ cwd: root,
+ encoding: 'utf8'
+ });
+
+ assert.notStrictEqual(result.status, 0, 'CLI should fail if all agents fail');
+ assert.match(result.stdout, /3 agent\(s\) failed with non-zero exit codes/);
+ assert.match(result.stdout, /Swarm failed to reach consensus/);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test('loop-swarm handles 2-of-3 majority with 1 divergent patch', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'loop-swarm-test-'));
+ try {
+ await setupGit(root);
+
+ const counterFile = join(tmpdir(), 'loop-swarm-counter-' + Math.random().toString().slice(2));
+ await writeFile(counterFile, '0');
+
+ const scriptPath = join(root, 'agent.cjs');
+ await writeFile(scriptPath, `
+ const fs = require('fs');
+ const counterFile = '${counterFile.replace(/\\/g, '\\\\')}';
+ const counter = parseInt(fs.readFileSync(counterFile, 'utf8'), 10);
+ fs.writeFileSync(counterFile, (counter + 1).toString());
+ if (counter === 2) {
+ fs.writeFileSync('changes.txt', 'divergent data\\n');
+ } else {
+ fs.writeFileSync('changes.txt', 'majority data\\n');
+ }
+ `);
+
+ const result = spawnSync('node', [cliPath, 'run', '--count', '3', '--', 'node', scriptPath], {
+ cwd: root,
+ encoding: 'utf8'
+ });
+
+ assert.strictEqual(result.status, 0, 'CLI should succeed on 2-of-3 majority');
+ assert.match(result.stdout, /Consensus reached! 2\/3/);
+
+ const patchStat = await stat(join(root, '.loop-sandbox', 'patches', 'consensus.patch'));
+ assert.ok(patchStat.size > 0, 'consensus.patch should be created');
+
+ await rm(counterFile, { force: true });
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test('loop-swarm handles exit-code-0 no-op majority', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'loop-swarm-test-'));
+ try {
+ await setupGit(root);
+
+ const counterFile = join(tmpdir(), 'loop-swarm-counter-' + Math.random().toString().slice(2));
+ await writeFile(counterFile, '0');
+
+ const scriptPath = join(root, 'agent.cjs');
+ await writeFile(scriptPath, `
+ const fs = require('fs');
+ const counterFile = '${counterFile.replace(/\\/g, '\\\\')}';
+ const counter = parseInt(fs.readFileSync(counterFile, 'utf8'), 10);
+ fs.writeFileSync(counterFile, (counter + 1).toString());
+ if (counter === 2) {
+ fs.writeFileSync('changes.txt', 'some change\\n');
+ }
+ `);
+
+ const result = spawnSync('node', [cliPath, 'run', '--count', '3', '--', 'node', scriptPath], {
+ cwd: root,
+ encoding: 'utf8'
+ });
+
+ assert.strictEqual(result.status, 0, 'CLI should succeed on no-op majority');
+ assert.match(result.stdout, /Consensus reached! 2\/3 agents produced NO changes/);
+
+ await rm(counterFile, { force: true });
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
diff --git a/tools/loop-swarm/tsconfig.json b/tools/loop-swarm/tsconfig.json
new file mode 100644
index 0000000..228252f
--- /dev/null
+++ b/tools/loop-swarm/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "declaration": true,
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true
+ },
+ "include": ["src/**/*"]
+}