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): ledger anchor can no longer be deleted and silently re-established (#3602)

ruv8446702423f5
diff --git a/v3/@claude-flow/cli/__tests__/policy-ledger-anchor-3602.test.ts b/v3/@claude-flow/cli/__tests__/policy-ledger-anchor-3602.test.ts
new file mode 100644
index 0000000000..beb41f05dc
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/policy-ledger-anchor-3602.test.ts
@@ -0,0 +1,238 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { existsSync, 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';
+
+// #3602: deleting the anchor fields from state.json (together with receipts)
+// made `policy verify` report valid and re-establish the anchor on the
+// truncated chain. ADR-475.
+
+const roots: Array<{ root: string; trust: string }> = [];
+function project(): string {
+ const root = mkdtempSync(join(tmpdir(), 'ruflo-policy-3602-'));
+ mkdirSync(join(root, '.claude-flow'), { recursive: true });
+ const id = createHash('sha256').update(realpathSync(root)).digest('hex');
+ roots.push({ root, trust: join(userInfo().homedir, '.config', 'ruflo', 'policy-trust', id) });
+ return root;
+}
+afterEach(() => {
+ Object.defineProperty(process.stdin, 'isTTY', { value: ttyOriginal.stdin, configurable: true, writable: true });
+ Object.defineProperty(process.stdout, 'isTTY', { value: ttyOriginal.stdout, configurable: true, writable: true });
+ 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 logPath = (root: string) => join(root, '.claude-flow', 'policy', 'ledger-anchors.json');
+const mirrorPath = (root: string) => {
+ const id = createHash('sha256').update(realpathSync(root)).digest('hex');
+ return join(userInfo().homedir, '.config', 'ruflo', 'policy-trust', id, 'ledger-anchor-head.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));
+const readLog = (root: string) => JSON.parse(readFileSync(logPath(root), 'utf8'));
+
+async function decide(root: string, i: number) {
+ return evaluatePolicyRequest({
+ identity: { id: `agent:${i}`, type: 'agent' },
+ action: { type: 'code.read', resource: `file-${i}` },
+ }, root);
+}
+async function ledgerWith(receipts: number): Promise<string> {
+ const root = project();
+ await autoMigratePolicyStateIfNeeded(root);
+ for (let i = 0; i < receipts; i++) await decide(root, i);
+ return root;
+}
+function truncate(root: string, keep: number, deleteAnchorFields: boolean) {
+ const state = readState(root);
+ state.receipts.splice(keep);
+ if (deleteAnchorFields) {
+ delete state.ledgerHead;
+ delete state.ledgerLength;
+ }
+ writeState(root, state);
+}
+const ttyOriginal = { stdin: process.stdin.isTTY, stdout: process.stdout.isTTY };
+function setTty(value: boolean) {
+ Object.defineProperty(process.stdin, 'isTTY', { value, configurable: true, writable: true });
+ Object.defineProperty(process.stdout, 'isTTY', { value, configurable: true, writable: true });
+}
+const asInteractive = () => setTty(true);
+
+describe('policy ledger anchor cannot be deleted and silently re-established (#3602)', () => {
+ it('reproduction: truncate AND delete the anchor fields is invalid, not established-now', async () => {
+ const root = await ledgerWith(5);
+ truncate(root, 3, true);
+ expect(await verifyPolicyLedger(root)).toEqual({ valid: false, length: 3, error: 'policy-ledger-truncated' });
+ // and verify did not write a new anchor into state.json
+ expect(readState(root).ledgerLength).toBeUndefined();
+ });
+
+ it('the CLI exits non-zero for the reproduction', async () => {
+ const root = await ledgerWith(5);
+ truncate(root, 3, true);
+ const result = await policyCommand.action!({ args: ['verify'], flags: { projectRoot: root } } as never);
+ expect(result).toMatchObject({ success: false, exitCode: 1, data: { valid: false, error: 'policy-ledger-truncated' } });
+ });
+
+ it('truncation with intact primary but deleted second anchor still fails', async () => {
+ const root = await ledgerWith(5);
+ truncate(root, 3, false);
+ rmSync(logPath(root));
+ expect((await verifyPolicyLedger(root)).error).toBe('policy-ledger-truncated');
+ });
+
+ it('a deleted second anchor alone (mirror remains) is tamper-suspected', async () => {
+ const root = await ledgerWith(5);
+ rmSync(logPath(root));
+ expect(await verifyPolicyLedger(root)).toEqual({ valid: false, length: 5, error: 'policy-anchor-log-missing' });
+ });
+
+ it('truncation plus every project-dir anchor deleted is caught by the mirror in the home directory', async () => {
+ const root = await ledgerWith(5);
+ truncate(root, 3, true);
+ rmSync(logPath(root));
+ expect((await verifyPolicyLedger(root)).valid).toBe(false);
+ });
+
+ it('with both anchors and the mirror gone and receipts present: anchor-missing (documented limit)', async () => {
+ const root = await ledgerWith(5);
+ truncate(root, 3, true);
+ rmSync(logPath(root));
+ rmSync(mirrorPath(root));
+ expect(await verifyPolicyLedger(root)).toEqual({ valid: false, length: 3, error: 'anchor-missing' });
+ });
+
+ it('refuses new decisions on a ledger that lost its anchors instead of re-anchoring it', async () => {
+ const root = await ledgerWith(5);
+ truncate(root, 3, true);
+ rmSync(logPath(root));
+ rmSync(mirrorPath(root));
+ await expect(decide(root, 99)).rejects.toThrow('policy-ledger-anchor-missing');
+ expect(readState(root).ledgerLength).toBeUndefined();
+ });
+
+ it('a ledger whose second anchor was rolled back to an older copy is rejected', async () => {
+ const root = await ledgerWith(2);
+ const old = readFileSync(logPath(root), 'utf8');
+ await decide(root, 10);
+ writeFileSync(logPath(root), old);
+ expect((await verifyPolicyLedger(root)).error).toBe('policy-anchor-log-rolled-back');
+ });
+
+ it('a corrupted anchors file is invalid until an explicit, logged establish rebuilds it', async () => {
+ const root = await ledgerWith(3);
+ writeFileSync(logPath(root), '{"version":1,"entries":[{"seq":0}]}');
+ expect((await verifyPolicyLedger(root)).error).toBe('policy-anchor-log-corrupt');
+ await expect(decide(root, 7)).rejects.toThrow('policy-anchor-log-corrupt');
+
+ const result = await verifyPolicyLedger(root, { establishAnchor: true });
+ expect(result).toMatchObject({ valid: true, length: 3, secondaryAnchor: 'established-explicitly' });
+ expect(readLog(root).entries).toMatchObject([{ length: 3, event: 'establish-anchor', by: userInfo().username }]);
+ expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 3 });
+ await decide(root, 8);
+ });
+
+ it('a corrupted anchors file cannot be rebuilt over a truncation the mirror remembers', async () => {
+ const root = await ledgerWith(5);
+ truncate(root, 3, true);
+ writeFileSync(logPath(root), 'not json');
+ expect((await verifyPolicyLedger(root, { establishAnchor: true })).error).toBe('policy-ledger-truncated');
+ });
+
+ it('genesis: an empty ledger needs no flag and verifies empty', async () => {
+ const root = project();
+ await autoMigratePolicyStateIfNeeded(root);
+ expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 0, state: 'empty' });
+ expect(existsSync(logPath(root))).toBe(false);
+ await decide(root, 0);
+ expect(readLog(root).entries).toHaveLength(1);
+ expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 1 });
+ });
+
+ it('a ledger emptied entirely (receipts and fields) is caught because the second anchor remembers it', async () => {
+ const root = await ledgerWith(4);
+ truncate(root, 0, true);
+ expect((await verifyPolicyLedger(root)).error).toBe('policy-ledger-truncated');
+ });
+
+ it('migration: a state.json anchor from an older version is accepted and the second anchor is written', async () => {
+ const root = await ledgerWith(4);
+ rmSync(logPath(root));
+ rmSync(mirrorPath(root));
+ expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 4, secondaryAnchor: 'recorded-from-state' });
+ expect(readLog(root).entries).toMatchObject([{ length: 4, event: 'migrated-from-state' }]);
+ expect(existsSync(mirrorPath(root))).toBe(true);
+ expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 4 });
+ truncate(root, 2, true);
+ expect((await verifyPolicyLedger(root)).error).toBe('policy-ledger-truncated');
+ });
+
+ it('a ledger from a version with no anchor at all gets anchor-missing and a one-step explicit repair', async () => {
+ const root = await ledgerWith(4);
+ truncate(root, 4, true);
+ rmSync(logPath(root));
+ rmSync(mirrorPath(root));
+ expect(await verifyPolicyLedger(root)).toEqual({ valid: false, length: 4, error: 'anchor-missing' });
+ await expect(decide(root, 50)).rejects.toThrow(/verify --establish-anchor/);
+
+ asInteractive();
+ const cli = await policyCommand.action!({ args: ['verify'], flags: { projectRoot: root, 'establish-anchor': true } } as never);
+ expect(cli).toMatchObject({ success: true, exitCode: 0, data: { valid: true, secondaryAnchor: 'established-explicitly' } });
+ const [entry] = readLog(root).entries;
+ expect(entry).toMatchObject({ event: 'establish-anchor', length: 4, by: userInfo().username });
+ expect(typeof entry.ts).toBe('number');
+ expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 4 });
+ await decide(root, 51);
+ expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 5 });
+ });
+
+ it('--establish-anchor is refused without an interactive terminal', async () => {
+ const root = await ledgerWith(2);
+ truncate(root, 2, true);
+ rmSync(logPath(root));
+ rmSync(mirrorPath(root));
+ setTty(false);
+ const result = await policyCommand.action!({ args: ['verify'], flags: { projectRoot: root, 'establish-anchor': true } } as never);
+ expect(result).toMatchObject({ success: false, exitCode: 1 });
+ expect(existsSync(logPath(root))).toBe(false);
+ });
+
+ it('--establish-anchor cannot bless a truncation the anchors still remember', async () => {
+ const root = await ledgerWith(5);
+ truncate(root, 3, true);
+ expect((await verifyPolicyLedger(root, { establishAnchor: true })).error).toBe('policy-ledger-truncated');
+ });
+
+ it('concurrent appends keep a valid, chained second anchor', async () => {
+ const root = await ledgerWith(1);
+ await Promise.all(Array.from({ length: 10 }, (_, i) => decide(root, 100 + i)));
+ expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 11 });
+ const { entries } = readLog(root);
+ expect(entries.at(-1).length).toBe(11);
+ entries.forEach((entry: { seq: number; prevAnchorHash: string | null }, i: number) => {
+ expect(entry.seq).toBe(i);
+ expect(entry.prevAnchorHash).toBe(i === 0 ? null : entries[i - 1].hash);
+ });
+ });
+
+ it('state ahead of the second anchor (crash between the two writes) is caught up, not rejected', async () => {
+ const root2 = await ledgerWith(2);
+ const lagging = readFileSync(logPath(root2), 'utf8');
+ await decide(root2, 20);
+ writeFileSync(logPath(root2), lagging);
+ rmSync(mirrorPath(root2));
+ expect(await verifyPolicyLedger(root2)).toEqual({ valid: true, length: 3 });
+ expect(readLog(root2).entries.at(-1).length).toBe(3);
+ });
+});
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
index bb7109534d..316e7eaed0 100644
--- a/v3/@claude-flow/cli/__tests__/policy-ledger-truncation-3568.test.ts
+++ b/v3/@claude-flow/cli/__tests__/policy-ledger-truncation-3568.test.ts
@@ -92,14 +92,14 @@ describe('policy verify detects a truncated decision ledger (#3568)', () => {
expect((await verifyPolicyLedger(root)).error).toBe('policy-ledger-truncated');
});
- it('anchors a ledger written before the anchor existed and reports it once', async () => {
+ it('restores a deleted primary anchor from the intact second anchor, and still catches truncation (#3602)', 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(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 5, secondaryAnchor: 'restored-primary' });
expect(readState(root).ledgerLength).toBe(5);
expect(await verifyPolicyLedger(root)).toEqual({ valid: true, length: 5 });
diff --git a/v3/@claude-flow/cli/src/commands/policy.ts b/v3/@claude-flow/cli/src/commands/policy.ts
index 5e98640e9e..9589fddca4 100644
--- a/v3/@claude-flow/cli/src/commands/policy.ts
+++ b/v3/@claude-flow/cli/src/commands/policy.ts
@@ -5,6 +5,7 @@ import type {
PolicyState,
} from '@claude-flow/security';
import type { Command, CommandContext, CommandResult } from '../types.js';
+import { anchorPosture } from '../services/policy-ledger-anchor.js';
import { output } from '../output.js';
import {
autoMigratePolicyStateIfNeeded,
@@ -34,12 +35,17 @@ function requireInteractiveAdministrator(): void {
}
}
+// #3602: say what verify can and cannot prove.
+const LEDGER_TRUST_SCOPE = 'detects edits confined to state.json or to the project directory; '
+ + 'does not defend against an attacker who can rewrite both the project directory and ~/.config/ruflo (ADR-475)';
+
export const policyCommand: Command = {
name: 'policy',
description: 'Agentic policy engine — evaluate actions, manage rules/approvals, and verify the decision ledger (ADR-324)',
options: [
{ name: 'mode', type: 'string', description: 'Policy mode: legacy | observe | enforce' },
{ name: 'project-root', type: 'string', description: 'Project root containing .claude-flow/policy' },
+ { name: 'establish-anchor', type: 'boolean', description: 'verify: explicitly anchor a ledger that has receipts but no anchor (interactive, logged with user and time)' },
],
async action(context: CommandContext): Promise<CommandResult> {
const args = (context as { args?: string[] }).args ?? [];
@@ -101,8 +107,10 @@ export const policyCommand: Command = {
return print({ receipts: state.receipts });
}
if (operation === 'verify') {
- const ledger = await verifyPolicyLedger(root);
- const result = print(ledger);
+ const establishAnchor = flags['establish-anchor'] === true || flags.establishAnchor === true;
+ if (establishAnchor) requireInteractiveAdministrator();
+ const ledger = await verifyPolicyLedger(root, { establishAnchor });
+ const result = print({ ...ledger, anchors: anchorPosture(root), scope: LEDGER_TRUST_SCOPE });
return ledger.valid ? result : { ...result, success: false, exitCode: 1 };
}
throw new Error(`unknown policy operation: ${operation}`);
diff --git a/v3/@claude-flow/cli/src/services/policy-ledger-anchor.ts b/v3/@claude-flow/cli/src/services/policy-ledger-anchor.ts
new file mode 100644
index 0000000000..d9560430b8
--- /dev/null
+++ b/v3/@claude-flow/cli/src/services/policy-ledger-anchor.ts
@@ -0,0 +1,184 @@
+/**
+ * Second, hash-chained copy of the policy ledger anchor (#3602, ADR-475).
+ *
+ * The primary anchor (`ledgerLength` / `ledgerHead`) lives inside state.json,
+ * the same file it protects, so deleting it together with receipts used to
+ * make `verify` bless the truncated chain. This module keeps an append-only
+ * chain of anchor entries in a SEPARATE file plus a mirror of the newest entry
+ * outside the project directory (~/.config/ruflo/policy-trust/<project>/).
+ *
+ * Threat model: this detects any tampering confined to state.json, and any
+ * tampering confined to the project directory. It does NOT stop an attacker
+ * who can rewrite both the project directory and the user's home directory.
+ */
+import { createHash } from 'node:crypto';
+import { existsSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { userInfo } from 'node:os';
+import type { PolicyState } from '@claude-flow/security';
+
+export type AnchorEvent = 'append' | 'migrated-from-state' | 'establish-anchor';
+
+export interface AnchorEntry {
+ seq: number;
+ length: number;
+ headHash: string | null;
+ prevAnchorHash: string | null;
+ ts: number;
+ event: AnchorEvent;
+ by?: string;
+ hash: string;
+}
+
+export type AnchorAssessment =
+ | { kind: 'absent' }
+ | { kind: 'ok'; last: AnchorEntry; behind: boolean }
+ | { kind: 'fail'; error: string };
+
+export type AnchorWriter = (file: string, value: unknown) => Promise<void>;
+
+const LOG_FILE = 'ledger-anchors.json';
+const MIRROR_FILE = 'ledger-anchor-head.json';
+
+export const anchorLogPath = (projectRoot: string): string => join(resolve(projectRoot), '.claude-flow', 'policy', LOG_FILE);
+
+function mirrorPath(projectRoot: string): string {
+ const id = createHash('sha256').update(realpathSync(projectRoot)).digest('hex');
+ return join(userInfo().homedir, '.config', 'ruflo', 'policy-trust', id, MIRROR_FILE);
+}
+
+function entryHash(entry: Omit<AnchorEntry, 'hash'>): string {
+ return createHash('sha256').update(JSON.stringify([
+ entry.seq, entry.length, entry.headHash, entry.prevAnchorHash, entry.ts, entry.event, entry.by ?? null,
+ ])).digest('hex');
+}
+
+function validEntry(value: unknown, seq: number, prev: string | null): value is AnchorEntry {
+ const e = value as AnchorEntry;
+ return !!e && typeof e === 'object'
+ && e.seq === seq
+ && Number.isInteger(e.length) && e.length >= 0
+ && (e.headHash === null || typeof e.headHash === 'string')
+ && e.prevAnchorHash === prev
+ && typeof e.ts === 'number'
+ && ['append', 'migrated-from-state', 'establish-anchor'].includes(e.event)
+ && typeof e.hash === 'string'
+ && e.hash === entryHash({ ...e, hash: undefined } as never);
+}
+
+function readLog(projectRoot: string): AnchorEntry[] | 'corrupt' {
+ const file = anchorLogPath(projectRoot);
+ if (!existsSync(file)) return [];
+ try {
+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as { version?: number; entries?: unknown[] };
+ if (parsed.version !== 1 || !Array.isArray(parsed.entries)) return 'corrupt';
+ let prev: string | null = null;
+ for (let i = 0; i < parsed.entries.length; i++) {
+ if (!validEntry(parsed.entries[i], i, prev)) return 'corrupt';
+ prev = (parsed.entries[i] as AnchorEntry).hash;
+ }
+ return parsed.entries as AnchorEntry[];
+ } catch {
+ return 'corrupt';
+ }
+}
+
+function readMirror(projectRoot: string): AnchorEntry | null | 'corrupt' {
+ const file = mirrorPath(projectRoot);
+ if (!existsSync(file)) return null;
+ try {
+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as AnchorEntry;
+ return typeof parsed?.hash === 'string' && parsed.hash === entryHash({ ...parsed, hash: undefined } as never)
+ ? parsed
+ : 'corrupt';
+ } catch {
+ return 'corrupt';
+ }
+}
+
+/**
+ * How the stored anchors relate to `state`; read-only. `rebuild` is the
+ * explicit-establish path: an unreadable log or mirror is treated as absent, but
+ * whatever readable anchor remains must still agree with the chain, so it can
+ * never bless a truncation the anchors still remember.
+ */
+export function assessAnchors(projectRoot: string, state: PolicyState, rebuild = false): AnchorAssessment {
+ let entries = readLog(projectRoot);
+ if (entries === 'corrupt') {
+ if (!rebuild) return { kind: 'fail', error: 'policy-anchor-log-corrupt' };
+ entries = [];
+ }
+ let mirror = readMirror(projectRoot);
+ if (mirror === 'corrupt') {
+ if (!rebuild) return { kind: 'fail', error: 'policy-anchor-mirror-corrupt' };
+ mirror = null;
+ }
+ if (entries.length === 0) {
+ if (!mirror) return { kind: 'absent' };
+ if (!rebuild) return { kind: 'fail', error: 'policy-anchor-log-missing' };
+ if (state.receipts.length < mirror.length) return { kind: 'fail', error: 'policy-ledger-truncated' };
+ if (mirror.length > 0 && state.receipts[mirror.length - 1]!.hash !== mirror.headHash) {
+ return { kind: 'fail', error: 'policy-ledger-anchor-mismatch' };
+ }
+ return { kind: 'absent' };
+ }
+ if (mirror && !entries.some((entry) => entry.hash === mirror.hash)) {
+ return { kind: 'fail', error: 'policy-anchor-log-rolled-back' };
+ }
+ const last = entries[entries.length - 1]!;
+ for (const anchor of mirror ? [last, mirror] : [last]) {
+ if (state.receipts.length < anchor.length) return { kind: 'fail', error: 'policy-ledger-truncated' };
+ if (anchor.length > 0 && state.receipts[anchor.length - 1]!.hash !== anchor.headHash) {
+ return { kind: 'fail', error: 'policy-ledger-anchor-mismatch' };
+ }
+ }
+ return { kind: 'ok', last, behind: state.receipts.length > last.length };
+}
+
+/**
+ * Append an entry for the current state if the newest entry does not already
+ * describe it. Must run under the policy lock. Throws if the log is corrupt:
+ * only an explicit establish may replace a corrupt log.
+ */
+export async function recordAnchor(
+ projectRoot: string,
+ state: PolicyState,
+ write: AnchorWriter,
+ event: AnchorEvent = 'append',
+ by?: string,
+): Promise<void> {
+ if (state.receipts.length === 0) return;
+ const loaded = readLog(projectRoot);
+ const entries = loaded === 'corrupt' ? [] : loaded;
+ if (loaded === 'corrupt' && event !== 'establish-anchor') throw new Error('policy-anchor-log-corrupt');
+ const last = entries[entries.length - 1];
+ const length = state.receipts.length;
+ const headHash = state.receipts[length - 1]!.hash;
+ let tip = last;
+ if (!last || last.length !== length || last.headHash !== headHash) {
+ const base = {
+ seq: entries.length,
+ length,
+ headHash,
+ prevAnchorHash: last?.hash ?? null,
+ ts: Date.now(),
+ event,
+ ...(by ? { by } : {}),
+ };
+ tip = { ...base, hash: entryHash(base) };
+ await write(anchorLogPath(projectRoot), { version: 1, entries: [...entries, tip] });
+ }
+ try {
+ const mirror = mirrorPath(projectRoot);
+ mkdirSync(dirname(mirror), { recursive: true, mode: 0o700 });
+ await write(mirror, tip);
+ } catch (error) {
+ // A read-only home must not stop the ledger; verify reports the weaker
+ // posture (no mirror) rather than failing closed on every decision.
+ process.stderr.write(`[policy] anchor mirror not written: ${(error as Error).message}\n`);
+ }
+}
+
+export function anchorPosture(projectRoot: string): { log: boolean; mirror: boolean } {
+ return { log: existsSync(anchorLogPath(projectRoot)), mirror: existsSync(mirrorPath(projectRoot)) };
+}
diff --git a/v3/@claude-flow/cli/src/services/policy-runtime.ts b/v3/@claude-flow/cli/src/services/policy-runtime.ts
index efb4569676..3cafab7619 100644
--- a/v3/@claude-flow/cli/src/services/policy-runtime.ts
+++ b/v3/@claude-flow/cli/src/services/policy-runtime.ts
@@ -36,6 +36,7 @@ import {
import { dirname, join, resolve } from 'node:path';
import { hostname, userInfo } from 'node:os';
import { syncPolicyProjection } from '../mods/policy-projection.js';
+import { assessAnchors, recordAnchor, type AnchorEvent } from './policy-ledger-anchor.js';
const POLICY_DIR = join('.claude-flow', 'policy');
const POLICY_FILE = 'state.json';
@@ -244,8 +245,17 @@ function verifyStateAnchor(projectRoot: string, state: PolicyState | undefined):
}
}
-async function writePolicyState(projectRoot: string, statePath: string, state: PolicyState): Promise<void> {
+async function writePolicyState(
+ projectRoot: string,
+ statePath: string,
+ state: PolicyState,
+ anchorEvent: AnchorEvent = 'append',
+ by?: string,
+): Promise<void> {
await writePolicyStateFiles(projectRoot, statePath, state);
+ // #3602: the second anchor is written after the state, so a crash leaves the
+ // state AHEAD of the log (caught up on the next write), never behind it.
+ await recordAnchor(projectRoot, state, writeJsonAtomic, anchorEvent, by);
// ADR-404: the ruflo mod reads Claude Code tool rules from a small
// projection, never from state.json. Written only after the state and its
// anchor are safely down; a failure here never fails the state write. A
@@ -374,19 +384,25 @@ export async function withPolicyTransaction<T>(
mkdirSync(target.dir, { recursive: true, mode: 0o700 });
const release = await acquireLock(target.lock);
try {
- const engine = AgenticPolicyEngine.fromState(loadPolicyState(projectRoot), {
+ const loaded = loadPolicyState(projectRoot);
+ const engine = AgenticPolicyEngine.fromState(loaded, {
signingKey: process.env.CLAUDE_FLOW_POLICY_SIGNING_KEY,
keyId: process.env.CLAUDE_FLOW_POLICY_KEY_ID,
evidenceVerifier: verifyPolicyEvidence,
approvalIssuerVerifier: options.approvalIssuerVerifier,
});
+ // #3602: refuse to operate on a ledger whose anchors are missing or
+ // disagree; a restored primary anchor is persisted by the write below.
+ const gate = reconcileLedger(projectRoot, engine, {});
+ if (!gate.result.valid) {
+ throw new Error(gate.result.error === 'anchor-missing'
+ ? `policy-ledger-anchor-missing: receipts exist but no ledger anchor was found. If this ledger predates anchors, run \`ruflo policy verify --establish-anchor\`; otherwise treat it as tampering.`
+ : gate.result.error ?? 'policy-ledger-verification-failed');
+ }
const result = await operation(engine);
- // 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);
+ await writePolicyState(projectRoot, target.state, nextState, gate.event);
return result;
} finally {
release();
@@ -452,13 +468,73 @@ export async function revokePolicyApproval(id: string, projectRoot = process.cwd
return withPolicyTransaction(projectRoot, (engine) => engine.revokeApproval(id));
}
+export type PolicyLedgerVerification = ReturnType<AgenticPolicyEngine['verifyLedger']> & {
+ /** How the second anchor was brought in line during this call. */
+ secondaryAnchor?: 'recorded-from-state' | 'restored-primary' | 'established-explicitly';
+};
+
+interface Reconciled {
+ result: PolicyLedgerVerification;
+ persist: boolean;
+ event?: AnchorEvent;
+}
+
/**
- * 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.
+ * Decide whether the ledger may be trusted, using the chain, the primary anchor
+ * in state.json and the second anchor (#3602). It never creates an anchor over
+ * existing receipts on its own: only an authentic second anchor (restoring a
+ * deleted primary) or an explicit `establishAnchor` does.
*/
-export async function verifyPolicyLedger(projectRoot = process.cwd()): Promise<ReturnType<AgenticPolicyEngine['verifyLedger']>> {
+function reconcileLedger(
+ projectRoot: string,
+ engine: AgenticPolicyEngine,
+ options: { establishAnchor?: boolean },
+): Reconciled {
+ const state = engine.exportState();
+ const length = state.receipts.length;
+ const primary = typeof state.ledgerLength === 'number';
+ const base = engine.verifyLedger();
+ const fail = (error: string): Reconciled => ({ result: { valid: false, length, error }, persist: false });
+ if (!base.valid && base.error !== 'anchor-missing') return { result: base, persist: false };
+ const assessed = assessAnchors(projectRoot, state, options.establishAnchor === true);
+ if (assessed.kind === 'fail') return fail(assessed.error);
+ if (primary) {
+ if (assessed.kind === 'absent' && length > 0) {
+ return options.establishAnchor
+ ? { result: { ...base, secondaryAnchor: 'established-explicitly' }, persist: true, event: 'establish-anchor' }
+ : { result: { ...base, secondaryAnchor: 'recorded-from-state' }, persist: true, event: 'migrated-from-state' };
+ }
+ return { result: base, persist: assessed.kind === 'ok' && assessed.behind, event: 'append' };
+ }
+ // No primary anchor.
+ if (length === 0) return { result: { valid: true, length, state: 'empty' }, persist: false };
+ if (assessed.kind === 'ok') {
+ // The second anchor is authentic and agrees with the chain: the deleted
+ // primary can be restored from it. Truncation was already rejected above.
+ engine.verifyLedger({ establishAnchor: true });
+ return { result: { valid: true, length, secondaryAnchor: 'restored-primary' }, persist: true, event: 'append' };
+ }
+ if (options.establishAnchor) {
+ const established = engine.verifyLedger({ establishAnchor: true });
+ return {
+ result: { ...established, secondaryAnchor: 'established-explicitly' },
+ persist: true,
+ event: 'establish-anchor',
+ };
+ }
+ return fail('anchor-missing');
+}
+
+/**
+ * Verification (#3568, #3602). It must not run inside `withPolicyTransaction`,
+ * whose own post-operation check throws a generic
+ * `policy-ledger-verification-failed` and hides which check failed. It writes
+ * only to bring the second anchor in line, or on an explicit `establishAnchor`.
+ */
+export async function verifyPolicyLedger(
+ projectRoot = process.cwd(),
+ options: { establishAnchor?: boolean } = {},
+): Promise<PolicyLedgerVerification> {
const target = paths(projectRoot);
mkdirSync(target.dir, { recursive: true, mode: 0o700 });
const release = await acquireLock(target.lock);
@@ -467,11 +543,12 @@ export async function verifyPolicyLedger(projectRoot = process.cwd()): Promise<R
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());
+ const outcome = reconcileLedger(projectRoot, engine, options);
+ if (outcome.persist) {
+ const by = outcome.event === 'establish-anchor' ? userInfo().username : undefined;
+ await writePolicyState(projectRoot, target.state, engine.exportState(), outcome.event, by);
}
- return result;
+ return outcome.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
index c18391f2a4..47b9150a32 100644
--- a/v3/@claude-flow/security/__tests__/policy-ledger-anchor.test.ts
+++ b/v3/@claude-flow/security/__tests__/policy-ledger-anchor.test.ts
@@ -68,30 +68,45 @@ describe('policy decision ledger anchor (#3568)', () => {
expect(engine.verifyLedger().error).toBe('policy-ledger-truncated');
});
- it('anchors a legacy ledger written before the anchor existed, once', () => {
+ it('never re-anchors receipts that have no anchor on its own (#3602)', () => {
const state = ledgerOf(16);
delete state.ledgerHead;
delete state.ledgerLength;
+ state.receipts.splice(10);
const engine = AgenticPolicyEngine.fromState(state);
- expect(engine.verifyLedger()).toEqual({ valid: true, length: 16, anchor: 'established-now' });
+ expect(engine.verifyLedger()).toEqual({ valid: false, length: 10, error: 'anchor-missing' });
+ expect(engine.exportState().ledgerLength).toBeUndefined();
+ });
+
+ it('anchors receipts only on an explicit establish, once', () => {
+ const state = ledgerOf(16);
+ delete state.ledgerHead;
+ delete state.ledgerLength;
+
+ const engine = AgenticPolicyEngine.fromState(state);
+ expect(engine.verifyLedger({ establishAnchor: true })).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', () => {
+ it('refuses to append to receipts that have no anchor, so appending cannot re-anchor them', () => {
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 });
+ expect(() => engine.evaluate(request(3))).toThrow('policy-ledger-anchor-missing');
+ });
+
+ it('a first decision on a genesis ledger anchors it', () => {
+ const engine = new AgenticPolicyEngine({ mode: 'legacy' });
+ engine.evaluate(request(0));
+ expect(engine.verifyLedger()).toEqual({ valid: true, length: 1 });
});
});
diff --git a/v3/@claude-flow/security/src/policy/engine.ts b/v3/@claude-flow/security/src/policy/engine.ts
index 475e5e52f5..e46a74bbea 100644
--- a/v3/@claude-flow/security/src/policy/engine.ts
+++ b/v3/@claude-flow/security/src/policy/engine.ts
@@ -153,7 +153,15 @@ export class AgenticPolicyEngine {
return { ...decision, receiptId: receipt.payload.receiptId };
}
- verifyLedger(): LedgerVerification {
+ /**
+ * `establishAnchor` is the ONLY way to create an anchor over receipts that
+ * already exist (#3602). A caller must have decided, outside the state file,
+ * that this is legitimate (genesis, an authentic second anchor, or an
+ * explicit operator action). Without it a ledger with receipts and no anchor
+ * is `anchor-missing`, because deleting the anchor fields from the file the
+ * anchor protects would otherwise let verify bless a truncated chain.
+ */
+ verifyLedger(options: { establishAnchor?: boolean } = {}): LedgerVerification {
let previous: string | null = null;
for (let i = 0; i < this.state.receipts.length; i++) {
const receipt = this.state.receipts[i]!;
@@ -191,8 +199,10 @@ export class AgenticPolicyEngine {
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.
+ // Receipts but no anchor: either written before anchors existed, or the
+ // anchor fields were deleted (#3602). The two are indistinguishable from
+ // this state alone, so never re-anchor silently.
+ if (!options.establishAnchor) return { valid: false, length, error: 'anchor-missing' };
this.state.ledgerHead = previous;
this.state.ledgerLength = length;
return { valid: true, length, anchor: 'established-now' };
@@ -270,6 +280,11 @@ export class AgenticPolicyEngine {
private appendReceipt(request: PolicyRequest, decision: Omit<PolicyDecision, 'receiptId'>): PolicyReceipt {
const previous = this.state.receipts.at(-1)?.hash ?? null;
+ // #3602: appending to receipts that have no anchor would anchor them,
+ // which is the silent re-establishment verify refuses to do.
+ if (typeof this.state.ledgerLength !== 'number' && this.state.receipts.length > 0) {
+ throw new Error('policy-ledger-anchor-missing');
+ }
// 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'
diff --git a/v3/@claude-flow/security/src/policy/types.ts b/v3/@claude-flow/security/src/policy/types.ts
index 3484520d33..d33c46f0f9 100644
--- a/v3/@claude-flow/security/src/policy/types.ts
+++ b/v3/@claude-flow/security/src/policy/types.ts
@@ -178,7 +178,9 @@ export interface PolicyState {
* 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.
+ * states written before the anchor existed (or with the fields deleted): such a
+ * ledger verifies as `anchor-missing` until an explicit, logged establish
+ * action (#3602).
*/
ledgerHead?: string | null;
ledgerLength?: number;
@@ -188,7 +190,7 @@ export interface LedgerVerification {
valid: boolean;
length: number;
error?: string;
- /** Receipts existed but no anchor did: the anchor was created from the current chain. */
+ /** An explicit establish action anchored receipts that had no anchor (#3602). */
anchor?: 'established-now';
/** No receipts and no anchor claiming any: distinct from "receipts intact". */
state?: 'empty';
diff --git a/v3/docs/adr/ADR-475-policy-ledger-anchor.md b/v3/docs/adr/ADR-475-policy-ledger-anchor.md
new file mode 100644
index 0000000000..1db72a41d0
--- /dev/null
+++ b/v3/docs/adr/ADR-475-policy-ledger-anchor.md
@@ -0,0 +1,47 @@
+# ADR 475: Policy ledger anchor cannot be deleted and silently re-established
+
+Status: Accepted
+
+Date: 2026-10-07
+
+Builds on: ADR-324 (agentic policy engine), #3568 (ledger truncation anchor)
+
+## 1. Context
+
+#3568 added an anchor (`ledgerLength`, `ledgerHead`) so that a truncated ledger no longer verified. The anchor lived in
+`state.json`, the file it protects, and `verify` re-created it whenever it was absent while receipts existed ("established-now").
+So an attacker who truncated receipts and also deleted the two anchor fields got `{"valid":true,"anchor":"established-now"}`
+(#3602, reproduced on 3.54.1). Appending a receipt to an unanchored ledger re-anchored it the same way.
+
+## 2. Decision
+
+1. **Never re-anchor silently.** With receipts present and no anchor, `verify` reports `anchor-missing` (invalid), and
+ `appendReceipt` / any policy transaction refuse (`policy-ledger-anchor-missing`). Only an empty ledger (genesis) anchors on its first receipt.
+2. **A second anchor outside the file the attacker edits.** `.claude-flow/policy/ledger-anchors.json` is an append-only,
+ hash-chained list `{seq, length, headHash, prevAnchorHash, ts, event, by?, hash}`, written after each state write that changes the chain.
+ The newest entry is mirrored to `~/.config/ruflo/policy-trust/<project>/ledger-anchor-head.json`. `verify` checks the
+ state against the primary anchor, the newest log entry and the mirror. The mirror must appear in the log (an older copy of the log is a rollback).
+ The log is written after `state.json`, so a crash leaves the state ahead of the log; that is caught up, never read as truncation.
+3. **Explicit repair.** `ruflo policy verify --establish-anchor` (interactive terminal only, not exposed over MCP) anchors a ledger
+ that has receipts and no usable anchor, and records `event: establish-anchor`, the OS user and the time in the log. It cannot override a
+ truncation or mismatch that the remaining anchors still prove.
+4. **Migration.** A state.json anchor from an older version is accepted; the second anchor is then written (`migrated-from-state`).
+ A ledger with no anchor at all (pre-#3568) gets `anchor-missing` and the one-step repair above, not a crash. A deleted primary with an
+ intact second anchor is restored from it (`restored-primary`) when the chain agrees.
+
+## 3. Threat model (stated in `verify` output as `scope`)
+
+Detected: edits confined to `state.json`; edits confined to the project directory (the mirror remembers the newest anchor); a rolled-back or deleted anchor log while the mirror exists; a
+corrupted log.
+
+NOT detected: an attacker who can rewrite both the project directory and the user's `~/.config/ruflo`. They can also delete the anchors,
+the mirror and the receipts, leaving a ledger that is either `anchor-missing` (which a naive operator may then "repair" with `--establish-anchor`) or, if they also forge a coherent log and mirror, valid.
+No local, unkeyed scheme defends against full local write access; stronger evidence needs an external witness (signed receipts via
+`CLAUDE_FLOW_POLICY_SIGNING_KEY`, or shipping the head hash off-host). A truncation back to a point where a *previous* anchor
+entry exists while that entry and everything after it is also removed from log and mirror is likewise undetectable. The mirror is best-effort (a read-only home logs a warning and continues).
+
+## 4. Consequences
+
+- `verifyPolicyLedger` gains `{ establishAnchor }` and results may carry `secondaryAnchor`. `LedgerVerification.anchor` is only set by an explicit establish.
+- `AgenticPolicyEngine.verifyLedger({ establishAnchor })` is the only engine path that anchors existing receipts.
+- Touches `@claude-flow/security` (bundled) and `@claude-flow/cli`.