Files
ruvnet__ruflo/v3/@claude-flow/cli/__tests__/daemon-migration-warning-2661.test.ts
rUv f220882025 feat(daemon): repository supervisor, structured telemetry, budget CLI, migration warning (#2661) (#2663)
* feat(daemon): repository supervisor, structured telemetry, budget CLI, migration warning (#2661)

Closes the four gaps flagged as still-open against #2661's full root-fix
spec after the containment + dedup phases already shipped (#2662).

1. Repository-level supervisor + worktree leases (workspace-lease.ts,
   repo-supervisor.ts). Ten worktree daemons of one repository independently
   deciding "is it time to run audit" every tick was the redundant-scheduler
   half of the cardinality bug — the budget ledger and job dedup already
   bound and dedupe actual spend, but every daemon still ran its own timer.
   Exactly one daemon per repositoryId is now elected supervisor (lock-
   protected takeover, same pattern as global-ai-budget.ts) and owns the
   recurring AI-worker schedule; every other worktree stays a lease-only
   participant (15-min TTL heartbeat) running its cheap local-only workers.
   An explicit `daemon trigger --headless` still bypasses the gate — it's a
   one-off user action, still budget/dedup-governed like any other launch.

2. Structured per-launch token telemetry. `claude --print` now runs with
   `--output-format json`; parseClaudePrintJsonEnvelope() extracts input/
   output tokens, cost, and API duration, receipted via the budget ledger's
   new recordUsage(). Lenient parsing — any schema mismatch degrades to
   "no usage captured" rather than breaking existing analysis-output
   parsing, since the raw `result` text still flows through unchanged.

3. `ruflo daemon budget show|pause|resume`. Budget state was previously
   visible only inline in `daemon status --all`; these give it an
   independently scriptable surface. pause()/resume() reuse the exact same
   enforcement path as the automatic quota-triggered circuit breaker.

4. One-time upgrade migration warning. A pre-existing multi-daemon fleet
   where AI workers were already enabled (old config/env from before this
   fix) is exactly the P0 shape #2661 describes — warned once ever (a
   persisted marker, not per-command), and only for that specific risky
   shape, not a harmless AI-off fleet (already covered by the existing
   always-shown fleet-size notice).

`daemon status --all` gains a "Repository Supervisors" panel alongside the
existing budget panel.

54 new tests across workspace-lease, repo-supervisor, claude-print-envelope,
global-ai-budget (extended), and daemon-migration-warning-2661 suites.

Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(statusline): don't import helper-refresh.js just for getInstalledCliVersion

statusline-generator.ts imported getInstalledCliVersion from helper-refresh.js
(added in b254e3215, shipped 3.27.3-3.27.4). ES module imports load a
module's ENTIRE top-level regardless of which export is used — helper-
refresh.ts imports the `semver` package at module scope (for
autoRefreshHelpersIfStale()'s version comparison, unrelated to the function
actually needed here), so merely importing getInstalledCliVersion dragged
`semver` into every context that loads this generator.

Confirmed live: PR #2663's "Static regression guards" CI job installs only
minimal smoke deps (no full `npm install`), and helpers-generator.ts
transitively imports statusline-generator.ts — the router smoke test
(#2257) failed with ERR_MODULE_NOT_FOUND('semver') the moment this file
gained the import, despite never calling anything semver-related itself.
Verified by temporarily hiding node_modules/semver locally: reproduced the
exact failure, confirmed fixed after this change.

Duplicates the same createRequire/walk-up version resolution locally
(getInstalledCliVersionLocal) using only Node builtins — this generator's
own footprint should stay minimal since it's loaded in exactly these
lightweight/partial-install contexts. No output change: the baked-in
version value and the rest of the generated script are byte-identical.

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-07-14 01:32:34 -04:00

106 lines
4.1 KiB
TypeScript

/**
* #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();
});
});