🌊 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
docs(spec): witness/receipt contract extracted from ADR-322C
ruva914ebdc69d2
diff --git a/v3/docs/spec/conformance-checklist.md b/v3/docs/spec/conformance-checklist.mdnew file mode 100644index 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.jsonnew file mode 100644index 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.jsonnew file mode 100644index 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.jsonnew file mode 100644index 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.jsonnew file mode 100644index 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.jsonnew file mode 100644index 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:<lowercase-hex>."+ },+ "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.jsonnew file mode 100644index 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: <previousLedgerHead>, commitId: <commit.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.mdnew file mode 100644index 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:<lowercase-hex>+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:<hex>"+evaluationRunId = UUIDv7, one per execution attempt+receiptId = SHA-256(JCS(unsigned receipt payload)) -> "sha256:<hex>"+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.