π 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): encode candidatePolicy fractions as decimal strings (#3229) (#3235)
rUvea2df4726cbe
diff --git a/v3/@claude-flow/cli/__tests__/flywheel-receipt.test.ts b/v3/@claude-flow/cli/__tests__/flywheel-receipt.test.tsindex 25699c9d0e..6a1ef5fca2 100644--- a/v3/@claude-flow/cli/__tests__/flywheel-receipt.test.ts+++ b/v3/@claude-flow/cli/__tests__/flywheel-receipt.test.ts@@ -5,6 +5,8 @@ import {RECEIPT_DOMAIN,canonicalizeJcs,createFlywheelReceipt,+ assertReceiptNumberDomain,+ encodePolicyFractions,policyCandidateId,sha256Ref,verifyFlywheelReceipt,@@ -254,3 +256,100 @@ describe('flywheel receipt protocol', () => {expect(receipt.payload.decision).toBe('rejected');});});++describe('ADR-322C rule 2 β fractional values are decimal strings (#3229)', () => {+ /**+ * The exact candidatePolicy v3.38.21 wrote, from the issue. Fractions become+ * scale-12 decimal strings; integers stay JSON numbers, which is what the+ * contract's own example shows (`{"hnswEf": 128, "hybridWeight": "0.65"}`).+ */+ it('encodes the live RetrievalConfig shape from the bug report', () => {+ const encoded = encodePolicyFractions({+ alpha: 0.3,+ subjectWeight: 1,+ mmrLambda: 0.5,+ bodyWeight: 1.5,+ typePenaltyFactor: 0.5,+ });+ expect(encoded).toEqual({+ alpha: '0.3',+ subjectWeight: 1,+ mmrLambda: '0.5',+ bodyWeight: '1.5',+ typePenaltyFactor: '0.5',+ });+ });++ it('recurses through nested objects and arrays', () => {+ expect(+ encodePolicyFractions({ outer: { inner: 0.25 }, list: [1, 0.5, 'x'], flag: true }),+ ).toEqual({ outer: { inner: '0.25' }, list: [1, '0.5', 'x'], flag: true });+ });++ /**+ * Idempotence is load-bearing: `policyCandidateId` encodes at the hashing+ * boundary, so a raw config and an already-encoded policy must hash the+ * same or `verify` could never recompute the ID from the payload.+ */+ it('is idempotent, so a raw and an encoded policy share one candidate ID', () => {+ const raw = { alpha: 0.3, hnswEf: 128 };+ const once = encodePolicyFractions(raw);+ expect(encodePolicyFractions(once)).toEqual(once);+ expect(policyCandidateId(raw)).toBe(+ policyCandidateId(once as Record<string, unknown>),+ );+ });++ it('normalizes negative zero rather than emitting -0', () => {+ expect(encodePolicyFractions({ z: -0 })).toEqual({ z: '0' });+ });++ it('refuses a non-finite policy value instead of writing null', () => {+ expect(() => encodePolicyFractions({ a: Number.NaN })).toThrow(/must be finite/);+ expect(() => encodePolicyFractions({ a: Number.POSITIVE_INFINITY })).toThrow(/must be finite/);+ });++ /** A produced receipt must satisfy the contract it claims. */+ it('produces a receipt whose candidatePolicy carries no fractional floats', () => {+ const { receipt } = acceptedReceipt();+ const policy = receipt.payload.candidatePolicy as Record<string, unknown>;+ expect(policy.alpha).toBe('0.3');+ for (const [k, v] of Object.entries(policy)) {+ if (typeof v === 'number') {+ expect(Number.isInteger(v), `${k} must be an integer if it is a number`).toBe(true);+ }+ }+ });++ /**+ * The enforcement half. Before this, `assertJsonValue` accepted any finite+ * non-`-0` number, so ruflo verified its own non-conforming receipts while+ * autogenous's stricter verifier rejected them. The error must NAME the+ * path β the original bug needed a live fixture to find precisely because+ * neither verifier said which field was wrong.+ */+ it('rejects a fractional JSON number anywhere in the payload, naming the path', () => {+ const { receipt } = acceptedReceipt();+ const tampered = JSON.parse(JSON.stringify(receipt));+ tampered.payload.candidatePolicy.alpha = 0.3;+ // Asserted at the RECEIPT boundary, not in the shared JCS canonicalizer β+ // that is used by the proposer envelope and the ledger, which the contract+ // does not govern.+ const result = verifyFlywheelReceipt(tampered);+ expect(result.valid).toBe(false);+ expect(result.errors.join(' ')).toMatch(+ /fractional number at \$\.candidatePolicy\.alpha must be a scale-12 decimal string/,+ );+ });++ it('still accepts integers and scaled integers as JSON numbers', () => {+ expect(() =>+ assertReceiptNumberDomain({ micros: 1_500_000, iterations: 2000, depth: 24 }),+ ).not.toThrow();+ });++ /** Regression guard: the rule must NOT live in the shared canonicalizer. */+ it('leaves the shared JCS canonicalizer permissive for non-receipt structures', () => {+ expect(() => canonicalizeJcs({ candidates: [{ policy: { alpha: 0.3 } }] })).not.toThrow();+ });+});diff --git a/v3/@claude-flow/cli/src/services/flywheel-receipt.ts b/v3/@claude-flow/cli/src/services/flywheel-receipt.tsindex 00078ce764..83b760e7f8 100644--- a/v3/@claude-flow/cli/src/services/flywheel-receipt.ts+++ b/v3/@claude-flow/cli/src/services/flywheel-receipt.ts@@ -262,8 +262,50 @@ export function sha256Ref(value: string | Buffer): string {return `sha256:${createHash('sha256').update(value).digest('hex')}`;}+/**+ * Enforce ADR-322C rule 2 / conformance-checklist A3 over a receipt payload:+ * "Every fractional value is a canonical decimal string, not a binary float."+ *+ * This lives at the RECEIPT boundary rather than inside `canonicalizeJcs`,+ * which is shared with the proposer envelope (`flywheel-proposer.ts`) and the+ * promotion ledger (`flywheel-transaction.ts`) β structures the contract does+ * not govern. A first attempt put the check in the canonicalizer and broke+ * those callers, which is the reason the scope is spelled out here.+ *+ * Integers and scaled integers stay JSON numbers (currency micros, durations,+ * iteration counts). A fractional JSON number anywhere in the payload is a+ * contract violation, and the error names the path β the original bug+ * (ruvnet/ruflo#3229) needed a live fixture to find precisely because neither+ * verifier said which field was wrong.+ */+export function assertReceiptNumberDomain(value: unknown, path = '$'): void {+ if (typeof value === 'number') {+ if (!Number.isInteger(value)) {+ throw new Error(+ `fractional number at ${path} must be a scale-12 decimal string (ADR-322C rule 2)`,+ );+ }+ return;+ }+ if (Array.isArray(value)) {+ value.forEach((v, i) => assertReceiptNumberDomain(v, `${path}[${i}]`));+ return;+ }+ if (value && typeof value === 'object') {+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {+ assertReceiptNumberDomain(v, `${path}.${k}`);+ }+ }+}+export function policyCandidateId(policy: Record<string, unknown>): string {- return sha256Ref(canonicalizeJcs(policy));+ // Encode at the hashing boundary so the content ID is always over the+ // CANONICAL form, whether the caller passed a raw config or an+ // already-encoded policy. `encodePolicyFractions` is idempotent β an+ // encoded value is a string and passes through untouched β so+ // policyCandidateId(raw) === policyCandidateId(encoded), which is what lets+ // `verify` recompute the ID from the payload and still match.+ return sha256Ref(canonicalizeJcs(encodePolicyFractions(policy)));}/** UUIDv7 with a 48-bit millisecond timestamp and RFC-4122 variant bits. */@@ -283,6 +325,39 @@ const decimal = (value: number, scale = 12): string => {return normalized === '-0' || normalized === '' ? '0' : normalized;};+/**+ * Encode an opaque policy object so every fractional value is a scale-12+ * decimal string, per ADR-322C rule 2 and conformance-checklist A3.+ *+ * `candidatePolicy` is declared "Opaque to this contract; its shape is owned by+ * policySchemaVersion. Must still satisfy the ADR-322C number rules" β a rule+ * the JSON Schema cannot express for an opaque object, so nothing enforced it+ * and the producer wrote binary floats (`{"alpha": 0.3, "mmrLambda": 0.5}`).+ * Ruflo's own verifier accepted them because `assertJsonValue` only checked+ * finite-and-not-negative-zero; autogenous's stricter verifier correctly+ * rejected the receipt (ruvnet/ruflo#3229, ruvnet/autogenous#15).+ *+ * Integers stay JSON numbers and only non-integers are encoded, which is what+ * the contract's own example shows: `{"hnswEf": 128, "hybridWeight": "0.65"}`.+ * Recurses through nested objects and arrays, because "every fractional value"+ * is not limited to the top level.+ */+export function encodePolicyFractions(value: unknown): unknown {+ if (typeof value === 'number') {+ if (!Number.isFinite(value)) throw new Error('policy value must be finite');+ // Integers are exact in JSON and the contract permits scaled integers, so+ // they are left alone; -0 is normalized away by `decimal`.+ return Number.isInteger(value) && !Object.is(value, -0) ? value : decimal(value);+ }+ if (Array.isArray(value)) return value.map(encodePolicyFractions);+ if (value && typeof value === 'object') {+ return Object.fromEntries(+ Object.entries(value as Record<string, unknown>).map(([k, v]) => [k, encodePolicyFractions(v)]),+ );+ }+ return value;+}+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') };@@ -385,6 +460,10 @@ function receiptIdentityPayload(payload: Omit<FlywheelReceiptPayload, 'receiptId}function signedBytes(payload: FlywheelReceiptPayload): Buffer {+ // Assert at the signing boundary: a receipt must never be SIGNED unless it+ // satisfies the number domain it claims. Covers both produce and verify,+ // since both paths sign or re-derive these bytes.+ assertReceiptNumberDomain(payload);return Buffer.concat([Buffer.from(RECEIPT_DOMAIN, 'utf8'),Buffer.from([0]),@@ -396,7 +475,12 @@ export function createFlywheelReceipt(input: CreateReceiptInput): FlywheelEvaluaconst now = input.now ?? Date.now();const evaluationRunId = input.evaluationRunId ?? uuidV7(now);const lineageId = input.lineageId ?? uuidV7(now);- const candidateId = policyCandidateId(input.candidatePolicy);+ // Encode ONCE and use the encoded object for both the candidate content ID+ // and the payload, so `verify`'s recomputation of policyCandidateId still+ // matches. Encoding after the ID were computed would make every receipt fail+ // its own 'candidate content ID mismatch' check.+ const candidatePolicy = encodePolicyFractions(input.candidatePolicy) as Record<string, unknown>;+ const candidateId = policyCandidateId(candidatePolicy);// Verifiers recompute the statistics from the payload's scale-12 decimal// strings β the only values they ever have. The encoded values are therefore// the statistical inputs of record: compute the decision from them, not from@@ -424,9 +508,23 @@ export function createFlywheelReceipt(input: CreateReceiptInput): FlywheelEvaluaevaluationRunId,baselineRef: input.baselineRef,expectedLedgerHead: input.expectedLedgerHead ?? GENESIS_LEDGER_HEAD,- candidatePolicy: input.candidatePolicy,+ candidatePolicy,gateVersion: input.gateVersion ?? statistics.ruleVersion,- policySchemaVersion: input.policySchemaVersion ?? 'ruflo.retrieval-policy/v1',+ // v1 -> v2: the encoding of `candidatePolicy` changed (#3229). Fixing it+ // changes the candidate content ID, so a pre-fix receipt can never match a+ // post-fix champion reference. Bumping the schema version makes the+ // promotion gate refuse those receipts with an ACCURATE reason β+ // 'policy schema changed' (flywheel-transaction.ts:468) β instead of a+ // confusing 'stale baseline' hash mismatch.+ //+ // Signed receipts are deliberately NOT migrated: re-encoding changes the+ // content, which changes the ID, which invalidates the signature. A+ // migration would mean re-signing, i.e. minting new receipts that claim to+ // be old ones, which is what the receipt design exists to prevent. Existing+ // receipts stay valid as history and unpromotable; the champion is+ // re-established through the explicit reset path, which already requires+ // confirmation and a recorded reason.+ policySchemaVersion: input.policySchemaVersion ?? 'ruflo.retrieval-policy/v2',safetyEnvelopeRef: input.safetyEnvelopeRef,...(input.anchorRef ? { anchorRef: input.anchorRef } : {}),requestedProposer: input.requestedProposer ?? 'local',@@ -495,6 +593,16 @@ export interface ReceiptVerification {}export function verifyFlywheelReceipt(receipt: FlywheelEvaluationReceipt, trustedPublicKeys?: Set<string>): ReceiptVerification {+ // The enforcement half of #3229. Before this, ruflo verified its own+ // non-conforming receipts because the only number rule was+ // finite-and-not-negative-zero, while autogenous's stricter verifier+ // correctly rejected them. Reported as an error rather than thrown so the+ // caller gets it alongside every other finding.+ try {+ assertReceiptNumberDomain(receipt.payload);+ } catch (err) {+ return { valid: false, signed: !!receipt.signature, errors: [(err as Error).message] };+ }const errors: string[] = [];try {if (receipt.payload.schemaVersion !== RECEIPT_SCHEMA) errors.push('unsupported receipt schema');diff --git a/v3/@claude-flow/cli/src/services/harness-flywheel.ts b/v3/@claude-flow/cli/src/services/harness-flywheel.tsindex 15a8e5d48f..35ac16bb35 100644--- a/v3/@claude-flow/cli/src/services/harness-flywheel.ts+++ b/v3/@claude-flow/cli/src/services/harness-flywheel.ts@@ -282,7 +282,12 @@ export async function evaluateFlywheelCandidate(projectRoot: string, deps: FlywhevaluationRunId: deps.evaluationRunId,baselineRef: refOf(baseline),expectedLedgerHead: txState.ledgerHead,- candidatePolicy: candidate as unknown as Record<string, unknown>,+ // `as unknown as` erased RetrievalConfig's `number` fields and laundered+ // binary floats into a receipt claiming ADR-322C conformance (#3229).+ // createFlywheelReceipt now encodes fractional values to scale-12+ // decimal strings, so a single structural cast is enough and the+ // type-erasing double cast is gone.+ candidatePolicy: { ...candidate } as Record<string, unknown>,safetyEnvelopeRef,anchorRef: deps.anchorRef,requestedProposer: deps.requestedProposer ?? 'local',