claude-flow 3.26.0 → 3.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,136 @@
1
+ /**
2
+ * #2661 — Cross-worktree AI job dedup (issue invariant 5).
3
+ *
4
+ * N worktrees of one repository checked out at the same HEAD schedule the
5
+ * same analyses independently: N audits of identical content, N optimize
6
+ * passes, N testgap sweeps. Before a model launch, callers compute
7
+ *
8
+ * jobKey = sha256(repositoryId, head, workerType, workerConfigHash)
9
+ *
10
+ * and skip the launch when the same job succeeded within the freshness
11
+ * window. HEAD moves → new key → the job runs again.
12
+ *
13
+ * The registry lives next to the AI budget ledger under the user's home
14
+ * directory (owner-only, symlink-rejecting) so all daemons share it:
15
+ *
16
+ * ~/.claude-flow/ai-jobs.json
17
+ *
18
+ * This is a best-effort OPTIMIZATION layered under the budget: two daemons
19
+ * racing the same key may both miss and both attempt a launch, but the
20
+ * budget's atomic reservation (maxConcurrentGlobal / hourly cap) is the hard
21
+ * invariant that bounds actual launches. Only operational metadata is
22
+ * persisted — never prompts, outputs, or source content.
23
+ */
24
+ import * as fs from 'fs';
25
+ import { join } from 'path';
26
+ import { homedir } from 'os';
27
+ import { createHash } from 'crypto';
28
+ const DAY_MS = 24 * 60 * 60 * 1000;
29
+ export function computeAiJobKey(parts) {
30
+ return createHash('sha256')
31
+ .update([parts.repositoryId, parts.head, parts.workerType, parts.configHash].join('\n'))
32
+ .digest('hex');
33
+ }
34
+ /** Stable hash of an arbitrary config object (key-sorted JSON). */
35
+ export function hashWorkerConfig(config) {
36
+ const canonical = JSON.stringify(config, (_k, v) => {
37
+ if (v && typeof v === 'object' && !Array.isArray(v)) {
38
+ return Object.fromEntries(Object.entries(v).sort(([a], [b]) => a.localeCompare(b)));
39
+ }
40
+ return v;
41
+ });
42
+ return createHash('sha256').update(canonical ?? 'null').digest('hex');
43
+ }
44
+ /** Invariant 9: registry files must never be symlinks. */
45
+ function assertNotSymlink(path) {
46
+ try {
47
+ const st = fs.lstatSync(path);
48
+ if (st.isSymbolicLink()) {
49
+ throw new Error(`AI job registry is a symlink (refusing): ${path}`);
50
+ }
51
+ }
52
+ catch (e) {
53
+ if (e.code === 'ENOENT')
54
+ return;
55
+ throw e;
56
+ }
57
+ }
58
+ export class AiJobDedupRegistry {
59
+ dir;
60
+ file;
61
+ constructor(options) {
62
+ this.dir = options?.baseDir
63
+ ?? process.env.RUFLO_AI_BUDGET_DIR
64
+ ?? join(homedir(), '.claude-flow');
65
+ this.file = join(this.dir, 'ai-jobs.json');
66
+ }
67
+ /**
68
+ * True when the job succeeded within `freshnessMs`. Any registry error
69
+ * reads as "not fresh" — dedup failing open only costs a (budget-capped)
70
+ * launch, never correctness.
71
+ */
72
+ isFresh(jobKey, freshnessMs) {
73
+ if (process.env.RUFLO_AI_DEDUP_DISABLE === '1')
74
+ return { fresh: false };
75
+ try {
76
+ const records = this.read();
77
+ const rec = records[jobKey];
78
+ if (rec && Date.now() - rec.at < freshnessMs) {
79
+ return { fresh: true, lastRunAt: rec.at };
80
+ }
81
+ return { fresh: false, lastRunAt: rec?.at };
82
+ }
83
+ catch {
84
+ return { fresh: false };
85
+ }
86
+ }
87
+ /** Record a successful run of a job. Best-effort. */
88
+ recordSuccess(jobKey, meta) {
89
+ try {
90
+ const records = this.read();
91
+ records[jobKey] = { at: Date.now(), ...meta };
92
+ this.write(records);
93
+ }
94
+ catch { /* dedup is an optimization — never block on it */ }
95
+ }
96
+ read() {
97
+ assertNotSymlink(this.file);
98
+ if (!fs.existsSync(this.file))
99
+ return {};
100
+ const raw = JSON.parse(fs.readFileSync(this.file, 'utf-8'));
101
+ if (!raw || typeof raw !== 'object')
102
+ return {};
103
+ // Prune anything older than 24h — freshness windows are far shorter,
104
+ // and HEAD churn would otherwise grow the file without bound.
105
+ const now = Date.now();
106
+ const out = {};
107
+ for (const [key, rec] of Object.entries(raw)) {
108
+ if (rec && typeof rec.at === 'number' && now - rec.at < DAY_MS) {
109
+ out[key] = rec;
110
+ }
111
+ }
112
+ return out;
113
+ }
114
+ write(records) {
115
+ if (!fs.existsSync(this.dir)) {
116
+ fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
117
+ }
118
+ assertNotSymlink(this.file);
119
+ const tmp = `${this.file}.tmp.${process.pid}`;
120
+ fs.writeFileSync(tmp, JSON.stringify(records), { mode: 0o600 });
121
+ fs.renameSync(tmp, this.file);
122
+ }
123
+ }
124
+ // Singleton — one registry per process.
125
+ let registryInstance = null;
126
+ export function getAiJobDedupRegistry() {
127
+ if (!registryInstance) {
128
+ registryInstance = new AiJobDedupRegistry();
129
+ }
130
+ return registryInstance;
131
+ }
132
+ /** Test hook: reset the singleton (e.g. after changing RUFLO_AI_BUDGET_DIR). */
133
+ export function resetAiJobDedupRegistryForTests() {
134
+ registryInstance = null;
135
+ }
136
+ //# sourceMappingURL=ai-job-dedup.js.map
@@ -0,0 +1,42 @@
1
+ /**
2
+ * #2661 — Git workspace identity: separate WORKTREE identity from
3
+ * REPOSITORY identity.
4
+ *
5
+ * Daemon dedup, state, and scheduling have historically been keyed on the
6
+ * worktree path (`process.cwd()`), so N Git worktrees of the same repository
7
+ * behave as N unrelated projects — the cardinality bug behind the worktree
8
+ * daemon fanout. This service resolves the identity that is SHARED across
9
+ * worktrees:
10
+ *
11
+ * worktreeRoot `git rev-parse --show-toplevel` — per-worktree
12
+ * commonGitDir `git rev-parse --git-common-dir` — shared by all worktrees
13
+ * repositoryId sha256(canonical commonGitDir) — stable repo key
14
+ * head `git rev-parse HEAD` — current commit
15
+ *
16
+ * Two worktrees of one repository resolve to the SAME repositoryId (and,
17
+ * when checked out at the same commit, the same head) — the key ingredient
18
+ * for cross-worktree job dedup (issue invariant 5).
19
+ *
20
+ * Non-git directories degrade gracefully: repositoryId falls back to a hash
21
+ * of the resolved directory path (prefixed `dir:`-style via isGit=false), so
22
+ * callers never need a special case.
23
+ */
24
+ export interface GitWorkspaceIdentity {
25
+ /** Absolute root of this worktree (or the input dir when not a git repo). */
26
+ worktreeRoot: string;
27
+ /** Absolute path of the shared .git directory (equals worktreeRoot/.git for non-worktree clones). */
28
+ commonGitDir: string;
29
+ /** Stable id shared by ALL worktrees of one repository. */
30
+ repositoryId: string;
31
+ /** Current HEAD commit sha ('' when not a git repo or unborn HEAD). */
32
+ head: string;
33
+ /** False when the directory is not inside a git repository. */
34
+ isGit: boolean;
35
+ }
36
+ /**
37
+ * Resolve the git workspace identity for a directory. Never throws.
38
+ */
39
+ export declare function resolveGitWorkspaceIdentity(dir: string): GitWorkspaceIdentity;
40
+ /** Test hook: clear the per-process identity cache. */
41
+ export declare function resetGitIdentityCacheForTests(): void;
42
+ //# sourceMappingURL=git-workspace-identity.d.ts.map
@@ -0,0 +1,99 @@
1
+ /**
2
+ * #2661 — Git workspace identity: separate WORKTREE identity from
3
+ * REPOSITORY identity.
4
+ *
5
+ * Daemon dedup, state, and scheduling have historically been keyed on the
6
+ * worktree path (`process.cwd()`), so N Git worktrees of the same repository
7
+ * behave as N unrelated projects — the cardinality bug behind the worktree
8
+ * daemon fanout. This service resolves the identity that is SHARED across
9
+ * worktrees:
10
+ *
11
+ * worktreeRoot `git rev-parse --show-toplevel` — per-worktree
12
+ * commonGitDir `git rev-parse --git-common-dir` — shared by all worktrees
13
+ * repositoryId sha256(canonical commonGitDir) — stable repo key
14
+ * head `git rev-parse HEAD` — current commit
15
+ *
16
+ * Two worktrees of one repository resolve to the SAME repositoryId (and,
17
+ * when checked out at the same commit, the same head) — the key ingredient
18
+ * for cross-worktree job dedup (issue invariant 5).
19
+ *
20
+ * Non-git directories degrade gracefully: repositoryId falls back to a hash
21
+ * of the resolved directory path (prefixed `dir:`-style via isGit=false), so
22
+ * callers never need a special case.
23
+ */
24
+ import { execFileSync } from 'child_process';
25
+ import { createHash } from 'crypto';
26
+ import { resolve } from 'path';
27
+ import * as fs from 'fs';
28
+ const GIT_TIMEOUT_MS = 3000;
29
+ function git(cwd, ...args) {
30
+ try {
31
+ return execFileSync('git', args, {
32
+ cwd,
33
+ encoding: 'utf-8',
34
+ timeout: GIT_TIMEOUT_MS,
35
+ stdio: ['ignore', 'pipe', 'ignore'],
36
+ windowsHide: true,
37
+ }).trim();
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ }
43
+ function sha256(input) {
44
+ return createHash('sha256').update(input).digest('hex');
45
+ }
46
+ // Identity is stable for the life of a process (repo location doesn't move),
47
+ // but HEAD is not — cache only the expensive, stable parts per directory.
48
+ const identityCache = new Map();
49
+ /**
50
+ * Resolve the git workspace identity for a directory. Never throws.
51
+ */
52
+ export function resolveGitWorkspaceIdentity(dir) {
53
+ const resolved = resolve(dir);
54
+ let stable = identityCache.get(resolved);
55
+ if (!stable) {
56
+ const worktreeRoot = git(resolved, 'rev-parse', '--show-toplevel');
57
+ if (!worktreeRoot) {
58
+ stable = {
59
+ worktreeRoot: resolved,
60
+ commonGitDir: '',
61
+ // 'dir:' prefix keeps non-git ids from ever colliding with repo ids.
62
+ repositoryId: sha256(`dir:${canonicalPath(resolved)}`),
63
+ isGit: false,
64
+ };
65
+ }
66
+ else {
67
+ // --git-common-dir may be relative to the worktree root (git < 2.31
68
+ // and some invocation contexts) — resolve against it.
69
+ const rawCommon = git(worktreeRoot, 'rev-parse', '--git-common-dir') ?? '.git';
70
+ const commonGitDir = resolve(worktreeRoot, rawCommon);
71
+ stable = {
72
+ worktreeRoot,
73
+ commonGitDir,
74
+ repositoryId: sha256(`git:${canonicalPath(commonGitDir)}`),
75
+ isGit: true,
76
+ };
77
+ }
78
+ identityCache.set(resolved, stable);
79
+ }
80
+ const head = stable.isGit ? (git(stable.worktreeRoot, 'rev-parse', 'HEAD') ?? '') : '';
81
+ return { ...stable, head };
82
+ }
83
+ /**
84
+ * Canonicalize a path so the same repository yields the same repositoryId
85
+ * regardless of symlinked prefixes (/tmp vs /private/tmp on macOS, etc.).
86
+ */
87
+ function canonicalPath(p) {
88
+ try {
89
+ return fs.realpathSync(p);
90
+ }
91
+ catch {
92
+ return p;
93
+ }
94
+ }
95
+ /** Test hook: clear the per-process identity cache. */
96
+ export function resetGitIdentityCacheForTests() {
97
+ identityCache.clear();
98
+ }
99
+ //# sourceMappingURL=git-workspace-identity.js.map
@@ -0,0 +1,110 @@
1
+ /**
2
+ * #2661 — Global AI launch budget (emergency cost fuse).
3
+ *
4
+ * Every autonomous `claude --print` launch across ALL ruflo daemons in ALL
5
+ * worktrees/workspaces owned by the current user must pass through this
6
+ * user-global budget before a process is created. Without it, N worktree
7
+ * daemons each schedule their own AI workers and aggregate launch volume
8
+ * scales linearly with worktree count — enough to exhaust a user's Claude
9
+ * hourly quota silently (13 launches/hour/daemon under the legacy schedule).
10
+ *
11
+ * The ledger lives under the user's home directory (NOT the workspace) so
12
+ * daemons started from different worktrees of the same repository — or from
13
+ * unrelated repositories — all share one budget:
14
+ *
15
+ * ~/.claude-flow/ai-budget.json launch ledger + circuit breaker
16
+ * ~/.claude-flow/ai-budget.lock O_EXCL mutation lock
17
+ * ~/.claude-flow/ai-budget-receipts.jsonl launch/deny/pause receipts
18
+ *
19
+ * Files are owner-only (0700 dir / 0600 files) and symlinks are rejected
20
+ * (invariant 9 of #2661). All checks happen BEFORE process creation and the
21
+ * ledger mutation is atomic under the lock, so two daemons racing for the
22
+ * last hourly slot cannot both win.
23
+ *
24
+ * Default limits (issue #2661 containment):
25
+ * maxConcurrentGlobal 1 at most one autonomous claude child, user-wide
26
+ * maxLaunchesPerHour 2
27
+ * maxLaunchesPerDay 12
28
+ * pauseOnQuotaErrorMinutes 60 circuit breaker on 429/quota responses
29
+ */
30
+ export interface AiBudgetLimits {
31
+ maxConcurrentGlobal: number;
32
+ maxLaunchesPerHour: number;
33
+ maxLaunchesPerDay: number;
34
+ pauseOnQuotaErrorMinutes: number;
35
+ }
36
+ export declare const DEFAULT_AI_BUDGET_LIMITS: AiBudgetLimits;
37
+ export interface AiBudgetRequest {
38
+ workerType: string;
39
+ model: string;
40
+ /** Worktree/workspace root requesting the launch (recorded for receipts only). */
41
+ workspace: string;
42
+ }
43
+ export interface AiBudgetPermit {
44
+ allowed: boolean;
45
+ permitId?: string;
46
+ reason?: string;
47
+ }
48
+ /**
49
+ * Heuristic match for Anthropic quota / rate-limit failures. Only ever
50
+ * applied to ERROR output of a FAILED launch (never to successful analysis
51
+ * output, which may legitimately discuss "rate limiting" in the user's code).
52
+ */
53
+ export declare function isQuotaErrorText(text: string | undefined): boolean;
54
+ export declare class GlobalAiBudget {
55
+ private readonly dir;
56
+ private readonly ledgerFile;
57
+ private readonly lockFile;
58
+ private readonly receiptsFile;
59
+ private readonly limits;
60
+ constructor(options?: {
61
+ baseDir?: string;
62
+ limits?: Partial<AiBudgetLimits>;
63
+ });
64
+ getLimits(): AiBudgetLimits;
65
+ /**
66
+ * Atomically reserve one launch slot. Denials carry a machine-readable
67
+ * reason and are receipted. The reservation is counted as a launch
68
+ * immediately (the hourly/daily invariant is on launches, not completions);
69
+ * `release()` only frees the concurrency slot.
70
+ *
71
+ * Fails CLOSED: if the ledger cannot be read or locked, the launch is
72
+ * denied — an unaccountable launch is exactly what this fuse exists to
73
+ * prevent. `RUFLO_AI_BUDGET_DISABLE=1` is the explicit escape hatch.
74
+ */
75
+ reserve(req: AiBudgetRequest): Promise<AiBudgetPermit>;
76
+ /** Free the concurrency slot held by a permit. Best-effort. */
77
+ release(permitId: string | undefined): Promise<void>;
78
+ /**
79
+ * Open the user-global circuit breaker: a quota/429 response from ANY
80
+ * daemon pauses ALL autonomous Claude launches for the cooldown window.
81
+ */
82
+ recordQuotaError(detail: string): Promise<void>;
83
+ /** Snapshot for `daemon status` / diagnostics. */
84
+ getUsage(): {
85
+ lastHour: number;
86
+ lastDay: number;
87
+ active: number;
88
+ pausedUntil?: number;
89
+ pauseReason?: string;
90
+ /** #2661 — 24h launch counts per worktree/workspace, most active first. */
91
+ byWorkspace: Array<{
92
+ workspace: string;
93
+ launches: number;
94
+ }>;
95
+ };
96
+ private ensureDir;
97
+ private acquireLock;
98
+ /** Read + prune the ledger. Caller must hold the lock for read-modify-write. */
99
+ private readLedger;
100
+ private writeLedger;
101
+ /**
102
+ * Invariant 10: every launch, denial, and pause emits a receipt. Only
103
+ * operational metadata is persisted — never prompts or source content.
104
+ */
105
+ private appendReceipt;
106
+ }
107
+ export declare function getGlobalAiBudget(): GlobalAiBudget;
108
+ /** Test hook: reset the singleton (e.g. after changing RUFLO_AI_BUDGET_DIR). */
109
+ export declare function resetGlobalAiBudgetForTests(): void;
110
+ //# sourceMappingURL=global-ai-budget.d.ts.map