🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(flywheel): reject unknown fields in receipt and commit verification
ruv7d0bb9c53b9d
diff --git a/v3/@claude-flow/cli/__tests__/flywheel-receipt.test.ts b/v3/@claude-flow/cli/__tests__/flywheel-receipt.test.tsindex 1dbc40ca22..b51df5d0b8 100644--- a/v3/@claude-flow/cli/__tests__/flywheel-receipt.test.ts+++ b/v3/@claude-flow/cli/__tests__/flywheel-receipt.test.ts@@ -1,10 +1,12 @@import { describe, expect, it } from 'vitest';-import { generateKeyPairSync } from 'node:crypto';+import { generateKeyPairSync, sign as edSign } from 'node:crypto';import {GENESIS_LEDGER_HEAD,+ RECEIPT_DOMAIN,canonicalizeJcs,createFlywheelReceipt,policyCandidateId,+ sha256Ref,verifyFlywheelReceipt,} from '../src/services/flywheel-receipt.js';@@ -39,6 +41,30 @@ function acceptedReceipt(key = keys(), now = 1_700_000_000_000) {};}+/**+ * Rebuild a receipt's identity and signature after mutating its payload — what a+ * producer emitting a non-contract field actually does. The result is internally+ * consistent and signed by a trusted key, so only a strict field check can refuse it.+ */+function resign(receipt: any, privateKeyPem: string, publicKeyPem: string) {+ const { receiptId: _drop, ...base } = receipt.payload;+ const payload = { ...base, receiptId: sha256Ref(canonicalizeJcs(base)) };+ const signedBytes = Buffer.concat([+ Buffer.from(RECEIPT_DOMAIN, 'utf8'),+ Buffer.from([0]),+ Buffer.from(canonicalizeJcs(payload), 'utf8'),+ ]);+ return {+ payload,+ signature: {+ algorithm: 'ed25519' as const,+ domain: RECEIPT_DOMAIN,+ publicKeyPem,+ signatureBase64: edSign(null, signedBytes, privateKeyPem).toString('base64'),+ },+ };+}+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}');@@ -73,6 +99,63 @@ describe('flywheel receipt protocol', () => {expect(second.payload.receiptId).not.toBe(receipt.payload.receiptId);});+ it('rejects an unknown payload field even when the signature over it is valid (ADR-322C, #3068)', () => {+ const { key, receipt } = acceptedReceipt();+ const forged: any = structuredClone(receipt);+ forged.payload.attackerControlledField = 'not defined by ADR-322C';+ const signed = resign(forged, key.privateKeyPem, key.publicKeyPem);++ const verification = verifyFlywheelReceipt(signed as any, new Set([key.publicKeyPem]));+ expect(verification.valid).toBe(false);+ expect(verification.errors).toContain('unknown field: payload.attackerControlledField');+ // The rejection must be attributable to the field, not to a broken signature —+ // a caller triaging this needs to tell "unrecognized" from "tampered".+ expect(verification.errors.join(' ')).not.toMatch(/signature invalid|content ID mismatch/);+ });++ it('rejects unknown fields in nested contract objects', () => {+ const { key, receipt } = acceptedReceipt();+ const forged: any = structuredClone(receipt);+ forged.payload.statistics.extraStat = 1;+ forged.payload.resourceEvidence.extraCost = 2;+ forged.payload.evidence.corpusRoles.extraRole = [];++ const signed: any = resign(forged, key.privateKeyPem, key.publicKeyPem);+ signed.signature.extraSignatureField = 'x'; // outside the signed bytes by construction++ const errors = verifyFlywheelReceipt(signed, new Set([key.publicKeyPem])).errors;+ expect(errors).toContain('unknown field: payload.statistics.extraStat');+ expect(errors).toContain('unknown field: payload.resourceEvidence.extraCost');+ expect(errors).toContain('unknown field: payload.evidence.corpusRoles.extraRole');+ expect(errors).toContain('unknown field: signature.extraSignatureField');+ });++ it('keeps contract-open objects open', () => {+ const key = keys();+ const receipt = createFlywheelReceipt({+ baselineRef: policyCandidateId({ alpha: 0.5 }),+ candidatePolicy: { alpha: 0.3, anyPolicyKnobTheSchemaOwns: 'ok', nested: { deep: 1 } },+ 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, anyCallerNamedGate: true },+ evidence: {+ corpusRoles: { selectionTaskIds: [], promotionHoldoutTaskIds: [], guardTaskIds: [] },+ verification: { arbitraryEvidencePayload: true },+ canary: { alsoArbitrary: 1 },+ },+ bootstrapIterations: 500,+ ...key,+ });+ // candidatePolicy is owned by policySchemaVersion, gates is a caller-named+ // term map, and the evidence payloads are evidence-specific — none are closed.+ expect(verifyFlywheelReceipt(receipt, new Set([key.publicKeyPem])).valid).toBe(true);+ });+it('recomputes the statistical verdict instead of trusting signed fields', () => {const { key, receipt } = acceptedReceipt();const forged = structuredClone(receipt);diff --git a/v3/@claude-flow/cli/__tests__/flywheel-transaction.test.ts b/v3/@claude-flow/cli/__tests__/flywheel-transaction.test.tsindex e84333bad9..a61c16a0ad 100644--- a/v3/@claude-flow/cli/__tests__/flywheel-transaction.test.ts+++ b/v3/@claude-flow/cli/__tests__/flywheel-transaction.test.ts@@ -1,11 +1,13 @@import { describe, expect, it } from 'vitest';import { generateKeyPairSync } from 'node:crypto';-import { mkdtempSync } from 'node:fs';+import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import {+ canonicalizeJcs,createFlywheelReceipt,policyCandidateId,+ sha256Ref,} from '../src/services/flywheel-receipt.js';import {promoteFlywheelCandidate,@@ -90,6 +92,39 @@ describe('flywheel promotion transaction', () => {expect(verifyFlywheelLedger(root)).toMatchObject({ valid: true, commits: 1 });});+ it('rejects a commit carrying a field the contract does not define (#3068)', async () => {+ const root = mkdtempSync(join(tmpdir(), 'flywheel-strict-commit-'));+ const key = keyPair();+ const receipt = makeReceipt(key);+ await registerFlywheelReceipt(root, receipt, 1_700_000_000_001);+ await promoteFlywheelCandidate(root, receipt.payload.receiptId, {+ confirm: true,+ now: 1_700_000_000_100,+ trustedPublicKeys: new Set([key.publicKeyPem]),+ applyFn: apply,+ });+ expect(verifyFlywheelLedger(root).valid).toBe(true);++ // The commit hash covers whatever fields the commit carries, so an undefined+ // field chains cleanly unless the field set itself is closed. Same class of+ // permissiveness as the receipt path, hence the same check.+ const statePath = join(root, '.claude-flow', 'flywheel-v1', 'transaction-state.json');+ const state = JSON.parse(readFileSync(statePath, 'utf8'));+ const { commitId: _drop, ...core } = state.commits[0];+ const tampered = { ...core, smuggledField: 'not defined by ADR-322C' };+ state.commits[0] = { ...tampered, commitId: sha256Ref(canonicalizeJcs(tampered)) };+ state.ledgerHead = sha256Ref(canonicalizeJcs({+ previous: core.previousLedgerHead,+ commitId: state.commits[0].commitId,+ }));+ writeFileSync(statePath, JSON.stringify(state));++ const verification = verifyFlywheelLedger(root);+ expect(verification.valid).toBe(false);+ expect(verification.errors).toContain('unknown field: commits[0].smuggledField');+ expect(verification.errors.join(' ')).not.toMatch(/hash mismatch|parent mismatch/);+ });+it('requires explicit signer trust and rejects stale baselines', async () => {const root = mkdtempSync(join(tmpdir(), 'flywheel-trust-'));const key = keyPair();diff --git a/v3/@claude-flow/cli/src/services/flywheel-receipt.ts b/v3/@claude-flow/cli/src/services/flywheel-receipt.tsindex fbd7f5eddf..d13f7b1e2b 100644--- a/v3/@claude-flow/cli/src/services/flywheel-receipt.ts+++ b/v3/@claude-flow/cli/src/services/flywheel-receipt.ts@@ -144,6 +144,80 @@ export interface CreateReceiptInput {bootstrapIterations?: number;}+/**+ * Closed field sets for ADR-322C strict verification. Three objects stay open by+ * contract: `candidatePolicy` is owned by `policySchemaVersion`, `gates` is a+ * caller-named term map, and `evidence.verification` / `evidence.canary` carry+ * evidence-specific payloads.+ */+const RECEIPT_FIELDS = {+ root: ['payload', 'signature'],+ payload: [+ 'schemaVersion', 'receiptId', 'lineageId', 'candidateId', 'evaluationRunId',+ 'baselineRef', 'expectedLedgerHead', 'candidatePolicy', 'gateVersion',+ 'policySchemaVersion', 'safetyEnvelopeRef', 'anchorRef', 'requestedProposer',+ 'effectiveProposer', 'proposerSubstitution', 'corpusVersion', 'corpusHash',+ 'baselineScore', 'candidateScore', 'heldOutDeltas', 'pairedOutcomes',+ 'statistics', 'gates', 'resourceEvidence', 'evidence', 'termVerification',+ 'decision', 'issuedAt', 'expiresAt',+ ],+ signature: ['algorithm', 'domain', 'publicKeyPem', 'signatureBase64'],+ statistics: [+ 'ruleVersion', 'relativeLift', 'pairedBootstrapProbability',+ 'pairedBootstrapDeltaCILow95', 'frozenAnchorRegression', 'iterations',+ 'seedHex', 'significant', 'accepted',+ ],+ resourceEvidence: [+ 'p95LatencyMicros', 'costMicrosPerTask', 'tokensPerTask', 'failureRate',+ 'evaluationCostMicros', 'energyMicrojoules', 'currency',+ ],+ evidence: ['corpusRoles', 'verification', 'canary'],+ corpusRoles: ['selectionTaskIds', 'promotionHoldoutTaskIds', 'guardTaskIds'],+ pairedOutcome: ['taskId', 'baselineScore', 'candidateScore'],+ termVerification: ['term', 'verification', 'evidenceRef', 'attestor'],+} as const;++/** Names present on `value` that the contract does not define, as `unknown field: <path>`. */+export function collectUnknownFields(value: unknown, allowed: readonly string[], path: string): string[] {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return [];+ return Object.keys(value as Record<string, unknown>)+ .filter((key) => !allowed.includes(key))+ .map((key) => `unknown field: ${path}.${key}`);+}++/**+ * ADR-322C: unknown fields fail verification for a given schema version.+ * Enforced here rather than delegated to out-of-band schema validation, because+ * a signature is valid over whatever the producer canonicalized — including+ * fields the contract never defined — so a permissive verifier lets a producer+ * attach arbitrary signed data that still verifies cleanly.+ */+export function collectUnknownReceiptFields(receipt: FlywheelEvaluationReceipt): string[] {+ const errors = collectUnknownFields(receipt, RECEIPT_FIELDS.root, 'receipt');+ const payload = receipt.payload;+ if (!payload || typeof payload !== 'object') return errors;+ const evidence = payload.evidence;+ errors.push(+ ...collectUnknownFields(payload, RECEIPT_FIELDS.payload, 'payload'),+ ...collectUnknownFields(receipt.signature, RECEIPT_FIELDS.signature, 'signature'),+ ...collectUnknownFields(payload.statistics, RECEIPT_FIELDS.statistics, 'payload.statistics'),+ ...collectUnknownFields(payload.resourceEvidence, RECEIPT_FIELDS.resourceEvidence, 'payload.resourceEvidence'),+ ...collectUnknownFields(evidence, RECEIPT_FIELDS.evidence, 'payload.evidence'),+ ...collectUnknownFields(evidence?.corpusRoles, RECEIPT_FIELDS.corpusRoles, 'payload.evidence.corpusRoles'),+ );+ if (Array.isArray(payload.pairedOutcomes)) {+ payload.pairedOutcomes.forEach((outcome, i) => {+ errors.push(...collectUnknownFields(outcome, RECEIPT_FIELDS.pairedOutcome, `payload.pairedOutcomes[${i}]`));+ });+ }+ if (Array.isArray(payload.termVerification)) {+ payload.termVerification.forEach((term, i) => {+ errors.push(...collectUnknownFields(term, RECEIPT_FIELDS.termVerification, `payload.termVerification[${i}]`));+ });+ }+ return errors;+}+function assertJsonValue(value: unknown, path = '$'): void {if (value === null || typeof value === 'string' || typeof value === 'boolean') return;if (typeof value === 'number') {@@ -416,6 +490,7 @@ export function verifyFlywheelReceipt(receipt: FlywheelEvaluationReceipt, trusteconst errors: string[] = [];try {if (receipt.payload.schemaVersion !== RECEIPT_SCHEMA) errors.push('unsupported receipt schema');+ errors.push(...collectUnknownReceiptFields(receipt));const { receiptId: _receiptId, ...base } = receipt.payload;const expectedId = sha256Ref(canonicalizeJcs(receiptIdentityPayload(base)));if (expectedId !== receipt.payload.receiptId) errors.push('receipt content ID mismatch');diff --git a/v3/@claude-flow/cli/src/services/flywheel-transaction.ts b/v3/@claude-flow/cli/src/services/flywheel-transaction.tsindex e7226cdd2e..0ddab1db3d 100644--- a/v3/@claude-flow/cli/src/services/flywheel-transaction.ts+++ b/v3/@claude-flow/cli/src/services/flywheel-transaction.ts@@ -12,6 +12,7 @@ import { applyChampionParams, type ApplyResult } from '../config/harness-feedbacimport {GENESIS_LEDGER_HEAD,canonicalizeJcs,+ collectUnknownFields,sha256Ref,uuidV7,verifyFlywheelReceipt,@@ -55,6 +56,12 @@ export interface PromotionCommit {promotedAt: number;}+const COMMIT_FIELDS = [+ 'commitId', 'transactionId', 'receiptId', 'lineageId', 'sequence',+ 'previousLedgerHead', 'baselineRef', 'candidateId', 'servingEpoch',+ 'proposer', 'proposerSubstitution', 'promotedAt',+] as const;+export interface FlywheelTransactionState {version: typeof STATE_VERSION;activeChampionRef: string | null;@@ -623,6 +630,10 @@ export function verifyFlywheelLedger(root: string): { valid: boolean; errors: stfor (let i = 0; i < state.commits.length; i++) {const commit = state.commits[i];const { commitId, ...core } = commit;+ // Same ADR-322C strictness as the receipt path: a commit hashes consistently+ // over whatever fields it carries, so an undefined field would otherwise+ // chain cleanly (ruflo#3068).+ errors.push(...collectUnknownFields(commit, COMMIT_FIELDS, `commits[${i}]`));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}`);