From a914ebdc69d2f1db3a529b0fc8ba3eb273a6add4 Mon Sep 17 00:00:00 2001 From: ruv Date: Wed, 19 Aug 2026 21:37:11 -0400 Subject: [PATCH 1/3] docs(spec): witness/receipt contract extracted from ADR-322C Makes ADR-322C's verification protocol consumable as a cross-repo witness/promotion contract without reading ruflo source, for ruvnet/rvm#35, ruvnet/autogenous#10, and ruvnet/RuVector#840. Extraction only - no new decisions. Every normative statement cites ADR-322/322A/322C/381 or the implementing source. Adds: - v3/docs/spec/witness-receipt-contract.md: record types, JCS canonicalization, identity derivation, signature construction with domain prefixes byte-exact, evidence grades, step-by-step verification, versioning, and the per-epoch alpha-ledger caveat. - v3/docs/spec/schemas/: draft 2020-12 schemas for the receipt and promotion commit, plus a PROPOSED-EXTENSION anchor record. - v3/docs/spec/examples/: fixtures generated by running flywheel-receipt.ts itself, so the signature and content IDs are real. - v3/docs/spec/conformance-checklist.md: testable criteria for consumers. Four gaps between ADR-322C and main are recorded rather than papered over: the bootstrap PRNG lives only in source (G1); the signed ledger head under ruflo/flywheel-ledger-head/v1 is specified but unimplemented, the chain is an unsigned SHA-256 chain (G2); verifyFlywheelReceipt has no unknown-field whitelist, so a producer-emitted unknown field verifies - the schemas' additionalProperties:false is the only enforcement (G3); and Flywheel projection stays disabled (G4). Co-Authored-By: claude-flow --- v3/docs/spec/conformance-checklist.md | 116 +++++++++ .../spec/examples/anchor-record.example.json | 13 + .../examples/promotion-commit.example.json | 16 ++ .../examples/receipt-accepted.example.json | 233 +++++++++++++++++ .../ruflo-anchor-record-v1.schema.json | 80 ++++++ .../ruflo-flywheel-receipt-v1.schema.json | 240 ++++++++++++++++++ .../ruflo-promotion-commit-v1.schema.json | 85 +++++++ v3/docs/spec/witness-receipt-contract.md | 225 ++++++++++++++++ 8 files changed, 1008 insertions(+) create mode 100644 v3/docs/spec/conformance-checklist.md create mode 100644 v3/docs/spec/examples/anchor-record.example.json create mode 100644 v3/docs/spec/examples/promotion-commit.example.json create mode 100644 v3/docs/spec/examples/receipt-accepted.example.json create mode 100644 v3/docs/spec/schemas/ruflo-anchor-record-v1.schema.json create mode 100644 v3/docs/spec/schemas/ruflo-flywheel-receipt-v1.schema.json create mode 100644 v3/docs/spec/schemas/ruflo-promotion-commit-v1.schema.json create mode 100644 v3/docs/spec/witness-receipt-contract.md diff --git a/v3/docs/spec/conformance-checklist.md b/v3/docs/spec/conformance-checklist.md new file mode 100644 index 0000000000..73c42e2658 --- /dev/null +++ b/v3/docs/spec/conformance-checklist.md @@ -0,0 +1,116 @@ +# Conformance checklist — Witness / Receipt Contract v1 + +Testable criteria for consumers of [`witness-receipt-contract.md`](./witness-receipt-contract.md): +`rvm-witness` anchoring (`ruvnet/rvm#35`), the `autogenous` ledger +(`ruvnet/autogenous#10`), and the `ruvector-agent-memory` TARL ledger +(`ruvnet/RuVector#840`). + +Each item is a test to write, not a box to assert. Items derived from ADR-322C's +own §"Required tests" are marked **[322C]**; the rest are the consumer-facing +consequences of the same rules. + +## A. Producer conformance (you emit records) + +- [ ] **A1** Every emitted record validates against the matching file in + [`schemas/`](./schemas/) with `additionalProperties: false`. This is the only + enforcement of ADR-322C's unknown-field rule — ruflo's own verifier does not + whitelist fields (contract §2.4, gap G3). +- [ ] **A2** No record contains `NaN`, `±Infinity`, or negative zero anywhere. +- [ ] **A3** Every fractional value is a canonical decimal string, not a binary + float. Round-tripping a record through your serializer does not change its + content ID. +- [ ] **A4** `candidateId` recomputes as `SHA-256(JCS(candidatePolicy))`, and + `receiptId` as `SHA-256(JCS(payload minus receiptId))` (contract §3). +- [ ] **A5** Re-evaluating the same candidate produces the **same** `candidateId` + with a **new** `evaluationRunId` and a **new** `receiptId`. **[322C]** +- [ ] **A6** The signature covers `UTF8(domain) || 0x00 || JCS(payload)` with the + exact domain string for the record type (contract §4). Verify against + [`examples/receipt-accepted.example.json`](./examples/receipt-accepted.example.json), + whose signature was produced by ruflo's implementation. +- [ ] **A7** Every gate marked `true` has a `termVerification` entry, and no + authorizing term is `trusted-assertion` without a named attestor (contract §5). +- [ ] **A8** `pairedOutcomes` is emitted, is the same length and order as + `heldOutDeltas`, and each per-task delta reproduces its aggregate. Aggregate-only + receipts are refused by the promotion authority (ADR-381). + +## B. Verifier conformance (you check records) + +- [ ] **B1** Altering **any** byte of a canonical record or a referenced object + fails verification. **[322C]** Confirmed behaviour: flipping one score in the + reference fixture yields `receipt content ID mismatch`. +- [ ] **B2** Reordering object keys in transport does **not** change validity — + canonicalization sorts keys. A verifier that depends on serialized order is + non-conforming. +- [ ] **B3** A cryptographically valid signature from a signer outside the trusted + set is **refused**, not merely flagged. +- [ ] **B4** A signature whose `domain` is not the exact expected string is + refused, including one that is otherwise valid under a different ruflo domain. + This is the replay defence — an ADR-103 witness signature must not verify as a + promotion signature (contract §4). +- [ ] **B5** The statistical decision is **recomputed**, not read. Your bootstrap + reproduces `relativeLift`, `pairedBootstrapProbability`, + `pairedBootstrapDeltaCILow95`, and `accepted` **exactly** for the reference + fixture, using the seed and PRNG in contract §6.1. Expected values for that + fixture: `0.092857142857`, `1`, `0.0425`, `true`, with + `seedHex = be51f05643bce93feb04b7da659e290a203a1a62b5cb408b9c46554df528da84`. +- [ ] **B6** Float and decimal fixtures produce identical hashes across every + runtime you support (Rust and TypeScript both matter here). **[322C]** +- [ ] **B7** Corpus-role disjointness is checked — a task ID appearing in both + `selectionTaskIds` and `promotionHoldoutTaskIds` fails verification. +- [ ] **B8** An expired receipt (`expiresAt <= now`) is refused. +- [ ] **B9** Your report labels **every** authorizing term `recomputed`, + `signature-verified`, or `trusted-assertion`, and refuses to describe a + promotion as independently verified while any authorizing term is an unapproved + assertion. **[322C]** + +## C. Ledger and anchoring + +- [ ] **C1** Removing, reordering, or reparenting a commit breaks verification + from head to genesis. **[322C]** +- [ ] **C2** Exactly one commit may consume a given `receiptId`; a second attempt + is idempotent, not a second promotion (ADR-322A). +- [ ] **C3** You anchor the **receipt** (`receiptId`), whose signature is + implemented — not the ledger head, whose `ruflo/flywheel-ledger-head/v1` + signature is specified but not implemented on `main` (contract gap G2). If you + anchor a head, you are anchoring an unsigned hash chain; say so. +- [ ] **C4** An anchored record's stated assurance is the assurance it carries, + not the assurance of the chain it landed in. A service-side record anchored into + a hypervisor chain does not acquire hypervisor-side guarantees + (`rvm` ADR-285). Uses the `PROPOSED-EXTENSION` field in + [`schemas/ruflo-anchor-record-v1.schema.json`](./schemas/ruflo-anchor-record-v1.schema.json). +- [ ] **C5** No dependency edge is introduced between `rvm-witness` and + `autogenous`'s witness crate in either direction — both consume this contract + independently (`rvm#35`, `autogenous#10`). + +## D. Separation of powers across the repo boundary + +- [ ] **D1** The party emitting receipts is **not** the party that decides + `allowedProposerSubstitutions`, `trustedPublicKeys`, or `approvedAttestors`. + A cross-repo promotion that lets one actor supply both collapses the + proposer/promoter split ADR-322 exists to maintain. +- [ ] **D2** A receipt carrying `proposerSubstitution` does not promote unless + that exact substitution string is explicitly allow-listed. Default denies. +- [ ] **D3** Promotion preconditions are re-checked **at promotion time**, not + inherited from evaluation time: `baselineRef`, `expectedLedgerHead`, + `gateVersion`, `policySchemaVersion`, `safetyEnvelopeRef`, `expiresAt` + (ADR-322A §"Promotion compare-and-swap"). + +## E. Statistical claims you republish + +- [ ] **E1** Any restatement of the family-wise false-promotion bound carries both + qualifiers: it is **per evidence epoch**, and **ADR-381 is `Proposed`** (though + the mechanism is present on `main`). Contract §6.2. +- [ ] **E2** A governed reset opens a new epoch, expires outstanding receipts, and + restarts allocation at `k = 1`. A receipt whose `issuedAt` predates the current + epoch boundary is refused even if registered after the reset. +- [ ] **E3** You do not claim phase-3/4 properties. `safetyEnvelopeRef` is carried + and compared, but the **signed** `SafetyEnvelope` it names is a phase-3 artifact + that does not exist yet (contract §7). + +## F. Versioning + +- [ ] **F1** You pin `schemaVersion` and `gateVersion` strings, not ruflo git + SHAs (`ruvnet/ruflo#3066`). +- [ ] **F2** An unrecognized `schemaVersion` is refused, never best-effort parsed. +- [ ] **F3** A `gateVersion` change is not applied retroactively to receipts + issued under an older gate. diff --git a/v3/docs/spec/examples/anchor-record.example.json b/v3/docs/spec/examples/anchor-record.example.json new file mode 100644 index 0000000000..4445097d3d --- /dev/null +++ b/v3/docs/spec/examples/anchor-record.example.json @@ -0,0 +1,13 @@ +{ + "payload": { + "schemaVersion": "ruflo.anchor-record/v1", + "anchoredContentId": "sha256:783fd640aadaf1092465a4f4c950a8ae7a99980856b166acd2451d0cccec2398", + "anchoredSchemaVersion": "ruflo.flywheel-receipt/v1", + "chain": { + "chainId": "rvm-witness/pir-acceptance", + "position": 4211 + }, + "assuranceLevel": "service-side", + "anchoredAt": "2026-08-19T00:02:00.000Z" + } +} diff --git a/v3/docs/spec/examples/promotion-commit.example.json b/v3/docs/spec/examples/promotion-commit.example.json new file mode 100644 index 0000000000..7e65f6d25f --- /dev/null +++ b/v3/docs/spec/examples/promotion-commit.example.json @@ -0,0 +1,16 @@ +{ + "commit": { + "transactionId": "0198f2a0-0000-7000-8000-00000000e5f6", + "receiptId": "sha256:783fd640aadaf1092465a4f4c950a8ae7a99980856b166acd2451d0cccec2398", + "lineageId": "0198f2a0-0000-7000-8000-00000000a1b2", + "sequence": 1, + "previousLedgerHead": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "baselineRef": "sha256:3f786850e387550fdab836ed7e6dc881de23001b0b4b1b0f0a1a2b3c4d5e6f70", + "candidateId": "sha256:61c84d2769efc8fa1f5e76d2c3d645763cf013a38fa658edaccaede460a172a2", + "servingEpoch": 1, + "proposer": "local", + "promotedAt": 1787097660000, + "commitId": "sha256:ac5ced28e6f8885e0ea90299791971d30d965f715191c94e999ec1ad29327e4b" + }, + "ledgerHead": "sha256:faa8ed99d82ce36636aa67f95a52dacc8af2a82f61c5d42fd943a979a83d48aa" +} diff --git a/v3/docs/spec/examples/receipt-accepted.example.json b/v3/docs/spec/examples/receipt-accepted.example.json new file mode 100644 index 0000000000..6a6f2be456 --- /dev/null +++ b/v3/docs/spec/examples/receipt-accepted.example.json @@ -0,0 +1,233 @@ +{ + "payload": { + "schemaVersion": "ruflo.flywheel-receipt/v1", + "lineageId": "0198f2a0-0000-7000-8000-00000000a1b2", + "candidateId": "sha256:61c84d2769efc8fa1f5e76d2c3d645763cf013a38fa658edaccaede460a172a2", + "evaluationRunId": "0198f2a0-0000-7000-8000-00000000c3d4", + "baselineRef": "sha256:3f786850e387550fdab836ed7e6dc881de23001b0b4b1b0f0a1a2b3c4d5e6f70", + "expectedLedgerHead": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "candidatePolicy": { + "hnswEf": 128, + "hybridWeight": "0.65", + "rerankDepth": 24 + }, + "gateVersion": "ruflo.flywheel-gate/v1", + "policySchemaVersion": "ruflo.retrieval-policy/v1", + "safetyEnvelopeRef": "sha256:9a271f2a916b0b6ee6cecb2426f0b3206ef074578be55d9bc94f6f3fe3ab86aa", + "anchorRef": "sha256:2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae", + "requestedProposer": "auto", + "effectiveProposer": "local", + "corpusVersion": "pir-conformance-corpus/2026-08-19", + "corpusHash": "sha256:fcde2b2edba56bf408601fb721fe9b5c338d10ee429ea04fae5511b68fbf8fb9", + "baselineScore": "0.7", + "candidateScore": "0.765", + "heldOutDeltas": [ + "0.08", + "0.08", + "0.08", + "0.08", + "0.08", + "0.08", + "0.08", + "0.08", + "0.08", + "0.08", + "0.08", + "0.08", + "0.08", + "0.08", + "-0.04", + "-0.04" + ], + "pairedOutcomes": [ + { + "taskId": "task-01", + "baselineScore": "0.7", + "candidateScore": "0.78" + }, + { + "taskId": "task-02", + "baselineScore": "0.7", + "candidateScore": "0.78" + }, + { + "taskId": "task-03", + "baselineScore": "0.7", + "candidateScore": "0.78" + }, + { + "taskId": "task-04", + "baselineScore": "0.7", + "candidateScore": "0.78" + }, + { + "taskId": "task-05", + "baselineScore": "0.7", + "candidateScore": "0.78" + }, + { + "taskId": "task-06", + "baselineScore": "0.7", + "candidateScore": "0.78" + }, + { + "taskId": "task-07", + "baselineScore": "0.7", + "candidateScore": "0.78" + }, + { + "taskId": "task-08", + "baselineScore": "0.7", + "candidateScore": "0.78" + }, + { + "taskId": "task-09", + "baselineScore": "0.7", + "candidateScore": "0.78" + }, + { + "taskId": "task-10", + "baselineScore": "0.7", + "candidateScore": "0.78" + }, + { + "taskId": "task-11", + "baselineScore": "0.7", + "candidateScore": "0.78" + }, + { + "taskId": "task-12", + "baselineScore": "0.7", + "candidateScore": "0.78" + }, + { + "taskId": "task-13", + "baselineScore": "0.7", + "candidateScore": "0.78" + }, + { + "taskId": "task-14", + "baselineScore": "0.7", + "candidateScore": "0.78" + }, + { + "taskId": "task-15", + "baselineScore": "0.7", + "candidateScore": "0.66" + }, + { + "taskId": "task-16", + "baselineScore": "0.7", + "candidateScore": "0.66" + } + ], + "statistics": { + "ruleVersion": "ruflo.flywheel-gate/v1", + "relativeLift": "0.092857142857", + "pairedBootstrapProbability": "1", + "pairedBootstrapDeltaCILow95": "0.0425", + "frozenAnchorRegression": "0", + "iterations": 10000, + "seedHex": "be51f05643bce93feb04b7da659e290a203a1a62b5cb408b9c46554df528da84", + "significant": true, + "accepted": true + }, + "gates": { + "heldOutImproves": true, + "frozenAnchorNoRegression": true, + "driftWithinBound": true, + "replayDeterministic": true, + "receiptCoverage": true, + "canaryNoWorse": true + }, + "resourceEvidence": { + "p95LatencyMicros": 412000, + "costMicrosPerTask": 1850, + "tokensPerTask": 3120, + "failureRate": "0", + "evaluationCostMicros": 29600, + "currency": "USD" + }, + "evidence": { + "corpusRoles": { + "selectionTaskIds": [ + "sel-01", + "sel-02", + "sel-03" + ], + "promotionHoldoutTaskIds": [ + "task-01", + "task-02", + "task-03", + "task-04", + "task-05", + "task-06", + "task-07", + "task-08", + "task-09", + "task-10", + "task-11", + "task-12", + "task-13", + "task-14", + "task-15", + "task-16" + ], + "guardTaskIds": [ + "anchor-01", + "anchor-02" + ] + }, + "verification": { + "replayTranscriptRef": "sha256:1b16b1df538ba12dc3f97edbb85caa7050d46c148134290feba80f8236c83db9" + }, + "canary": { + "rollbackRate": "0", + "sliceRef": "sha256:0263829989b6fd954f72baaf2fc64bc2e2f01d692d4de72986ea808f6e99813f" + } + }, + "termVerification": [ + { + "term": "heldOutImproves", + "verification": "recomputed", + "evidenceRef": "inline:pairedOutcomes" + }, + { + "term": "frozenAnchorNoRegression", + "verification": "recomputed", + "evidenceRef": "inline:statistics.frozenAnchorRegression" + }, + { + "term": "driftWithinBound", + "verification": "recomputed", + "evidenceRef": "inline:evidence.verification" + }, + { + "term": "replayDeterministic", + "verification": "recomputed", + "evidenceRef": "sha256:1b16b1df538ba12dc3f97edbb85caa7050d46c148134290feba80f8236c83db9" + }, + { + "term": "receiptCoverage", + "verification": "recomputed", + "evidenceRef": "inline:evidence.corpusRoles" + }, + { + "term": "canaryNoWorse", + "verification": "signature-verified", + "evidenceRef": "sha256:0263829989b6fd954f72baaf2fc64bc2e2f01d692d4de72986ea808f6e99813f", + "attestor": "ruflo-canary-runner/v1" + } + ], + "decision": "accepted", + "issuedAt": "2026-08-19T00:00:00.000Z", + "expiresAt": "2026-08-20T00:00:00.000Z", + "receiptId": "sha256:783fd640aadaf1092465a4f4c950a8ae7a99980856b166acd2451d0cccec2398" + }, + "signature": { + "algorithm": "ed25519", + "domain": "ruflo/flywheel-receipt/v1", + "publicKeyPem": "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAqNSpk4jp2Y7WJ3jzCgOiXnVFKQKm5R7266xFiPWUU0s=\n-----END PUBLIC KEY-----\n", + "signatureBase64": "EoE4mrCbcTBitpgFdR66vpk9PnhBH2IVwvG933E+SAU1Q9xEgUAlOK9LnYJammnSI52TcPJiCmUoOQZBGEPoBA==" + } +} diff --git a/v3/docs/spec/schemas/ruflo-anchor-record-v1.schema.json b/v3/docs/spec/schemas/ruflo-anchor-record-v1.schema.json new file mode 100644 index 0000000000..89acbaee9f --- /dev/null +++ b/v3/docs/spec/schemas/ruflo-anchor-record-v1.schema.json @@ -0,0 +1,80 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/ruvnet/ruflo/v3/docs/spec/schemas/ruflo-anchor-record-v1.schema.json", + "title": "RufloAnchorRecordV1 (PROPOSED-EXTENSION)", + "description": "PROPOSED-EXTENSION - NOT part of ADR-322C. ADR-322C defines records and their verification but is silent on how a record is anchored into a foreign chain. ruvnet/rvm#35 and ruvnet/autogenous#10 both need a pointer format, so this is the minimal placeholder for that need. It requires its own ADR before any repo depends on it. Do not treat conformance to this file as conformance to ADR-322C.", + "type": "object", + "required": ["payload"], + "additionalProperties": false, + "properties": { + "payload": { "$ref": "#/$defs/payload" }, + "signature": { "$ref": "#/$defs/signature" } + }, + "$defs": { + "contentId": { "type": "string", "pattern": "^sha256:[0-9a-f]{64}$" }, + "timestamp": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z$" + }, + "signature": { + "type": "object", + "required": ["algorithm", "domain", "publicKeyPem", "signatureBase64"], + "additionalProperties": false, + "properties": { + "algorithm": { "const": "ed25519" }, + "domain": { + "const": "ruflo/flywheel-anchor/v1", + "description": "PROPOSED-EXTENSION signing domain. Distinct from ruflo/flywheel-receipt/v1 so an anchor signature can never be replayed as a receipt signature, per ADR-322 section Persistence and key boundaries." + }, + "publicKeyPem": { "type": "string", "pattern": "^-----BEGIN PUBLIC KEY-----" }, + "signatureBase64": { "type": "string", "pattern": "^[A-Za-z0-9+/]+={0,2}$" } + } + }, + "payload": { + "type": "object", + "required": [ + "schemaVersion", + "anchoredContentId", + "anchoredSchemaVersion", + "chain", + "assuranceLevel", + "anchoredAt" + ], + "additionalProperties": false, + "properties": { + "schemaVersion": { "const": "ruflo.anchor-record/v1" }, + "anchoredContentId": { + "$ref": "#/$defs/contentId", + "description": "Content ID of the ADR-322C record being anchored - normally a receiptId, since the receipt signature is implemented and the ledger head signature is not (gap G2)." + }, + "anchoredSchemaVersion": { + "type": "string", + "minLength": 1, + "description": "schemaVersion of the anchored record, so a verifier knows which rules to apply without parsing it first." + }, + "chain": { + "type": "object", + "required": ["chainId", "position"], + "additionalProperties": false, + "properties": { + "chainId": { + "type": "string", + "minLength": 1, + "description": "Identifier of the foreign chain, e.g. an rvm-witness chain. Opaque to this contract." + }, + "position": { + "type": "integer", + "minimum": 0, + "description": "Position of the anchoring event within the foreign chain." + } + } + }, + "assuranceLevel": { + "enum": ["service-side", "hypervisor-side"], + "description": "Required by rvm#35 and autogenous#10: a service-side record anchored into a hypervisor-side chain does NOT thereby acquire hypervisor-side guarantees (rvm ADR-285 discipline). This field records what the anchored record actually carries, never what the chain it landed in carries." + }, + "anchoredAt": { "$ref": "#/$defs/timestamp" } + } + } + } +} diff --git a/v3/docs/spec/schemas/ruflo-flywheel-receipt-v1.schema.json b/v3/docs/spec/schemas/ruflo-flywheel-receipt-v1.schema.json new file mode 100644 index 0000000000..7aea2cf047 --- /dev/null +++ b/v3/docs/spec/schemas/ruflo-flywheel-receipt-v1.schema.json @@ -0,0 +1,240 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/ruvnet/ruflo/v3/docs/spec/schemas/ruflo-flywheel-receipt-v1.schema.json", + "title": "RufloFlywheelReceiptV1", + "description": "Evaluation receipt defined by ADR-322C. Structural validation only: schema conformance is necessary but NOT sufficient. A conforming record is valid only after the content-ID, signature, and statistical recomputation steps of witness-receipt-contract.md section 6.", + "type": "object", + "required": ["payload"], + "additionalProperties": false, + "properties": { + "payload": { "$ref": "#/$defs/payload" }, + "signature": { "$ref": "#/$defs/signature" } + }, + "$defs": { + "contentId": { + "type": "string", + "pattern": "^sha256:[0-9a-f]{64}$", + "description": "ADR-322C content ID: sha256:." + }, + "uuidV7": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" + }, + "timestamp": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z$", + "description": "RFC 3339 UTC normalized to YYYY-MM-DDTHH:mm:ss.sssZ." + }, + "decimalString": { + "type": "string", + "pattern": "^-?(0|[1-9][0-9]*)(\\.[0-9]+)?$", + "description": "Canonical decimal string. ADR-322C forbids binary floats for signed fractional values; -0 is not representable by this pattern." + }, + "signature": { + "type": "object", + "required": ["algorithm", "domain", "publicKeyPem", "signatureBase64"], + "additionalProperties": false, + "properties": { + "algorithm": { "const": "ed25519" }, + "domain": { + "const": "ruflo/flywheel-receipt/v1", + "description": "Ed25519 domain-separation prefix. Signed bytes are UTF8(domain) || 0x00 || JCS(payload)." + }, + "publicKeyPem": { "type": "string", "pattern": "^-----BEGIN PUBLIC KEY-----" }, + "signatureBase64": { "type": "string", "pattern": "^[A-Za-z0-9+/]+={0,2}$" } + } + }, + "pairedOutcome": { + "type": "object", + "required": ["taskId", "baselineScore", "candidateScore"], + "additionalProperties": false, + "properties": { + "taskId": { "type": "string", "minLength": 1 }, + "baselineScore": { "$ref": "#/$defs/decimalString" }, + "candidateScore": { "$ref": "#/$defs/decimalString" } + } + }, + "statistics": { + "type": "object", + "required": [ + "ruleVersion", + "relativeLift", + "pairedBootstrapProbability", + "pairedBootstrapDeltaCILow95", + "frozenAnchorRegression", + "iterations", + "seedHex", + "significant", + "accepted" + ], + "additionalProperties": false, + "properties": { + "ruleVersion": { "type": "string", "minLength": 1 }, + "relativeLift": { "$ref": "#/$defs/decimalString" }, + "pairedBootstrapProbability": { "$ref": "#/$defs/decimalString" }, + "pairedBootstrapDeltaCILow95": { "$ref": "#/$defs/decimalString" }, + "frozenAnchorRegression": { "$ref": "#/$defs/decimalString" }, + "iterations": { "type": "integer", "minimum": 100 }, + "seedHex": { + "type": "string", + "pattern": "^[0-9a-f]{64}$", + "description": "Full SHA-256 digest of \"ruflo/bootstrap/v1\" || corpusHash || candidateId || baselineRef || evaluationRunId." + }, + "significant": { "type": "boolean" }, + "accepted": { "type": "boolean" } + } + }, + "resourceEvidence": { + "type": "object", + "required": [ + "p95LatencyMicros", + "costMicrosPerTask", + "tokensPerTask", + "failureRate", + "evaluationCostMicros", + "currency" + ], + "additionalProperties": false, + "properties": { + "p95LatencyMicros": { "type": "integer", "minimum": 0 }, + "costMicrosPerTask": { "type": "integer", "minimum": 0 }, + "tokensPerTask": { "type": "integer", "minimum": 0 }, + "failureRate": { "$ref": "#/$defs/decimalString" }, + "evaluationCostMicros": { "type": "integer", "minimum": 0 }, + "energyMicrojoules": { "type": "integer", "minimum": 0 }, + "currency": { "type": "string", "pattern": "^[A-Z]{3}$", "description": "ISO 4217." } + } + }, + "termVerification": { + "type": "object", + "required": ["term", "verification", "evidenceRef"], + "additionalProperties": false, + "properties": { + "term": { "type": "string", "minLength": 1 }, + "verification": { + "enum": ["recomputed", "signature-verified", "trusted-assertion"], + "description": "ADR-322C evidence grade." + }, + "evidenceRef": { "type": "string", "minLength": 1 }, + "attestor": { "type": "string", "minLength": 1 } + }, + "allOf": [ + { + "if": { "properties": { "verification": { "const": "trusted-assertion" } }, "required": ["verification"] }, + "then": { + "required": ["attestor"], + "properties": { "attestor": { "type": "string", "minLength": 1 } }, + "description": "A trusted-assertion authorizing an accepted gate must name an attestor, which the promotion authority checks against its approved set." + } + } + ] + }, + "payload": { + "type": "object", + "required": [ + "schemaVersion", + "receiptId", + "lineageId", + "candidateId", + "evaluationRunId", + "baselineRef", + "expectedLedgerHead", + "candidatePolicy", + "gateVersion", + "policySchemaVersion", + "safetyEnvelopeRef", + "requestedProposer", + "effectiveProposer", + "corpusVersion", + "corpusHash", + "baselineScore", + "candidateScore", + "heldOutDeltas", + "statistics", + "gates", + "resourceEvidence", + "evidence", + "termVerification", + "decision", + "issuedAt", + "expiresAt" + ], + "additionalProperties": false, + "properties": { + "schemaVersion": { "const": "ruflo.flywheel-receipt/v1" }, + "receiptId": { + "$ref": "#/$defs/contentId", + "description": "SHA-256(JCS(payload with this member omitted))." + }, + "lineageId": { "$ref": "#/$defs/uuidV7" }, + "candidateId": { + "$ref": "#/$defs/contentId", + "description": "SHA-256(JCS(candidatePolicy))." + }, + "evaluationRunId": { "$ref": "#/$defs/uuidV7" }, + "baselineRef": { "$ref": "#/$defs/contentId" }, + "expectedLedgerHead": { + "$ref": "#/$defs/contentId", + "description": "Ledger head this receipt was evaluated against. Genesis is sha256:<64 zeros>." + }, + "candidatePolicy": { + "type": "object", + "description": "Opaque to this contract; its shape is owned by policySchemaVersion. Must still satisfy the ADR-322C number rules." + }, + "gateVersion": { "type": "string", "minLength": 1 }, + "policySchemaVersion": { "type": "string", "minLength": 1 }, + "safetyEnvelopeRef": { "$ref": "#/$defs/contentId" }, + "anchorRef": { "$ref": "#/$defs/contentId" }, + "requestedProposer": { "enum": ["auto", "local", "darwin"] }, + "effectiveProposer": { "enum": ["local", "darwin"] }, + "proposerSubstitution": { + "type": "string", + "minLength": 1, + "description": "Present only when the effective proposer differs from the requested one. Promotion is refused unless this exact string is allow-listed by the promotion authority (separation of powers)." + }, + "corpusVersion": { "type": "string", "minLength": 1 }, + "corpusHash": { "$ref": "#/$defs/contentId" }, + "baselineScore": { "$ref": "#/$defs/decimalString" }, + "candidateScore": { "$ref": "#/$defs/decimalString" }, + "heldOutDeltas": { "type": "array", "items": { "$ref": "#/$defs/decimalString" } }, + "pairedOutcomes": { + "type": "array", + "items": { "$ref": "#/$defs/pairedOutcome" }, + "description": "Task-level evidence, same order and length as heldOutDeltas. Optional in the schema so pre-existing receipts still verify byte-identically, but the promotion authority REQUIRES it by default and refuses aggregate-only receipts (ADR-381)." + }, + "statistics": { "$ref": "#/$defs/statistics" }, + "gates": { + "type": "object", + "minProperties": 1, + "additionalProperties": { "type": "boolean" }, + "description": "Named gate terms. Every gate that passed must have a matching termVerification entry." + }, + "resourceEvidence": { "$ref": "#/$defs/resourceEvidence" }, + "evidence": { + "type": "object", + "required": ["corpusRoles", "verification", "canary"], + "additionalProperties": false, + "properties": { + "corpusRoles": { + "type": "object", + "required": ["selectionTaskIds", "promotionHoldoutTaskIds", "guardTaskIds"], + "additionalProperties": false, + "description": "Role assignment is disjoint: a task used for selection may not serve as promotion holdout for the same lineage (ADR-322 Track C).", + "properties": { + "selectionTaskIds": { "type": "array", "items": { "type": "string" } }, + "promotionHoldoutTaskIds": { "type": "array", "items": { "type": "string" } }, + "guardTaskIds": { "type": "array", "items": { "type": "string" } } + } + }, + "verification": { "type": "object" }, + "canary": { "type": "object" } + } + }, + "termVerification": { "type": "array", "items": { "$ref": "#/$defs/termVerification" } }, + "decision": { "enum": ["accepted", "rejected"] }, + "issuedAt": { "$ref": "#/$defs/timestamp" }, + "expiresAt": { "$ref": "#/$defs/timestamp" } + } + } + } +} diff --git a/v3/docs/spec/schemas/ruflo-promotion-commit-v1.schema.json b/v3/docs/spec/schemas/ruflo-promotion-commit-v1.schema.json new file mode 100644 index 0000000000..a5cbe201bc --- /dev/null +++ b/v3/docs/spec/schemas/ruflo-promotion-commit-v1.schema.json @@ -0,0 +1,85 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/ruvnet/ruflo/v3/docs/spec/schemas/ruflo-promotion-commit-v1.schema.json", + "title": "RufloPromotionCommitV1", + "description": "Promotion commit and resulting ledger head. ADR-322C section Ledger specifies content-addressed segments with a segmentMerkleRoot and a head signed under ruflo/flywheel-ledger-head/v1; this schema describes what is actually implemented on main (flywheel-transaction.ts:553-568) - a flat, sequence-numbered commit chain whose head is an UNSIGNED SHA-256 chain value. See witness-receipt-contract.md gap G2 before anchoring a head across a repo boundary.", + "type": "object", + "required": ["commit", "ledgerHead"], + "additionalProperties": false, + "properties": { + "commit": { "$ref": "#/$defs/commit" }, + "ledgerHead": { + "$ref": "#/$defs/contentId", + "description": "SHA-256(JCS({ previous: , commitId: })). Genesis is sha256:<64 zeros>." + } + }, + "$defs": { + "contentId": { "type": "string", "pattern": "^sha256:[0-9a-f]{64}$" }, + "uuidV7": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" + }, + "commit": { + "type": "object", + "required": [ + "commitId", + "transactionId", + "receiptId", + "lineageId", + "sequence", + "previousLedgerHead", + "baselineRef", + "candidateId", + "servingEpoch", + "proposer", + "promotedAt" + ], + "additionalProperties": false, + "properties": { + "commitId": { + "$ref": "#/$defs/contentId", + "description": "SHA-256(JCS(commit with this member omitted))." + }, + "transactionId": { "$ref": "#/$defs/uuidV7" }, + "receiptId": { + "$ref": "#/$defs/contentId", + "description": "The evaluation receipt consumed by this promotion. Exactly one commit may consume a given receipt." + }, + "lineageId": { "$ref": "#/$defs/uuidV7" }, + "sequence": { + "type": "integer", + "minimum": 1, + "description": "1-based position in the chain. Verification walks the chain from genesis; a gap, reorder, or altered parent breaks it." + }, + "previousLedgerHead": { "$ref": "#/$defs/contentId" }, + "baselineRef": { + "$ref": "#/$defs/contentId", + "description": "Champion this promotion replaced. Must equal the active champion at commit time (compare-and-swap, ADR-322A)." + }, + "candidateId": { + "$ref": "#/$defs/contentId", + "description": "New active champion." + }, + "servingEpoch": { + "type": "integer", + "minimum": 1, + "description": "Monotonic per lineage; uniquely constrained (ADR-322A)." + }, + "proposer": { + "enum": ["local", "darwin"], + "description": "Effective proposer. Recorded because the proposer holds no promotion authority (ADR-322 separation of powers)." + }, + "proposerSubstitution": { + "type": "string", + "minLength": 1, + "description": "Present only when a substitution occurred; its presence means the promotion authority explicitly allow-listed that exact substitution." + }, + "promotedAt": { + "type": "integer", + "minimum": 0, + "description": "Unix epoch milliseconds. Note this differs from the receipt's RFC 3339 string timestamps - it is transcribed from the implementation, not from ADR-322C." + } + } + } + } +} diff --git a/v3/docs/spec/witness-receipt-contract.md b/v3/docs/spec/witness-receipt-contract.md new file mode 100644 index 0000000000..aa226880a9 --- /dev/null +++ b/v3/docs/spec/witness-receipt-contract.md @@ -0,0 +1,225 @@ +# Witness / Receipt Contract v1 (extracted from ADR-322C) + +- **Status**: Descriptive extract — adds no decisions. Every normative statement + traces to [ADR-322](../adr/ADR-322-metaharness-flywheel-integration.md), + [ADR-322A](../adr/ADR-322A-evaluation-promotion-transaction.md), + [ADR-322C](../adr/ADR-322C-receipt-ledger-verification.md), + [ADR-381](../adr/ADR-381-sequential-promotion-evidence-governance.md), or the + implementing source under `v3/@claude-flow/cli/src/services/`. +- **Audience**: external implementers (`ruvnet/rvm#35`, `ruvnet/autogenous#10`, + `ruvnet/RuVector#840`) producing or verifying these records **without reading + ruflo's source**. Tracked by `ruvnet/ruflo#3066`. +- **`PROPOSED-EXTENSION`** marks anything *not* in ADR-322C: a minimal placeholder + for a consumer need 322C does not address, requiring its own ADR before use. + +## 1. Record types + +| # | Record | Schema id | Signing domain | Implementation status | +|---|---|---|---|---| +| 1 | Evaluation receipt | `ruflo.flywheel-receipt/v1` | `ruflo/flywheel-receipt/v1` | Implemented (`flywheel-receipt.ts:18`) | +| 2 | Promotion commit + ledger head | *(unnamed in 322C)* | `ruflo/flywheel-ledger-head/v1` | **Commit implemented unsigned**; head signing **specified but not implemented** — see §7 | +| 3 | Cross-repo anchor record | `ruflo.anchor-record/v1` | `ruflo/flywheel-anchor/v1` | `PROPOSED-EXTENSION` — see §9 | + +A third domain-separation string exists but is **not** a signing domain: +`"ruflo/bootstrap/v1"`, the seed prefix for the paired bootstrap (ADR-322C +§"Default statistical rule"). Do not treat it as an Ed25519 domain. + +**Separation of powers** (ADR-322 §Decision, Track A): the proposer never promotes. +The receipt records `requestedProposer`, `effectiveProposer`, and +`proposerSubstitution`; the promotion authority refuses any receipt whose +`proposerSubstitution` is not explicitly allow-listed +(`flywheel-transaction.ts:463-466`). Crossing a repo boundary must not collapse +these roles: the party that emits a receipt must not be the party that decides +`allowedProposerSubstitutions`. + +## 2. Canonicalization + +ADR-322C §Canonical format: + +```text +Canonical JSON: RFC 8785 JCS +Digest: SHA-256 +Signature: Ed25519(domainPrefix || 0x00 || canonicalBytes) +Content ID: sha256: +Timestamp: RFC 3339 UTC as YYYY-MM-DDTHH:mm:ss.sssZ +``` + +Rules, all from ADR-322C §Canonical format unless noted: + +1. `NaN`, `±Infinity`, and negative zero are forbidden anywhere in a record. +2. Fractional values are **decimal strings**, never binary floats — scores, deltas, + lift, probabilities, rates. Currency is integer micros plus an ISO-4217 code; + duration is integer microseconds; energy is integer microjoules. +3. Object key order in transport is irrelevant — canonicalization sorts keys + (`flywheel-receipt.ts:176-185`). Do not rely on serialized order. +4. Unknown fields fail verification for a given schema version. **Caveat**: the + implementation enforces this only *transitively* (an unknown field changes the + recomputed content ID, catching post-signing injection), but has no field + whitelist, so a *producer* may emit unknown fields and they will verify. + Consumers MUST validate against `schemas/`, which set + `additionalProperties: false`. Gap G3 in §7. + +## 3. Identity derivation + +ADR-322C §Identity domains: + +```text +candidateId = SHA-256(JCS(candidate policy)) -> "sha256:" +evaluationRunId = UUIDv7, one per execution attempt +receiptId = SHA-256(JCS(unsigned receipt payload)) -> "sha256:" +lineageId = UUIDv7, one per persistent lineage +``` + +"Unsigned receipt payload" means **the `payload` object with the `receiptId` +member omitted** and no `signature` present (`flywheel-receipt.ts:394,419-421`). +Re-running the same candidate yields the same `candidateId` but a new +`evaluationRunId` and a new `receiptId` (ADR-322C §Identity domains). + +## 4. Signature construction + +For domain `D` and record `R`: + +```text +canonicalBytes = UTF-8( JCS(R) ) +signedBytes = UTF-8(D) || 0x00 || canonicalBytes +signature = Ed25519_sign(privateKey, signedBytes) # base64 in the record +``` + +For the receipt, `R` is the **complete `payload` including `receiptId`**, and `D` +is `ruflo/flywheel-receipt/v1` (`flywheel-receipt.ts:313-319`). The signature +object carries `algorithm`, `domain`, `publicKeyPem`, `signatureBase64`. + +Domain separation is the point: ADR-322 §"Persistence and key boundaries" requires +a distinct prefix and key purpose so that an ADR-103 witness signature cannot be +replayed as a promotion signature. A verifier MUST reject a signature whose +`domain` is not the exact string expected for that record type. + +## 5. Evidence grades + +ADR-322C §RufloFlywheelReceiptV1 defines exactly three grades. Each entry in +`termVerification[]` labels one authorizing term: + +| Grade | Applies when | Verifier obligation | +|---|---|---| +| `recomputed` | The verifier reproduced the term from data inside or content-addressed by the receipt | Recompute it; a mismatch fails verification | +| `signature-verified` | The term is cryptographically bound to an identified attestor | Verify the binding **and** that the attestor is approved and in scope | +| `trusted-assertion` | Neither of the above — a bare claim | Refuse to call the promotion independently verified | + +ADR-322C §Verification: *"Verification cannot label a promotion independently +verified while any authorizing term remains an unapproved assertion."* The +promotion authority enforces this: every passing gate must have a +`termVerification` entry, and a `trusted-assertion` entry must name an attestor +present in the approved set (`flywheel-transaction.ts:467-476`). + +## 6. Verification algorithm + +From ADR-322C §Verification, with the implementable detail a consumer needs: + +1. **Schema.** Reject unknown or invalid fields for the declared `schemaVersion`. +2. **Content IDs.** Recompute `receiptId` per §3 and `candidateId` from + `candidatePolicy`; both must match. +3. **Signature.** Check `algorithm == "ed25519"`, `domain` is the exact expected + string, the signer is trusted, and Ed25519 verifies over §4's `signedBytes`. +4. **Evidence.** Resolve every evidence reference; verify provenance and authority + scope. +5. **Statistics.** Recompute the decision (§6.1); it must reproduce + `statistics` byte-for-byte under JCS. +6. **Corpus roles.** Check role disjointness and sealed manifests — a task used for + selection may not also serve as promotion holdout for the same lineage + (ADR-322 Track C). +7. **Preconditions.** Check `baselineRef`, `safetyEnvelopeRef`, `gateVersion`, + `policySchemaVersion`, `expiresAt`, and ledger continuity. +8. **Report.** Emit a grade (§5) for every term. + +### 6.1 Statistical recomputation + +Default rule (ADR-322C §Default statistical rule) — all four conjuncts: + +```text +relativeLift >= 0.02 +AND pairedBootstrapProbability(candidate > baseline) >= 0.95 +AND pairedBootstrapDeltaCILow95 > 0 +AND frozenAnchorRegression <= 0 +``` + +with `relativeLift = (candidateMean - baselineMean) / max(|baselineMean|, metricEpsilon)`, +`metricEpsilon` fixed by the metric schema (ADR-322 §Statistical promotion rule; +default `1e-12` at `flywheel-receipt.ts:265`). + +Seed (ADR-322C): `SHA-256("ruflo/bootstrap/v1" || corpusHash || candidateId || +baselineRef || evaluationRunId)`, concatenated with no separator. The full digest +hex is recorded as `seedHex`. + +**The ADR does not specify the PRNG driven by that seed, but recomputation is +impossible without it.** Transcribed from `flywheel-receipt.ts:212-293` and +normative for any independent verifier: + +- PRNG state = first 4 bytes of the seed digest, big-endian uint32. +- Step: `state = (1664525 * state + 1013904223) mod 2^32`; draw = `state / 2^32`. +- 10,000 resamples by default; each draws `n` indices as `floor(draw * n)` and + averages the corresponding `heldOutDeltas`. +- `pairedBootstrapProbability` = fraction of resample means strictly `> 0`. +- `pairedBootstrapDeltaCILow95` = the `floor(0.025 * iterations)`-th order + statistic (0-based) of the resample means. + +Filed as gap G1 in §7: this belongs in ADR-322C, not only in source. + +### 6.2 Sequential evidence (ADR-381) + +Promotion additionally requires an anytime-valid e-process over task-level +`pairedOutcomes`. Per discordant pair the e-value multiplies by `(1 + λ)` when the +candidate wins and `(1 - λ)` when the baseline wins; concordant pairs +(`|delta| <= 1e-9`) carry no information. Test `k` must clear `1 / α_k` where +`α_k = α_total · 6/(π² k²)`, defaults `α_total = 0.05`, `λ = 0.5` +(ADR-381 §1, §3; `flywheel-sequential-evidence.ts:39-124`). + +**Guarantee, stated honestly (ADR-381 §2):** the family-wise false-promotion bound +is `≤ α_total` **per evidence epoch**, not for all time. An explicit, logged +governance reset opens a new epoch, expires outstanding receipts, and restarts the +allocation at `k = 1`. **ADR-381's status is `Proposed`** — but the mechanism is +already present on `main` (`flywheel-transaction.ts:478-550`, state fields +`sequentialTests` / `evidenceEpoch` / `sequentialResets`). Consumers quoting the +bound must quote the per-epoch qualifier and the `Proposed` status together. + +## 7. Known gaps between ADR-322C and the implementation + +| # | Gap | Consumer impact | +|---|---|---| +| G1 | Bootstrap PRNG algorithm is in source only (§6.1) | Blocking for independent recomputation; consumers must transcribe §6.1 | +| G2 | ADR-322C §Ledger specifies content-addressed segments with `segmentMerkleRoot` and a **signed** head under `ruflo/flywheel-ledger-head/v1`. `main` implements a flat `commits[]` array in one state file with an **unsigned** SHA-256 chain (`flywheel-transaction.ts:553-568,619-636`) | A ledger head cannot currently be signature-verified across a repo boundary; anchor the **receipt**, whose signature is implemented | +| G3 | No unknown-field whitelist in `verifyFlywheelReceipt` (§2.4) | Consumers must enforce it via `schemas/` | +| G4 | ADR-322C §Flywheel projection (external receipt export) is deliberately disabled (ADR-322 §Current inventory) | Do not assume an upstream `@metaharness/flywheel` round-trip is available | + +Per ADR-322 §"Phased rollout", phases 0–2 are implemented; phases 3–4 (signed +`SafetyEnvelope`, `toolPolicy`/`modelPolicy` evolution, unattended promotion) are +**not** — `safetyEnvelopeRef` is carried and compared, but the signed envelope it +names is a phase-3 artifact. + +## 8. Versioning + +- `schemaVersion` is exact-match, not semver-range. A verifier accepts only the + versions it implements (ADR-322C §Canonical format: schema evolution requires a + new version plus a migration recording input and output hashes). +- `gateVersion` changes are **never retroactive** — an existing receipt is judged + under the gate version it recorded (ADR-322C §Default statistical rule). +- Per `ruvnet/ruflo#3066`, consumers must not pin to unreleased ruflo commits + without a compatibility ADR. Pin `schemaVersion` + `gateVersion` strings, not + git SHAs. + +## 9. `PROPOSED-EXTENSION`: cross-repo anchoring + +ADR-322C defines records and their verification but **no pointer format** for +anchoring one into a foreign chain. `rvm#35` and `autogenous#10` both need one. +Minimal placeholder in `schemas/ruflo-anchor-record-v1.schema.json`: + +- `anchoredContentId` / `anchoredSchemaVersion` — the `sha256:` ID of the anchored + record and what kind of record it is. +- `chain` — foreign chain identifier and position. +- `assuranceLevel` (`service-side` | `hypervisor-side`) — required by `rvm#35` and + `autogenous#10`: a service-side record anchored into a hypervisor chain does + **not** thereby acquire hypervisor-side guarantees (`rvm` ADR-285 discipline). +- Signing domain `ruflo/flywheel-anchor/v1` — distinct so an anchor signature can + never be replayed as a receipt signature (§4). + +Nothing above is decided. It needs an ADR before `rvm`, `autogenous`, or +`ruvector` depends on it. From 66fbe7ce12d88aec993e7ea6bac593009fd7da76 Mon Sep 17 00:00:00 2001 From: ruv Date: Wed, 19 Aug 2026 22:01:21 -0400 Subject: [PATCH 2/3] docs(adr): make ADR-322C recomputation reproducible from the spec alone Closes the gap raised by ruflo#3069: ADR-322C required independent statistical recomputation but specified only the bootstrap seed, not the generator it drives. A verifier could not reproduce a receipt's statistics from the document - the only way to recompute correctly was to read flywheel-receipt.ts, which is a copy rather than an independent check. Appends an "Update (2026-08-19)" section per this repo's ADR convention (ADR-380) rather than editing the text above. It makes normative: the LCG and its constants, the seeding rule and exact byte slice, the resampling procedure and draw order, the quantile rule, tie/edge cases, and the scale-12 decimal encoding the statistics must reproduce byte-for-byte. It also records the ledger divergence (flat unsigned commits[] on main vs the content-addressed segments and signed head the ADR describes, with flywheel-ledger-head/v1 unused), the disabled projection path, and that strictness is versioned. Acceptance is demonstrated, not asserted: conformance/recompute_reference.py is written only from the amendment prose, in a different language from the reference implementation, and reproduces the fixture exactly. Adds receipt-bootstrap-reference.example.json because the existing example turned out not to discriminate - its deltas take two distinct values, so a wrong seed slice, wrong byte order, or entirely different LCG constants all yield the same 2.5th percentile. The new fixture has heterogeneous deltas and separates all three. Records one defect found while building it (gap G5): createFlywheelReceipt computes statistics from full-precision means while storing scale-12 strings, so a receipt whose mean needs more than twelve decimals fails its own verifyFlywheelReceipt. Reproduced at mean 0.7687083333333332. Existing fixtures use exactly-representable means, which is why it was not caught. Co-Authored-By: claude-flow --- .../ADR-322C-receipt-ledger-verification.md | 156 +++++++++++ v3/docs/spec/conformance-checklist.md | 20 +- .../spec/conformance/recompute_reference.py | 126 +++++++++ .../receipt-bootstrap-reference.example.json | 261 ++++++++++++++++++ v3/docs/spec/witness-receipt-contract.md | 31 ++- 5 files changed, 583 insertions(+), 11 deletions(-) create mode 100644 v3/docs/spec/conformance/recompute_reference.py create mode 100644 v3/docs/spec/examples/receipt-bootstrap-reference.example.json diff --git a/v3/docs/adr/ADR-322C-receipt-ledger-verification.md b/v3/docs/adr/ADR-322C-receipt-ledger-verification.md index f845f43860..b17a4abd46 100644 --- a/v3/docs/adr/ADR-322C-receipt-ledger-verification.md +++ b/v3/docs/adr/ADR-322C-receipt-ledger-verification.md @@ -150,3 +150,159 @@ The adapter projects ruflo policy and evidence into `@metaharness/flywheel` type 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. + +## Update (2026-08-19) — normative recomputation procedure, ledger status, projection status + +Raised by ruflo#3069 during the ADR-322C contract extraction for the RuV Perpetual +Intelligence Runtime (ruflo#3066, PR #3067). Appended rather than edited into the +text above, per this repo's norms around honest documentation. + +**The problem.** This ADR's central claim is that a verifier *recomputes* the +statistics rather than trusting the proposer's reported numbers. But the sections +above specify only the bootstrap **seed**, not the generator it drives, the +resampling procedure, or the decimal encoding of the results. An independent +verifier therefore could not reproduce a receipt's statistics from this document — +the only way to recompute correctly was to read `flywheel-receipt.ts`, which is a +copy, not an independent check. The recomputation requirement was unverifiable in +practice. The procedure below closes that; it is transcribed from +`flywheel-receipt.ts:206-307` and is normative from this Update onward. + +### 1. Deterministic PRNG + +```text +digest = SHA-256("ruflo/bootstrap/v1" || corpusHash || candidateId || + baselineRef || evaluationRunId) # concatenation, no separator +seedHex = lowercase hex of the full 32-byte digest # recorded in the receipt +state = uint32 big-endian read of digest[0..4] # FIRST FOUR BYTES ONLY +``` + +Each draw advances a linear congruential generator and returns a value in `[0, 1)`: + +```text +state = (1664525 * state + 1013904223) mod 2^32 +draw = state / 2^32 +``` + +The multiplier, increment, and modulus are exact. `state` is unsigned throughout. +The first draw uses the *advanced* state, never the seed value itself. + +### 2. Resampling procedure + +`iterations` defaults to 10,000, must be an integer, and must be `>= 100`. Let `n` +be the length of `heldOutDeltas`. + +```text +if n == 0: + every resample mean is 0 +else: + for b in 0 .. iterations-1: + total = 0 + for i in 0 .. n-1: + total += heldOutDeltas[ floor(draw() * n) ] + means[b] = total / n +``` + +Draw order is load-bearing: exactly `n` draws per iteration, consumed in sequence. +An implementation that draws indices in a different order, or draws once per +iteration, produces a different — and non-conforming — result. + +```text +pairedBootstrapProbability = count(means[b] > 0) / iterations # strictly greater +pairedBootstrapDeltaCILow95 = the floor(0.025 * iterations)-th smallest of means + # 0-based order statistic (selection, not sorting; + # any correct selection algorithm is conforming) +``` + +### 3. Decision + +```text +relativeLift = (candidateScore - baselineScore) / max(|baselineScore|, metricEpsilon) +metricEpsilon defaults to 1e-12 +significant = pairedBootstrapProbability >= 0.95 AND pairedBootstrapDeltaCILow95 > 0 +accepted = relativeLift >= 0.02 AND significant AND frozenAnchorRegression <= 0 +decision = "accepted" if (accepted AND every value in gates is true) else "rejected" +``` + +Comparisons are on the numeric values, before decimal encoding. + +### 4. Decimal encoding of results + +The `statistics` object must reproduce **byte-for-byte** under JCS, so its encoding +is part of the contract. Every fractional field is encoded by: + +```text +1. fixed-point render at scale 12 (twelve digits after the decimal point) +2. strip trailing zeros, then a trailing decimal point if one remains +3. if the result is "" or "-0", emit "0" +``` + +So `0.0928571428571...` renders `"0.092857142857"`, `1` renders `"1"`, and `0` +renders `"0"`. This applies to `relativeLift`, `pairedBootstrapProbability`, +`pairedBootstrapDeltaCILow95`, and `frozenAnchorRegression`, and to the +`baselineScore`, `candidateScore`, and `heldOutDeltas` fields. + +**A producer must compute the statistics from the encoded values, not from its +internal full-precision values.** A verifier has only the encoded strings, so any +precision the producer used but did not record is precision the verifier cannot +reproduce. Stated as a rule: decode `baselineScore`, `candidateScore`, and +`heldOutDeltas` back from their encoded form and compute from *those*, so producer +and verifier are evaluating identical inputs by construction. + +**Known divergence (2026-08-19).** `createFlywheelReceipt` currently violates this: +it computes `statistics` from full-precision means while storing scale-12 strings, +so a receipt whose mean needs more than twelve decimals fails its own +`verifyFlywheelReceipt` with `statistical decision does not recompute`. Reproduced +with twenty-four 3-decimal task scores (mean `0.7687083333333332`, stored +`"0.768708333333"`), which shifts `relativeLift` by one unit in the last place. +Receipts with exactly-representable means are unaffected, which is why existing +fixtures pass. This is a defect against the rule above, not a change to it. + +### 5. Ledger: what is implemented, what is aspirational + +The §Ledger section above describes content-addressed segments binding +`segmentId`/`previousSegmentId`/`firstSequence`/`lastSequence`/`commits[]`/ +`segmentMerkleRoot`/`createdAt`, plus a **signed** head under +`ruflo/flywheel-ledger-head/v1`. **That is not what `main` implements.** The +implementation (`flywheel-transaction.ts:553-568`, `619-636`) is a flat, +sequence-numbered `commits[]` array inside one transaction-state file: + +```text +commitId = SHA-256(JCS(commit with commitId omitted)) +ledgerHead = SHA-256(JCS({ previous: , commitId: })) +genesis = sha256:<64 zeros> +``` + +There are no segments, no `segmentMerkleRoot`, and **the head is not signed** — the +`ruflo/flywheel-ledger-head/v1` domain is specified but unused on `main`. Chain +integrity today rests on the hash chain plus the signed receipt each commit +consumes, not on a head signature. + +Consumers anchoring across a repo boundary must therefore anchor the **receipt** +(`ruflo.flywheel-receipt/v1`), the only record type whose signature is implemented. +Anchoring a ledger head today means anchoring an unsigned hash-chain value, and +must be described that way. Segments and head signing remain the intended target; +this Update records the divergence rather than leaving consumers to read the ADR as +a description of what exists. + +### 6. Flywheel projection is disabled + +Per ADR-322 §"Current Metaharness capability inventory", external Flywheel receipt +projection is intentionally disabled until a projection can preserve ruflo's gate +and evidence semantics without information loss. No upstream round-trip is +available, so a consumer cannot export state and feed it back to confirm the +round-trip preserves meaning. Re-enabling it is gated on the ADR-322 phase-3 +projection cross-check landing in CI; until then §Flywheel projection describes an +intended capability, not a shipped one. + +### 7. Strictness is versioned + +Unknown fields fail verification for a given schema version (§Canonical format). +A consequence worth stating: a verifier implementing `ruflo.flywheel-receipt/v1` +will reject a receipt from a future version that adds fields. That is the correct +behavior for a security property — fail closed on the unrecognized — but it means +schema evolution requires consumers to upgrade before they can verify newer +receipts, not merely to tolerate them. + +A language-neutral extraction of this protocol, with JSON Schemas, worked examples, +and a conformance checklist, is maintained at +[`../spec/witness-receipt-contract.md`](../spec/witness-receipt-contract.md). diff --git a/v3/docs/spec/conformance-checklist.md b/v3/docs/spec/conformance-checklist.md index 73c42e2658..b4582c134a 100644 --- a/v3/docs/spec/conformance-checklist.md +++ b/v3/docs/spec/conformance-checklist.md @@ -49,10 +49,22 @@ consequences of the same rules. promotion signature (contract §4). - [ ] **B5** The statistical decision is **recomputed**, not read. Your bootstrap reproduces `relativeLift`, `pairedBootstrapProbability`, - `pairedBootstrapDeltaCILow95`, and `accepted` **exactly** for the reference - fixture, using the seed and PRNG in contract §6.1. Expected values for that - fixture: `0.092857142857`, `1`, `0.0425`, `true`, with - `seedHex = be51f05643bce93feb04b7da659e290a203a1a62b5cb408b9c46554df528da84`. + `pairedBootstrapDeltaCILow95`, and `accepted` **exactly** for + [`examples/receipt-bootstrap-reference.example.json`](./examples/receipt-bootstrap-reference.example.json), + using the procedure now normative in ADR-322C §Update (2026-08-19). Expected: + `0.100428571429`, `1`, `0.0489`, `true`, with + `seedHex = 167c9185d76163dfa69ae57c11af813669a6353abcb49d7af673acf918f3a7c3`. + Use **that** fixture, not `receipt-accepted.example.json` — only its deltas are + heterogeneous enough to discriminate. Verified: a wrong seed slice, wrong byte + order, or different LCG constants all produce `0.0425` on the accepted-receipt + fixture (indistinguishable) but `0.04975` / `0.04965` / `0.04915` on this one. + [`conformance/recompute_reference.py`](./conformance/recompute_reference.py) is a + runnable oracle you can diff your implementation against. +- [ ] **B5a** Your producer computes statistics from the **encoded** scores, not + from internal full-precision values — a verifier only ever sees the encoded form. + Note contract gap G5: ruflo's own producer does not yet do this, so a receipt + whose mean needs more than twelve decimals fails its own verifier. Distinguish + that failure from tampering when triaging. - [ ] **B6** Float and decimal fixtures produce identical hashes across every runtime you support (Rust and TypeScript both matter here). **[322C]** - [ ] **B7** Corpus-role disjointness is checked — a task ID appearing in both diff --git a/v3/docs/spec/conformance/recompute_reference.py b/v3/docs/spec/conformance/recompute_reference.py new file mode 100644 index 0000000000..a9f60b3743 --- /dev/null +++ b/v3/docs/spec/conformance/recompute_reference.py @@ -0,0 +1,126 @@ +""" +Independent reference implementation of the ADR-322C bootstrap recomputation. + +Written ONLY from the prose of ADR-322C's "Update (2026-08-19)" amendment, with +no reference to flywheel-receipt.ts. Deliberately in a different language from +the reference implementation: an independent check written by reading the TypeScript +would be a copy, not a check (ruflo#3069). + +It exists to answer one question -- is the specification sufficient to reimplement +from? -- and doubles as a runnable oracle for consumers building their own verifier. + +Usage: + python3 recompute_reference.py ../examples/receipt-bootstrap-reference.example.json + +Exits 0 when the recomputed statistics match the receipt's recorded ones. +Use receipt-bootstrap-reference.example.json, not receipt-accepted.example.json: +only the former has heterogeneous per-task deltas, so only the former actually +discriminates a wrong PRNG (see witness-receipt-contract.md section 6.1). +""" +import hashlib +import json +import sys + + +def seed_state(corpus_hash, candidate_id, baseline_ref, evaluation_run_id): + """Section 1: SHA-256 over the concatenation, no separator.""" + data = ("ruflo/bootstrap/v1" + corpus_hash + candidate_id + + baseline_ref + evaluation_run_id).encode("utf-8") + digest = hashlib.sha256(data).digest() + seed_hex = digest.hex() + state = int.from_bytes(digest[0:4], "big") # FIRST FOUR BYTES ONLY + return seed_hex, state + + +def make_rng(state): + """Section 1: LCG. First draw uses the advanced state.""" + s = state + + def draw(): + nonlocal s + s = (1664525 * s + 1013904223) % (2 ** 32) + return s / (2 ** 32) + + return draw + + +def bootstrap(deltas, draw, iterations=10000): + """Section 2: exactly n draws per iteration, consumed in sequence.""" + n = len(deltas) + if n == 0: + return [0.0] * iterations + means = [] + for _ in range(iterations): + total = 0.0 + for _ in range(n): + total += deltas[int(draw() * n)] + means.append(total / n) + return means + + +def decimal12(value): + """Section 4: scale 12, strip trailing zeros then trailing point, '' or '-0' -> '0'.""" + rendered = f"{value:.12f}" + if "." in rendered: + rendered = rendered.rstrip("0").rstrip(".") + if rendered in ("", "-0"): + return "0" + return rendered + + +def recompute(receipt_payload): + p = receipt_payload + deltas = [float(d) for d in p["heldOutDeltas"]] + baseline = float(p["baselineScore"]) + candidate = float(p["candidateScore"]) + frozen_anchor = float(p["statistics"]["frozenAnchorRegression"]) + iterations = p["statistics"]["iterations"] + metric_epsilon = 1e-12 + + seed_hex, state = seed_state( + p["corpusHash"], p["candidateId"], p["baselineRef"], p["evaluationRunId"] + ) + means = bootstrap(deltas, make_rng(state), iterations) + + probability = sum(1 for m in means if m > 0) / iterations + ci_low = sorted(means)[int(0.025 * iterations)] # 0-based order statistic + + # Section 3 + relative_lift = (candidate - baseline) / max(abs(baseline), metric_epsilon) + significant = probability >= 0.95 and ci_low > 0 + accepted = relative_lift >= 0.02 and significant and frozen_anchor <= 0 + decision = "accepted" if (accepted and all(p["gates"].values())) else "rejected" + + return { + "seedHex": seed_hex, + "relativeLift": decimal12(relative_lift), + "pairedBootstrapProbability": decimal12(probability), + "pairedBootstrapDeltaCILow95": decimal12(ci_low), + "frozenAnchorRegression": decimal12(frozen_anchor), + "significant": significant, + "accepted": accepted, + "decision": decision, + } + + +if __name__ == "__main__": + receipt = json.load(open(sys.argv[1])) + payload = receipt["payload"] + got = recompute(payload) + want = { + "seedHex": payload["statistics"]["seedHex"], + "relativeLift": payload["statistics"]["relativeLift"], + "pairedBootstrapProbability": payload["statistics"]["pairedBootstrapProbability"], + "pairedBootstrapDeltaCILow95": payload["statistics"]["pairedBootstrapDeltaCILow95"], + "frozenAnchorRegression": payload["statistics"]["frozenAnchorRegression"], + "significant": payload["statistics"]["significant"], + "accepted": payload["statistics"]["accepted"], + "decision": payload["decision"], + } + ok = True + for k in want: + match = got[k] == want[k] + ok = ok and match + print(f"{'OK ' if match else 'FAIL'} {k}: got={got[k]!r} want={want[k]!r}") + print("\nRESULT:", "spec is sufficient" if ok else "SPEC INSUFFICIENT") + sys.exit(0 if ok else 1) diff --git a/v3/docs/spec/examples/receipt-bootstrap-reference.example.json b/v3/docs/spec/examples/receipt-bootstrap-reference.example.json new file mode 100644 index 0000000000..d25c9eabc7 --- /dev/null +++ b/v3/docs/spec/examples/receipt-bootstrap-reference.example.json @@ -0,0 +1,261 @@ +{ + "payload": { + "schemaVersion": "ruflo.flywheel-receipt/v1", + "lineageId": "0198f2a0-0000-7000-8000-00000000b1c2", + "candidateId": "sha256:61c84d2769efc8fa1f5e76d2c3d645763cf013a38fa658edaccaede460a172a2", + "evaluationRunId": "0198f2a0-0000-7000-8000-00000000d3e4", + "baselineRef": "sha256:3f786850e387550fdab836ed7e6dc881de23001b0b4b1b0f0a1a2b3c4d5e6f70", + "expectedLedgerHead": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "candidatePolicy": { + "hnswEf": 128, + "hybridWeight": "0.65", + "rerankDepth": 24 + }, + "gateVersion": "ruflo.flywheel-gate/v1", + "policySchemaVersion": "ruflo.retrieval-policy/v1", + "safetyEnvelopeRef": "sha256:9a271f2a916b0b6ee6cecb2426f0b3206ef074578be55d9bc94f6f3fe3ab86aa", + "anchorRef": "sha256:2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae", + "requestedProposer": "auto", + "effectiveProposer": "local", + "corpusVersion": "pir-conformance-corpus/2026-08-19", + "corpusHash": "sha256:fcde2b2edba56bf408601fb721fe9b5c338d10ee429ea04fae5511b68fbf8fb9", + "baselineScore": "0.7", + "candidateScore": "0.7703", + "heldOutDeltas": [ + "0.021", + "0.137", + "0.048", + "0.092", + "0.006", + "0.113", + "0.034", + "0.159", + "0.017", + "0.071", + "0.128", + "0.055", + "0.083", + "-0.012", + "0.101", + "0.029", + "0.146", + "0.064", + "0.038", + "0.076" + ], + "pairedOutcomes": [ + { + "taskId": "task-01", + "baselineScore": "0.7", + "candidateScore": "0.721" + }, + { + "taskId": "task-02", + "baselineScore": "0.7", + "candidateScore": "0.837" + }, + { + "taskId": "task-03", + "baselineScore": "0.7", + "candidateScore": "0.748" + }, + { + "taskId": "task-04", + "baselineScore": "0.7", + "candidateScore": "0.792" + }, + { + "taskId": "task-05", + "baselineScore": "0.7", + "candidateScore": "0.706" + }, + { + "taskId": "task-06", + "baselineScore": "0.7", + "candidateScore": "0.813" + }, + { + "taskId": "task-07", + "baselineScore": "0.7", + "candidateScore": "0.734" + }, + { + "taskId": "task-08", + "baselineScore": "0.7", + "candidateScore": "0.859" + }, + { + "taskId": "task-09", + "baselineScore": "0.7", + "candidateScore": "0.717" + }, + { + "taskId": "task-10", + "baselineScore": "0.7", + "candidateScore": "0.771" + }, + { + "taskId": "task-11", + "baselineScore": "0.7", + "candidateScore": "0.828" + }, + { + "taskId": "task-12", + "baselineScore": "0.7", + "candidateScore": "0.755" + }, + { + "taskId": "task-13", + "baselineScore": "0.7", + "candidateScore": "0.783" + }, + { + "taskId": "task-14", + "baselineScore": "0.7", + "candidateScore": "0.688" + }, + { + "taskId": "task-15", + "baselineScore": "0.7", + "candidateScore": "0.801" + }, + { + "taskId": "task-16", + "baselineScore": "0.7", + "candidateScore": "0.729" + }, + { + "taskId": "task-17", + "baselineScore": "0.7", + "candidateScore": "0.846" + }, + { + "taskId": "task-18", + "baselineScore": "0.7", + "candidateScore": "0.764" + }, + { + "taskId": "task-19", + "baselineScore": "0.7", + "candidateScore": "0.738" + }, + { + "taskId": "task-20", + "baselineScore": "0.7", + "candidateScore": "0.776" + } + ], + "statistics": { + "ruleVersion": "ruflo.flywheel-gate/v1", + "relativeLift": "0.100428571429", + "pairedBootstrapProbability": "1", + "pairedBootstrapDeltaCILow95": "0.0489", + "frozenAnchorRegression": "0", + "iterations": 10000, + "seedHex": "167c9185d76163dfa69ae57c11af813669a6353abcb49d7af673acf918f3a7c3", + "significant": true, + "accepted": true + }, + "gates": { + "heldOutImproves": true, + "frozenAnchorNoRegression": true, + "driftWithinBound": true, + "replayDeterministic": true, + "receiptCoverage": true, + "canaryNoWorse": true + }, + "resourceEvidence": { + "p95LatencyMicros": 412000, + "costMicrosPerTask": 1850, + "tokensPerTask": 3120, + "failureRate": "0", + "evaluationCostMicros": 29600, + "currency": "USD" + }, + "evidence": { + "corpusRoles": { + "selectionTaskIds": [ + "sel-01", + "sel-02", + "sel-03" + ], + "promotionHoldoutTaskIds": [ + "task-01", + "task-02", + "task-03", + "task-04", + "task-05", + "task-06", + "task-07", + "task-08", + "task-09", + "task-10", + "task-11", + "task-12", + "task-13", + "task-14", + "task-15", + "task-16", + "task-17", + "task-18", + "task-19", + "task-20" + ], + "guardTaskIds": [ + "anchor-01", + "anchor-02" + ] + }, + "verification": { + "replayTranscriptRef": "sha256:1b16b1df538ba12dc3f97edbb85caa7050d46c148134290feba80f8236c83db9" + }, + "canary": { + "rollbackRate": "0", + "sliceRef": "sha256:0263829989b6fd954f72baaf2fc64bc2e2f01d692d4de72986ea808f6e99813f" + } + }, + "termVerification": [ + { + "term": "heldOutImproves", + "verification": "recomputed", + "evidenceRef": "inline:pairedOutcomes" + }, + { + "term": "frozenAnchorNoRegression", + "verification": "recomputed", + "evidenceRef": "inline:statistics.frozenAnchorRegression" + }, + { + "term": "driftWithinBound", + "verification": "recomputed", + "evidenceRef": "inline:evidence.verification" + }, + { + "term": "replayDeterministic", + "verification": "recomputed", + "evidenceRef": "sha256:1b16b1df538ba12dc3f97edbb85caa7050d46c148134290feba80f8236c83db9" + }, + { + "term": "receiptCoverage", + "verification": "recomputed", + "evidenceRef": "inline:evidence.corpusRoles" + }, + { + "term": "canaryNoWorse", + "verification": "signature-verified", + "evidenceRef": "sha256:0263829989b6fd954f72baaf2fc64bc2e2f01d692d4de72986ea808f6e99813f", + "attestor": "ruflo-canary-runner/v1" + } + ], + "decision": "accepted", + "issuedAt": "2026-08-19T00:00:00.000Z", + "expiresAt": "2026-08-20T00:00:00.000Z", + "receiptId": "sha256:013a3ab18ec9ddec4cb0a2544bdd1bb9189b3859a9f919ce1d7dcbc6b1b7b913" + }, + "signature": { + "algorithm": "ed25519", + "domain": "ruflo/flywheel-receipt/v1", + "publicKeyPem": "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAqNSpk4jp2Y7WJ3jzCgOiXnVFKQKm5R7266xFiPWUU0s=\n-----END PUBLIC KEY-----\n", + "signatureBase64": "LWwGMjiZtZbt5mEB4MGl4HAWfxGO5j4H/n19gLJ9dswmjCdmkIJaPD0Xnp6tfeAPuvcxMALx16Wx80MKQdMlBw==" + } +} diff --git a/v3/docs/spec/witness-receipt-contract.md b/v3/docs/spec/witness-receipt-contract.md index aa226880a9..8a8007f72f 100644 --- a/v3/docs/spec/witness-receipt-contract.md +++ b/v3/docs/spec/witness-receipt-contract.md @@ -150,19 +150,35 @@ Seed (ADR-322C): `SHA-256("ruflo/bootstrap/v1" || corpusHash || candidateId || baselineRef || evaluationRunId)`, concatenated with no separator. The full digest hex is recorded as `seedHex`. -**The ADR does not specify the PRNG driven by that seed, but recomputation is -impossible without it.** Transcribed from `flywheel-receipt.ts:212-293` and -normative for any independent verifier: +The PRNG driven by that seed, the resampling procedure, and the decimal encoding +of the results are now normative in **ADR-322C §Update (2026-08-19)** — added by +ruflo#3069, which this spec's first draft raised. Consult that section as the +authority; in summary: - PRNG state = first 4 bytes of the seed digest, big-endian uint32. - Step: `state = (1664525 * state + 1013904223) mod 2^32`; draw = `state / 2^32`. -- 10,000 resamples by default; each draws `n` indices as `floor(draw * n)` and - averages the corresponding `heldOutDeltas`. +- 10,000 resamples by default; each draws `n` indices as `floor(draw * n)`, in + sequence, and averages the corresponding `heldOutDeltas`. - `pairedBootstrapProbability` = fraction of resample means strictly `> 0`. - `pairedBootstrapDeltaCILow95` = the `floor(0.025 * iterations)`-th order statistic (0-based) of the resample means. +- Results are encoded at scale 12 with trailing zeros stripped. -Filed as gap G1 in §7: this belongs in ADR-322C, not only in source. +**Test your implementation against +[`examples/receipt-bootstrap-reference.example.json`](./examples/receipt-bootstrap-reference.example.json), +not the accepted-receipt example.** Only the former has heterogeneous per-task +deltas. The latter's deltas take two distinct values, which makes its 2.5th +percentile identical under a wrong seed slice, a wrong byte order, or entirely +different LCG constants — it would pass a non-conforming verifier. +[`conformance/recompute_reference.py`](./conformance/recompute_reference.py) is a +runnable oracle written from the ADR prose alone; it reproduces that fixture +exactly and is the demonstration that the spec is sufficient to reimplement from. + +**Caveat consumers will hit:** a producer must compute the statistics from the +*encoded* scores, since that is all a verifier has. `createFlywheelReceipt` +currently computes from full-precision means while storing scale-12 strings, so a +receipt whose mean needs more than twelve decimals fails ruflo's own verifier with +`statistical decision does not recompute`. Gap G5 in §7. ### 6.2 Sequential evidence (ADR-381) @@ -185,10 +201,11 @@ bound must quote the per-epoch qualifier and the `Proposed` status together. | # | Gap | Consumer impact | |---|---|---| -| G1 | Bootstrap PRNG algorithm is in source only (§6.1) | Blocking for independent recomputation; consumers must transcribe §6.1 | +| G1 | ~~Bootstrap PRNG algorithm is in source only~~ — **closed** by ADR-322C §Update (2026-08-19) (ruflo#3069) | Resolved; recompute from the ADR, verify against the reference fixture | | G2 | ADR-322C §Ledger specifies content-addressed segments with `segmentMerkleRoot` and a **signed** head under `ruflo/flywheel-ledger-head/v1`. `main` implements a flat `commits[]` array in one state file with an **unsigned** SHA-256 chain (`flywheel-transaction.ts:553-568,619-636`) | A ledger head cannot currently be signature-verified across a repo boundary; anchor the **receipt**, whose signature is implemented | | G3 | No unknown-field whitelist in `verifyFlywheelReceipt` (§2.4) | Consumers must enforce it via `schemas/` | | G4 | ADR-322C §Flywheel projection (external receipt export) is deliberately disabled (ADR-322 §Current inventory) | Do not assume an upstream `@metaharness/flywheel` round-trip is available | +| G5 | `createFlywheelReceipt` computes statistics from full-precision means but stores scale-12 strings, so a receipt whose mean needs >12 decimals fails ruflo's own verifier (§6.1) | A legitimately produced receipt can be unverifiable. Compute from the encoded values; treat a `statistical decision does not recompute` error on a receipt you trust as this defect, not tampering | Per ADR-322 §"Phased rollout", phases 0–2 are implemented; phases 3–4 (signed `SafetyEnvelope`, `toolPolicy`/`modelPolicy` evolution, unattended promotion) are From 34f11dbd46c3d8e4142222c8c04c820061ce3b4b Mon Sep 17 00:00:00 2001 From: ruv Date: Thu, 20 Aug 2026 08:37:26 -0400 Subject: [PATCH 3/3] docs(spec): bound signatureBase64 to the exact Ed25519 base64 length MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The receipt and anchor-record schemas accepted any length of base64 (^[A-Za-z0-9+/]+={0,2}$), so oversized garbage passed structural validation. An Ed25519 signature is exactly 64 bytes — 88 base64 characters with two padding chars — so the pattern is now ^[A-Za-z0-9+/]{86}==$, consistent with the fixed-width contentId and seedHex patterns elsewhere in the schemas. The promotion-commit schema carries no signature field (commits are unsigned in ADR-322C) and is unchanged. All four example fixtures re-validated against the tightened schemas with Ajv 2020 strict; a 4KB-garbage-signature negative control is now rejected. Co-Authored-By: claude-flow Claude-Session: https://claude.ai/code/session_012Jib2gQyJpqCoo2xYAbb4X --- v3/docs/spec/schemas/ruflo-anchor-record-v1.schema.json | 2 +- v3/docs/spec/schemas/ruflo-flywheel-receipt-v1.schema.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/v3/docs/spec/schemas/ruflo-anchor-record-v1.schema.json b/v3/docs/spec/schemas/ruflo-anchor-record-v1.schema.json index 89acbaee9f..1ebe84eb30 100644 --- a/v3/docs/spec/schemas/ruflo-anchor-record-v1.schema.json +++ b/v3/docs/spec/schemas/ruflo-anchor-record-v1.schema.json @@ -27,7 +27,7 @@ "description": "PROPOSED-EXTENSION signing domain. Distinct from ruflo/flywheel-receipt/v1 so an anchor signature can never be replayed as a receipt signature, per ADR-322 section Persistence and key boundaries." }, "publicKeyPem": { "type": "string", "pattern": "^-----BEGIN PUBLIC KEY-----" }, - "signatureBase64": { "type": "string", "pattern": "^[A-Za-z0-9+/]+={0,2}$" } + "signatureBase64": { "type": "string", "pattern": "^[A-Za-z0-9+/]{86}==$" } } }, "payload": { diff --git a/v3/docs/spec/schemas/ruflo-flywheel-receipt-v1.schema.json b/v3/docs/spec/schemas/ruflo-flywheel-receipt-v1.schema.json index 7aea2cf047..7ebbd628d1 100644 --- a/v3/docs/spec/schemas/ruflo-flywheel-receipt-v1.schema.json +++ b/v3/docs/spec/schemas/ruflo-flywheel-receipt-v1.schema.json @@ -41,7 +41,7 @@ "description": "Ed25519 domain-separation prefix. Signed bytes are UTF8(domain) || 0x00 || JCS(payload)." }, "publicKeyPem": { "type": "string", "pattern": "^-----BEGIN PUBLIC KEY-----" }, - "signatureBase64": { "type": "string", "pattern": "^[A-Za-z0-9+/]+={0,2}$" } + "signatureBase64": { "type": "string", "pattern": "^[A-Za-z0-9+/]{86}==$" } } }, "pairedOutcome": {