🌊 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
feat(flywheel): implement ADR-322 promotion loop (#2817)
rUv0e3d412756d7
diff --git a/package.json b/package.jsonindex 78a788541a..8b00c9af40 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "claude-flow",- "version": "3.32.25",+ "version": "3.32.26","description": "Ruflo - Enterprise AI agent orchestration for Claude Code. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration","main": "dist/index.js","type": "module",diff --git a/ruflo/package.json b/ruflo/package.jsonindex a75b035063..23b6c10c79 100644--- a/ruflo/package.json+++ b/ruflo/package.json@@ -1,6 +1,6 @@{"name": "ruflo",- "version": "3.32.25",+ "version": "3.32.26","description": "Ruflo - Enterprise AI agent orchestration platform. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration","main": "bin/ruflo.js","type": "module",diff --git a/scripts/check-metaharness-pins.mjs b/scripts/check-metaharness-pins.mjsindex 6163a963b7..cb48d38091 100644--- a/scripts/check-metaharness-pins.mjs+++ b/scripts/check-metaharness-pins.mjs@@ -29,7 +29,7 @@import { readFileSync } from 'node:fs';import { execFileSync } from 'node:child_process';-import { fileURLToPath } from 'node:url';+import { fileURLToPath, pathToFileURL } from 'node:url';import { dirname, join } from 'node:path';const HERE = dirname(fileURLToPath(import.meta.url));@@ -37,10 +37,11 @@ const REPO = join(HERE, '..');const CLI_PKG = join(REPO, 'v3', '@claude-flow', 'cli', 'package.json');const DISTILL = join(REPO, 'v3', '@claude-flow', 'cli', 'src', 'services', 'distill-oracle.ts');-const ARGS = { format: 'table', offline: false };+const ARGS = { format: 'table', offline: false, requireInstalled: false };for (let i = 2; i < process.argv.length; i++) {if (process.argv[i] === '--format') ARGS.format = process.argv[++i];else if (process.argv[i] === '--offline') ARGS.offline = true;+ else if (process.argv[i] === '--require-installed') ARGS.requireInstalled = true;}/** Parse "1.2.3" → [1,2,3]; tolerant of pre-release/build suffixes. */@@ -78,6 +79,7 @@ async function main() {{ name: 'metaharness', range: pkg.dependencies?.metaharness, where: 'dependencies' },{ name: '@metaharness/router', range: pkg.dependencies?.['@metaharness/router'], where: 'dependencies' },{ name: '@metaharness/darwin', range: pkg.optionalDependencies?.['@metaharness/darwin'], where: 'optionalDependencies' },+ { name: '@metaharness/flywheel', range: pkg.optionalDependencies?.['@metaharness/flywheel'], where: 'optionalDependencies' },];const rows = [];@@ -104,8 +106,33 @@ async function main() {const stale = rows.filter((r) => r.status === 'STALE');const constBad = constRow && constRow.status === 'OUT-OF-RANGE';- const drift = stale.length > 0 || constBad;- const payload = { generatedAt: new Date().toISOString(), drift, pins: rows, constCheck: constRow };+ const apiErrors = [];+ if (ARGS.requireInstalled) {+ const cliDir = dirname(CLI_PKG);+ try {+ const darwin = await import(pathToFileURL(join(cliDir, 'node_modules/@metaharness/darwin/dist/index.js')).href);+ if (typeof darwin.evolve !== 'function') apiErrors.push('@metaharness/darwin must export evolve');+ } catch (error) {+ apiErrors.push(`@metaharness/darwin import failed: ${error.message}`);+ }+ try {+ const flywheel = await import(pathToFileURL(join(cliDir, 'node_modules/@metaharness/flywheel/dist/index.js')).href);+ for (const symbol of ['runFlywheelGenerations', 'meetsPromotionRule', 'makeSigner', 'verifyReplayBundle']) {+ if (typeof flywheel[symbol] !== 'function') apiErrors.push(`@metaharness/flywheel must export ${symbol}`);+ }+ } catch (error) {+ apiErrors.push(`@metaharness/flywheel import failed: ${error.message}`);+ }+ }+ const drift = stale.length > 0 || constBad || apiErrors.length > 0;+ const payload = {+ generatedAt: new Date().toISOString(),+ drift,+ pins: rows,+ constCheck: constRow,+ installedApiChecked: ARGS.requireInstalled,+ apiErrors,+ };if (ARGS.format === 'json') {console.log(JSON.stringify(payload, null, 2));@@ -115,6 +142,7 @@ async function main() {console.log('|---|---|---|---|');for (const r of rows) console.log(`| ${r.name} | ${r.range ?? '—'} | ${r.latest ?? '—'} | ${r.status} |`);if (constRow) console.log(`| ${constRow.name} | =${constRow.pin} (vs ${constRow.declared}) | — | ${constRow.status} |`);+ if (ARGS.requireInstalled) console.log(`\nInstalled API check: ${apiErrors.length ? `FAIL — ${apiErrors.join('; ')}` : 'PASS'}`);console.log('');if (drift) {console.log('⚠**Pin drift detected.** One or more metaharness pins no longer admit the current npm release.');diff --git a/v3/@claude-flow/cli/__tests__/flywheel-proposer.test.ts b/v3/@claude-flow/cli/__tests__/flywheel-proposer.test.tsnew file mode 100644index 0000000000..1cd4d8f877--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/flywheel-proposer.test.ts@@ -0,0 +1,130 @@+import { describe, expect, it } from 'vitest';+import {+ DarwinUnavailableError,+ proposeFlywheelCandidates,+ type SafetyEnvelope,+} from '../src/services/flywheel-proposer.js';++const envelope: SafetyEnvelope = {+ ref: 'sha256:safety',+ allowedPolicyKeys: ['alpha'],+ numericBounds: { alpha: { min: 0.1, max: 0.9 } },+ maxP95LatencyMicros: 10_000,+ maxCostMicrosPerTask: 100,+ maxTokensPerTask: 1_000,+ maxFailureRate: 0.01,+ maxEvaluationCostMicros: 10_000,+};+const resources = {+ p95LatencyMicros: 1_000,+ costMicrosPerTask: 10,+ tokensPerTask: 100,+ failureRate: 0,+ evaluationCostMicros: 1_000,+};+const localProposer = () => [+ { policy: { alpha: 0.3 }, resources },+ { policy: { alpha: 1.2 }, resources: { ...resources, p95LatencyMicros: 20_000 } },+];++describe('flywheel proposer adapter', () => {+ it('applies hard admissibility constraints before archive selection', async () => {+ const archive = await proposeFlywheelCandidates({+ mode: 'local',+ baselinePolicy: { alpha: 0.5 },+ safetyEnvelope: envelope,+ seed: 42,+ localProposer,+ });+ expect(archive.candidates).toHaveLength(2);+ expect(archive.admissibleCandidates).toHaveLength(1);+ expect(archive.paretoCandidates).toHaveLength(1);+ expect(archive.candidates[1].rejectionReasons).toEqual(expect.arrayContaining([+ 'alpha above maximum',+ 'p95 latency exceeds envelope',+ ]));+ });++ it('keeps only non-dominated admissible policies on the Pareto frontier', async () => {+ const archive = await proposeFlywheelCandidates({+ mode: 'local',+ baselinePolicy: { alpha: 0.5 },+ safetyEnvelope: envelope,+ seed: 42,+ localProposer: () => [+ { policy: { alpha: 0.3 }, score: 0.8, resources },+ {+ policy: { alpha: 0.4 },+ score: 0.7,+ resources: { ...resources, p95LatencyMicros: 2_000, costMicrosPerTask: 20 },+ },+ {+ policy: { alpha: 0.2 },+ score: 0.9,+ resources: { ...resources, costMicrosPerTask: 30 },+ },+ ],+ });+ expect(archive.admissibleCandidates).toHaveLength(3);+ expect(archive.paretoCandidates.map((candidate) => candidate.policy.alpha)).toEqual([0.3, 0.2]);+ });++ it('fails closed when Darwin is explicitly requested and unavailable', async () => {+ await expect(proposeFlywheelCandidates({+ mode: 'darwin',+ baselinePolicy: { alpha: 0.5 },+ safetyEnvelope: envelope,+ seed: 42,+ localProposer,+ })).rejects.toBeInstanceOf(DarwinUnavailableError);+ });++ it('marks auto fallback as evaluation-only unless substitution promotion is explicitly allowed', async () => {+ const archive = await proposeFlywheelCandidates({+ mode: 'auto',+ baselinePolicy: { alpha: 0.5 },+ safetyEnvelope: envelope,+ seed: 42,+ localProposer,+ });+ expect(archive).toMatchObject({+ effectiveProposer: 'local',+ proposerSubstitution: 'darwin-unavailable',+ promotionAllowed: false,+ });+ });++ it('records completed Darwin output while still rejecting inadmissible candidates', async () => {+ const archive = await proposeFlywheelCandidates({+ mode: 'darwin',+ baselinePolicy: { alpha: 0.5 },+ safetyEnvelope: envelope,+ seed: 42,+ localProposer,+ darwinInvoker: async () => ({+ completed: true,+ candidates: [{ policy: { networkAccess: true }, resources }],+ }),+ });+ expect(archive.effectiveProposer).toBe('darwin');+ expect(archive.admissibleCandidates).toHaveLength(0);+ expect(archive.candidates[0].rejectionReasons).toContain('policy key not allowed: networkAccess');+ });++ it('enforces aggregate Darwin budget even when the invoker ignores it', async () => {+ await expect(proposeFlywheelCandidates({+ mode: 'darwin',+ baselinePolicy: { alpha: 0.5 },+ safetyEnvelope: { ...envelope, maxEvaluationCostMicros: 1_500 },+ seed: 42,+ localProposer,+ darwinInvoker: async () => ({+ completed: true,+ candidates: [+ { policy: { alpha: 0.3 }, resources },+ { policy: { alpha: 0.4 }, resources },+ ],+ }),+ })).rejects.toThrow(/evaluation-cost budget/);+ });+});diff --git a/v3/@claude-flow/cli/__tests__/flywheel-receipt.test.ts b/v3/@claude-flow/cli/__tests__/flywheel-receipt.test.tsnew file mode 100644index 0000000000..e388dd2c8b--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/flywheel-receipt.test.ts@@ -0,0 +1,100 @@+import { describe, expect, it } from 'vitest';+import { generateKeyPairSync } from 'node:crypto';+import {+ GENESIS_LEDGER_HEAD,+ canonicalizeJcs,+ createFlywheelReceipt,+ policyCandidateId,+ verifyFlywheelReceipt,+} from '../src/services/flywheel-receipt.js';++function keys() {+ const pair = generateKeyPairSync('ed25519');+ return {+ privateKeyPem: pair.privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(),+ publicKeyPem: pair.publicKey.export({ type: 'spki', format: 'pem' }).toString(),+ };+}++function acceptedReceipt(key = keys(), now = 1_700_000_000_000) {+ return {+ key,+ receipt: createFlywheelReceipt({+ baselineRef: policyCandidateId({ alpha: 0.5 }),+ expectedLedgerHead: GENESIS_LEDGER_HEAD,+ candidatePolicy: { alpha: 0.3 },+ safetyEnvelopeRef: 'sha256:safety',+ corpusVersion: 'corpus-v1',+ corpusHash: 'sha256:corpus',+ baselineScore: 0.5,+ candidateScore: 0.65,+ heldOutDeltas: [0.1, 0.12, 0.2, 0.08, 0.15, 0.11],+ frozenAnchorRegression: 0,+ gates: { heldOut: true, redblue: true, replay: true },+ now,+ bootstrapIterations: 1_000,+ ...key,+ }),+ };+}++describe('flywheel receipt protocol', () => {+ it('uses deterministic canonical JSON and rejects ambiguous numeric values', () => {+ expect(canonicalizeJcs({ z: 1, a: { c: 2, b: 1 } })).toBe('{"a":{"b":1,"c":2},"z":1}');+ expect(() => canonicalizeJcs({ value: -0 })).toThrow(/non-canonical number/);+ expect(() => canonicalizeJcs({ value: Number.NaN })).toThrow(/non-canonical number/);+ });++ it('signs an accepted receipt and verifies only against an approved key', () => {+ const { key, receipt } = acceptedReceipt();+ expect(receipt.payload.decision).toBe('accepted');+ expect(verifyFlywheelReceipt(receipt, new Set([key.publicKeyPem]))).toEqual({+ valid: true,+ signed: true,+ errors: [],+ });+ expect(verifyFlywheelReceipt(receipt, new Set([keys().publicKeyPem])).errors).toContain('receipt signer is not trusted');+ });++ it('detects one-byte-equivalent content changes and separates run identity from policy identity', () => {+ const { key, receipt } = acceptedReceipt();+ const tampered = structuredClone(receipt);+ tampered.payload.candidatePolicy.alpha = 0.31;+ expect(verifyFlywheelReceipt(tampered, new Set([key.publicKeyPem])).valid).toBe(false);++ const second = acceptedReceipt(key, 1_700_000_000_001).receipt;+ expect(second.payload.candidateId).toBe(receipt.payload.candidateId);+ expect(second.payload.evaluationRunId).not.toBe(receipt.payload.evaluationRunId);+ expect(second.payload.receiptId).not.toBe(receipt.payload.receiptId);+ });++ it('recomputes the statistical verdict instead of trusting signed fields', () => {+ const { key, receipt } = acceptedReceipt();+ const forged = structuredClone(receipt);+ forged.payload.statistics.relativeLift = '99';+ expect(verifyFlywheelReceipt(forged, new Set([key.publicKeyPem])).errors).toContain(+ 'statistical decision does not recompute',+ );+ });++ it('rejects small relative lifts even when every held-out delta is positive', () => {+ const { privateKeyPem, publicKeyPem } = keys();+ const receipt = createFlywheelReceipt({+ baselineRef: policyCandidateId({ alpha: 0.5 }),+ candidatePolicy: { alpha: 0.49 },+ safetyEnvelopeRef: 'sha256:safety',+ corpusVersion: 'corpus-v1',+ corpusHash: 'sha256:corpus',+ baselineScore: 1,+ candidateScore: 1.01,+ heldOutDeltas: [0.01, 0.01, 0.01, 0.01],+ frozenAnchorRegression: 0,+ gates: { heldOut: true },+ bootstrapIterations: 500,+ privateKeyPem,+ publicKeyPem,+ });+ expect(receipt.payload.statistics.significant).toBe(true);+ expect(receipt.payload.decision).toBe('rejected');+ });+});diff --git a/v3/@claude-flow/cli/__tests__/flywheel-transaction.test.ts b/v3/@claude-flow/cli/__tests__/flywheel-transaction.test.tsnew file mode 100644index 0000000000..49d92fa5a0--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/flywheel-transaction.test.ts@@ -0,0 +1,162 @@+import { describe, expect, it } from 'vitest';+import { generateKeyPairSync } from 'node:crypto';+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ createFlywheelReceipt,+ policyCandidateId,+} from '../src/services/flywheel-receipt.js';+import {+ promoteFlywheelCandidate,+ readFlywheelTransactionState,+ recoverFlywheelMaterialization,+ registerFlywheelReceipt,+ verifyFlywheelLedger,+} from '../src/services/flywheel-transaction.js';++function keyPair() {+ const pair = generateKeyPairSync('ed25519');+ return {+ privateKeyPem: pair.privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(),+ publicKeyPem: pair.publicKey.export({ type: 'spki', format: 'pem' }).toString(),+ };+}++function makeReceipt(+ key: ReturnType<typeof keyPair>,+ over: Partial<Parameters<typeof createFlywheelReceipt>[0]> = {},+) {+ return createFlywheelReceipt({+ baselineRef: policyCandidateId({ alpha: 0.5 }),+ candidatePolicy: { alpha: 0.3 },+ safetyEnvelopeRef: 'sha256:safety-envelope-v1',+ corpusVersion: 'corpus-v1',+ corpusHash: 'sha256:corpus-v1',+ baselineScore: 0.5,+ candidateScore: 0.65,+ heldOutDeltas: [0.1, 0.12, 0.2, 0.08, 0.15, 0.11],+ frozenAnchorRegression: 0,+ gates: { heldOut: true, redblue: true, replay: true },+ termVerification: ['heldOut', 'redblue', 'replay'].map((term) => ({+ term,+ verification: 'recomputed' as const,+ evidenceRef: `sha256:${term}`,+ })),+ now: 1_700_000_000_000,+ ttlMs: 1_000_000,+ bootstrapIterations: 500,+ ...key,+ ...over,+ });+}++const apply = () => ({ applied: true, from: null, to: 'candidate' });++describe('flywheel promotion transaction', () => {+ it('commits exactly once under 100 concurrent promotion attempts', async () => {+ const root = mkdtempSync(join(tmpdir(), 'flywheel-cas-'));+ const key = keyPair();+ const receipt = makeReceipt(key);+ await registerFlywheelReceipt(root, receipt, 1_700_000_000_001);++ const results = await Promise.all(Array.from({ length: 100 }, () =>+ promoteFlywheelCandidate(root, receipt.payload.receiptId, {+ confirm: true,+ now: 1_700_000_000_100,+ trustedPublicKeys: new Set([key.publicKeyPem]),+ applyFn: apply,+ }),+ ));++ expect(results.filter((result) => result.success && !result.idempotent)).toHaveLength(1);+ expect(results.every((result) => result.success)).toBe(true);+ const state = readFlywheelTransactionState(root);+ expect(state.commits).toHaveLength(1);+ expect(state.activeChampionRef).toBe(receipt.payload.candidateId);+ expect(state.servingEpoch).toBe(1);+ expect(state.materializedServingEpoch).toBe(1);+ expect(verifyFlywheelLedger(root)).toMatchObject({ valid: true, commits: 1 });+ });++ it('requires explicit signer trust and rejects stale baselines', async () => {+ const root = mkdtempSync(join(tmpdir(), 'flywheel-trust-'));+ const key = keyPair();+ const first = makeReceipt(key);+ await registerFlywheelReceipt(root, first);+ expect((await promoteFlywheelCandidate(root, first.payload.receiptId, {+ confirm: true,+ now: 1_700_000_000_100,+ applyFn: apply,+ })).reason).toMatch(/trusted receipt signer/);++ const promoted = await promoteFlywheelCandidate(root, first.payload.receiptId, {+ confirm: true,+ now: 1_700_000_000_100,+ trustedPublicKeys: new Set([key.publicKeyPem]),+ applyFn: apply,+ });+ expect(promoted.success).toBe(true);++ const stale = makeReceipt(key, {+ evaluationRunId: '01900000-0000-7000-8000-000000000002',+ candidatePolicy: { alpha: 0.2 },+ });+ await registerFlywheelReceipt(root, stale);+ const rejected = await promoteFlywheelCandidate(root, stale.payload.receiptId, {+ confirm: true,+ now: 1_700_000_000_200,+ trustedPublicKeys: new Set([key.publicKeyPem]),+ applyFn: apply,+ });+ expect(rejected).toMatchObject({ success: false, reason: 'stale baseline' });+ });++ it('rejects an accepted receipt whose promotion gate lacks classified evidence', async () => {+ const root = mkdtempSync(join(tmpdir(), 'flywheel-evidence-'));+ const key = keyPair();+ const receipt = makeReceipt(key, { termVerification: [] });+ await registerFlywheelReceipt(root, receipt);+ const rejected = await promoteFlywheelCandidate(root, receipt.payload.receiptId, {+ confirm: true,+ now: 1_700_000_000_100,+ trustedPublicKeys: new Set([key.publicKeyPem]),+ applyFn: apply,+ });+ expect(rejected.reason).toMatch(/missing verification for gate/);+ expect(readFlywheelTransactionState(root).commits).toHaveLength(0);+ });++ it('recovers consistently from faults before and after the atomic commit', async () => {+ const root = mkdtempSync(join(tmpdir(), 'flywheel-fault-'));+ const key = keyPair();+ const receipt = makeReceipt(key);+ await registerFlywheelReceipt(root, receipt);+ const common = {+ confirm: true,+ now: 1_700_000_000_100,+ trustedPublicKeys: new Set([key.publicKeyPem]),+ applyFn: apply,+ };++ await expect(promoteFlywheelCandidate(root, receipt.payload.receiptId, {+ ...common,+ faultAt: 'before-commit',+ })).rejects.toThrow(/before-commit/);+ expect(readFlywheelTransactionState(root).commits).toHaveLength(0);++ await expect(promoteFlywheelCandidate(root, receipt.payload.receiptId, {+ ...common,+ faultAt: 'after-commit-before-materialize',+ })).rejects.toThrow(/after-commit/);+ let state = readFlywheelTransactionState(root);+ expect(state.commits).toHaveLength(1);+ expect(state.materializedServingEpoch).toBe(0);++ const recovered = await recoverFlywheelMaterialization(root, common);+ expect(recovered).toMatchObject({ success: true, materialized: true });+ state = readFlywheelTransactionState(root);+ expect(state.materializedServingEpoch).toBe(state.servingEpoch);+ expect(verifyFlywheelLedger(root).valid).toBe(true);+ });+});diff --git a/v3/@claude-flow/cli/__tests__/harness-flywheel.test.ts b/v3/@claude-flow/cli/__tests__/harness-flywheel.test.tsindex 40160a41e0..f2424748b9 100644--- a/v3/@claude-flow/cli/__tests__/harness-flywheel.test.ts+++ b/v3/@claude-flow/cli/__tests__/harness-flywheel.test.ts@@ -132,16 +132,18 @@ function makeDeps(now: number, activeParams: () => Partial<{ alpha: number }> |}describe('runFlywheelTick', () => {- it('LEARNS: a lower-alpha neighbor improves the anchor without regressing the guard → applied + proven', async () => {+ it('LEARNS: evaluation emits proof without mutating the active champion', async () => {const cwd = mkdtempSync(join(tmpdir(), 'fw-'));const r = await runFlywheelTick(cwd, makeDeps(1000));expect(r.ran).toBe(true);expect(r.accepted).toBe(true);- expect(r.applied).toBe(true);+ expect(r.applied).toBe(false);expect(r.anchorRegressed).toBe(false); // guard heldexpect(r.candidateScore!).toBeGreaterThan(r.baselineScore!); // real improvement- // the champion is live AND the proof ledger recorded a significant, accepted entry.- expect((activeChampion(cwd)?.params as { alpha: number }).alpha).toBeLessThanOrEqual(0.4);+ expect(activeChampion(cwd)).toBeNull();+ expect(r.receiptId).toMatch(/^sha256:[a-f0-9]{64}$/);+ expect(r.receipt?.payload.decision).toBe('accepted');+ expect(r.promotable).toBe(false); // unsigned local evaluation cannot promoteconst led = readLedger(join(cwd, '.claude-flow', 'metrics'));expect(led.length).toBe(1);expect(led[0].accepted).toBe(true);@@ -149,6 +151,21 @@ describe('runFlywheelTick', () => {expect(led[0].deltaCILow!).toBeGreaterThan(0);});+ it('retains implicit mutation for one compatibility cycle only behind an explicit flag', async () => {+ const cwd = mkdtempSync(join(tmpdir(), 'fw-'));+ const prior = process.env.RUFLO_FLYWHEEL_LEGACY_APPLY;+ process.env.RUFLO_FLYWHEEL_LEGACY_APPLY = '1';+ try {+ const r = await runFlywheelTick(cwd, makeDeps(1000));+ expect(r.applied).toBe(true);+ expect(r.legacyDeprecation).toBe(true);+ expect((activeChampion(cwd)?.params as { alpha: number }).alpha).toBeLessThanOrEqual(0.4);+ } finally {+ if (prior === undefined) delete process.env.RUFLO_FLYWHEEL_LEGACY_APPLY;+ else process.env.RUFLO_FLYWHEEL_LEGACY_APPLY = prior;+ }+ });+it('records the attempt even on a no-op (proof surface is always written)', async () => {const cwd = mkdtempSync(join(tmpdir(), 'fw-'));// start already at the optimum (alpha 0.3) → no neighbor improves → honest refuse.diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.jsonindex 09d4b00e83..db9e19a28a 100644--- a/v3/@claude-flow/cli/package.json+++ b/v3/@claude-flow/cli/package.json@@ -1,6 +1,6 @@{"name": "@claude-flow/cli",- "version": "3.32.25",+ "version": "3.32.26","type": "module","description": "Ruflo CLI - Enterprise AI agent orchestration with 60+ specialized agents, swarm coordination, MCP server, self-learning hooks, and vector memory for Claude Code","main": "dist/src/index.js",@@ -86,6 +86,7 @@],"scripts": {"build": "tsc",+ "check:metaharness-pins": "node ../../../scripts/check-metaharness-pins.mjs","test": "vitest run","test:plugin-store": "npx tsx src/plugins/tests/standalone-test.ts","test:pattern-store": "npx tsx src/transfer/store/tests/standalone-test.ts",@@ -116,6 +117,7 @@"@claude-flow/memory": "^3.0.0-alpha.21","@claude-flow/security": "^3.0.0-alpha.12","@metaharness/darwin": "^0.8.0",+ "@metaharness/flywheel": "^0.1.7","agentdb": "^3.0.0-alpha.17","agentic-flow": "^3.0.0-alpha.1","better-sqlite3": "^12.9.0",diff --git a/v3/@claude-flow/cli/scripts/benchmark-flywheel.mjs b/v3/@claude-flow/cli/scripts/benchmark-flywheel.mjsnew file mode 100644index 0000000000..1d3f02a35d--- /dev/null+++ b/v3/@claude-flow/cli/scripts/benchmark-flywheel.mjs@@ -0,0 +1,91 @@+#!/usr/bin/env node+/**+ * ADR-322 repeatable microbenchmark.+ *+ * Run after `pnpm build`:+ * node scripts/benchmark-flywheel.mjs+ */+import { generateKeyPairSync } from 'node:crypto';+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { performance } from 'node:perf_hooks';+import {+ computePromotionStatistics,+ createFlywheelReceipt,+ policyCandidateId,+} from '../dist/src/services/flywheel-receipt.js';+import {+ promoteFlywheelCandidate,+ registerFlywheelReceipt,+ verifyFlywheelLedger,+} from '../dist/src/services/flywheel-transaction.js';++const rounds = Number(process.env.FLYWHEEL_BENCH_ROUNDS || 250);+const deltas = [0.1, 0.12, 0.2, 0.08, 0.15, 0.11, 0.09, 0.13, 0.14, 0.07];+const statisticsStart = performance.now();+for (let i = 0; i < rounds; i++) {+ computePromotionStatistics({+ baselineScore: 0.5,+ candidateScore: 0.65,+ heldOutDeltas: deltas,+ frozenAnchorRegression: 0,+ corpusHash: 'sha256:benchmark-corpus',+ candidateId: 'sha256:benchmark-candidate',+ baselineRef: 'sha256:benchmark-baseline',+ evaluationRunId: `benchmark-${i}`,+ });+}+const statisticsMs = performance.now() - statisticsStart;++const pair = generateKeyPairSync('ed25519');+const privateKeyPem = pair.privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();+const publicKeyPem = pair.publicKey.export({ type: 'spki', format: 'pem' }).toString();+const root = mkdtempSync(join(tmpdir(), 'flywheel-benchmark-'));+const receipt = createFlywheelReceipt({+ baselineRef: policyCandidateId({ alpha: 0.5 }),+ candidatePolicy: { alpha: 0.3 },+ safetyEnvelopeRef: 'sha256:safety',+ corpusVersion: 'benchmark-v1',+ corpusHash: 'sha256:benchmark-corpus',+ baselineScore: 0.5,+ candidateScore: 0.65,+ heldOutDeltas: deltas,+ frozenAnchorRegression: 0,+ gates: { heldOut: true, redblue: true, replay: true },+ termVerification: ['heldOut', 'redblue', 'replay'].map((term) => ({+ term,+ verification: 'recomputed',+ evidenceRef: `sha256:${term}`,+ })),+ privateKeyPem,+ publicKeyPem,+});+await registerFlywheelReceipt(root, receipt);+const promotionStart = performance.now();+const promotions = await Promise.all(Array.from({ length: 100 }, () =>+ promoteFlywheelCandidate(root, receipt.payload.receiptId, {+ confirm: true,+ trustedPublicKeys: new Set([publicKeyPem]),+ applyFn: () => ({ applied: true }),+ }),+));+const promotionMs = performance.now() - promotionStart;+const ledger = verifyFlywheelLedger(root);++console.log(JSON.stringify({+ schema: 'ruflo.flywheel-benchmark/v1',+ node: process.version,+ statistics: {+ rounds,+ bootstrapIterationsPerRound: 10_000,+ totalMs: Number(statisticsMs.toFixed(3)),+ meanMs: Number((statisticsMs / rounds).toFixed(3)),+ },+ promotionContention: {+ attempts: promotions.length,+ commits: promotions.filter((result) => result.success && !result.idempotent).length,+ totalMs: Number(promotionMs.toFixed(3)),+ ledgerValid: ledger.valid,+ },+}, null, 2));diff --git a/v3/@claude-flow/cli/src/commands/metaharness.ts b/v3/@claude-flow/cli/src/commands/metaharness.tsindex 5406ff67d1..580eca1540 100644--- a/v3/@claude-flow/cli/src/commands/metaharness.ts+++ b/v3/@claude-flow/cli/src/commands/metaharness.ts@@ -37,9 +37,16 @@import type { Command, CommandContext, CommandResult } from '../types.js';import { output } from '../output.js';import { spawnSync } from 'child_process';-import { existsSync } from 'fs';+import { existsSync, readFileSync } from 'fs';import { join, dirname, resolve } from 'path';import { fileURLToPath } from 'url';+import { runFlywheelWorker } from '../services/harness-flywheel-runtime.js';+import {+ listFlywheelReceipts,+ promoteFlywheelCandidate,+ readFlywheelTransactionState,+ verifyFlywheelLedger,+} from '../services/flywheel-transaction.js';const __dirname = dirname(fileURLToPath(import.meta.url));@@ -69,8 +76,77 @@ const SUBCOMMANDS: Record<string, string> = {// @metaharness/[email protected] — GEPA library surface (genome ops; the// gepaOptimize loop itself stays library-only / behind evolve)gepa: 'gepa.mjs',+ // ADR-153 Darwin evolution and stable benchmark-corpus operations.+ evolve: 'evolve.mjs',+ bench: 'bench.mjs',+ // ADR-322 evaluation receipt + atomic promotion loop; handled in-process.+ flywheel: '__internal__',};+function flywheelFlag<T>(flags: Record<string, unknown>, name: string, fallback?: T): T | undefined {+ const value = flags[name];+ return (value === undefined ? fallback : value) as T | undefined;+}++async function dispatchFlywheel(+ operation: string | undefined,+ positional: string[],+ flags: Record<string, unknown>,+): Promise<CommandResult> {+ const projectRoot = resolve(String(flywheelFlag(flags, 'projectRoot', process.cwd())));+ let data: unknown;+ if (!operation || operation === 'status') {+ data = {+ state: readFlywheelTransactionState(projectRoot),+ ledger: verifyFlywheelLedger(projectRoot),+ };+ } else if (operation === 'run') {+ const privateKeyPath = flywheelFlag<string>(flags, 'privateKey');+ const publicKeyPath = flywheelFlag<string>(flags, 'publicKey');+ if (!!privateKeyPath !== !!publicKeyPath) {+ data = { success: false, reason: '--private-key and --public-key must be supplied together' };+ } else {+ data = await runFlywheelWorker(projectRoot, {+ optInOverride: true,+ sample: Number(flywheelFlag(flags, 'sample', 40)),+ proposer: String(flywheelFlag(flags, 'proposer', 'auto')) as 'auto' | 'local' | 'darwin',+ receiptPrivateKeyPem: privateKeyPath ? readFileSync(resolve(privateKeyPath), 'utf8') : undefined,+ receiptPublicKeyPem: publicKeyPath ? readFileSync(resolve(publicKeyPath), 'utf8') : undefined,+ });+ }+ } else if (operation === 'receipts') {+ data = listFlywheelReceipts(projectRoot).map(({ receipt, state }) => ({+ receiptId: receipt.payload.receiptId,+ candidateId: receipt.payload.candidateId,+ baselineRef: receipt.payload.baselineRef,+ decision: receipt.payload.decision,+ signed: !!receipt.signature,+ issuedAt: receipt.payload.issuedAt,+ state,+ }));+ } else if (operation === 'history') {+ const state = readFlywheelTransactionState(projectRoot);+ data = { ledgerHead: state.ledgerHead, commits: state.commits };+ } else if (operation === 'promote') {+ const receiptId = positional[0];+ const publicKeyPath = flywheelFlag<string>(flags, 'publicKey');+ if (!receiptId || !publicKeyPath) {+ data = { success: false, reason: 'promote requires <receipt-id> and --public-key <PEM path>' };+ } else {+ const publicKey = readFileSync(resolve(publicKeyPath), 'utf8');+ data = await promoteFlywheelCandidate(projectRoot, receiptId, {+ confirm: flywheelFlag<boolean>(flags, 'confirm', false) === true,+ trustedPublicKeys: new Set([publicKey]),+ });+ }+ } else {+ data = { success: false, reason: `unknown flywheel operation: ${operation}` };+ }+ output.writeln(JSON.stringify(data, null, 2));+ const success = !(data && typeof data === 'object' && (data as { success?: boolean }).success === false);+ return { success, exitCode: success ? 0 : 1, data };+}+/*** Walk up from the current dirname to find the ruflo repo root that* contains plugins/ruflo-metaharness/. Handles three install layouts:@@ -134,7 +210,7 @@ export const metaharnessCommand: Command = {// iter 73 — list reflects all dispatchable subcommands (was// stale at the iter-3 list of 5). Keep this synced with the// SUBCOMMANDS map above.- description: 'One of: score | genome | mcp-scan | threat-model | oia-audit | audit-list | audit-trend | similarity | drift-from-history | mint | redblue | learn | gepa',+ description: 'One of: score | genome | mcp-scan | threat-model | oia-audit | audit-list | audit-trend | similarity | drift-from-history | mint | redblue | learn | gepa | evolve | bench | flywheel',type: 'string' as const,},],@@ -194,6 +270,9 @@ export const metaharnessCommand: Command = {output.writeln(' drift-from-history iter 53 — diff current state against most recent audit (1-command drift)');output.writeln(' mint scaffold a custom harness (dry-run by default)');output.writeln(' redblue adversarial red/blue LLM testing (init|run|patch|attack|report)');+ output.writeln(' evolve Darwin candidate evolution');+ output.writeln(' bench create or verify a stable benchmark suite');+ output.writeln(' flywheel receipt loop: run | status | receipts | history | promote');output.writeln('');output.writeln('Each subcommand accepts --format json|table and --help.');output.writeln('');@@ -207,6 +286,10 @@ export const metaharnessCommand: Command = {return { success: false, exitCode: 2, data: { subcommand } };}+ if (subcommand === 'flywheel') {+ return dispatchFlywheel(positionalRest[0], positionalRest.slice(1), ctxFlags);+ }+const scriptDir = locatePluginScripts(SUBCOMMANDS[subcommand]);if (!scriptDir) {output.writeln(diff --git a/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.tsindex 622969f212..6a160a34a7 100644--- a/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/metaharness-tools.ts@@ -50,9 +50,16 @@import type { MCPTool, getProjectCwd as _ } from './types.js';import { getProjectCwd } from './types.js';import { spawn } from 'node:child_process';-import { existsSync } from 'node:fs';+import { existsSync, readFileSync } from 'node:fs';import { join, dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';+import { runFlywheelWorker } from '../services/harness-flywheel-runtime.js';+import {+ listFlywheelReceipts,+ promoteFlywheelCandidate,+ readFlywheelTransactionState,+ verifyFlywheelLedger,+} from '../services/flywheel-transaction.js';const __dirname = dirname(fileURLToPath(import.meta.url));@@ -609,4 +616,81 @@ export const metaharnessTools: MCPTool[] = [return { success: r.success, data: r.json, degraded: r.degraded, exitCode: r.exitCode };},},+ {+ name: 'metaharness_flywheel',+ description: 'ADR-322 — evaluate candidates into immutable receipts, inspect the append-only promotion ledger, and explicitly promote one signed receipt with atomic compare-and-swap semantics. Evaluation never mutates the active champion. Promotion requires confirm=true and a local approved Ed25519 public-key PEM path; explicit trust is mandatory.',+ category: 'metaharness',+ inputSchema: {+ type: 'object',+ properties: {+ operation: { type: 'string', enum: ['run', 'status', 'receipts', 'history', 'promote'], description: 'Flywheel operation', default: 'status' },+ projectRoot: { type: 'string', description: 'Target project root (default: active project cwd)' },+ receiptId: { type: 'string', description: 'Receipt content ID for promote' },+ sample: { type: 'number', description: 'Maximum harvested evaluation sample', default: 40 },+ proposer: { type: 'string', enum: ['local', 'auto', 'darwin'], description: 'Candidate proposer. Auto fallback is evaluation-only; explicit darwin fails closed when no compatible adapter is installed.', default: 'auto' },+ privateKeyPath: { type: 'string', description: 'Local Ed25519 private-key PEM path for signing run receipts; must be paired with publicKeyPath' },+ publicKeyPath: { type: 'string', description: 'Local Ed25519 public-key PEM path used to sign a run or approve a promotion' },+ confirm: { type: 'boolean', description: 'Required for promote; never inferred', default: false },+ },+ required: ['operation'],+ },+ handler: async (input) => {+ const operation = String(input.operation ?? 'status');+ const projectRoot = resolve(String(input.projectRoot ?? getProjectCwd()));+ if (operation === 'status') {+ return {+ success: true,+ data: {+ state: readFlywheelTransactionState(projectRoot),+ ledger: verifyFlywheelLedger(projectRoot),+ },+ degraded: false,+ exitCode: 0,+ };+ }+ if (operation === 'receipts') {+ const data = listFlywheelReceipts(projectRoot).map(({ receipt, state }) => ({+ receiptId: receipt.payload.receiptId,+ candidateId: receipt.payload.candidateId,+ baselineRef: receipt.payload.baselineRef,+ decision: receipt.payload.decision,+ signed: !!receipt.signature,+ issuedAt: receipt.payload.issuedAt,+ state,+ }));+ return { success: true, data, degraded: false, exitCode: 0 };+ }+ if (operation === 'history') {+ const state = readFlywheelTransactionState(projectRoot);+ return { success: true, data: { ledgerHead: state.ledgerHead, commits: state.commits }, degraded: false, exitCode: 0 };+ }+ if (operation === 'run') {+ const privateKeyPath = input.privateKeyPath ? resolve(String(input.privateKeyPath)) : undefined;+ const publicKeyPath = input.publicKeyPath ? resolve(String(input.publicKeyPath)) : undefined;+ if (!!privateKeyPath !== !!publicKeyPath) {+ return { success: false, data: { reason: 'privateKeyPath and publicKeyPath must be supplied together' }, degraded: false, exitCode: 2 };+ }+ const data = await runFlywheelWorker(projectRoot, {+ optInOverride: true,+ sample: Number(input.sample ?? 40),+ proposer: String(input.proposer ?? 'auto') as 'local' | 'auto' | 'darwin',+ receiptPrivateKeyPem: privateKeyPath ? readFileSync(privateKeyPath, 'utf8') : undefined,+ receiptPublicKeyPem: publicKeyPath ? readFileSync(publicKeyPath, 'utf8') : undefined,+ });+ return { success: data.ran, data, degraded: false, exitCode: data.ran ? 0 : 1 };+ }+ if (operation === 'promote') {+ if (!input.receiptId || !input.publicKeyPath) {+ return { success: false, data: { reason: 'receiptId and publicKeyPath are required' }, degraded: false, exitCode: 2 };+ }+ const publicKey = readFileSync(resolve(String(input.publicKeyPath)), 'utf8');+ const data = await promoteFlywheelCandidate(projectRoot, String(input.receiptId), {+ confirm: input.confirm === true,+ trustedPublicKeys: new Set([publicKey]),+ });+ return { success: data.success, data, degraded: false, exitCode: data.success ? 0 : 1 };+ }+ return { success: false, data: { reason: `unsupported operation: ${operation}` }, degraded: false, exitCode: 2 };+ },+ },];diff --git a/v3/@claude-flow/cli/src/services/flywheel-proposer.ts b/v3/@claude-flow/cli/src/services/flywheel-proposer.tsnew file mode 100644index 0000000000..cfff614619--- /dev/null+++ b/v3/@claude-flow/cli/src/services/flywheel-proposer.ts@@ -0,0 +1,251 @@+/**+ * ADR-322B proposer adapter.+ *+ * Proposers are untrusted candidate generators. This adapter normalizes local+ * and Darwin output, enforces hard policy/resource admissibility before Pareto+ * ranking, and makes auto-mode substitution evaluation-only by default.+ */+import { canonicalizeJcs, policyCandidateId, sha256Ref, type ProposerName } from './flywheel-receipt.js';++export type ProposerMode = 'auto' | ProposerName;++export interface SafetyEnvelope {+ ref: string;+ allowedPolicyKeys: string[];+ numericBounds?: Record<string, { min?: number; max?: number }>;+ maxP95LatencyMicros: number;+ maxCostMicrosPerTask: number;+ maxTokensPerTask: number;+ maxFailureRate: number;+ maxEvaluationCostMicros: number;+}++export interface CandidateResources {+ p95LatencyMicros: number;+ costMicrosPerTask: number;+ tokensPerTask: number;+ failureRate: number;+ evaluationCostMicros: number;+}++export interface ProposedCandidate {+ policy: Record<string, unknown>;+ resources: CandidateResources;+ score?: number;+ mutation?: string;+ parentIds?: string[];+}++export interface NormalizedCandidate extends ProposedCandidate {+ candidateId: string;+ admissible: boolean;+ rejectionReasons: string[];+}++export interface CandidateArchive {+ archiveVersion: 'ruflo.candidate-archive/v1';+ archiveId: string;+ requestedProposer: ProposerMode;+ effectiveProposer: ProposerName;+ proposerSubstitution?: string;+ promotionAllowed: boolean;+ baselineRef: string;+ safetyEnvelopeRef: string;+ seed: number;+ candidates: NormalizedCandidate[];+ admissibleCandidates: NormalizedCandidate[];+ paretoCandidates: NormalizedCandidate[];+ completed: boolean;+}++export interface DarwinRunInput {+ baselinePolicy: Record<string, unknown>;+ seed: number;+ budget: {+ maxEvaluationCostMicros: number;+ maxConcurrency: number;+ maxWallTimeMs: number;+ };+}++export type DarwinInvoker = (input: DarwinRunInput) => Promise<{+ completed: boolean;+ candidates: ProposedCandidate[];+ reason?: string;+}>;++export interface ProposeCandidatesInput {+ mode: ProposerMode;+ baselinePolicy: Record<string, unknown>;+ safetyEnvelope: SafetyEnvelope;+ seed: number;+ localProposer: (baseline: Record<string, unknown>, seed: number) => ProposedCandidate[] | Promise<ProposedCandidate[]>;+ darwinInvoker?: DarwinInvoker;+ allowSubstitutionPromotion?: boolean;+ maxConcurrency?: number;+ maxWallTimeMs?: number;+ maxCandidates?: number;+}++export class DarwinUnavailableError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'DarwinUnavailableError';+ }+}++function validateCandidate(candidate: ProposedCandidate, envelope: SafetyEnvelope): NormalizedCandidate {+ const reasons: string[] = [];+ const allowed = new Set(envelope.allowedPolicyKeys);+ for (const [key, value] of Object.entries(candidate.policy)) {+ if (!allowed.has(key)) {+ reasons.push(`policy key not allowed: ${key}`);+ continue;+ }+ const bounds = envelope.numericBounds?.[key];+ if (bounds && typeof value === 'number') {+ if (bounds.min !== undefined && value < bounds.min) reasons.push(`${key} below minimum`);+ if (bounds.max !== undefined && value > bounds.max) reasons.push(`${key} above maximum`);+ }+ }+ const r = candidate.resources;+ if (r.p95LatencyMicros > envelope.maxP95LatencyMicros) reasons.push('p95 latency exceeds envelope');+ if (r.costMicrosPerTask > envelope.maxCostMicrosPerTask) reasons.push('cost per task exceeds envelope');+ if (r.tokensPerTask > envelope.maxTokensPerTask) reasons.push('tokens per task exceeds envelope');+ if (r.failureRate > envelope.maxFailureRate) reasons.push('failure rate exceeds envelope');+ if (r.evaluationCostMicros > envelope.maxEvaluationCostMicros) reasons.push('evaluation cost exceeds envelope');+ return {+ ...candidate,+ candidateId: policyCandidateId(candidate.policy),+ admissible: reasons.length === 0,+ rejectionReasons: reasons,+ };+}++function finalizeArchive(input: {+ requested: ProposerMode;+ effective: ProposerName;+ substitution?: string;+ promotionAllowed: boolean;+ baselineRef: string;+ safetyEnvelope: SafetyEnvelope;+ seed: number;+ candidates: ProposedCandidate[];+ completed: boolean;+}): CandidateArchive {+ const normalized = input.candidates.map((candidate) => validateCandidate(candidate, input.safetyEnvelope));+ const admissible = normalized.filter((candidate) => candidate.admissible);+ const dominates = (a: NormalizedCandidate, b: NormalizedCandidate): boolean => {+ const av = [+ a.score ?? 0,+ -a.resources.p95LatencyMicros,+ -a.resources.costMicrosPerTask,+ -a.resources.tokensPerTask,+ -a.resources.failureRate,+ -a.resources.evaluationCostMicros,+ ];+ const bv = [+ b.score ?? 0,+ -b.resources.p95LatencyMicros,+ -b.resources.costMicrosPerTask,+ -b.resources.tokensPerTask,+ -b.resources.failureRate,+ -b.resources.evaluationCostMicros,+ ];+ return av.every((value, index) => value >= bv[index])+ && av.some((value, index) => value > bv[index]);+ };+ const paretoCandidates = admissible.filter((candidate, index) =>+ !admissible.some((other, otherIndex) => otherIndex !== index && dominates(other, candidate)));+ const core = {+ archiveVersion: 'ruflo.candidate-archive/v1' as const,+ requestedProposer: input.requested,+ effectiveProposer: input.effective,+ ...(input.substitution ? { proposerSubstitution: input.substitution } : {}),+ promotionAllowed: input.promotionAllowed,+ baselineRef: input.baselineRef,+ safetyEnvelopeRef: input.safetyEnvelope.ref,+ seed: input.seed,+ candidates: normalized,+ completed: input.completed,+ };+ return {+ ...core,+ archiveId: sha256Ref(canonicalizeJcs(core)),+ admissibleCandidates: admissible,+ paretoCandidates,+ };+}++export async function proposeFlywheelCandidates(input: ProposeCandidatesInput): Promise<CandidateArchive> {+ const baselineRef = policyCandidateId(input.baselinePolicy);+ const runLocal = async (substitution?: string) => finalizeArchive({+ requested: input.mode,+ effective: 'local',+ substitution,+ promotionAllowed: substitution ? input.allowSubstitutionPromotion === true : true,+ baselineRef,+ safetyEnvelope: input.safetyEnvelope,+ seed: input.seed,+ candidates: await input.localProposer(input.baselinePolicy, input.seed),+ completed: true,+ });++ if (input.mode === 'local') return runLocal();+ if (!input.darwinInvoker) {+ if (input.mode === 'darwin') throw new DarwinUnavailableError('Darwin explicitly requested but unavailable');+ return runLocal('darwin-unavailable');+ }++ try {+ const maxWallTimeMs = input.maxWallTimeMs ?? 60_000;+ let timeout: NodeJS.Timeout | undefined;+ const result = await Promise.race([+ input.darwinInvoker({+ baselinePolicy: input.baselinePolicy,+ seed: input.seed,+ budget: {+ maxEvaluationCostMicros: input.safetyEnvelope.maxEvaluationCostMicros,+ maxConcurrency: input.maxConcurrency ?? 2,+ maxWallTimeMs,+ },+ }),+ new Promise<never>((_, reject) => {+ timeout = setTimeout(() => reject(new DarwinUnavailableError('Darwin exceeded wall-time budget')), maxWallTimeMs);+ timeout.unref?.();+ }),+ ]).finally(() => {+ if (timeout) clearTimeout(timeout);+ });+ if (!result.completed) {+ if (input.mode === 'darwin') throw new DarwinUnavailableError(result.reason ?? 'Darwin archive incomplete');+ return runLocal(`darwin-incomplete:${result.reason ?? 'unknown'}`);+ }+ if (result.candidates.length > (input.maxCandidates ?? 256)) {+ throw new DarwinUnavailableError('Darwin archive exceeded candidate-count budget');+ }+ const evaluationCost = result.candidates.reduce(+ (sum, candidate) => sum + candidate.resources.evaluationCostMicros,+ 0,+ );+ if (evaluationCost > input.safetyEnvelope.maxEvaluationCostMicros) {+ throw new DarwinUnavailableError('Darwin archive exceeded evaluation-cost budget');+ }+ return finalizeArchive({+ requested: input.mode,+ effective: 'darwin',+ promotionAllowed: true,+ baselineRef,+ safetyEnvelope: input.safetyEnvelope,+ seed: input.seed,+ candidates: result.candidates,+ completed: true,+ });+ } catch (error) {+ if (input.mode === 'darwin') {+ if (error instanceof DarwinUnavailableError) throw error;+ throw new DarwinUnavailableError(`Darwin failed closed: ${(error as Error).message}`);+ }+ return runLocal(`darwin-error:${(error as Error).message}`);+ }+}diff --git a/v3/@claude-flow/cli/src/services/flywheel-receipt.ts b/v3/@claude-flow/cli/src/services/flywheel-receipt.tsnew file mode 100644index 0000000000..5853a5d779--- /dev/null+++ b/v3/@claude-flow/cli/src/services/flywheel-receipt.ts@@ -0,0 +1,437 @@+/**+ * ADR-322C receipt protocol.+ *+ * Provides deterministic JCS-style canonicalization, distinct policy/run/receipt+ * identities, deterministic paired-bootstrap statistics, and domain-separated+ * Ed25519 signatures. Signed receipts are immutable; promotion consumption is+ * tracked separately by flywheel-transaction.ts.+ */+import {+ createHash,+ randomBytes,+ sign as edSign,+ verify as edVerify,+} from 'node:crypto';++export const RECEIPT_SCHEMA = 'ruflo.flywheel-receipt/v1';+export const RECEIPT_DOMAIN = 'ruflo/flywheel-receipt/v1';+export const GENESIS_LEDGER_HEAD = `sha256:${'0'.repeat(64)}`;++export type VerificationKind = 'recomputed' | 'signature-verified' | 'trusted-assertion';+export type ProposerName = 'local' | 'darwin';++export interface ReceiptSignature {+ algorithm: 'ed25519';+ domain: typeof RECEIPT_DOMAIN;+ publicKeyPem: string;+ signatureBase64: string;+}++export interface ResourceEvidence {+ p95LatencyMicros: number;+ costMicrosPerTask: number;+ tokensPerTask: number;+ failureRate: string;+ evaluationCostMicros: number;+ energyMicrojoules?: number;+ currency: string;+}++export interface PromotionStatistics {+ ruleVersion: 'ruflo.flywheel-gate/v1';+ relativeLift: string;+ pairedBootstrapProbability: string;+ pairedBootstrapDeltaCILow95: string;+ frozenAnchorRegression: string;+ iterations: number;+ seedHex: string;+ significant: boolean;+ accepted: boolean;+}++export interface TermVerification {+ term: string;+ verification: VerificationKind;+ evidenceRef: string;+ attestor?: string;+}++export interface EvaluationEvidence {+ corpusRoles: {+ selectionTaskIds: string[];+ promotionHoldoutTaskIds: string[];+ guardTaskIds: string[];+ };+ verification: Record<string, unknown>;+ canary: Record<string, unknown>;+}++export interface FlywheelReceiptPayload {+ schemaVersion: typeof RECEIPT_SCHEMA;+ receiptId: string;+ lineageId: string;+ candidateId: string;+ evaluationRunId: string;+ baselineRef: string;+ expectedLedgerHead: string;+ candidatePolicy: Record<string, unknown>;+ gateVersion: string;+ policySchemaVersion: string;+ safetyEnvelopeRef: string;+ requestedProposer: 'auto' | ProposerName;+ effectiveProposer: ProposerName;+ proposerSubstitution?: string;+ corpusVersion: string;+ corpusHash: string;+ baselineScore: string;+ candidateScore: string;+ heldOutDeltas: string[];+ statistics: PromotionStatistics;+ gates: Record<string, boolean>;+ resourceEvidence: ResourceEvidence;+ evidence: EvaluationEvidence;+ termVerification: TermVerification[];+ decision: 'accepted' | 'rejected';+ issuedAt: string;+ expiresAt: string;+}++export interface FlywheelEvaluationReceipt {+ payload: FlywheelReceiptPayload;+ signature?: ReceiptSignature;+}++export interface CreateReceiptInput {+ lineageId?: string;+ evaluationRunId?: string;+ baselineRef: string;+ expectedLedgerHead?: string;+ candidatePolicy: Record<string, unknown>;+ gateVersion?: string;+ policySchemaVersion?: string;+ safetyEnvelopeRef: string;+ requestedProposer?: 'auto' | ProposerName;+ effectiveProposer?: ProposerName;+ proposerSubstitution?: string;+ corpusVersion: string;+ corpusHash: string;+ baselineScore: number;+ candidateScore: number;+ heldOutDeltas: number[];+ frozenAnchorRegression: number;+ gates: Record<string, boolean>;+ resourceEvidence?: Partial<ResourceEvidence>;+ evidence?: EvaluationEvidence;+ termVerification?: TermVerification[];+ now?: number;+ ttlMs?: number;+ privateKeyPem?: string;+ publicKeyPem?: string;+ bootstrapIterations?: number;+}++function assertJsonValue(value: unknown, path = '$'): void {+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return;+ if (typeof value === 'number') {+ if (!Number.isFinite(value) || Object.is(value, -0)) {+ throw new Error(`non-canonical number at ${path}`);+ }+ return;+ }+ if (Array.isArray(value)) {+ value.forEach((v, i) => {+ if (v === undefined) throw new Error(`undefined array member at ${path}[${i}]`);+ assertJsonValue(v, `${path}[${i}]`);+ });+ return;+ }+ if (typeof value === 'object') {+ for (const [key, child] of Object.entries(value as Record<string, unknown>)) {+ if (child === undefined) throw new Error(`undefined property at ${path}.${key}`);+ assertJsonValue(child, `${path}.${key}`);+ }+ return;+ }+ throw new Error(`unsupported JSON value at ${path}`);+}++/**+ * RFC-8785-compatible for the JSON domain accepted above: ECMAScript primitive+ * serialization plus recursively sorted UTF-16 property names.+ */+export function canonicalizeJcs(value: unknown): string {+ assertJsonValue(value);+ const encode = (v: unknown): string => {+ if (v === null || typeof v !== 'object') return JSON.stringify(v);+ if (Array.isArray(v)) return `[${v.map(encode).join(',')}]`;+ const obj = v as Record<string, unknown>;+ return `{${Object.keys(obj).sort().map((k) => `${JSON.stringify(k)}:${encode(obj[k])}`).join(',')}}`;+ };+ return encode(value);+}++export function sha256Ref(value: string | Buffer): string {+ return `sha256:${createHash('sha256').update(value).digest('hex')}`;+}++export function policyCandidateId(policy: Record<string, unknown>): string {+ return sha256Ref(canonicalizeJcs(policy));+}++/** UUIDv7 with a 48-bit millisecond timestamp and RFC-4122 variant bits. */+export function uuidV7(now = Date.now()): string {+ const bytes = randomBytes(16);+ const timestamp = BigInt(now);+ for (let i = 5; i >= 0; i--) bytes[5 - i] = Number((timestamp >> BigInt(i * 8)) & 0xffn);+ bytes[6] = (bytes[6] & 0x0f) | 0x70;+ bytes[8] = (bytes[8] & 0x3f) | 0x80;+ const hex = bytes.toString('hex');+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;+}++const decimal = (value: number, scale = 12): string => {+ if (!Number.isFinite(value)) throw new Error('metric must be finite');+ const normalized = value.toFixed(scale).replace(/\.?0+$/, '');+ return normalized === '-0' || normalized === '' ? '0' : normalized;+};++function seedFrom(parts: string[]): { seed: number; hex: string } {+ const digest = createHash('sha256').update(parts.join('')).digest();+ return { seed: digest.readUInt32BE(0), hex: digest.toString('hex') };+}++/**+ * Deterministic three-way quickselect. Bootstrap promotion needs one quantile,+ * not a fully sorted distribution; selecting it in expected O(n) removes the+ * O(n log n) sort from every evaluation. Three-way partitioning also keeps the+ * common all-equal bootstrap case linear.+ */+function selectKth(values: number[], k: number): number {+ let left = 0;+ let right = values.length - 1;+ while (left <= right) {+ const pivot = values[(left + right) >>> 1];+ let lower = left;+ let scan = left;+ let upper = right;+ while (scan <= upper) {+ if (values[scan] < pivot) {+ [values[lower], values[scan]] = [values[scan], values[lower]];+ lower++;+ scan++;+ } else if (values[scan] > pivot) {+ [values[scan], values[upper]] = [values[upper], values[scan]];+ upper--;+ } else {+ scan++;+ }+ }+ if (k < lower) right = lower - 1;+ else if (k > upper) left = upper + 1;+ else return values[k];+ }+ return values[k] ?? 0;+}++export function computePromotionStatistics(input: {+ baselineScore: number;+ candidateScore: number;+ heldOutDeltas: number[];+ frozenAnchorRegression: number;+ corpusHash: string;+ candidateId: string;+ baselineRef: string;+ evaluationRunId: string;+ iterations?: number;+ metricEpsilon?: number;+}): PromotionStatistics {+ const iterations = input.iterations ?? 10_000;+ if (!Number.isInteger(iterations) || iterations < 100) throw new Error('bootstrap iterations must be >= 100');+ const n = input.heldOutDeltas.length;+ const metricEpsilon = input.metricEpsilon ?? 1e-12;+ const relativeLift = (input.candidateScore - input.baselineScore) / Math.max(Math.abs(input.baselineScore), metricEpsilon);+ const seeded = seedFrom([+ 'ruflo/bootstrap/v1',+ input.corpusHash,+ input.candidateId,+ input.baselineRef,+ input.evaluationRunId,+ ]);+ let state = seeded.seed >>> 0;+ const rnd = () => {+ state = (1664525 * state + 1013904223) >>> 0;+ return state / 4294967296;+ };+ const means = new Array<number>(iterations);+ let positiveMeans = 0;+ if (n === 0) {+ means.fill(0);+ } else {+ for (let b = 0; b < iterations; b++) {+ let total = 0;+ for (let i = 0; i < n; i++) total += input.heldOutDeltas[Math.floor(rnd() * n)];+ const mean = total / n;+ means[b] = mean;+ if (mean > 0) positiveMeans++;+ }+ }+ const probability = positiveMeans / iterations;+ const ciLow = selectKth(means, Math.floor(0.025 * iterations));+ const significant = probability >= 0.95 && ciLow > 0;+ const accepted = relativeLift >= 0.02 && significant && input.frozenAnchorRegression <= 0;+ return {+ ruleVersion: 'ruflo.flywheel-gate/v1',+ relativeLift: decimal(relativeLift),+ pairedBootstrapProbability: decimal(probability),+ pairedBootstrapDeltaCILow95: decimal(ciLow),+ frozenAnchorRegression: decimal(input.frozenAnchorRegression),+ iterations,+ seedHex: seeded.hex,+ significant,+ accepted,+ };+}++function receiptIdentityPayload(payload: Omit<FlywheelReceiptPayload, 'receiptId'>): unknown {+ return payload;+}++function signedBytes(payload: FlywheelReceiptPayload): Buffer {+ return Buffer.concat([+ Buffer.from(RECEIPT_DOMAIN, 'utf8'),+ Buffer.from([0]),+ Buffer.from(canonicalizeJcs(payload), 'utf8'),+ ]);+}++export function createFlywheelReceipt(input: CreateReceiptInput): FlywheelEvaluationReceipt {+ const now = input.now ?? Date.now();+ const evaluationRunId = input.evaluationRunId ?? uuidV7(now);+ const lineageId = input.lineageId ?? uuidV7(now);+ const candidateId = policyCandidateId(input.candidatePolicy);+ const statistics = computePromotionStatistics({+ baselineScore: input.baselineScore,+ candidateScore: input.candidateScore,+ heldOutDeltas: input.heldOutDeltas,+ frozenAnchorRegression: input.frozenAnchorRegression,+ corpusHash: input.corpusHash,+ candidateId,+ baselineRef: input.baselineRef,+ evaluationRunId,+ iterations: input.bootstrapIterations,+ });+ const decision = statistics.accepted && Object.values(input.gates).every(Boolean) ? 'accepted' : 'rejected';+ const base = {+ schemaVersion: RECEIPT_SCHEMA,+ lineageId,+ candidateId,+ evaluationRunId,+ baselineRef: input.baselineRef,+ expectedLedgerHead: input.expectedLedgerHead ?? GENESIS_LEDGER_HEAD,+ candidatePolicy: input.candidatePolicy,+ gateVersion: input.gateVersion ?? statistics.ruleVersion,+ policySchemaVersion: input.policySchemaVersion ?? 'ruflo.retrieval-policy/v1',+ safetyEnvelopeRef: input.safetyEnvelopeRef,+ requestedProposer: input.requestedProposer ?? 'local',+ effectiveProposer: input.effectiveProposer ?? 'local',+ ...(input.proposerSubstitution ? { proposerSubstitution: input.proposerSubstitution } : {}),+ corpusVersion: input.corpusVersion,+ corpusHash: input.corpusHash,+ baselineScore: decimal(input.baselineScore),+ candidateScore: decimal(input.candidateScore),+ heldOutDeltas: input.heldOutDeltas.map((v) => decimal(v)),+ statistics,+ gates: input.gates,+ resourceEvidence: {+ p95LatencyMicros: input.resourceEvidence?.p95LatencyMicros ?? 0,+ costMicrosPerTask: input.resourceEvidence?.costMicrosPerTask ?? 0,+ tokensPerTask: input.resourceEvidence?.tokensPerTask ?? 0,+ failureRate: input.resourceEvidence?.failureRate ?? '0',+ evaluationCostMicros: input.resourceEvidence?.evaluationCostMicros ?? 0,+ ...(input.resourceEvidence?.energyMicrojoules === undefined+ ? {}+ : { energyMicrojoules: input.resourceEvidence.energyMicrojoules }),+ currency: input.resourceEvidence?.currency ?? 'USD',+ },+ evidence: input.evidence ?? {+ corpusRoles: {+ selectionTaskIds: [],+ promotionHoldoutTaskIds: [],+ guardTaskIds: [],+ },+ verification: {},+ canary: {},+ },+ termVerification: input.termVerification ?? [],+ decision,+ issuedAt: new Date(now).toISOString(),+ expiresAt: new Date(now + (input.ttlMs ?? 24 * 60 * 60 * 1000)).toISOString(),+ } satisfies Omit<FlywheelReceiptPayload, 'receiptId'>;+ const receiptId = sha256Ref(canonicalizeJcs(receiptIdentityPayload(base)));+ const payload: FlywheelReceiptPayload = { ...base, receiptId };+ const receipt: FlywheelEvaluationReceipt = { payload };+ if (input.privateKeyPem || input.publicKeyPem) {+ if (!input.privateKeyPem || !input.publicKeyPem) throw new Error('both Ed25519 private and public PEM keys are required');+ receipt.signature = {+ algorithm: 'ed25519',+ domain: RECEIPT_DOMAIN,+ publicKeyPem: input.publicKeyPem,+ signatureBase64: edSign(null, signedBytes(payload), input.privateKeyPem).toString('base64'),+ };+ }+ return receipt;+}++export interface ReceiptVerification {+ valid: boolean;+ signed: boolean;+ errors: string[];+}++export function verifyFlywheelReceipt(receipt: FlywheelEvaluationReceipt, trustedPublicKeys?: Set<string>): ReceiptVerification {+ const errors: string[] = [];+ try {+ if (receipt.payload.schemaVersion !== RECEIPT_SCHEMA) errors.push('unsupported receipt schema');+ const { receiptId: _receiptId, ...base } = receipt.payload;+ const expectedId = sha256Ref(canonicalizeJcs(receiptIdentityPayload(base)));+ if (expectedId !== receipt.payload.receiptId) errors.push('receipt content ID mismatch');+ if (policyCandidateId(receipt.payload.candidatePolicy) !== receipt.payload.candidateId) errors.push('candidate content ID mismatch');+ const recomputedStatistics = computePromotionStatistics({+ baselineScore: Number(receipt.payload.baselineScore),+ candidateScore: Number(receipt.payload.candidateScore),+ heldOutDeltas: receipt.payload.heldOutDeltas.map(Number),+ frozenAnchorRegression: Number(receipt.payload.statistics.frozenAnchorRegression),+ corpusHash: receipt.payload.corpusHash,+ candidateId: receipt.payload.candidateId,+ baselineRef: receipt.payload.baselineRef,+ evaluationRunId: receipt.payload.evaluationRunId,+ iterations: receipt.payload.statistics.iterations,+ });+ if (canonicalizeJcs(recomputedStatistics) !== canonicalizeJcs(receipt.payload.statistics)) {+ errors.push('statistical decision does not recompute');+ }+ const recomputedDecision = recomputedStatistics.accepted && Object.values(receipt.payload.gates).every(Boolean)+ ? 'accepted'+ : 'rejected';+ if (receipt.payload.decision !== recomputedDecision) errors.push('receipt decision does not recompute');+ if (!receipt.signature) {+ errors.push('receipt is unsigned');+ } else {+ if (receipt.signature.algorithm !== 'ed25519' || receipt.signature.domain !== RECEIPT_DOMAIN) {+ errors.push('unsupported signature metadata');+ } else if (trustedPublicKeys && !trustedPublicKeys.has(receipt.signature.publicKeyPem)) {+ errors.push('receipt signer is not trusted');+ } else if (!edVerify(+ null,+ signedBytes(receipt.payload),+ receipt.signature.publicKeyPem,+ Buffer.from(receipt.signature.signatureBase64, 'base64'),+ )) {+ errors.push('receipt signature invalid');+ }+ }+ } catch (error) {+ errors.push(`verification error: ${(error as Error).message}`);+ }+ return { valid: errors.length === 0, signed: !!receipt.signature, errors };+}diff --git a/v3/@claude-flow/cli/src/services/flywheel-transaction.ts b/v3/@claude-flow/cli/src/services/flywheel-transaction.tsnew file mode 100644index 0000000000..e2d38665bb--- /dev/null+++ b/v3/@claude-flow/cli/src/services/flywheel-transaction.ts@@ -0,0 +1,451 @@+/**+ * ADR-322A promotion transaction.+ *+ * A single atomic state file is the authority for active champion, receipt+ * consumption, lineage head, and serving epoch. Cross-process mutation is+ * serialized with an O_EXCL lock; atomic rename commits all authoritative state+ * at once. Runtime policy materialization is derived and recoverable.+ */+import * as fs from 'node:fs';+import * as path from 'node:path';+import { applyChampionParams, type ApplyResult } from '../config/harness-feedback-applier.js';+import {+ GENESIS_LEDGER_HEAD,+ canonicalizeJcs,+ sha256Ref,+ uuidV7,+ verifyFlywheelReceipt,+ type FlywheelEvaluationReceipt,+} from './flywheel-receipt.js';++const STATE_VERSION = 1 as const;+const STATE_DIR = ['.claude-flow', 'flywheel-v1'] as const;+const STATE_FILE = 'transaction-state.json';+const LOCK_FILE = 'transaction-state.lock';+const RECEIPTS_DIR = 'receipts';+const LOCK_TIMEOUT_MS = 10_000;+const LOCK_STALE_MS = 60_000;++export interface ReceiptState {+ receiptId: string;+ status: 'evaluated' | 'consumed' | 'expired' | 'revoked';+ registeredAt: number;+ promotedAt: number | null;+ promotionTransactionId: string | null;+}++export interface PromotionCommit {+ commitId: string;+ transactionId: string;+ receiptId: string;+ lineageId: string;+ sequence: number;+ previousLedgerHead: string;+ baselineRef: string;+ candidateId: string;+ servingEpoch: number;+ proposer: string;+ proposerSubstitution?: string;+ promotedAt: number;+}++export interface FlywheelTransactionState {+ version: typeof STATE_VERSION;+ activeChampionRef: string | null;+ activePolicy: Record<string, unknown> | null;+ activeGateVersion: string | null;+ activePolicySchemaVersion: string | null;+ activeSafetyEnvelopeRef: string | null;+ ledgerHead: string;+ servingEpoch: number;+ materializedServingEpoch: number;+ servedChampionRef: string | null;+ receiptStates: Record<string, ReceiptState>;+ commits: PromotionCommit[];+}++export interface PromotionResult {+ success: boolean;+ idempotent: boolean;+ reason: string;+ transactionId?: string;+ receiptId?: string;+ championRef?: string;+ ledgerHead?: string;+ servingEpoch?: number;+ materialized?: boolean;+ materializeReason?: string;+}++export interface PromoteOptions {+ confirm: boolean;+ now?: number;+ trustedPublicKeys?: Set<string>;+ approvedAttestors?: Set<string>;+ allowedProposerSubstitutions?: Set<string>;+ applyFn?: (root: string, policy: Record<string, unknown>, championRef: string, previous: string | null, now: number) => ApplyResult;+ /** Test-only crash hook; production callers leave unset. */+ faultAt?: 'before-commit' | 'after-commit-before-materialize';+}++const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));++function stateDir(root: string): string {+ return path.join(root, ...STATE_DIR);+}++function statePath(root: string): string {+ return path.join(stateDir(root), STATE_FILE);+}++function lockPath(root: string): string {+ return path.join(stateDir(root), LOCK_FILE);+}++function receiptDir(root: string): string {+ return path.join(stateDir(root), RECEIPTS_DIR);+}++function assertSafeFile(file: string): void {+ try {+ if (fs.lstatSync(file).isSymbolicLink()) throw new Error(`refusing symlink: ${file}`);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+}++function ensureDir(root: string): void {+ fs.mkdirSync(receiptDir(root), { recursive: true, mode: 0o700 });+ assertSafeFile(statePath(root));+ assertSafeFile(lockPath(root));+}++function emptyState(): FlywheelTransactionState {+ return {+ version: STATE_VERSION,+ activeChampionRef: null,+ activePolicy: null,+ activeGateVersion: null,+ activePolicySchemaVersion: null,+ activeSafetyEnvelopeRef: null,+ ledgerHead: GENESIS_LEDGER_HEAD,+ servingEpoch: 0,+ materializedServingEpoch: 0,+ servedChampionRef: null,+ receiptStates: {},+ commits: [],+ };+}++export function readFlywheelTransactionState(root: string): FlywheelTransactionState {+ try {+ assertSafeFile(statePath(root));+ const parsed = JSON.parse(fs.readFileSync(statePath(root), 'utf8')) as FlywheelTransactionState;+ if (parsed.version !== STATE_VERSION || !parsed.receiptStates || !Array.isArray(parsed.commits)) return emptyState();+ return parsed;+ } catch {+ return emptyState();+ }+}++function atomicWriteJson(file: string, value: unknown): void {+ assertSafeFile(file);+ const tmp = `${file}.tmp.${process.pid}.${Date.now()}`;+ const fd = fs.openSync(tmp, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);+ try {+ fs.writeFileSync(fd, `${canonicalizeJcs(value)}\n`, 'utf8');+ fs.fsyncSync(fd);+ } finally {+ fs.closeSync(fd);+ }+ fs.renameSync(tmp, file);+ const dirFd = fs.openSync(path.dirname(file), fs.constants.O_RDONLY);+ try {+ fs.fsyncSync(dirFd);+ } finally {+ fs.closeSync(dirFd);+ }+}++async function withStateLock<T>(root: string, fn: () => T | Promise<T>): Promise<T> {+ ensureDir(root);+ const lock = lockPath(root);+ const deadline = Date.now() + LOCK_TIMEOUT_MS;+ for (;;) {+ try {+ const fd = fs.openSync(lock, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);+ fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, at: Date.now() }), 'utf8');+ fs.closeSync(fd);+ try {+ return await fn();+ } finally {+ try { fs.unlinkSync(lock); } catch { /* lock already gone */ }+ }+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;+ try {+ const stat = fs.lstatSync(lock);+ if (Date.now() - stat.mtimeMs > LOCK_STALE_MS) {+ fs.unlinkSync(lock);+ continue;+ }+ } catch { /* raced with owner */ }+ if (Date.now() >= deadline) throw new Error('timed out acquiring flywheel transaction lock');+ await delay(5);+ }+ }+}++function validateReceiptId(receiptId: string): void {+ if (!/^sha256:[a-f0-9]{64}$/.test(receiptId)) throw new Error('invalid receipt ID');+}++function receiptPath(root: string, receiptId: string): string {+ validateReceiptId(receiptId);+ return path.join(receiptDir(root), `${receiptId.slice('sha256:'.length)}.json`);+}++export function readFlywheelReceipt(root: string, receiptId: string): FlywheelEvaluationReceipt | null {+ try {+ const file = receiptPath(root, receiptId);+ assertSafeFile(file);+ return JSON.parse(fs.readFileSync(file, 'utf8')) as FlywheelEvaluationReceipt;+ } catch {+ return null;+ }+}++export async function registerFlywheelReceipt(+ root: string,+ receipt: FlywheelEvaluationReceipt,+ now = Date.now(),+): Promise<ReceiptState> {+ ensureDir(root);+ validateReceiptId(receipt.payload.receiptId);+ const file = receiptPath(root, receipt.payload.receiptId);+ if (!fs.existsSync(file)) atomicWriteJson(file, receipt);+ return withStateLock(root, () => {+ const state = readFlywheelTransactionState(root);+ const existing = state.receiptStates[receipt.payload.receiptId];+ if (existing) return existing;+ const record: ReceiptState = {+ receiptId: receipt.payload.receiptId,+ status: 'evaluated',+ registeredAt: now,+ promotedAt: null,+ promotionTransactionId: null,+ };+ state.receiptStates[receipt.payload.receiptId] = record;+ atomicWriteJson(statePath(root), state);+ return record;+ });+}++function materialize(+ root: string,+ state: FlywheelTransactionState,+ now: number,+ applyFn?: PromoteOptions['applyFn'],+): ApplyResult {+ if (!state.activeChampionRef || !state.activePolicy) return { applied: false, reason: 'no active champion' };+ const previous = state.servedChampionRef;+ const apply = applyFn ?? ((projectRoot, policy, championRef, prior, appliedAt) =>+ applyChampionParams(projectRoot, {+ championId: championRef,+ params: policy,+ layer: 'repo/local',+ previous: prior,+ now: appliedAt,+ }));+ return apply(root, state.activePolicy, state.activeChampionRef, previous, now);+}++export async function recoverFlywheelMaterialization(+ root: string,+ opts: Pick<PromoteOptions, 'now' | 'applyFn'> = {},+): Promise<PromotionResult> {+ const now = opts.now ?? Date.now();+ const before = readFlywheelTransactionState(root);+ if (!before.activeChampionRef || before.servingEpoch === before.materializedServingEpoch) {+ return { success: true, idempotent: true, reason: 'materialization current', materialized: true };+ }+ const applied = materialize(root, before, now, opts.applyFn);+ if (!applied.applied && applied.reason !== 'already active') {+ return {+ success: false,+ idempotent: false,+ reason: 'promotion committed; materialization pending',+ championRef: before.activeChampionRef,+ servingEpoch: before.servingEpoch,+ materialized: false,+ materializeReason: applied.reason,+ };+ }+ await withStateLock(root, () => {+ const state = readFlywheelTransactionState(root);+ if (state.activeChampionRef === before.activeChampionRef && state.servingEpoch === before.servingEpoch) {+ state.materializedServingEpoch = state.servingEpoch;+ state.servedChampionRef = state.activeChampionRef;+ atomicWriteJson(statePath(root), state);+ }+ });+ return {+ success: true,+ idempotent: !applied.applied,+ reason: 'materialized',+ championRef: before.activeChampionRef,+ servingEpoch: before.servingEpoch,+ materialized: true,+ };+}++export async function promoteFlywheelCandidate(+ root: string,+ receiptId: string,+ options: PromoteOptions,+): Promise<PromotionResult> {+ if (!options.confirm) return { success: false, idempotent: false, reason: 'explicit confirmation required' };+ if (!options.trustedPublicKeys?.size) {+ return { success: false, idempotent: false, reason: 'at least one trusted receipt signer is required' };+ }+ const receipt = readFlywheelReceipt(root, receiptId);+ if (!receipt) return { success: false, idempotent: false, reason: 'receipt not found' };+ const verification = verifyFlywheelReceipt(receipt, options.trustedPublicKeys);+ if (!verification.valid) {+ return { success: false, idempotent: false, reason: `receipt verification failed: ${verification.errors.join(', ')}` };+ }+ const now = options.now ?? Date.now();+ const transaction = await withStateLock(root, () => {+ const state = readFlywheelTransactionState(root);+ const receiptState = state.receiptStates[receiptId];+ if (!receiptState) return { success: false, idempotent: false, reason: 'receipt is not registered' } satisfies PromotionResult;+ if (receiptState.status === 'consumed' && receiptState.promotionTransactionId) {+ const prior = state.commits.find((c) => c.transactionId === receiptState.promotionTransactionId);+ return {+ success: true,+ idempotent: true,+ reason: 'already promoted',+ transactionId: prior?.transactionId,+ receiptId,+ championRef: prior?.candidateId ?? state.activeChampionRef ?? undefined,+ ledgerHead: state.ledgerHead,+ servingEpoch: prior?.servingEpoch ?? state.servingEpoch,+ } satisfies PromotionResult;+ }+ if (receiptState.status !== 'evaluated' || receiptState.promotedAt !== null) {+ return { success: false, idempotent: false, reason: `receipt state is ${receiptState.status}` } satisfies PromotionResult;+ }+ if (receipt.payload.decision !== 'accepted') return { success: false, idempotent: false, reason: 'receipt decision is not accepted' } satisfies PromotionResult;+ if (Date.parse(receipt.payload.expiresAt) <= now) return { success: false, idempotent: false, reason: 'receipt expired' } satisfies PromotionResult;++ if (state.activeChampionRef === null) {+ state.activeChampionRef = receipt.payload.baselineRef;+ state.activeGateVersion = receipt.payload.gateVersion;+ state.activePolicySchemaVersion = receipt.payload.policySchemaVersion;+ state.activeSafetyEnvelopeRef = receipt.payload.safetyEnvelopeRef;+ }+ if (state.activeChampionRef !== receipt.payload.baselineRef) return { success: false, idempotent: false, reason: 'stale baseline' } satisfies PromotionResult;+ if (state.ledgerHead !== receipt.payload.expectedLedgerHead) return { success: false, idempotent: false, reason: 'stale ledger head' } satisfies PromotionResult;+ if (state.activeGateVersion !== receipt.payload.gateVersion) return { success: false, idempotent: false, reason: 'gate version changed' } satisfies PromotionResult;+ if (state.activePolicySchemaVersion !== receipt.payload.policySchemaVersion) return { success: false, idempotent: false, reason: 'policy schema changed' } satisfies PromotionResult;+ if (state.activeSafetyEnvelopeRef !== receipt.payload.safetyEnvelopeRef) return { success: false, idempotent: false, reason: 'safety envelope changed' } satisfies PromotionResult;+ if (+ receipt.payload.proposerSubstitution+ && !options.allowedProposerSubstitutions?.has(receipt.payload.proposerSubstitution)+ ) return { success: false, idempotent: false, reason: 'proposer substitution is evaluation-only' } satisfies PromotionResult;+ const verificationByTerm = new Map(receipt.payload.termVerification.map((term) => [term.term, term]));+ for (const [term, passed] of Object.entries(receipt.payload.gates)) {+ if (!passed) continue;+ const evidence = verificationByTerm.get(term);+ if (!evidence) return { success: false, idempotent: false, reason: `missing verification for gate: ${term}` } satisfies PromotionResult;+ if (+ evidence.verification === 'trusted-assertion'+ && (!evidence.attestor || !options.approvedAttestors?.has(evidence.attestor))+ ) return { success: false, idempotent: false, reason: `unapproved evidence attestor for gate: ${term}` } satisfies PromotionResult;+ }+ if (options.faultAt === 'before-commit') throw new Error('fault injection: before-commit');++ const transactionId = uuidV7(now);+ const commitCore = {+ transactionId,+ receiptId,+ lineageId: receipt.payload.lineageId,+ sequence: state.commits.length + 1,+ previousLedgerHead: state.ledgerHead,+ baselineRef: receipt.payload.baselineRef,+ candidateId: receipt.payload.candidateId,+ servingEpoch: state.servingEpoch + 1,+ proposer: receipt.payload.effectiveProposer,+ ...(receipt.payload.proposerSubstitution ? { proposerSubstitution: receipt.payload.proposerSubstitution } : {}),+ promotedAt: now,+ };+ const commit: PromotionCommit = { ...commitCore, commitId: sha256Ref(canonicalizeJcs(commitCore)) };+ const nextHead = sha256Ref(canonicalizeJcs({ previous: state.ledgerHead, commitId: commit.commitId }));+ state.commits.push(commit);+ state.ledgerHead = nextHead;+ state.activeChampionRef = receipt.payload.candidateId;+ state.activePolicy = receipt.payload.candidatePolicy;+ state.servingEpoch = commit.servingEpoch;+ receiptState.status = 'consumed';+ receiptState.promotedAt = now;+ receiptState.promotionTransactionId = transactionId;+ atomicWriteJson(statePath(root), state);+ return {+ success: true,+ idempotent: false,+ reason: 'promotion committed',+ transactionId,+ receiptId,+ championRef: commit.candidateId,+ ledgerHead: nextHead,+ servingEpoch: commit.servingEpoch,+ } satisfies PromotionResult;+ });++ if (!transaction.success || transaction.idempotent) {+ if (transaction.success) {+ const recovered = await recoverFlywheelMaterialization(root, options);+ return { ...transaction, materialized: recovered.materialized, materializeReason: recovered.materializeReason };+ }+ return transaction;+ }+ if (options.faultAt === 'after-commit-before-materialize') {+ throw new Error('fault injection: after-commit-before-materialize');+ }+ const recovered = await recoverFlywheelMaterialization(root, options);+ return { ...transaction, materialized: recovered.materialized, materializeReason: recovered.materializeReason };+}++export function listFlywheelReceipts(root: string): Array<{ receipt: FlywheelEvaluationReceipt; state: ReceiptState | null }> {+ const state = readFlywheelTransactionState(root);+ try {+ return fs.readdirSync(receiptDir(root))+ .filter((file) => /^[a-f0-9]{64}\.json$/.test(file))+ .map((file) => {+ const receipt = JSON.parse(fs.readFileSync(path.join(receiptDir(root), file), 'utf8')) as FlywheelEvaluationReceipt;+ return { receipt, state: state.receiptStates[receipt.payload.receiptId] ?? null };+ })+ .sort((a, b) => a.receipt.payload.issuedAt.localeCompare(b.receipt.payload.issuedAt));+ } catch {+ return [];+ }+}++export function verifyFlywheelLedger(root: string): { valid: boolean; errors: string[]; commits: number; head: string } {+ const state = readFlywheelTransactionState(root);+ const errors: string[] = [];+ let head = GENESIS_LEDGER_HEAD;+ for (let i = 0; i < state.commits.length; i++) {+ const commit = state.commits[i];+ const { commitId, ...core } = commit;+ if (commit.sequence !== i + 1) errors.push(`sequence mismatch at ${i + 1}`);+ if (commit.previousLedgerHead !== head) errors.push(`parent mismatch at ${i + 1}`);+ if (sha256Ref(canonicalizeJcs(core)) !== commitId) errors.push(`commit hash mismatch at ${i + 1}`);+ head = sha256Ref(canonicalizeJcs({ previous: head, commitId }));+ }+ if (head !== state.ledgerHead) errors.push('ledger head mismatch');+ if (state.commits.length && state.commits[state.commits.length - 1].candidateId !== state.activeChampionRef) {+ errors.push('active champion does not match ledger head');+ }+ return { valid: errors.length === 0, errors, commits: state.commits.length, head };+}diff --git a/v3/@claude-flow/cli/src/services/harness-flywheel-runtime.ts b/v3/@claude-flow/cli/src/services/harness-flywheel-runtime.tsindex 7301459770..4f0487835d 100644--- a/v3/@claude-flow/cli/src/services/harness-flywheel-runtime.ts+++ b/v3/@claude-flow/cli/src/services/harness-flywheel-runtime.ts@@ -5,9 +5,24 @@* pays the ONNX cost only when actually running a tick. Never throws.*/import { harnessLoopOptedIn } from './harness-worker.js';-import { runFlywheelTick, type FlywheelDeps, type FlywheelResult, type RetrievalConfig, type AnchorTask } from './harness-flywheel.js';+import {+ DEFAULT_CONFIG,+ retrievalPolicyNeighbors,+ runFlywheelTick,+ type FlywheelDeps,+ type FlywheelResult,+ type RetrievalConfig,+ type AnchorTask,+} from './harness-flywheel.js';import { runFlywheelGeneration, checkServedChampionDrift, type GenerationResult, type GenerationDeps } from './harness-flywheel-generations.js';import { loadFrozenHumanEval } from './harness-frozen-eval.js';+import {+ proposeFlywheelCandidates,+ type DarwinInvoker,+ type ProposerMode,+ type SafetyEnvelope,+} from './flywheel-proposer.js';+import { sha256Ref } from './flywheel-receipt.js';/** The human-labeled ADR-081 anchor — the never-regress relevance set. */const ANCHOR: AnchorTask[] = [@@ -29,7 +44,19 @@ const ANCHOR: AnchorTask[] = [*/export async function runFlywheelWorker(projectRoot: string,- opts: { sample?: number; optInOverride?: boolean; now?: number } = {},+ opts: {+ sample?: number;+ optInOverride?: boolean;+ now?: number;+ receiptPrivateKeyPem?: string;+ receiptPublicKeyPem?: string;+ lineageId?: string;+ evaluationRunId?: string;+ safetyEnvelopeRef?: string;+ proposer?: ProposerMode;+ darwinInvoker?: DarwinInvoker;+ allowSubstitutionPromotion?: boolean;+ } = {},): Promise<FlywheelResult> {try {if (!(opts.optInOverride ?? harnessLoopOptedIn())) return { ran: false, reason: 'opt-in required (RUFLO_HARNESS_LOOP=1)' };@@ -38,6 +65,60 @@ export async function runFlywheelWorker(const tool = neural.neuralTools.find((t) => t.name === 'neural_patterns');if (!tool) return { ran: false, reason: 'neural_patterns tool unavailable' };+ const baseline: RetrievalConfig = {+ ...DEFAULT_CONFIG,+ ...((applier.activeChampion(projectRoot)?.params as Partial<RetrievalConfig>) ?? {}),+ };+ const safetyEnvelope: SafetyEnvelope = {+ ref: opts.safetyEnvelopeRef ?? sha256Ref(JSON.stringify({+ schema: 'ruflo.retrieval-safety-envelope/v1',+ allowedPolicyKeys: ['alpha', 'topK', 'rerank', 'mmrLambda'],+ numericBounds: {+ alpha: { min: 0.1, max: 0.9 },+ topK: { min: 5, max: 20 },+ mmrLambda: { min: 0.3, max: 0.9 },+ },+ })),+ allowedPolicyKeys: ['alpha', 'topK', 'rerank', 'mmrLambda'],+ numericBounds: {+ alpha: { min: 0.1, max: 0.9 },+ topK: { min: 5, max: 20 },+ mmrLambda: { min: 0.3, max: 0.9 },+ },+ // Retrieval evaluations are local and report zero provider spend today;+ // finite ceilings make any future resource evidence fail closed.+ maxP95LatencyMicros: 5_000_000,+ maxCostMicrosPerTask: 10_000,+ maxTokensPerTask: 100_000,+ maxFailureRate: 0.01,+ maxEvaluationCostMicros: 1_000_000,+ };+ const proposerMode = opts.proposer+ ?? ((process.env.RUFLO_FLYWHEEL_PROPOSER as ProposerMode | undefined) ?? 'auto');+ if (!['auto', 'local', 'darwin'].includes(proposerMode)) {+ return { ran: false, reason: `invalid proposer mode: ${proposerMode}` };+ }+ const archive = await proposeFlywheelCandidates({+ mode: proposerMode,+ baselinePolicy: baseline as unknown as Record<string, unknown>,+ safetyEnvelope,+ seed: opts.now ?? Date.now(),+ localProposer: () => retrievalPolicyNeighbors(baseline).map((policy) => ({+ policy: policy as unknown as Record<string, unknown>,+ resources: {+ p95LatencyMicros: 0,+ costMicrosPerTask: 0,+ tokensPerTask: 0,+ failureRate: 0,+ evaluationCostMicros: 0,+ },+ })),+ darwinInvoker: opts.darwinInvoker,+ allowSubstitutionPromotion: opts.allowSubstitutionPromotion,+ });+ const candidatePolicies = archive.paretoCandidates.map((candidate) => candidate.policy as unknown as RetrievalConfig);+ if (!candidatePolicies.length) return { ran: false, reason: 'proposer archive contained no admissible candidates' };+const deps: FlywheelDeps = {getPatterns: () => neural.getStorePatterns(),search: async (query, cfg: RetrievalConfig) => {@@ -45,9 +126,18 @@ export async function runFlywheelWorker(return (r.results || []).slice(0, 5).map((m) => ({ id: m?.id ?? '', name: m?.name ?? '' }));},anchorTasks: ANCHOR,- activeParams: () => (applier.activeChampion(projectRoot)?.params as Partial<RetrievalConfig>) ?? null,+ activeParams: () => baseline,sample: opts.sample ?? 40,now: opts.now,+ receiptPrivateKeyPem: opts.receiptPrivateKeyPem,+ receiptPublicKeyPem: opts.receiptPublicKeyPem,+ lineageId: opts.lineageId,+ evaluationRunId: opts.evaluationRunId,+ safetyEnvelopeRef: safetyEnvelope.ref,+ requestedProposer: archive.requestedProposer,+ effectiveProposer: archive.effectiveProposer,+ proposerSubstitution: archive.proposerSubstitution,+ candidatePolicies,};return await runFlywheelTick(projectRoot, deps);} catch (e) {diff --git a/v3/@claude-flow/cli/src/services/harness-flywheel.ts b/v3/@claude-flow/cli/src/services/harness-flywheel.tsindex 09ea2ef241..0becfe5dd6 100644--- a/v3/@claude-flow/cli/src/services/harness-flywheel.ts+++ b/v3/@claude-flow/cli/src/services/harness-flywheel.ts@@ -11,10 +11,9 @@* 4. GATE the winner through the shipped runHarnessLoop on the HELD-OUT split:* held_out_improves AND redblue(anchor-no-regress) AND drift<=thr AND* replay-deterministic AND receipt_coverage AND canary-no-worse.- * 5. On accept → APPLY locally (the install self-optimizes on its own data; no- * signing needed because nothing is propagated), CHAIN to the previous- * champion, and record the attempt in the improvement ledger. Also STAGE- * the unsigned champion for optional promotion to the signed global channel.+ * 5. On accept → emit + persist an immutable evaluation receipt. Evaluation+ * never mutates active policy. Explicit promotion is handled by the+ * ADR-322A transaction service.** Trust split: LOCAL self-optimization is unsigned (an install trusting its own* measured gate); CROSS-install propagation still requires the config-signed@@ -27,6 +26,15 @@ import { hashCorpus } from './harness-benchmark.js';import { harvestSelfSupervisedTasks, blendCorpus, type HarvestPattern } from './harness-corpus-harvester.js';import { applyChampionParams } from '../config/harness-feedback-applier.js';import { appendLedger, bootstrapDeltaCILow, type LedgerEntry } from './harness-improvement-ledger.js';+import {+ createFlywheelReceipt,+ sha256Ref,+ type FlywheelEvaluationReceipt,+} from './flywheel-receipt.js';+import {+ readFlywheelTransactionState,+ registerFlywheelReceipt,+} from './flywheel-transaction.js';export interface RetrievalConfig { alpha: number; subjectWeight: number; mmrLambda: number; bodyWeight: number; typePenaltyFactor: number; }export const DEFAULT_CONFIG: RetrievalConfig = { alpha: 0.5, subjectWeight: 2.0, mmrLambda: 0.7, bodyWeight: 1.0, typePenaltyFactor: 1.0 };@@ -41,6 +49,17 @@ export interface FlywheelDeps {activeParams?: () => Partial<RetrievalConfig> | null;sample?: number;now?: number;+ lineageId?: string;+ evaluationRunId?: string;+ safetyEnvelopeRef?: string;+ requestedProposer?: 'auto' | 'local' | 'darwin';+ effectiveProposer?: 'local' | 'darwin';+ proposerSubstitution?: string;+ receiptPrivateKeyPem?: string;+ receiptPublicKeyPem?: string;+ bootstrapIterations?: number;+ /** Candidate policies supplied by an external proposer archive (ADR-322B). */+ candidatePolicies?: RetrievalConfig[];}export interface FlywheelResult {@@ -54,6 +73,11 @@ export interface FlywheelResult {anchorRegressed?: boolean;championRef?: string;corpusVersion?: string;+ candidateConfig?: RetrievalConfig;+ receiptId?: string;+ receipt?: FlywheelEvaluationReceipt;+ promotable?: boolean;+ legacyDeprecation?: boolean;}const EPS = 1e-3;@@ -76,7 +100,7 @@ function grade(ranked: RankedItem[], expected: unknown): number {return idx >= 0 ? 1 / (idx + 1) : 0;}-function neighbors(base: RetrievalConfig): RetrievalConfig[] {+export function retrievalPolicyNeighbors(base: RetrievalConfig): RetrievalConfig[] {const steps: Record<keyof RetrievalConfig, number> = { alpha: 0.1, subjectWeight: 0.5, mmrLambda: 0.1, bodyWeight: 0.5, typePenaltyFactor: 0.25 };const out: RetrievalConfig[] = [];const seen = new Set<string>();@@ -113,7 +137,7 @@ function split<T extends { id: string }>(tasks: T[], frac: number): { train: T[]* Returns a rich result AND (as a side effect) appends to the improvement ledger* and — on accept — applies the champion locally + chains it.*/-export async function runFlywheelTick(projectRoot: string, deps: FlywheelDeps): Promise<FlywheelResult> {+export async function evaluateFlywheelCandidate(projectRoot: string, deps: FlywheelDeps): Promise<FlywheelResult> {try {const patterns = await deps.getPatterns();if (!patterns || patterns.length < 8) return { ran: false, reason: 'store too small to harvest a corpus' };@@ -124,7 +148,9 @@ export async function runFlywheelTick(projectRoot: string, deps: FlywheelDeps):const anchorIdSet = new Set(blended.anchorIds);const baseline: RetrievalConfig = { ...DEFAULT_CONFIG, ...(deps.activeParams?.() ?? {}) };- const candidates = neighbors(baseline);+ const candidates = deps.candidatePolicies?.length+ ? deps.candidatePolicies.map((candidate) => ({ ...candidate }))+ : retrievalPolicyNeighbors(baseline);// OBJECTIVE = the human-labeled anchor (the relevance we actually care about,// where headroom is known to exist). GUARD = the large, growing harvested set@@ -197,7 +223,76 @@ export async function runFlywheelTick(projectRoot: string, deps: FlywheelDeps):const heldDeltas = held.map((t) => heldScoreFor(candidate, t) - heldScoreFor(baseline, t));const deltaCILow = bootstrapDeltaCILow(heldDeltas);const significant = deltaCILow > 0;- const finalAccept = result.accepted && significant;+ const provisionalGates = Object.fromEntries(Object.entries(result.verdict?.terms ?? {}).map(([k, v]) => [k, v.pass]));+ const txState = readFlywheelTransactionState(projectRoot);+ const safetyEnvelopeRef = deps.safetyEnvelopeRef ?? sha256Ref(JSON.stringify({+ schema: 'ruflo.safety-envelope/local-default-v1',+ authorizationExpansion: false,+ networkExpansion: false,+ spendExpansion: false,+ }));+ const receipt = createFlywheelReceipt({+ lineageId: deps.lineageId,+ evaluationRunId: deps.evaluationRunId,+ baselineRef: refOf(baseline),+ expectedLedgerHead: txState.ledgerHead,+ candidatePolicy: candidate as unknown as Record<string, unknown>,+ safetyEnvelopeRef,+ requestedProposer: deps.requestedProposer ?? 'local',+ effectiveProposer: deps.effectiveProposer ?? 'local',+ proposerSubstitution: deps.proposerSubstitution,+ corpusVersion: blended.version,+ corpusHash: blended.corpusHash,+ baselineScore,+ candidateScore,+ heldOutDeltas: heldDeltas,+ frozenAnchorRegression: guardRegressed ? 1 : 0,+ gates: provisionalGates,+ resourceEvidence: {+ p95LatencyMicros: 0,+ costMicrosPerTask: 0,+ tokensPerTask: 0,+ failureRate: '0',+ evaluationCostMicros: 0,+ currency: 'USD',+ },+ evidence: {+ corpusRoles: {+ selectionTaskIds: train.map((task) => task.id),+ promotionHoldoutTaskIds: held.map((task) => task.id),+ guardTaskIds: guard.map((task) => task.id),+ },+ verification: {+ redblue: result.verify?.redblue ?? 'SKIPPED',+ drift: result.verify?.drift ?? -1,+ driftThreshold: result.verify?.driftThreshold ?? 0.2,+ driftVerdict: result.verify?.driftVerdict ?? 'skipped',+ adversarialPass: result.verify?.adversarialPass ?? false,+ },+ canary: {+ candidate: result.canary?.candidate ?? {},+ baseline: result.canary?.baseline ?? {},+ pass: result.canary?.pass ?? false,+ },+ },+ termVerification: Object.keys(provisionalGates).map((term) => ({+ term,+ verification: 'recomputed' as const,+ evidenceRef: sha256Ref(JSON.stringify({+ term,+ corpusHash: blended.corpusHash,+ heldOutDeltas: heldDeltas,+ verification: result.verify,+ canary: result.canary,+ })),+ })),+ now: deps.now,+ privateKeyPem: deps.receiptPrivateKeyPem,+ publicKeyPem: deps.receiptPublicKeyPem,+ bootstrapIterations: deps.bootstrapIterations,+ });+ await registerFlywheelReceipt(projectRoot, receipt, deps.now ?? Date.now());+ const finalAccept = result.accepted && significant && receipt.payload.decision === 'accepted';const entry: LedgerEntry = {ts: deps.now ?? Date.now(),@@ -207,28 +302,49 @@ export async function runFlywheelTick(projectRoot: string, deps: FlywheelDeps):baselineScore, candidateScore, delta: candidateScore - baselineScore,deltaCILow, significant, loopAccepted: result.accepted,anchorRegressed, accepted: finalAccept,- gates: Object.fromEntries(Object.entries(result.verdict?.terms ?? {}).map(([k, v]) => [k, v.pass])),+ gates: provisionalGates,reason: finalAccept ? result.reason : (result.accepted ? `held back — improvement not significant (CI low ${deltaCILow.toFixed(4)})` : result.reason),};- let applied = false;- if (finalAccept && result.manifest) {- entry.championRef = refOf(candidate);- // Apply locally (self-optimization) + chain to the previous champion.- const ap = applyChampionParams(projectRoot, {- championId: refOf(candidate), params: candidate as unknown as Record<string, unknown>,- layer: 'repo/local', previous: refOf(baseline), now: deps.now,- });- applied = ap.applied;- }appendLedger(`${projectRoot}/.claude-flow/metrics`, entry);return {- ran: true, reason: entry.reason, accepted: finalAccept, applied,+ ran: true, reason: entry.reason, accepted: finalAccept, applied: false,baselineScore, candidateScore, delta: candidateScore - baselineScore,- anchorRegressed, championRef: entry.championRef, corpusVersion: blended.version,+ anchorRegressed, championRef: finalAccept ? refOf(candidate) : undefined,+ corpusVersion: blended.version, candidateConfig: candidate,+ receiptId: receipt.payload.receiptId, receipt, promotable: finalAccept && !!receipt.signature,};} catch (e) {return { ran: false, reason: `error: ${(e as Error)?.message ?? e}` };}}++/**+ * Compatibility wrapper. New callers get evaluation-only semantics. The legacy+ * implicit apply path exists for one release behind an explicit opt-in flag.+ */+export async function runFlywheelTick(projectRoot: string, deps: FlywheelDeps): Promise<FlywheelResult> {+ const result = await evaluateFlywheelCandidate(projectRoot, deps);+ if (+ process.env.RUFLO_FLYWHEEL_LEGACY_APPLY === '1'+ && result.accepted+ && result.candidateConfig+ && result.championRef+ ) {+ const applied = applyChampionParams(projectRoot, {+ championId: result.championRef,+ params: result.candidateConfig as unknown as Record<string, unknown>,+ layer: 'repo/local',+ previous: result.receipt?.payload.baselineRef,+ now: deps.now,+ });+ return {+ ...result,+ applied: applied.applied,+ legacyDeprecation: true,+ reason: `${result.reason}; deprecated implicit apply path`,+ };+ }+ return result;+}diff --git a/v3/docs/adr/ADR-322-metaharness-flywheel-integration.md b/v3/docs/adr/ADR-322-metaharness-flywheel-integration.mdnew file mode 100644index 0000000000..7c848c16b2--- /dev/null+++ b/v3/docs/adr/ADR-322-metaharness-flywheel-integration.md@@ -0,0 +1,339 @@+# ADR-322: Adopt `@metaharness/{flywheel,darwin}` as pluggable engines behind ruflo's ADR-176 self-improvement flywheel++- **Status**: Accepted — phases 0–2 implemented+- **Date**: 2026-07-28+- **Related**: ADR-176 (self-optimizing harness flywheel — the loop that already exists), ADR-150 (metaharness integration surfaces), ADR-321 (metaharness/router hard dependency), ADR-153 (Darwin/GEPA surfaces), ADR-148/149 (cost-optimal router), ADR-103 (Ed25519 witness manifest), upstream agentic-flow ADR-075 (sister integration), upstream agent-harness-generator ADR-145 (router as an evolvable surface, *Proposed*)+- **Grounded in** (RuvNet brain, read this turn): `agent-harness-generator/packages/darwin-mode/package.json` (`@metaharness/[email protected]`), npm `@metaharness/[email protected]` package surface, `agentic-flow/docs/adr/ADR-075`, and ruflo's own `src/services/harness-flywheel*.ts` / `evolve-proof.ts` / `harness-improvement-ledger.ts`.++## Implementation status++Phases 0–2 are implemented in the CLI package:++- `evaluateFlywheelCandidate` is non-mutating. `runFlywheelTick` preserves implicit application for one compatibility cycle only when `RUFLO_FLYWHEEL_LEGACY_APPLY=1`.+- `flywheel-receipt.ts` implements canonical JSON, distinct candidate/run/receipt identities, deterministic paired-bootstrap decisions, Ed25519 domain separation, and independent statistical recomputation.+- `flywheel-transaction.ts` implements an O_EXCL cross-process lock and one atomic, directory-fsynced compare-and-swap state containing receipt consumption, ledger head, active champion, and serving epoch. Runtime materialization is derived and recoverable.+- `flywheel-proposer.ts` implements `local|auto|darwin`, fail-closed explicit Darwin selection, evaluation-only auto substitution, hard admissibility ceilings, and Pareto filtering before evaluation. The runtime consumes the resulting archive through `candidatePolicies`; Darwin adapters remain candidate generators and never gain promotion authority.+- `ruflo metaharness evolve`, `bench`, and `flywheel run|status|receipts|history|promote` are first-class CLI verbs. `metaharness_flywheel` provides the corresponding MCP surface.+- `@metaharness/darwin@^0.8.0` and `@metaharness/flywheel@^0.1.7` are optional dependencies guarded by `scripts/check-metaharness-pins.mjs`. Removing them leaves the local receipt, transaction, and proposer path operational.+- The acceptance suite covers canonicalization, signer trust, one-byte tampering, statistical recomputation, hard resource constraints, explicit-Darwin failure, safe auto fallback, stale baselines, missing evidence classification, crash recovery, and 100 concurrent promotion attempts producing exactly one commit.++Phases 3–4 remain explicitly out of scope for activation: tool/model-policy evolution and unattended `/loop` promotion stay disabled until their separate privilege, spend, corpus-isolation, and production rollout gates are accepted.++## Context++The user wants ruflo to "better integrate metaharness" using the three published npm packages: `metaharness`, `@metaharness/darwin`, and `@metaharness/flywheel`. Grounding the current state (not from memory) changes the shape of the answer.++### What each package is++| Package | Version | Role in the "freeze the model, evolve the harness" thesis |+|---|---|---|+| `metaharness` | 0.4.1 | Umbrella / scaffolder CLI — **DESCRIBE**: `score` (5-dim readiness), `genome`, `mint`, `mcp-scan`, `threat-model`, provenance `sign/verify`. |+| `@metaharness/darwin` | 0.8.0 | The evolve **ENGINE** — **PROPOSE**: mutate one of 7 policy surfaces (`planner`, `contextBuilder`, `reviewer`, `retryPolicy`, `toolPolicy`, `memoryPolicy`, `scorePolicy`), sandbox-score each, keep measured wins, build a Pareto **archive**. Bin `metaharness-darwin`; `evolve` / `bench create|verify`. Upstream benchmark claims are informative only; they are not evidence for a ruflo promotion unless accompanied by a reproducible corpus, receipt, model/pricing snapshot, and run identifier. |+| `@metaharness/flywheel` | 0.1.7 | The **LOOP** — **GOVERN**: "a verifiable self-improvement loop … promote only what proves lift." Keywords: `promotion`, `lineage`, `receipts`. ESM library with `.` and `./cli` exports (no `bin` — imported/`/cli`, not `npx`). |++### What ruflo already has (ADR-176) — the load-bearing fact++Ruflo did **not** wait for a published flywheel. It already ships a mature self-improvement loop in `src/services/`:++- **`harness-flywheel.ts` — `runFlywheelTick`**: `HARVEST` a benchmark corpus from the install's real store (self-supervised) blended with the human-labeled ADR-081 anchor → `BASELINE` = active champion → `PROPOSE` neighbor configs and pick the best on a **TRAIN** split (a *local deterministic hill-climb*) → `GATE` the winner on a **HELD-OUT** split with a conjunctive rule: `held_out_improves AND redblue(anchor-no-regress) AND drift ≤ thr AND replay-deterministic AND receipt_coverage AND canary-no-worse`. **Current implementation note:** an accepted result calls `applyChampionParams` inside `runFlywheelTick`; this function is not a dry-run boundary.+- **`harness-improvement-ledger.ts`**: best-effort bounded JSONL. Accepted champions chain `baselineRef == previous championRef` within the retained window, but rotation discards old entries and write failures are swallowed. It is useful operational telemetry, not yet a complete append-only audit history.+- **`harness-flywheel-generations.ts`**: stateful, compounding lineage — each daemon tick uses the persisted champion as the next baseline. The latest promoted champion is automatically served at the start of the following tick (a one-generation delay), not held indefinitely for manual promotion.+- **`evolve-proof.ts`**: a single-round proof-of-mechanism. Held-out scores and significance are recomputed, but the verifier currently trusts the recorded canary rollback rate because the raw canary slice is not embedded.+- **`harness-flywheel-runtime.ts`**: binds the loop to the live neural store; opt-in via `RUFLO_HARNESS_LOOP`; never throws.++Ruflo's gate evaluates more local safety signals than the 0.1.x package surface: anchor no-regression, canary isolation, drift bound, replay-determinism, and receipt coverage. Those signals are valuable, but the current persistence and serve boundaries do not yet justify claims of complete external verifiability or manual-only serving. The deterministic local path is pure Node and costs $0.++### Current Metaharness capability inventory++“Integrated” currently means that a capability has an MCP tool or plugin wrapper that an operator can invoke. It does **not** mean that the ADR-176 runtime flywheel calls it automatically.++| Capability | Current exposure | Used by ADR-176 runtime flywheel today? | Change required by this ADR |+|---|---|---:|---|+| `metaharness score` / `genome` | CLI subcommands, plugin scripts, and `metaharness_score` / `metaharness_genome` MCP tools | No | Admit versioned descriptors as optional fitness metadata; they do not authorize promotion |+| MCP scan, threat model, mint, audit/drift/similarity | CLI subcommands and MCP/plugin surfaces | No | Keep as describe/audit inputs; bind any promotion-relevant output into the receipt |+| Darwin `evolve` | `metaharness_evolve`, `ruflo metaharness evolve`, and `evolve.mjs`; shells out through the pinned `_darwin.mjs` wrapper | Through the ADR-322B proposer contract when a Darwin invoker is supplied | Keep Darwin restricted to PROPOSE; ruflo remains promotion authority |+| Darwin `bench create\|verify` | `metaharness_bench`, `ruflo metaharness bench`, and `bench.mjs`; a verified suite can be passed to on-demand `evolve` | As an explicit proposal/evaluation input, never an authority input | Complete signed corpus-role manifests before unattended use |+| Darwin security bench | `metaharness_security_bench` MCP tool and plugin script | No | Treat as an additional security signal or CI job, not as a substitute for structural authorization invariants |+| Darwin GEPA | `ruflo metaharness gepa`, `metaharness_gepa`, and `gepa.mjs` for genome load/validate/render/analyze; optimization remains behind `metaharness_evolve` | No | Permit GEPA-derived candidates through the same proposer and authoritative ruflo gate |+| Metaharness `learn` | `ruflo metaharness learn`, `metaharness_learn`, and `learn.mjs`; dry-run by default and requires a checkout for real runs | No | Keep opt-in and subject model-backed runs to the same immutable cost envelope |+| Red/blue adversarial testing | `ruflo metaharness redblue`, `metaharness_redblue`, and plugin scripts | Only through existing local gate-specific logic, not as the upstream Flywheel loop | Version and bind the exact red/blue evidence used by a promotion |+| `@metaharness/router` | Hard dependency and independently callable routing product | No; `modelPolicy` is not an evolvable flywheel surface | Add constrained `modelPolicy` only after the signed `SafetyEnvelope` exists |+| `@metaharness/flywheel` | Optional dependency plus API pin guard; ruflo-native `flywheel` CLI/MCP surface | Interoperability package, not promotion authority | Add projection cross-check before external receipt exchange is enabled |++The former CLI and dependency exposure gaps are closed. External Flywheel receipt projection remains intentionally disabled until a projection can preserve ruflo's stronger gate and evidence semantics without information loss.++### The actual gaps (what "better integrate" means here)++1. **The PROPOSE step is narrow.** ADR-176 explores by *local deterministic hill-climb over neighbor configs*. `@metaharness/darwin` provides a broader candidate-search mechanism — 7 typed policy surfaces, sandbox scoring, crossover/epistasis, MAP-Elites niches, and a Pareto archive. Its practical superiority over the local proposer must be established on ruflo workloads through controlled quality, cost, latency, and reproducibility comparisons. Ruflo already shells out to Darwin for **GEPA** (`gepa.mjs`) but **not** as the flywheel's proposer.+2. **The receipt/lineage format is bespoke.** Ruflo's champions and receipts use their own schema and do not currently round-trip through the `lineage`/`receipts` model exposed by `@metaharness/flywheel`.+3. **`model`/router is not an evolvable surface.** Ruflo has `@metaharness/router` (hard dep, ADR-321) but the flywheel doesn't evolve routing policy — upstream ADR-145's "8th surface."+4. **No first-class flywheel command surface.** Ruflo has a mixed surface today: the main CLI exposes `score`, `genome`, `gepa`, `learn`, and related commands, while `evolve` and `bench` are MCP/plugin-only. There is no `flywheel` verb or MCP tool exposing the loop that already exists internally.+5. **Evaluation and mutation are coupled.** `runFlywheelTick` both decides and applies. A safe dry-run CLI requires a pure evaluation result that can later be promoted with an explicit, integrity-checked command.+6. **Security envelopes are not explicit.** Authorization, secret/network scope, and spend ceilings must not be expandable by an optimizer merely because a benchmark score improves.++### Dream-cycle reconciliation (2026-07-28)++The five latest `dream-cycle` issues were reviewed against this decision. They contain useful candidate signals, but they do not expand ADR-322 into a general memory, security, ensemble, performance, or swarm redesign.++| Issue | Signal relevant to ADR-322 | Routing decision |+|---|---|---|+| [#2803](https://github.com/ruvnet/ruflo/issues/2803) — MemIR provenance-role collapse | Promotion evidence needs typed origin, authority, subject, producer, and transformation lineage; a flat string is insufficient | Add typed evidence provenance to `RufloFlywheelReceiptV1`. The proposed AgentDB-wide schema and plugin SDK migration require a separate ADR |+| [#2792](https://github.com/ruvnet/ruflo/issues/2792) — heterogeneous reasoning ensembles | A heterogeneous topology may be a strong `planner`/`modelPolicy` candidate | Treat it as one candidate phenotype; it receives no privileged promotion path and must beat the same sealed holdout under the same cost envelope |+| [#2783](https://github.com/ruvnet/ruflo/issues/2783) — ShareLock and ChannelGuard | Per-tool inspection is insufficient for composed tool descriptions, and individually safe agents do not guarantee safe channels | Composite-tool inspection and inter-agent channel controls are structural preconditions for evolving those surfaces, not optional benchmark terms |+| [#2778](https://github.com/ruvnet/ruflo/issues/2778) — agentic inference and mixture-of-agents performance | Quality must be evaluated jointly with tokens, latency, money, and, when measurable, energy | Record resource observations in receipts and compare candidates on a declared Pareto policy; do not describe higher quality as “free” without measured equal-resource evidence |+| [#2768](https://github.com/ruvnet/ruflo/issues/2768) — least-privilege delegation | Privilege selection is a demonstrated orchestration bottleneck | Reinforces the signed, non-expanding `SafetyEnvelope`; an optimizer may select or narrow pre-approved grants but cannot mint or widen them |++The research signals are hypotheses and candidate generators, not promotion evidence. An arXiv preprint is not classified as peer-reviewed merely because it is recent; every benchmark claim used by the flywheel must record publication status, exact artifact/version, corpus, model, configuration, pricing snapshot, and reproducible run receipt.++#### ADR-number and branch governance++The dream branches currently contain multiple unrelated files named ADR-320, and the #2803 branch contains `ADR-322-dream-cycle-memory-typed-provenance.md`. This ADR already owns number 322 for Metaharness Flywheel integration. Before any dream branch is merged:++1. Allocate a unique ADR number from the target branch at merge time.+2. Rename the file and update its internal title, related links, issue body, and cross-references atomically.+3. Rebase onto the accepted ADR index and fail CI if a number maps to more than one decision.+4. Treat a report hash concatenated with a starting/session commit as provenance metadata, not proof that the report was committed or independently attested. Merge evidence must bind the final report blob, final branch commit, source references, and reviewer decision.++## Decision++Do **not** rip out the ADR-176 loop to adopt a 0.1.x package. Instead, treat the three npm packages as **pluggable engines and a shared interop format behind ruflo's existing gate**, in three tracks. Ruflo's gate currently evaluates a broader set of promotion conditions than the upstream package surface (held-out + anchor + drift + replay + receipt + canary + shadow) and stays the authority on promotion throughout.++### Normative implementation specifications++ADR-322 is the architectural umbrella. Acceptance of this decision does not imply that all three implementation contracts ship as one change. The implementation is divided into independently testable specifications, each with its own schema version, feature flag, rollout, and acceptance report:++1. **[ADR-322A — Evaluation and promotion transaction model](./ADR-322A-evaluation-promotion-transaction.md)**+ - Owns pure evaluation, promotion eligibility, atomic compare-and-swap, serving state, crash recovery, idempotency, and the legacy compatibility boundary.+ - Rollout flag: `RUFLO_FLYWHEEL_TRANSACTION_V1`.+2. **[ADR-322B — Darwin proposer adapter](./ADR-322B-darwin-proposer-adapter.md)**+ - Owns `auto|local|darwin` selection, package compatibility, candidate/archive translation, sandbox and model budgets, fallback behavior, and proposer comparisons.+ - Rollout flag: `RUFLO_FLYWHEEL_DARWIN_V1`.+3. **[ADR-322C — Receipt, ledger, and verification protocol](./ADR-322C-receipt-ledger-verification.md)**+ - Owns canonicalization, identifiers, signatures, evidence provenance, statistical decision records, durable lineage, verification, export, and Flywheel projection.+ - Rollout flag: `RUFLO_FLYWHEEL_RECEIPT_V1`.++No specification may rely on another specification's unversioned internal representation. Their contracts meet only through versioned policy, evaluation, promotion, and receipt schemas.++The A/B/C suffixes identify subordinate normative specifications owned by ADR-322; they do not allocate three independent entries in the global ADR-number registry.++### Track A — `@metaharness/darwin` as the flywheel's PROPOSE/evolve engine++Make the proposer pluggable behind a stable interface:++- `RUFLO_FLYWHEEL_PROPOSER=darwin` → the PROPOSE step invokes `@metaharness/darwin evolve` (via the existing `plugins/ruflo-metaharness/scripts/_darwin.mjs` subprocess pattern, `--sandbox real|mock|agent`, `--selection pareto`, `--mutator deterministic|ruvllm`) and returns its Pareto archive as candidate configs.+- `RUFLO_FLYWHEEL_PROPOSER=local` → the existing local hill-climb (byte-reproducible, $0, no network).+- `RUFLO_FLYWHEEL_PROPOSER=auto` (the default) → use Darwin when installed and compatible. If Darwin is unavailable, record the attempted proposer, failure classification, and substitution in the evaluation receipt, then allow the local proposer to produce **evaluation-only** candidates. A substituted proposer cannot promote unless an administrator-signed policy explicitly allows that exact substitution; the default substitution policy denies promotion.+- An explicitly requested `darwin` proposer **fails closed** if Darwin is unavailable or incompatible; it must not silently run a different optimizer.+- With no model credential, only the deterministic mutator is permitted. The `ruvllm` mutator requires `--confirm` plus explicit immutable limits for maximum USD, requests, tokens, concurrency, and wall time. The implementation must enforce those limits locally and, where supported, at the provider; forwarding an opaque `--risk-budget` alone does not establish a monetary hard cap.++The candidates Darwin proposes still pass **ruflo's** held-out gate before a promotion receipt can be issued — Darwin proposes, ruflo disposes.++### Track B — `@metaharness/flywheel` as the interop lineage/receipt format + the standard surface++- Introduce a versioned `RufloFlywheelReceiptV1` envelope and a canonical adapter to `@metaharness/flywheel` lineage commits. The adapter serializes numeric and structured policy values canonically; records the adapter, gate, corpus, and policy-schema versions; and carries the raw evidence needed to recompute every ruflo gate term.+- A portable receipt must include, or content-address, the held-out and canary observations, baseline/candidate outputs, anchor results, drift observations, replay transcript, receipt-coverage result, resource measurements (tokens, latency, USD, and energy when available), policy manifests, promotion decision, and signatures. Every evidence object records its provenance type, producer/attestor, authority scope, subject, transformation lineage, and content hash. A verifier must label each term as **recomputed**, **signature-verified**, or **trusted assertion**. “Externally verifiable” means all promotion-authorizing terms are recomputed or cryptographically bound to an identified trusted attestor.+- Split the current loop into two explicit interfaces:+ - `evaluateFlywheelCandidate(input) -> EvaluationPlan | EvaluationReceipt`: pure with respect to the active policy; it may write a candidate receipt but cannot apply or serve it.+ - `promoteFlywheelCandidate(receiptRef, confirmation) -> PromotionReceipt`: revalidates receipt integrity, gate version, policy version, corpus identity, expiry, and the current baseline before applying exactly once.+- Add `evolve` and `bench` to the main `ruflo metaharness` CLI map for parity with their existing MCP tools. Add a `metaharness_flywheel` MCP tool + `ruflo metaharness flywheel <run|status|promote|history|receipts>` CLI subcommand over the new evaluation/promotion interfaces. `run` is dry-run by construction. `promote` requires `--confirm`, refuses stale-baseline receipts, and is the only new command allowed to mutate the active policy. It must **not** call the side-effecting `runFlywheelTick` as its dry-run implementation.+- Use `@metaharness/flywheel`'s reference rule as a **projection cross-check** in CI. Its `Policy` and `PromotionEvidence` types cannot represent all ruflo evidence directly, so CI must test the canonical projection separately from the authoritative ruflo gate. A disagreement fails the compatibility job and blocks claiming interoperability, but never promotes a candidate.++#### Canonical wire format and identities++All signed or hashed ADR-322C objects use the following normative format:++```text+Canonical JSON: RFC 8785 JSON Canonicalization Scheme (JCS)+Digest: SHA-256+Signature: Ed25519 over domainPrefix || 0x00 || canonicalBytes+Content ID: sha256:<lowercase-hex>+Timestamp: RFC 3339 UTC, normalized to YYYY-MM-DDTHH:mm:ss.sssZ+```++- Non-finite JSON numbers (`NaN`, positive/negative infinity, negative zero) are forbidden.+- Evolvable fractional policy fields are quantized according to the versioned policy schema and encoded as canonical decimal strings or scaled integers; raw binary floating-point values are not signed policy inputs.+- Measured fractional metrics are encoded as canonical decimal strings with the scale declared by the metric schema. Currency uses integer micros in an identified ISO-4217 currency; durations use integer microseconds; energy uses integer microjoules when available.+- Unknown fields are rejected while verifying a schema version. Schema evolution requires a new version and an explicit migration whose input and output hashes are both recorded.++Identity domains are separate:++```text+candidateId = SHA-256(JCS(candidate policy))+evaluationRunId = UUIDv7 generated for each execution attempt+receiptId = SHA-256(JCS(unsigned receipt payload))+lineageId = UUIDv7 created once for a persistent evolutionary lineage+```++Re-evaluating the same candidate produces the same `candidateId`, a new `evaluationRunId`, and a new `receiptId`. Retries, independent verification, and multiple lineages therefore cannot be conflated with policy identity.++#### Statistical promotion rule++“Held-out improves” is not a raw positive delta. Every receipt embeds the complete, versioned decision rule and per-item paired observations. The initial default rule is:++```text+relativeLift >= 0.02+AND pairedBootstrapProbability(candidate > baseline) >= 0.95+AND pairedBootstrapDeltaCILow95 > 0+AND frozenAnchorRegression <= 0+```++Domains may configure stricter thresholds or an approved alternative test, but cannot omit a noise/significance rule. A change to the statistical rule creates a new gate version and cannot be applied retroactively to an existing evaluation receipt.++For the default rule:++- `relativeLift = (candidateMean - baselineMean) / max(abs(baselineMean), metricEpsilon)`, where `metricEpsilon` is fixed by the versioned metric schema.+- The paired bootstrap uses 10,000 resamples over task-level paired deltas.+- Its deterministic PRNG seed is `SHA-256("ruflo/bootstrap/v1" || corpusHash || candidateId || baselineRef || evaluationRunId)`.+- `pairedBootstrapProbability` is the fraction of resampled mean deltas strictly greater than zero; `pairedBootstrapDeltaCILow95` is the 2.5th percentile using the gate-versioned quantile rule.+- The receipt records sample count, seed, implementation version, point estimates, interval, probability, and all paired deltas or their content-addressed evidence object.++### Track C — `metaharness` + darwin bench as the DESCRIBE/fitness backend++- Keep `metaharness score`/`genome` (already integrated) as the fitness **descriptors** and baseline readiness signal feeding the flywheel's selection.+- Allow a signed **darwin bench suite** (`darwin bench create|verify`, taskHash-stamped so it cannot be silently hand-edited), subject to strict corpus-role isolation:+ - **Selection/train** may be read by Darwin while proposing candidates.+ - **Promotion holdout** is sealed before proposal and is unavailable to Darwin and all candidate-selection logic.+ - **Frozen anchor** is versioned, human-reviewed, and never optimized against.+ A suite used for Darwin selection cannot later serve as promotion holdout for the same lineage. The receipt binds every task ID to exactly one role. The gate remains “improve promotion holdout AND no frozen-anchor regression.”++### What ruflo evolves — the surface map (7 + 1)++Darwin's abstract policy surfaces map onto ruflo's real, already-configurable knobs:++| Darwin surface | Ruflo phenotype it mutates |+|---|---|+| `planner` | swarm topology + strategy (hierarchical/mesh, maxAgents, specialized) |+| `contextBuilder` | memory retrieval: HNSW ef/threshold, hybrid vs semantic, RRF/MMR weights |+| `reviewer` | verification-quality gate thresholds (truth-score, adversarial verify depth) |+| `retryPolicy` | hooks retry/escalation policy (3-tier routing thresholds) |+| `toolPolicy` | Selection within an administrator-signed MCP tool/AuthScope envelope; evolution may narrow or choose among pre-approved bundles but cannot add tools, claims, secret scopes, network destinations, or privilege |+| `memoryPolicy` | AgentDB tiers, consolidation cadence, EWC++ retention |+| `scorePolicy` | intelligence-pipeline JUDGE verdict weights |+| **`modelPolicy`** *(8th, ADR-145)* | Selection among administrator-approved `@metaharness/router` candidates and quality thresholds; immutable provider/model allowlists and per-run/per-day cost ceilings remain outside the genome |++The evolvable genome is subordinate to an administrator-signed `SafetyEnvelope`. Before sandbox execution and again before promotion, ruflo rejects any candidate that expands authorization, secret access, network reachability, model/provider access, concurrency, or spending beyond that envelope. Candidates that alter tool composition or inter-agent message policy must also clear the applicable composite-tool and channel guardrails before execution. These are structural preconditions, not benchmark scores and not overrideable warnings.++Resource constraints are also eligibility gates, not merely Pareto dimensions. Before ranking, a candidate must satisfy every hard limit in the signed envelope, including:++```text+p95LatencyMicros <= envelope.maxP95LatencyMicros+costMicrosPerTask <= envelope.maxCostMicrosPerTask+tokensPerTask <= envelope.maxTokensPerTask+failureRate <= envelope.maxFailureRate+evaluationCostMicros <= envelope.maxEvaluationCostMicros+```++Only admissible candidates enter Pareto selection. Missing resource evidence fails eligibility unless the envelope explicitly marks that metric unavailable and non-authorizing. A candidate cannot compensate for violating a hard resource or safety limit by improving quality.++### Dependency policy++- When implemented, `@metaharness/darwin` and `@metaharness/flywheel` will be declared in **`optionalDependencies`** (`^0.8.0` / `^0.1.7`), **not** `dependencies`. Unlike `@metaharness/router` (a hot-path import, hard dep per ADR-321) and `metaharness` (hard dep), the flywheel and evolve engines are **opt-in, heavy, explicitly-invoked loops**. The ADR-150 removability constraint (“works without them”) stays in force. Graceful fallback applies only to `auto`; explicit engine selection fails closed.+- The implementation change must add both pins to a companion guard (`scripts/check-metaharness-pins.mjs` + `metaharness-pin-drift.yml`) and verify package API compatibility, not merely semver freshness. Until those artifacts and optional dependencies land, this ADR records intent rather than shipped state.++### Persistence and key boundaries++- Replace bounded destructive rotation with immutable, content-addressed ledger segments plus a signed head/checkpoint that links each segment to its predecessor. Retention may archive old segments, but must not make a truncated chain report itself as complete.+- Promotion fails closed if its receipt or ledger commit cannot be durably persisted. Best-effort telemetry may still fail open, but it is not promotion evidence.+- Reuse ADR-103's key **provider and storage mechanism**, not an undifferentiated signing domain. Flywheel receipts use a distinct Ed25519 domain-separation prefix and key purpose (`ruflo/flywheel-receipt/v1`) so a witness signature cannot be replayed as a promotion signature.+- Store private signing material outside the repository. Receipts include the public-key identifier, algorithm, signing domain, issuance time, and rotation metadata.++### Active-policy promotion transaction++ADR-322A defines promotion as an atomic compare-and-swap transaction, not a sequence of best-effort file writes. The transaction is eligible only when:++```text+activeChampionRef == receipt.baselineRef+AND receipt.decision == "accepted"+AND receiptState.promotedAt == null+AND ledgerHead == receipt.expectedLedgerHead+AND receipt.gateVersion == activeGateVersion+AND receipt.policySchemaVersion == activePolicySchemaVersion+AND receipt.safetyEnvelopeRef == activeSafetyEnvelopeRef+AND receipt.expiresAt > transactionTime+```++Within one serializable transaction, the promotion authority must:++1. Persist the immutable promotion commit and mark the separate receipt-state record as consumed; the signed evaluation receipt itself remains immutable.+2. Append the commit to lineage and advance the signed ledger head.+3. Compare-and-swap the active champion reference from `baselineRef` to `candidateId`.+4. Allocate and record the next serving epoch.+5. Record `promotedAt`, transaction ID, proposer identity/substitution status, and recovery metadata.++The transaction commits all five state changes or none. Implementations may use a transaction-capable state store or a write-ahead transaction journal with deterministic recovery, but must expose one authoritative state machine. Policy materialization into runtime files occurs from the committed champion and serving epoch; it is idempotent and recoverable, never a second source of truth.++Concurrent attempts against the same receipt or baseline produce at most one successful commit. Repeating an already successful transaction returns its recorded result without reapplying the policy. A stale baseline, changed ledger head, consumed receipt, expired receipt, or changed safety envelope fails closed.++### Threat model++The implementation must trace controls and tests to at least these attackers and failures:++| Threat | Required control |+|---|---|+| Malicious candidate policy | Schema validation, signed non-expanding `SafetyEnvelope`, sandboxing, structural tool/channel checks, held-out and frozen-anchor gates |+| Compromised proposer process | Proposer has no promotion authority; canonical candidate output is treated as untrusted input; explicit proposer identity and substitution are recorded |+| Tampered benchmark corpus | Signed/content-addressed corpus manifest, sealed role assignment, task hashes, and corpus version bound into the receipt |+| Compromised evidence attestor | Attestor allowlist and scope, provenance per term, independent recomputation where possible, revocation and key rotation |+| Replay of an old accepted receipt | Baseline/ledger-head compare-and-swap, expiry, consumed state, lineage and safety-envelope binding |+| Concurrent promoters | Serializable transaction, unique constraint on receipt consumption and serving epoch, idempotent result |+| Compromised signing key | Purpose/domain separation, external key storage, rotation/revocation metadata, incident procedure that prevents new promotions and marks affected receipts |+| Evaluation resource exhaustion | Signed per-run and aggregate budgets, concurrency/wall-time limits, cancellation, sandbox quotas, and fail-closed budget exhaustion |+| Crash or partial persistence | Atomic transaction or write-ahead recovery; fault injection at every boundary; one authoritative champion after recovery |++## Consequences++**Positive**+- A broader explorer (Darwin's 7-surface evolve + Pareto archive) behind ruflo's existing broader promotion gate. Whether it produces better candidates per unit cost is measured rather than assumed.+- Once the V1 evidence requirements and compatibility tests pass, ruflo champions/receipts become portable to the metaharness ecosystem and third parties can independently verify every promotion-authorizing term.+- `modelPolicy` closes the loop between the router product (ADR-148/149) and the evolutionary engine — "which model, when" becomes evolved, not hand-tuned.+- Convergence path: one loop concept, cross-checked against the productized package, instead of two parallel implementations drifting apart.++**Negative / risks**+- **Goodhart / benchmark quality.** A weak held-out corpus evolves toward the wrong objective. Mitigation: keep the ADR-081 human anchor as a hard no-regression guard and darwin's safety rails (exit 99 = safety-disqualified) — never promote on the training corpus alone.+- **Two gates could disagree.** Ruflo's gate and `@metaharness/flywheel`'s gate may differ; ruflo's is the authority. The package's gate is a CI cross-check, never the promoter.+- **0.1.x churn.** `@metaharness/[email protected]` will move fast and may break; the pin-drift guard + optionalDependency + graceful fallback bound the blast radius.+- **MCP/CLI surface growth** and **evolve cost** (sandbox + optional model calls) — all opt-in; evaluation is non-serving by default, and model-backed evolution requires explicit locally enforced limits.+- **Receipt key management** (Ed25519) — reuse ADR-103's key-provider mechanism with a flywheel-specific signing domain and key purpose; do not reuse witness signatures across protocols.+- **Compatibility projection can be lossy.** The package's string-valued policy and four-axis evidence are narrower than ruflo's native schema. The versioned adapter and compatibility tests make any loss explicit; ruflo receipts remain the authoritative evidence until the upstream schema can carry every gate term.++**Neutral**+- Default agent behavior remains opt-in (`RUFLO_HARNESS_LOOP`). At the time of this decision, the legacy generational runner auto-serves the previous promotion on the following tick; the new CLI/MCP surface must not inherit that behavior. Removing the two proposed optional engine packages leaves the local proposer and core CLI operational (ADR-150).++## Phased rollout++- **Phase 0 — implemented.** Evaluation is separate from application; promotion is an explicit, idempotent transaction. The legacy mutation path is disabled by default and available for one compatibility cycle behind `RUFLO_FLYWHEEL_LEGACY_APPLY=1`.+- **Phase 1 — implemented.** `RufloFlywheelReceiptV1`, durable lineage, signature domain separation, independent verification, CLI parity, and CLI/MCP flywheel surfaces are present. `run` is non-serving; `promote --confirm` is explicit.+- **Phase 2 — implemented for bounded retrieval-policy candidates.** Both engines are optional and API-guarded. `auto|local|darwin`, resource admissibility, Pareto filtering, and fail-closed/evaluation-only substitution semantics are enforced. Model-backed mutation remains disabled unless a caller supplies a separately budgeted Darwin invoker.+- **Phase 3 — governed policy expansion.** Introduce the signed `SafetyEnvelope`; then enable constrained `toolPolicy` and `modelPolicy`. Add role-isolated Darwin suites and the Flywheel projection cross-check in CI.+- **Phase 4 — durable autopilot.** Integrate with `/loop` only after fault-injection tests establish idempotency, crash recovery, complete lineage, no privilege expansion, budget enforcement, and explicit serving semantics. Evaluate convergence onto `@metaharness/flywheel` only once its evidence model is provably at least as strong as ruflo's.++## Normative acceptance criteria++ADR-322 is not implementation-complete until automated evidence demonstrates all of the following:++1. Evaluation cannot modify the active champion, serving epoch, or runtime policy under normal operation or injected process, filesystem, and database failures.+2. One hundred concurrent promotion attempts against one accepted receipt produce exactly one successful commit and one stable idempotent result for all retries.+3. A receipt whose baseline or expected ledger head is stale is rejected without mutation.+4. A candidate cannot expand any field of the signed `SafetyEnvelope`, including authorization, tools, claims, secrets, network, provider/model access, concurrency, or spending.+5. Altering any canonical receipt byte, referenced evidence object, policy manifest, or lineage link causes verification to fail.+6. Every promotion-authorizing term is either independently recomputed or cryptographically bound to an approved, scoped attestor and reported as such.+7. Explicit Darwin mode fails closed when Darwin is absent, incompatible, times out before producing a complete archive, or violates its resource budget.+8. `auto` proposer substitution is evaluation-only unless the active signed policy authorizes the exact substitution and the receipt records it.+9. Local proposer mode is byte-reproducible for identical versioned inputs, seed, platform contract, and corpus.+10. Fault injection before and after every promotion transaction operation recovers to exactly one consistent active champion, ledger head, receipt-consumption state, and serving epoch.+11. Removing both optional packages leaves local evaluation, local promotion, receipt verification, and the core CLI operational.+12. The default statistical gate rejects improvements below its lift/significance thresholds and reproduces the recorded decision from paired observations.+13. Hard latency, cost, token, failure-rate, and evaluation-budget violations are rejected before Pareto ranking.+14. An ADR-322C interoperability fixture round-trips through the Flywheel adapter without changing any ruflo-authorizing evidence; any intentionally unrepresentable field is reported as projection loss and prevents an interoperability claim.+15. The temporary legacy mutation flag emits a deprecation event, is never used by the new CLI/MCP surface, and is removed on the stated release boundary.++The load-bearing concurrency/fault test is:++> Run 100 concurrent promotion attempts against one accepted receipt while injecting process termination at every persistence boundary. Exactly one promotion succeeds; one champion and serving epoch are active; one receipt is consumed; and the signed ledger verifies from head to genesis.++## Alternatives considered++- **Rip-and-replace: adopt `@metaharness/flywheel` as the runtime, retire ADR-176.** Rejected — a 0.1.7 package would replace ruflo's broader local gate (anchor/canary/drift/replay/receipt coverage) and its live-neural-store integration with something unproven. Convergence, not replacement.+- **Status quo (bespoke flywheel only).** Rejected — leaves the weak hill-climb proposer, no ecosystem-portable receipts, and no evolvable routing. Ignores the user's explicit request to use the three packages.+- **Hard-dependency the evolve/flywheel engines (like ADR-321).** Rejected — they are opt-in, explicitly-invoked, heavy loops, not hot-path imports; keeping them optional preserves ADR-150 removability at zero functional cost.+- **Numeric-genome evolution à la MetaBioHacker/PixelRAG** (evolve a JSON genome, not source surfaces). Noted as the right model for ruflo's *config* surfaces (which are parameters, not source), and folded into Track A — darwin's `mapLimit`/`paretoFront` primitives over a ruflo config genome, with `evolve()`'s source-surface mutation reserved for the harness files it actually owns.diff --git a/v3/docs/adr/ADR-322A-evaluation-promotion-transaction.md b/v3/docs/adr/ADR-322A-evaluation-promotion-transaction.mdnew file mode 100644index 0000000000..ce746872b3--- /dev/null+++ b/v3/docs/adr/ADR-322A-evaluation-promotion-transaction.md@@ -0,0 +1,118 @@+# ADR-322A: Evaluation and promotion transaction model++- **Status**: Accepted — implemented+- **Parent**: ADR-322+- **Rollout flag**: `RUFLO_FLYWHEEL_TRANSACTION_V1`+- **Owner**: ruflo flywheel runtime++## Scope++This specification defines the boundary between evaluating a candidate and making it active. It owns purity, eligibility, compare-and-swap promotion, serving epochs, idempotency, concurrency, crash recovery, and temporary legacy behavior. It does not define how candidates are proposed (ADR-322B) or how receipts are encoded and verified (ADR-322C).++## State model++The promotion authority maintains one serializable state machine:++```text+ActivePolicyState {+ lineageId+ activeChampionRef+ activeGateVersion+ activePolicySchemaVersion+ activeSafetyEnvelopeRef+ ledgerHead+ servingEpoch+ transactionVersion+}++ReceiptState {+ receiptId+ promotedAt: timestamp | null+ promotionTransactionId: UUIDv7 | null+ status: evaluated | consumed | expired | revoked+}+```++Signed evaluation receipts are immutable. Consumption and promotion metadata live in `ReceiptState`.++## Interfaces++```text+evaluateFlywheelCandidate(input) -> EvaluationReceipt+promoteFlywheelCandidate(receiptId, confirmation) -> PromotionResult+materializeServingEpoch(servingEpoch) -> MaterializationResult+recoverPromotionState() -> RecoveryResult+```++`evaluateFlywheelCandidate` may persist evidence and receipts but cannot modify `ActivePolicyState`, runtime policy files, or served state.++`promoteFlywheelCandidate` is the only ADR-322 interface authorized to advance the active champion. It requires explicit confirmation for interactive CLI/MCP calls.++## Promotion compare-and-swap++Promotion is eligible only when:++```text+activeChampionRef == receipt.baselineRef+AND receipt.decision == "accepted"+AND receiptState.promotedAt == null+AND receiptState.status == "evaluated"+AND ledgerHead == receipt.expectedLedgerHead+AND receipt.gateVersion == activeGateVersion+AND receipt.policySchemaVersion == activePolicySchemaVersion+AND receipt.safetyEnvelopeRef == activeSafetyEnvelopeRef+AND receipt.expiresAt > transactionTime+```++Within one serializable transaction:++1. Persist the immutable promotion commit.+2. Mark `ReceiptState` consumed and bind its transaction ID.+3. Append lineage and advance the signed ledger head.+4. Compare-and-swap `activeChampionRef`.+5. Increment and record `servingEpoch`.+6. Record `promotedAt`, proposer/substitution identity, and recovery metadata.++All changes commit or none do. A transaction-capable store is preferred; a write-ahead journal is acceptable only when deterministic recovery is proven by the same fault suite.++## Serving++The committed active champion is authoritative. Runtime materialization is derived, idempotent state:++```text+ServedPolicyState {+ championRef+ servingEpoch+ materializedAt+ materializationHash+}+```++Materialization writes a complete epoch to a temporary location, validates its hash, then atomically switches the runtime pointer. A crash can leave the previous epoch served temporarily, but cannot create two authoritative champions. Recovery converges to the committed `ActivePolicyState`.++## Idempotency and concurrency++- A unique constraint covers `ReceiptState.receiptId` consumption.+- A unique monotonic constraint covers each lineage's `servingEpoch`.+- Repeating a successful transaction returns the recorded `PromotionResult`.+- Concurrent attempts using one receipt or baseline produce at most one commit.+- Stale baseline, ledger, gate, policy schema, safety envelope, expiry, or receipt state fails closed.++## Legacy boundary++For at most one release, legacy implicit application is available only with:++```text+RUFLO_FLYWHEEL_LEGACY_APPLY=1+```++Every use emits a structured deprecation event. New CLI/MCP surfaces never set or honor this flag. Without it, the compatibility wrapper evaluates only. The implicit-application path is removed in the following release.++## Required tests++1. Evaluation cannot modify active, served, or runtime policy state under fault injection.+2. One hundred concurrent attempts against one receipt produce exactly one promotion.+3. Stale baseline and ledger-head receipts are rejected.+4. Repeating a successful transaction is idempotent.+5. Process termination at every transaction and materialization boundary recovers to one active champion, one ledger head, one receipt state, and one serving epoch.+6. Legacy mutation is disabled by default, emits deprecation when enabled, and is unreachable from new CLI/MCP handlers.diff --git a/v3/docs/adr/ADR-322B-darwin-proposer-adapter.md b/v3/docs/adr/ADR-322B-darwin-proposer-adapter.mdnew file mode 100644index 0000000000..122fdee1b8--- /dev/null+++ b/v3/docs/adr/ADR-322B-darwin-proposer-adapter.md@@ -0,0 +1,96 @@+# ADR-322B: Darwin proposer adapter++- **Status**: Accepted — implemented for bounded retrieval-policy candidates+- **Parent**: ADR-322+- **Rollout flag**: `RUFLO_FLYWHEEL_DARWIN_V1`+- **Owner**: ruflo Metaharness integration++## Scope++This specification defines proposer selection, Darwin invocation, archive translation, sandbox and resource controls, substitution behavior, and comparison with the local proposer. A proposer produces untrusted candidates only. It cannot issue promotion decisions or mutate active policy.++## Interface++```text+proposeCandidates({+ proposerMode,+ baselinePolicy,+ policySchemaVersion,+ selectionCorpusRef,+ safetyEnvelopeRef,+ budget,+ seed+}) -> CandidateArchive+```++`CandidateArchive` records:++```text+archiveVersion+requestedProposer+effectiveProposer+substitutionReason+packageName+packageVersion+packageIntegrity+invocationHash+baselineRef+selectionCorpusRef+safetyEnvelopeRef+seed+candidates[]+resourceUsage+completed+```++Each candidate has a canonical `candidateId`, mutation description, parent references, surface, raw proposer score, and policy-schema validation result. Proposer scores are selection metadata, not ruflo promotion evidence.++## Modes++- `local`: run the deterministic local proposer.+- `darwin`: require a compatible Darwin package and complete archive; any absence, incompatibility, timeout, malformed output, safety exit, or budget violation fails closed.+- `auto`: prefer Darwin. If it cannot complete, record the failure and permit local evaluation-only substitution.++An `auto` substitution cannot promote unless the active administrator-signed substitution policy explicitly allows `darwin -> local` for the current gate and safety-envelope versions. Default policy denies promotion.++## Darwin invocation++The initial adapter invokes:++```text+@metaharness/darwin@~0.8.0+metaharness-darwin evolve+--sandbox real|mock|agent+--selection pareto+--mutator deterministic|ruvllm+```++The adapter verifies package version, resolved package integrity, supported command/API shape, exit classification, complete archive schema, and candidate count before accepting output.++No model credential means only the deterministic mutator is permitted. `ruvllm` requires explicit confirmation and immutable ceilings for USD, requests, tokens, concurrency, wall time, and sandbox resources. Budget exhaustion cancels the run and produces no promotable archive.++## Safety and corpus boundaries++- All proposer output is untrusted and validated against the versioned policy schema.+- Candidates that expand the signed `SafetyEnvelope` are rejected before execution.+- Tool-composition and inter-agent channel mutations clear structural guards before sandboxing.+- Darwin reads only the selection corpus. It cannot access sealed promotion holdout or frozen-anchor answers.+- Selection, holdout, and anchor task IDs are bound to disjoint signed role manifests.++## Admissibility and ranking++Hard envelope limits for authorization, latency, cost, tokens, failure rate, evaluation cost, network, and concurrency are evaluated before Pareto ranking. Only admissible candidates enter the archive presented to ADR-322A.++## Comparative claim++Darwin is described as broader, not inherently superior. Any superiority claim requires a controlled comparison using identical baselines, selection budgets, sealed holdouts, gate versions, seeds, and resource accounting. Report quality lift, accepted-candidate rate, wall time, tokens, USD, and reproducibility for both Darwin and local modes.++## Required tests++1. Explicit Darwin mode fails closed for missing, incompatible, timed-out, malformed, incomplete, or over-budget runs.+2. `auto` substitution is fully recorded and evaluation-only by default.+3. Local mode is byte-reproducible for identical versioned inputs and platform contract.+4. Darwin cannot read sealed holdout or anchor answers.+5. Safety-envelope expansion is rejected before sandbox execution.+6. Package and invocation identity are bound into every archive and downstream receipt.+7. Only admissible candidates enter Pareto ranking.diff --git a/v3/docs/adr/ADR-322C-receipt-ledger-verification.md b/v3/docs/adr/ADR-322C-receipt-ledger-verification.mdnew file mode 100644index 0000000000..f845f43860--- /dev/null+++ b/v3/docs/adr/ADR-322C-receipt-ledger-verification.md@@ -0,0 +1,152 @@+# ADR-322C: Receipt, ledger, and verification protocol++- **Status**: Accepted — implemented+- **Parent**: ADR-322+- **Rollout flag**: `RUFLO_FLYWHEEL_RECEIPT_V1`+- **Owner**: ruflo verification and lineage++## Scope++This specification defines canonical encoding, identifiers, evidence provenance, statistical decisions, signatures, ledger continuity, independent verification, and projection to `@metaharness/flywheel`. It does not authorize promotion; ADR-322A consumes a verified accepted receipt.++## Canonical format++```text+Canonical JSON: RFC 8785 JCS+Digest: SHA-256+Signature: Ed25519(domainPrefix || 0x00 || canonicalBytes)+Content ID: sha256:<lowercase-hex>+Timestamp: RFC 3339 UTC as YYYY-MM-DDTHH:mm:ss.sssZ+```++Non-finite numbers and negative zero are forbidden. Signed policy fractions use schema-quantized decimal strings or scaled integers. Metrics declare scale; currency uses integer micros plus ISO-4217 currency, duration uses integer microseconds, and energy uses integer microjoules when available. Unknown fields fail verification for a given schema version.++## Identity domains++```text+candidateId = SHA-256(JCS(candidate policy))+evaluationRunId = UUIDv7 per execution attempt+receiptId = SHA-256(JCS(unsigned receipt payload))+lineageId = UUIDv7 per persistent evolutionary lineage+```++Repeated candidate executions share `candidateId` but receive distinct run and receipt identities.++## RufloFlywheelReceiptV1++The unsigned payload contains:++```text+schemaVersion+receiptIdDomain+lineageId+candidateId+evaluationRunId+baselineRef+expectedLedgerHead+candidatePolicyRef+gateVersion+policySchemaVersion+safetyEnvelopeRef+proposerIdentity+proposerSubstitution+corpusRoleManifestRef+heldoutEvidenceRef+anchorEvidenceRef+canaryEvidenceRef+driftEvidenceRef+replayEvidenceRef+receiptCoverageEvidenceRef+resourceEvidenceRef+statisticalDecision+termVerification[]+decision+issuedAt+expiresAt+```++Every evidence object records origin/provenance type, producer or attestor, authority scope, subject, transformation lineage, content hash, schema version, and collection time. Each authorizing term is labeled `recomputed`, `signature-verified`, or `trusted-assertion`.++## Default statistical rule++```text+relativeLift >= 0.02+AND pairedBootstrapProbability(candidate > baseline) >= 0.95+AND pairedBootstrapDeltaCILow95 > 0+AND frozenAnchorRegression <= 0+```++The paired bootstrap uses 10,000 task-level paired resamples. Its deterministic seed is:++```text+SHA-256("ruflo/bootstrap/v1" ||+ corpusHash ||+ candidateId ||+ baselineRef ||+ evaluationRunId)+```++The receipt records the rule, metric epsilon, sample count, seed, implementation version, quantile rule, point estimates, probability, confidence interval, and paired deltas or their content-addressed object. Gate-rule changes require a new version and are not retroactive.++## Signatures and keys++Receipt domain:++```text+ruflo/flywheel-receipt/v1+```++Ledger-head domain:++```text+ruflo/flywheel-ledger-head/v1+```++Keys use ADR-103's provider mechanism but a distinct purpose/domain. Private material remains outside the repository. Receipts carry public-key ID, algorithm, purpose, issuance time, and rotation/revocation metadata.++## Ledger++The ledger consists of immutable, content-addressed segments. Each segment binds:++```text+segmentId+previousSegmentId+firstSequence+lastSequence+commits[]+segmentMerkleRoot+createdAt+```++A signed head binds `lineageId`, current segment, current sequence, active champion, gate version, and timestamp. Archiving may move segments but cannot delete continuity evidence or report a truncated chain as complete.++Promotion fails closed if the promotion commit and new head cannot be durably committed by ADR-322A.++## Verification++A verifier:++1. Parses the declared schema and rejects unknown or invalid fields.+2. Reconstructs JCS bytes and verifies content IDs and signatures.+3. Resolves every evidence reference and verifies provenance/authority.+4. Recomputes all reproducible terms, statistics, and the decision.+5. Checks corpus-role disjointness and sealed manifests.+6. Checks baseline, safety envelope, gate, policy schema, expiry, and ledger continuity.+7. Reports every term as recomputed, signature-verified, or trusted assertion.++Verification cannot label a promotion independently verified while any authorizing term remains an unapproved assertion.++## Flywheel projection++The adapter projects ruflo policy and evidence into `@metaharness/flywheel` types and round-trips the ruflo envelope unchanged. Because the upstream string-valued policy and four-axis evidence are narrower, projection loss is explicit. Any loss affecting an authorizing term prevents an interoperability claim and can never weaken the ruflo gate.++## Required tests++1. Altering any canonical receipt byte or referenced object fails verification.+2. All authorizing terms reproduce from the fixture or bind to an approved scoped attestor.+3. Float/decimal fixtures produce identical hashes across supported runtimes.+4. Repeated candidate runs retain candidate identity but have distinct run and receipt identities.+5. Segment removal, reordering, or parent alteration breaks head-to-genesis verification.+6. Key revocation and rotation produce the declared historical/current verification behavior.+7. The Flywheel adapter round-trips without loss of ruflo-authorizing evidence; projection loss blocks interoperability claims.+8. Removing optional packages does not disable native receipt or ledger verification.diff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yamlindex c1e8223918..556e1672c9 100644--- a/v3/pnpm-lock.yaml+++ b/v3/pnpm-lock.yaml@@ -157,6 +157,9 @@ importers:'@metaharness/darwin':specifier: ^0.8.0version: 0.8.0+ '@metaharness/flywheel':+ specifier: ^0.1.7+ version: 0.1.7agentdb:specifier: ^3.0.0-alpha.17version: 3.0.0-alpha.17(@types/[email protected])([email protected])