🌊 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(mcp): isolate and bound governance audit logs
Rudy Celeklia1013a79887d
diff --git a/docs/mcp-audit-retention.md b/docs/mcp-audit-retention.mdnew file mode 100644index 0000000000..06a59c04f7--- /dev/null+++ b/docs/mcp-audit-retention.md@@ -0,0 +1,47 @@+# MCP governance audit storage++With `RUFLO_MCP_ENFORCE_POLICY=1` and `auditLog: true` in+`.harness/mcp-policy.json`, stdio tool calls require a successful audit write.+The default log is now `.claude-flow/logs/mcp-audit.jsonl` under the server's+working directory, alongside the project whose policy is loaded. Each record+also includes `projectPath` so records remain attributable if explicitly routed+to a shared destination.++Set `RUFLO_MCP_AUDIT_LOG_PATH` on the server process to choose another destination.+Absolute paths are used directly; relative paths resolve against the server's+working directory. Missing parent directories are created. New directories use+mode `0700`, and new logs use `0600` on systems that support POSIX permissions;+existing permissions are not rewritten.++For example, preserve up to five rotated 10 MiB segments plus the active log:++```json+{+ "auditLog": true,+ "auditLogMaxBytes": 10485760,+ "auditLogMaxFiles": 5+}+```++These values are the defaults. `auditLogMaxBytes` must be a positive safe integer;+`auditLogMaxFiles` must be an integer from 1 through 100 and counts backups in+addition to the active log. Rotation occurs before appending a record that would+exceed the byte limit. `.1` is the newest backup; the highest configured segment+expires on rotation. Invalid settings, an oversized single record, or a failed+write/rotation deny the tool call under the existing fail-closed policy.++Writers sharing a path use an exclusive `<log>.lock` file around rotation and+append. Contention denies that call instead of racing an audit-file rename; a+caller can retry. A process crash can leave a stale lock. Stop all writers for+that path, inspect the failure, and remove the lock only after verifying that no+writer owns it. The implementation does not guess lock ownership or delete a+lock held by another process.++This is bounded local retention, not permanent archival or a tamper-evident log.+There is no age-based rotation. Reducing retention settings does not retroactively+resize existing segments or delete higher-numbered segments from an earlier+configuration. Archive or prune those separately while writers are stopped.+The old machine-wide temporary log is not migrated or deleted. Update log readers+to the project path or set the environment variable to an explicitly managed+path. Enforcement coverage is unchanged: this does not add governance enforcement+to HTTP/WebSocket dispatchers.diff --git a/v3/@claude-flow/cli/__tests__/mcp-audit-retention-3417.test.ts b/v3/@claude-flow/cli/__tests__/mcp-audit-retention-3417.test.tsnew file mode 100644index 0000000000..2b4b1b3e54--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/mcp-audit-retention-3417.test.ts@@ -0,0 +1,90 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';+import { appendAuditLog, evaluateToolCall, getAuditLogPath, resetPolicyEnforcerState, setAuditLogPathForTesting } from '../src/mcp-tools/policy-enforcer.js';++let project: string;+const entry = (id: number) => ({ timestamp: '2026-09-26T00:00:00.000Z', sessionId: 's', toolName: `tool_${id}`, allowed: true });+const records = (file: string) => fs.readFileSync(file, 'utf8').trim().split('\n').map(line => JSON.parse(line));+beforeEach(() => {+ project = fs.mkdtempSync(path.join(os.tmpdir(), 'ruflo-audit-retention-'));+ vi.spyOn(process, 'cwd').mockReturnValue(project);+ // Isolate the legacy tmpdir destination as well when running the negative control.+ vi.stubEnv('TMPDIR', project);+ vi.stubEnv('TMP', project);+ vi.stubEnv('TEMP', project);+ vi.stubEnv('RUFLO_MCP_AUDIT_LOG_PATH', '');+ setAuditLogPathForTesting(null);+ resetPolicyEnforcerState();+});+afterEach(() => {+ setAuditLogPathForTesting(null);+ vi.unstubAllEnvs();+ vi.restoreAllMocks();+ fs.rmSync(project, { recursive: true, force: true });+});++describe('project audit retention (#3417)', () => {+ it('isolates default logs by project instead of using a global temporary file', () => {+ const first = getAuditLogPath();+ expect(first).toBe(path.join(project, '.claude-flow/logs/mcp-audit.jsonl'));+ vi.mocked(process.cwd).mockReturnValue(path.join(project, 'second'));+ expect(getAuditLogPath()).not.toBe(first);+ });+ it.each(['audit/events.jsonl', '/explicit/audit/events.jsonl'])('resolves a deployment path: %s', configured => {+ vi.stubEnv('RUFLO_MCP_AUDIT_LOG_PATH', configured);+ expect(getAuditLogPath()).toBe(path.resolve(project, configured));+ });+ it('creates the configured parent and records the project with private permissions', () => {+ vi.stubEnv('RUFLO_MCP_AUDIT_LOG_PATH', 'custom/events.jsonl');+ expect(appendAuditLog({ auditLog: true }, entry(1))).toBe(true);+ const file = getAuditLogPath();+ expect(records(file)[0]).toMatchObject({ ...entry(1), projectPath: project });+ if (process.platform !== 'win32') expect(fs.statSync(file).mode & 0o777).toBe(0o600);+ });+ it('rotates before exceeding the byte bound and retains only the configured backups', () => {+ const bytes = Buffer.byteLength(JSON.stringify({ ...entry(1), projectPath: project }) + '\n');+ const policy = { auditLog: true, auditLogMaxBytes: bytes + 1, auditLogMaxFiles: 2 };+ for (let i = 1; i <= 6; i++) expect(appendAuditLog(policy, entry(i))).toBe(true);+ const file = getAuditLogPath();+ expect(records(file)[0].toolName).toBe('tool_6');+ expect(records(`${file}.1`)[0].toolName).toBe('tool_5');+ expect(records(`${file}.2`)[0].toolName).toBe('tool_4');+ expect(fs.existsSync(`${file}.3`)).toBe(false);+ for (const candidate of [file, `${file}.1`, `${file}.2`]) expect(fs.statSync(candidate).size).toBeLessThanOrEqual(policy.auditLogMaxBytes);+ });+ it.each([{ auditLogMaxBytes: 0 }, { auditLogMaxBytes: 1.5 }, { auditLogMaxFiles: -1 }, { auditLogMaxFiles: 101 }])('fails closed for invalid retention settings %o', invalid => {+ expect(evaluateToolCall({ auditLog: true, ...invalid }, 's', 'tool').allowed).toBe(false);+ });+ it('denies an oversized record without deleting previous audit evidence', () => {+ expect(appendAuditLog({ auditLog: true }, entry(1))).toBe(true);+ const before = fs.readFileSync(getAuditLogPath());+ expect(evaluateToolCall({ auditLog: true, auditLogMaxBytes: 1 }, 's', 'tool').allowed).toBe(false);+ expect(fs.readFileSync(getAuditLogPath())).toEqual(before);+ });+ it('fails closed on lock contention without removing the other writer lock', () => {+ expect(appendAuditLog({ auditLog: true }, entry(1))).toBe(true);+ const file = getAuditLogPath();+ fs.writeFileSync(`${file}.lock`, 'other writer');+ const before = fs.readFileSync(file);+ expect(evaluateToolCall({ auditLog: true }, 's', 'tool').allowed).toBe(false);+ expect(fs.readFileSync(file)).toEqual(before);+ expect(fs.readFileSync(`${file}.lock`, 'utf8')).toBe('other writer');+ });+ it('preserves evidence and releases its lock after a rotation failure', () => {+ expect(appendAuditLog({ auditLog: true }, entry(1))).toBe(true);+ const file = getAuditLogPath();+ const before = fs.readFileSync(file);+ fs.mkdirSync(`${file}.1`);+ expect(evaluateToolCall({ auditLog: true, auditLogMaxBytes: before.length + 1 }, 's', 'tool').allowed).toBe(false);+ expect(fs.readFileSync(file)).toEqual(before);+ expect(fs.existsSync(`${file}.lock`)).toBe(false);+ fs.rmdirSync(`${file}.1`);+ expect(appendAuditLog({ auditLog: true }, entry(2))).toBe(true);+ });+ it('does no filesystem work when auditing is disabled', () => {+ expect(appendAuditLog({ auditLog: false, auditLogMaxBytes: -1 }, entry(1))).toBe(true);+ expect(fs.readdirSync(project)).toEqual([]);+ });+});diff --git a/v3/@claude-flow/cli/__tests__/mcp-policy-enforcer.test.ts b/v3/@claude-flow/cli/__tests__/mcp-policy-enforcer.test.tsindex 71829706ba..57cfc95bc7 100644--- a/v3/@claude-flow/cli/__tests__/mcp-policy-enforcer.test.ts+++ b/v3/@claude-flow/cli/__tests__/mcp-policy-enforcer.test.ts@@ -271,8 +271,8 @@ describe('evaluateToolCall — single enforcement entry point (fail-closed)', ()describe('getAuditLogPath', () => {afterEach(() => setAuditLogPathForTesting(null));- it('defaults to a path under the OS tmpdir', () => {- expect(getAuditLogPath().startsWith(os.tmpdir())).toBe(true);+ it('defaults to the current project log directory', () => {+ expect(getAuditLogPath()).toBe(path.join(process.cwd(), '.claude-flow', 'logs', 'mcp-audit.jsonl'));});});diff --git a/v3/@claude-flow/cli/scripts/test-mcp-policy-stdio.mjs b/v3/@claude-flow/cli/scripts/test-mcp-policy-stdio.mjsindex 88cab2d1c4..e500fc5b4b 100644--- a/v3/@claude-flow/cli/scripts/test-mcp-policy-stdio.mjs+++ b/v3/@claude-flow/cli/scripts/test-mcp-policy-stdio.mjs@@ -27,7 +27,7 @@ export async function callMCPTool(name) {}`;-async function runSession(entry, { policy, enforce = true, calls = 1, badAuditPath = false }) {+async function runSession(entry, { policy, enforce = true, calls = 1, badAuditPath = false, customAuditPath = false }) {const project = mkdtempSync(join(tmpdir(), 'ruflo-stdio-policy-'));let child;try {@@ -44,12 +44,14 @@ async function runSession(entry, { policy, enforce = true, calls = 1, badAuditPawriteFileSync(join(project, '.harness/mcp-policy.json'), policy);}+ const configuredAudit = customAuditPath ? 'custom/audit.jsonl' : '';+ if (badAuditPath) writeFileSync(join(project, 'audit-parent-file'), 'not a directory');child = spawn(process.execPath, [join(bin, entry), ...(entry === 'cli.js' ? ['mcp', 'start'] : [])], {cwd: project,env: {...process.env,RUFLO_MCP_ENFORCE_POLICY: enforce ? '1' : '0',- TMPDIR: badAuditPath ? join(project, 'unwritable-audit-dir') : project,+ RUFLO_MCP_AUDIT_LOG_PATH: badAuditPath ? join(project, 'audit-parent-file/log.jsonl') : configuredAudit,},stdio: ['pipe', 'pipe', 'pipe'],});@@ -80,9 +82,10 @@ async function runSession(entry, { policy, enforce = true, calls = 1, badAuditPachild.stdin.end();assert.equal(await closed, 0, `${entry} exited abnormally: ${stderr}`);const executionsPath = join(project, 'executions.txt');- const auditPath = join(project, 'ruflo-mcp-audit.jsonl');+ const auditPath = join(project, configuredAudit || '.claude-flow/logs/mcp-audit.jsonl');return {responses,+ segments: [auditPath, `${auditPath}.1`, `${auditPath}.2`, `${auditPath}.3`].filter(existsSync).map(file => ({ path: file, bytes: Buffer.byteLength(readFileSync(file)), records: readFileSync(file, 'utf8').trim().split('\n').map(JSON.parse) })),executions: existsSync(executionsPath) ? readFileSync(executionsPath, 'utf8').trim().split('\n') : [],audit: existsSync(auditPath) ? readFileSync(auditPath, 'utf8').trim().split('\n').map(JSON.parse) : [],};@@ -120,6 +123,14 @@ for (const entry of ['cli.js', 'mcp-server.js']) {assert.deepEqual(result.audit.map(record => record.allowed), [true, false]);});+ test(`${entry}: configured audit logs rotate in a real stdio session`, async () => {+ const result = await runSession(entry, { policy: JSON.stringify({ auditLog: true, auditLogMaxBytes: 512, auditLogMaxFiles: 2 }), calls: 10, customAuditPath: true });+ assert.equal(result.executions.length, 10);+ assert.equal(result.segments.length, 3);+ assert.ok(result.segments.every(segment => segment.bytes <= 512));+ assert.ok(result.segments.every(segment => segment.records.every(record => record.projectPath && record.allowed)));+ });+test(`${entry}: mandatory audit failure denies before execution`, async () => {const result = await runSession(entry, {policy: JSON.stringify({ auditLog: true }), badAuditPath: true,diff --git a/v3/@claude-flow/cli/src/mcp-tools/policy-enforcer.ts b/v3/@claude-flow/cli/src/mcp-tools/policy-enforcer.tsindex bc03b99e8b..6838d7fdce 100644--- a/v3/@claude-flow/cli/src/mcp-tools/policy-enforcer.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/policy-enforcer.ts@@ -59,7 +59,6 @@import * as fs from 'fs';import * as path from 'path';-import * as os from 'os';export interface McpPolicy {schema?: number;@@ -67,6 +66,10 @@ export interface McpPolicy {harnessId?: string;defaultDeny?: boolean;auditLog?: boolean;+ /** Maximum bytes per audit segment. Default 10 MiB; oversized records fail closed. */+ auditLogMaxBytes?: number;+ /** Rotated segments retained in addition to the active log. Default 5, maximum 100. */+ auditLogMaxFiles?: number;requireApprovalForDangerous?: boolean;toolTimeoutMs?: number;/**@@ -168,6 +171,7 @@ export interface AuditLogEntry {toolName: string;allowed: boolean;reason?: string;+ projectPath?: string;}let auditLogPathOverride: string | null = null;@@ -178,7 +182,10 @@ export function setAuditLogPathForTesting(p: string | null): void {}function defaultAuditLogPath(): string {- return path.join(os.tmpdir(), 'ruflo-mcp-audit.jsonl');+ const configured = process.env.RUFLO_MCP_AUDIT_LOG_PATH;+ return configured+ ? path.resolve(process.cwd(), configured)+ : path.join(process.cwd(), '.claude-flow', 'logs', 'mcp-audit.jsonl');}export function getAuditLogPath(): string {@@ -195,8 +202,52 @@ export function getAuditLogPath(): string {export function appendAuditLog(policy: McpPolicy, entry: AuditLogEntry): boolean {if (!policy.auditLog) return true;try {- fs.appendFileSync(getAuditLogPath(), `${JSON.stringify(entry)}\n`, 'utf-8');- return true;+ const maxBytes = policy.auditLogMaxBytes ?? 10 * 1024 * 1024;+ const maxFiles = policy.auditLogMaxFiles ?? 5;+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0 ||+ !Number.isSafeInteger(maxFiles) || maxFiles < 1 || maxFiles > 100) return false;+ const line = `${JSON.stringify({ ...entry, projectPath: path.resolve(process.cwd()) })}\n`;+ const bytes = Buffer.byteLength(line, 'utf8');+ if (bytes > maxBytes) return false;++ const logPath = getAuditLogPath();+ fs.mkdirSync(path.dirname(logPath), { recursive: true, mode: 0o700 });+ // All writers of a configured path serialize rotation AND append. On+ // contention (or a stale lock after a crash), deny rather than lose audit+ // evidence by racing a rename. Only the lock owner removes its lock.+ const lockPath = `${logPath}.lock`;+ const lock = fs.openSync(lockPath, 'wx', 0o600);+ try {+ let size = 0;+ try {+ const stat = fs.lstatSync(logPath);+ if (!stat.isFile()) throw new Error('Audit log is not a regular file');+ size = stat.size;+ }+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }+ if (size + bytes > maxBytes) {+ // Validate the entire chain before moving or expiring any evidence.+ for (let index = 1; index <= maxFiles; index++) {+ try { if (!fs.lstatSync(`${logPath}.${index}`).isFile()) throw new Error('Audit segment is not a regular file'); }+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }+ }+ for (let index = maxFiles; index >= 1; index--) {+ const source = index === 1 ? logPath : `${logPath}.${index - 1}`;+ const target = `${logPath}.${index}`;+ if (index === maxFiles) {+ try { fs.unlinkSync(target); }+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }+ }+ try { fs.renameSync(source, target); }+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }+ }+ }+ fs.appendFileSync(logPath, line, { encoding: 'utf8', mode: 0o600 });+ return true;+ } finally {+ fs.closeSync(lock);+ fs.unlinkSync(lockPath);+ }} catch {return false;}