graph

package
v0.1.0-alpha.2 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 13 Imported by: 0

README

Graph Package

The data model and the wire types of SemEngine's entity graph. The package imports no NATS client: a reader of a graph type does not pull in the transport to get it (graph-transport-boundary, "The graph root imports no transport"; TestGraphImportsNoTransport).

What the package holds

  • The data model. EntityState is one entity's stored state: its 6-part ID (org.platform.system.domain.type.instance, the key in the ENTITY_STATES bucket), its statements (message.Triple), an optional StorageRef, the MessageType that last wrote it, and UpdatedAt, the store's write time. It carries no version number of its own: the bucket's key-value revision is the only concurrency fence (graph-entity-writes, "The revision is the only fence"). A stored value written with a version key still decodes.
  • The replace rule, a pure function with no I/O. ReplaceBySource treats the statements of one (subject, predicate, source) as one set: an arriving set replaces only the stored set of its own key, and a set older than the stored one (by Timestamp) is not applied and is reported in ReplaceResult.Stale. Confidence and Context never decide whether a write applies.
  • The single-value reads. A predicate may hold statements from several sources. EntityState.GetTriple and EntityState.GetPropertyValue pick the same statement every time: the latest Timestamp; on equal timestamps, the Source that sorts first; on equal sources, the first stored. A reader that wants another choice reads Triples.
  • The reserved sources. SourceIndexingProfile, SourceHierarchy and SourceLifecycle are the names graph-ingest and pkg/lifecycle write their own statements under; IsReservedSource recognises them.
  • The state contract. MarshalEntityState is the validating encoder for stored entities and UnmarshalEntityState the validating decoder; StateContractError and its classifiers carry the "graph state reset required" contract across a request and its reply. Entity-ID prefixes and the predicate token codec sit beside them.
  • Bucket names. The Bucket* constants name the graph's buckets. The catalog that describes and acquires them is graph/kvcatalog.
  • The wire types. The query request and reply types, the mutation requests and responses (ReconcilePredicatesRequest names the one source it reconciles), ExactEntity and ExactEntityReader for the authority read, and IndexStatusResponse, the readiness envelope a producer writes to GRAPH_STATUS, with its IndexState* constants. The computation that fills the envelope is in graph/readiness.
  • The query reply envelope. Replies on graph.ingest.query.* are not enveloped.
  • The verb table. QueryVerbs declares the request/reply verbs graph-ingest answers (entity, batch and prefix on graph.ingest.query.*), each with its subject, request type and reply type.
Entity Identification

All entity IDs use the 6-part federated format defined in message.EntityID (canonical order, ADR-102: org.platform = the minting deployment authority, system = the source, domain.type = a delegated taxonomy):

org.platform.system.domain.type.instance

Example: c360.telemetry.mavlink.robotics.drone.42

To parse entity IDs and extract type information:

eid, err := message.ParseEntityID(state.ID)
if err != nil {
    return fmt.Errorf("invalid entity ID: %w", err)
}

entityType := eid.Type      // "drone"
system := eid.System        // "mavlink"
instance := eid.Instance    // "42"

Graphable Interface

The Graphable interface enables domain payloads to self-declare their entities and relationships:

type Graphable interface {
    EntityID() string                  // Returns 6-part federated ID
    Triples() []message.Triple        // Returns all facts about this entity
}

Why it's here: Components implementing graph integration naturally import graph/ to find contracts. This interface defines how payloads transform into graph-compatible data.

Example Implementation
type PositionPayload struct {
    SystemID  uint8   `json:"system_id"`
    Latitude  float64 `json:"latitude"`
    Longitude float64 `json:"longitude"`
    Altitude  float32 `json:"altitude"`
}

func (p *PositionPayload) EntityID() string {
    return fmt.Sprintf("acme.telemetry.robotics.mavlink.drone.%d", p.SystemID)
}

func (p *PositionPayload) Triples() []message.Triple {
    entityID := p.EntityID()
    return []message.Triple{
        {Subject: entityID, Predicate: "geo.location.latitude", Object: p.Latitude},
        {Subject: entityID, Predicate: "geo.location.longitude", Object: p.Longitude},
        {Subject: entityID, Predicate: "geo.location.altitude", Object: p.Altitude},
    }
}

Design Principles

One-Way Transformation

Graphable → EntityState is a one-way transformation at message ingestion time:

  1. Domain payload implements Graphable interface
  2. Graphable.Triples() generates triples at runtime from payload fields
  3. EntityState persists those triples in NATS KV storage
  4. No reverse transformation (storage → payload) is supported or needed
Triple-Based Storage

Properties, relationships, and domain-specific data are all stored as RDF-like triples:

Triple{
    Subject:   "c360.telemetry.robotics.mavlink.drone.42",
    Predicate: "geo.location.latitude",
    Object:    34.052235,
}

This provides maximum flexibility while maintaining semantic clarity.

What is elsewhere

  • graph/kvcatalog: the bucket catalog, its acquisition, the owned-bucket retention check and IsKVTombstone.
  • graph/readiness: the readiness computation and the GRAPH_STATUS publisher.
  • graph/inference: hierarchy inference (its hierarchy slice).

Import

import "github.com/c360studio/semengine/graph"

Documentation

Overview

Package graph provides the canonical graph mutation request/reply contract. Request/reply messages are identified by their typed port and operation subject, so they do not use the polymorphic payload registry.

Package graph provides request/response types for the NATS mutation and query APIs. See mutation_requests.go for the full package documentation.

Package graph provides index query data types for the graph query system.

Package graph provides predicate query data types for the graph query system.

Package graph defines the types and primitives for the SemStreams knowledge graph engine.

Package graph provides graph summary query data types.

Package graph provides types for entity state storage in the graph system.

Index

Constants

View Source
const (
	// Primary entity storage
	BucketEntityStates = "ENTITY_STATES"

	// Graph relationship indexes
	BucketPredicateIndex = "PREDICATE_INDEX"
	BucketIncomingIndex  = "INCOMING_INDEX"
	BucketOutgoingIndex  = "OUTGOING_INDEX"

	// Lookup indexes
	BucketAliasIndex = "ALIAS_INDEX"
	// BucketNameIndex maps a normalized (case-folded) human-readable name/title
	// to the entities carrying it, for deterministic name→ranked-IDs lookup
	// (graph.query.byName, gh#376). Complements ALIAS_INDEX, which excludes
	// display-name (AliasTypeLabel) predicates.
	BucketNameIndex     = "NAME_INDEX"
	BucketSpatialIndex  = "SPATIAL_INDEX"
	BucketTemporalIndex = "TEMPORAL_INDEX"
	// BucketTemporalIndexReverse maps entityID -> current temporal bucket key.
	// It lets graph-index-temporal remove an entity's stale event from its prior
	// time bucket when the entity is re-indexed (observed-time changed) or deleted,
	// so a range query never returns an entity from a bucket it has since left.
	BucketTemporalIndexReverse = "TEMPORAL_INDEX_REVERSE"

	// Semantic tier buckets
	BucketEmbeddingIndex = "EMBEDDING_INDEX"
	BucketEmbeddingDedup = "EMBEDDING_DEDUP"
	BucketCommunityIndex = "COMMUNITY_INDEX"
	// BucketCommunitySummaries holds LLM-generated community summaries, written
	// ONLY by the graph-clustering enhancement worker and keyed by
	// {level}.{membership_hash} (content-addressed). It is deliberately SEPARATE
	// from COMMUNITY_INDEX: the detector owns the partition (COMMUNITY_INDEX),
	// the worker owns the LLM prose (this bucket), so a lagging worker can never
	// clobber a fresher partition or resurrect a Prune-deleted community (ADR-087).
	BucketCommunitySummaries = "COMMUNITY_SUMMARIES"
	BucketAnomalyIndex       = "ANOMALY_INDEX"

	// BucketGraphIngestAppliedSeq is graph-ingest's ADR-072 redelivery-guard
	// durable tier: `(entityID/streamName) → (stream generation, last-applied
	// stream sequence)`.
	// Created and owned exclusively by graph-ingest (processor/graph-ingest);
	// a member of FrameworkOwnedBuckets so a generic rule update_kv cannot forge
	// a sequence stamp and silently reopen the redelivery overwrite the guard
	// closes (framework-owned-bucket-guards F2, #715). It is correctness-critical
	// no-eviction state, so the retention sweep covers it.
	BucketGraphIngestAppliedSeq = "GRAPH_INGEST_APPLIED_SEQ"
	// BucketSemEngineConfig is the PREFIX of the runtime configuration bucket
	// family. Each deployment's bucket is named by its declared authority pair,
	// "semengine_config_<org>_<stem>", derived only by config.BucketName (owner
	// ruling on #1188, 2026-09-01); the bare name is not a member. The family is
	// in the catalog because the framework guarantees BOTH its retention and its
	// write-ownership: since ADR-104 each member holds the create-once platform
	// identity record, which must never be evicted and must never be forged.
	//
	// config.Manager is its only acquirer; processor/rule's ConfigManager writes
	// rules.* through the key family config.Manager serves it. It is still
	// owner-only, because ownership is about who may NOT write. A generic rule
	// update_kv is refused for every key in every member, at load validation,
	// action runtime, and writer acquisition (owner ruling 2026-08-31, #1168
	// comment 5479005060).
	BucketSemEngineConfig = "semengine_config"

	// BucketGraphStatus is the ADR-083 readiness distribution bucket. Producers
	// (graph-index, graph-embedding, graph-ingest, and rule) write their liveness
	// envelope; consumers watch it to answer "(status, fresh|unknown)". It is the
	// single source of truth for the bucket name — graph/readiness re-exports this constant. Its catalog
	// descriptor declares History 3 (readiness replay depth) and no lifecycle
	// retention; the acquisition seam and backstop strip only MaxAge/MaxBytes and
	// leave History untouched.
	BucketGraphStatus = "GRAPH_STATUS"

	// BucketStorageReport is the account storage report
	// (storage-observability): ONE KEY PER INVENTORIED RESOURCE, carrying that
	// resource's attribution, capacity, growth rate, projection, and pressure
	// state, written by the storage collector each collection. Every
	// operator-facing surface reads it rather than recomputing an inventory, so
	// there is one produced truth and no two surfaces can disagree.
	//
	// A resource that disappears from the account has its key DELETED by the
	// collector — a semantic decision, never an expiry — which is why its
	// catalog descriptor declares no-lifecycle retention like the rest of the
	// graph. Its bounded History is the restart-surviving growth series.
	BucketStorageReport = "STORAGE_REPORT"
)

Bucket name constants for NATS KV storage

View Source
const (
	IndexStateBuilding      = "building"
	IndexStateReady         = "ready"
	IndexStateDegraded      = "degraded"
	IndexStateResetRequired = "reset_required"
)

Index readiness states. Mirrors pkg/fusion.IndexState string values.

View Source
const (
	// ErrorCodeRevisionMismatch indicates the request specified an
	// ExpectedRevision that didn't match the entity's current KV
	// revision at the time of write. Callers (notably
	// pkg/lifecycle.Manager.Transition) use this to drive
	// read-validate-retry loops.
	ErrorCodeRevisionMismatch = "revision_mismatch"

	// ErrorCodeEntityNotFound indicates the request targeted an
	// entity ID that does not exist in ENTITY_STATES. For
	// update-style requests this means the entity was never created
	// or was deleted concurrently.
	ErrorCodeEntityNotFound = "entity_not_found"

	// ErrorCodeEntityExists indicates a create-style request hit an
	// entity ID that already exists. Used by entity.create to surface
	// strict-create conflicts.
	ErrorCodeEntityExists = "entity_already_exists"

	// ErrorCodeInvalidRequest indicates the request envelope failed
	// pre-write validation (nil entity, malformed JSON, etc.).
	// Callers should not retry without fixing the request.
	ErrorCodeInvalidRequest = "invalid_request"

	// ErrorCodeStructuralInvalid indicates a token in the mutation violated the
	// structural-identity contract — an entity ID that is not exactly 6 parts, or a
	// predicate that is not exactly 3 parts (domain.category.property). The token is
	// malformed at its source; callers must fix the token, not retry. Emitted by the
	// graph-ingest structural gate when enforcement is on.
	ErrorCodeStructuralInvalid = "structural_invalid"

	// ErrorCodeMessageTypeUnregistered indicates an entity.create stamped a
	// message_type the receiving binary's payload registry does not hold
	// (ADR-103: the registry is the single type authority). Class invalid; the
	// caller registers the type, it does not retry. Detail carries the key under
	// "message_type". Emitted by graph-ingest's registered-type gate on both
	// create paths (the RPC lane and the in-process CreateEntity).
	ErrorCodeMessageTypeUnregistered = "message_type_unregistered"

	// ErrorCodeInternal is the catch-all for handler-internal
	// failures (KV transport errors, unmarshal failures on stored
	// state, etc.). Callers may retry as appropriate.
	ErrorCodeInternal = "internal"

	// ErrorCodeResourceExhausted indicates a query would exceed a server-side read
	// budget — e.g. a byName lookup on a name shared by more entities than the
	// hydration cap (gh#474 Codex P2a interim guard). The caller should narrow the
	// query rather than retry unchanged; the full hot-key NAME redesign is gh#381.
	ErrorCodeResourceExhausted = "resource_exhausted"

	// ErrorCodeIndexNotReady indicates a query arrived while the serving index was not
	// SOUND to read from — the responder or its watcher is unavailable, the index is
	// degraded by an unresolved required write, or it has not finished its initial
	// build. The motivating case is the breaking composite-key format cutover on an
	// in-place upgrade (gh#474 Codex P1d), where old aggregate keys are inert and the
	// new keyset is still materialising: serving it would advertise a smaller graph
	// than exists.
	//
	// NOT emitted for ordinary revision lag (narrowed by ADR-084). A healthy index that
	// is merely behind SERVES, reporting its view age as staleness_ms on the readiness
	// envelope, because coverage was never evidence of soundness and gating on it made
	// every write burst look like a fault (#592). Probe health with
	// `nats kv get GRAPH_STATUS graph-index` and read `state` + `bootstrap_complete` —
	// NOT the `ready` bit, which answers coverage and is false on any busy index.
	//
	// Callers retrying it should retry with backoff against the health question, and a
	// caller that needs "is MY write visible?" should not use this code at all: compare
	// the kv_revision its mutation returned against the envelope's indexed_revision,
	// which is the one sound per-entity check (ADR-084).
	ErrorCodeIndexNotReady = "index_not_ready"

	// ErrorCodeEmbeddingUnavailable indicates a similarity/embedding query targeted
	// a SOURCE entity that has no usable embedding to query FROM — the entity has no
	// embedding record, its embedding is not yet generated (status != generated), or
	// its stored vector is empty. It is a PER-ENTITY miss, NOT a producer-wide index
	// fault: the embedding index itself is sound (contrast ErrorCodeIndexNotReady),
	// this one source entity simply has no vector yet (e.g. an aggregation/group
	// entity never projected through the embedder). Class is ErrorInvalid.
	//
	// Emitted by graph-embedding's handleQuerySimilarNATS. The semantic-edge cache
	// (B2 §7) recognizes it as a definitive "this entity has no semantic neighbors"
	// and fails open to an empty set, distinct from a malformed / unknown reply which
	// it must count toward its coverage-threshold abort rather than cache as a hollow
	// empty (#662 / Codex P1#2). Consumers classify by this stable code, never by the
	// message text.
	ErrorCodeEmbeddingUnavailable = "embedding_unavailable"
)

Stable failure codes carried by *errs.ClassifiedError.Code on the mutation error path (ADR-060). Reached caller-side via errors.As(err, &ce) → ce.Code; revision_mismatch additionally matches the errs.ErrRevisionMismatch sentinel via errors.Is. The set is closed — adding a value requires updating both this declaration and the graph-ingest handler that emits it.

View Source
const (
	// SourceIndexingProfile names the indexing-profile statement graph-ingest
	// stamps at an entity's birth (ADR-054).
	SourceIndexingProfile = "graph-ingest-indexing-profile"
	// SourceHierarchy names the hierarchy statements graph-ingest derives, and
	// the statements of the containers it creates for them.
	SourceHierarchy = "graph-ingest-hierarchy"
	// SourceLifecycle names every statement pkg/lifecycle's manager writes.
	SourceLifecycle = "semengine-lifecycle"
)

The reserved sources: the names graph-ingest and pkg/lifecycle write their own statements under. A stream message may not carry a statement under one of them (graph-entity-writes, "Statement metadata is required"), so no producer on the stream can replace their sets; the mutation lane accepts them, since pkg/lifecycle writes there under its own.

View Source
const DefaultPrefixQueryLimit = 1000

DefaultPrefixQueryLimit is the default number of entities returned per page when the caller does not specify a limit. Matches the server-side default that existed before typed pagination was introduced.

View Source
const ErrorCodeGraphStateResetRequired = "graph_state_reset_required"

ErrorCodeGraphStateResetRequired is the cross-component code for authoritative ENTITY_STATES that cannot be interpreted by the running graph contract.

View Source
const MaxPrefixQueryLimit = DefaultPrefixQueryLimit

MaxPrefixQueryLimit is the maximum number of entities returned per page. The active NATS max_payload ceiling is the binding byte constraint. Graph ingest exactly fits the complete encoded response, including continuation, against the observed connection limit. Callers requesting more than this count are silently clamped.

Variables

AllIndexStates is the closed iteration domain for the one-hot readiness `state` metric published by every producer of the envelope (graph-index, graph-embedding). It lives next to the const block so it is the single source of truth: adding a new readiness state means adding it HERE, and every one-hot state gauge picks it up automatically — otherwise a new state would render as all-zeros (silent "no data", not an alertable signal).

Functions

func ClassifyStateContractError

func ClassifyStateContractError(err error) error

ClassifyStateContractError applies the one cross-component failure shape for incompatible authoritative graph state. Non-contract errors pass through unchanged so callers cannot accidentally promote operational failures.

func DecodeCursor

func DecodeCursor(cursor string) (string, error)

DecodeCursor decodes a cursor token back to its raw key. Returns empty string and no error for the empty-cursor (first-page) case.

func DecodePredicateToken

func DecodePredicateToken(token string) (string, bool)

DecodePredicateToken reverses EncodePredicateToken. Returns (predicate, true) on success, ("", false) when the token is not valid hex (a malformed key token the caller should skip rather than surface as data).

func EncodeCursor

func EncodeCursor(key string) string

EncodeCursor encodes a raw key as an opaque, URL-safe cursor token.

func EncodePredicateToken

func EncodePredicateToken(predicate string) string

EncodePredicateToken hex-encodes a predicate for use as a single key token in the INCOMING / NAME / CONTEXT composite-key reverse indexes (gh#474 Codex P1a).

Canonical predicates are validated before persistence and are NATS-key-safe, but their three semantic segments contain two dots. Encoding the raw predicate in a composite key would consume three physical tokens and change the fixed token positions and arity used by INCOMING / NAME / CONTEXT filters.

Hex (not a hash) is deliberate: it is reversible, so a reader reconstructs the exact predicate from the key with no per-row value lookup — keeping INCOMING a pure prefix key-scan on its hot path. Hex is a fixed-alphabet ([0-9a-f]), dot-free encoding, so an encoded predicate is always exactly one KV-safe token. This is only a physical codec; it provides no compatibility path and does not weaken canonical predicate validation.

Shared here (not in the graph-index package) because graph-clustering and other reverse-index readers reconstruct these keys and must decode with the identical codec.

func IsReservedSource

func IsReservedSource(source string) bool

IsReservedSource reports whether source is one of the reserved sources, compared exactly.

func IsStateContractError

func IsStateContractError(err error) bool

IsStateContractError reports whether err carries the shared authoritative graph-reset contract, either as the in-process typed cause or as the stable classified code reconstructed across request/reply.

func MarshalEntityState

func MarshalEntityState(entity *EntityState) ([]byte, error)

MarshalEntityState is the authoritative in-process ENTITY_STATES persistence seam. It validates the complete final candidate before serialization.

func MatchesAnyIDPrefix

func MatchesAnyIDPrefix(id string, prefixes []string) bool

MatchesAnyIDPrefix reports whether a dot-delimited entity ID falls under any of the given ID prefixes (OR-matched). An empty/nil prefixes slice means "no filter" and matches every ID — the convention already proven by graphrag.filterEntityIDsByType and the []string type-filter surfaces (ADR-071).

Matching is on a dot boundary: id matches prefix p iff id == p or id has the literal prefix p+"." So prefix "c360.semspec.source.doc" matches "c360.semspec.source.doc" and "c360.semspec.source.doc.readme" but NOT "c360.semspec.source.docker.compose" — a prefix must end on a segment boundary, never mid-segment. This mirrors the dot-prefix convention on PrefixQueryRequest (the server appends the trailing dot when it filters), so the deterministic prefix query and the NL scope filter share ONE matcher and their semantics cannot drift.

An empty string element inside a non-empty slice is treated as an explicit match-all (consistent with empty=no-filter), not as "matches only the empty ID".

func UnmarshalEntityState

func UnmarshalEntityState(data []byte, entity *EntityState) error

UnmarshalEntityState is the authoritative decoder for ENTITY_STATES and graph-view consumers. It refuses unreadable or noncanonical stored state.

func UnmarshalEntityStateTrusted

func UnmarshalEntityStateTrusted(data []byte, entity *EntityState) error

UnmarshalEntityStateTrusted decodes stored ENTITY_STATES bytes WITHOUT re-validating the canonical entity-state contract (gh#562).

It exists for exactly one caller class: the ENTITY_STATES OWNER's own read-modify-write reads — graph-ingest's CAS merge and mutation closures. Those bytes were validated by MarshalEntityState when they were written, and every RMW cycle either commits a candidate re-validated by MarshalEntityState or commits nothing at all (no-op cycles exit via sentinel before any KV write). Resident noncanonical state therefore cannot launder through a merge: it survives into the merged candidate and the write gate rejects the whole write. Read-side validation on that lane is redundant for enforcement — it only changes WHERE the failure is reported — while sitting on the per-key-serialized RMW critical path (ADR-072), where it measurably lowers the ingest ceiling.

Every other reader MUST keep UnmarshalEntityState: external and authoritative readers (query handlers, graph-view consumers, index builders, lifecycle manager), poison-detection paths (the ENTITY_STATES contract guard), and any surface exposing decoded state downstream. This decoder does NOT reject noncanonical predicates or identities — that is its contract, not a gap. Malformed JSON returns a plain decode error, not the graph-state-reset classification.

func ValidateDecodedEntityIDs

func ValidateDecodedEntityIDs(entityIDs []string) error

ValidateDecodedEntityIDs validates identity-only authoritative query replies (semantic hits, name matches, and relationship endpoints) as one unit.

func ValidateDecodedEntityState

func ValidateDecodedEntityState(entity *EntityState) error

ValidateDecodedEntityState applies the authoritative graph-state failure contract to an EntityState that was decoded as part of a larger query reply. Aggregate decoders must call this before exposing any candidate downstream.

func ValidateDecodedEntityStatePointers

func ValidateDecodedEntityStatePointers(entities []*EntityState) error

ValidateDecodedEntityStatePointers is the pointer-slice counterpart used by GraphRAG hydration replies. Nil entries are contract violations, not absence: the batch protocol represents absence by omitting an entity.

func ValidateDecodedEntityStates

func ValidateDecodedEntityStates(entities []EntityState) error

ValidateDecodedEntityStates validates an entire value collection before its caller performs any downstream work. The indexed wrapper preserves the contract error for errors.As while identifying which candidate poisoned the reply.

func ValidateEntityPredicates

func ValidateEntityPredicates(entity *EntityState) error

ValidateEntityPredicates validates the complete final EntityState candidate. It returns all unique predicate/reason pairs, sorted deterministically.

func ValidateEntityStateContract

func ValidateEntityStateContract(entity *EntityState) error

ValidateEntityStateContract validates one complete final EntityState candidate. It never fills or rewrites fields; the Graphable fact lane owns its one allowed empty-subject projection convenience before this seam.

Types

type AliasData

type AliasData struct {
	CanonicalID *string `json:"canonical_id"` // nil if not found
}

AliasData contains the canonical entity ID for an alias lookup.

type AppendSubjectResult

type AppendSubjectResult struct {
	EntityID   string           `json:"entity_id"`
	Outcome    MutationOutcome  `json:"outcome"`
	KVRevision uint64           `json:"kv_revision,omitempty"`
	Error      *MutationFailure `json:"error,omitempty"`
}

AppendSubjectResult reports one subject's independent append result. Outcome is the discriminator: failed requires Error; every other outcome forbids it. A failed result is definite; transport ambiguity is never encoded here.

type AppendTriplesRequest

type AppendTriplesRequest struct {
	Triples   []message.Triple `json:"triples"`
	TraceID   string           `json:"trace_id,omitempty"`
	RequestID string           `json:"request_id,omitempty"`
}

AppendTriplesRequest appends canonical tuples independently per subject.

type AppendTriplesResponse

type AppendTriplesResponse struct {
	Results   []AppendSubjectResult `json:"results"`
	TraceID   string                `json:"trace_id,omitempty"`
	RequestID string                `json:"request_id,omitempty"`
}

AppendTriplesResponse reports explicit partial results by distinct subject.

type CompoundPredicateData

type CompoundPredicateData struct {
	Entities []string `json:"entities"`
	Operator string   `json:"operator"`
	Matched  int      `json:"matched"`
}

CompoundPredicateData contains entities matching a compound predicate query.

type CompoundPredicateQuery

type CompoundPredicateQuery struct {
	Predicates []string `json:"predicates"`
	Operator   string   `json:"operator"` // "AND" or "OR"
	Limit      int      `json:"limit,omitempty"`
}

CompoundPredicateQuery represents a query combining multiple predicates.

type CreateEntityRequest

type CreateEntityRequest struct {
	Entity          *EntityState     `json:"entity"`
	Triples         []message.Triple `json:"triples"`
	IndexingProfile string           `json:"indexing_profile,omitempty"`
	TraceID         string           `json:"trace_id,omitempty"`
	RequestID       string           `json:"request_id,omitempty"`
}

CreateEntityRequest atomically creates one entity with its initial facts.

type CreateEntityResponse

type CreateEntityResponse struct {
	Outcome    MutationOutcome `json:"outcome"`
	Entity     *EntityState    `json:"entity"`
	KVRevision uint64          `json:"kv_revision"`
	TraceID    string          `json:"trace_id,omitempty"`
	RequestID  string          `json:"request_id,omitempty"`
}

CreateEntityResponse reports one atomic birth.

type DeleteEntityRequest

type DeleteEntityRequest struct {
	EntityID         string `json:"entity_id"`
	ExpectedRevision uint64 `json:"expected_revision"`
	TraceID          string `json:"trace_id,omitempty"`
	RequestID        string `json:"request_id,omitempty"`
}

DeleteEntityRequest conditionally deletes one entity.

type DeleteEntityResponse

type DeleteEntityResponse struct {
	EntityID         string          `json:"entity_id"`
	Outcome          MutationOutcome `json:"outcome"`
	ExpectedRevision uint64          `json:"expected_revision"`
	TraceID          string          `json:"trace_id,omitempty"`
	RequestID        string          `json:"request_id,omitempty"`
}

DeleteEntityResponse response for entity deletion

type EntityBatchResponse

type EntityBatchResponse struct {
	Entities []EntityState `json:"entities"`
	// Missing names the requested IDs not present in Entities, with a reason each.
	// Omitted entirely when nothing was missing.
	Missing []MissingEntity `json:"missing,omitempty"`
}

EntityBatchResponse is the batch-query reply. Entities keeps its field name and shape, so a consumer reading only `entities` is unaffected; `missing` is additive and omitempty, so a fully-hydrated batch is byte-identical to the pre-ADR-084 response.

type EntityPredicateContractError

type EntityPredicateContractError struct {
	Violations []InvalidEntityPredicate `json:"violations"`
}

EntityPredicateContractError reports every unique invalid predicate in one candidate. Writers must reject the whole candidate when this error is returned.

func (*EntityPredicateContractError) Error

Error implements error with deterministic ordering for logs and tests.

type EntityState

type EntityState struct {
	// ID is the 6-part entity identifier: org.platform.system.domain.type.instance
	// Used as NATS KV key for storage and retrieval.
	ID string `json:"id"`

	// Triples contains all semantic facts about this entity.
	// Properties, relationships, and domain-specific data are all stored as triples.
	Triples []message.Triple `json:"triples"`

	// StorageRef optionally points to where the full original message is stored.
	// Supports "store once, reference anywhere" pattern for large payloads.
	// Nil if message was not stored or storage reference not available.
	StorageRef *message.StorageReference `json:"storage_ref,omitempty"`

	// MessageType records the original message type that created/updated this entity.
	// Provides provenance and enables filtering by message source.
	MessageType message.Type `json:"message_type"`

	// UpdatedAt records when this entity state was last modified.
	UpdatedAt time.Time `json:"updated_at"`
}

EntityState represents complete local graph state for an entity. Triples are the single source of truth for all semantic properties.

The ID field is the 6-part entity identifier (org.platform.system.domain.type.instance) which serves as the NATS KV key for storage and retrieval.

To extract type information from the ID, use message.ParseEntityID():

eid, err := message.ParseEntityID(state.ID)
if err != nil {
    return fmt.Errorf("invalid entity ID: %w", err)
}
entityType := eid.Type

func (*EntityState) Clone

func (es *EntityState) Clone() *EntityState

Clone returns a deep copy of the EntityState. This is used to avoid race conditions when multiple goroutines process the same entity concurrently.

func (*EntityState) GetPropertyValue

func (es *EntityState) GetPropertyValue(predicate string) (any, bool)

GetPropertyValue returns the value for a property by predicate. It checks Triples for a matching predicate and returns the Object value. Returns (value, true) if found, (nil, false) if not found.

func (*EntityState) GetTriple

func (es *EntityState) GetTriple(predicate string) *message.Triple

GetTriple returns one statement of the given predicate, or nil when the entity holds none. A predicate may hold statements from several sources (each source replaces only its own), so the read picks the same way every time: the latest Timestamp; on equal timestamps, the Source that sorts first; on equal sources, the first stored. A reader that wants another choice reads Triples and picks.

type EntityStateContractError

type EntityStateContractError struct {
	Field       EntityStateContractField
	TripleIndex int
	Err         error
}

EntityStateContractError reports the first noncanonical identity-bearing field in a complete EntityState. TripleIndex is -1 for the root ID.

Precedence is root ID, subjects in slice order, explicit references in slice order, then the existing deterministic predicate contract. This keeps error classification stable without echoing rejected identity bytes.

func (*EntityStateContractError) Error

func (e *EntityStateContractError) Error() string

Error implements error without exposing the rejected identity.

func (*EntityStateContractError) Unwrap

func (e *EntityStateContractError) Unwrap() error

Unwrap exposes the canonical entity-ID or object-type cause.

type EntityStateContractField

type EntityStateContractField string

EntityStateContractField identifies the first identity-bearing field that makes a complete EntityState candidate noncanonical.

const (
	// EntityStateContractFieldID is the EntityState.ID root key.
	EntityStateContractFieldID EntityStateContractField = "id"
	// EntityStateContractFieldSubject is a persisted Triple.Subject.
	EntityStateContractFieldSubject EntityStateContractField = "subject"
	// EntityStateContractFieldReference is an explicitly marked @id object.
	EntityStateContractFieldReference EntityStateContractField = "reference"
)

type EntityTypeSummary

type EntityTypeSummary struct {
	// Type is the system.domain.type triple (positions 3-5 of the canonical
	// entity ID, by named field) — the bucket name.
	Type string `json:"type"`

	// Count is how many entities in the scanned sample fall in this
	// bucket. Approximate when EntitySampleTruncated is set on the
	// parent SummaryData.
	Count int `json:"count"`

	// Examples is up to ExamplesPerType real entity IDs from this
	// bucket. The caller uses these as starting points for
	// query_entity / query_relationships without having to invent IDs.
	Examples []string `json:"examples"`
}

EntityTypeSummary represents one entity-type bucket — entities grouped by their 6-part ID's domain.system.type segments (parts 3.4.5 in 1-indexed terms; parts 2-4 in 0-indexed slice terms).

Examples in this codebase:

acme.platform1.agentic-loop.agent.execution.<loopID>
→ type "agent.agentic-loop.execution"

acme.platform1.web.agent.observation.<hash>
→ type "agent.web.observation"

type ExactEntity

type ExactEntity struct {
	Entity     *EntityState `json:"entity"`
	KVRevision uint64       `json:"kvRevision"`
}

ExactEntity is one validated authority value and the revision of the same ENTITY_STATES entry. KVRevision is the entry's only revision: the stored value carries none of its own.

type ExactEntityReader

type ExactEntityReader interface {
	ReadExactEntity(context.Context, string) (*ExactEntity, error)
}

ExactEntityReader is the operation-specific embedded authority-read adapter.

func NewExactEntityReader

func NewExactEntityReader(
	requester interface {
		RequestClassified(context.Context, string, []byte, time.Duration) ([]byte, error)
	},
	timeout time.Duration,
) (ExactEntityReader, error)

NewExactEntityReader constructs the narrow embedded authority-read adapter. It exposes no raw subject, KV handle, or aggregate graph-client capability. A zero timeout means the requester's default; a negative one is refused.

type Graphable

type Graphable interface {
	// EntityID returns deterministic 6-part ID: org.platform.system.domain.type.instance
	EntityID() string

	// Triples returns all facts about this entity
	Triples() []message.Triple
}

Graphable enables messages to self-declare their domain entities and relationships. This interface eliminates the need for brittle string matching in entity extraction by allowing payloads to explicitly state what entities they contain and how those entities relate to each other.

The Graphable pattern addresses a core architectural requirement: messages should contain domain expertise about the entities they represent. Rather than having infrastructure code guess what entities exist based on message types or field names, the message payload itself declares this information.

Design Benefits:

  • Domain Expertise: Payloads contain knowledge about their entities
  • Type Safety: No string matching or reflection-based entity detection
  • Extensibility: New domains simply implement the interface
  • Relationships: Explicit declaration of entity relationships
  • Performance: No need for complex entity detection algorithms
  • Resolution Guidance: Provides hints for entity resolution and merging

Triple-Based Design:

The Graphable interface uses a Triple-based approach where payloads return RDF-like triples (subject, predicate, object) to describe entity properties and relationships. This provides maximum flexibility while remaining simple.

Example Implementation:

type PositionPayload struct {
    SystemID  uint8   `json:"system_id"`
    Latitude  float64 `json:"latitude"`
    Longitude float64 `json:"longitude"`
    Altitude  float32 `json:"altitude"`
}

func (p *PositionPayload) EntityID() string {
    // Return deterministic 6-part ID
    return fmt.Sprintf("acme.telemetry.mavlink.robotics.drone.%d", p.SystemID)
}

func (p *PositionPayload) Triples() []message.Triple {
    entityID := p.EntityID()
    return []message.Triple{
        {Subject: entityID, Predicate: "geo.location.latitude", Object: p.Latitude},
        {Subject: entityID, Predicate: "geo.location.longitude", Object: p.Longitude},
        {Subject: entityID, Predicate: "geo.location.altitude", Object: p.Altitude},
    }
}

Graphable provides entity identification and semantic triples

type IncomingEntry

type IncomingEntry struct {
	FromEntityID string `json:"from_entity_id"`
	Predicate    string `json:"predicate"`
}

IncomingEntry represents a single incoming relationship in the graph.

type IncomingRelationshipsData

type IncomingRelationshipsData struct {
	Relationships []IncomingEntry `json:"relationships"`
}

IncomingRelationshipsData contains incoming relationships for an entity.

type IndexStatusResponse

type IndexStatusResponse struct {
	Ready bool   `json:"ready"` // target>0 && indexed_revision>=target_revision
	State string `json:"state"` // "building" | "ready" | "degraded" | "reset_required"
	// Code and Reason carry bounded operator-actionable fatal readiness state.
	// They are empty during ordinary building/ready/degraded operation.
	Code   string `json:"code,omitempty"`
	Reason string `json:"reason,omitempty"`
	// BootstrapComplete reports whether this producer has finished its INITIAL BUILD
	// in the current process lifetime: enumeration of ENTITY_STATES plus replay up to
	// the enumeration-time target, including the authoritatively-empty 0/0 outcome. It
	// latches true once and resets to false on restart, so a restart into a format
	// cutover re-gates (ADR-084 D2).
	//
	// It exists because health is otherwise not evaluable from the wire: an index
	// halfway through a gh#474 cutover reports State=building with a plausible Lag,
	// indistinguishable from an index that is merely behind. Ready cannot answer it
	// (a caught-up index is bootstrapped, but a bootstrapped index under write is not
	// caught up) and TargetRevision==0 cannot either (it is false during a cutover and
	// wrongly deferred the empty graph).
	//
	// NOT omitempty, and absent reads FALSE — fail closed. An envelope from a
	// pre-ADR-084 producer therefore defers every health gate until the lockstep
	// upgrade lands; that is the accepted migration cost, and the explicit `false` on
	// the wire keeps "old producer" distinguishable from "not yet bootstrapped" in a
	// `nats kv get GRAPH_STATUS <producer>` dump.
	BootstrapComplete bool `json:"bootstrap_complete"`
	// IndexedRevision is the low-water-of-pending watermark: every delivered
	// ENTITY_STATES revision <= this has been applied and nothing <= it is still
	// in flight. A consumer that knows its own target revision can gate on
	// IndexedRevision >= myRev instead of the coarse global Ready bool.
	IndexedRevision uint64 `json:"indexed_revision,omitempty"`
	// TargetRevision is the ENTITY_STATES stream LastSeq read at query time — the
	// latest committed write the index must catch up to.
	TargetRevision uint64 `json:"target_revision,omitempty"`
	// Lag is TargetRevision - IndexedRevision; 0 means caught up.
	Lag uint64 `json:"lag,omitempty"`
	// FailedCount / FailedReasons / FirstFailureAt are the bounded failure detail a
	// producer that tracks per-entity failures carries on a DEGRADED envelope so an
	// operator can tell a whole-dependency outage from a few persistently-failing
	// entities WITHOUT any unbounded per-entity list on the watched key (#613).
	//
	// All three are additive and omitempty: a producer with no failures — including
	// graph-index, which enforces the same rule caller-side via its watermark hole —
	// emits none, so the wire is byte-unchanged. FailedReasons is bounded to a fixed
	// reason enum (a handful of keys), keeping the watched key compact on the hot KV
	// path. FirstFailureAt is RFC3339. FailedCount is echoed from the projection input
	// (in graph-index's revision-lag projection it also drives State=degraded); the
	// other two are set by the producer after the projection.
	FailedCount    uint64            `json:"failed_count,omitempty"`
	FailedReasons  map[string]uint64 `json:"failed_reasons,omitempty"`
	FirstFailureAt string            `json:"first_failure_at,omitempty"`
	// StalenessMs is the AGE OF THE VIEW in milliseconds (ADR-083): now minus the
	// KV commit time of the newest ENTITY_STATES revision the index has fully
	// covered. It is the view-rate consumer's tolerance unit because it is
	// invariant to write rate and coalesce_ms, where a revision count is not
	// (gh#590: the correct revision bound shifted 2-4x with the coalesce dial
	// alone).
	//
	// PRESENCE ENCODING — 0 does NOT mean "zero staleness". It means the value
	// carries no information: either Ready is true (no staleness to report) or the
	// producer could not compute it (nothing covered yet / an early-return hard
	// stop). Any COMPUTED staleness is reported as at least 1ms, so a consumer can
	// treat `StalenessMs > 0` as the presence bit and never read an absent age as
	// "0ms fresh".
	//
	// It is REPORTED, never gating. readiness.EvaluateReadinessGate does not look at
	// this field: readiness withholds an answer only for index health, and how far
	// behind the view is rides on the answer instead (community detection stamps it on
	// staleness_at_detection_ms). A consumer that surfaces it must carry the presence
	// encoding with it — publishing a bare 0 as "caught up" is the one way to turn an
	// unknown age back into a false claim.
	//
	// It is a FLOOR, not an oracle: a revision still undelivered server-side cannot
	// age it. Total stalls surface through the wall-clock stuck detector
	// (State=degraded), not through this field.
	StalenessMs uint64 `json:"staleness_ms,omitempty"`
	// BootstrapScope is the SIZE OF THE INITIAL BUILD this producer latched
	// BootstrapComplete against, expressed in THE PRODUCER'S OWN UNIT — entities for
	// an enumerating producer, messages for a backlog producer, replayed values for a
	// watcher producer. It is deliberately not normalized across producers; a shared
	// unit would be a fiction, and every consumer reads it alongside the key it asked
	// for, so it already knows whose unit it is.
	//
	// It exists for exactly one distinction, which is NOT recoverable from the wire
	// today for any producer: `BootstrapComplete && BootstrapScope == 0` is
	// "authoritatively nothing to do" — the producer finished its initial build and
	// the build was empty — as opposed to "finished a build that had work in it".
	// gh#732 raises this: a consumer waiting for a bootstrap replay cannot otherwise
	// tell an empty-by-truth replay from one it observed too early.
	//
	// THE GATE MUST NOT READ IT. readiness.EvaluateReadinessGate does not look at this
	// field and must never start: the moment a verdict depends on a magnitude, this
	// becomes a threshold knob and readiness stops being a health question (ADR-085 deleted
	// max_staleness for the same reason). A test pins the gate's verdict as identical
	// across two envelopes differing only in this field.
	//
	// IT LICENSES NOTHING ABOUT ABSENCE. Scope 0 says the initial build found nothing
	// to do at the instant it latched — not that the underlying collection is empty,
	// and not that anything published later has been seen.
	BootstrapScope uint64 `json:"bootstrap_scope,omitempty"`
	// PublishedAt is when the producer's publisher wrote this value: UTC, RFC 3339
	// with nanoseconds, from the wall clock. graph/readiness.Publisher.Publish sets
	// it on every write, whatever the caller passed, so no producer can leave it
	// out. It states when the producer wrote, not when anything in the graph was
	// asserted.
	PublishedAt string `json:"published_at"`
}

IndexStatusResponse is the wire shape of the readiness envelope (gh#397, enriched by ADR-066, distributed as GRAPH_STATUS KV state by ADR-083): the deterministic-fusion honesty envelope's readiness signal.

Ready reports COVERAGE: every committed ENTITY_STATES revision <= the query-time target has been applied (revision-lag, ADR-066), not merely "indexing started" (the old sticky NAME_INDEX-non-empty signal that fired minutes before the index was populated, gh#431). It guarantees revision coverage, not last-writer-wins freshness under same-key churn (ADR-066 §1 Scope boundary).

Ready LICENSES NOTHING ABOUT ABSENCE (ADR-084). It once carried an "only Ready permits an authoritative not-found" contract; that is retired, because coverage cannot answer the question — an index caught up to every revision ever committed still knows nothing about a source that never published. No consumer may treat an empty result as an authoritative not-found under ANY envelope state.

Nor does Ready == false withhold a response any more: reads gate on HEALTH (State plus BootstrapComplete), and a healthy index that is merely behind serves while reporting StalenessMs. Under continuous write Ready is false essentially always, which is what made it a poor proxy for soundness. Its remaining jobs are a caught-up fast path for the freshness question, and being the value a caller compares its own revision against via IndexedRevision — the one sound per-entity check.

IndexedRevision is the one spelling of the revision; the pin's phase, revision and last_synced fields are not carried. The readiness computation that fills this envelope is in graph/readiness, so a reader of GRAPH_STATUS needs no NATS import.

type InvalidEntityPredicate

type InvalidEntityPredicate struct {
	Predicate string                               `json:"predicate"`
	Reason    vocabulary.PredicateValidationReason `json:"reason"`
}

InvalidEntityPredicate identifies one unique noncanonical predicate in an EntityState candidate. Predicate values are included for diagnostics; Reason is bounded and safe for metric labels.

type MissingEntity

type MissingEntity struct {
	ID     string        `json:"id"`
	Reason MissingReason `json:"reason"`
}

MissingEntity names one requested ID that is not in the response's entity list.

type MissingReason

type MissingReason string

MissingReason is why one requested ID is absent from a batch response. The set is CLOSED so a consumer can switch on it exhaustively.

const (
	// MissingNotFound is a KV read that returned not-found for the key — the
	// overwhelmingly common case.
	MissingNotFound MissingReason = "not_found"
	// MissingError is a per-ID fault that did not fail the whole call. The first-error
	// contract still stands for READ faults — a non-not-found backend error fails the
	// batch — so the only current emitter is a malformed requested ID (the empty
	// string), which is never looked up at all and therefore cannot honestly be called
	// not_found.
	MissingError MissingReason = "error"
)

The closed missing-reason set.

type MutationFailure

type MutationFailure struct {
	Class string `json:"class"`
	Code  string `json:"code"`
}

MutationFailure carries a definite classified subject-local failure without erasing receipts for other subjects that already committed.

type MutationOutcome

type MutationOutcome string

MutationOutcome is the closed graph-mutation server vocabulary. Transport uncertainty is classified by the typed requester and is never asserted by a server response.

const (
	// MutationApplied reports that the authority entry changed.
	MutationApplied MutationOutcome = "applied"
	// MutationUnchanged reports convergence without a new authority revision.
	MutationUnchanged MutationOutcome = "unchanged"
	// MutationEntityNotFound reports a missing required authority entry.
	MutationEntityNotFound MutationOutcome = "entity_not_found"
	// MutationEntityAlreadyExists reports strict-create conflict.
	MutationEntityAlreadyExists MutationOutcome = "entity_already_exists"
	// MutationRevisionMismatch reports a stale expected authority revision.
	MutationRevisionMismatch MutationOutcome = "revision_mismatch"
	// MutationInvalid reports a structurally invalid request.
	MutationInvalid MutationOutcome = "invalid"
	// MutationFailed reports a classified per-subject append failure.
	MutationFailed MutationOutcome = "failed"
)

type NameData

type NameData struct {
	Matches []NameMatch `json:"matches"`
}

NameData contains the ranked entities for a name lookup. Order IS the ranking: exact-case matches first, then by label-predicate salience, then entity ID.

type NameIndexItem

type NameIndexItem struct {
	EntityID  string `json:"entity_id"`
	Name      string `json:"name"`      // original-case name as stored on the entity
	Predicate string `json:"predicate"` // the label predicate carrying it
	Priority  int    `json:"priority"`  // label-predicate salience (lower = higher)
}

NameIndexItem is one entity's claim on a name, stored in NAME_INDEX.

type NameMatch

type NameMatch struct {
	// EntityID is the matched entity (an opaque handle for the caller).
	EntityID string `json:"entity_id"`
	// MatchedName is the name as stored on the entity (original case).
	MatchedName string `json:"matched_name"`
	// Predicate is the label predicate that carried the name (e.g. dc.terms.title).
	Predicate string `json:"predicate"`
	// ExactCase is true when MatchedName equals the query verbatim (case included);
	// such matches rank above case-folded-only matches.
	ExactCase bool `json:"exact_case"`
}

NameMatch is one entity whose name/title matched a graph.query.byName lookup, carrying the signals a deterministic caller needs to calibrate trust (gh#376).

type OutgoingEntry

type OutgoingEntry struct {
	ToEntityID string `json:"to_entity_id"`
	Predicate  string `json:"predicate"`
}

OutgoingEntry represents a single outgoing relationship in the graph.

type OutgoingRelationshipsData

type OutgoingRelationshipsData struct {
	Relationships []OutgoingEntry `json:"relationships"`
}

OutgoingRelationshipsData contains outgoing relationships for an entity.

type PredicateData

type PredicateData struct {
	Entities []string `json:"entities"`
}

PredicateData contains entities that have a specific predicate.

type PredicateListData

type PredicateListData struct {
	Predicates []PredicateSummary `json:"predicates"`
	Total      int                `json:"total"`
}

PredicateListData contains all predicates with their entity counts.

type PredicateListQuery

type PredicateListQuery struct {
	Namespace string `json:"namespace,omitempty"`
}

PredicateListQuery is the request for graph.index.query.predicateList. Namespace, when set, scopes the listing to one exact domain or domain.category namespace (for example, "inferred.semantic" matches "inferred.semantic.high"). Omitted or empty means "list every predicate" (ADR-065).

type PredicateStatsData

type PredicateStatsData struct {
	Predicate      string   `json:"predicate"`
	EntityCount    int      `json:"entity_count"`
	SampleEntities []string `json:"sample_entities"`
}

PredicateStatsData contains detailed statistics for a single predicate.

type PredicateSummary

type PredicateSummary struct {
	Predicate   string `json:"predicate"`
	EntityCount int    `json:"entity_count"`
}

PredicateSummary represents a predicate with its entity count.

type PrefixQueryRequest

type PrefixQueryRequest struct {
	// Prefix is a dot-delimited entity-ID prefix (e.g. "acme.ops.robotics").
	// Empty string matches all entities when Pattern is also empty. Do NOT
	// include a trailing dot — the server appends it automatically when
	// filtering. Mutually exclusive with Pattern.
	Prefix string `json:"prefix"`

	// Pattern is an optional exact six-position entity-ID pattern in ADR-102
	// canonical order where any position may be "*". Mutually exclusive with
	// Prefix. Example: "acme.ops.*.intel.platform.*".
	Pattern string `json:"pattern,omitempty"`

	// Limit is the maximum number of entities to return on this page.
	// <=0 means "use server default". Clamped to MaxPrefixQueryLimit.
	Limit int `json:"limit,omitempty"`

	// Cursor is the opaque page-continuation token from a previous response.
	// Leave empty to request the first page.
	Cursor string `json:"cursor,omitempty"`
}

PrefixQueryRequest is the typed request envelope for graph.query.prefix.

Cursor contract (OPAQUE):

  • First page: leave Cursor empty.
  • Subsequent pages: pass back the NextCursor value VERBATIM from the previous PrefixQueryResponse. Consumers MUST NOT parse, construct, or modify cursor values — the encoding may change between server versions.
  • Empty NextCursor in the response means the result set is exhausted.

Limit semantics:

  • <=0 → server applies DefaultPrefixQueryLimit.
  • Values above MaxPrefixQueryLimit are clamped to MaxPrefixQueryLimit.
  • Even within the limit, the server may return fewer entities when the complete encoded response reaches the active NATS max_payload ceiling. In that case NextCursor is set so the caller can fetch the remainder.

V1 pagination caveat (keyset semantics):

  • The server sorts matching keys lexicographically and uses the last returned key as the page boundary. Entities whose IDs sort before the cursor position and that are inserted between page fetches will not appear on later pages — standard keyset behaviour.

Backend note (informational, subject to change):

  • NATS KV has no ranged scan; the server fetches ALL keys matching the prefix, sorts them, then slices the requested page. Large namespaces therefore incur a full key scan on every request.

type PrefixQueryResponse

type PrefixQueryResponse struct {
	// Entities is the full EntityState slice for this page.
	Entities []EntityState `json:"entities"`

	// NextCursor is the opaque continuation token; empty = exhausted.
	NextCursor string `json:"next_cursor,omitempty"`
}

PrefixQueryResponse is the typed response envelope for graph.query.prefix.

Entities contains the full EntityState values for this page, triples included. SemOps depends on full values being present so that downstream consumers do not need additional N+1 fetches.

NextCursor is the opaque token to pass as PrefixQueryRequest.Cursor on the next call. An empty NextCursor means the result set is exhausted, and the field is omitted from the JSON output.

type Provider

type Provider interface {
	// GetAllEntityIDs returns all entity IDs in the graph.
	GetAllEntityIDs(ctx context.Context) ([]string, error)

	// GetNeighbors returns the entity IDs connected to the given entity.
	// direction: "outgoing", "incoming", or "both"
	GetNeighbors(ctx context.Context, entityID string, direction string) ([]string, error)

	// GetEdgeWeight returns the weight of the edge between two entities.
	// Returns 1.0 if edge exists but has no weight, 0.0 if no edge exists.
	GetEdgeWeight(ctx context.Context, fromID, toID string) (float64, error)
}

Provider abstracts the graph data source for algorithms. Used by clustering, structural indexing, and other graph operations.

type QueryVerb

type QueryVerb struct {
	// Name is the verb, the last token of its subject.
	Name    string
	Subject string
	// Responder is the component type that answers on Subject.
	Responder string
	// RequestType is the request's Go type, or its JSON fields as
	// {field:type} when it has no named type.
	RequestType string
	// ReplyType is the reply's Go type.
	ReplyType string
}

QueryVerb declares one request/reply verb: the subject it is served on, the component that answers it, and the shapes of its request and its reply.

func QueryVerbs

func QueryVerbs() []QueryVerb

QueryVerbs returns the declared request/reply verbs. Each call returns a new slice, so a caller cannot change the declaration.

type ReconcilePredicatesRequest

type ReconcilePredicatesRequest struct {
	EntityID         string           `json:"entity_id"`
	ExpectedRevision uint64           `json:"expected_revision"`
	Source           string           `json:"source"`
	Predicates       []string         `json:"predicates"`
	Desired          []message.Triple `json:"desired"`
	TraceID          string           `json:"trace_id,omitempty"`
	RequestID        string           `json:"request_id,omitempty"`
}

ReconcilePredicatesRequest makes the statements of the named predicates from Source equal Desired on one existing entity at ExpectedRevision; the same predicates' statements from other sources stay. Desired may be empty, which clears Source's statements of them. Source is required, and every desired statement's Source must equal it (graph-entity-writes, "One rule per write mode"); graph-ingest refuses the request as invalid_request otherwise.

type ReconcilePredicatesResponse

type ReconcilePredicatesResponse struct {
	Outcome    MutationOutcome `json:"outcome"`
	Entity     *EntityState    `json:"entity"`
	KVRevision uint64          `json:"kv_revision"`
	TraceID    string          `json:"trace_id,omitempty"`
	RequestID  string          `json:"request_id,omitempty"`
}

ReconcilePredicatesResponse reports the exact current or committed entity.

type ReplaceResult

type ReplaceResult struct {
	Triples []message.Triple
	Stale   []StaleSet
}

ReplaceResult is what ReplaceBySource leaves: the statements to store, and each arriving set it did not apply.

func ReplaceBySource

func ReplaceBySource(stored, arrival []message.Triple) ReplaceResult

ReplaceBySource is the replace write mode (graph-entity-writes, "One rule per write mode" and "Timestamp orders a replace"). The statements of one (subject, predicate, source) are one set: each set the arrival carries replaces the stored set of the same key whole, and the statements of the same predicate from every other source stay. A set whose latest Timestamp is older than the latest Timestamp of the stored set of its key is not applied and is named in Stale; equal timestamps apply. Confidence and Context never decide. Stored statements of keys the arrival does not carry are kept in their order, ahead of the arrival's applied sets. An applied set keeps a statement the arrival repeats equal in every field once, the first in arrival order (see keyOfStatement for what equal means).

type StaleSet

type StaleSet struct {
	Subject   string
	Predicate string
	Source    string
}

StaleSet names one (subject, predicate, source) set of an arrival that ReplaceBySource did not apply because it was older than the stored set.

type StateContractError

type StateContractError struct {
	Reason   StateResetReason `json:"reason"`
	EntityID string           `json:"entity_id,omitempty"`
	Err      error            `json:"-"`
}

StateContractError means the authoritative graph cannot be safely read or projected. Recovery is reader-class-conditional: the authoritative read surface (graph-ingest's query lanes) scopes refusal to the poisoned entity and recovers as soon as operators repair the stored bytes (delete + recreate through canonical writes) — no restart required. Projection owners (derived views built from watched or replayed entity state) stay in sticky reset-required state and recover only by operator reset and process restart.

EntityID names the poisoned entity when the classification site knows it (snapshot sweep entry key, queried entity ID, RMW target, mutation read seam). It is additive and in-process only: the wire carries just the error class and code, so consumers reconstructing the classification from headers never see it. Err is excluded from JSON on purpose (error values do not marshal usefully); the rendered Error() string is the transport for detail.

func (*StateContractError) Error

func (e *StateContractError) Error() string

Error implements error.

func (*StateContractError) Unwrap

func (e *StateContractError) Unwrap() error

Unwrap exposes the structural or JSON cause.

type StateResetReason

type StateResetReason string

StateResetReason is a bounded machine-readable reset cause.

const (
	// GraphStateReasonUnreadableEntity means authoritative JSON cannot decode.
	GraphStateReasonUnreadableEntity StateResetReason = "unreadable_entity_state"
	// GraphStateReasonNoncanonicalPredicate means stored state violates the predicate grammar.
	GraphStateReasonNoncanonicalPredicate StateResetReason = "noncanonical_predicate"
	// GraphStateReasonNoncanonicalEntityID means the stored entity ID, a triple
	// subject, or an explicitly marked entity reference violates the canonical
	// entity identity contract.
	GraphStateReasonNoncanonicalEntityID StateResetReason = "noncanonical_entity_id"
	// GraphStateReasonMissingStatementMetadata means a stored statement has no Source or no Timestamp, which every
	// stored statement carries (ADR-110 Decision 5).
	GraphStateReasonMissingStatementMetadata StateResetReason = "missing_statement_metadata"
)

type SummaryData

type SummaryData struct {
	// TotalEntities is the count of entities actually scanned (= sum
	// of EntityTypes counts). When EntitySampleTruncated is true,
	// the underlying graph holds more than this.
	TotalEntities int `json:"total_entities"`

	// EntitySampleTruncated is true when the entity scan hit
	// EntitySampleLimit before draining the bucket. The TotalEntities
	// and per-type counts are then approximate.
	EntitySampleTruncated bool `json:"entity_sample_truncated"`

	// EntityTypes is the sorted (highest-count-first) list of type
	// buckets discovered in the scanned sample.
	EntityTypes []EntityTypeSummary `json:"entity_types"`

	// Predicates is populated when IncludePredicates is true (default).
	// Each entry mirrors PredicateSummary — predicate name + the
	// entity count from the predicate index. Counts here are exact
	// (the predicate index maintains them at write time); they do
	// NOT inherit the entity-scan truncation.
	Predicates []PredicateSummary `json:"predicates,omitempty"`

	// PredicateTotal is len(Predicates). Convenience for callers
	// formatting "N predicates registered" lines.
	PredicateTotal int `json:"predicate_total,omitempty"`
}

SummaryData is the composite response. Caller-friendly text formatting happens at the tool-wrapper layer (agent tools / future MCP); this shape stays structured for non-LLM consumers (dashboards, audit, programmatic clients).

type SummaryRequest

type SummaryRequest struct {
	// IncludePredicates toggles the predicate counts section.
	// Defaults to true. Setting false is useful when the caller
	// already has the predicate list cached or when the response
	// would otherwise exceed the gateway's body budget at large
	// scales.
	IncludePredicates bool `json:"include_predicates"`

	// EntitySampleLimit caps how many entity IDs the type-distribution
	// aggregation walks. Defaults to 2000. The resulting type counts
	// are approximate when the scan is truncated; the response sets
	// EntitySampleTruncated=true and TotalEntities reflects what was
	// scanned, not what the graph holds. V2 candidates: write-time
	// type-count index for exact counts.
	EntitySampleLimit int `json:"entity_sample_limit"`

	// ExamplesPerType caps how many sample entity IDs to retain per
	// type bucket in the response. Defaults to 2. Example IDs are
	// load-bearing for the discovery use case (semspec's bug log
	// confirms models invent IDs when no examples are provided);
	// keep this >= 1.
	ExamplesPerType int `json:"examples_per_type"`
}

SummaryRequest is the request shape for the graph summary query. Both fields are optional with sensible V1 defaults.

Directories

Path Synopsis
Package inference derives an entity's hierarchy statements from its 6-part ID (org.platform.system.domain.type.instance, ADR-102).
Package inference derives an entity's hierarchy statements from its 6-part ID (org.platform.system.domain.type.instance, ADR-102).
Package kvcatalog is the POPULATION half of the framework KV bucket catalog (framework-bucket-catalog): the ONE literal table of every KV bucket whose write-ownership or retention the framework guarantees, and its acquisition.
Package kvcatalog is the POPULATION half of the framework KV bucket catalog (framework-bucket-catalog): the ONE literal table of every KV bucket whose write-ownership or retention the framework guarantees, and its acquisition.
Package readiness owns BOTH sides of the ADR-083 readiness distribution contract.
Package readiness owns BOTH sides of the ADR-083 readiness distribution contract.

Jump to

Keyboard shortcuts

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