Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

feat(daemon): repository supervisor, structured telemetry, budget CLI, migration warning (#2661) (#2663)

rUvf22088202560
diff --git a/v3/@claude-flow/cli/__tests__/daemon-migration-warning-2661.test.ts b/v3/@claude-flow/cli/__tests__/daemon-migration-warning-2661.test.ts
new file mode 100644
index 0000000000..e17175d647
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/daemon-migration-warning-2661.test.ts
@@ -0,0 +1,105 @@
+/**
+ * #2661 root-fix β€” one-time upgrade migration warning.
+ *
+ * A pre-existing multi-daemon fleet with AI workers enabled somewhere in it
+ * is the exact P0 shape the issue describes. This must warn exactly ONCE
+ * ever (a persisted marker, not a per-command check) and only for that
+ * specific risky shape β€” never for a harmless multi-daemon fleet where AI
+ * workers are off everywhere (the existing always-shown notice already
+ * covers that case, and duplicating it here would just be noise).
+ */
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, existsSync, readFileSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { maybeShowMultiDaemonMigrationWarning } from '../src/commands/daemon.js';
+
+describe('#2661 root-fix β€” maybeShowMultiDaemonMigrationWarning', () => {
+ let dir: string;
+ let markerFile: string;
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'migration-warning-test-'));
+ markerFile = join(dir, '.claude-flow', 'multi-daemon-warning-shown.json');
+ });
+
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ const wtWithState = (aiWorkersEnabled: boolean): string => {
+ const wt = mkdtempSync(join(dir, 'wt-'));
+ mkdirSync(join(wt, '.claude-flow'), { recursive: true });
+ writeFileSync(join(wt, '.claude-flow', 'daemon-state.json'), JSON.stringify({ config: { aiWorkersEnabled } }));
+ return wt;
+ };
+
+ it('does nothing for a single daemon (no fanout)', async () => {
+ const wt = wtWithState(true);
+ await maybeShowMultiDaemonMigrationWarning({
+ markerFile,
+ fleetScanner: async () => [{ pid: 1, workspace: wt }],
+ });
+ expect(existsSync(markerFile)).toBe(false);
+ });
+
+ it('writes the marker but shows nothing for a multi-daemon fleet with AI workers off everywhere', async () => {
+ const wt1 = wtWithState(false);
+ const wt2 = wtWithState(false);
+ await maybeShowMultiDaemonMigrationWarning({
+ markerFile,
+ fleetScanner: async () => [{ pid: 1, workspace: wt1 }, { pid: 2, workspace: wt2 }],
+ });
+ expect(existsSync(markerFile)).toBe(true);
+ const marker = JSON.parse(readFileSync(markerFile, 'utf-8'));
+ expect(marker.anyAiEnabled).toBe(false);
+ });
+
+ it('writes the marker for a multi-daemon fleet where AT LEAST ONE has AI workers enabled', async () => {
+ const wt1 = wtWithState(false);
+ const wt2 = wtWithState(true);
+ await maybeShowMultiDaemonMigrationWarning({
+ markerFile,
+ fleetScanner: async () => [{ pid: 1, workspace: wt1 }, { pid: 2, workspace: wt2 }],
+ });
+ expect(existsSync(markerFile)).toBe(true);
+ const marker = JSON.parse(readFileSync(markerFile, 'utf-8'));
+ expect(marker.anyAiEnabled).toBe(true);
+ expect(marker.fleetSize).toBe(2);
+ });
+
+ it('is a true ONE-TIME warning β€” never re-checks the fleet once the marker exists', async () => {
+ let scanCount = 0;
+ const scanner = async () => {
+ scanCount++;
+ return [{ pid: 1, workspace: wtWithState(true) }, { pid: 2, workspace: wtWithState(true) }];
+ };
+
+ await maybeShowMultiDaemonMigrationWarning({ markerFile, fleetScanner: scanner });
+ expect(scanCount).toBe(1);
+
+ await maybeShowMultiDaemonMigrationWarning({ markerFile, fleetScanner: scanner });
+ expect(scanCount).toBe(1); // marker already exists β€” scanner not called again
+ });
+
+ it('tolerates an unreadable/missing daemon-state.json without throwing', async () => {
+ const wt = mkdtempSync(join(dir, 'wt-nostate-'));
+ await expect(
+ maybeShowMultiDaemonMigrationWarning({
+ markerFile,
+ fleetScanner: async () => [{ pid: 1, workspace: wt }, { pid: 2, workspace: null }],
+ })
+ ).resolves.toBeUndefined();
+ expect(existsSync(markerFile)).toBe(true); // still writes the marker
+ });
+
+ it('never throws even if the fleet scanner itself throws', async () => {
+ await expect(
+ maybeShowMultiDaemonMigrationWarning({
+ markerFile,
+ fleetScanner: async () => { throw new Error('ps failed'); },
+ })
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/services/claude-print-envelope.test.ts b/v3/@claude-flow/cli/__tests__/services/claude-print-envelope.test.ts
new file mode 100644
index 0000000000..ef26f2e15a
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/services/claude-print-envelope.test.ts
@@ -0,0 +1,83 @@
+/**
+ * #2661 root-fix β€” structured per-launch token telemetry.
+ *
+ * parseClaudePrintJsonEnvelope() is deliberately lenient: `claude --print
+ * --output-format json`'s schema isn't a versioned public contract, so any
+ * mismatch must degrade to "no usage captured" (null) rather than throw β€”
+ * the caller then falls back to the raw stdout text, preserving today's
+ * behavior for every existing worker.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { parseClaudePrintJsonEnvelope } from '../../src/services/headless-worker-executor.js';
+
+describe('#2661 root-fix β€” parseClaudePrintJsonEnvelope', () => {
+ it('extracts result text, usage, cost, and duration from a well-formed envelope', () => {
+ const raw = JSON.stringify({
+ type: 'result',
+ is_error: false,
+ result: 'the actual analysis text',
+ total_cost_usd: 0.0031,
+ duration_ms: 4521,
+ usage: { input_tokens: 1200, output_tokens: 340 },
+ });
+ const parsed = parseClaudePrintJsonEnvelope(raw);
+ expect(parsed).toEqual({
+ result: 'the actual analysis text',
+ inputTokens: 1200,
+ outputTokens: 340,
+ costUsd: 0.0031,
+ durationMs: 4521,
+ });
+ });
+
+ it('tolerates camelCase field-name variants', () => {
+ const raw = JSON.stringify({
+ result: 'text',
+ totalCostUsd: 0.01,
+ durationMs: 100,
+ usage: { inputTokens: 10, outputTokens: 5 },
+ });
+ const parsed = parseClaudePrintJsonEnvelope(raw);
+ expect(parsed).toEqual({ result: 'text', inputTokens: 10, outputTokens: 5, costUsd: 0.01, durationMs: 100 });
+ });
+
+ it('returns null for plain (non-JSON) text output β€” the common case before this feature existed', () => {
+ expect(parseClaudePrintJsonEnvelope('Just a plain analysis report, no JSON here.')).toBeNull();
+ });
+
+ it('returns null for malformed JSON rather than throwing', () => {
+ expect(parseClaudePrintJsonEnvelope('{not: valid, json')).toBeNull();
+ });
+
+ it('returns null when the parsed JSON has no `result` field (unexpected schema)', () => {
+ expect(parseClaudePrintJsonEnvelope(JSON.stringify({ foo: 'bar' }))).toBeNull();
+ });
+
+ it('returns null for an empty string', () => {
+ expect(parseClaudePrintJsonEnvelope('')).toBeNull();
+ expect(parseClaudePrintJsonEnvelope(' ')).toBeNull();
+ });
+
+ it('still returns the result text even when usage/cost/duration are absent', () => {
+ const parsed = parseClaudePrintJsonEnvelope(JSON.stringify({ result: 'text only' }));
+ expect(parsed).toEqual({
+ result: 'text only',
+ inputTokens: undefined,
+ outputTokens: undefined,
+ costUsd: undefined,
+ durationMs: undefined,
+ });
+ });
+
+ it('ignores non-numeric usage fields instead of propagating garbage', () => {
+ const raw = JSON.stringify({ result: 'text', usage: { input_tokens: 'not-a-number', output_tokens: null } });
+ const parsed = parseClaudePrintJsonEnvelope(raw);
+ expect(parsed?.inputTokens).toBeUndefined();
+ expect(parsed?.outputTokens).toBeUndefined();
+ });
+
+ it('handles a JSON array (not an object) gracefully', () => {
+ expect(parseClaudePrintJsonEnvelope('[1,2,3]')).toBeNull();
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/services/global-ai-budget.test.ts b/v3/@claude-flow/cli/__tests__/services/global-ai-budget.test.ts
index 1223069654..57c4c644c3 100644
--- a/v3/@claude-flow/cli/__tests__/services/global-ai-budget.test.ts
+++ b/v3/@claude-flow/cli/__tests__/services/global-ai-budget.test.ts
@@ -184,6 +184,90 @@ describe('#2661 β€” GlobalAiBudget', () => {
});
});
+ describe('#2661 root-fix β€” recordUsage', () => {
+ it('appends a receipted usage event keyed by permitId', async () => {
+ const budget = makeBudget();
+ const permit = await budget.reserve(REQ);
+ budget.recordUsage(permit.permitId, {
+ workerType: 'audit',
+ model: 'haiku',
+ inputTokens: 1200,
+ outputTokens: 340,
+ durationMs: 4521,
+ costUsd: 0.0031,
+ });
+
+ const receiptsFile = join(dir, 'ai-budget-receipts.jsonl');
+ const lines = readFileSync(receiptsFile, 'utf-8').trim().split('\n').map((l) => JSON.parse(l));
+ const usage = lines.find((r) => r.event === 'usage');
+ expect(usage).toBeTruthy();
+ expect(usage.permitId).toBe(permit.permitId);
+ expect(usage.inputTokens).toBe(1200);
+ expect(usage.outputTokens).toBe(340);
+ expect(usage.costUsd).toBe(0.0031);
+ });
+
+ it('is a silent no-op for a bypass permit (RUFLO_AI_BUDGET_DISABLE=1)', () => {
+ const budget = makeBudget();
+ expect(() => budget.recordUsage('bypass_123_456', { workerType: 'audit', model: 'haiku' })).not.toThrow();
+ const receiptsFile = join(dir, 'ai-budget-receipts.jsonl');
+ expect(existsSync(receiptsFile)).toBe(false);
+ });
+
+ it('is a silent no-op when permitId is undefined (denied launch)', () => {
+ const budget = makeBudget();
+ expect(() => budget.recordUsage(undefined, { workerType: 'audit', model: 'haiku' })).not.toThrow();
+ });
+ });
+
+ describe('#2661 root-fix β€” manual pause / resume', () => {
+ it('pause() blocks new reservations with a manual-pause reason', async () => {
+ const budget = makeBudget();
+ await budget.pause('taking a break');
+ const permit = await budget.reserve(REQ);
+ expect(permit.allowed).toBe(false);
+ expect(permit.reason).toMatch(/circuit-open/);
+
+ const usage = budget.getUsage();
+ expect(usage.pauseReason).toBe('taking a break');
+ });
+
+ it('resume() clears a manual pause and reservations succeed again', async () => {
+ const budget = makeBudget();
+ await budget.pause();
+ await budget.resume();
+ const permit = await budget.reserve(REQ);
+ expect(permit.allowed).toBe(true);
+ });
+
+ it('resume() also clears an automatic quota-triggered pause', async () => {
+ const budget = makeBudget();
+ await budget.recordQuotaError('429 rate limited');
+ expect((await budget.reserve(REQ)).allowed).toBe(false);
+
+ await budget.resume();
+ expect((await budget.reserve(REQ)).allowed).toBe(true);
+ });
+
+ it('pause()/resume() are receipted', async () => {
+ const budget = makeBudget();
+ await budget.pause('manual test');
+ await budget.resume();
+
+ const receiptsFile = join(dir, 'ai-budget-receipts.jsonl');
+ const lines = readFileSync(receiptsFile, 'utf-8').trim().split('\n').map((l) => JSON.parse(l));
+ expect(lines.some((r) => r.event === 'manual-pause')).toBe(true);
+ expect(lines.some((r) => r.event === 'manual-resume')).toBe(true);
+ });
+
+ it('resume() on an already-unpaused budget does not emit a spurious receipt', async () => {
+ const budget = makeBudget();
+ await budget.resume();
+ const receiptsFile = join(dir, 'ai-budget-receipts.jsonl');
+ expect(existsSync(receiptsFile)).toBe(false);
+ });
+ });
+
describe('isQuotaErrorText', () => {
it('matches quota / rate-limit failure signatures', () => {
expect(isQuotaErrorText('HTTP 429 Too Many Requests')).toBe(true);
diff --git a/v3/@claude-flow/cli/__tests__/services/repo-supervisor.test.ts b/v3/@claude-flow/cli/__tests__/services/repo-supervisor.test.ts
new file mode 100644
index 0000000000..825d010d95
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/services/repo-supervisor.test.ts
@@ -0,0 +1,147 @@
+/**
+ * #2661 root-fix β€” one elected repository-level supervisor.
+ *
+ * Exactly one daemon per repositoryId should own the recurring AI-worker
+ * schedule at a time. Election must never let two live daemons both believe
+ * they are supervisor, must take over promptly when the current supervisor
+ * dies, and must never downgrade a healthy supervisor just because another
+ * process asked.
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, symlinkSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { RepoSupervisorRegistry, SUPERVISOR_STALE_MS } from '../../src/services/repo-supervisor.js';
+
+describe('#2661 root-fix β€” RepoSupervisorRegistry', () => {
+ let dir: string;
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'repo-supervisor-test-'));
+ });
+
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+ vi.useRealTimers();
+ });
+
+ const makeRegistry = () => new RepoSupervisorRegistry({ baseDir: dir });
+
+ it('the first daemon to elect for a repository becomes supervisor', async () => {
+ const registry = makeRegistry();
+ const result = await registry.electOrRenew('repo-1', '/tmp/wt-1');
+ expect(result.isSupervisor).toBe(true);
+ expect(result.record?.pid).toBe(process.pid);
+ expect(registry.isSupervisor('repo-1', '/tmp/wt-1')).toBe(true);
+ });
+
+ it('a second (different) worktree does NOT become supervisor while the first is healthy', async () => {
+ const registry = makeRegistry();
+ await registry.electOrRenew('repo-1', '/tmp/wt-1');
+
+ // Same test process (same real PID) attempting election under a
+ // DIFFERENT worktreeRoot β€” isSupervisor() distinguishes by worktreeRoot,
+ // not just PID, so this exercises the "never overwrite a healthy
+ // supervisor" branch even though the PID matches.
+ const second = await registry.electOrRenew('repo-1', '/tmp/wt-2');
+ expect(second.isSupervisor).toBe(false);
+ expect(second.record?.worktreeRoot).toBe('/tmp/wt-1'); // unchanged
+ expect(registry.isSupervisor('repo-1', '/tmp/wt-1')).toBe(true); // still supervisor
+ expect(registry.isSupervisor('repo-1', '/tmp/wt-2')).toBe(false);
+ });
+
+ it('renewing as the current supervisor keeps supervisor status (never a downgrade)', async () => {
+ const registry = makeRegistry();
+ const first = await registry.electOrRenew('repo-1', '/tmp/wt-1');
+ expect(first.isSupervisor).toBe(true);
+
+ const renewed = await registry.electOrRenew('repo-1', '/tmp/wt-1');
+ expect(renewed.isSupervisor).toBe(true);
+ expect(renewed.record!.electedAt).toBe(first.record!.electedAt); // election time unchanged, only heartbeat renews
+ });
+
+ it('leases for different repositories elect independently', async () => {
+ const registry = makeRegistry();
+ const a = await registry.electOrRenew('repo-1', '/tmp/wt-1');
+ const b = await registry.electOrRenew('repo-2', '/tmp/wt-2');
+ expect(a.isSupervisor).toBe(true);
+ expect(b.isSupervisor).toBe(true);
+ });
+
+ it('release() clears supervisor status so another worktree can take over immediately', async () => {
+ const registry = makeRegistry();
+ await registry.electOrRenew('repo-1', '/tmp/wt-1');
+ expect(registry.isSupervisor('repo-1', '/tmp/wt-1')).toBe(true);
+
+ await registry.release('repo-1', '/tmp/wt-1');
+ expect(registry.isSupervisor('repo-1', '/tmp/wt-1')).toBe(false);
+ expect(registry.getRecord('repo-1')).toBeNull();
+ });
+
+ it('release() only clears a record this exact worktree owns, never someone else\'s', async () => {
+ const registry = makeRegistry();
+ await registry.electOrRenew('repo-1', '/tmp/wt-1');
+ // A different (non-owning) worktree attempting release must be a no-op.
+ await registry.release('repo-1', '/tmp/wt-2');
+ expect(registry.isSupervisor('repo-1', '/tmp/wt-1')).toBe(true);
+ });
+
+ it('a supervisor record with a dead PID is treated as stale β€” takeover is allowed', async () => {
+ const registry = makeRegistry();
+ const supDir = join(dir, 'supervisors');
+ mkdirSync(supDir, { recursive: true });
+ writeFileSync(
+ join(supDir, 'repo-1.json'),
+ JSON.stringify({ worktreeRoot: '/tmp/wt-dead', pid: 999999, electedAt: Date.now(), lastHeartbeat: Date.now() }),
+ );
+ expect(registry.isSupervisor('repo-1', '/tmp/wt-dead')).toBe(false); // dead pid never reads as supervisor
+
+ const result = await registry.electOrRenew('repo-1', '/tmp/wt-live');
+ expect(result.isSupervisor).toBe(true);
+ expect(result.record?.worktreeRoot).toBe('/tmp/wt-live');
+ });
+
+ it('a supervisor record whose heartbeat is older than SUPERVISOR_STALE_MS allows takeover, even with a live PID', async () => {
+ const registry = makeRegistry();
+ const supDir = join(dir, 'supervisors');
+ mkdirSync(supDir, { recursive: true });
+ // Use OUR OWN pid so isProcessAlive() would say "alive" β€” staleness must
+ // still win on the heartbeat age alone.
+ writeFileSync(
+ join(supDir, 'repo-1.json'),
+ JSON.stringify({
+ worktreeRoot: '/tmp/wt-old',
+ pid: process.pid,
+ electedAt: Date.now() - SUPERVISOR_STALE_MS - 1000,
+ lastHeartbeat: Date.now() - SUPERVISOR_STALE_MS - 1000,
+ }),
+ );
+ const result = await registry.electOrRenew('repo-1', '/tmp/wt-new');
+ expect(result.isSupervisor).toBe(true);
+ expect(result.record?.worktreeRoot).toBe('/tmp/wt-new');
+ });
+
+ it('getRecord() returns null once the record is stale, without mutating anything', async () => {
+ const registry = makeRegistry();
+ const supDir = join(dir, 'supervisors');
+ mkdirSync(supDir, { recursive: true });
+ writeFileSync(
+ join(supDir, 'repo-1.json'),
+ JSON.stringify({ worktreeRoot: '/tmp/wt-old', pid: 999999, electedAt: Date.now(), lastHeartbeat: Date.now() }),
+ );
+ expect(registry.getRecord('repo-1')).toBeNull();
+ });
+
+ it('rejects a symlinked supervisor file (invariant 9) and fails closed (not supervisor)', async () => {
+ const registry = makeRegistry();
+ const supDir = join(dir, 'supervisors');
+ mkdirSync(supDir, { recursive: true });
+ const real = join(dir, 'evil.json');
+ writeFileSync(real, JSON.stringify({ worktreeRoot: '/x', pid: 1, electedAt: 0, lastHeartbeat: 0 }));
+ symlinkSync(real, join(supDir, 'repo-1.json'));
+
+ const result = await registry.electOrRenew('repo-1', '/tmp/wt-1');
+ expect(result.isSupervisor).toBe(false); // fails closed, never overwrites/uses a symlinked path
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/services/workspace-lease.test.ts b/v3/@claude-flow/cli/__tests__/services/workspace-lease.test.ts
new file mode 100644
index 0000000000..1a95023dfe
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/services/workspace-lease.test.ts
@@ -0,0 +1,127 @@
+/**
+ * #2661 root-fix β€” worktree leases.
+ *
+ * A lease is how a worktree's daemon says "I'm alive" to the rest of the
+ * repository. It must expire (15 min, no heartbeat) so a removed worktree
+ * or a crashed daemon becomes ineligible instead of lingering forever.
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { WorkspaceLeaseRegistry, LEASE_TTL_MS } from '../../src/services/workspace-lease.js';
+
+describe('#2661 root-fix β€” WorkspaceLeaseRegistry', () => {
+ let dir: string;
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'workspace-lease-test-'));
+ });
+
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+ vi.useRealTimers();
+ });
+
+ const makeRegistry = () => new WorkspaceLeaseRegistry({ baseDir: dir });
+
+ it('ships the 15-minute TTL from the issue spec', () => {
+ expect(LEASE_TTL_MS).toBe(15 * 60 * 1000);
+ });
+
+ it('a freshly-heartbeated lease is active', async () => {
+ const registry = makeRegistry();
+ await registry.heartbeat('repo-1', '/tmp/wt-1');
+ expect(registry.isLeaseActive('repo-1', '/tmp/wt-1')).toBe(true);
+ expect(registry.listActive('repo-1')).toHaveLength(1);
+ expect(registry.listActive('repo-1')[0].worktreeRoot).toBe('/tmp/wt-1');
+ });
+
+ it('a worktree with no lease is not active', () => {
+ const registry = makeRegistry();
+ expect(registry.isLeaseActive('repo-1', '/tmp/never-registered')).toBe(false);
+ });
+
+ it('multiple worktrees of the same repository all show as active', async () => {
+ const registry = makeRegistry();
+ await registry.heartbeat('repo-1', '/tmp/wt-1');
+ await registry.heartbeat('repo-1', '/tmp/wt-2');
+ await registry.heartbeat('repo-1', '/tmp/wt-3');
+ const active = registry.listActive('repo-1');
+ expect(active).toHaveLength(3);
+ expect(active.map((l) => l.worktreeRoot).sort()).toEqual(['/tmp/wt-1', '/tmp/wt-2', '/tmp/wt-3']);
+ });
+
+ it('leases for different repositories do not leak into each other', async () => {
+ const registry = makeRegistry();
+ await registry.heartbeat('repo-1', '/tmp/wt-1');
+ await registry.heartbeat('repo-2', '/tmp/wt-2');
+ expect(registry.listActive('repo-1')).toHaveLength(1);
+ expect(registry.listActive('repo-2')).toHaveLength(1);
+ expect(registry.isLeaseActive('repo-1', '/tmp/wt-2')).toBe(false);
+ });
+
+ it('release() removes the lease immediately, not just letting it expire', async () => {
+ const registry = makeRegistry();
+ await registry.heartbeat('repo-1', '/tmp/wt-1');
+ expect(registry.isLeaseActive('repo-1', '/tmp/wt-1')).toBe(true);
+ await registry.release('repo-1', '/tmp/wt-1');
+ expect(registry.isLeaseActive('repo-1', '/tmp/wt-1')).toBe(false);
+ });
+
+ it('a lease older than the 15-minute TTL is no longer active', async () => {
+ const registry = makeRegistry();
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
+ await registry.heartbeat('repo-1', '/tmp/wt-1');
+ expect(registry.isLeaseActive('repo-1', '/tmp/wt-1')).toBe(true);
+
+ vi.setSystemTime(new Date('2026-01-01T00:16:00Z')); // 16 minutes later
+ expect(registry.isLeaseActive('repo-1', '/tmp/wt-1')).toBe(false);
+ expect(registry.listActive('repo-1')).toHaveLength(0);
+ });
+
+ it('a heartbeat renews the TTL window', async () => {
+ const registry = makeRegistry();
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
+ await registry.heartbeat('repo-1', '/tmp/wt-1');
+
+ vi.setSystemTime(new Date('2026-01-01T00:14:00Z')); // just under TTL
+ await registry.heartbeat('repo-1', '/tmp/wt-1'); // renew
+
+ vi.setSystemTime(new Date('2026-01-01T00:20:00Z')); // 6 min after renewal, 20 after registration
+ expect(registry.isLeaseActive('repo-1', '/tmp/wt-1')).toBe(true);
+ });
+
+ it('a lease whose owning PID is dead is treated as inactive even within the TTL window', async () => {
+ const registry = makeRegistry();
+ // Write a lease record directly with a PID that (almost certainly) does
+ // not exist, bypassing heartbeat()'s use of the real process.pid.
+ const leasesDir = join(dir, 'leases');
+ const crypto = await import('crypto');
+ const key = crypto.createHash('sha256').update('/tmp/wt-dead').digest('hex').slice(0, 16);
+ const { mkdirSync } = await import('fs');
+ mkdirSync(leasesDir, { recursive: true });
+ writeFileSync(
+ join(leasesDir, 'repo-1.json'),
+ JSON.stringify({ version: 1, leases: { [key]: { worktreeRoot: '/tmp/wt-dead', pid: 999999, registeredAt: Date.now(), lastHeartbeat: Date.now() } } }),
+ );
+ expect(registry.isLeaseActive('repo-1', '/tmp/wt-dead')).toBe(false);
+ });
+
+ it('rejects a symlinked lease file (invariant 9)', async () => {
+ const registry = makeRegistry();
+ const { mkdirSync } = await import('fs');
+ const leasesDir = join(dir, 'leases');
+ mkdirSync(leasesDir, { recursive: true });
+ const real = join(dir, 'evil.json');
+ writeFileSync(real, JSON.stringify({ version: 1, leases: {} }));
+ symlinkSync(real, join(leasesDir, 'repo-1.json'));
+
+ // heartbeat() is best-effort and must not throw even though the write
+ // path refuses the symlinked target.
+ await expect(registry.heartbeat('repo-1', '/tmp/wt-1')).resolves.toBeUndefined();
+ });
+});
diff --git a/v3/@claude-flow/cli/src/commands/daemon.ts b/v3/@claude-flow/cli/src/commands/daemon.ts
index 95ac446478..1b579b4e7b 100644
--- a/v3/@claude-flow/cli/src/commands/daemon.ts
+++ b/v3/@claude-flow/cli/src/commands/daemon.ts
@@ -9,6 +9,7 @@ import { WorkerDaemon, getDaemon, startDaemon, stopDaemon, type WorkerType, type
import { spawn, execFile, fork } from 'child_process';
import { fileURLToPath } from 'url';
import { dirname, join, resolve, isAbsolute } from 'path';
+import { homedir } from 'os';
import * as fs from 'fs';
// Start daemon subcommand
@@ -599,6 +600,12 @@ async function startBackgroundDaemon(projectRoot: string, quiet: boolean, forwar
output.printInfo('Stop all: ruflo daemon stop --all');
}
} catch { /* best-effort visibility β€” never fail the start */ }
+
+ // #2661 root-fix β€” one-time migration warning for a pre-existing
+ // multi-daemon fleet that already had AI workers enabled before this
+ // fix landed. Separate from the always-shown notice above: this one
+ // fires at most once ever, and only for the genuinely risky shape.
+ await maybeShowMultiDaemonMigrationWarning();
}
return { success: true };
@@ -966,6 +973,70 @@ async function scanRunningDaemons(): Promise<Array<{ pid: number; workspace: str
}
}
+function defaultMultiDaemonWarningMarker(): string {
+ return join(homedir(), '.claude-flow', 'multi-daemon-warning-shown.json');
+}
+
+/**
+ * #2661 root-fix β€” one-time upgrade migration warning. A user who had
+ * `aiWorkersEnabled: true` configured BEFORE this fix landed (old config
+ * file or RUFLO_DAEMON_AI_WORKERS=1) and already has multiple worktree
+ * daemons running is exactly the P0 scenario the issue describes β€” surface
+ * it plainly, ONCE ever (not on every `daemon start`, which would just be
+ * noise once the user has seen and acted on it). The supervisor/lease
+ * mechanism (task #9) already makes only one of those daemons actually
+ * schedule AI workers going forward; this warning's job is purely to make
+ * a pre-existing fleet VISIBLE the first time this code runs, not to take
+ * any destructive action β€” nothing here stops or kills another daemon.
+ *
+ * `opts` exists for tests ONLY, mirroring the injectable-dependency pattern
+ * used elsewhere in this codebase (e.g. helper-refresh.ts's
+ * sourceDirOverride) β€” real callers always use the defaults.
+ */
+export async function maybeShowMultiDaemonMigrationWarning(opts?: {
+ markerFile?: string;
+ fleetScanner?: () => Promise<Array<{ pid: number; workspace: string | null }>>;
+}): Promise<void> {
+ const markerFile = opts?.markerFile ?? defaultMultiDaemonWarningMarker();
+ try {
+ if (fs.existsSync(markerFile)) return;
+
+ const fleet = await (opts?.fleetScanner ?? scanRunningDaemons)();
+ if (fleet.length <= 1) return;
+
+ let anyAiEnabled = false;
+ for (const d of fleet) {
+ if (!d.workspace) continue;
+ try {
+ const statePath = join(d.workspace, '.claude-flow', 'daemon-state.json');
+ if (!fs.existsSync(statePath)) continue;
+ const st = JSON.parse(fs.readFileSync(statePath, 'utf-8'));
+ if (st?.config?.aiWorkersEnabled === true) {
+ anyAiEnabled = true;
+ break;
+ }
+ } catch { /* unreadable state β€” skip this daemon */ }
+ }
+
+ // Only the genuinely risky shape (pre-existing fleet + AI workers
+ // enabled somewhere in it) warrants the migration warning. A harmless
+ // multi-daemon fleet with AI workers off everywhere already gets the
+ // lighter, always-shown fleet-size notice at daemon start.
+ if (anyAiEnabled) {
+ output.writeln();
+ output.printWarning(`Ruflo found ${fleet.length} worktree daemons. Scheduled AI workers are now supervisor-gated.`);
+ output.printInfo('Inspect: ruflo daemon status --all');
+ output.printInfo('Stop all: ruflo daemon stop --all');
+ output.printInfo('Pause autonomous launches: ruflo daemon budget pause');
+ output.writeln();
+ }
+
+ const dir = dirname(markerFile);
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
+ fs.writeFileSync(markerFile, JSON.stringify({ shownAt: new Date().toISOString(), fleetSize: fleet.length, anyAiEnabled }), { mode: 0o600 });
+ } catch { /* best-effort visibility β€” never fail the command */ }
+}
+
/**
* #2356: render the global `daemon status --all` view. For each running daemon
* it reads that workspace's daemon-state.json to show age + configured TTL,
@@ -1043,6 +1114,40 @@ async function renderAllDaemonsStatus(): Promise<CommandResult> {
output.printInfo('Stop all daemons across workspaces with: ruflo daemon stop --all');
}
+ // #2661 root-fix β€” repository supervisor state, one row per distinct
+ // repository among the scanned daemons' workspaces. Resolving identity
+ // per workspace is cheap (a couple of `git rev-parse` calls, cached).
+ try {
+ const { resolveGitWorkspaceIdentity } = await import('../services/git-workspace-identity.js');
+ const { getRepoSupervisorRegistry } = await import('../services/repo-supervisor.js');
+ const { getWorkspaceLeaseRegistry } = await import('../services/workspace-lease.js');
+ const seenRepos = new Map<string, string>(); // repositoryId -> a representative workspace path
+ for (const d of daemons) {
+ if (!d.workspace) continue;
+ const identity = resolveGitWorkspaceIdentity(d.workspace);
+ if (identity.isGit && !seenRepos.has(identity.repositoryId)) {
+ seenRepos.set(identity.repositoryId, d.workspace);
+ }
+ }
+ if (seenRepos.size > 0) {
+ const supervisorReg = getRepoSupervisorRegistry();
+ const leaseReg = getWorkspaceLeaseRegistry();
+ const lines: string[] = [];
+ for (const [repositoryId, sampleWorkspace] of seenRepos) {
+ const record = supervisorReg.getRecord(repositoryId);
+ const activeLeases = leaseReg.listActive(repositoryId).length;
+ const label = repositoryId.slice(0, 12);
+ lines.push(
+ record
+ ? ` ${label}… supervisor: ${record.worktreeRoot} (pid ${record.pid}) | active leases: ${activeLeases}`
+ : ` ${label}… supervisor: ${output.dim('none elected')} | active leases: ${activeLeases}`
+ );
+ }
+ output.writeln();
+ output.printBox(lines.join('\n'), 'Repository Supervisors (#2661 root-fix)');
+ }
+ } catch { /* supervisor registry unavailable β€” skip the panel */ }
+
// #2661: user-global AI launch usage β€” the shared budget every daemon
// draws from, independent of worktree count.
try {
@@ -1556,6 +1661,83 @@ const uninstallSupervisorCommand: Command = {
},
};
+// #2661 root-fix β€” `daemon budget show|pause|resume`. The budget state was
+// previously visible only inline in `daemon status --all`; these give it an
+// independently scriptable surface (e.g. `ruflo daemon budget pause` before
+// a long interactive session, `... resume` after).
+const budgetShowCommand: Command = {
+ name: 'show',
+ description: 'Show the user-global AI launch budget (launches, active children, circuit-breaker state)',
+ options: [],
+ examples: [{ command: 'claude-flow daemon budget show', description: 'Show current budget usage and limits' }],
+ action: async (): Promise<CommandResult> => {
+ const { getGlobalAiBudget } = await import('../services/global-ai-budget.js');
+ const budget = getGlobalAiBudget();
+ const usage = budget.getUsage();
+ const limits = budget.getLimits();
+ output.writeln();
+ const byWs = usage.byWorkspace.slice(0, 10).map((w) => ` ${w.launches}Γ— ${w.workspace}`);
+ output.printBox(
+ [
+ `Launches (last hour): ${usage.lastHour}/${limits.maxLaunchesPerHour}`,
+ `Launches (last 24h): ${usage.lastDay}/${limits.maxLaunchesPerDay}`,
+ `Active Claude children: ${usage.active}/${limits.maxConcurrentGlobal}`,
+ usage.pausedUntil
+ ? output.warning(`PAUSED until ${new Date(usage.pausedUntil).toISOString()} (${usage.pauseReason ?? 'quota error'})`)
+ : `Circuit breaker: ${output.dim('closed (normal)')}`,
+ ...(byWs.length > 0 ? ['Launches by workspace (24h):', ...byWs] : []),
+ ].join('\n'),
+ 'Global AI Budget'
+ );
+ return { success: true, data: { usage, limits } };
+ },
+};
+
+const budgetPauseCommand: Command = {
+ name: 'pause',
+ description: 'Pause ALL autonomous Claude launches across every daemon until resumed',
+ options: [
+ { name: 'reason', short: 'r', type: 'string', description: 'Optional reason recorded in the pause receipt' },
+ ],
+ examples: [{ command: 'claude-flow daemon budget pause --reason "conserving quota for a demo"', description: 'Pause autonomous launches' }],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const { getGlobalAiBudget } = await import('../services/global-ai-budget.js');
+ await getGlobalAiBudget().pause(ctx.flags.reason as string | undefined);
+ output.printSuccess('Autonomous AI worker launches paused across all daemons. Resume with: ruflo daemon budget resume');
+ return { success: true };
+ },
+};
+
+const budgetResumeCommand: Command = {
+ name: 'resume',
+ description: 'Resume autonomous Claude launches (clears a manual pause or a quota-triggered circuit-breaker pause)',
+ options: [],
+ examples: [{ command: 'claude-flow daemon budget resume', description: 'Resume autonomous launches' }],
+ action: async (): Promise<CommandResult> => {
+ const { getGlobalAiBudget } = await import('../services/global-ai-budget.js');
+ await getGlobalAiBudget().resume();
+ output.printSuccess('Autonomous AI worker launches resumed.');
+ return { success: true };
+ },
+};
+
+const budgetCommand: Command = {
+ name: 'budget',
+ description: 'Inspect and control the user-global AI launch budget (#2661)',
+ subcommands: [budgetShowCommand, budgetPauseCommand, budgetResumeCommand],
+ options: [],
+ examples: [
+ { command: 'claude-flow daemon budget show', description: 'Show current usage/limits' },
+ { command: 'claude-flow daemon budget pause', description: 'Pause all autonomous launches' },
+ { command: 'claude-flow daemon budget resume', description: 'Resume autonomous launches' },
+ ],
+ // Bare `daemon budget` (no subcommand) shows usage β€” same as `show`.
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const result = await budgetShowCommand.action!(ctx);
+ return result ?? { success: true };
+ },
+};
+
// Main daemon command
export const daemonCommand: Command = {
name: 'daemon',
@@ -1566,6 +1748,7 @@ export const daemonCommand: Command = {
statusCommand,
triggerCommand,
enableCommand,
+ budgetCommand,
installSupervisorCommand,
uninstallSupervisorCommand,
],
diff --git a/v3/@claude-flow/cli/src/init/statusline-generator.ts b/v3/@claude-flow/cli/src/init/statusline-generator.ts
index f7105f3c7e..2c32dd02a7 100644
--- a/v3/@claude-flow/cli/src/init/statusline-generator.ts
+++ b/v3/@claude-flow/cli/src/init/statusline-generator.ts
@@ -11,7 +11,48 @@
*/
import type { InitOptions } from './types.js';
-import { getInstalledCliVersion } from './helper-refresh.js';
+import * as fs from 'fs';
+import * as path from 'path';
+import { fileURLToPath } from 'url';
+import { createRequire } from 'module';
+
+const __dirname_sg = path.dirname(fileURLToPath(import.meta.url));
+
+/**
+ * Resolves the running CLI's own version β€” same createRequire/walk-up
+ * approach as helper-refresh.ts's getInstalledCliVersion(), duplicated
+ * here rather than imported. helper-refresh.ts pulls in the `semver`
+ * package at module scope (for autoRefreshHelpersIfStale()'s version
+ * comparison, unrelated to this) β€” ES module imports load a module's
+ * ENTIRE top-level regardless of which export is used, so importing just
+ * getInstalledCliVersion from there still requires `semver` to be resolvable.
+ * Confirmed live: the CI smoke job that loads this generator via a minimal
+ * "smoke deps" install (no full `npm install`) failed with
+ * ERR_MODULE_NOT_FOUND('semver') the moment this file gained that import,
+ * even though this function itself never touches semver. Keeping this
+ * generator's own dependency footprint to bare Node builtins avoids
+ * dragging every future helper-refresh.ts dependency into every context
+ * that merely wants to render a statusline script.
+ */
+function getInstalledCliVersionLocal(): string {
+ try {
+ const esmRequire = createRequire(import.meta.url);
+ const pkg = JSON.parse(fs.readFileSync(esmRequire.resolve('@claude-flow/cli/package.json'), 'utf-8'));
+ return String(pkg.version || '0.0.0');
+ } catch {
+ let dir = __dirname_sg;
+ for (let i = 0; i < 6; i++) {
+ try {
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8'));
+ if (pkg && pkg.name === '@claude-flow/cli') return String(pkg.version || '0.0.0');
+ } catch { /* no package.json here, or unreadable β€” keep climbing */ }
+ const parent = path.dirname(dir);
+ if (parent === dir) break;
+ dir = parent;
+ }
+ return '0.0.0';
+ }
+}
/**
* Generate optimized statusline script
@@ -36,7 +77,7 @@ export function generateStatuslineScript(options: InitOptions): string {
// previous hardcoded "3.6" placeholder. getPkgVersion()'s own runtime
// candidate scan still wins over this baked-in value when it finds
// something newer (e.g. a later `npm update` in the same project).
- const bakedVersion = getInstalledCliVersion();
+ const bakedVersion = getInstalledCliVersionLocal();
return `#!/usr/bin/env node
/**
diff --git a/v3/@claude-flow/cli/src/services/global-ai-budget.ts b/v3/@claude-flow/cli/src/services/global-ai-budget.ts
index 2399f28676..4227e1b34e 100644
--- a/v3/@claude-flow/cli/src/services/global-ai-budget.ts
+++ b/v3/@claude-flow/cli/src/services/global-ai-budget.ts
@@ -268,6 +268,69 @@ export class GlobalAiBudget {
}
}
+ /**
+ * #2661 root-fix β€” manual pause, via `ruflo daemon budget pause`. Distinct
+ * from the automatic quota-error circuit breaker only in duration (open-
+ * ended, until explicitly resumed, instead of a fixed cooldown) and
+ * reason text β€” the enforcement path in reserve() is identical, so a
+ * manual pause is just as hard a stop as a quota-triggered one.
+ */
+ async pause(reason?: string): Promise<void> {
+ let unlock: (() => void) | null = null;
+ try {
+ unlock = await this.acquireLock();
+ const now = Date.now();
+ const ledger = this.readLedger(now);
+ // Sentinel far-future timestamp rather than a real duration β€” resume()
+ // is the only thing that clears it. year ~2255, safely beyond any
+ // realistic process lifetime, and still a valid finite JS timestamp.
+ ledger.pausedUntil = 9_000_000_000_000;
+ ledger.pauseReason = (reason ?? 'manual pause (ruflo daemon budget pause)').slice(0, 200);
+ this.writeLedger(ledger);
+ this.appendReceipt({ event: 'manual-pause', at: now, reason: ledger.pauseReason });
+ } finally {
+ unlock?.();
+ }
+ }
+
+ /** #2661 root-fix β€” `ruflo daemon budget resume`. Clears ANY pause (manual or quota-triggered). */
+ async resume(): Promise<void> {
+ let unlock: (() => void) | null = null;
+ try {
+ unlock = await this.acquireLock();
+ const now = Date.now();
+ const ledger = this.readLedger(now);
+ const wasPaused = ledger.pausedUntil !== undefined && ledger.pausedUntil > now;
+ ledger.pausedUntil = undefined;
+ ledger.pauseReason = undefined;
+ this.writeLedger(ledger);
+ if (wasPaused) {
+ this.appendReceipt({ event: 'manual-resume', at: now });
+ }
+ } finally {
+ unlock?.();
+ }
+ }
+
+ /**
+ * #2661 root-fix β€” structured per-launch token telemetry. Best-effort,
+ * receipt-only: usage is recorded as a distinct receipt keyed by permitId
+ * rather than mutated into the launch ledger, so a usage-recording failure
+ * can never corrupt the budget-enforcement ledger. Only operational
+ * metadata β€” never prompts or source content.
+ */
+ recordUsage(permitId: string | undefined, usage: {
+ workerType: string;
+ model: string;
+ inputTokens?: number;
+ outputTokens?: number;
+ durationMs?: number;
+ costUsd?: number;
+ }): void {
+ if (!permitId || permitId.startsWith('bypass_')) return;
+ this.appendReceipt({ event: 'usage', at: Date.now(), permitId, ...usage });
+ }
+
/** Snapshot for `daemon status` / diagnostics. */
getUsage(): {
lastHour: number;
diff --git a/v3/@claude-flow/cli/src/services/headless-worker-executor.ts b/v3/@claude-flow/cli/src/services/headless-worker-executor.ts
index 8e406bf2a6..54c53603ba 100644
--- a/v3/@claude-flow/cli/src/services/headless-worker-executor.ts
+++ b/v3/@claude-flow/cli/src/services/headless-worker-executor.ts
@@ -172,6 +172,11 @@ export interface HeadlessExecutionResult {
/** Estimated tokens used (if available) */
tokensUsed?: number;
+ /** #2661 root-fix β€” structured usage, when `claude --print --output-format json` exposed it. */
+ inputTokens?: number;
+ outputTokens?: number;
+ costUsd?: number;
+
/** Model used for execution */
model: string;
@@ -579,6 +584,50 @@ export function getModelId(model: ModelType): string {
return MODEL_IDS[model];
}
+export interface ClaudePrintEnvelope {
+ result: string;
+ inputTokens?: number;
+ outputTokens?: number;
+ costUsd?: number;
+ durationMs?: number;
+}
+
+/**
+ * #2661 root-fix β€” best-effort parse of `claude --print --output-format
+ * json`'s response envelope. Deliberately lenient: probes a couple of
+ * plausible field-name shapes (the CLI's JSON schema is not a versioned
+ * public contract) and returns null on anything unexpected rather than
+ * throwing, so a schema mismatch degrades to "no usage captured" β€” the
+ * caller then falls back to the raw stdout text, exactly today's behavior.
+ * Exported for direct unit testing without spawning a real process.
+ */
+export function parseClaudePrintJsonEnvelope(raw: string): ClaudePrintEnvelope | null {
+ const trimmed = raw.trim();
+ if (!trimmed || trimmed[0] !== '{') return null;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(trimmed);
+ } catch {
+ return null;
+ }
+ if (!parsed || typeof parsed !== 'object') return null;
+ const obj = parsed as Record<string, unknown>;
+
+ const result = typeof obj.result === 'string' ? obj.result : undefined;
+ if (result === undefined) return null; // not the envelope shape we expect
+
+ const usage = (obj.usage && typeof obj.usage === 'object') ? obj.usage as Record<string, unknown> : undefined;
+ const numOrUndef = (v: unknown): number | undefined => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);
+
+ return {
+ result,
+ inputTokens: numOrUndef(usage?.input_tokens ?? usage?.inputTokens),
+ outputTokens: numOrUndef(usage?.output_tokens ?? usage?.outputTokens),
+ costUsd: numOrUndef(obj.total_cost_usd ?? obj.cost_usd ?? obj.totalCostUsd),
+ durationMs: numOrUndef(obj.duration_ms ?? obj.durationMs),
+ };
+}
+
/**
* Get worker configuration by type
*/
@@ -1008,6 +1057,9 @@ export class HeadlessWorkerExecutor extends EventEmitter {
parsedOutput,
durationMs: Date.now() - startTime,
tokensUsed: result.tokensUsed,
+ inputTokens: result.inputTokens,
+ outputTokens: result.outputTokens,
+ costUsd: result.costUsd,
model: headless.model || 'sonnet',
sandboxMode: headless.sandbox,
workerType,
@@ -1019,6 +1071,18 @@ export class HeadlessWorkerExecutor extends EventEmitter {
// Log result
this.logExecution(executionId, 'result', JSON.stringify(executionResult, null, 2));
+ // #2661 root-fix β€” structured per-launch telemetry, receipted
+ // regardless of success/failure (a failed launch still spent
+ // whatever tokens it spent before erroring).
+ budget.recordUsage(permit.permitId, {
+ workerType,
+ model,
+ inputTokens: result.inputTokens,
+ outputTokens: result.outputTokens,
+ durationMs: result.apiDurationMs ?? executionResult.durationMs,
+ costUsd: result.costUsd,
+ });
+
// #2661 invariant 5 β€” record the success so sibling worktrees at the
// same HEAD skip this job for the rest of the freshness window.
if (result.success) {
@@ -1272,7 +1336,16 @@ Analyze the above codebase context and provide your response following the forma
executionId: string;
workerType: HeadlessWorkerType;
}
- ): Promise<{ success: boolean; output: string; tokensUsed?: number; error?: string }> {
+ ): Promise<{
+ success: boolean;
+ output: string;
+ tokensUsed?: number;
+ inputTokens?: number;
+ outputTokens?: number;
+ costUsd?: number;
+ apiDurationMs?: number;
+ error?: string;
+ }> {
return new Promise((resolve) => {
const env: Record<string, string> = {
...(process.env as Record<string, string>),
@@ -1313,7 +1386,15 @@ Analyze the above codebase context and provide your response following the forma
// diagnosed as a 5-second redispatch + subprocess-table growth.
// `detached: true` puts the child in its own process group so we
// can signal the whole tree with `process.kill(-pid, sig)`.
- const child = spawn('claude', ['--print'], {
+ // #2661 root-fix β€” structured usage telemetry. `--output-format json`
+ // wraps the response in an envelope carrying `result` (the actual
+ // text β€” what `output` must still contain, unchanged for every
+ // existing downstream parser) alongside `usage`/cost/duration
+ // metadata. Parsing is lenient (parseClaudePrintJsonEnvelope below)
+ // and ALWAYS falls back to the raw text on any mismatch β€” a schema
+ // surprise from an older/newer `claude` CLI must degrade to exactly
+ // today's behavior (no usage captured), never break analysis output.
+ const child = spawn('claude', ['--print', '--output-format', 'json'], {
cwd: this.projectRoot,
env,
stdio: ['pipe', 'pipe', 'pipe'],
@@ -1393,9 +1474,17 @@ Analyze the above codebase context and provide your response following the forma
resolved = true;
cleanup();
+ const envelope = parseClaudePrintJsonEnvelope(stdout);
resolve({
success: code === 0,
- output: stdout || stderr,
+ output: envelope?.result ?? stdout ?? stderr,
+ inputTokens: envelope?.inputTokens,
+ outputTokens: envelope?.outputTokens,
+ tokensUsed: envelope
+ ? (envelope.inputTokens ?? 0) + (envelope.outputTokens ?? 0)
+ : undefined,
+ costUsd: envelope?.costUsd,
+ apiDurationMs: envelope?.durationMs,
error: code !== 0 ? stderr || `Process exited with code ${code}` : undefined,
});
});
diff --git a/v3/@claude-flow/cli/src/services/repo-supervisor.ts b/v3/@claude-flow/cli/src/services/repo-supervisor.ts
new file mode 100644
index 0000000000..256d135875
--- /dev/null
+++ b/v3/@claude-flow/cli/src/services/repo-supervisor.ts
@@ -0,0 +1,237 @@
+/**
+ * #2661 root-fix β€” one repository-level supervisor.
+ *
+ * Ten worktree daemons of the same repository independently deciding "is it
+ * time to run audit/optimize/testgaps" every tick is the redundant-scheduler
+ * half of the original cardinality bug β€” the budget ledger and job dedup
+ * (global-ai-budget.ts, ai-job-dedup.ts) already bound and dedupe the actual
+ * `claude --print` spend, but every daemon still runs its own timer and its
+ * own "should I launch" decision. This module elects exactly ONE daemon per
+ * repositoryId to own the recurring AI-worker schedule; every other worktree
+ * of that repository stays a lease-only participant (workspace-lease.ts) β€”
+ * it keeps running its cheap, $0 local-only workers (map/consolidate/backup)
+ * on its own schedule, but does not attempt headless (`claude --print`)
+ * execution for its recurring ticks. An explicit `daemon trigger --headless`
+ * in a non-supervisor worktree is still honored (still budget/dedup-gated) β€”
+ * this module only governs the unattended recurring schedule.
+ *
+ * Election is a simple lock-protected takeover, same pattern as
+ * global-ai-budget.ts:
+ * - No record, a dead PID, or a stale heartbeat (>SUPERVISOR_STALE_MS) β†’
+ * the calling daemon takes over.
+ * - A live supervisor with a fresh heartbeat β†’ the calling daemon is not
+ * elected; it does nothing (never overwrites a healthy supervisor).
+ *
+ * The registry lives under the user's home directory so every worktree's
+ * daemon can see it:
+ *
+ * ~/.claude-flow/supervisors/<repositoryId>.json
+ */
+
+import * as fs from 'fs';
+import { join } from 'path';
+import { homedir } from 'os';
+
+// Longer than any plausible daemon heartbeat interval (daemons renew via the
+// existing 60s lifecycle-monitor tick) so a merely-slow tick never triggers
+// a false takeover, but short enough that a crashed supervisor's worktree
+// yields the schedule within a few minutes rather than indefinitely.
+export const SUPERVISOR_STALE_MS = 3 * 60 * 1000;
+const LOCK_STALE_MS = 10_000;
+
+export interface SupervisorRecord {
+ worktreeRoot: string;
+ pid: number;
+ electedAt: number;
+ lastHeartbeat: number;
+}
+
+export interface SupervisorElectionResult {
+ isSupervisor: boolean;
+ record: SupervisorRecord | null;
+}
+
+function delay(ms: number): Promise<void> {
+ return new Promise((r) => setTimeout(r, ms));
+}
+
+function isProcessAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** Invariant 9 (#2661): registry files must never be symlinks. */
+function assertNotSymlink(path: string): void {
+ try {
+ const st = fs.lstatSync(path);
+ if (st.isSymbolicLink()) {
+ throw new Error(`Repo-supervisor file is a symlink (refusing): ${path}`);
+ }
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code === 'ENOENT') return;
+ throw e;
+ }
+}
+
+export class RepoSupervisorRegistry {
+ private readonly dir: string;
+
+ constructor(options?: { baseDir?: string }) {
+ this.dir = options?.baseDir
+ ?? process.env.RUFLO_AI_BUDGET_DIR
+ ?? join(homedir(), '.claude-flow');
+ }
+
+ private fileFor(repositoryId: string): string {
+ return join(this.dir, 'supervisors', `${repositoryId}.json`);
+ }
+
+ private ensureDir(): void {
+ const dir = join(this.dir, 'supervisors');
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
+ }
+
+ private async withLock<T>(repositoryId: string, fn: () => T): Promise<T> {
+ this.ensureDir();
+ const lockFile = `${this.fileFor(repositoryId)}.lock`;
+ const deadline = Date.now() + 2000;
+ for (;;) {
+ try {
+ const fd = fs.openSync(lockFile, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);
+ fs.writeSync(fd, String(process.pid));
+ fs.closeSync(fd);
+ try {
+ return fn();
+ } finally {
+ try { fs.unlinkSync(lockFile); } catch { /* already gone */ }
+ }
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e;
+ try {
+ const st = fs.lstatSync(lockFile);
+ if (Date.now() - st.mtimeMs > LOCK_STALE_MS) {
+ fs.unlinkSync(lockFile);
+ continue;
+ }
+ } catch { /* raced β€” retry */ }
+ if (Date.now() > deadline) throw new Error('timed out acquiring repo-supervisor lock');
+ await delay(25);
+ }
+ }
+ }
+
+ private readRecord(repositoryId: string): SupervisorRecord | null {
+ const file = this.fileFor(repositoryId);
+ assertNotSymlink(file);
+ if (!fs.existsSync(file)) return null;
+ try {
+ const raw = JSON.parse(fs.readFileSync(file, 'utf-8'));
+ if (raw && typeof raw.pid === 'number' && typeof raw.lastHeartbeat === 'number') {
+ return raw as SupervisorRecord;
+ }
+ } catch { /* corrupt β€” treat as absent */ }
+ return null;
+ }
+
+ private writeRecord(repositoryId: string, record: SupervisorRecord): void {
+ const file = this.fileFor(repositoryId);
+ assertNotSymlink(file);
+ const tmp = `${file}.tmp.${process.pid}`;
+ fs.writeFileSync(tmp, JSON.stringify(record), { mode: 0o600 });
+ fs.renameSync(tmp, file);
+ }
+
+ private isStale(record: SupervisorRecord, now: number): boolean {
+ return now - record.lastHeartbeat > SUPERVISOR_STALE_MS || !isProcessAlive(record.pid);
+ }
+
+ /**
+ * Attempt election (or renewal, if this process already holds it). Safe
+ * and cheap to call on every daemon tick β€” a no-op write when nothing
+ * needs to change would still cost a lock+read+write, so callers should
+ * still throttle to their own heartbeat cadence rather than calling this
+ * per-worker-tick.
+ */
+ async electOrRenew(repositoryId: string, worktreeRoot: string): Promise<SupervisorElectionResult> {
+ try {
+ return await this.withLock(repositoryId, () => {
+ const now = Date.now();
+ const existing = this.readRecord(repositoryId);
+
+ if (existing && existing.pid === process.pid && existing.worktreeRoot === worktreeRoot) {
+ const renewed: SupervisorRecord = { ...existing, lastHeartbeat: now };
+ this.writeRecord(repositoryId, renewed);
+ return { isSupervisor: true, record: renewed };
+ }
+
+ if (!existing || this.isStale(existing, now)) {
+ const record: SupervisorRecord = { worktreeRoot, pid: process.pid, electedAt: now, lastHeartbeat: now };
+ this.writeRecord(repositoryId, record);
+ return { isSupervisor: true, record };
+ }
+
+ // A live supervisor already owns this repository β€” never overwrite it.
+ return { isSupervisor: false, record: existing };
+ });
+ } catch {
+ // Fail closed on the SCHEDULE side too: if we can't safely coordinate,
+ // assume we are NOT the supervisor rather than risk two daemons both
+ // believing they own the schedule. The budget ledger is the actual
+ // hard invariant either way.
+ return { isSupervisor: false, record: null };
+ }
+ }
+
+ /** Cheap read-only check β€” does NOT renew or elect. */
+ isSupervisor(repositoryId: string, worktreeRoot: string): boolean {
+ try {
+ const existing = this.readRecord(repositoryId);
+ if (!existing) return false;
+ const now = Date.now();
+ if (this.isStale(existing, now)) return false;
+ return existing.pid === process.pid && existing.worktreeRoot === worktreeRoot;
+ } catch {
+ return false;
+ }
+ }
+
+ /** Release supervisor status on graceful shutdown, so the next tick elsewhere can take over promptly. Best-effort. */
+ async release(repositoryId: string, worktreeRoot: string): Promise<void> {
+ try {
+ await this.withLock(repositoryId, () => {
+ const existing = this.readRecord(repositoryId);
+ if (existing && existing.pid === process.pid && existing.worktreeRoot === worktreeRoot) {
+ const file = this.fileFor(repositoryId);
+ try { fs.unlinkSync(file); } catch { /* already gone */ }
+ }
+ });
+ } catch { /* best-effort */ }
+ }
+
+ /** Snapshot for `daemon status --all`. Read-only, never mutates. */
+ getRecord(repositoryId: string): SupervisorRecord | null {
+ try {
+ const existing = this.readRecord(repositoryId);
+ if (!existing || this.isStale(existing, Date.now())) return null;
+ return existing;
+ } catch {
+ return null;
+ }
+ }
+}
+
+let registryInstance: RepoSupervisorRegistry | null = null;
+
+export function getRepoSupervisorRegistry(): RepoSupervisorRegistry {
+ if (!registryInstance) registryInstance = new RepoSupervisorRegistry();
+ return registryInstance;
+}
+
+/** Test hook: reset the singleton (e.g. after changing RUFLO_AI_BUDGET_DIR). */
+export function resetRepoSupervisorRegistryForTests(): void {
+ registryInstance = null;
+}
diff --git a/v3/@claude-flow/cli/src/services/worker-daemon.ts b/v3/@claude-flow/cli/src/services/worker-daemon.ts
index 5966a26c33..390da4a418 100644
--- a/v3/@claude-flow/cli/src/services/worker-daemon.ts
+++ b/v3/@claude-flow/cli/src/services/worker-daemon.ts
@@ -30,6 +30,9 @@ import {
// quick_check-gated, so it's safe to call unconditionally on every tick.
import { runDistillation, defaultMemoryDbPath, type DistillReport } from './memory-distillation.js';
import { backupMemoryDb } from './memory-backup.js';
+import { resolveGitWorkspaceIdentity, type GitWorkspaceIdentity } from './git-workspace-identity.js';
+import { getWorkspaceLeaseRegistry } from './workspace-lease.js';
+import { getRepoSupervisorRegistry, type SupervisorRecord } from './repo-supervisor.js';
// Worker types matching hooks-tools.ts
export type WorkerType =
@@ -88,6 +91,14 @@ interface DaemonStatus {
startedAt?: Date;
workers: Map<WorkerType, WorkerState>;
config: DaemonConfig;
+ // #2661 root-fix β€” repository-supervisor state, null when AI workers are
+ // disabled or the git identity couldn't be resolved (non-git directory).
+ supervisor?: {
+ repositoryId: string;
+ isSupervisor: boolean;
+ record: SupervisorRecord | null;
+ activeLeases: number;
+ } | null;
}
export interface DaemonConfig {
@@ -220,6 +231,12 @@ export class WorkerDaemon extends EventEmitter {
// during state restoration (R1: constructor config takes priority over stale state)
private originalConfig?: Partial<DaemonConfig>;
+ // #2661 root-fix β€” resolved once (git identity doesn't change at runtime)
+ // and reused for lease heartbeats + supervisor election, both gated on
+ // aiWorkersEnabled since they only matter for the recurring AI schedule.
+ private gitIdentity: GitWorkspaceIdentity | null = null;
+ private lastSupervisorRenewalMs = 0;
+
constructor(projectRoot: string, config?: Partial<DaemonConfig>) {
super();
this.projectRoot = projectRoot;
@@ -882,6 +899,15 @@ export class WorkerDaemon extends EventEmitter {
this.writePidFile();
this.emit('started', { pid: process.pid, startedAt: this.startedAt });
+ // #2661 root-fix β€” resolve repository identity and register/attempt
+ // election immediately at start, not just on the first 60s lifecycle
+ // tick, so `daemon status` reflects supervisor state right away. Only
+ // meaningful when AI workers are enabled (see field doc comment).
+ if (this.config.aiWorkersEnabled) {
+ this.gitIdentity = resolveGitWorkspaceIdentity(this.projectRoot);
+ void this.renewLeaseAndSupervisor();
+ }
+
// Schedule all enabled workers
for (const workerConfig of this.config.workers) {
if (workerConfig.enabled) {
@@ -1002,6 +1028,19 @@ export class WorkerDaemon extends EventEmitter {
try { this.headlessExecutor.cancelAll(); } catch { /* best-effort */ }
}
+ // #2661 root-fix β€” release this worktree's lease and, if held,
+ // supervisor status, so a sibling worktree's daemon can take over the
+ // schedule within its next tick instead of waiting out the 3-minute
+ // supervisor staleness window. Best-effort β€” a graceful release is an
+ // optimization; the staleness timeout is what actually bounds a crash.
+ if (this.config.aiWorkersEnabled && this.gitIdentity) {
+ const { repositoryId, worktreeRoot } = this.gitIdentity;
+ try {
+ await getRepoSupervisorRegistry().release(repositoryId, worktreeRoot);
+ await getWorkspaceLeaseRegistry().release(repositoryId, worktreeRoot);
+ } catch { /* best-effort */ }
+ }
+
this.running = false;
this.removePidFile();
this.saveState();
@@ -1032,6 +1071,13 @@ export class WorkerDaemon extends EventEmitter {
const reason = this.lifecycleShutdownReason(Date.now());
if (reason) {
void this.selfShutdown(reason);
+ return;
+ }
+ // #2661 root-fix β€” renew this worktree's lease + supervisor status on
+ // the same cadence. Both windows (15min lease TTL, 3min supervisor
+ // staleness) comfortably outlive a single missed 60s tick.
+ if (this.config.aiWorkersEnabled) {
+ void this.renewLeaseAndSupervisor();
}
}, CHECK_INTERVAL_MS);
if (typeof this.lifecycleTimer.unref === 'function') {
@@ -1110,16 +1156,57 @@ export class WorkerDaemon extends EventEmitter {
process.exit(0);
}
+ /**
+ * #2661 root-fix β€” heartbeat this worktree's lease and attempt/renew
+ * repository-supervisor election. Best-effort: any failure here must
+ * never affect worker scheduling correctness (the budget ledger remains
+ * the hard invariant regardless of supervisor state) β€” a daemon that
+ * can't safely coordinate simply falls back to "not supervisor" and runs
+ * its cheap local-only workers, same as any other lease-only worktree.
+ */
+ private async renewLeaseAndSupervisor(): Promise<void> {
+ if (!this.gitIdentity) return;
+ const { repositoryId, worktreeRoot } = this.gitIdentity;
+ try {
+ await getWorkspaceLeaseRegistry().heartbeat(repositoryId, worktreeRoot);
+ await getRepoSupervisorRegistry().electOrRenew(repositoryId, worktreeRoot);
+ this.lastSupervisorRenewalMs = Date.now();
+ } catch { /* best-effort β€” see docstring */ }
+ }
+
+ /**
+ * Cheap read-only check: does THIS daemon currently hold repository
+ * supervisor status? Used to gate recurring headless (`claude --print`)
+ * execution β€” see repo-supervisor.ts's module doc comment for the full
+ * rationale. Never true when AI workers are disabled or the git identity
+ * couldn't be resolved (e.g. a non-git directory).
+ */
+ private isRepositorySupervisor(): boolean {
+ if (!this.config.aiWorkersEnabled || !this.gitIdentity) return false;
+ return getRepoSupervisorRegistry().isSupervisor(this.gitIdentity.repositoryId, this.gitIdentity.worktreeRoot);
+ }
+
/**
* Get daemon status
*/
getStatus(): DaemonStatus {
+ let supervisor: DaemonStatus['supervisor'] = null;
+ if (this.config.aiWorkersEnabled && this.gitIdentity) {
+ const { repositoryId, worktreeRoot } = this.gitIdentity;
+ supervisor = {
+ repositoryId,
+ isSupervisor: getRepoSupervisorRegistry().isSupervisor(repositoryId, worktreeRoot),
+ record: getRepoSupervisorRegistry().getRecord(repositoryId),
+ activeLeases: getWorkspaceLeaseRegistry().listActive(repositoryId).length,
+ };
+ }
return {
running: this.running,
pid: process.pid,
startedAt: this.startedAt,
workers: new Map(this.workers),
config: this.config,
+ supervisor,
};
}
@@ -1188,7 +1275,7 @@ export class WorkerDaemon extends EventEmitter {
/**
* Execute a worker with timeout protection
*/
- private async executeWorker(workerConfig: WorkerConfig): Promise<WorkerResult> {
+ private async executeWorker(workerConfig: WorkerConfig, opts?: { manualTrigger?: boolean }): Promise<WorkerResult> {
const state = this.workers.get(workerConfig.type)!;
const workerId = `${workerConfig.type}_${Date.now()}`;
const startTime = Date.now();
@@ -1205,7 +1292,7 @@ export class WorkerDaemon extends EventEmitter {
// Execute worker logic with timeout (P1 fix)
// Pass cleanup callback to kill orphan child processes on timeout (#1117)
const output = await this.runWithTimeout(
- () => this.runWorkerLogic(workerConfig),
+ () => this.runWorkerLogic(workerConfig, opts),
this.config.workerTimeoutMs,
`Worker ${workerConfig.type} timed out after ${this.config.workerTimeoutMs / 1000}s`,
() => {
@@ -1316,12 +1403,21 @@ export class WorkerDaemon extends EventEmitter {
/**
* Run the actual worker logic
*/
- private async runWorkerLogic(workerConfig: WorkerConfig): Promise<unknown> {
+ private async runWorkerLogic(workerConfig: WorkerConfig, opts?: { manualTrigger?: boolean }): Promise<unknown> {
// Check if this is a headless worker type and headless execution is available.
// #2661 β€” aiWorkersEnabled is re-checked here (not just at init) as
// defence in depth: no code path may promote a worker to `claude --print`
// without explicit consent.
- if (this.config.aiWorkersEnabled && isHeadlessWorker(workerConfig.type) && this.headlessAvailable && this.headlessExecutor) {
+ //
+ // #2661 root-fix β€” the RECURRING schedule additionally requires this
+ // daemon to be the elected repository supervisor (see repo-supervisor.ts):
+ // ten worktree daemons of one repository must not each independently
+ // decide "is it time to run audit" every tick. An explicit
+ // `daemon trigger --headless` (opts.manualTrigger) is still honored
+ // regardless of supervisor status β€” it's a one-off, user-initiated
+ // action, still budget/dedup-gated the same as any other launch.
+ const supervisorGateOk = opts?.manualTrigger === true || this.isRepositorySupervisor();
+ if (this.config.aiWorkersEnabled && supervisorGateOk && isHeadlessWorker(workerConfig.type) && this.headlessAvailable && this.headlessExecutor) {
try {
this.log('info', `Running ${workerConfig.type} in headless mode (Claude Code AI)`);
const result = await this.headlessExecutor.execute(workerConfig.type as HeadlessWorkerType);
@@ -1877,7 +1973,10 @@ export class WorkerDaemon extends EventEmitter {
// use headless correctly. Scheduled fires already wait long enough
// (timer + offset) that this is a no-op for them.
await this.headlessInitPromise;
- return this.executeWorker(workerConfig);
+ // #2661 root-fix β€” an explicit manual trigger bypasses the repository-
+ // supervisor gate (still budget/dedup-gated) β€” see runWorkerLogic()'s
+ // doc comment.
+ return this.executeWorker(workerConfig, { manualTrigger: true });
}
/**
diff --git a/v3/@claude-flow/cli/src/services/workspace-lease.ts b/v3/@claude-flow/cli/src/services/workspace-lease.ts
new file mode 100644
index 0000000000..3d4c3735f9
--- /dev/null
+++ b/v3/@claude-flow/cli/src/services/workspace-lease.ts
@@ -0,0 +1,207 @@
+/**
+ * #2661 root-fix β€” worktree leases.
+ *
+ * Registers which worktrees of a repository are currently "alive" (have a
+ * running daemon actively heartbeating), independent of whether that
+ * worktree's daemon is the elected repository supervisor (see
+ * repo-supervisor.ts). A lease expires after 15 minutes without a heartbeat
+ * β€” a removed worktree, or a daemon that crashed without a graceful
+ * shutdown, becomes ineligible within one expiry window instead of lingering
+ * forever in the registry.
+ *
+ * The registry lives under the user's home directory (not the workspace) so
+ * it is visible to every worktree's daemon, keyed by repositoryId:
+ *
+ * ~/.claude-flow/leases/<repositoryId>.json
+ *
+ * This is deliberately a thin, single-purpose registry β€” repo-supervisor.ts
+ * is the piece that actually elects one process to own the recurring AI
+ * worker schedule; leases only answer "which worktrees are currently live"
+ * for status reporting and future supervisor-dispatched work.
+ */
+
+import * as fs from 'fs';
+import { join } from 'path';
+import { homedir } from 'os';
+import { createHash } from 'crypto';
+
+export const LEASE_TTL_MS = 15 * 60 * 1000; // 15 minutes β€” issue #2661 spec
+const LOCK_STALE_MS = 10_000;
+
+export interface LeaseRecord {
+ worktreeRoot: string;
+ pid: number;
+ registeredAt: number;
+ lastHeartbeat: number;
+}
+
+interface LeaseFile {
+ version: 1;
+ leases: Record<string, LeaseRecord>; // keyed by sha256(worktreeRoot).slice(0,16)
+}
+
+function delay(ms: number): Promise<void> {
+ return new Promise((r) => setTimeout(r, ms));
+}
+
+function isProcessAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** Invariant 9 (#2661): registry files must never be symlinks. */
+function assertNotSymlink(path: string): void {
+ try {
+ const st = fs.lstatSync(path);
+ if (st.isSymbolicLink()) {
+ throw new Error(`Workspace lease file is a symlink (refusing): ${path}`);
+ }
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code === 'ENOENT') return;
+ throw e;
+ }
+}
+
+function leaseKey(worktreeRoot: string): string {
+ return createHash('sha256').update(worktreeRoot).digest('hex').slice(0, 16);
+}
+
+export class WorkspaceLeaseRegistry {
+ private readonly dir: string;
+
+ constructor(options?: { baseDir?: string }) {
+ this.dir = options?.baseDir
+ ?? process.env.RUFLO_AI_BUDGET_DIR // shares the same override as global-ai-budget for test isolation
+ ?? join(homedir(), '.claude-flow');
+ }
+
+ private fileFor(repositoryId: string): string {
+ return join(this.dir, 'leases', `${repositoryId}.json`);
+ }
+
+ private ensureDir(repositoryId: string): void {
+ const dir = join(this.dir, 'leases');
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
+ void repositoryId;
+ }
+
+ private async withLock<T>(repositoryId: string, fn: () => T): Promise<T> {
+ this.ensureDir(repositoryId);
+ const lockFile = `${this.fileFor(repositoryId)}.lock`;
+ const deadline = Date.now() + 2000;
+ for (;;) {
+ try {
+ const fd = fs.openSync(lockFile, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);
+ fs.writeSync(fd, String(process.pid));
+ fs.closeSync(fd);
+ try {
+ return fn();
+ } finally {
+ try { fs.unlinkSync(lockFile); } catch { /* already gone */ }
+ }
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e;
+ try {
+ const st = fs.lstatSync(lockFile);
+ if (Date.now() - st.mtimeMs > LOCK_STALE_MS) {
+ fs.unlinkSync(lockFile);
+ continue;
+ }
+ } catch { /* raced β€” retry */ }
+ if (Date.now() > deadline) throw new Error('timed out acquiring workspace-lease lock');
+ await delay(25);
+ }
+ }
+ }
+
+ private readFile(repositoryId: string): LeaseFile {
+ const file = this.fileFor(repositoryId);
+ assertNotSymlink(file);
+ let parsed: LeaseFile = { version: 1, leases: {} };
+ if (fs.existsSync(file)) {
+ try {
+ const raw = JSON.parse(fs.readFileSync(file, 'utf-8'));
+ if (raw && typeof raw === 'object' && raw.leases && typeof raw.leases === 'object') {
+ parsed = { version: 1, leases: raw.leases };
+ }
+ } catch { /* corrupt β€” start fresh */ }
+ }
+ return parsed;
+ }
+
+ private writeFile(repositoryId: string, data: LeaseFile): void {
+ const file = this.fileFor(repositoryId);
+ assertNotSymlink(file);
+ const tmp = `${file}.tmp.${process.pid}`;
+ fs.writeFileSync(tmp, JSON.stringify(data), { mode: 0o600 });
+ fs.renameSync(tmp, file);
+ }
+
+ /** Register or renew this process's lease on a worktree. Best-effort. */
+ async heartbeat(repositoryId: string, worktreeRoot: string): Promise<void> {
+ try {
+ await this.withLock(repositoryId, () => {
+ const data = this.readFile(repositoryId);
+ const now = Date.now();
+ const key = leaseKey(worktreeRoot);
+ const existing = data.leases[key];
+ data.leases[key] = {
+ worktreeRoot,
+ pid: process.pid,
+ registeredAt: existing?.registeredAt ?? now,
+ lastHeartbeat: now,
+ };
+ this.writeFile(repositoryId, data);
+ });
+ } catch { /* best-effort β€” a missed heartbeat just expires the lease early */ }
+ }
+
+ /** Release this worktree's lease on graceful shutdown. Best-effort. */
+ async release(repositoryId: string, worktreeRoot: string): Promise<void> {
+ try {
+ await this.withLock(repositoryId, () => {
+ const data = this.readFile(repositoryId);
+ delete data.leases[leaseKey(worktreeRoot)];
+ this.writeFile(repositoryId, data);
+ });
+ } catch { /* best-effort */ }
+ }
+
+ /**
+ * Active leases for a repository β€” expired (>15 min stale) or dead-PID
+ * entries are excluded, not just filtered at read time, so callers never
+ * see a worktree that's actually gone.
+ */
+ listActive(repositoryId: string): LeaseRecord[] {
+ try {
+ const data = this.readFile(repositoryId);
+ const now = Date.now();
+ return Object.values(data.leases).filter(
+ (l) => now - l.lastHeartbeat < LEASE_TTL_MS && isProcessAlive(l.pid),
+ );
+ } catch {
+ return [];
+ }
+ }
+
+ /** True when the given worktree currently holds a live (non-expired) lease. */
+ isLeaseActive(repositoryId: string, worktreeRoot: string): boolean {
+ return this.listActive(repositoryId).some((l) => l.worktreeRoot === worktreeRoot);
+ }
+}
+
+let registryInstance: WorkspaceLeaseRegistry | null = null;
+
+export function getWorkspaceLeaseRegistry(): WorkspaceLeaseRegistry {
+ if (!registryInstance) registryInstance = new WorkspaceLeaseRegistry();
+ return registryInstance;
+}
+
+/** Test hook: reset the singleton (e.g. after changing RUFLO_AI_BUDGET_DIR). */
+export function resetWorkspaceLeaseRegistryForTests(): void {
+ registryInstance = null;
+}