evidencebook

package module
v0.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 20, 2026 License: Apache-2.0 Imports: 48 Imported by: 4

README

evidencebook

evidencebook is a Go implementation of the evidence layer: a local evidence store that records evidence and the typed links between records, commits payload digests while payload bytes are resolved separately, keeps three distinct classes of index, and answers requests for evidence with portable bundles that anyone can verify.

A book embeds a commitment substrate and never exposes it. The Checkpointed Local Log (CLL Go) is the reference substrate; a SCITT receipt-holding binding shows the book does not depend on it. Every record is sealed as an Agent Action Capsule, so a bundle from a book on the CLL substrate verifies, interval and all, with the neutral Evidence Bundle verifier alone.

Terms Packs (packs): EU AI Act Obligations and Outcomes (draft) are published at actionstate.ai/packs, and Everyday Rules ships with the Muse integration.

Install

Requires Go 1.27 or newer.

go get github.com/action-state-group/evidencebook

Use

store, _ := evidencebook.OpenFileStore("book/records")
substrate, _ := evidencebook.OpenCLL("book/cll.jsonl", "orders-log", checkpointKey)
signer, _ := evidencebook.NewEd25519Signer(recordKey)
// Payload bytes live in an artifact store (capsule-emit's artifact.Store
// contract); this is its JSONL backend, trusting the book's signer.
originals, _ := evidencebook.OpenOriginalsFile(ctx, "artifacts.jsonl", "orders", signer.PublicKey())

book, err := evidencebook.Open(ctx, evidencebook.Config{
	BookID: "orders", Operator: "example-operator",
	Store: store, Substrate: substrate, Originals: originals, Signer: signer,
})

observed, err := book.Append(ctx, evidencebook.Entry{
	RecordType:    "observation",
	EpistemicType: evidencebook.ObservedEvent,
	SubjectRef:    "order-17",
	Payloads:      [][]byte{[]byte(`{"status":"approved"}`)},
})

bundle, err := book.Bundle(ctx, evidencebook.BundleRequest{Root: observed.RecordID})

Production code must handle every error. The verbs are Append, Query, Bundle, Request, Respond, Reconcile and Close. See docs/design.md for how each public type maps to the specification, the cross-implementation checks, and the known limits.

Answering requests

Respond implements the responder side of the Minimum Evidence Interoperability Profile, evidence-interop/0 (agent-action-capsule spec/interop-profile-v0.md), over the request map of draft-mih-agent-evidence-request-00. It takes the request octets with their media type (application/json or application/cbor) and answers in the same encoding with a signed envelope carrying the canonical Artifact, or a signed refusal with exactly one registered reason. The Artifact depends only on the subject, the resolved anchor and the derivation: never on the requester, the nonce, the route or the encoding. Manifest returns the profile's history-free manifest.

A protected subject is answered only to a requester the transport has authenticated: set RespondOptions.AuthenticatedRequester from that authentication. With it empty, only checkpoints and the history_card/1 derivation are answered and every other subject gets a signed not_authorized refusal. A declared requester id is never trusted and is not recorded. See the CHANGELOG for the upgrade note.

Testing evidencebook with your own verifier

To check evidencebook's answers with a verifier you wrote yourself, from the profile text and with keys you choose to trust, follow docs/THIRD-PARTY-VERIFIER.md. It starts from a fresh machine. It names the pinned profile, request draft and conformance vectors, and runs a test responder (go run ./test/interop/answer) that answers your own request octets. For each vector class it gives the request to send and the result the vectors specify, and it says what to report back. Its personal-evidence part reproduces the run the Personal-Agent History vectors were cut from (go run ./test/interop/personal-history) and gives the result specified for each of their cases.

Checking foreign evidence

Adapters check objects produced by other protocols under each protocol's own verification method and report every property with the method used. The first is x402 (the payer's signed transfer authorization, the settlement response, and an optional payee receipt):

go run ./cmd/evidencebook adapt x402 -policy trust-policy.json exchange.http

The ACP adapter (adapt acp) reads the Agentic Commerce Protocol's checkout session, order and delegated payment token. ACP signs none of them, so it reports possession of the exact octets and never a native PASS.

See docs/ADAPTERS.md for the interface, what each adapter checks and does not check, and how a failed check maps to a requirement.

Development

gofmt -l .
go vet ./...
go test ./...
go test -race ./...

CI also checks bundles both ways: a bundle produced here is verified by the Python Agent Action Capsule bundle verifier (test/interop/python-aac/verify_bundle.py) and the Python CLL reference (test/interop/python-cll/verify_bundle.py), and a bundle produced in Python (test/interop/python-cll/build_bundle.py) is verified here (test/interop/verify); a tampered copy must fail in each direction. The profile's reference verifier checks this responder's replies against the profile's conformance vectors (test/interop/responder, test/interop/python-profile/verify_responder.py), over the native stream, the A2A carriage (Book.A2A) and the MCP carriage (Book.MCP), and checks that all three carry a byte-identical canonical Artifact. CI also reproduces the responder run of the Personal-Agent History vectors byte for byte (test/interop/personal-history), rebuilds the corpus from it, and runs the corpus's own test.

Other implementations and parity

  • Rust: the evidencebook crate in this repository (rust/evidencebook, moved here from checkpointed-local-log with its history) implements the same evidence-layer semantics over the Rust Checkpointed Local Log: records, epistemic types, links, disclosure, retention, requests and reconcile/close.
  • Parity vectors shared across implementations, all checked in CI:
    • schemas/vendor/epistemic-types.json: the epistemic type value set (TestEpistemicTypeThreeWayParity);
    • testdata/refusal-interop/: a refusal signed in Python, verified here; a refusal signed here is verified in Python;
    • testdata/evidence-request/: the request draft's spec-derived request, resolution and refusal vectors, vendored with their upstream SHA-256s (TestRequestVectors, TestResolutionVectors, TestRefusalVectors);
    • testdata/reconcile-parity/: exchange halves and the Python correlator's outcomes, which ReconcileHalves must match.
  • Bundles are Evidence Bundle v2: anything that verifies one (the Go and Python Agent Action Capsule bundle verifiers) checks a bundle from a book.

docs/design.md lists every cross-implementation check.

License

Apache-2.0.

Documentation

Overview

Package evidencebook is a reference implementation of the Evidence Layer: a local evidence store that records evidence and the typed links between records, keeps payload digests committed while payload bytes are resolved separately, maintains three distinct classes of index, and answers requests for evidence with portable, independently verifiable bundles.

A Book embeds a commitment substrate. The Checkpointed Local Log binding (OpenCLL) is the reference; a SCITT receipt-holding binding (NewSCITTReceiptSubstrate) shows that conformance does not depend on it. The substrate never appears in the Book's API: callers append records and ask for bundles, requests, reconciliations and closes, and the book composes every proof itself.

Every record is sealed as an Agent Action Capsule whose agent input digest commits the record header, so a bundle this package produces is checked by the neutral Evidence Bundle verifier with nothing from this package. Over the SCITT stub, which keeps no ordered log, that verifier reports interval coverage as withheld.

Index

Constants

View Source
const (
	ExtensionPayloads  = "evidencebook/payloads"
	ExtensionInclusion = "evidencebook/inclusion"
	ExtensionSubject   = "evidencebook/subject"
)

Bundle extension keys this package writes. Extensions are integrity-covered by the bundle digest and uninterpreted by the neutral bundle verifier.

View Source
const (
	HalfMemberDealID             = "deal_id"
	HalfMemberBookID             = "book_id"
	HalfMemberRecordedAt         = "recorded_at"
	HalfMemberCommitAlg          = "commit_alg"
	HalfMemberAmountCommitment   = "amount_commitment"
	HalfMemberCurrencyCommitment = "currency_commitment"
)

The six abstract half members a half mapping fills (DR §4.1).

View Source
const (
	SetComplete  = "COMPLETE"
	SetUndecided = "UNDECIDED"
	SetNotShown  = "NOT_SHOWN"
)

Set statuses (DR §6.1).

View Source
const (
	// A2AProtocolVersion is the one A2A-Version this carriage speaks.
	A2AProtocolVersion = "1.0"
	// A2AExtensionURI is the extension the exchange is advertised and
	// activated under (P-37): the request draft's Datatracker URL.
	A2AExtensionURI = "https://datatracker.ietf.org/doc/draft-mih-agent-evidence-request/"
	// A2AProtocolBinding is the Agent Card protocolBinding this carriage
	// serves.
	A2AProtocolBinding = "JSONRPC"
)

The A2A carriage of the exchange (profile §11.4.4), over A2A 1.0 in its JSON-RPC binding.

View Source
const (
	BindingStream = "evidence-request/1"
	BindingHTTP   = "http"
	BindingA2A    = "a2a"
	BindingMCP    = "mcp"
)

Binding tokens a manifest may list (profile §4, §11.4.2).

View Source
const (
	// MCPProtocolVersion is the one MCP revision this carriage speaks.
	MCPProtocolVersion = "2026-07-28"
	// MCPToolManifest returns the manifest (profile §11.4.2) as its
	// structuredContent.
	MCPToolManifest = "evidence_manifest"
	// MCPToolRequest carries one request and returns its reply.
	MCPToolRequest = "evidence_request"
)

The MCP carriage of the exchange (profile §11.4.5), over MCP 2026-07-28.

View Source
const (
	KindCLLCheckpoint       = evidencerequest.KindCLLCheckpoint
	KindCLLInclusionProof   = evidencerequest.KindCLLInclusionProof
	KindCLLConsistencyProof = evidencerequest.KindCLLConsistencyProof
)

Verification-material kinds (profile §6.2.1), the Checkpointed Local Log mechanism's proof formats.

View Source
const (
	ProfileID             = evidencerequest.ProfileID
	RequestDraft          = evidencerequest.RequestDraft
	DerivationHistoryCard = evidencerequest.DerivationHistoryCard
)

The request draft's identifiers, subject forms, refusal reasons and request types are defined in go/evidencerequest (draft-mih-agent-evidence-request-00, profile evidence-interop/0); these names keep evidencebook's API.

View Source
const (
	SubjectFullHistory = evidencerequest.SubjectFullHistory
	SubjectCheckpoints = evidencerequest.SubjectCheckpoints
	SubjectRecord      = evidencerequest.SubjectRecord
	SubjectRange       = evidencerequest.SubjectRange
	SubjectCorrelation = evidencerequest.SubjectCorrelation
	SubjectExchange    = evidencerequest.SubjectExchange
)
View Source
const (
	ReasonNotAuthorized         = evidencerequest.ReasonNotAuthorized
	ReasonNoSuchSubject         = evidencerequest.ReasonNoSuchSubject
	ReasonCoverageUnsatisfiable = evidencerequest.ReasonCoverageUnsatisfiable
	ReasonDerivationUnsupported = evidencerequest.ReasonDerivationUnsupported
	ReasonPolicyDeclined        = evidencerequest.ReasonPolicyDeclined
	ReasonDeadlineUnmet         = evidencerequest.ReasonDeadlineUnmet
	ReasonRequestMalformed      = evidencerequest.ReasonRequestMalformed
	ReasonRetentionExpired      = evidencerequest.ReasonRetentionExpired
)

The registered refusal reasons (ER §13).

View Source
const (
	// RefusalPolicySpecific answers the most specific registered token.
	RefusalPolicySpecific = "specific"
	// RefusalPolicyUniform answers policy_declined wherever a more specific
	// token would disclose what the responder's policy protects: whether a
	// subject exists, whether it is covered yet, and whether this requester
	// may see it (ER §4.2, §12).
	RefusalPolicyUniform = "uniform"
)

Refusal policies a responder may declare (profile §11.4.2 refusal_policy).

View Source
const (
	DefaultMaxRequestBytes = 64 << 10
	DefaultMaxAnswerItems  = 10_000
)

Defaults of the responder's cost policy.

View Source
const (
	RelationshipStranger     = "stranger"
	RelationshipIdentified   = "identified"
	RelationshipCounterparty = "counterparty"
)

Relationship of a requester to this book, checkable from local records. A stranger is a caller with no authenticated identity.

View Source
const (
	MediaTypeJSON = evidencerequest.MediaTypeJSON
	MediaTypeCBOR = evidencerequest.MediaTypeCBOR
)

The two encodings a request and its reply travel in (profile §4, §11.4.1 rule 7). The wire values, their strict decoders and deterministic encoders live in go/evidencerequest; these names keep evidencebook's API.

View Source
const (
	JoinExchangeID    = "exchange_id"
	JoinRequestDigest = "request_digest"
)

Join keys a pair can be correlated by, in preference order.

View Source
const (
	RecordTypeClose           = "close"
	RecordTypeDisclosure      = "disclosure"
	RecordTypeLifecycle       = "lifecycle"
	RecordTypeIndexRoot       = "index_root"
	RecordTypeRequest         = "evidence_request"
	RecordTypeRequestAnswered = "evidence_request_answered"
	RecordTypeResponse        = "evidence_response"
	RecordTypeAbsence         = "recorded_absence"
	RecordTypeAcknowledgement = "acknowledgement"
	RecordTypeRebuttal        = "rebuttal"
)

Record types this package writes itself. Callers may use any other token; record_type is open vocabulary.

View Source
const (
	OutcomeArtifact             = "artifact"
	OutcomeRefusal              = "refusal"
	OutcomeArtifactFailed       = "artifact_verification_failed"
	OutcomeRefusalNonconforming = "refusal_nonconformant"
)

Response outcomes as recorded by a requester. Artifact and refusal are two of the request draft's three outcomes; the other two values are sub-states of a received reply that did not verify (a response received and failed, profile P-21), named as the request-draft vectors name them. None is ever an absence.

View Source
const CadenceDepth = 16

CadenceDepth is the tree's fixed depth: every path is 16 hashes, and a tick holds at most 2^16 - 1 logs beside its filler.

View Source
const CadenceExtension = "x-cadence-witness/v0"

CadenceExtension is the bundle extension a deal's cadence chain travels in, capsule-cli's name for it. Bundles from before carried it as "cadence-witness/v0" or "x-deal-cadence-v0"; verifiers still read those.

View Source
const CommitAlgNonce256 = "sha256-jcs-nonce256"

CommitAlgNonce256 names the salted per-field commitment a header's field_commitments use: agent-action-capsule spec/presentation-contract-v0.md §7.2, the construction capsule-cli's deal records already declare under the same identifier, and the one evidencebook#44 rules a History's deal-level commitments use:

commitment = lowercase_hex(SHA-256(JCS({"nonce": N, "text": T})))

N is 64 lowercase hex characters encoding 32 fresh CSPRNG bytes per committed text; T is the exact text, unnormalized. That is the Disclosure Envelope's DE-3 computation (JSON-DIGEST) applied to the opening object {nonce, text}, never to the bare text: without N a guess at T cannot be tested.

View Source
const DealReconcileContractRef = "ec:deal-reconcile@1"

DealReconcileContractRef is the contract_ref a claim under this contract carries.

View Source
const DefaultClosureDepth = 2

DefaultClosureDepth is the citation depth a bundle follows from its root.

View Source
const DefaultDeveloper = "evidencebook"

DefaultDeveloper is the AAC developer value a book writes when none is set.

View Source
const HeaderMember = "agent_input"

HeaderMember is the AAC disclosure member that carries a record header.

View Source
const HeaderVersion = 1

HeaderVersion is the version of the record header wire form this package writes and accepts.

View Source
const InclusionKindSCITTReceiptUnverified = "scitt-receipt-unverified"

InclusionKindSCITTReceiptUnverified labels the inclusion evidence this stub carries: a transparency-service receipt held as opaque bytes and never verified here. It proves possession of those bytes only (FR-20); a verifier runs the receipt's own check. The stub's receipts are never served as checkpoints or proofs in a profile answer: Respond answers only from a Checkpointed Local Log.

View Source
const MinimumAbsenceWindow = time.Minute

MinimumAbsenceWindow is the shortest waiting window an absence may claim, measured from when the request was recorded.

View Source
const RecordHeaderMember = "evidence_record_header"

RecordHeaderMember is the top-level Capsule member through which a capsule sealed by the book's caller (AppendCapsule) carries its own record header: the header's JSON, exactly as the book canonicalized it. capsule_id covers it like every member, so the capsule commits its header without a separate digest, and a reader of the capsule reads the header in it. A record the book seals itself (Append) commits its header as the capsule's agent_input_digest instead, and carries no such member.

View Source
const RecordTypeRetentionCommitment = "retention_commitment"

RecordTypeRetentionCommitment is the record type of a retention commitment this book has issued.

View Source
const SubstrateKindCLL = "cll"

SubstrateKindCLL labels checkpoints and proofs produced by the CLL binding.

View Source
const SubstrateKindSCITTReceipt = "scitt-receipt"

SubstrateKindSCITTReceipt labels the receipt-holding binding.

Variables

View Source
var (
	// ErrInvalid reports input that violates the record model or a request
	// shape. It is go/evidencerequest's own sentinel, so an error from the
	// aliased protocol types (Refusal.Verify, Envelope.Verify, ...) and one
	// raised here both match it.
	ErrInvalid = evidencerequest.ErrInvalid
	// ErrNotFound reports a record, payload or checkpoint the book does not hold.
	ErrNotFound = errors.New("evidencebook: not found")
	// ErrCorrupt reports stored state that disagrees with the commitment substrate.
	ErrCorrupt = errors.New("evidencebook: corrupt")
	// ErrUnsupported reports a capability the configured substrate or index does
	// not provide, such as range proofs over a receipt-only substrate.
	ErrUnsupported = errors.New("evidencebook: unsupported")
	// ErrNotCovered reports a record that no checkpoint covers yet.
	ErrNotCovered = errors.New("evidencebook: not checkpoint-covered")
	// ErrUnavailable reports a payload whose retention state yields no bytes.
	ErrUnavailable = errors.New("evidencebook: payload unavailable")
	// ErrLegalHold reports a deletion blocked by a legal hold.
	ErrLegalHold = errors.New("evidencebook: legal hold")
	// ErrReleased reports a write to a book, or a call on a shelf, after it
	// was released.
	ErrReleased = errors.New("evidencebook: released")
)

RefusalReasons is the registry, in the draft's order.

SubjectForms lists the six forms in code-point order.

Functions

func DerivedFillers added in v0.5.0

func DerivedFillers(seed []byte, count uint64, used map[uint64]bool) (map[uint64][]byte, error)

DerivedFillers returns fillers 1..count of a tick, by position. Filler i is SHA-256(0x03 ‖ n_i) with n_i = SHA-256(seed ‖ uint64be(i)); its position is the first unused one among, for attempt a = 0, 1, …, uint64be(SHA-256(seed ‖ "pos" ‖ uint64be(i) ‖ uint32be(a))[0:8]) mod 2^16, after the logs' leaves and filler 0 (used) and the fillers before it. used is updated. The same seed, count and used positions give the same fillers, so a tick's tree is rebuilt from what it stored.

func EncodeRequest added in v0.2.0

func EncodeRequest(r EvidenceRequest, mediaType string) ([]byte, error)

EncodeRequest encodes r in the given media type: JCS for JSON, core deterministic CBOR for CBOR.

func KeyID

func KeyID(s Signer) string

KeyID is the lowercase hex encoding of the signer's raw public key, the same key_id convention the record envelopes and checkpoints use.

func MigratePayloadDir added in v0.5.0

func MigratePayloadDir(ctx context.Context, store Store, originals ArtifactStore, dir string) (int, error)

MigratePayloadDir moves the payload bytes an earlier evidencebook kept in a payload directory (one file per payload, named by its SHA-256) into the artifact store, one artifact.Record per record that commits payloads. It reads the records from store and changes none of them: no header, record id, log entry or checkpoint moves, so every existing proof still holds. A record whose originals are already in the artifact store is skipped, so an interrupted migration is resumed by running it again. Retention is now per record, folded as Retention folds it: a record whose latest lifecycle state is DELETED is not stored, even when a file survived because another record shares the digest (the book reads it as DELETED before it looks for originals), and a payload an earlier per-payload deletion named is left out of a record that stays readable. A payload whose file is missing is left out of the record, so reading it reports the store does not hold it rather than claiming it was never kept. It returns how many records it stored.

The directory itself is left for the caller to remove once the call returns without error.

func ReconcileHalves

func ReconcileHalves(a, b HalfSet, compare Comparator) ([]PairResult, Tallies)

ReconcileHalves pairs two sides' halves and classifies every exchange seen on either side into exactly one of six states.

Correlation runs in two passes over all halves, so the result does not depend on input order: first exchange_id (preferring a counterpart whose request_digest also agrees), then request_digest for halves still unpaired. An agreeing exchange_id with disagreeing request digests is CONFLICTING and is never re-paired on the weaker key. twin_bracket_id is recorded when both halves carry the same value and is never a join key.

One half unavailable is not disagreement: an unpaired half is A_ONLY or B_ONLY when the other side's account is complete, INSUFFICIENT otherwise, and never CONFLICTING.

func ReconcileHalvesWith added in v0.5.0

func ReconcileHalvesWith(a, b HalfSet, check ContentCheck) ([]PairResult, Tallies)

ReconcileHalvesWith is ReconcileHalves with a three-way content check: on a covered, trusted, correlated pair, Agree is MATCHED, Disagree is CONFLICTING and Undecided is INSUFFICIENT. The precedence is unchanged: a key conflict, then an uncovered half (INSUFFICIENT), then an untrusted half (UNRESOLVED), then the content check.

func SamePayloadCommitments

func SamePayloadCommitments(a, b Half) bool

SamePayloadCommitments is a Comparator for deterministic content: the two halves committed identical payload digests. Content produced by sampling needs a comparator over the disclosed content instead.

func VerifyKeyRange

func VerifyKeyRange(root IndexRoot, lo, hi string, proof KeyRangeProof) ([]string, error)

VerifyKeyRange checks a range proof against a committed root and returns the record ids it proves are exactly the leaves with keys in [lo, hi].

func VerifyLeaf

func VerifyLeaf(root IndexRoot, proof LeafProof) error

VerifyLeaf checks one leaf proof against a committed root.

func VerifyOpening added in v0.5.0

func VerifyOpening(commitment string, o Opening) bool

VerifyOpening reports whether o opens commitment: its nonce is well formed and SHA-256(JCS({nonce, text})) equals commitment, compared as lowercase hex strings. It never errors; a malformed opening does not open anything.

Types

type A2AOptions added in v0.2.0

type A2AOptions struct {
	// Manifest is what the host states about its carriers; Bindings must
	// list BindingA2A. The Agent Card's extension params are
	// Book.Manifest(Manifest), byte for byte the manifest served elsewhere.
	Manifest ManifestOptions
	// Policy is the sharing policy every request is answered under, as for
	// RespondOptions.Policy.
	Policy SharePolicy
	// Name and URL are the Agent Card's name and the JSON-RPC endpoint the
	// host serves Handle at. Both are required.
	Name, URL string
	// Description is the Agent Card's description; empty is a fixed default.
	Description string
	// Version is the Agent Card's version; empty is "unversioned".
	Version string
}

A2AOptions configures the A2A carriage of a book's responder.

type A2ARequest added in v0.2.0

type A2ARequest struct {
	Version    string
	Extensions []string
	Body       []byte
}

A2ARequest is one JSON-RPC message received over A2A with the service parameters it arrived with (A2A §3.2.6): the A2A-Version value ("" when absent) and the A2A-Extensions URIs, which the host splits from their comma-separated header or metadata entry.

type A2AResponse added in v0.2.0

type A2AResponse struct {
	Body       []byte
	Extensions []string
}

A2AResponse is the JSON-RPC message to send back, and the extensions this carriage activated, to send as the response's A2A-Extensions. Body is nil for a notification.

type A2AServer added in v0.2.0

type A2AServer struct {
	// contains filtered or unexported fields
}

A2AServer carries the evidence request exchange over A2A (profile §11.4.4): the Agent Card extension entry, and SendMessage answered with a completed Task holding the reply in one Artifact. It is a carriage only. It moves the request and reply octets as opaque bytes and adds nothing to what Respond answers: the canonical Artifact is the one the native stream and MCP get for the same request (FR-8, ER §5).

It keeps no task. The Task is returned whole, completed, in the SendMessage response; no other client can list or fetch it (§11.4.3), and GetTask and CancelTask find nothing. Its identifiers are random, encoding no count and no time. It does not stream (capabilities.streaming false) and offers no push notifications and no extended Agent Card.

It is transport-neutral: the host owns the HTTP endpoint, the Agent Card URL and their authentication.

func (*A2AServer) AgentCard added in v0.2.0

func (s *A2AServer) AgentCard() []byte

AgentCard returns the Agent Card to serve at the host's well-known URL. It is the same for every caller (§11.4.2, §11.4.3): it carries the manifest as the extension's params and nothing about what the book holds. A host that adds security schemes adds them to this JSON.

func (*A2AServer) Handle added in v0.2.0

func (s *A2AServer) Handle(ctx context.Context, req A2ARequest, authenticated string) A2AResponse

Handle answers one JSON-RPC message received over A2A.

authenticated is the requester identity the host's transport established through the A2A security scheme it enforces, exactly as for RespondOptions.AuthenticatedRequester, or "" when the caller is not authenticated. It is the only identity Respond sees. Nothing inside the message is ever read as one: not the Agent Card the client presents or claims, not the Message or request metadata, messageId, contextId, tenant or extensions, not the JSON-RPC id. As in Respond, authentication decides whether a subject is answered, never what is answered (profile §11.4.1 rule 5).

Every reply, envelope or refusal, is a completed Task holding one Artifact with the extension URI and one raw Part of the request's media type (P-39). Anything that is not a request under §11.4.4 gets a JSON-RPC or A2A error, which is a transport condition and never a refusal.

type AbsenceRecord added in v0.2.0

type AbsenceRecord struct {
	Outcome       string        `json:"outcome"`
	RequestDigest string        `json:"request_digest"`
	Route         string        `json:"route,omitempty"`
	Window        AbsenceWindow `json:"window"`
	RecordedAt    string        `json:"recorded_at"`
}

AbsenceRecord is the requester's own record that neither an envelope nor a refusal arrived in its waiting window (ER §4.4, profile §6.4). It is the statement of a recorded_absence record, so the book's signature over the record attributes it to the requester; it carries no responder act.

type AbsenceWindow added in v0.2.0

type AbsenceWindow struct {
	Opened string `json:"opened"`
	Closed string `json:"closed"`
}

AbsenceWindow is when the request was transmitted and when the waiting window closed.

type Anchor added in v0.2.0

type Anchor = evidencerequest.Anchor

The reply types are the request draft's, defined in go/evidencerequest (ER §4.1, §4.2, profile §6.2, §6.3); these names keep evidencebook's API.

type AnsweredStatement

type AnsweredStatement struct {
	RequestDigest  string      `json:"request_digest"`
	SubjectKind    SubjectKind `json:"subject_kind,omitempty"`
	Outcome        string      `json:"outcome"`
	Reason         string      `json:"reason,omitempty"`
	Relationship   string      `json:"relationship"`
	Anchor         string      `json:"anchor,omitempty"`
	ArtifactDigest string      `json:"artifact_digest,omitempty"`
}

AnsweredStatement is the body of the record a responder seals for a request it answered for an authenticated requester. It names no requester, and records of this type are never served to anyone (they are not servable), so asking leaves no trace another requester can read.

type ArtifactStore added in v0.5.0

type ArtifactStore interface {
	Put(ctx context.Context, record artifact.Record) error
	Get(ctx context.Context, id string) (artifact.Record, error)
	// Purge erases a record's present originals and keeps their digests.
	Purge(ctx context.Context, id string) error
}

ArtifactStore is where a book keeps its records' originals: the payload bytes a header commits by digest. It is capsule-emit's artifact store contract (artifact.Store) reduced to what the book calls, so any of its backends (jsonl, sqlite, mysql) serves. The store holds one artifact.Record per record that has originals, keyed by the record id: the record capsule, its Producer Envelope, and the originals. The store must trust the book's signer, since Put and Get verify the envelope signer against the store's trusted keys.

The header commits digests, never storage locations, and the store's per-original ContentSHA256 is the same SHA-256 the header commits, so an original is found by the digest its record commits. Each record keeps its own copy: two records committing identical bytes hold two copies, and destroying one record's originals never touches the other's.

Put and Purge must be durable when they return: the book stores a record only after its originals' Put returns, so a record that survives a crash has originals that survived it too. OpenOriginalsFile's store syncs its file; a host supplying its own store makes the same guarantee.

func OpenOriginalsFile added in v0.5.0

func OpenOriginalsFile(ctx context.Context, path, namespace string, trusted ...ed25519.PublicKey) (ArtifactStore, error)

OpenOriginalsFile opens, creating it when absent, the reference ArtifactStore: capsule-emit's JSONL artifact store at path, under namespace, trusting the given keys (the book's signer key among them). It suits a single writer, as the book is. The file is kept owner-only, and every Put and Purge is synced to stable storage before it returns.

func SyncedFile added in v0.5.0

func SyncedFile(store ArtifactStore, path string) ArtifactStore

SyncedFile makes a file-backed ArtifactStore durable as the book requires: after each successful Put or Purge it syncs the file at path and the directory holding it.

type AuthenticatedIndex

type AuthenticatedIndex interface {
	Name() string
	// KeyOf returns the key a record contributes, or false for none.
	KeyOf(record Record) (string, bool)
	Add(key, recordID string) error
	Reset()
	Root() IndexRoot
	ProveMember(key, recordID string) (LeafProof, error)
	// ProveRange proves exactly which records carry a key in [lo, hi]; with
	// lo == hi it is a completeness proof for one key, and an empty result is
	// a non-membership proof.
	ProveRange(lo, hi string) (KeyRangeProof, error)
}

AuthenticatedIndex is a deterministic structure whose root the book commits as a record.

What a party that does not trust the book can check, and what it cannot: a membership proof shows a (key, record id) leaf is under the committed root, with no further trust. Non-membership, range and completeness proofs additionally rely on the committed tree being sorted and holding every record: a book that commits an unsorted or incomplete tree can prove a false absence or omit a match. Only a party holding the full leaf set (for example the book's full history) can audit that, by rebuilding the root. Those three claims are therefore statements by the book, checkable against its commitment but not against a dishonest book.

type Book

type Book struct {
	// contains filtered or unexported fields
}

Book is an evidence store: records, typed links, payload separation, three index classes and request/reconcile mechanics over an embedded commitment substrate. The substrate is never exposed; callers get records, bundles and answers, and the book composes every proof itself.

func Open

func Open(ctx context.Context, cfg Config) (*Book, error)

Open validates cfg, reconciles the record store with the substrate, and rebuilds every index from the committed history.

func (*Book) A2A added in v0.2.0

func (b *Book) A2A(opts A2AOptions) (*A2AServer, error)

A2A returns the A2A carriage of this book's responder.

func (*Book) Acknowledge

func (b *Book) Acknowledge(ctx context.Context, peerCloseID, counterparty string) (Record, error)

Acknowledge records that this book has seen and holds a counterparty's Close, which is what makes that Close AGREED from the counterparty's side.

func (*Book) Append

func (b *Book) Append(ctx context.Context, entry Entry) (Record, error)

Append validates entry, seals its header into a record capsule, stores the capsule and its payload bytes in the artifact store (one Put), stores the record, appends its identity to the substrate, and updates every index -- in that order. When the record is committed but a later step (indexing, an automatic checkpoint) fails, the committed record is returned together with the error: do not retry it.

func (*Book) AppendCapsule added in v0.5.0

func (b *Book) AppendCapsule(ctx context.Context, entry Entry, originals []artifact.Artifact, seal CapsuleSealer) (Record, error)

AppendCapsule commits a capsule its caller seals itself as the record: the capsule is the record, its id the log entry, with no wrapper record around it. The book takes the next position under its writer lock, builds the header (payload_commitments are the SHA-256 of each present original, in order; one declared never retained is stored as declared and not committed), and calls seal with it there; the capsule must carry that header in RecordHeaderMember and be signed by the book's signer, or nothing is written. The capsule, its envelope and originals are then stored in the artifact store in one Put, the record in the store, and its id appended to the substrate, as Append does.

entry.Payloads must be empty: a caller-sealed record's originals are named, and may be bound to the capsule's own digests (a payload bound to agent_input_digest, say), so they are passed as originals.

Crash contract: the position exists only in memory until the record is stored. A crash before that leaves no record, and the next record takes the same position; the artifact store may then hold the abandoned capsule, which no log entry names. A crash after it is the pending-tail case of Append: the next Open commits the stored record at its position.

func (*Book) Bundle

func (b *Book) Bundle(ctx context.Context, req BundleRequest) (Bundle, error)

Bundle resolves the root's citation closure, constructs the disclosure, asks the substrate for interval and membership evidence under one anchor, and returns a portable bundle. It then commits a disclosure record citing every record whose header or payload the bundle disclosed.

func (*Book) Checkpoint

func (b *Book) Checkpoint(ctx context.Context) (Checkpoint, error)

Checkpoint commits any changed authenticated-index roots as records, then checkpoints the commitment history underlying this book.

func (*Book) CheckpointAt added in v0.5.0

func (b *Book) CheckpointAt(ctx context.Context, at time.Time) (Checkpoint, error)

CheckpointAt is Checkpoint with the checkpoint's time given: a cadence cuts every log at the tick's time, coarsened to the minute, so no checkpoint says when within the minute its log grew.

func (*Book) Checkpoints

func (b *Book) Checkpoints(ctx context.Context) ([]Checkpoint, error)

Checkpoints returns every checkpoint this book has issued, oldest first.

func (*Book) Close

func (b *Book) Close(ctx context.Context, in CloseInput) (Record, error)

Close reconciles, then seals a Close record: a closes link to every own record the reconciliation placed, and the full state population in its statement. Its status is read later from the links other records make to it.

func (*Book) CommitRetention added in v0.2.0

func (b *Book) CommitRetention(ctx context.Context, subject Subject, until time.Time) (Record, error)

CommitRetention seals a retention commitment: a signed statement that subject stays answerable under this interaction until until (ER §9). The subject is a record, an exchange or a range: a digest or a position, never a correlation or the whole history (ERV A11). After until, a request for a subject the book no longer answers is refused retention_expired, never no_such_subject (ER §4.2 item 2).

func (*Book) Discover

func (b *Book) Discover(ctx context.Context, query string, limit int) (Candidates, error)

Discover returns approximate candidates. See Candidates for what that result may and may not be used for.

func (*Book) Get

func (b *Book) Get(_ context.Context, recordID string) (Record, error)

Get returns one record by id.

func (*Book) IndexState

func (b *Book) IndexState(ctx context.Context) (string, error)

IndexState is the operational index's current state digest.

func (*Book) Info

func (b *Book) Info() (string, SubstrateInfo)

Info names the book and the substrate it states it uses.

func (*Book) MCP added in v0.2.0

func (b *Book) MCP(opts MCPOptions) (*MCPServer, error)

MCP returns the MCP carriage of this book's responder.

func (*Book) Manifest added in v0.2.0

func (b *Book) Manifest(opts ManifestOptions) ([]byte, error)

Manifest returns the responder's manifest (ER §10, profile §11.4.2): a JSON object, in JCS, whose every value is a text string or a sorted array of text strings. It says what can be asked, never what exists: it carries no count, digest, anchor, time, principal, counterparty or history card (profile §11.4.3), and it is the same for every caller. The book's discovery index (Discover) is never part of it.

func (*Book) Opening added in v0.5.0

func (b *Book) Opening(ctx context.Context, recordID, field string) (Opening, error)

Opening returns the opening of one field commitment of a record, read from the artifact store, when the record's retention state allows it. It is checked against the commitment the record's header carries.

func (*Book) ProveKeyRange

func (b *Book) ProveKeyRange(ctx context.Context, index, lo, hi string) (KeyRangeAnswer, error)

ProveKeyRange proves exactly which records carry a key in [lo, hi] of the named authenticated index. It first commits the index's current root as a record and checkpoints, so the proof is always against a root the book has committed and a checkpoint covers — never a live root that has drifted from the last committed one. An empty result is a non-membership proof.

func (*Book) Query

func (b *Book) Query(ctx context.Context, filter Filter) ([]Record, error)

Query answers from the operational index. Its result is a local lookup, not a proof; use Bundle or Respond for anything a stranger must check.

func (*Book) Rebuild

func (b *Book) Rebuild(ctx context.Context) (string, error)

Rebuild re-derives the operational and discovery indexes from the committed history alone and returns the operational index's state digest.

func (*Book) Rebut

func (b *Book) Rebut(ctx context.Context, peerCloseID, counterparty string, reason json.RawMessage) (Record, error)

Rebut records that this book disputes a counterparty's Close.

func (*Book) Reconcile

func (b *Book) Reconcile(ctx context.Context, in ReconcileInput) (Reconciliation, error)

Reconcile compares this book's halves in its window with the halves a peer disclosed in a verified bundle.

func (*Book) RecordAbsence

func (b *Book) RecordAbsence(ctx context.Context, requestRecordID string, windowEnd time.Time, route string) (Record, error)

RecordAbsence commits that no reply arrived for the recorded request between its recording and windowEnd. The request digest, its deadline and the window's opening come from the committed request record, and so does the route when the request named one: a different route is refused. When the request named none, route is the route the binding attempted, if any. It refuses while the request is still pending (window not closed, or closing before the request's own deadline) and once any reply has been recorded, so an outcome is never converted into another. The record's statement is the profile's absence record (AbsenceRecord), in JCS.

func (*Book) RecordResponse

func (b *Book) RecordResponse(ctx context.Context, requestRecordID string, reply Message, keys ResponderKeys) (Record, error)

RecordResponse verifies and records the reply that came back for the request recorded as requestRecordID, keeping the reply's octets as the response record's payload (ReplyOctets reads them back). Both responder keys are required. A reply that is not signed under the pinned signer key for this request's digest is refused and is not recorded: an unauthenticated message can neither become an outcome nor foreclose the real one. A reply genuinely signed by the responder that fails a check of profile §7.2 is recorded as received-and-failed, never as a grant and never as an absence.

func (*Book) RegisterDerivation added in v0.2.0

func (b *Book) RegisterDerivation(def DerivationDefinition) (string, error)

RegisterDerivation makes a derivation answerable by its identifier, which it returns. The registration is held in memory: a host registers its definitions each time it opens the book, and they are never written into the book's history, because a recipient-specific definition names its recipient.

func (*Book) Release

func (b *Book) Release() error

Release closes the store, substrate and operational index. It is idempotent, and afterwards every write (Append, AppendCapsule, Checkpoint, SetRetention) refuses with ErrReleased.

func (*Book) ReplyOctets added in v0.5.0

func (b *Book) ReplyOctets(ctx context.Context, responseRecordID string) ([]byte, error)

ReplyOctets returns the reply a response record observed, as received, from the artifact store. It is the response record's one payload.

func (*Book) Request

func (b *Book) Request(ctx context.Context, req EvidenceRequest, responder string) (SentRequest, error)

Request records that this book is asking responder for evidence and returns the octets to transmit: the request map under this profile (its profile member set to ProfileID), in JCS (profile §6.1, P-9). An empty nonce is filled with a fresh random one, and a nonce this book already used is refused. Recording happens before sending, so "I asked" is committed whatever comes back.

func (*Book) ResolvePayload

func (b *Book) ResolvePayload(ctx context.Context, recordID, digest string) ([]byte, error)

ResolvePayload returns one payload of one record, read from the artifact store, when the record's retention state allows it.

func (*Book) Respond

func (b *Book) Respond(ctx context.Context, request Message, opts RespondOptions) (Reply, Record, error)

Respond answers one request, received as request (octets and media type), with a signed envelope carrying the canonical Artifact or a signed refusal with exactly one registered reason, encoded in the request's encoding (profile §6, §11.4.1 rule 3). The artifact is a deterministic function of (subject, resolved anchor, derivation) only: the requester, nonce, route, profile member and encoding never change its bytes (ER §5, FR-8).

For an authenticated requester whose request was well formed, Respond seals an evidence_request_answered record and returns it; otherwise the returned Record is zero. Malformed and unauthenticated traffic never grows the log and never forces a checkpoint (FR-37).

func (*Book) Retention

func (b *Book) Retention(_ context.Context, recordID string) (RetentionState, error)

Retention returns the record's current retention state (Evidence Layer §6.1): the state its header committed, folded forward through every lifecycle record that cites it, in log order. While a retention commitment this book issued covers the record and has not expired (CommitRetention), an AVAILABLE or PARTIAL record reads as LEGAL_HOLD: the hold blocks deletion and changes no resolvability. A WITHHELD record stays WITHHELD under a hold, which still blocks its deletion. A record that commits no payload and no field has no retention state and is refused.

func (*Book) SetRetention

func (b *Book) SetRetention(ctx context.Context, recordID string, state RetentionState, reason string) (Record, error)

SetRetention appends a lifecycle record moving recordID to state. DELETED is permanent and is refused while the record is held: under LEGAL_HOLD set by a lifecycle record, or covered by a live retention commitment. Deleting purges the record's originals from the artifact store after the lifecycle record is committed; the record's own commitments, and every other record's originals, are untouched. Asking for DELETED again on a deleted record retries a failed purge and returns the existing lifecycle record.

func (*Book) Size

func (b *Book) Size() uint64

Size is the number of committed records.

type Bundle

type Bundle struct {
	JSON       []byte
	Digest     string
	Anchor     Checkpoint
	Disclosure Record
}

Bundle is a portable, self-verifying Evidence Bundle v2 plus the disclosure record the book committed about it.

type BundleCheckpoint

type BundleCheckpoint struct {
	LogID   string `json:"log_id,omitempty"`
	Root    string `json:"root"`
	MMRSize uint64 `json:"mmr_size"`
	COSE    string `json:"cose,omitempty"`
}

BundleCheckpoint is the checkpoint member of an Evidence Bundle. COSE is the base64url signed checkpoint statement, so a verifier authenticates the root rather than trusting the producer's copy of it. LogID is the log id the statement signs, as the completeness certificate states it; a bundle from before it was stated has none.

type BundleClaims

type BundleClaims struct {
	GraphClosure        string
	IntervalCoverage    string
	PerRecordMembership string
}

BundleClaims is the status of each Evidence Bundle verifier claim.

type BundleRequest

type BundleRequest struct {
	Root string
	// Include adds records to the selected set beyond the root's closure.
	Include []string
	// ClosureDepth is how many link hops to follow from Root; zero selects
	// DefaultClosureDepth.
	ClosureDepth int
	// Payloads is the disclosure claim for the selected set: all carries
	// every payload of every selected record (refused if any is unavailable),
	// selected carries those not withheld.
	Payloads PayloadsMode
	// WithholdPayloads carries headers only: every payload of the selected
	// set is withheld with its digest.
	WithholdPayloads bool
	// Suppress names disclosure members left out of the overlay; suppressing
	// HeaderMember leaves every disclosed header as withheld-with-digest. A
	// header carried inside its capsule (RecordHeaderMember) is part of the
	// capsule's committed bytes, so it travels whatever Suppress says. For
	// such a record, suppressing agent_input or agent_output also withholds
	// the original bound to it (unless another, unsuppressed member is bound
	// to the same bytes).
	Suppress []string
	// Withhold names payload digests this disclosure does not carry.
	Withhold []string
	// At pins the coverage anchor; nil checkpoints the book now.
	At *Checkpoint
	// Extensions are further extension blocks, by kind. producer-key/v1
	// is set through ProducerKey and composed/v1 is agent-action-capsule's
	// own, so both are refused here.
	Extensions map[string]json.RawMessage
	// ProducerKey, a raw 32-byte Ed25519 public key, declares the bundle's
	// producer key (the producer-key/v1 extension).
	ProducerKey ed25519.PublicKey
}

BundleRequest selects what a bundle carries and how much it discloses.

type CLLSubstrate

type CLLSubstrate struct {
	// contains filtered or unexported fields
}

CLLSubstrate embeds a Checkpointed Local Log. It is the only place this module touches CLL; everything it returns is an evidencebook type.

func OpenCLL

func OpenCLL(path, logID string, checkpointKey ed25519.PrivateKey) (*CLLSubstrate, error)

OpenCLL opens (initializing if absent) a CLL journal at path. checkpointKey signs the log's checkpoints in the CLL checkpoint wire format; it is the substrate's key, held by the substrate, and may differ from the book signer.

func OpenCLLSQLite added in v0.5.0

func OpenCLLSQLite(path, logID string, checkpointKey ed25519.PrivateKey) (*CLLSubstrate, error)

OpenCLLSQLite opens (initializing if absent) the CLL log logID in the SQLite file at path. One file holds many logs, one per log id, as a profile's per-deal logs are held today (capsule-cli deal.db).

func (*CLLSubstrate) Append

func (s *CLLSubstrate) Append(ctx context.Context, recordID string, at time.Time) (uint64, error)

func (*CLLSubstrate) Checkpoint

func (s *CLLSubstrate) Checkpoint(ctx context.Context, now time.Time) (Checkpoint, error)

func (*CLLSubstrate) Entries

func (s *CLLSubstrate) Entries(ctx context.Context, afterSeq uint64, limit int) ([]SubstrateEntry, error)

func (*CLLSubstrate) Info

func (s *CLLSubstrate) Info() SubstrateInfo

func (*CLLSubstrate) Latest

func (s *CLLSubstrate) Latest(ctx context.Context) (Checkpoint, error)

func (*CLLSubstrate) ProveConsistency

func (s *CLLSubstrate) ProveConsistency(ctx context.Context, older, newer Checkpoint) (ConsistencyEvidence, error)

func (*CLLSubstrate) ProveInclusion

func (s *CLLSubstrate) ProveInclusion(ctx context.Context, seq uint64, at Checkpoint) (InclusionEvidence, error)

func (*CLLSubstrate) ProveInterval

func (s *CLLSubstrate) ProveInterval(ctx context.Context, firstSeq uint64, at Checkpoint) (IntervalEvidence, error)

func (*CLLSubstrate) Release

func (s *CLLSubstrate) Release() error

func (*CLLSubstrate) Size

func (s *CLLSubstrate) Size(ctx context.Context) (uint64, error)

type Cadence added in v0.5.0

type Cadence struct {
	// contains filtered or unexported fields
}

Cadence runs a shelf's heartbeat ticks.

func (*Cadence) Chain added in v0.5.0

func (c *Cadence) Chain(ctx context.Context, statement []byte) (map[string]any, error)

Chain is the witnessed cadence chain for a log's checkpoint (its COSE statement): capsule-cli's cadenceChain, member for member, so its released verifier (deal_cadence_verify.go) checks it unchanged.

  • "all": a witnessed tick carries this very checkpoint;
  • "part": the newest witnessed tick carrying an earlier checkpoint of the log, plus that checkpoint and a consistency proof from it to this one ("earlier").

The leaf's salt, position and the tick's path; the cadence log's checkpoint, the tick's entry index and its inclusion proof; and the witness receipt the host reported. A profile adds its own members (a deal's "steps_witnessed" and "steps"). ErrNotFound when no witnessed tick carries the log up to this checkpoint: the host then says "pending" or "scheduled" from its own witness state.

func (*Cadence) Get added in v0.5.0

func (c *Cadence) Get(ctx context.Context, n uint64) (CadenceTick, error)

Get returns stored tick n.

func (*Cadence) ImportLegacy added in v0.6.0

func (c *Cadence) ImportLegacy(ctx context.Context, legacy LegacyCadence) error

ImportLegacy carries a pre-shelf cadence into this one, in one transaction, under the shelf's lock:

  • every log in legacy.Logs is registered: it counts into H;
  • each tick not already held is stored, numbered after the cadence's last tick, with its due time, leaves, checkpoint and receipt, so the cadence continues from it and Chain rebuilds a bundle anchored on it;
  • each witnessed tick's leaves get cadence_witnessed rows;
  • each registered log is live unless it has ended and has not grown past its largest witnessed checkpoint (the #36 rule).

It is re-runnable: a tick already held (the same cadence-log position and checkpoint) keeps its number and content, and is only promoted to witnessed when it now carries a receipt it did not (a pre-shelf writer delivered it since); a later run imports only ticks a pre-shelf writer added since, after the cadence's own. A tick at a held position with another checkpoint, or older than the newest tick held, is refused: it would rewrite what bundles may already name. So is any import while the cadence's own last tick is unfinished (a crash after its row): Tick resumes only the last tick, so a later tick would strand it; the host ticks first, which finishes it. Ended is evaluated before the transaction, as for Witnessed, and must not call the shelf.

func (*Cadence) Last added in v0.6.0

func (c *Cadence) Last(ctx context.Context) (tick CadenceTick, ok bool, err error)

Last returns the cadence's newest stored tick; ok is false when it has none. A host reads a log's pending standing from it (the newest tick holding the log, capsule-cli#242 §2.5) and maps a delivered cadence checkpoint back to its tick, walking back with Get.

func (*Cadence) Live added in v0.5.0

func (c *Cadence) Live(ctx context.Context) ([]string, error)

Live lists the live set, in log id order.

func (*Cadence) Tick added in v0.5.0

func (c *Cadence) Tick(ctx context.Context, now time.Time) (TickResult, error)

Tick cuts a tick when one is due at now; otherwise it reports when one is. A tick is due when now is at or after the last tick's DueNext, and only then: its timing and size never depend on what the logs did.

func (*Cadence) Witnessed added in v0.5.0

func (c *Cadence) Witnessed(ctx context.Context, n uint64, receipt WitnessReceipt) error

Witnessed records that tick n's cadence checkpoint has a verified witness receipt. In one transaction, under the shelf's lock: each log checkpoint the tick carries gets a cadence_witnessed row, and each of those logs that has ended and has not grown past its largest witnessed checkpoint leaves the live set. Each log compares its own size, so a receipt for an older tick reported late never moves a log back.

func (*Cadence) WitnessedTick added in v0.5.0

func (c *Cadence) WitnessedTick(ctx context.Context, logID, checkpointSHA256 string, mmrSize uint64) (extent string, tick CadenceTick, leaf TickLeaf, err error)

WitnessedTick finds the witnessed tick a bundle of logID's checkpoint (its statement's SHA-256 and MMR size) is anchored by, from the index: "all" when a witnessed tick carries that very checkpoint, else "part" with the newest witnessed tick carrying an earlier checkpoint of the log (a bundle then adds a consistency proof from it). ErrNotFound when no witnessed tick carries any checkpoint of the log up to that size.

type CadenceConfig added in v0.5.0

type CadenceConfig struct {
	// LogID is the profile's cadence log, in the shelf's file
	// ("deal-cadence/<16hex>" for a deal profile).
	LogID string
	// Interval is at least 1m; Jitter is under half of it. Zero values take
	// the defaults (5m, 1m), unless NoJitter says the jitter is zero.
	Interval, Jitter time.Duration
	// NoJitter makes every tick due exactly Interval after the last (a
	// profile configured with no jitter).
	NoJitter bool
	// WitnessIDs are the witnesses each cadence checkpoint is queued for:
	// the checkpoint and a pending delivery to each are one commit of the
	// cadence log, as capsule-cli's checkpoint runner does. The host
	// delivers them (cll's PendingWitnesses on the cadence log) and reports
	// a verified receipt with Witnessed. None queues nothing.
	WitnessIDs []string
	// PadBucket pads the cadence log to a multiple of this many entries per
	// tick, at most 1024; zero is 1 (no padding).
	PadBucket uint64
	// Ended is the profile's predicate: whether a log has ended (for a
	// deal, a close step is sealed). It is evaluated each time it is
	// needed, never stored.
	Ended func(ctx context.Context, logID string) (bool, error)
}

CadenceConfig is a shelf's cadence. The defaults and limits are capsule-cli's: a tick every 5m, give or take 1m (288 a day).

type CadenceLog added in v0.5.0

type CadenceLog interface {
	LogID() string
	// MMRSize is the MMR node count of everything the log holds.
	MMRSize(ctx context.Context) (uint64, error)
	// CutLocal checkpoints everything the log holds at at, cutting a new
	// checkpoint only if the log grew, and returns the checkpoint's COSE
	// statement and MMR size. Nothing is sent to a witness.
	CutLocal(ctx context.Context, at time.Time) (statement []byte, mmrSize uint64, err error)
	// contains filtered or unexported methods
}

CadenceLog is what a tick checkpoints: a book, or a deal's log from before the upgrade (LegacyLog).

type CadenceTick added in v0.5.0

type CadenceTick struct {
	N        uint64
	At       time.Time
	DueNext  time.Time
	EntrySeq uint64
	// CheckpointSize and Checkpoint are the cadence log's checkpoint (MMR
	// size and COSE statement) that carries this tick's root.
	CheckpointSize uint64
	Checkpoint     []byte
	Leaves         TickLeaves
	// Witnessed is set once the host reported the checkpoint's receipt
	// verified (Witnessed), and Receipt is that receipt.
	Witnessed bool
	Receipt   *WitnessReceipt
}

CadenceTick is one tick as stored: capsule-cli's deal_cadence row.

type Candidates

type Candidates struct {
	// contains filtered or unexported fields
}

Candidates is the only result type a DiscoveryIndex returns. It is a list of places to look, never a statement about what exists or what is true: no function in this package that produces a proof, a bundle, or an answer to a request accepts it (enforced by TestDiscoveryCandidatesNeverReachProofs). To act on a candidate, fetch it by id through the book.

func (Candidates) IDs

func (c Candidates) IDs() []string

IDs returns candidate record ids, best match first.

func (Candidates) Query

func (c Candidates) Query() string

Query returns the text that produced these candidates.

type CapsuleSealer added in v0.5.0

type CapsuleSealer func(header Header, headerJSON []byte) (emit.Result, error)

CapsuleSealer seals a caller's own capsule as a record, under the book's writer lock (AppendCapsule). header is the record's header with its position and commit time assigned, and headerJSON its canonical bytes; the capsule must carry headerJSON as its RecordHeaderMember member and be signed by the book's signer. It returns the sealed capsule and its Producer Envelope. The book's lock is held while it runs and is not reentrant: the sealer must not call back into the Book.

type Checkpoint

type Checkpoint struct {
	Kind      string    `json:"kind"`
	LogID     string    `json:"log_id"`
	ID        string    `json:"id"`
	Entries   uint64    `json:"entries"`
	Root      string    `json:"root,omitempty"`
	TreeSize  uint64    `json:"tree_size,omitempty"`
	KeyID     string    `json:"key_id,omitempty"`
	IssuedAt  time.Time `json:"issued_at"`
	Statement []byte    `json:"statement,omitempty"`
}

Checkpoint names one committed state. ID is independent of which party serves the checkpoint: for the CLL binding it is "<root-hex>:<mmr_size>".

func VerifyCheckpoints

func VerifyCheckpoints(checkpoints []Checkpoint, consistency []ConsistencyEvidence, pinnedKey string) (Checkpoint, error)

VerifyCheckpoints checks a checkpoints/v1 history and returns its newest checkpoint as the signed statement states it. Every field is taken from the signed statement, never from the listed copy: each statement must verify, sign under pinnedKey, name the same log as the first, and match its listed fields exactly; sizes must strictly grow; and each consistency proof must show the next signed root append-only extends the previous one.

func (Checkpoint) Covers

func (c Checkpoint) Covers(seq uint64) bool

Covers reports whether seq is committed under this checkpoint.

type CloseInput

type CloseInput struct {
	Reconcile    ReconcileInput
	Counterparty string
	// Profile names the contract or profile version whose comparator and
	// windows produced the reconciliation.
	Profile    string
	Supersedes string
	Reason     string
}

CloseInput states what a Close binds. The book computes the reconciliation itself from Reconcile; a caller never supplies tallies. Supersedes names a prior Close this one adjusts; the prior Close is never rewritten.

type CloseStatement

type CloseStatement struct {
	Counterparty   string         `json:"counterparty"`
	Profile        string         `json:"profile"`
	Reconciliation Reconciliation `json:"reconciliation"`
	Reason         string         `json:"reason,omitempty"`
}

CloseStatement is the body of a Close record.

type CloseStatus

type CloseStatus string

CloseStatus is read from links, never from a field the Close sets.

const (
	Agreed     CloseStatus = "AGREED"
	Unilateral CloseStatus = "UNILATERAL"
	Contested  CloseStatus = "CONTESTED"
)

func StatusOfClose

func StatusOfClose(closeID, counterpartyBookID, counterpartyCheckpointKey string, counterparty VerifiedBundle) (CloseStatus, error)

StatusOfClose derives a Close's status from the counterparty's own records: a rebuts link makes it CONTESTED, an acknowledges link AGREED, and neither leaves it UNILATERAL. Only records that verified, carry the counterparty's book id, and sit under a checkpoint signed by the key the caller pinned for that counterparty count; a bundle from anyone else says nothing about the Close.

type Comparator

type Comparator func(a, b Half) bool

Comparator is the content test a declared profile supplies. It runs only on covered, trusted, correlated pairs and returns whether the contents agree.

func (Comparator) Check added in v0.5.0

func (c Comparator) Check() ContentCheck

Check lifts a Comparator to a ContentCheck: true agrees, false disagrees.

type CompletenessCertificate

type CompletenessCertificate struct {
	LogID       string                `json:"log_id"`
	RangeRoot   string                `json:"range_root"`
	FirstSeq    uint64                `json:"first_seq"`
	LastSeq     uint64                `json:"last_seq"`
	BodyDigests []string              `json:"body_digests"`
	RangeProof  RangeWitness          `json:"range_proof"`
	Memberships map[string]Membership `json:"memberships"`
}

CompletenessCertificate is the Evidence Bundle v2 per-record range claim.

type Config

type Config struct {
	BookID    string
	Operator  string
	Developer string

	Store     Store
	Substrate Substrate
	// Originals is the artifact store that holds every record's payload
	// bytes (ArtifactStore). It must trust Signer's key.
	Originals ArtifactStore
	Signer    Signer

	Operational   OperationalIndex
	Authenticated []AuthenticatedIndex
	Discovery     DiscoveryIndex

	// CheckpointEvery checkpoints after every N appends; zero checkpoints
	// only when Checkpoint is called or an answer requires it.
	CheckpointEvery uint64
	Now             func() time.Time

	// Responder is the responder's cost and abuse policy for Respond
	// (FR-37). The zero value answers the most specific reason with no rate
	// limit.
	Responder ResponderPolicy
}

Config assembles a book. Store, Substrate, Originals and Signer are required; every index defaults to the reference implementation.

type ConsistencyEvidence

type ConsistencyEvidence struct {
	Kind  string          `json:"kind"`
	Proof json.RawMessage `json:"proof"`
}

ConsistencyEvidence proves newer append-only extends older.

type ContentCheck added in v0.5.0

type ContentCheck func(a, b Half) ContentVerdict

ContentCheck is a three-way content test: like a Comparator, but it can say the content needed is not there.

func OpenedFieldsAgree added in v0.5.0

func OpenedFieldsAgree(required ...string) ContentCheck

OpenedFieldsAgree compares the required fields' opened texts. Each record commits with its own fresh nonce, so two halves of the same text carry different commitments and only both openings can show agreement: a required field not opened on either half is Undecided; otherwise equal texts on every required field Agree, and any difference Disagrees. With no required field there is nothing to compare, so every pair is Undecided (INSUFFICIENT): name the fields the profile compares.

type ContentVerdict added in v0.5.0

type ContentVerdict int

ContentVerdict is what a content check concludes about a covered, trusted, correlated pair.

const (
	// Undecided: the content needed to compare is not available
	// (INSUFFICIENT), for example an unopened field commitment. Missing
	// content is never disagreement. It is the zero value, so a check that
	// returns nothing decided never reports a match.
	Undecided ContentVerdict = iota
	// Agree: the contents agree (MATCHED).
	Agree
	// Disagree: the contents were compared and differ (CONFLICTING).
	Disagree
)

type Correlation

type Correlation struct {
	ExchangeID    string `json:"exchange_id,omitempty"`
	RequestDigest string `json:"request_digest,omitempty"`
	TwinBracketID string `json:"twin_bracket_id,omitempty"`
}

Correlation carries the exchange correlation keys used to pair two halves of one interaction across independently held books. Join order is ExchangeID, then RequestDigest; TwinBracketID is recorded, never joined on.

type Coverage

type Coverage = evidencerequest.Coverage

type CoverageGiven added in v0.6.0

type CoverageGiven struct {
	Period      ResultPeriod      `json:"period"`
	Declaration map[string]any    `json:"declaration"`
	Properties  map[string]string `json:"properties"`
}

CoverageGiven is a coverage declaration given for one book, with the period it is given for and the verifier's report of its coverage properties (IP §6.7.2), by property name.

type DealHalf added in v0.6.0

type DealHalf struct {
	Book   string
	Octets []byte
}

DealHalf is one half as the reconcile is given it: its octets as held and the book it comes from.

type DealReconcile added in v0.6.0

type DealReconcile struct {
	// FieldOpenings is each carried opening's status, PASS or FAIL, by half
	// digest and field, for the halves in the reconcile.
	FieldOpenings   map[string]map[string]string        `json:"field_openings"`
	SetCompleteness map[string]SetCompleteness          `json:"set_completeness"`
	Pairings        map[string]map[string]ExchangeState `json:"pairings"`
	Tallies         map[string]ResultTallies            `json:"tallies"`
	Sufficiency     map[string]string                   `json:"sufficiency"`
	Verdict         map[string]string                   `json:"verdict"`
	// DealState is DR §7.5's optional per-deal state; a caller may leave it
	// unshown.
	DealState map[string]string   `json:"deal_state"`
	Result    DealReconcileResult `json:"result"`
}

DealReconcile is the recompute's full outcome: every intermediate DR names, by requirement id where it is per requirement.

func RecomputeDealReconcile added in v0.6.0

func RecomputeDealReconcile(in DealReconcileInput) (DealReconcile, error)

RecomputeDealReconcile recomputes a reconcile under ec:deal-reconcile@1.

It reads each half only after its own format's checks have passed (DR §4.1, last paragraph): the caller verifies each half's signature, that it comes from the book it is given with, and that it is covered, and admits only halves that pass. This function checks the contract's structure only and treats every half it is given as admitted.

A malformed input, or a half malformed by DR §4.2, refuses the reconcile with ErrInvalid and no Result. Every half given is read through its book's mapping before the period and the two books scope it, so a malformed half refuses the reconcile even when it would be left out.

type DealReconcileInput added in v0.6.0

type DealReconcileInput struct {
	// SideA is the book that produces the Result; Peer is side B.
	SideA, Peer string
	Period      ResultPeriod
	// HalfMappings is each book's half mapping, by book id.
	HalfMappings map[string]HalfMapping
	Halves       []DealHalf
	// FieldOpenings are by half digest, then by field name (DR §5).
	FieldOpenings map[string]map[string]Opening
	// Coverage is the coverage given for a book, by book id; a book with
	// none given is NOT_SHOWN.
	Coverage map[string]CoverageGiven
	// GeneratedAt is the Result's generated_at.
	GeneratedAt string
}

DealReconcileInput is everything a reconcile under the contract reads.

type DealReconcileResult added in v0.6.0

type DealReconcileResult struct {
	ResultVersion string           `json:"result_version"`
	GeneratedAt   string           `json:"generated_at"`
	Claims        []ReconcileClaim `json:"claims"`
	Aggregate     ResultAggregate  `json:"aggregate"`
}

DealReconcileResult is an Evidence Result v0 holding the two claims.

type DerivationDefinition added in v0.2.0

type DerivationDefinition struct {
	// Document is the definition document, a JSON object. The derivation's
	// identifier is SHA-256 over UTF-8 of its JCS. The profile does not fix
	// its member names (P-14); this package reads none of them, and the
	// holder states what it declares in the fields below as well.
	Document []byte
	// Recipient is the authenticated requester the projection is prepared
	// for, as the definition names it. Only that requester is answered. An
	// empty Recipient makes the derivation answerable under the share policy
	// like any protected subject.
	Recipient string
	// Forms are the subject forms the derivation is defined over; any other
	// form is answered no_such_subject (ER §3.3).
	Forms []SubjectKind
	// Fields is the declared field set: the record header members the
	// projection reveals, and nothing else (ER §8).
	Fields []string
}

DerivationDefinition is a derivation this responder serves by the digest of its definition (ER §3.3). A recipient-specific disclosure is exactly such a derivation (profile §6.5, ruling 5): a new identity, never a variant of the canonical Artifact of the underived subject.

type DisclosureStatement

type DisclosureStatement struct {
	BundleDigest     string         `json:"bundle_digest"`
	Anchor           string         `json:"anchor"`
	Payloads         PayloadsMode   `json:"payloads"`
	SuppressedFields []string       `json:"suppressed_fields"`
	Withheld         []WithheldItem `json:"withheld"`
}

DisclosureStatement is the body of a disclosure record (Evidence Layer §6.2).

type DiscoveryIndex

type DiscoveryIndex interface {
	Add(ctx context.Context, record Record) error
	Search(ctx context.Context, query string, limit int) (Candidates, error)
	Rebuild(ctx context.Context, source RecordSource) error
}

DiscoveryIndex finds candidate records by approximate match. It is always rebuildable and is never proof of completeness or of truth.

type Ed25519Signer

type Ed25519Signer struct {
	// contains filtered or unexported fields
}

Ed25519Signer is the reference in-process Signer.

func NewEd25519Signer

func NewEd25519Signer(private ed25519.PrivateKey) (*Ed25519Signer, error)

NewEd25519Signer copies private so later mutation by the caller has no effect.

func (*Ed25519Signer) PublicKey

func (s *Ed25519Signer) PublicKey() ed25519.PublicKey

PublicKey returns a copy of the verifying key.

func (*Ed25519Signer) Sign

func (s *Ed25519Signer) Sign(ctx context.Context, message []byte) ([]byte, error)

Sign returns the Ed25519 signature over message.

type Entry

type Entry struct {
	RecordType     string
	EpistemicType  EpistemicType
	EventTimeClaim time.Time
	Payloads       [][]byte
	// Fields are texts committed with a fresh nonce each (CommitAlgNonce256),
	// by field name: the header carries the commitments, the artifact store
	// the openings.
	Fields          map[string]string
	Links           []Link
	SubjectRef      string
	PrincipalRef    string
	CounterpartyRef string
	Correlation     Correlation
	Statement       json.RawMessage
}

Entry is what a caller asks the book to record. Seq, CommittedAt, BookID and the record identity are assigned by the book.

type Envelope added in v0.2.0

type Envelope = evidencerequest.Envelope

The reply types are the request draft's, defined in go/evidencerequest (ER §4.1, §4.2, profile §6.2, §6.3); these names keep evidencebook's API.

type EpistemicType

type EpistemicType string

EpistemicType states how a record's content came to be known. It is a closed set (Evidence Layer §4.1), assigned once at commit and never upgraded by anything attached to the record later.

const (
	ObservedEvent       EpistemicType = "observed_event"
	SystemOfRecordFact  EpistemicType = "system_of_record_fact"
	ProducerClaim       EpistemicType = "producer_claim"
	HumanReport         EpistemicType = "human_report"
	SemanticJudgment    EpistemicType = "semantic_judgment"
	DerivedMetric       EpistemicType = "derived_metric"
	Adjudication        EpistemicType = "adjudication"
	ObligationReference EpistemicType = "obligation_reference"
)

func EpistemicTypes

func EpistemicTypes() []EpistemicType

EpistemicTypes returns the closed value set in registry order.

func (EpistemicType) Valid

func (t EpistemicType) Valid() bool

Valid reports whether t is one of the eight registered values.

type EvidenceRef added in v0.6.0

type EvidenceRef struct {
	Digest    string `json:"digest"`
	DigestAlg string `json:"digest_alg"`
}

EvidenceRef is evidence by digest only (RES §5).

type EvidenceRequest

type EvidenceRequest = evidencerequest.Request

type ExchangeState

type ExchangeState string

ExchangeState is the per-exchange reconciliation state.

const (
	Matched      ExchangeState = "MATCHED"
	AOnly        ExchangeState = "A_ONLY"
	BOnly        ExchangeState = "B_ONLY"
	Conflicting  ExchangeState = "CONFLICTING"
	Insufficient ExchangeState = "INSUFFICIENT"
	Unresolved   ExchangeState = "UNRESOLVED"
)

type FileStore

type FileStore struct {
	// contains filtered or unexported fields
}

FileStore is an append-only JSONL record journal plus a checkpoint journal.

func OpenFileStore

func OpenFileStore(dir string) (*FileStore, error)

OpenFileStore opens (creating if absent) a store in dir. A torn final line left by a crash is truncated; a malformed complete line is corruption.

func (*FileStore) Checkpoints

func (s *FileStore) Checkpoints(context.Context) ([]Checkpoint, error)

func (*FileStore) GetRecord

func (s *FileStore) GetRecord(_ context.Context, recordID string) (StoredRecord, error)

func (*FileStore) PutCheckpoint

func (s *FileStore) PutCheckpoint(ctx context.Context, cp Checkpoint) error

func (*FileStore) PutRecord

func (s *FileStore) PutRecord(ctx context.Context, record StoredRecord) error

func (*FileStore) Records

func (s *FileStore) Records(context.Context) ([]StoredRecord, error)

func (*FileStore) Release

func (s *FileStore) Release() error

type Filter

type Filter struct {
	RecordType      string
	SubjectRef      string
	CounterpartyRef string
	ExchangeID      string
	RequestDigest   string
	LinkType        LinkType
	LinkTarget      string
	FromSeq         uint64
	ToSeq           uint64
}

Filter selects records from the operational index. Zero-valued fields do not constrain the result.

type Freshness

type Freshness = evidencerequest.Freshness

type Half

type Half struct {
	RecordID           string
	Seq                uint64
	Correlation        Correlation
	PayloadCommitments []string
	// FieldCommitments are the record's salted field commitments, by name.
	FieldCommitments map[string]string
	// Opened holds the texts of the fields whose openings verified against
	// this half's own commitments (OpenHalf).
	Opened  map[string]string
	Covered bool
	Trusted bool
}

Half is one side's record of one exchange as the reconciliation sees it. Covered means inside an authenticated checkpoint; Trusted means the record verifies and its header matches what it committed.

func OpenHalf added in v0.5.0

func OpenHalf(h Half, openings map[string]Opening) Half

OpenHalf checks each opening given for h against h's own field commitments. One that opens records its text in Opened; one that does not (a wrong nonce, a changed text, a field h does not commit) makes h untrusted, so its pair is UNRESOLVED whatever else holds. A missing opening changes nothing here: OpenedFieldsAgree reads it as Undecided.

type HalfMapping added in v0.6.0

type HalfMapping struct {
	Profile string            `json:"profile"`
	Members map[string]string `json:"members"`
}

HalfMapping is a profile's declared mapping onto the abstract members (DR §4.2): each member is a JSON Pointer (RFC 6901) into the half.

type HalfSet

type HalfSet struct {
	Halves   []Half
	Complete bool
}

HalfSet is one side's account of a period. Complete means that account is checkpoint-covered, so a missing counterpart on this side is a provable absence rather than an unknown.

type Header struct {
	Version            int           `json:"v"`
	BookID             string        `json:"book_id"`
	Seq                uint64        `json:"seq"`
	RecordType         string        `json:"record_type"`
	EpistemicType      EpistemicType `json:"epistemic_type"`
	CommittedAt        string        `json:"committed_at"`
	EventTimeClaim     string        `json:"event_time_claim,omitempty"`
	PayloadCommitments []string      `json:"payload_commitments,omitempty"`
	// FieldCommitments are the record's salted per-field commitments, by
	// field name, under CommitAlg (CommitAlgNonce256). Their openings are
	// originals in the artifact store, never in the record. Presentation
	// contract §7.2 records carry the same values as `<name>_commitment`
	// members; here they are one map, and the values are identical.
	FieldCommitments map[string]string `json:"field_commitments,omitempty"`
	CommitAlg        string            `json:"commit_alg,omitempty"`
	RetentionState   RetentionState    `json:"retention_state,omitempty"`
	Links            []Link            `json:"links"`
	SubjectRef       string            `json:"subject_ref,omitempty"`
	PrincipalRef     string            `json:"principal_ref,omitempty"`
	CounterpartyRef  string            `json:"counterparty_ref,omitempty"`
	Correlation      *Correlation      `json:"correlation,omitempty"`
	Statement        json.RawMessage   `json:"statement,omitempty"`
}

Header is the durable, privacy-minimized record header (Evidence Layer §4). Its canonical JSON is committed as the record capsule's agent_input_digest, so every field below is fixed at commit.

func (Header) LinksTo

func (h Header) LinksTo(t LinkType) []string

LinksTo returns the targets of every link of type t in h.

type InclusionEvidence

type InclusionEvidence struct {
	Kind  string          `json:"kind"`
	Seq   uint64          `json:"seq"`
	Proof json.RawMessage `json:"proof"`
}

InclusionEvidence is a substrate-specific inclusion proof for one record, labelled by Kind so a verifier knows which algorithm checks it.

type IndexRoot

type IndexRoot struct {
	Index string `json:"index"`
	Root  string `json:"root"`
	Size  uint64 `json:"size"`
}

IndexRoot is what the book commits: the index name, its Merkle root, and its leaf count.

type IntervalEvidence

type IntervalEvidence struct {
	Certificate CompletenessCertificate `json:"completeness_certificate"`
	Checkpoint  BundleCheckpoint        `json:"checkpoint"`
}

IntervalEvidence carries the completeness certificate and authenticated checkpoint in the Evidence Bundle v2 wire shape.

type KeyRangeAnswer

type KeyRangeAnswer struct {
	Root         IndexRoot     `json:"root"`
	RootRecordID string        `json:"root_record_id"`
	Anchor       Checkpoint    `json:"anchor"`
	Proof        KeyRangeProof `json:"proof"`
}

KeyRangeAnswer is a key-range proof bound to what the book committed: the index root it verifies under, the index_root record that committed that root, and the checkpoint that covers that record. This package ships no standalone verifier for the binding (that the root equals the index_root record's statement and that the record is included under Anchor); a relying party checks the proof with VerifyKeyRange and the binding from a bundle carrying the index_root record. See AuthenticatedIndex for what the proof does not establish against a dishonest book.

type KeyRangeProof

type KeyRangeProof struct {
	Lo      string      `json:"lo"`
	Hi      string      `json:"hi"`
	First   uint64      `json:"first"`
	Matches []LeafProof `json:"matches"`
	Left    *LeafProof  `json:"left,omitempty"`
	Right   *LeafProof  `json:"right,omitempty"`
}

KeyRangeProof proves the complete set of leaves whose key lies in [Lo, Hi]: the matches are contiguous, and the neighbours on either side (when the range does not touch an edge of the tree) have keys outside the range.

type LeafProof

type LeafProof struct {
	Key      string   `json:"key"`
	RecordID string   `json:"record_id"`
	Index    uint64   `json:"index"`
	Path     []string `json:"path"`
}

LeafProof proves one (key, record id) leaf sits at Index under a root.

type LegacyCadence added in v0.6.0

type LegacyCadence struct {
	// Logs are the profile's pre-shelf logs, each a log of the shelf's file
	// that is not a book (capsule-cli: "deal/" + every deal_id of
	// deal_steps, sales included). Each counts into H.
	Logs []string
	// Ticks are the pre-shelf writer's finished ticks (CheckpointSize > 0),
	// in cadence-log order. N is ignored: a tick's identity is its place in
	// the cadence log (EntrySeq) and its checkpoint, and ImportLegacy
	// numbers it. Witnessed and Receipt are set on each tick whose receipt
	// the host has verified; evidencebook verifies no receipt. Every log a
	// tick carries is one of Logs.
	Ticks []CadenceTick
}

LegacyCadence is a profile's cadence as a pre-shelf writer kept it: capsule-cli's deal_cadence rows, on the same cadence log, and the logs its deal index holds (evidencebook#36 §4, capsule-cli#242 §3.2).

type LegacyLog added in v0.5.0

type LegacyLog struct {
	// contains filtered or unexported fields
}

LegacyLog is a deal's log from before the upgrade (#36 §4): its capsules are not book records, so it is never converted. It takes part in the cadence like a book. Every write to it goes through Append, under the shelf's lock.

func (*LegacyLog) Append added in v0.5.0

func (l *LegacyLog) Append(ctx context.Context, write func() error) error

Append runs write, the profile's own step for this log (it opens its own handle on the log), under the shelf's lock. write must not call the shelf or its cadence: the lock is held. Append puts the log back in the live set: an append to a closed deal (later evidence) re-enters the tick like any append.

func (*LegacyLog) CutLocal added in v0.5.0

func (l *LegacyLog) CutLocal(ctx context.Context, at time.Time) ([]byte, uint64, error)

func (*LegacyLog) LogID added in v0.5.0

func (l *LegacyLog) LogID() string

func (*LegacyLog) MMRSize added in v0.5.0

func (l *LegacyLog) MMRSize(ctx context.Context) (uint64, error)

type LifecycleStatement

type LifecycleStatement struct {
	RetentionState RetentionState `json:"retention_state"`
	Reason         string         `json:"reason,omitempty"`
}

LifecycleStatement is the body of a lifecycle record: a later, separately committed statement that the cited record's retention state changed. The state belongs to the record as a whole, never to one of its payloads, and the record that committed the payloads is never rewritten.

A lifecycle record written before retention was kept per record also names a payload_commitment; it is read as applying to the whole record.

type Link struct {
	Type   LinkType `json:"type"`
	Target string   `json:"target"`
}

Link is a typed, directed reference to another record by its record id. A link is committed inside the carrying record and never mutates its target.

type LinkType

type LinkType string

LinkType is the closed typed-link vocabulary (Evidence Layer §5).

const (
	Cites        LinkType = "cites"
	Adjudicates  LinkType = "adjudicates"
	Supersedes   LinkType = "supersedes"
	Acknowledges LinkType = "acknowledges"
	Rebuts       LinkType = "rebuts"
	Closes       LinkType = "closes"
)

func LinkTypes

func LinkTypes() []LinkType

LinkTypes returns the closed link vocabulary in registry order.

func (LinkType) Valid

func (t LinkType) Valid() bool

Valid reports whether t is a registered link type.

type LogCoordinates

type LogCoordinates struct {
	LogID     string `json:"log_id"`
	Seq       uint64 `json:"seq"`
	LeafIndex uint64 `json:"leaf_index"`
}

LogCoordinates locates a record in the log.

type MCPOptions added in v0.2.0

type MCPOptions struct {
	// Manifest is what the host states about its carriers; Bindings must
	// list BindingMCP. The manifest served by evidence_manifest is
	// Book.Manifest(Manifest), byte for byte the one served elsewhere.
	Manifest ManifestOptions
	// Policy is the sharing policy every request is answered under, as for
	// RespondOptions.Policy.
	Policy SharePolicy
	// ServerVersion is the version in the serverInfo each result carries;
	// empty is "unversioned".
	ServerVersion string
}

MCPOptions configures the MCP carriage of a book's responder.

type MCPServer added in v0.2.0

type MCPServer struct {
	// contains filtered or unexported fields
}

MCPServer carries the evidence request exchange over MCP (profile §11.4.5): the tools evidence_manifest and evidence_request, and the server/discover and tools/list requests MCP requires around them. It is a carriage only. It moves the request and reply octets as opaque bytes and adds nothing to what Respond answers: the canonical Artifact is the one the native stream gets for the same request (FR-8, ER §5).

It is transport-neutral: Handle takes one received JSON-RPC message and returns the message to send back. The host owns the transport and its authentication.

func (*MCPServer) Handle added in v0.2.0

func (s *MCPServer) Handle(ctx context.Context, message []byte, authenticated string) []byte

Handle answers one JSON-RPC message received over MCP and returns the JSON-RPC message to send back, or nil for a notification.

authenticated is the requester identity the host's transport established by its own authentication of this message (MCP authorization over HTTP, or the credentials of a stdio process), exactly as for RespondOptions.AuthenticatedRequester, or "" when the caller is not authenticated. It is the only identity Respond sees. Nothing inside the message is ever read as one: not the MCP _meta (clientInfo included), not a tool argument, not the JSON-RPC id, and not the connection the message arrived on. MCP 2026-07-28 has no session to read one from either. As in Respond, authentication decides whether a subject is answered, never what is answered (profile §11.4.1 rule 5).

Every reply, envelope or refusal, is a tool result with isError false and structuredContent {"reply", "media_type"} (P-40). Anything that is not a request under §11.4.5 gets a JSON-RPC error, which is a transport condition and never a refusal.

type MMRInclusion

type MMRInclusion struct {
	V          uint64   `json:"v"`
	Kind       string   `json:"kind"`
	Size       uint64   `json:"size"`
	LeafIndex  uint64   `json:"leaf_index"`
	Witness    []string `json:"witness"`
	PeaksLeft  []string `json:"peaks_left"`
	PeaksRight []string `json:"peaks_right"`
}

MMRInclusion is the portable MMR inclusion proof.

type ManifestOptions added in v0.2.0

type ManifestOptions struct {
	// Bindings are the binding tokens the host answers this exchange over.
	Bindings []string
	// Retention is a URI where the responder's retention commitments can be
	// fetched, or empty. It must not be an enumerable index open to
	// unauthenticated callers (profile §11.4.3).
	Retention string
}

ManifestOptions is what the host states about how it carries the exchange. The book knows its own profile, drafts, subject forms, derivations and refusal policy; it does not know its carriers.

type Membership

type Membership struct {
	LogCoordinates LogCoordinates `json:"log_coordinates"`
	InclusionProof MMRInclusion   `json:"inclusion_proof"`
}

Membership binds one record to its log coordinates with an inclusion proof.

type Message added in v0.2.0

type Message = evidencerequest.Message

Message is octets as carried, with the media type they were carried under.

type Opening added in v0.5.0

type Opening struct {
	Nonce string `json:"nonce"`
	Text  string `json:"text"`
}

Opening is what opens one field commitment: the nonce and the text. It stays with the record's originals and leaves only when disclosed.

func NewOpening added in v0.5.0

func NewOpening(text string) (Opening, error)

NewOpening draws a fresh 32-byte nonce for text.

func (Opening) Commitment added in v0.5.0

func (o Opening) Commitment() (string, error)

Commitment is the field commitment o opens.

type OperationalIndex

type OperationalIndex interface {
	Add(ctx context.Context, record Record) error
	// Find returns matching record ids in log order.
	Find(ctx context.Context, filter Filter) ([]string, error)
	// Rebuild discards all state and re-derives it from source.
	Rebuild(ctx context.Context, source RecordSource) error
	// StateDigest is a deterministic digest of the full index contents.
	StateDigest(ctx context.Context) (string, error)
	Release() error
}

OperationalIndex is fast local lookup with no independent trust value: its answers are only as trustworthy as the store producing them, and nothing that produces a proof reads from it.

type PairResult

type PairResult struct {
	State         ExchangeState `json:"state"`
	JoinKey       string        `json:"join_key,omitempty"`
	A             string        `json:"a,omitempty"`
	B             string        `json:"b,omitempty"`
	TwinBracketID string        `json:"twin_bracket_id,omitempty"`
}

PairResult classifies one exchange.

type PayloadsMode

type PayloadsMode string

PayloadsMode is the disclosure record's payloads claim.

const (
	PayloadsAll      PayloadsMode = "all"
	PayloadsSelected PayloadsMode = "selected"
)

type PeerRecord

type PeerRecord struct {
	RecordID       string
	Seq            uint64
	Header         *Header
	HeaderVerified bool
	CapsuleOK      bool
}

PeerRecord is one record read from a verified bundle. Header is nil when the bundle withheld it; HeaderVerified is true only when the disclosed header hashes to the digest the record's capsule commits, or the capsule, verified, carries the header itself (RecordHeaderMember).

type RangeWitness

type RangeWitness struct {
	FromSeq   uint64   `json:"from_seq"`
	ToSeq     uint64   `json:"to_seq"`
	Size      uint64   `json:"size"`
	FromIndex uint64   `json:"from_index"`
	ToIndex   uint64   `json:"to_index"`
	Witness   []string `json:"witness"`
}

RangeWitness is the index-shaped range proof a completeness certificate carries.

type Receipt

type Receipt struct {
	ServiceID string `json:"service_id"`
	TreeSize  uint64 `json:"tree_size"`
	LeafIndex uint64 `json:"leaf_index"`
	Bytes     []byte `json:"bytes"`
}

Receipt is an opaque transparency-service receipt (for example a COSE Receipt) with the tree coordinates it attests.

type ReconcileBody added in v0.6.0

type ReconcileBody struct {
	JoinKey       string        `json:"join_key"`
	Peer          string        `json:"peer"`
	Period        ResultPeriod  `json:"period"`
	Tallies       ResultTallies `json:"tallies"`
	StateOfRecord string        `json:"state_of_record"`
}

ReconcileBody is the RES §4.1 reconcile body.

type ReconcileClaim added in v0.6.0

type ReconcileClaim struct {
	ID             string             `json:"id"`
	Type           string             `json:"type"`
	ContractRef    string             `json:"contract_ref"`
	RequirementRef string             `json:"requirement_ref"`
	Tier           string             `json:"tier"`
	Grade          string             `json:"grade"`
	Sufficiency    string             `json:"sufficiency"`
	Verdict        string             `json:"verdict"`
	Evidence       []EvidenceRef      `json:"evidence"`
	Proofs         []EvidenceRef      `json:"proofs"`
	Presentation   ResultPresentation `json:"presentation"`
	Reconcile      ReconcileBody      `json:"reconcile"`
}

ReconcileClaim is a type: reconcile claim citing the contract. It has no member that cites a Close (DR §7.4).

type ReconcileInput

type ReconcileInput struct {
	Peer VerifiedBundle
	// RecordType restricts both sides to one record type; empty takes every
	// record that carries correlation keys.
	RecordType string
	// FromSeq and ToSeq bound this book's own window; zero leaves an end open.
	FromSeq, ToSeq uint64
	// PeerFromSeq and PeerToSeq bound the peer's window the same way.
	PeerFromSeq, PeerToSeq uint64
	// Compare or Check is the content test; exactly one is set. Check can
	// answer Undecided (OpenedFieldsAgree, for salted field commitments).
	Compare Comparator
	Check   ContentCheck
	// OwnOpenings and PeerOpenings are field openings by record id, checked
	// against each half's own commitments (OpenHalf) before comparison.
	OwnOpenings, PeerOpenings map[string]map[string]Opening
}

ReconcileInput names the peer's disclosed account and the content test. Each side's window is in that side's own log positions.

type Reconciliation

type Reconciliation struct {
	OwnHead      string       `json:"own_head"`
	PeerHead     string       `json:"peer_head"`
	PeerLog      string       `json:"peer_log"`
	PeerComplete bool         `json:"peer_complete"`
	FromSeq      uint64       `json:"from_seq"`
	ToSeq        uint64       `json:"to_seq"`
	PeerFromSeq  uint64       `json:"peer_from_seq"`
	PeerToSeq    uint64       `json:"peer_to_seq"`
	Pairs        []PairResult `json:"pairs"`
	Tallies      Tallies      `json:"states"`
}

Reconciliation is the result of comparing this book (side A) with a peer's verified bundle (side B). It is computed from bundles alone.

type Record

type Record struct {
	RecordID string
	Seq      uint64
	Header   Header
}

Record is one committed entry: its identity, position, and header. RecordID is the Capsule ID of the sealed record capsule and is the exact 32-byte value appended to the commitment substrate.

type RecordSource

type RecordSource func(ctx context.Context, yield func(Record) error) error

RecordSource yields every committed record in log order. Index rebuilds read only from a RecordSource, so an index can always be reproduced from the committed history alone.

type Refusal

type Refusal = evidencerequest.Refusal

The reply types are the request draft's, defined in go/evidencerequest (ER §4.1, §4.2, profile §6.2, §6.3); these names keep evidencebook's API.

type Registrar

type Registrar interface {
	Register(ctx context.Context, recordID string) (Receipt, error)
}

Registrar registers a record identity with a SCITT transparency service and returns the service's receipt. The service, not the book, assigns the position the receipt proves.

type Reply added in v0.2.0

type Reply = evidencerequest.Reply

The reply types are the request draft's, defined in go/evidencerequest (ER §4.1, §4.2, profile §6.2, §6.3); these names keep evidencebook's API.

func ParseReply added in v0.2.0

func ParseReply(m Message) (Reply, error)

ParseReply reads a received reply: exactly one of an envelope or a refusal. Every failure matches ErrInvalid.

type RequestLimiter added in v0.2.0

type RequestLimiter interface {
	Allow(requester string, now time.Time) bool
}

RequestLimiter decides whether a requester may be answered now. The requester is the authenticated identity, or "" for every caller the transport did not authenticate. A request over the limit is refused policy_declined.

type RequestStatement

type RequestStatement struct {
	Request      json.RawMessage `json:"request"`
	ResponderRef string          `json:"responder_ref,omitempty"`
}

RequestStatement is the body of the record a requester seals before it sends a request. The responder is named here, not in counterparty_ref: asking a party does not make it a counterparty of this book.

type RespondOptions

type RespondOptions struct {
	AuthenticatedRequester string
	// Deprecated: a declared identity is not authentication. Respond ignores
	// it; set AuthenticatedRequester from the transport's authentication.
	RequesterID string
	Policy      SharePolicy
}

RespondOptions carries the requester's identity and the sharing policy.

AuthenticatedRequester is the requester identity established by the transport's own authentication of the caller (for example a verified mutual-TLS peer or a verified signature over the request). Set it only from that authentication; leave it empty when the caller is not authenticated. It is the only input to the relationship gate: with it empty, Respond answers only public questions (the checkpoints subject and the history_card/1 derivation) and refuses every other subject with a signed not_authorized refusal, whatever the policy tier. It decides whether a subject is answered, never what is answered (ER §3.7, §5).

RequesterID is the identity the caller declared. It is never trusted: it does not select a relationship, does not grant any scope, and is not recorded. A handle, route, Agent Card or connection is not authorization either; only AuthenticatedRequester is read.

type ResponderKeys

type ResponderKeys struct {
	Signer     string
	Checkpoint string
	// Witnesses is the requester's witness directory, used when it checks an
	// Evidence Bundle (VerifyBundleAnswer).
	Witnesses []WitnessRow
}

ResponderKeys are the responder's keys as the requester obtained them, independently of any reply: Signer signs refusals and envelopes, Checkpoint signs the checkpoints an artifact is anchored to.

type ResponderPolicy added in v0.2.0

type ResponderPolicy struct {
	// RefusalPolicy is RefusalPolicySpecific (the default when empty) or
	// RefusalPolicyUniform.
	RefusalPolicy string
	// Limiter rate-limits requests per requester; nil sets no limit.
	Limiter RequestLimiter
	// MaxRequestBytes caps a request's size; zero is DefaultMaxRequestBytes.
	MaxRequestBytes int
	// MaxAnswerItems caps the records or checkpoints one artifact carries; a
	// larger answer is refused policy_declined. Zero is DefaultMaxAnswerItems.
	MaxAnswerItems int
}

ResponderPolicy is the responder's cost and abuse policy (FR-37). The zero value answers the most specific token with no rate limit.

type ResponseStatement

type ResponseStatement struct {
	RequestDigest string `json:"request_digest"`
	Outcome       string `json:"outcome"`
	Reason        string `json:"reason,omitempty"`
	KeyID         string `json:"key_id"`
	CheckpointKey string `json:"checkpoint_key_id"`
	Artifact      string `json:"artifact_digest,omitempty"`
	Anchor        string `json:"anchor,omitempty"`
	// NotChecked names the profile properties (§7.2) this requester could
	// not check for a recorded artifact, for example anchor_inclusion where
	// the profile defines no material kind for the subject (P-13).
	NotChecked []string `json:"not_checked,omitempty"`
	Failure    string   `json:"failure,omitempty"`
}

ResponseStatement is the body of the record a requester seals on receipt. KeyID is always the pinned responder key the reply verified under.

type ResultAggregate added in v0.6.0

type ResultAggregate struct {
	Coverage struct {
		EvaluatedPopulation   int `json:"evaluated_population"`
		ExcludedNotApplicable int `json:"excluded_not_applicable"`
		UnknownCount          int `json:"unknown_count"`
	} `json:"coverage"`
	Buckets struct {
		Met          []string `json:"met"`
		NotMet       []string `json:"not_met"`
		NotEvaluable []string `json:"not_evaluable"`
	} `json:"buckets"`
}

ResultAggregate is the Result's coverage statement and buckets (RES §7).

type ResultPeriod added in v0.6.0

type ResultPeriod struct {
	Start string `json:"start"`
	End   string `json:"end"`
}

ResultPeriod is a reconcile's period [start, end), in RFC 3339 UTC with Z and seconds precision.

type ResultPresentation added in v0.6.0

type ResultPresentation struct {
	Kind     string        `json:"kind"`
	Status   string        `json:"status"`
	Evidence []EvidenceRef `json:"evidence"`
}

ResultPresentation is a claim's disclosure carrier (RES §2).

type ResultTallies added in v0.6.0

type ResultTallies struct {
	Matched      int `json:"matched"`
	AOnly        int `json:"a_only"`
	BOnly        int `json:"b_only"`
	Conflicting  int `json:"conflicting"`
	Insufficient int `json:"insufficient"`
	Unresolved   int `json:"unresolved"`
}

ResultTallies are a reconcile claim's six tallies (RES §4.1).

type RetentionState

type RetentionState string

RetentionState names whether a record's payload can currently be resolved (Evidence Layer §6.1).

const (
	Available RetentionState = "AVAILABLE"
	Partial   RetentionState = "PARTIAL"
	Withheld  RetentionState = "WITHHELD"
	Deleted   RetentionState = "DELETED"
	LegalHold RetentionState = "LEGAL_HOLD"
)

func (RetentionState) Valid

func (s RetentionState) Valid() bool

Valid reports whether s is a registered retention state.

type SCITTReceiptSubstrate

type SCITTReceiptSubstrate struct {
	// contains filtered or unexported fields
}

SCITTReceiptSubstrate is a stub binding: it holds one receipt per record in memory and answers inclusion with that receipt. It keeps no log of its own, so interval and consistency proofs are ErrUnsupported and the book's bundles over it carry receipts instead of a completeness certificate. It exists so the "no particular substrate required" property is exercised in code, not asserted in prose; it is not durable.

func NewSCITTReceiptSubstrate

func NewSCITTReceiptSubstrate(serviceID string, registrar Registrar) (*SCITTReceiptSubstrate, error)

NewSCITTReceiptSubstrate returns the receipt-holding substrate stub.

func (*SCITTReceiptSubstrate) Append

func (s *SCITTReceiptSubstrate) Append(ctx context.Context, recordID string, at time.Time) (uint64, error)

func (*SCITTReceiptSubstrate) Checkpoint

func (s *SCITTReceiptSubstrate) Checkpoint(ctx context.Context, _ time.Time) (Checkpoint, error)

Checkpoint names the latest receipt's tree state. The identity comes from the transparency service's coordinates, not from anything the book computes.

func (*SCITTReceiptSubstrate) Entries

func (s *SCITTReceiptSubstrate) Entries(_ context.Context, afterSeq uint64, limit int) ([]SubstrateEntry, error)

func (*SCITTReceiptSubstrate) Info

func (*SCITTReceiptSubstrate) Latest

func (*SCITTReceiptSubstrate) ProveConsistency

func (*SCITTReceiptSubstrate) ProveInclusion

func (*SCITTReceiptSubstrate) ProveInterval

func (*SCITTReceiptSubstrate) Release

func (s *SCITTReceiptSubstrate) Release() error

func (*SCITTReceiptSubstrate) Size

type SQLiteIndex

type SQLiteIndex struct {
	// contains filtered or unexported fields
}

SQLiteIndex is the reference OperationalIndex.

func OpenSQLiteIndex

func OpenSQLiteIndex(path string) (*SQLiteIndex, error)

OpenSQLiteIndex opens the reference operational index. An empty path keeps it in memory, which is safe because it is always rebuildable.

func (*SQLiteIndex) Add

func (x *SQLiteIndex) Add(ctx context.Context, record Record) error

func (*SQLiteIndex) Find

func (x *SQLiteIndex) Find(ctx context.Context, f Filter) ([]string, error)

func (*SQLiteIndex) Rebuild

func (x *SQLiteIndex) Rebuild(ctx context.Context, source RecordSource) error

func (*SQLiteIndex) Release

func (x *SQLiteIndex) Release() error

func (*SQLiteIndex) StateDigest

func (x *SQLiteIndex) StateDigest(ctx context.Context) (string, error)

type SentRequest

type SentRequest struct {
	Bytes    []byte
	Digest   string
	RecordID string
}

SentRequest is a request as transmitted: its octets (JCS JSON), their digest, and the id of the record of having asked. RecordResponse and RecordAbsence re-derive everything else from that committed record.

func (SentRequest) Message added in v0.2.0

func (s SentRequest) Message() Message

Message is the request as carried.

type SetCompleteness added in v0.6.0

type SetCompleteness struct {
	Status string  `json:"status"`
	Kind   *string `json:"kind"`
}

SetCompleteness is a side's §6.1 status and its declared kind, null when no declaration is given.

type SharePolicy

type SharePolicy struct {
	RecordAtCompletion string `json:"record_at_completion"`
	HistorySegments    string `json:"history_segments"`
	Adjudications      string `json:"adjudications"`
	Witness            string `json:"witness,omitempty"`
}

SharePolicy is the four-switch sharing policy, carried unchanged from the mesh plugin's share.* object. Every default keys on relationship.

func DefaultSharePolicy

func DefaultSharePolicy() SharePolicy

DefaultSharePolicy returns the documented defaults.

func (SharePolicy) Validate

func (p SharePolicy) Validate() error

Validate rejects any switch outside its enumerated values.

type Shelf added in v0.5.0

type Shelf struct {
	// contains filtered or unexported fields
}

Shelf is one profile's books, each its own log (evidencebook#36 §1): a deal's bundle is built from its book alone, so it carries no other deal's records. A shelf holds the profile's writer lock from OpenSQLiteShelf to Release and is the profile's only writer. It keeps one Book per log id for its lifetime: a Book allocates positions from its own in-memory order, so two instances of one log could give two records one position.

Each book keeps its own mutex; books of one shelf do not share one. Their positions are per log, so they need no common order, and their writes to the shared file are serialized by SQLite (WAL, a busy timeout, immediate CLL transactions). Operations across books, such as a cadence tick, take the shelf's mutex.

func OpenSQLiteShelf added in v0.5.0

func OpenSQLiteShelf(ctx context.Context, cfg ShelfConfig) (*Shelf, error)

OpenSQLiteShelf takes the writer lock, waiting for any other holder until ctx is done, and opens the shelf's SQLite file, creating its tables when absent.

The file has two kinds of handle: the shelf's own (records and checkpoints of every book) and one per book's CLL log. Both use WAL and a busy timeout, and CLL writes take an immediate transaction, so two writers wait rather than fail. A record's append spans two handles (its log leaf, then its row) and is not one transaction; that is the shape of the JSONL journal and FileStore too, and Open's recovery reconciles a crash between them. Do not fold the handles into one connection to "fix" it: the CLL store owns its own.

func (*Shelf) Books added in v0.5.0

func (s *Shelf) Books(ctx context.Context) ([]string, error)

Books lists the ids of the books that hold records, in id order.

func (*Shelf) Cadence added in v0.5.0

func (s *Shelf) Cadence(ctx context.Context, cfg CadenceConfig) (*Cadence, error)

Cadence opens the shelf's cadence log, creating it when absent.

func (*Shelf) Legacy added in v0.5.0

func (s *Shelf) Legacy(ctx context.Context, logID string) (*LegacyLog, error)

Legacy opens an existing log of the shelf's file that is not a book and registers it with the cadence: it counts into the lifetime log count and is live until it has ended and a witnessed tick carries its final checkpoint. It never provisions a log.

func (*Shelf) Open added in v0.5.0

func (s *Shelf) Open(ctx context.Context, logID string) (*Book, error)

Open returns the book whose log id is logID, creating it on first use. It is the same *Book for the same id for the shelf's lifetime.

func (*Shelf) Records added in v0.6.0

func (s *Shelf) Records(ctx context.Context, bookIDs ...string) (ShelfRecords, error)

Records lists the committed records of the shelf's books, in book id then seq order, without opening a book: nothing is recovered, verified or written. A reader across every deal of a profile costs two queries (the records, and every log's entry count), not one book opened per deal.

A record is committed when 1 <= seq <= its book's log entry count (an entry count, not an MMR size). bookIDs narrows the listing to those books; none lists every book.

The headers are as stored. Records is for readers on the device that wrote them; a book's Open is what checks them against its log.

func (*Shelf) Release added in v0.5.0

func (s *Shelf) Release() error

Release releases every book the shelf opened, closes its file and gives up the writer lock. A book from this shelf refuses writes afterwards (ErrReleased).

type ShelfConfig added in v0.5.0

type ShelfConfig struct {
	// Path is the SQLite file holding every book's records, checkpoints and
	// CLL log (one log per book, keyed by its id), as capsule-cli keeps a
	// profile's per-deal logs in one deal.db.
	Path string
	// LockPath is the profile's writer lock file. A host that already has
	// a writer lock for the store passes that path, so its own writers and
	// the shelf exclude each other: capsule-cli's deal store must pass
	// "<deal.db>.deal.lock" (lockDealStore). Empty means Path + ".lock",
	// which excludes only other shelves.
	LockPath string

	Operator  string
	Developer string
	// Signer seals every book's records; CheckpointKey signs every book's
	// checkpoints, as one key signs a profile's deal logs today.
	Signer        Signer
	CheckpointKey ed25519.PrivateKey
	// Originals is the profile's one artifact store (capsule-cli#236
	// decision 3), shared by every book: an artifact record is keyed by its
	// record id, which is unique across books.
	Originals ArtifactStore
	Now       func() time.Time
	// AuthenticatedIndexes gives a book its authenticated indexes when the
	// shelf opens it. A nil function, or a nil result for a log, gives that
	// book the defaults (NewRecordIDIndex, NewSubjectIndex). An empty,
	// non-nil result gives it none, so its checkpoints commit no index_root
	// records: a deal's log then holds its own steps only.
	AuthenticatedIndexes func(logID string) []AuthenticatedIndex
}

ShelfConfig assembles a Shelf: one profile's books in one SQLite file.

type ShelfRecord added in v0.6.0

type ShelfRecord struct {
	BookID   string
	Seq      uint64
	RecordID string
	Header   Header
	// Retention is the record's retention state now, as Book.Retention
	// gives it; empty for a record that commits no payload or field, which
	// has none.
	Retention RetentionState
}

ShelfRecord is a committed record of one of a shelf's books, as Records lists it.

type ShelfRecords added in v0.6.0

type ShelfRecords struct {
	Records []ShelfRecord
	// Pending counts, by book, the records stored above the book's
	// committed entry count: a crash after PutRecord and before the log
	// append, which the book's next Open recovers. They are not listed.
	Pending map[string]int
}

ShelfRecords is what Records reads: the committed records, and how many records each book holds beyond them.

type Signer

type Signer interface {
	PublicKey() ed25519.PublicKey
	Sign(ctx context.Context, message []byte) ([]byte, error)
}

Signer is the book's signing seam. A host plugs in any key custodian (a local key, an HSM, a KMS) that produces raw Ed25519 signatures; the book never holds or requires a particular key. Sign receives the exact bytes to be signed (for COSE, the Sig_structure), never a pre-hash.

type SortedMerkleIndex

type SortedMerkleIndex struct {
	// contains filtered or unexported fields
}

SortedMerkleIndex is the reference AuthenticatedIndex: a sorted list of (key, record id) leaves under an RFC 9162 Merkle tree.

func NewRecordIDIndex

func NewRecordIDIndex() *SortedMerkleIndex

NewRecordIDIndex indexes every record under its own record id, so the book can prove that a record id is, or is not, committed.

func NewSubjectIndex

func NewSubjectIndex() *SortedMerkleIndex

NewSubjectIndex indexes records under subject_ref, so the book can prove the complete set of records it holds under one subject_ref. A key range proof over it proves subject_ref membership only; it does not establish that a correlation subject's answer is complete, since a record that carries a correlation identifier is answered under that (bookView.Correlated).

func (*SortedMerkleIndex) Add

func (m *SortedMerkleIndex) Add(key, recordID string) error

func (*SortedMerkleIndex) KeyOf

func (m *SortedMerkleIndex) KeyOf(record Record) (string, bool)

func (*SortedMerkleIndex) Name

func (m *SortedMerkleIndex) Name() string

func (*SortedMerkleIndex) ProveMember

func (m *SortedMerkleIndex) ProveMember(key, recordID string) (LeafProof, error)

func (*SortedMerkleIndex) ProveRange

func (m *SortedMerkleIndex) ProveRange(lo, hi string) (KeyRangeProof, error)

func (*SortedMerkleIndex) Reset

func (m *SortedMerkleIndex) Reset()

func (*SortedMerkleIndex) Root

func (m *SortedMerkleIndex) Root() IndexRoot

type Store

type Store interface {
	PutRecord(ctx context.Context, record StoredRecord) error
	GetRecord(ctx context.Context, recordID string) (StoredRecord, error)
	Records(ctx context.Context) ([]StoredRecord, error)
	PutCheckpoint(ctx context.Context, cp Checkpoint) error
	Checkpoints(ctx context.Context) ([]Checkpoint, error)
	Release() error
}

Store holds complete records and the checkpoints the book has observed. A record is stored before its identity is appended to the substrate, so the substrate never commits an identity the book cannot produce.

type StoredRecord

type StoredRecord struct {
	Seq      uint64          `json:"seq"`
	RecordID string          `json:"record_id"`
	Header   json.RawMessage `json:"header"`
	Capsule  json.RawMessage `json:"capsule"`
	Envelope []byte          `json:"envelope"`
}

StoredRecord is the durable form of one record: the canonical header bytes, the sealed signature-free capsule, and its Producer Envelope.

type Subject

type Subject = evidencerequest.Subject

type SubjectKind

type SubjectKind = evidencerequest.SubjectKind

SubjectKind names one of the six subject forms (ER §3.1).

type Substrate

type Substrate interface {
	Info() SubstrateInfo
	// Append assigns the next position to recordID. Appending an identity
	// that is already present returns its original position.
	Append(ctx context.Context, recordID string, at time.Time) (uint64, error)
	Size(ctx context.Context) (uint64, error)
	Entries(ctx context.Context, afterSeq uint64, limit int) ([]SubstrateEntry, error)
	// Checkpoint commits a checkpoint over everything appended so far.
	Checkpoint(ctx context.Context, now time.Time) (Checkpoint, error)
	// Latest returns the newest checkpoint, or ErrNotFound when none exists.
	Latest(ctx context.Context) (Checkpoint, error)
	ProveInclusion(ctx context.Context, seq uint64, at Checkpoint) (InclusionEvidence, error)
	// ProveInterval returns the per-record range and membership evidence for
	// positions [firstSeq, at.Entries]. Substrates that do not maintain an
	// ordered log return ErrUnsupported.
	ProveInterval(ctx context.Context, firstSeq uint64, at Checkpoint) (IntervalEvidence, error)
	ProveConsistency(ctx context.Context, older, newer Checkpoint) (ConsistencyEvidence, error)
	Release() error
}

Substrate is the commitment-substrate interface (Evidence Layer §8). A book needs exactly four properties from it: append order, inclusion, consistency, and checkpoint identity. A Checkpointed Local Log is the reference binding (OpenCLL); a SCITT receipt-holding binding (NewSCITTReceiptSubstrate) shows the book does not require one.

Record identities cross this interface as lowercase hex strings and every proof leaves it as an evidencebook type, so no substrate implementation type is ever visible to a book caller.

type SubstrateEntry

type SubstrateEntry struct {
	Seq        uint64
	RecordID   string
	AppendedAt time.Time
}

SubstrateEntry is one committed position.

type SubstrateInfo

type SubstrateInfo struct {
	Kind  string `json:"kind"`
	LogID string `json:"log_id"`
}

SubstrateInfo names the substrate a book states it uses.

type Tallies

type Tallies struct {
	Matched      int `json:"MATCHED"`
	AOnly        int `json:"A_ONLY"`
	BOnly        int `json:"B_ONLY"`
	Conflicting  int `json:"CONFLICTING"`
	Insufficient int `json:"INSUFFICIENT"`
	Unresolved   int `json:"UNRESOLVED"`
}

Tallies counts exchanges per state.

type TickLeaf added in v0.5.0

type TickLeaf struct {
	LogID            string `json:"log_id"`
	Size             uint64 `json:"size"`
	CheckpointSHA256 string `json:"checkpoint_sha256"`
	Salt             string `json:"salt"`
	Index            uint64 `json:"index"`
	// Statement is the log's checkpoint itself (base64url COSE), kept on
	// the device so a later bundle can show an earlier witnessed checkpoint
	// is a prefix of its current one. The leaf commits to its SHA-256.
	Statement string `json:"statement,omitempty"`
}

TickLeaf is one log's leaf in one tick, as stored on the device. It is capsule-cli's dealTickLeaf, member for member.

type TickLeaves added in v0.5.0

type TickLeaves struct {
	Deals       map[string]TickLeaf `json:"deals"`
	FillerIndex uint64              `json:"filler_index"`
	FillerNonce string              `json:"filler_nonce"`
	// FillerSeed and FillerCount derive fillers 1..FillerCount
	// (DerivedFillers). The seed stays on the device, like the salts.
	FillerSeed  string `json:"filler_seed,omitempty"`
	FillerCount uint64 `json:"filler_count,omitempty"`
}

TickLeaves is every leaf of one tick: capsule-cli's dealTickLeaves (the logs under "deals", one filler) plus the derived fillers that keep a tick's occupancy at the profile's lifetime log count (§2, occupancy floor). A tick stored by a released capsule-cli build has no filler_seed and no derived fillers, and reads unchanged.

func (TickLeaves) Tree added in v0.5.0

func (l TickLeaves) Tree(index uint64) (root []byte, path [][]byte, err error)

Tree rebuilds the tick's tree from its stored leaves and returns the root and the path of the leaf at index.

type TickResult added in v0.5.0

type TickResult struct {
	// Ticked is false when no tick was due; DueNext then says when one is.
	Ticked  bool
	Tick    CadenceTick
	DueNext time.Time
}

TickResult is what one Tick call did.

type TokenIndex

type TokenIndex struct {
	// contains filtered or unexported fields
}

TokenIndex is the reference DiscoveryIndex.

func NewTokenIndex

func NewTokenIndex() *TokenIndex

NewTokenIndex is a small reference DiscoveryIndex that matches word tokens in record_type, subject_ref and statement text.

func (*TokenIndex) Add

func (x *TokenIndex) Add(_ context.Context, record Record) error

func (*TokenIndex) Rebuild

func (x *TokenIndex) Rebuild(ctx context.Context, source RecordSource) error

func (*TokenIndex) Search

func (x *TokenIndex) Search(_ context.Context, query string, limit int) (Candidates, error)

type UnavailableError

type UnavailableError struct {
	RecordID string
	Digest   string
	State    RetentionState
}

UnavailableError reports why a payload yields no bytes. WITHHELD and DELETED both yield none; only DELETED is permanent, so callers read State.

func (*UnavailableError) Error

func (e *UnavailableError) Error() string

func (*UnavailableError) Unwrap

func (e *UnavailableError) Unwrap() error

type VerificationEntry added in v0.2.0

type VerificationEntry = evidencerequest.VerificationEntry

The reply types are the request draft's, defined in go/evidencerequest (ER §4.1, §4.2, profile §6.2, §6.3); these names keep evidencebook's API.

type VerifiedBundle

type VerifiedBundle struct {
	Digest              string
	LogID               string
	Anchor              BundleCheckpoint
	AnchorAuthenticated bool
	AnchorKeyID         string
	// AnchorStatement is the anchor's signed checkpoint statement, when
	// AnchorAuthenticated.
	AnchorStatement []byte
	// Witnesses are the witness receipts the bundle carries
	// (checkpoint.witnesses), as given. Nothing here verifies them: a
	// requester checks them against the anchor under its own witness
	// directory (RecordResponse does, through ResponderKeys.Witnesses).
	Witnesses     []json.RawMessage
	IntervalFirst uint64
	IntervalLast  uint64
	Records       []PeerRecord
	Payloads      map[string][]byte
	// Extensions are integrity-covered by the bundle digest but are the
	// producer's statements; nothing in them is independently verified.
	Extensions map[string]json.RawMessage
	Findings   []string
	// Claims is each of the three verifier claims' status ("pass",
	// "withheld", "unverified", ...). VerifyBundle refuses only "fail";
	// FullyVerified reports whether everything passed.
	Claims BundleClaims
}

VerifiedBundle is what a relying party learns from a bundle after the neutral Evidence Bundle verifier has checked it. AnchorAuthenticated means the checkpoint statement verifies under the key it names (AnchorKeyID); whether that key and log belong to the party the relying party expects is the relying party's check, against a key it obtained independently.

func VerifyBundle

func VerifyBundle(data []byte) (VerifiedBundle, error)

VerifyBundle checks a bundle with the neutral AAC Evidence Bundle verifier and then reads the evidence-layer content out of what verified. It never trusts the producer's own verification member.

Everything is read from the one decoded tree the verifier checked, by exact key, so the verifier and this reader can never see different members: a second copy of a member under a case-variant key ("Disclosures", "CHECKPOINT") is refused outright, and a member present only under a case-variant key is simply absent, exactly as the verifier sees it.

func VerifyBundleAnswer added in v0.2.0

func VerifyBundleAnswer(data []byte, keys ResponderKeys) (VerifiedBundle, error)

VerifyBundleAnswer checks an Evidence Bundle a holder disclosed to this requester (Book.Bundle) under the holder's pinned keys: the neutral bundle verifier must pass every claim, the anchor must be a checkpoint signed by keys.Checkpoint, and every witness receipt carried on it must verify against that checkpoint under the requester's own witness directory. A bundle is never the canonical Artifact of an evidence request; this is the separate disclosure path (profile §6.6).

func (VerifiedBundle) Covers

func (v VerifiedBundle) Covers(seq uint64) bool

Covers reports whether the bundle proves seq is inside its authenticated interval.

func (VerifiedBundle) FullyVerified

func (v VerifiedBundle) FullyVerified() error

FullyVerified returns nil only when all three claims passed and every record's capsule verified. VerifyBundle accepts a bundle whose claims are "withheld" or "unverified" (nothing in it is false); a caller that treats the bundle as proof of what it answers must also require this.

type WindowLimiter added in v0.2.0

type WindowLimiter struct {
	// contains filtered or unexported fields
}

WindowLimiter allows each requester at most N requests in any window of Window. Unauthenticated callers share the one "" bucket.

func NewWindowLimiter added in v0.2.0

func NewWindowLimiter(n int, window time.Duration) *WindowLimiter

NewWindowLimiter returns a limiter of n requests per window.

func (*WindowLimiter) Allow added in v0.2.0

func (l *WindowLimiter) Allow(requester string, now time.Time) bool

Allow records a request at now and reports whether it is within the limit.

type WithheldItem

type WithheldItem struct {
	RecordID          string         `json:"record_id"`
	Member            string         `json:"member,omitempty"`
	PayloadCommitment string         `json:"payload_commitment,omitempty"`
	Digest            string         `json:"digest"`
	RetentionState    RetentionState `json:"retention_state,omitempty"`
}

WithheldItem names material committed but not carried, always with its digest.

type WitnessReceipt added in v0.5.0

type WitnessReceipt struct {
	TSURL     string `json:"ts_url"`
	EntryHash string `json:"entry_hash"`
	Receipt   []byte `json:"receipt"`
	LeafIndex uint64 `json:"leaf_index"`
	TreeSize  uint64 `json:"tree_size"`
}

WitnessReceipt is the witness's receipt for a tick's cadence checkpoint, as the host verified it: capsule-cli's chain carries these members (cll.WitnessState's receipt).

type WitnessRow added in v0.1.1

type WitnessRow struct {
	Name       string   `json:"name"`
	Endpoint   string   `json:"endpoint"`
	Binding    string   `json:"binding"`
	KeyIDs     []string `json:"key_ids"`
	PublicKeys []string `json:"public_keys"`
}

WitnessRow is one row of a witness directory, in capsule-emit's witnesses.json format: the witness's endpoint, its binding (cll when absent) and its keys. A key id is a raw Ed25519 key in hex, or the SHA-256 of a DER key listed in public_keys. Other row fields are read past.

func ParseWitnessDirectory added in v0.1.1

func ParseWitnessDirectory(raw []byte) ([]WitnessRow, error)

ParseWitnessDirectory reads a witness directory: {"witnesses": [rows]} or a bare array of rows.

Directories

Path Synopsis
Package adapter defines the interface every foreign-evidence adapter implements, and the bridge from its per-property results to a requirement's sufficiency and verdict.
Package adapter defines the interface every foreign-evidence adapter implements, and the bridge from its per-property results to a requirement's sufficiency and verdict.
acp
Package acp is the evidencebook adapter for the Agentic Commerce Protocol (ACP), API version 2026-04-17: the checkout session, the order, and the delegated payment token, as declared in agent-action-capsule spec/adapters/acp-v0.md (cited here as acp-v0).
Package acp is the evidencebook adapter for the Agentic Commerce Protocol (ACP), API version 2026-04-17: the checkout session, the order, and the delegated payment token, as declared in agent-action-capsule spec/adapters/acp-v0.md (cited here as acp-v0).
internal/ijson
Package ijson is the adapters' one JSON reader and their one RFC 8785 serializer.
Package ijson is the adapters' one JSON reader and their one RFC 8785 serializer.
ucp
Package ucp is the evidencebook adapter for the Universal Commerce Protocol (UCP) v2026-08-25, as declared in agent-action-capsule spec/adapters/ucp-v0.md.
Package ucp is the evidencebook adapter for the Universal Commerce Protocol (UCP) v2026-08-25, as declared in agent-action-capsule spec/adapters/ucp-v0.md.
x402
Package x402 is the evidencebook adapter for x402 payments, implementing the x402 adapter declaration v0 (agent-action-capsule spec/adapters/x402-v0.md) as ruled for its first implementation.
Package x402 is the evidencebook adapter for x402 payments, implementing the x402 adapter declaration v0 (agent-action-capsule spec/adapters/x402-v0.md) as ruled for its first implementation.
capsulectl module
cmd
evidencebook command
Command evidencebook runs evidencebook's foreign-evidence adapters.
Command evidencebook runs evidencebook's foreign-evidence adapters.
report module
test
interop/answer command
Command answer is a test responder for anyone checking evidencebook with their own verifier (docs/THIRD-PARTY-VERIFIER.md).
Command answer is a test responder for anyone checking evidencebook with their own verifier (docs/THIRD-PARTY-VERIFIER.md).
interop/bundle command
Command bundle writes an Evidence Bundle and a signed refusal produced by a fresh book, for verification by other implementations.
Command bundle writes an Evidence Bundle and a signed refusal produced by a fresh book, for verification by other implementations.
interop/capsules command
Command capsules writes every record capsule a fresh book seals when its records carry each link type, and when it bundles them, as one JSON array for the producer-side registry conformance check (AAC agent_action_capsule.registry_conformance).
Command capsules writes every record capsule a fresh book seals when its records carry each link type, and when it bundles them, as one JSON array for the producer-side registry conformance check (AAC agent_action_capsule.registry_conformance).
interop/personal-history command
Command personal-history produces the positive run of the Personal-Agent History Profile v0 conformance vectors (spec/personal-agent-history-profile-v0.md §6.4) with an IP responder: evidencebook's Book.Respond, unmodified.
Command personal-history produces the positive run of the Personal-Agent History Profile v0 conformance vectors (spec/personal-agent-history-profile-v0.md §6.4) with an IP responder: evidencebook's Book.Respond, unmodified.
interop/responder command
Command responder answers the responder-side requests of the evidence interoperability profile's conformance vectors with a fresh book, and writes every request and reply as carried, for checking by an independent verifier (test/interop/python-profile/verify_responder.py runs the AAC reference verifier over them).
Command responder answers the responder-side requests of the evidence interoperability profile's conformance vectors with a fresh book, and writes every request and reply as carried, for checking by an independent verifier (test/interop/python-profile/verify_responder.py runs the AAC reference verifier over them).
interop/verify command
Command verify checks a bundle produced by another implementation with evidencebook.VerifyBundle, and requires it to be fully verified: all three claims pass, the checkpoint is authenticated, and every record's capsule verifies.
Command verify checks a bundle produced by another implementation with evidencebook.VerifyBundle, and requires it to be fully verified: all three claims pass, the checkpoint is authenticated, and every record's capsule verifies.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL