protocol

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Package protocol implements the ExitMesh History Protocol v1 described in protocol/SPEC.md.

Index

Constants

View Source
const (
	MaxRecordBytes   = 4 << 20
	MaxNestingDepth  = 32
	MaxContainerSize = 1 << 20
)

Decoding limits from SPEC section 3.2.

View Source
const (
	FindingEvidenceTruncated  uint64 = 1 << 0
	FindingEvidenceLimited    uint64 = 1 << 1
	FindingIncompleteCoverage uint64 = 1 << 2
	FindingSamplesCompacted   uint64 = 1 << 3
	FindingLateAtWriter       uint64 = 1 << 4
)

Finding flag bits.

View Source
const (
	TokenCluster   = "c"
	TokenHost      = "h"
	TokenHostGroup = "g"
)

Token kinds of enrollment tokens (SPEC 9.2).

View Source
const (
	FlagSynthetic   uint64 = 1 << 0
	FlagMetricFacts uint64 = 1 << 1
)

Delta flag bits.

View Source
const (
	MethodHello            = "history.hello"
	MethodSummary          = "history.summary"
	MethodAck              = "history.ack"
	MethodReject           = "history.reject"
	MethodSuperseded       = "session.superseded"
	MethodBundleFetch      = "bundle.fetch"
	MethodBundleAvailable  = "bundle.available"
	MethodHealth           = "agent.health"
	MethodAudit            = "investigation.audit"
	MethodDeenroll         = "target.deenroll"
	MethodDeenrolled       = "target.deenrolled"
	MethodCredentialRotate = "credential.rotate" //nolint:gosec // an RPC method name, not a credential
	MethodInitialize       = "initialize"
	MethodPing             = "ping"
	MethodToolsList        = "tools/list"
	MethodToolsCall        = "tools/call"
)

JSON-RPC method names of the tunnel binding (SPEC 9.4).

View Source
const (
	DecisionResume = "resume"
	DecisionOpened = "opened"

	CodeUnauthorized        = "unauthorized"
	CodeIdentityConflict    = "identity_conflict"
	CodeWriterRetired       = "writer_retired"
	CodeEpochClosed         = "epoch_closed"
	CodeNotOwner            = "not_owner"
	CodeStaleIncarnation    = "stale_incarnation"
	CodeDivergence          = "divergence"
	CodeInvalidHello        = "invalid_hello"
	CodeUnsupportedProtocol = "unsupported_protocol"
)

Hello decisions and rejection codes (SPEC 8.3).

View Source
const (
	RPCParseError     = -32700
	RPCInvalidRequest = -32600
	RPCMethodNotFound = -32601
	RPCInvalidParams  = -32602
	RPCInternalError  = -32603
	RPCUnauthorized   = -32001
	RPCForbidden      = -32002
	RPCHistoryReject  = -32010
)

JSON-RPC error codes used on the tunnel.

View Source
const (
	TargetKubernetes = "kubernetes"
	TargetHost       = "host"
)

Target types.

View Source
const (
	FrameRecordBatch  byte = 0x01
	CompressionNone   byte = 0x00
	CompressionZstd   byte = 0x01
	MaxFramePayload        = 16 << 20
	DefaultWindowSize      = 8 << 20
	TunnelSubprotocol      = "exitmesh.v1"
	TunnelPath             = "/agent/v1/tunnel"
	EnrollPath             = "/agent/v1/enroll"
)

Binary frame constants (SPEC 9.3).

View Source
const (
	OpenInitial      = "initial"
	OpenRebaseline   = "rebaseline"
	OpenWriterChange = "writer_change"
)

Epoch-open reasons.

View Source
const (
	CompatOK              = "ok"
	CompatUpdateAvailable = "update_available"
	CompatOutdated        = "outdated"
	CompatUnsupported     = "unsupported"
)

Compatibility statuses.

View Source
const (
	LifecycleFiring   = "firing"
	LifecycleResolved = "resolved"
	LifecycleStale    = "stale"
)

Lifecycle states in a summary.

View Source
const ExportMagic = "EMHPX1\n"

ExportMagic starts an air-gap export file (SPEC 10).

View Source
const ExtensionKeyMin = 1000

ExtensionKeyMin is the first extension key (SPEC 3.4).

View Source
const SchemaVersion = 1

SchemaVersion is the state schema version written by this implementation.

View Source
const Version = 1

Version is the protocol major version.

Variables

View Source
var (
	ErrMalformed        = &Error{Code: "malformed"}
	ErrTooLarge         = &Error{Code: "too_large"}
	ErrUnsupportedField = &Error{Code: "unsupported_field"}
	ErrInvalidValue     = &Error{Code: "invalid_value"}
	ErrInvalidChain     = &Error{Code: "invalid_chain"}
	ErrInvalidOp        = &Error{Code: "invalid_op"}
	ErrInvalidStateHash = &Error{Code: "invalid_state_hash"}
	ErrUnavailable      = &Error{Code: "unavailable"}
	ErrFold             = &Error{Code: "fold"}
)

Rejection reasons. Their Code values are the wire codes of SPEC section 9.4.

Functions

func CloneFields

func CloneFields(m map[string]any) map[string]any

CloneFields deep-copies a field map; nil becomes an empty map.

func CloneValue

func CloneValue(v any) any

CloneValue deep-copies a normalized value.

func CodeOf

func CodeOf(err error) string

CodeOf returns the protocol code of err, or "" if err is not a protocol error.

func DecodeBatchFrame

func DecodeBatchFrame(frame []byte) ([][]byte, error)

DecodeBatchFrame returns the record byte strings of a batch frame.

func Encode

func Encode(r *Record) ([]byte, error)

Encode validates r, encodes it deterministically, and records its bytes and hash.

func EncodeBatchFrame

func EncodeBatchFrame(records [][]byte, compress bool) ([]byte, error)

EncodeBatchFrame builds a record batch binary frame (SPEC 9.3) from exact record bytes.

func EncodeFinding

func EncodeFinding(f *Finding) ([]byte, error)

EncodeFinding deterministically encodes a finding body outside a record (node agent queues).

func FieldChanges

func FieldChanges(cur, next map[string]any) map[string]any

FieldChanges returns the update changes from cur to next: changed or added values, and nil for removed keys.

func FindingID

func FindingID(targetID, dedupKey string, firstSeen uint64) string

FindingID derives the deterministic finding id for an episode.

func IsUnavailable

func IsUnavailable(spans []Span, seq uint64) bool

IsUnavailable reports whether seq falls in one of the spans.

func Marshal

func Marshal(v any) ([]byte, error)

Marshal encodes v with core deterministic encoding.

func NormalizeFields

func NormalizeFields(m map[string]any, allowNull bool) (map[string]any, error)

NormalizeFields normalizes a field map. With allowNull, nil values (field removals) are kept.

func NormalizeValue

func NormalizeValue(v any, allowNull bool) (any, error)

NormalizeValue converts a Go value to the canonical SPEC 3.3 representation; nil is rejected unless allowNull.

func ReadExport

func ReadExport(r io.Reader) (ExportHeader, []*Record, error)

ReadExport parses an export file, decoding and chain-checking every record.

func Readable

func Readable(r *Record, chainHash *Hash) map[string]any

Readable renders a record with named fields for support and export inspection (PRD 7.4).

func SortOps

func SortOps(ops []Op)

SortOps orders ops canonically (SPEC 5.3).

func UnixMilli

func UnixMilli(ms uint64) time.Time

UnixMilli returns the instant of a millisecond wire timestamp, saturating values beyond the int64 range.

func ValidTargetID

func ValidTargetID(s string) bool

ValidTargetID reports whether s is a well-formed target_id.

func ValueEqual

func ValueEqual(a, b any) bool

ValueEqual reports whether two values have identical deterministic encodings.

Types

type AckParams

type AckParams struct {
	Epoch     EpochID `json:"epoch"`
	Seq       uint64  `json:"seq"`
	ChainHash Hash    `json:"chain_hash"`
}

AckParams reports the committed head.

type ActiveSession

type ActiveSession struct {
	SessionID   string
	Writer      WriterID
	Incarnation uint64
}

ActiveSession is the currently attached writer session of a target.

type AgentInfo

type AgentInfo struct {
	Version           string `json:"version"`
	Protocol          int    `json:"protocol"`
	Schema            int    `json:"schema"`
	Engine            int    `json:"engine"`
	Role              string `json:"role"`
	Platform          string `json:"platform,omitempty"`
	KubernetesVersion string `json:"kubernetes_version,omitempty"`
	OS                string `json:"os,omitempty"`
}

AgentInfo is reported on every connect (PRD U1).

type Boundary

type Boundary struct {
	Seq      uint64
	Expected Hash
	Got      Hash
}

Boundary is a reconstruction boundary: a checkpoint whose content did not match replayed state.

type BundleAvailableParams

type BundleAvailableParams struct {
	Version    string `json:"version"`
	TargetType string `json:"target_type"`
}

BundleAvailableParams announces a new target bundle version.

type BundleFetchParams

type BundleFetchParams struct {
	TargetType string `json:"target_type"`
	Have       string `json:"have"`
}

BundleFetchParams requests the assigned rule bundle.

type BundleFetchResult

type BundleFetchResult struct {
	Version     string `json:"version"`
	Bundle      []byte `json:"bundle"`
	Signature   []byte `json:"signature"`
	KeyManifest []byte `json:"key_manifest"`
	// KeyManifestChain holds earlier manifests in ascending sequence so a writer that only trusts an older root can follow rotations.
	KeyManifestChain [][]byte `json:"key_manifest_chain,omitempty"`
}

BundleFetchResult carries a signed bundle and the latest key manifest.

type Chain

type Chain struct {
	TargetID       string
	Epoch          EpochID
	Writer         WriterID
	Head           uint64
	HeadHash       Hash
	LastCheckpoint uint64
}

Chain tracks one epoch's chain position and verifies linkage (SPEC 4.1).

func NewChain

func NewChain(targetID string, epoch EpochID, writer WriterID) *Chain

NewChain returns an empty chain for an epoch; Head 0 carries the genesis hash.

func (*Chain) Append

func (c *Chain) Append(r *Record) (Hash, error)

Append verifies and advances the chain, returning the record's chain hash.

func (*Chain) Check

func (c *Chain) Check(r *Record) (Hash, error)

Check verifies that r extends the chain and returns its chain hash without advancing.

func (*Chain) Next

func (c *Chain) Next(t RecordType, incarnation, timeMs uint64) Envelope

Next returns the envelope for the next non-range record appended to the chain.

type ChainPoint

type ChainPoint struct {
	Seq       uint64 `json:"seq"`
	ChainHash Hash   `json:"chain_hash"`
}

ChainPoint is a sequence and its chain hash.

type Checkpoint

type Checkpoint struct {
	Reason       CheckpointReason
	Interval     Interval
	Resources    []Resource
	Edges        []Edge
	Scopes       map[string]ScopeStatus
	Capabilities []string
	StateHash    Hash
	PrevEpoch    *EpochID
	PrevHead     *uint64
}

Checkpoint is a full state record (SPEC 4.2).

func (*Checkpoint) ContentHash

func (c *Checkpoint) ContentHash() Hash

ContentHash computes the state hash of the checkpoint content.

type CheckpointReason

type CheckpointReason uint64

CheckpointReason is checkpoint body key 0.

const (
	ReasonInitial      CheckpointReason = 1
	ReasonAnchor       CheckpointReason = 2
	ReasonRebaseline   CheckpointReason = 3
	ReasonWriterChange CheckpointReason = 4
	ReasonReplayAnchor CheckpointReason = 5
)

type Compat

type Compat struct {
	Status         string `json:"status"`
	MinimumVersion string `json:"minimum_version,omitempty"`
	LatestVersion  string `json:"latest_version,omitempty"`
	Message        string `json:"message,omitempty"`
}

Compat is the control plane's compatibility verdict (PRD U2, U3).

type CredentialRotateParams

type CredentialRotateParams struct {
	Credential   string `json:"credential"`
	CredentialID string `json:"credential_id"`
}

CredentialRotateParams delivers a rotated credential.

type Decision

type Decision struct {
	Row          int
	Accept       bool
	Code         string
	Outcome      string
	OpenEpoch    bool
	CloseEpoch   *EpochID
	RetireWriter *WriterID
	Supersede    bool
	SetConflict  bool
	ClearBinding bool
	Audit        bool
	Alarm        bool
}

Decision is the outcome of the ownership decision table.

func Decide

func Decide(st *OwnershipState, h *HelloParams, credentialValid bool) Decision

Decide evaluates the normative ownership decision table (SPEC 8.3) for a hello.

type DeenrollParams

type DeenrollParams struct {
	Reason string `json:"reason"`
}

DeenrollParams requests explicit de-enrollment.

type DeleteReason

type DeleteReason uint64

DeleteReason distinguishes deletion from scope removal (SPEC 4.3).

const (
	DeleteDeleted      DeleteReason = 1
	DeleteScopeRemoved DeleteReason = 2
)

type Delta

type Delta struct {
	Ops       []Op
	Flags     uint64
	Uncertain *Interval
}

Delta is a set of state operations (SPEC 4.3).

type Edge

type Edge struct {
	From  string
	Type  string
	To    string
	Attrs map[string]any
}

Edge is one change-graph edge.

func (Edge) Key

func (e Edge) Key() EdgeKey

type EdgeKey

type EdgeKey struct{ From, Type, To string }

EdgeKey identifies an edge.

func (EdgeKey) Less

func (k EdgeKey) Less(o EdgeKey) bool

Less orders edge keys bytewise element by element.

type EnrollRequest

type EnrollRequest struct {
	Token      string    `json:"token"`
	WriterID   WriterID  `json:"writer_id"`
	TargetType string    `json:"target_type"`
	MachineID  string    `json:"machine_id,omitempty"`
	Hostname   string    `json:"hostname,omitempty"`
	Agent      AgentInfo `json:"agent"`
}

EnrollRequest exchanges an enrollment token for a credential (SPEC 9.2).

type EnrollResponse

type EnrollResponse struct {
	TargetID     string `json:"target_id"`
	Credential   string `json:"credential"`
	CredentialID string `json:"credential_id"`
}

EnrollResponse returns the target identity and credential.

type EnrollmentToken

type EnrollmentToken struct {
	Kind   string
	ID     string
	Secret string
}

EnrollmentToken is a parsed enrollment token.

func ParseEnrollmentToken

func ParseEnrollmentToken(s string) (EnrollmentToken, error)

ParseEnrollmentToken parses emx1_<kind>_<id>_<secret>.

func (EnrollmentToken) TargetID

func (t EnrollmentToken) TargetID() (string, bool)

TargetID returns the embedded target_id for cluster and host tokens.

type Envelope

type Envelope struct {
	Type        RecordType
	TargetID    string
	Epoch       EpochID
	Seq         uint64
	Writer      WriterID
	Incarnation uint64
	Parent      uint64
	Base        uint64
	Time        uint64
	Schema      uint64
}

Envelope holds the record identity and chain position (SPEC 4.1).

type EpochID

type EpochID = ID

EpochID identifies an epoch; writers generate UUIDv7 values.

func NewEpoch

func NewEpoch(t time.Time) (EpochID, error)

NewEpoch returns a UUIDv7 epoch identifier for time t.

type EpochInfo

type EpochInfo struct {
	ID       EpochID
	Owner    WriterID
	Open     bool
	Head     ChainPoint
	ClosedAt uint64
}

EpochInfo is the control plane's view of one epoch.

type EpochOpen

type EpochOpen struct {
	Reason    string   `json:"reason"`
	PrevEpoch *EpochID `json:"prev_epoch,omitempty"`
	PrevHead  *uint64  `json:"prev_head,omitempty"`
}

EpochOpen declares that the hello opens a new epoch.

type Error

type Error struct{ Code string }

Error is a protocol rejection class; wrap it with fmt.Errorf("%w: ...").

func (*Error) Error

func (e *Error) Error() string

type Evidence

type Evidence struct {
	Source    string
	Time      uint64
	Text      string
	Count     uint64
	Labels    map[string]string
	Truncated bool
	Context   bool
}

Evidence is one capped, redacted sample.

type ExportHeader

type ExportHeader struct {
	TargetID      string `cbor:"target_id"`
	WriterID      []byte `cbor:"writer_id"`
	Incarnation   uint64 `cbor:"incarnation"`
	Epoch         []byte `cbor:"epoch"`
	LastCommitted uint64 `cbor:"last_committed"`
	ExportedAt    uint64 `cbor:"exported_at"`
	AgentVersion  string `cbor:"agent_version"`
}

ExportHeader is the first item of an export file.

type ExportWriter

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

ExportWriter writes an export file.

func NewExportWriter

func NewExportWriter(w io.Writer, h ExportHeader) (*ExportWriter, error)

NewExportWriter writes the magic and header.

func (*ExportWriter) Write

func (e *ExportWriter) Write(record []byte) error

Write appends one record's exact bytes.

type Finding

type Finding struct {
	ID          string
	DedupKey    string
	Transition  Transition
	Provenance  Provenance
	Category    string
	Severity    Severity
	EvalTime    uint64
	FirstSeen   uint64
	LastSeen    uint64
	Count       uint64
	Resources   []string
	Facts       map[string]any
	Evidence    []Evidence
	Flags       uint64
	Node        string
	Labels      map[string]string
	Summary     string
	Suggestions []Suggestion
	Coverage    []string
}

Finding is a finding event (SPEC 4.5).

func DecodeFinding

func DecodeFinding(b []byte) (*Finding, error)

DecodeFinding strictly decodes a finding body produced by EncodeFinding.

func (Finding) Clone

func (f Finding) Clone() Finding

Clone deep-copies a finding.

type Hash

type Hash [32]byte

Hash is a SHA-256 digest.

func ChainHash

func ChainHash(prev, record Hash) Hash

ChainHash links a record hash to its predecessor's chain hash.

func Genesis

func Genesis(targetID string, epoch EpochID, writer WriterID) Hash

Genesis is the chain hash of parent 0 for an epoch.

func ParseHash

func ParseHash(s string) (Hash, error)

ParseHash parses a lowercase or uppercase hex SHA-256 digest.

func QueryHash

func QueryHash(language, normalizedQuery, source string) Hash

QueryHash hashes a normalized investigation query.

func RecordHash

func RecordHash(b []byte) Hash

RecordHash is SHA-256("EMHPv1/record" || 0 || bytes).

func (Hash) IsZero

func (h Hash) IsZero() bool

func (Hash) MarshalJSON

func (h Hash) MarshalJSON() ([]byte, error)

func (Hash) String

func (h Hash) String() string

func (*Hash) UnmarshalJSON

func (h *Hash) UnmarshalJSON(b []byte) error

type HelloParams

type HelloParams struct {
	TargetID      string      `json:"target_id"`
	TargetType    string      `json:"target_type"`
	WriterID      WriterID    `json:"writer_id"`
	Incarnation   uint64      `json:"incarnation"`
	Epoch         EpochID     `json:"epoch"`
	EpochOpen     *EpochOpen  `json:"epoch_open"`
	LastCommitted *ChainPoint `json:"last_committed"`
	MachineID     string      `json:"machine_id,omitempty"`
	Agent         AgentInfo   `json:"agent"`
}

HelloParams opens a history session.

type HelloResult

type HelloResult struct {
	Decision      string     `json:"decision"`
	SessionID     string     `json:"session_id"`
	Epoch         EpochID    `json:"epoch"`
	Head          ChainPoint `json:"head"`
	WindowBytes   int64      `json:"window_bytes"`
	MaxFrameBytes int64      `json:"max_frame_bytes"`
	Compat        Compat     `json:"compat"`
}

HelloResult accepts a history session.

type ID

type ID [16]byte

ID is a 16-byte identifier used for writer IDs and epochs.

func ParseID

func ParseID(s string) (ID, error)

ParseID parses a 16-byte hex identifier.

func (ID) IsZero

func (id ID) IsZero() bool

func (ID) MarshalJSON

func (id ID) MarshalJSON() ([]byte, error)

func (ID) String

func (id ID) String() string

func (*ID) UnmarshalJSON

func (id *ID) UnmarshalJSON(b []byte) error

type Interval

type Interval struct{ Start, End uint64 }

Interval is a closed [Start, End] time interval in milliseconds.

type Op

type Op struct {
	Kind         OpKind
	UID          string
	ResourceKind string
	Namespace    string
	Name         string
	Fields       map[string]any
	DeleteReason DeleteReason
	EdgeType     string
	To           string
	Attrs        map[string]any
	PrevAttrs    map[string]any
	ScopeKey     string
	Scope        ScopeStatus
}

Op is one state operation; the meaningful fields depend on Kind (SPEC 4.3), and edge ops use UID as the source.

func Create

func Create(uid, kind, ns, name string, fields map[string]any) Op

Create returns a create op.

func Delete

func Delete(uid string, reason DeleteReason) Op

Delete returns a delete op.

func EdgeAdd

func EdgeAdd(from, typ, to string, attrs map[string]any) Op

EdgeAdd returns an edge-add op.

func EdgeRemove

func EdgeRemove(from, typ, to string, attrs map[string]any) Op

EdgeRemove returns an edge-remove op carrying the removed attributes.

func EdgeReplace

func EdgeReplace(from, typ, to string, attrs, prev map[string]any) Op

EdgeReplace returns an edge-replace op.

func ScopeSet

func ScopeSet(key string, st ScopeStatus) Op

ScopeSet returns a scope-set op.

func Update

func Update(uid string, changes map[string]any) Op

Update returns an update op; nil values in changes remove fields.

func (*Op) EdgeKey

func (o *Op) EdgeKey() EdgeKey

EdgeKey returns the edge key of an edge op.

type OpKind

type OpKind uint64

OpKind is op key 0 (SPEC 4.3).

const (
	OpCreate      OpKind = 1
	OpUpdate      OpKind = 2
	OpDelete      OpKind = 3
	OpEdgeAdd     OpKind = 4
	OpEdgeRemove  OpKind = 5
	OpEdgeReplace OpKind = 6
	OpScopeSet    OpKind = 7
)

func (OpKind) String

func (k OpKind) String() string

type OwnershipState

type OwnershipState struct {
	TargetType         string
	Revoked            bool
	OpenEpoch          *EpochID
	Epochs             map[EpochID]*EpochInfo
	Retired            map[WriterID]bool
	HighestIncarnation map[WriterID]uint64
	Active             *ActiveSession
	EnrolledMachineID  string
	Conflict           bool
	PendingBinding     bool
	// ChainHashAt returns the committed chain hash at seq in epoch; seq 0 is the genesis.
	ChainHashAt func(epoch EpochID, seq uint64) (Hash, bool)
}

OwnershipState is the per-target ownership registry input to Decide (SPEC 8.2).

type Provenance

type Provenance struct {
	Kind          ProvenanceKind
	RuleID        string
	RuleVersion   uint64
	BundleVersion string
	QueryHash     Hash
	Requester     string
}

Provenance identifies what produced a finding.

type ProvenanceKind

type ProvenanceKind uint64

ProvenanceKind distinguishes rule- and query-generated findings.

const (
	ProvenanceRule  ProvenanceKind = 1
	ProvenanceQuery ProvenanceKind = 2
)

type RPCError

type RPCError struct {
	Code    int           `json:"code"`
	Message string        `json:"message"`
	Data    *RPCErrorData `json:"data,omitempty"`
}

RPCError is a JSON-RPC error object; Data.Code carries the protocol code.

func (*RPCError) Error

func (e *RPCError) Error() string

type RPCErrorData

type RPCErrorData struct {
	Code string `json:"code"`
}

RPCErrorData carries the product-level error code.

type RPCMessage

type RPCMessage struct {
	JSONRPC string           `json:"jsonrpc"`
	ID      *json.RawMessage `json:"id,omitempty"`
	Method  string           `json:"method,omitempty"`
	Params  json.RawMessage  `json:"params,omitempty"`
	Result  json.RawMessage  `json:"result,omitempty"`
	Error   *RPCError        `json:"error,omitempty"`
}

RPCMessage is a JSON-RPC 2.0 request, notification, or response.

type Range

type Range struct {
	Ops       []Op
	From, To  uint64
	Findings  []RangeFinding
	Flags     uint64
	Uncertain []Interval
}

Range replaces a coalesced run of records (SPEC 4.4).

func Fold

func Fold(records []*Record) (*Range, error)

Fold coalesces a contiguous run of delta, range, and finding records into one range body (SPEC 5).

type RangeFinding

type RangeFinding struct {
	Seq     uint64
	Finding Finding
}

RangeFinding is a finding event preserved inside a range with its original sequence.

type Record

type Record struct {
	Envelope
	Checkpoint *Checkpoint
	Delta      *Delta
	Range      *Range
	Finding    *Finding
	Ext        map[uint64]any
	// contains filtered or unexported fields
}

Record is one decoded or to-be-encoded history record. Exactly one body is set.

func Decode

func Decode(b []byte) (*Record, error)

Decode strictly decodes and validates one record (SPEC 3.2, 4).

func NewRangeRecord

func NewRangeRecord(tmpl Envelope, g *Range, parent, base uint64) (*Record, error)

NewRangeRecord builds the range record replacing a folded run whose first record's parent is parent and whose governing checkpoint is base.

func (*Record) Bytes

func (r *Record) Bytes() []byte

Bytes returns the exact encoded bytes; nil before Encode or Decode.

func (*Record) Equal

func (r *Record) Equal(o *Record) bool

Equal reports whether two records have identical bytes.

func (*Record) Hash

func (r *Record) Hash() Hash

Hash returns the record hash of the exact bytes.

func (*Record) ID

func (r *Record) ID() RecordID

type RecordID

type RecordID struct {
	TargetID string
	Epoch    EpochID
	Seq      uint64
}

RecordID is the (target_id, epoch, seq) identity of a record.

func (RecordID) String

func (id RecordID) String() string

type RecordType

type RecordType uint64

RecordType is envelope key 1.

const (
	TypeCheckpoint RecordType = 1
	TypeDelta      RecordType = 2
	TypeRange      RecordType = 3
	TypeFinding    RecordType = 4
)

func (RecordType) String

func (t RecordType) String() string

type RejectParams

type RejectParams struct {
	Epoch   EpochID `json:"epoch"`
	Seq     uint64  `json:"seq"`
	Code    string  `json:"code"`
	Message string  `json:"message,omitempty"`
}

RejectParams reports a rejected record.

type Replayer

type Replayer struct {
	Boundaries  []Boundary
	Unavailable []Span
	// contains filtered or unexported fields
}

Replayer reconstructs state along a chain (SPEC 6.3).

func NewReplayer

func NewReplayer(targetID string, epoch EpochID, writer WriterID) *Replayer

NewReplayer starts at the first record of an epoch.

func NewReplayerAt

func NewReplayerAt(anchor *Record, prev Hash) (*Replayer, error)

NewReplayerAt starts from a retained anchor checkpoint whose predecessor chain hash is prev.

func (*Replayer) Apply

func (p *Replayer) Apply(r *Record) (Hash, error)

Apply verifies linkage and applies r; a disagreeing checkpoint is recorded as a boundary and replaces state.

func (*Replayer) Chain

func (p *Replayer) Chain() Chain

Chain exposes the current chain position.

func (*Replayer) State

func (p *Replayer) State() *State

State returns the state at the chain head. Callers must not mutate it.

func (*Replayer) StateHashAt

func (p *Replayer) StateHashAt(seq uint64) (Hash, error)

StateHashAt returns the state hash at a replayed sequence, or ErrUnavailable for range interiors.

type Resource

type Resource struct {
	UID       string
	Kind      string
	Namespace string
	Name      string
	Fields    map[string]any
}

Resource is one normalized resource in state.

type ScopeState

type ScopeState uint64

ScopeState is the completeness state of a scope.

const (
	ScopeComplete    ScopeState = 0
	ScopePartial     ScopeState = 1
	ScopeUnavailable ScopeState = 2
)

type ScopeStatus

type ScopeStatus struct {
	State  ScopeState
	Reason string
	Since  uint64
}

ScopeStatus is the status of one collection scope.

type Severity

type Severity uint64

Severity is finding body key 5.

const (
	SeverityInfo     Severity = 1
	SeverityLow      Severity = 2
	SeverityMedium   Severity = 3
	SeverityHigh     Severity = 4
	SeverityCritical Severity = 5
)

func ParseSeverity

func ParseSeverity(s string) Severity

ParseSeverity maps a severity label to its value; unknown labels map to medium.

func (Severity) String

func (s Severity) String() string

type Span

type Span struct{ From, To uint64 }

Span is a closed sequence interval.

type State

type State struct {
	Resources map[string]*Resource
	Edges     map[EdgeKey]map[string]any
	Scopes    map[string]ScopeStatus
}

State is the reconstructable state of an epoch (SPEC 6.1).

func NewState

func NewState() *State

NewState returns an empty state.

func Reconstruct

func Reconstruct(records []*Record, seq uint64) (*State, error)

Reconstruct replays an epoch's records (in chain order, starting with its first checkpoint) up to and including seq and returns the state there.

func StateFromCheckpoint

func StateFromCheckpoint(c *Checkpoint) *State

StateFromCheckpoint builds state from checkpoint content.

func (*State) ApplyOps

func (s *State) ApplyOps(ops []Op) error

ApplyOps applies ops touching distinct keys atomically: all apply or the state is unchanged.

func (*State) ApplyRecord

func (s *State) ApplyRecord(r *Record) error

ApplyRecord applies a delta or range record; checkpoints and findings leave state unchanged.

func (*State) Checkpoint

func (s *State) Checkpoint(reason CheckpointReason, iv Interval, capabilities []string) *Checkpoint

Checkpoint snapshots the state into a checkpoint body. Content is deep-copied.

func (*State) Clone

func (s *State) Clone() *State

Clone deep-copies the state.

func (*State) Diff

func (s *State) Diff(target *State, reason DeleteReason) []Op

Diff returns the canonical ops that transform s into target. Delete ops use reason.

func (*State) Equal

func (s *State) Equal(o *State) bool

Equal reports whether two states have the same hash.

func (*State) Hash

func (s *State) Hash() Hash

Hash is the state hash of SPEC 6.2.

func (*State) SortedEdges

func (s *State) SortedEdges() []Edge

SortedEdges returns edges ordered by edge key.

func (*State) SortedResources

func (s *State) SortedResources() []Resource

SortedResources returns resources ordered by UID.

type Suggestion

type Suggestion struct {
	Language string
	Query    string
	Source   string
}

Suggestion is a bounded investigation option.

type SummaryEntry

type SummaryEntry struct {
	FindingID      string `json:"finding_id"`
	DedupKey       string `json:"dedup_key"`
	State          string `json:"state"`
	FirstSeen      uint64 `json:"first_seen"`
	LastTransition uint64 `json:"last_transition"`
	EvalTime       uint64 `json:"eval_time"`
	RuleID         string `json:"rule_id,omitempty"`
	BundleVersion  string `json:"bundle_version,omitempty"`
	Severity       string `json:"severity"`
}

SummaryEntry is one finding in a lifecycle summary (PRD 7.7).

type SummaryParams

type SummaryParams struct {
	Epoch     EpochID        `json:"epoch"`
	Watermark uint64         `json:"watermark"`
	Head      uint64         `json:"head"`
	Entries   []SummaryEntry `json:"entries"`
}

SummaryParams is the finding lifecycle summary at the replay watermark.

type SupersededParams

type SupersededParams struct {
	SessionID string `json:"session_id"`
}

SupersededParams closes a superseded session.

type Transition

type Transition uint64

Transition is finding body key 2.

const (
	TransitionFiring   Transition = 1
	TransitionUpdate   Transition = 2
	TransitionResolved Transition = 3
	TransitionStale    Transition = 4
	TransitionFresh    Transition = 5
)

func (Transition) String

func (t Transition) String() string

type WriterID

type WriterID = ID

WriterID identifies a spool for its lifetime.

func NewWriterID

func NewWriterID() (WriterID, error)

NewWriterID returns a random writer ID.

Directories

Path Synopsis
Package client implements the transport-agnostic writer session of the History Protocol (protocol/SPEC.md sections 8 and 9): hello, resume and drain, windowed replay, acknowledgements, divergence handling with rebaseline, and the reverse MCP channel.
Package client implements the transport-agnostic writer session of the History Protocol (protocol/SPEC.md sections 8 and 9): hello, resume and drain, windowed replay, acknowledgements, divergence handling with rebaseline, and the reverse MCP channel.
clienttest
Package clienttest provides an in-memory writer model implementing client.Hooks over a client.MemStore, for tests.
Package clienttest provides an in-memory writer model implementing client.Hooks over a client.MemStore, for tests.
Package refcp is an in-memory reference control plane for contract and end-to-end tests.
Package refcp is an in-memory reference control plane for contract and end-to-end tests.

Jump to

Keyboard shortcuts

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