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

fix(claims): share lossless CLI and MCP persistence format

Rudy Celekli6d80e75b0570
diff --git a/v3/@claude-flow/cli/__tests__/claims-store-compatibility.test.ts b/v3/@claude-flow/cli/__tests__/claims-store-compatibility.test.ts
new file mode 100644
index 0000000000..550a2663ae
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/claims-store-compatibility.test.ts
@@ -0,0 +1,58 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { ClaimService } from '../src/services/claim-service.js';
+import { claimsTools } from '../src/mcp-tools/claims-tools.js';
+let dir: string;
+let file: string;
+const owner = { type: 'agent' as const, agentId: 'worker', agentType: 'coder' };
+const claimTool = claimsTools.find(t => t.name === 'claims_claim')!;
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'ruflo-claims-store-'));
+ mkdirSync(join(dir, '.claude-flow', 'claims'), { recursive: true });
+ file = join(dir, '.claude-flow', 'claims', 'claims.json');
+ vi.spyOn(process, 'cwd').mockReturnValue(dir);
+});
+afterEach(() => { vi.restoreAllMocks(); rmSync(dir, { recursive: true, force: true }); });
+describe('shared CLI/MCP claims persistence', () => {
+ it.each(['CLI', 'MCP'])('preserves claims when %s writes before the other surface', async first => {
+ if (first === 'CLI') {
+ const cli = new ClaimService(dir); await cli.initialize(); await cli.claim('first', owner);
+ expect(await claimTool.handler({ issueId: 'second', claimant: 'agent:worker:coder' })).toMatchObject({ success: true });
+ } else {
+ await claimTool.handler({ issueId: 'first', claimant: 'agent:worker:coder' });
+ const cli = new ClaimService(dir); await cli.initialize(); await cli.claim('second', owner);
+ }
+ const reopened = new ClaimService(dir); await reopened.initialize();
+ expect((await reopened.getAllClaims()).map(c => c.issueId).sort()).toEqual(['first', 'second']);
+ for (const issueId of ['first', 'second']) {
+ expect(await claimTool.handler({ issueId, claimant: 'agent:other:coder' })).toMatchObject({ success: false });
+ }
+ });
+ it.each(['{broken', '{"claims":null}', '{"claims":[{}]}'])('fails closed on malformed persisted claims: %s', async contents => {
+ writeFileSync(file, contents);
+ await expect(claimTool.handler({ issueId: 'new', claimant: 'agent:worker:coder' })).rejects.toThrow();
+ expect(readFileSync(file, 'utf8')).toBe(contents);
+ await expect(new ClaimService(dir).initialize()).rejects.toThrow();
+ expect(readFileSync(file, 'utf8')).toBe(contents);
+ });
+ it('round trips work-stealing metadata and unrelated contest records', async () => {
+ await claimTool.handler({ issueId: 'first', claimant: 'agent:worker:coder' });
+ const data = JSON.parse(readFileSync(file, 'utf8'));
+ data.operatorMetadata = { custom: ['preserve', 'this'] };
+ data.claims.first.externalReference = 'tracking-id';
+ data.contests = { first: { reason: 'existing contest', originalClaimant: owner } };
+ writeFileSync(file, JSON.stringify(data));
+ const cli = new ClaimService(dir); await cli.initialize();
+ await cli.markStealable('first', { reason: 'voluntary', stealableAt: new Date(), preferredTypes: ['tester'], progress: 25, context: 'resume here' });
+ const reopened = new ClaimService(dir); await reopened.initialize();
+ expect(await reopened.getStealable('coder')).toEqual([]);
+ expect((await reopened.getStealable('tester')).map(c => c.issueId)).toEqual(['first']);
+ const stored = JSON.parse(readFileSync(file, 'utf8'));
+ expect(stored.contests).toEqual(data.contests);
+ expect(stored.operatorMetadata).toEqual(data.operatorMetadata);
+ expect(stored.claims.first.externalReference).toBe('tracking-id');
+ expect(stored.stealable.first.context).toBe('resume here');
+ });
+});
diff --git a/v3/@claude-flow/cli/src/mcp-tools/claims-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/claims-tools.ts
index 04e1527201..ab26a456ce 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/claims-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/claims-tools.ts
@@ -8,6 +8,7 @@
*/
import type { MCPTool } from './types.js';
+import { readClaimsStore } from '../services/claims-store.js';
import { validateIdentifier, validateText } from './validate-input.js';
// Inline claim service since we can't import external modules
@@ -43,7 +44,7 @@ interface ClaimsStore {
}
// File-based persistence
-import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
+import { existsSync, writeFileSync, mkdirSync } from 'fs';
import { join, resolve } from 'path';
const CLAIMS_DIR = '.claude-flow/claims';
@@ -61,15 +62,7 @@ function ensureClaimsDir(): void {
}
function loadClaims(): ClaimsStore {
- try {
- const path = getClaimsPath();
- if (existsSync(path)) {
- return JSON.parse(readFileSync(path, 'utf-8'));
- }
- } catch {
- // Return empty store on error
- }
- return { claims: {}, stealable: {}, contests: {} };
+ return readClaimsStore(getClaimsPath()) as unknown as ClaimsStore;
}
function saveClaims(store: ClaimsStore): void {
diff --git a/v3/@claude-flow/cli/src/services/claim-service.ts b/v3/@claude-flow/cli/src/services/claim-service.ts
index ac0fe13dbc..30def0d8d4 100644
--- a/v3/@claude-flow/cli/src/services/claim-service.ts
+++ b/v3/@claude-flow/cli/src/services/claim-service.ts
@@ -17,6 +17,7 @@ import { EventEmitter } from 'events';
import * as fs from 'fs';
import * as path from 'path';
import { execFileSync } from 'child_process';
+import { readClaimsStore } from './claims-store.js';
// ============================================================================
// Types
@@ -233,26 +234,24 @@ export class ClaimService extends EventEmitter {
}
private async loadClaims(): Promise<void> {
- const claimsFile = path.join(this.storagePath, 'claims.json');
- if (fs.existsSync(claimsFile)) {
- try {
- const data = JSON.parse(fs.readFileSync(claimsFile, 'utf-8'));
- for (const claim of data.claims || []) {
- claim.claimedAt = new Date(claim.claimedAt);
- claim.statusChangedAt = new Date(claim.statusChangedAt);
- if (claim.expiresAt) claim.expiresAt = new Date(claim.expiresAt);
- this.claims.set(claim.issueId, claim);
- }
- } catch {
- // Start fresh if file is corrupted
- }
+ const data = readClaimsStore(path.join(this.storagePath, 'claims.json'));
+ for (const claim of Object.values(data.claims as Record<string, IssueClaim>)) {
+ claim.claimedAt = new Date(claim.claimedAt);
+ claim.statusChangedAt = new Date(claim.statusChangedAt);
+ if (claim.expiresAt) claim.expiresAt = new Date(claim.expiresAt);
+ this.claims.set(claim.issueId, claim);
+ }
+ for (const [id, info] of Object.entries(data.stealable as Record<string, StealableInfo>)) {
+ this.stealableInfo.set(id, { ...info, stealableAt: new Date(info.stealableAt) });
}
}
private async saveClaims(): Promise<void> {
const claimsFile = path.join(this.storagePath, 'claims.json');
const data = {
- claims: Array.from(this.claims.values()),
+ ...readClaimsStore(claimsFile),
+ claims: Object.fromEntries(this.claims),
+ stealable: Object.fromEntries(this.stealableInfo),
savedAt: new Date().toISOString(),
};
fs.writeFileSync(claimsFile, JSON.stringify(data, null, 2));
diff --git a/v3/@claude-flow/cli/src/services/claims-store.ts b/v3/@claude-flow/cli/src/services/claims-store.ts
new file mode 100644
index 0000000000..91b720e90d
--- /dev/null
+++ b/v3/@claude-flow/cli/src/services/claims-store.ts
@@ -0,0 +1,37 @@
+/** Shared on-disk shape for the CLI claim service and public MCP claim tools. */
+import { readFileSync } from 'node:fs';
+
+function record(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+/** Read legacy CLI arrays and MCP dictionaries; never replace unreadable state. */
+export function readClaimsStore(file: string): Record<string, unknown> {
+ let text: string;
+ try { text = readFileSync(file, 'utf8'); }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { claims: {}, stealable: {}, contests: {} };
+ throw error;
+ }
+ const data: unknown = JSON.parse(text);
+ if (!record(data) || (!Array.isArray(data.claims) && !record(data.claims))) {
+ throw new Error('Invalid claims store: expected a claims array or object');
+ }
+ const entries = Array.isArray(data.claims)
+ ? data.claims.map((claim: unknown) => [record(claim) ? claim.issueId : undefined, claim])
+ : Object.entries(data.claims);
+ const claims: Record<string, unknown> = Object.create(null);
+ for (const [id, claim] of entries) {
+ if (typeof id !== 'string' || !id || !record(claim) || claim.issueId !== id ||
+ !record(claim.claimant) || typeof claim.status !== 'string' ||
+ typeof claim.claimedAt !== 'string' || typeof claim.statusChangedAt !== 'string' ||
+ Object.hasOwn(claims, id)) {
+ throw new Error('Invalid claims store: malformed or duplicate claim');
+ }
+ claims[id] = claim;
+ }
+ for (const key of ['stealable', 'contests']) {
+ if (data[key] !== undefined && !record(data[key])) throw new Error(`Invalid claims store: ${key} must be an object`);
+ }
+ return { ...data, claims, stealable: data.stealable ?? {}, contests: data.contests ?? {} };
+}