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(policy): anchor the decision ledger head so truncation fails verification (#3568)

ruvf0906284529c
diff --git a/v3/@claude-flow/cli/__tests__/policy-ledger-truncation-3568.test.ts b/v3/@claude-flow/cli/__tests__/policy-ledger-truncation-3568.test.ts
new file mode 100644
index 0000000000..bb7109534d
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/policy-ledger-truncation-3568.test.ts
@@ -0,0 +1,117 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir, userInfo } from 'node:os';
+import { createHash } from 'node:crypto';
+import {
+ autoMigratePolicyStateIfNeeded,
+ evaluatePolicyRequest,
+ verifyPolicyLedger,
+} from '../src/services/policy-runtime.js';
+import { policyCommand } from '../src/commands/policy.js';
+
+// #3568: `policy verify` reported `{"valid": true}` after the most recent
+// receipts, or all of them, were deleted from .claude-flow/policy/state.json.
+
+const roots: Array<{ root: string; trust: string }> = [];
+function project(): string {
+ const root = mkdtempSync(join(tmpdir(), 'ruflo-policy-3568-'));
+ mkdirSync(join(root, '.claude-flow'), { recursive: true });
+ const projectId = createHash('sha256').update(realpathSync(root)).digest('hex');
+ roots.push({ root, trust: join(userInfo().homedir, '.config', 'ruflo', 'policy-trust', projectId) });
+ return root;
+}
+
+afterEach(() => {
+ for (const item of roots.splice(0)) {
+ rmSync(item.trust, { recursive: true, force: true });
+ rmSync(item.root, { recursive: true, force: true });
+ }
+});
+
+const statePath = (root: string) => join(root, '.claude-flow', 'policy', 'state.json');
+const readState = (root: string) => JSON.parse(readFileSync(statePath(root), 'utf8'));
+const writeState = (root: string, state: unknown) => writeFileSync(statePath(root), JSON.stringify(state, null, 2));
+
+async function ledgerWith(receipts: number): Promise<string> {
+ const root = project();
+ await autoMigratePolicyStateIfNeeded(root);
+ for (let i = 0; i < receipts; i++) {
+ await evaluatePolicyRequest({
+ identity: { id: `agent:${i}`, type: 'agent' },
+ action: { type: 'code.read', resource: `file-${i}` },
+ }, root);
+ }
+ return root;
+}
+
+async function cliVerify(root: string) {
+ return policyCommand.action!({ args: ['verify'], flags: { projectRoot: root } } as never);
+}
+
+describe('policy verify detects a truncated decision ledger (#3568)', () => {
+ it('passes an untouched ledger', async () => {
+ const root = await ledgerWith(16);
+ expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 16 });
+ const result = await cliVerify(root);
+ expect(result).toMatchObject({ success: true, exitCode: 0 });
+ });
+
+ it.each([
+ ['the last receipt', 1],
+ ['the last 10 of 16', 10],
+ ['every receipt', 16],
+ ])('fails when %s is deleted from state.json', async (_label, removed) => {
+ const root = await ledgerWith(16);
+ const state = readState(root);
+ state.receipts.splice(16 - removed, removed);
+ writeState(root, state);
+
+ expect(await verifyPolicyLedger(root)).toEqual({
+ valid: false,
+ length: 16 - removed,
+ error: 'policy-ledger-truncated',
+ });
+ const result = await cliVerify(root);
+ expect(result).toMatchObject({
+ success: false,
+ exitCode: 1,
+ data: { valid: false, error: 'policy-ledger-truncated' },
+ });
+ });
+
+ it('refuses new decisions on a truncated ledger instead of re-anchoring it', async () => {
+ const root = await ledgerWith(4);
+ const state = readState(root);
+ state.receipts.pop();
+ writeState(root, state);
+ await expect(evaluatePolicyRequest({
+ identity: { id: 'agent:late', type: 'agent' },
+ action: { type: 'code.read', resource: 'late' },
+ }, root)).rejects.toThrow('policy-ledger-truncated');
+ expect((await verifyPolicyLedger(root)).error).toBe('policy-ledger-truncated');
+ });
+
+ it('anchors a ledger written before the anchor existed and reports it once', async () => {
+ const root = await ledgerWith(5);
+ const state = readState(root);
+ delete state.ledgerHead;
+ delete state.ledgerLength;
+ writeState(root, state);
+
+ expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 5, anchor: 'established-now' });
+ expect(readState(root).ledgerLength).toBe(5);
+ expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 5 });
+
+ const anchored = readState(root);
+ anchored.receipts.pop();
+ writeState(root, anchored);
+ expect((await verifyPolicyLedger(root)).error).toBe('policy-ledger-truncated');
+ });
+
+ it('answers an empty ledger distinctly', async () => {
+ const root = project();
+ await autoMigratePolicyStateIfNeeded(root);
+ expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 0, state: 'empty' });
+ });
+});
diff --git a/v3/@claude-flow/cli/src/commands/policy.ts b/v3/@claude-flow/cli/src/commands/policy.ts
index 3aec0ae369..5e98640e9e 100644
--- a/v3/@claude-flow/cli/src/commands/policy.ts
+++ b/v3/@claude-flow/cli/src/commands/policy.ts
@@ -100,7 +100,11 @@ export const policyCommand: Command = {
const state = loadPolicyState(root);
return print({ receipts: state.receipts });
}
- if (operation === 'verify') return print(await verifyPolicyLedger(root));
+ if (operation === 'verify') {
+ const ledger = await verifyPolicyLedger(root);
+ const result = print(ledger);
+ return ledger.valid ? result : { ...result, success: false, exitCode: 1 };
+ }
throw new Error(`unknown policy operation: ${operation}`);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
diff --git a/v3/@claude-flow/cli/src/services/policy-runtime.ts b/v3/@claude-flow/cli/src/services/policy-runtime.ts
index 1aeab94e93..8102882834 100644
--- a/v3/@claude-flow/cli/src/services/policy-runtime.ts
+++ b/v3/@claude-flow/cli/src/services/policy-runtime.ts
@@ -362,8 +362,11 @@ export async function withPolicyTransaction<T>(
approvalIssuerVerifier: options.approvalIssuerVerifier,
});
const result = await operation(engine);
- const nextState = engine.exportState();
+ // Verify before exporting: verification establishes the ledger anchor
+ // (#3568) on state written before the anchor existed, and that anchor
+ // must be part of what is persisted.
if (!engine.verifyLedger().valid) throw new Error('policy-ledger-verification-failed');
+ const nextState = engine.exportState();
await writePolicyState(projectRoot, target.state, nextState);
return result;
} finally {
@@ -430,8 +433,29 @@ export async function revokePolicyApproval(id: string, projectRoot = process.cwd
return withPolicyTransaction(projectRoot, (engine) => engine.revokeApproval(id));
}
+/**
+ * Read-only verification (#3568). It must not run inside
+ * `withPolicyTransaction`, whose own post-operation check throws a generic
+ * `policy-ledger-verification-failed` and hides which check failed. The only
+ * write is persisting an anchor established for a pre-anchor ledger.
+ */
export async function verifyPolicyLedger(projectRoot = process.cwd()): Promise<ReturnType<AgenticPolicyEngine['verifyLedger']>> {
- return withPolicyTransaction(projectRoot, (engine) => engine.verifyLedger());
+ const target = paths(projectRoot);
+ mkdirSync(target.dir, { recursive: true, mode: 0o700 });
+ const release = await acquireLock(target.lock);
+ try {
+ const engine = AgenticPolicyEngine.fromState(loadPolicyState(projectRoot), {
+ signingKey: process.env.CLAUDE_FLOW_POLICY_SIGNING_KEY,
+ keyId: process.env.CLAUDE_FLOW_POLICY_KEY_ID,
+ });
+ const result = engine.verifyLedger();
+ if (result.anchor === 'established-now') {
+ await writePolicyState(projectRoot, target.state, engine.exportState());
+ }
+ return result;
+ } finally {
+ release();
+ }
}
/**
diff --git a/v3/@claude-flow/security/__tests__/policy-ledger-anchor.test.ts b/v3/@claude-flow/security/__tests__/policy-ledger-anchor.test.ts
new file mode 100644
index 0000000000..c18391f2a4
--- /dev/null
+++ b/v3/@claude-flow/security/__tests__/policy-ledger-anchor.test.ts
@@ -0,0 +1,97 @@
+import { describe, expect, it } from 'vitest';
+import { AgenticPolicyEngine, type PolicyRequest, type PolicyState } from '../src/policy/index.js';
+
+// #3568: a prefix of a valid hash chain is itself a valid chain, so deleting
+// the tail of the ledger (or all of it) used to verify as `valid: true`.
+
+const request = (index: number): PolicyRequest => ({
+ identity: { id: `agent:${index}`, type: 'agent' },
+ action: { type: 'code.read', resource: `file-${index}` },
+});
+
+function ledgerOf(receipts: number): PolicyState {
+ const engine = new AgenticPolicyEngine({ mode: 'legacy' });
+ for (let i = 0; i < receipts; i++) engine.evaluate(request(i));
+ return engine.exportState();
+}
+
+describe('policy decision ledger anchor (#3568)', () => {
+ it('verifies an untouched ledger exactly as before', () => {
+ const state = ledgerOf(16);
+ expect(state.ledgerLength).toBe(16);
+ expect(state.ledgerHead).toBe(state.receipts.at(-1)!.hash);
+ expect(AgenticPolicyEngine.fromState(state).verifyLedger()).toEqual({ valid: true, length: 16 });
+ });
+
+ it.each([
+ ['the last receipt', 1],
+ ['the last 10 of 16 receipts', 10],
+ ['every receipt', 16],
+ ])('rejects a ledger with %s deleted', (_label, removed) => {
+ const state = ledgerOf(16);
+ state.receipts.splice(16 - removed, removed);
+ expect(AgenticPolicyEngine.fromState(state).verifyLedger()).toEqual({
+ valid: false,
+ length: 16 - removed,
+ error: 'policy-ledger-truncated',
+ });
+ });
+
+ it('still rejects a modified middle receipt', () => {
+ const state = ledgerOf(16);
+ state.receipts[7]!.payload.request.action.resource = 'tampered';
+ expect(AgenticPolicyEngine.fromState(state).verifyLedger()).toMatchObject({
+ valid: false,
+ error: 'receipt-hash-mismatch',
+ });
+ });
+
+ it('still rejects a deleted middle receipt', () => {
+ const state = ledgerOf(16);
+ state.receipts.splice(7, 1);
+ expect(AgenticPolicyEngine.fromState(state).verifyLedger()).toMatchObject({
+ valid: false,
+ error: 'receipt-chain-mismatch',
+ });
+ });
+
+ it('reports an empty ledger distinctly from an intact one', () => {
+ expect(new AgenticPolicyEngine({ mode: 'legacy' }).verifyLedger())
+ .toEqual({ valid: true, length: 0, state: 'empty' });
+ });
+
+ it('refuses to extend a truncated ledger, so appending cannot erase the evidence', () => {
+ const state = ledgerOf(16);
+ state.receipts.splice(10, 6);
+ const engine = AgenticPolicyEngine.fromState(state);
+ expect(() => engine.evaluate(request(99))).toThrow('policy-ledger-truncated');
+ expect(engine.verifyLedger().error).toBe('policy-ledger-truncated');
+ });
+
+ it('anchors a legacy ledger written before the anchor existed, once', () => {
+ const state = ledgerOf(16);
+ delete state.ledgerHead;
+ delete state.ledgerLength;
+
+ const engine = AgenticPolicyEngine.fromState(state);
+ expect(engine.verifyLedger()).toEqual({ valid: true, length: 16, anchor: 'established-now' });
+
+ const anchored = engine.exportState();
+ expect(anchored.ledgerLength).toBe(16);
+ expect(anchored.ledgerHead).toBe(anchored.receipts.at(-1)!.hash);
+ expect(AgenticPolicyEngine.fromState(anchored).verifyLedger()).toEqual({ valid: true, length: 16 });
+
+ // From here on, truncation is detected.
+ anchored.receipts.pop();
+ expect(AgenticPolicyEngine.fromState(anchored).verifyLedger().error).toBe('policy-ledger-truncated');
+ });
+
+ it('keeps the anchor in step when a legacy ledger receives a new decision', () => {
+ const state = ledgerOf(3);
+ delete state.ledgerHead;
+ delete state.ledgerLength;
+ const engine = AgenticPolicyEngine.fromState(state);
+ engine.evaluate(request(3));
+ expect(engine.verifyLedger()).toEqual({ valid: true, length: 4 });
+ });
+});
diff --git a/v3/@claude-flow/security/src/policy/engine.ts b/v3/@claude-flow/security/src/policy/engine.ts
index 3ce5b11255..475e5e52f5 100644
--- a/v3/@claude-flow/security/src/policy/engine.ts
+++ b/v3/@claude-flow/security/src/policy/engine.ts
@@ -2,6 +2,7 @@ import { policyHash, signPolicyHash, verifyPolicySignature } from './canonical.j
import { evaluatePolicy } from './evaluator.js';
import type {
BudgetLimit,
+ LedgerVerification,
BudgetUsage,
PolicyApproval,
PolicyDecision,
@@ -58,6 +59,10 @@ export class AgenticPolicyEngine {
engine.state.migratedAt = state.migratedAt;
engine.state.migratedFrom = state.migratedFrom;
engine.state.configuredMode = state.configuredMode;
+ if (typeof state.ledgerLength === 'number') {
+ engine.state.ledgerLength = state.ledgerLength;
+ engine.state.ledgerHead = state.ledgerHead ?? null;
+ }
return engine;
}
@@ -148,7 +153,7 @@ export class AgenticPolicyEngine {
return { ...decision, receiptId: receipt.payload.receiptId };
}
- verifyLedger(): { valid: boolean; length: number; error?: string } {
+ verifyLedger(): LedgerVerification {
let previous: string | null = null;
for (let i = 0; i < this.state.receipts.length; i++) {
const receipt = this.state.receipts[i]!;
@@ -171,7 +176,26 @@ export class AgenticPolicyEngine {
}
previous = receipt.hash;
}
- return { valid: true, length: this.state.receipts.length };
+ const length = this.state.receipts.length;
+ // #3568: a prefix of a valid chain is itself a valid chain, so the chain
+ // alone cannot tell "the last receipts were deleted" from "they were never
+ // written". The anchor records how long the chain is and where it ends.
+ if (typeof this.state.ledgerLength === 'number') {
+ if (this.state.ledgerLength !== length || (this.state.ledgerHead ?? null) !== previous) {
+ return {
+ valid: false,
+ length,
+ error: length < this.state.ledgerLength ? 'policy-ledger-truncated' : 'policy-ledger-anchor-mismatch',
+ };
+ }
+ return length === 0 ? { valid: true, length, state: 'empty' } : { valid: true, length };
+ }
+ if (length === 0) return { valid: true, length, state: 'empty' };
+ // Receipts written before the anchor existed. Anchor the current chain;
+ // a truncation that happened before this moment cannot be detected.
+ this.state.ledgerHead = previous;
+ this.state.ledgerLength = length;
+ return { valid: true, length, anchor: 'established-now' };
}
private applyBudget(request: PolicyRequest, decision: Omit<PolicyDecision, 'receiptId'>): Omit<PolicyDecision, 'receiptId'> {
@@ -246,6 +270,14 @@ export class AgenticPolicyEngine {
private appendReceipt(request: PolicyRequest, decision: Omit<PolicyDecision, 'receiptId'>): PolicyReceipt {
const previous = this.state.receipts.at(-1)?.hash ?? null;
+ // Never extend a chain that no longer matches its anchor: appending would
+ // re-anchor onto the truncated chain and erase the evidence of truncation.
+ if (typeof this.state.ledgerLength === 'number'
+ && (this.state.ledgerLength !== this.state.receipts.length || (this.state.ledgerHead ?? null) !== previous)) {
+ throw new Error(this.state.receipts.length < this.state.ledgerLength
+ ? 'policy-ledger-truncated'
+ : 'policy-ledger-anchor-mismatch');
+ }
const sequence = this.state.receipts.length;
const payloadWithoutId = {
previousReceiptHash: previous,
@@ -265,6 +297,8 @@ export class AgenticPolicyEngine {
keyId: this.signingKey ? (this.keyId ?? 'local') : undefined,
};
this.state.receipts.push(receipt);
+ this.state.ledgerHead = hash;
+ this.state.ledgerLength = this.state.receipts.length;
return receipt;
}
diff --git a/v3/@claude-flow/security/src/policy/types.ts b/v3/@claude-flow/security/src/policy/types.ts
index 8b7508b881..3484520d33 100644
--- a/v3/@claude-flow/security/src/policy/types.ts
+++ b/v3/@claude-flow/security/src/policy/types.ts
@@ -173,6 +173,25 @@ export interface PolicyState {
usage: BudgetUsage[];
approvals: PolicyApproval[];
receipts: PolicyReceipt[];
+ /**
+ * Ledger anchor (#3568): hash of the final receipt and the receipt count,
+ * written in the same state write as every receipt append. A prefix of a
+ * valid hash chain is itself a valid chain, so without this anchor a
+ * truncated or fully erased ledger verified as `valid: true`. Absent on
+ * states written before the anchor existed; established on first use.
+ */
+ ledgerHead?: string | null;
+ ledgerLength?: number;
+}
+
+export interface LedgerVerification {
+ valid: boolean;
+ length: number;
+ error?: string;
+ /** Receipts existed but no anchor did: the anchor was created from the current chain. */
+ anchor?: 'established-now';
+ /** No receipts and no anchor claiming any: distinct from "receipts intact". */
+ state?: 'empty';
}
export interface PolicyEngineOptions {