ontology

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MetaValidFrom  = "_valid_from"  // RFC3339 — fact validity start (empty = epoch)
	MetaValidTo    = "_valid_to"    // RFC3339 — fact validity end (empty = still valid)
	MetaRecordedAt = "_recorded_at" // RFC3339 — system time when triple was first recorded
	MetaRecordedBy = "_recorded_by" // who recorded (agent ID, "human", peer DID)
	MetaSource     = "_source"      // origin category for source precedence
	MetaConfidence = "_confidence"  // "0.0000" ~ "1.0000"
)

Reserved metadata keys for temporal and provenance fields. These live in graph.Triple.Metadata (prefix "_" to avoid collision with user properties).

View Source
const P2PConfidenceScale = 0.8

P2PConfidenceScale caps effective confidence for P2P facts (max 80%).

Variables

View Source
var ErrPermissionDenied = errors.New("ontology: permission denied")

ErrPermissionDenied is returned when a principal lacks the required permission.

View Source
var SourcePrecedence = map[string]int{
	"manual":         10,
	"knowledge":      8,
	"correction":     7,
	"llm_extraction": 4,
	"graph_engine":   3,
	"memory_hook":    2,
	"p2p_exchange":   1,
}

SourcePrecedence defines priority ordering for source-of-truth auto-resolution. Higher value = higher priority. Used by TruthMaintainer.canAutoResolve. immutable after init — do not modify at runtime.

Functions

func BuildTools

func BuildTools(svc OntologyService, reg *ActionRegistry) []*agent.Tool

BuildTools creates agent-facing tools for ontology management and data ingestion. When reg is non-nil, dynamic tools are generated for each registered action.

func ComputeDigest

func ComputeDigest(types []SchemaTypeSlim, predicates []SchemaPredicateSlim) string

ComputeDigest produces a SHA256 hex string from the canonical JSON of types and predicates. Types and predicates are sorted by name for order independence.

func SeedDefaults

func SeedDefaults(ctx context.Context, svc OntologyService) error

SeedDefaults registers the existing 9 predicates and 6 node types into the ontology registry. Idempotent — skips entries that already exist.

Types

type ACLPolicy

type ACLPolicy interface {
	Check(principal string, required Permission) error
}

ACLPolicy checks whether a principal has the required permission.

type ActionEffects

type ActionEffects struct {
	FactsAsserted  []FactEffect     `json:"factsAsserted,omitempty"`
	FactsRetracted []FactRetraction `json:"factsRetracted,omitempty"`
	PropertiesSet  []PropertyEffect `json:"propertiesSet,omitempty"`
}

ActionEffects captures the side effects produced by an action's Execute phase.

type ActionExecutor

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

ActionExecutor orchestrates action execution with ACL, preconditions, logging, and compensation.

func NewActionExecutor

func NewActionExecutor(svc OntologyService, reg *ActionRegistry, acl ACLPolicy, logStore *ActionLogStore) *ActionExecutor

NewActionExecutor creates a new ActionExecutor.

func (*ActionExecutor) Execute

func (e *ActionExecutor) Execute(ctx context.Context, actionName string, params map[string]string) (*ActionResult, error)

Execute runs the named action through the full lifecycle: ACL check → Precondition → Log(started) → Execute → Log(completed/failed/compensated).

type ActionLogEntry

type ActionLogEntry struct {
	ID          uuid.UUID         `json:"id"`
	ActionName  string            `json:"actionName"`
	Principal   string            `json:"principal"`
	Params      map[string]string `json:"params"`
	Status      ActionStatus      `json:"status"`
	Effects     *ActionEffects    `json:"effects,omitempty"`
	Error       string            `json:"error,omitempty"`
	StartedAt   time.Time         `json:"startedAt"`
	CompletedAt *time.Time        `json:"completedAt,omitempty"`
}

ActionLogEntry represents a persisted action execution record.

type ActionLogStore

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

ActionLogStore provides Ent-backed CRUD for action execution records.

func NewActionLogStore

func NewActionLogStore(client *ent.Client) *ActionLogStore

NewActionLogStore creates a new ActionLogStore.

func (*ActionLogStore) Compensated

func (s *ActionLogStore) Compensated(ctx context.Context, id uuid.UUID) error

Compensated updates an action log to "compensated".

func (*ActionLogStore) Complete

func (s *ActionLogStore) Complete(ctx context.Context, id uuid.UUID, effects *ActionEffects) error

Complete updates an action log to "completed" with effects.

func (*ActionLogStore) Create

func (s *ActionLogStore) Create(ctx context.Context, actionName, principal string, params map[string]string) (uuid.UUID, error)

Create inserts a new action log with status "started".

func (*ActionLogStore) Fail

func (s *ActionLogStore) Fail(ctx context.Context, id uuid.UUID, errMsg string) error

Fail updates an action log to "failed" with error message.

func (*ActionLogStore) Get

Get retrieves a single action log by ID.

func (*ActionLogStore) List

func (s *ActionLogStore) List(ctx context.Context, actionName string, limit int) ([]ActionLogEntry, error)

List retrieves action logs filtered by action name, ordered by started_at desc.

type ActionRegistry

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

ActionRegistry stores registered ActionTypes by name.

func NewActionRegistry

func NewActionRegistry() *ActionRegistry

NewActionRegistry creates a new empty ActionRegistry.

func (*ActionRegistry) Get

func (r *ActionRegistry) Get(name string) (*ActionType, bool)

Get retrieves an ActionType by name.

func (*ActionRegistry) List

func (r *ActionRegistry) List() []*ActionType

List returns all registered ActionTypes.

func (*ActionRegistry) Register

func (r *ActionRegistry) Register(a *ActionType) error

Register adds an ActionType to the registry. Returns error if name is duplicate.

type ActionResult

type ActionResult struct {
	LogID   uuid.UUID      `json:"logID"`
	Status  ActionStatus   `json:"status"`
	Effects *ActionEffects `json:"effects,omitempty"`
	Error   string         `json:"error,omitempty"`
}

ActionResult is the outcome of executing an action.

type ActionStatus

type ActionStatus string

ActionStatus represents the execution state of an action.

const (
	ActionStarted     ActionStatus = "started"
	ActionCompleted   ActionStatus = "completed"
	ActionFailed      ActionStatus = "failed"
	ActionCompensated ActionStatus = "compensated"
)

type ActionSummary

type ActionSummary struct {
	Name         string            `json:"name"`
	Description  string            `json:"description"`
	RequiredPerm Permission        `json:"requiredPerm"`
	ParamSchema  map[string]string `json:"paramSchema"`
}

ActionSummary provides metadata about a registered action (for listing).

type ActionType

type ActionType struct {
	Name        string
	Description string
	// RequiredPerm is the permission the executor checks before running.
	// INVARIANT: must be >= max permission of any OntologyService method
	// called by Execute or Compensate. Violating this causes "executor
	// passed but service rejected" partial failures.
	RequiredPerm Permission
	// ParamSchema maps parameter names to descriptions (used for tool generation).
	ParamSchema map[string]string
	// Precondition validates whether the action can be executed.
	// Returns nil if preconditions are met.
	Precondition func(ctx context.Context, svc OntologyService, params map[string]string) error
	// Execute performs the action and returns its effects.
	Execute func(ctx context.Context, svc OntologyService, params map[string]string) (*ActionEffects, error)
	// Compensate reverses the effects on Execute failure. May be nil.
	Compensate func(ctx context.Context, svc OntologyService, effects *ActionEffects) error
}

ActionType defines a reusable transactional operation on the ontology. ActionTypes are in-process Go closures registered at startup — NOT persisted DSL.

func BuiltinLinkEntities

func BuiltinLinkEntities() *ActionType

BuiltinLinkEntities returns an action that asserts a fact between two entities.

func BuiltinSetEntityStatus

func BuiltinSetEntityStatus() *ActionType

BuiltinSetEntityStatus returns an action that sets an entity's status property.

type AliasStore

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

AliasStore provides Ent-backed CRUD for entity aliases.

func NewAliasStore

func NewAliasStore(client *ent.Client) *AliasStore

NewAliasStore creates an AliasStore backed by the given Ent client.

func (*AliasStore) ListByCanonical

func (s *AliasStore) ListByCanonical(ctx context.Context, canonicalID string) ([]string, error)

ListByCanonical returns all raw IDs that map to the given canonical ID.

func (*AliasStore) Register

func (s *AliasStore) Register(ctx context.Context, rawID, canonicalID, source string) error

Register creates or updates an alias mapping from rawID to canonicalID.

func (*AliasStore) Remove

func (s *AliasStore) Remove(ctx context.Context, rawID string) error

Remove deletes an alias for a raw ID (used by Split).

func (*AliasStore) Resolve

func (s *AliasStore) Resolve(ctx context.Context, rawID string) (string, error)

Resolve returns the canonical ID for a raw ID. If no alias exists, returns rawID unchanged.

type AllowAllPolicy

type AllowAllPolicy struct{}

AllowAllPolicy permits every operation. Used as the default when ACL is disabled.

func (AllowAllPolicy) Check

type AssertionInput

type AssertionInput struct {
	Triple     graph.Triple
	Source     string    // origin category (key in SourcePrecedence)
	Confidence float64   // 0.0–1.0
	ValidFrom  time.Time // zero = now
}

AssertionInput carries a triple plus provenance metadata for fact assertion.

type AssertionResult

type AssertionResult struct {
	Stored     bool
	ConflictID *uuid.UUID // non-nil when a conflict was created
	Message    string
}

AssertionResult reports the outcome of an AssertFact call.

type CandidateTriple

type CandidateTriple struct {
	Subject    string `json:"subject"`
	Object     string `json:"object"`
	Source     string `json:"source"`
	Confidence string `json:"confidence"`
	RecordedAt string `json:"recorded_at"`
}

CandidateTriple is a serializable snapshot of a triple involved in a conflict.

type Cardinality

type Cardinality string

Cardinality defines the relationship multiplicity between subject and object types.

const (
	OneToOne   Cardinality = "one_to_one"
	OneToMany  Cardinality = "one_to_many"
	ManyToOne  Cardinality = "many_to_one"
	ManyToMany Cardinality = "many_to_many"
)

type Conflict

type Conflict struct {
	ID         uuid.UUID
	Subject    string
	Predicate  string
	Candidates []CandidateTriple
	Status     ConflictStatus
	ResolvedAt *time.Time
	Resolution string
	CreatedAt  time.Time
}

Conflict represents a detected contradiction between triples.

type ConflictStatus

type ConflictStatus string

ConflictStatus represents the lifecycle state of an ontology conflict.

const (
	ConflictOpen         ConflictStatus = "open"
	ConflictResolved     ConflictStatus = "resolved"
	ConflictAutoResolved ConflictStatus = "auto_resolved"
)

type ConflictStore

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

ConflictStore provides Ent-backed CRUD for ontology conflicts.

func NewConflictStore

func NewConflictStore(client *ent.Client) *ConflictStore

NewConflictStore creates a ConflictStore backed by the given Ent client.

func (*ConflictStore) Create

func (s *ConflictStore) Create(ctx context.Context, c Conflict) (*Conflict, error)

Create persists a new conflict record.

func (*ConflictStore) Delete

func (s *ConflictStore) Delete(ctx context.Context, id uuid.UUID) error

Delete removes a conflict record (for reconciliation cleanup).

func (*ConflictStore) Get

func (s *ConflictStore) Get(ctx context.Context, id uuid.UUID) (*Conflict, error)

Get retrieves a conflict by ID.

func (*ConflictStore) ListBySubjectPredicate

func (s *ConflictStore) ListBySubjectPredicate(ctx context.Context, subject, predicate string) ([]Conflict, error)

ListBySubjectPredicate returns conflicts matching subject and predicate.

func (*ConflictStore) ListOpen

func (s *ConflictStore) ListOpen(ctx context.Context) ([]Conflict, error)

ListOpen returns all conflicts with status "open".

func (*ConflictStore) Resolve

func (s *ConflictStore) Resolve(ctx context.Context, id uuid.UUID, resolution string) error

Resolve marks a conflict as resolved with a reason.

type Constraint

type Constraint struct {
	Kind  ConstraintKind `json:"kind"`
	Value string         `json:"value"`
}

Constraint defines a validation rule for a property.

type ConstraintKind

type ConstraintKind string

ConstraintKind identifies the type of validation constraint.

const (
	ConstraintMin   ConstraintKind = "min"
	ConstraintMax   ConstraintKind = "max"
	ConstraintEnum  ConstraintKind = "enum"
	ConstraintRegex ConstraintKind = "regex"
)

type EntRegistry

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

EntRegistry implements Registry backed by Ent ORM (SQLite).

func NewEntRegistry

func NewEntRegistry(client *ent.Client) *EntRegistry

NewEntRegistry creates a new Ent-backed registry.

func (*EntRegistry) DeprecatePredicate

func (r *EntRegistry) DeprecatePredicate(ctx context.Context, name string) error

func (*EntRegistry) DeprecateType

func (r *EntRegistry) DeprecateType(ctx context.Context, name string) error

func (*EntRegistry) GetPredicate

func (r *EntRegistry) GetPredicate(ctx context.Context, name string) (*PredicateDefinition, error)

func (*EntRegistry) GetType

func (r *EntRegistry) GetType(ctx context.Context, name string) (*ObjectType, error)

func (*EntRegistry) ListPredicates

func (r *EntRegistry) ListPredicates(ctx context.Context) ([]PredicateDefinition, error)

func (*EntRegistry) ListTypes

func (r *EntRegistry) ListTypes(ctx context.Context) ([]ObjectType, error)

func (*EntRegistry) RegisterPredicate

func (r *EntRegistry) RegisterPredicate(ctx context.Context, p PredicateDefinition) error

func (*EntRegistry) RegisterType

func (r *EntRegistry) RegisterType(ctx context.Context, t ObjectType) error

func (*EntRegistry) UpdatePredicateStatus

func (r *EntRegistry) UpdatePredicateStatus(ctx context.Context, name string, status SchemaStatus) error

func (*EntRegistry) UpdateTypeStatus

func (r *EntRegistry) UpdateTypeStatus(ctx context.Context, name string, status SchemaStatus) error

type EntityResolver

type EntityResolver interface {
	// Resolve returns the canonical ID for a raw ID. If no alias exists, returns rawID unchanged.
	Resolve(ctx context.Context, rawID string) (string, error)

	// RegisterAlias creates a mapping from rawID to canonicalID.
	RegisterAlias(ctx context.Context, rawID, canonicalID, source string) error

	// DeclareSameAs declares that nodeA and nodeB refer to the same entity.
	// The canonical is chosen by source precedence; ties go to the first-created alias.
	DeclareSameAs(ctx context.Context, nodeA, nodeB, source string) error

	// Merge moves all relationships from duplicate to canonical and retracts the originals.
	// Order: snapshot → replicate → retract → alias (last, to avoid mid-merge canonicalization).
	Merge(ctx context.Context, canonical, duplicate string) (*MergeResult, error)

	// Split removes the alias for splitOut from canonical. Relationship restoration is manual.
	Split(ctx context.Context, canonical, splitOut string) error

	// Aliases returns all raw IDs that map to canonicalID.
	Aliases(ctx context.Context, canonicalID string) ([]string, error)
}

EntityResolver manages entity identity — aliases, canonicalization, merge/split.

func NewEntityResolver

func NewEntityResolver(as *AliasStore, store graph.Store, tm TruthMaintainer) EntityResolver

NewEntityResolver creates an EntityResolver backed by the given stores.

type EntityResult

type EntityResult struct {
	EntityID   string            `json:"entityId"`
	EntityType string            `json:"entityType"`
	Properties map[string]string `json:"properties"`
	Outgoing   []ResultTriple    `json:"outgoing,omitempty"` // subject=entityID
	Incoming   []ResultTriple    `json:"incoming,omitempty"` // object=entityID
}

EntityResult combines an entity's properties with its graph relationships.

type FactEffect

type FactEffect struct {
	Subject   string `json:"subject"`
	Predicate string `json:"predicate"`
	Object    string `json:"object"`
}

FactEffect records a fact that was asserted by an action.

type FactRetraction

type FactRetraction struct {
	Subject   string `json:"subject"`
	Predicate string `json:"predicate"`
	Object    string `json:"object"`
	Reason    string `json:"reason"`
}

FactRetraction records a fact that was retracted by an action.

type FilterOp

type FilterOp string

FilterOp defines comparison operators for property queries.

const (
	FilterEq       FilterOp = "eq"       // exact match
	FilterNeq      FilterOp = "neq"      // not equal
	FilterContains FilterOp = "contains" // substring match
)

type GovernanceEngine

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

GovernanceEngine manages schema lifecycle FSM and rate limiting. Type/predicate agnostic — FSM rules and rate limits apply equally.

func NewGovernanceEngine

func NewGovernanceEngine(policy GovernancePolicy) *GovernanceEngine

NewGovernanceEngine creates a GovernanceEngine with the given policy.

func (*GovernanceEngine) CheckRateLimit

func (g *GovernanceEngine) CheckRateLimit(_ context.Context) error

CheckRateLimit enforces the daily proposal limit (type + predicate combined).

func (*GovernanceEngine) SchemaHealth

func (g *GovernanceEngine) SchemaHealth(ctx context.Context, registry Registry) (*SchemaHealthReport, error)

SchemaHealth returns status counts for types and predicates.

func (*GovernanceEngine) TypeUsage

func (g *GovernanceEngine) TypeUsage(ctx context.Context, registry Registry, typeName string) (*TypeUsageInfo, error)

TypeUsage returns basic info about a type's status and age. Full usage counting (triple/property counts) is deferred to a future observability change.

func (*GovernanceEngine) ValidateTransition

func (g *GovernanceEngine) ValidateTransition(from, to SchemaStatus) error

ValidateTransition checks whether a transition from → to is allowed by the FSM.

type GovernancePolicy

type GovernancePolicy struct {
	MaxNewPerDay          int // combined daily limit for type + predicate proposals
	QuarantinePeriodHrs   int
	ShadowModeDurationHrs int
	MinUsageForPromotion  int
	SchemaExplosionBudget int // per month, type + predicate combined
}

GovernancePolicy configures schema lifecycle governance.

type ImportMode

type ImportMode string

ImportMode determines how imported schema elements are treated.

const (
	ImportShadow   ImportMode = "shadow"   // default: import as shadow status
	ImportGoverned ImportMode = "governed" // governance FSM: import as proposed
	ImportDryRun   ImportMode = "dry_run"  // report diff only, no mutations
)

type ImportOptions

type ImportOptions struct {
	Mode      ImportMode `json:"mode"`
	SourceDID string     `json:"sourceDID,omitempty"` // DID of the exporting peer
}

ImportOptions controls import behavior.

type ImportResult

type ImportResult struct {
	TypesAdded       int      `json:"typesAdded"`
	TypesSkipped     int      `json:"typesSkipped"`
	TypesConflicting []string `json:"typesConflicting,omitempty"`
	PredsAdded       int      `json:"predsAdded"`
	PredsSkipped     int      `json:"predsSkipped"`
	PredsConflicting []string `json:"predsConflicting,omitempty"`
}

ImportResult reports what happened during schema import.

type MergeResult

type MergeResult struct {
	TriplesUpdated int
	AliasesCreated int
}

MergeResult reports the outcome of a Merge operation.

type ObjectType

type ObjectType struct {
	ID          uuid.UUID     `json:"id"`
	Name        string        `json:"name"`
	Description string        `json:"description"`
	Properties  []PropertyDef `json:"properties"`
	Extends     string        `json:"extends,omitempty"`
	Status      SchemaStatus  `json:"status"`
	Version     int           `json:"version"`
	CreatedAt   time.Time     `json:"createdAt"`
	UpdatedAt   time.Time     `json:"updatedAt"`
}

ObjectType represents a formal entity type in the ontology.

func SlimToType

func SlimToType(s SchemaTypeSlim, status SchemaStatus) ObjectType

SlimToType converts a slim wire type to a full ObjectType with generated local fields.

type OntologyService

type OntologyService interface {
	// Schema queries
	GetType(ctx context.Context, name string) (*ObjectType, error)
	ListTypes(ctx context.Context) ([]ObjectType, error)
	GetPredicate(ctx context.Context, name string) (*PredicateDefinition, error)
	ListPredicates(ctx context.Context) ([]PredicateDefinition, error)

	// Schema mutations
	RegisterType(ctx context.Context, t ObjectType) error
	RegisterPredicate(ctx context.Context, p PredicateDefinition) error
	DeprecateType(ctx context.Context, name string) error
	DeprecatePredicate(ctx context.Context, name string) error

	// Validation
	ValidateTriple(ctx context.Context, t graph.Triple) error

	// Schema version — increments on register/deprecate
	SchemaVersion(ctx context.Context) (int, error)

	// Triple storage facade — Resolve → store.AddTriple.
	// When EntityResolver is available, canonicalizes subject and object
	// before storing. Predicate validation is NOT performed here — use
	// AssertFact for validated storage with temporal metadata and conflict detection.
	StoreTriple(ctx context.Context, t graph.Triple) error

	// PredicateValidator returns a context-free closure for hot-path
	// predicate validation. Uses a cached map, refreshed on schema changes.
	PredicateValidator() func(name string) bool

	// Truth Maintenance — Change 1-3
	AssertFact(ctx context.Context, input AssertionInput) (*AssertionResult, error)
	RetractFact(ctx context.Context, subject, predicate, object, reason string) error
	ConflictSet(ctx context.Context, subject, predicate string) ([]Conflict, error)
	ResolveConflict(ctx context.Context, conflictID uuid.UUID, winnerObject, reason string) error
	FactsAt(ctx context.Context, subject string, validAt time.Time) ([]graph.Triple, error)
	OpenConflicts(ctx context.Context) ([]Conflict, error)

	// Entity Resolution — Change 1-4
	Resolve(ctx context.Context, rawID string) (string, error)
	DeclareSameAs(ctx context.Context, nodeA, nodeB, source string) error
	MergeEntities(ctx context.Context, canonical, duplicate string) (*MergeResult, error)
	SplitEntity(ctx context.Context, canonical, splitOut string) error
	Aliases(ctx context.Context, canonicalID string) ([]string, error)
	// QueryTriples resolves subject via alias before querying graph store.
	QueryTriples(ctx context.Context, subject string) ([]graph.Triple, error)

	// Property Store — Change 1.5-1
	SetEntityProperty(ctx context.Context, entityID, entityType, property, value string) error
	GetEntityProperties(ctx context.Context, entityID string) (map[string]string, error)
	QueryEntities(ctx context.Context, q PropertyQuery) ([]EntityResult, error)
	GetEntity(ctx context.Context, entityID string) (*EntityResult, error)
	DeleteEntityProperties(ctx context.Context, entityID string) error

	// Action Types — Change 2-2
	ExecuteAction(ctx context.Context, actionName string, params map[string]string) (*ActionResult, error)
	ListActions(ctx context.Context) ([]ActionSummary, error)
	GetActionLog(ctx context.Context, logID uuid.UUID) (*ActionLogEntry, error)
	ListActionLogs(ctx context.Context, actionName string, limit int) ([]ActionLogEntry, error)

	// Governance — Change 2-3
	PromoteType(ctx context.Context, typeName string, targetStatus SchemaStatus, reason string) error
	PromotePredicate(ctx context.Context, predName string, targetStatus SchemaStatus, reason string) error
	SchemaHealth(ctx context.Context) (*SchemaHealthReport, error)
	TypeUsage(ctx context.Context, typeName string) (*TypeUsageInfo, error)

	// Schema Exchange — Change 3-1
	ExportSchema(ctx context.Context) (*SchemaBundle, error)
	ImportSchema(ctx context.Context, bundle *SchemaBundle, opts ImportOptions) (*ImportResult, error)

	// P2P Fact Exchange — Change 3-4
	AssertP2PFact(ctx context.Context, input P2PFactInput) (*AssertionResult, error)
	VerifyP2PFact(ctx context.Context, subject, predicate, object string) error
}

OntologyService is the single facade for all ontology operations. All consumers use this interface — never reference Registry or other internal components directly.

type P2PFactInput

type P2PFactInput struct {
	Triple     graph.Triple
	PeerDID    string  // DID of the asserting peer
	PeerTrust  float64 // 0.0-1.0 peer reputation score
	Confidence float64 // peer's claimed confidence
}

P2PFactInput carries a fact received from a peer with reputation context.

type Permission

type Permission int

Permission represents an ordered access level for ontology operations. Higher values include all lower permissions: Admin > Write > Read.

const (
	PermRead  Permission = iota + 1 // query, list, validate
	PermWrite                       // register, assert, retract, set property
	PermAdmin                       // deprecate, merge, split, resolve conflict, delete
)

func ParsePermission

func ParsePermission(s string) Permission

ParsePermission converts a string ("read", "write", "admin") to a Permission value. Returns PermRead for unrecognized strings.

type PredicateDefinition

type PredicateDefinition struct {
	ID          uuid.UUID    `json:"id"`
	Name        string       `json:"name"`
	Description string       `json:"description"`
	SourceTypes []string     `json:"sourceTypes"`
	TargetTypes []string     `json:"targetTypes"`
	Cardinality Cardinality  `json:"cardinality"`
	Inverse     string       `json:"inverse,omitempty"`
	Status      SchemaStatus `json:"status"`
	Version     int          `json:"version"`
	CreatedAt   time.Time    `json:"createdAt"`
	UpdatedAt   time.Time    `json:"updatedAt"`
}

PredicateDefinition represents a formal relationship type in the ontology.

func SlimToPredicate

func SlimToPredicate(s SchemaPredicateSlim, status SchemaStatus) PredicateDefinition

SlimToPredicate converts a slim wire type to a full PredicateDefinition with generated local fields.

type PropertyDef

type PropertyDef struct {
	Name        string       `json:"name"`
	Type        PropertyType `json:"type"`
	Required    bool         `json:"required"`
	Indexed     bool         `json:"indexed"`
	Constraints []Constraint `json:"constraints,omitempty"`
}

PropertyDef defines a single property on an ObjectType.

type PropertyEffect

type PropertyEffect struct {
	EntityID string `json:"entityID"`
	Property string `json:"property"`
	OldValue string `json:"oldValue,omitempty"`
	NewValue string `json:"newValue"`
}

PropertyEffect records a property change made by an action.

type PropertyFilter

type PropertyFilter struct {
	Property string   `json:"property"`
	Op       FilterOp `json:"op"`
	Value    string   `json:"value"`
}

PropertyFilter is a single condition in a PropertyQuery.

type PropertyQuery

type PropertyQuery struct {
	EntityType string           `json:"entityType"` // required
	Filters    []PropertyFilter `json:"filters"`    // AND
	Limit      int              `json:"limit"`      // default 100
	Offset     int              `json:"offset"`
}

PropertyQuery selects entities by type and property filters (AND semantics).

type PropertyStore

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

PropertyStore provides Ent-backed EAV storage for per-entity property values.

func NewPropertyStore

func NewPropertyStore(client *ent.Client) *PropertyStore

NewPropertyStore creates a PropertyStore backed by the given Ent client.

func (*PropertyStore) DeleteProperties

func (s *PropertyStore) DeleteProperties(ctx context.Context, entityID string) error

DeleteProperties removes all properties for an entity.

func (*PropertyStore) GetEntityType

func (s *PropertyStore) GetEntityType(ctx context.Context, entityID string) (string, error)

GetEntityType returns the entity type for a given entity ID. Returns empty string if no properties are stored for this entity.

func (*PropertyStore) GetProperties

func (s *PropertyStore) GetProperties(ctx context.Context, entityID string) (map[string]string, error)

GetProperties returns all properties for an entity as a key-value map.

func (*PropertyStore) GetPropertiesBatch

func (s *PropertyStore) GetPropertiesBatch(ctx context.Context, entityIDs []string) (map[string]map[string]string, error)

GetPropertiesBatch returns properties for multiple entities in a single query. Result maps entityID → (property → value).

func (*PropertyStore) Query

func (s *PropertyStore) Query(ctx context.Context, q PropertyQuery) ([]string, error)

Query returns entity IDs matching type + property filters (AND semantics).

func (*PropertyStore) SetProperty

func (s *PropertyStore) SetProperty(ctx context.Context, entityID, entityType, property, value, valueType string) error

SetProperty stores or updates a property value for an entity (upsert).

type PropertyType

type PropertyType string

PropertyType defines the data type of an ObjectType property.

const (
	TypeString    PropertyType = "string"
	TypeInt       PropertyType = "int"
	TypeFloat     PropertyType = "float"
	TypeBool      PropertyType = "bool"
	TypeDateTime  PropertyType = "datetime"
	TypeReference PropertyType = "reference"
)

type Registry

type Registry interface {
	// ObjectType operations
	RegisterType(ctx context.Context, t ObjectType) error
	GetType(ctx context.Context, name string) (*ObjectType, error)
	ListTypes(ctx context.Context) ([]ObjectType, error)
	DeprecateType(ctx context.Context, name string) error

	// PredicateDefinition operations
	RegisterPredicate(ctx context.Context, p PredicateDefinition) error
	GetPredicate(ctx context.Context, name string) (*PredicateDefinition, error)
	ListPredicates(ctx context.Context) ([]PredicateDefinition, error)
	DeprecatePredicate(ctx context.Context, name string) error

	// UpdateTypeStatus sets the status of an existing type by name.
	UpdateTypeStatus(ctx context.Context, name string, status SchemaStatus) error
	// UpdatePredicateStatus sets the status of an existing predicate by name.
	UpdatePredicateStatus(ctx context.Context, name string, status SchemaStatus) error
}

Registry is the internal interface for ontology schema persistence. Only used by ServiceImpl — external consumers use OntologyService.

type ResultTriple

type ResultTriple struct {
	Subject     string            `json:"subject"`
	Predicate   string            `json:"predicate"`
	Object      string            `json:"object"`
	SubjectType string            `json:"subjectType,omitempty"`
	ObjectType  string            `json:"objectType,omitempty"`
	Metadata    map[string]string `json:"metadata,omitempty"`
}

ResultTriple is a serializable triple for EntityResult. Avoids importing graph in types.go; populated by the service layer from graph.Triple.

type RoleBasedPolicy

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

RoleBasedPolicy maps principal names to their maximum permission level. Principals with level >= required pass; others are denied. Principals with "peer:" prefix use P2PPermission instead of the roles map.

func NewRoleBasedPolicy

func NewRoleBasedPolicy(roles map[string]Permission) *RoleBasedPolicy

NewRoleBasedPolicy creates a RoleBasedPolicy from a principal→permission map.

func (*RoleBasedPolicy) Check

func (p *RoleBasedPolicy) Check(principal string, required Permission) error

Check verifies that principal has at least the required permission.

Special rules:

  • "" or "system" → PermAdmin (programmatic callers without agent context)
  • Unknown principal (not in roles) → PermRead (safe default)
  • Known principal → roles[principal] >= required

func (*RoleBasedPolicy) SetP2PPermission

func (p *RoleBasedPolicy) SetP2PPermission(perm Permission)

SetP2PPermission sets the default permission for peer: prefix principals.

type SchemaBundle

type SchemaBundle struct {
	Version       int                   `json:"version"`       // bundle format version (1)
	SchemaVersion int                   `json:"schemaVersion"` // ontology version at export time
	ExportedAt    time.Time             `json:"exportedAt"`
	ExportedBy    string                `json:"exportedBy"` // DID or "local"
	Types         []SchemaTypeSlim      `json:"types"`
	Predicates    []SchemaPredicateSlim `json:"predicates"`
	Digest        string                `json:"digest"` // SHA256(canonical JSON of Types+Predicates)
}

SchemaBundle is the P2P-serializable representation of an ontology schema. Uses slim wire types only — no UUID, timestamps, status, or version.

type SchemaHealthReport

type SchemaHealthReport struct {
	Types      map[SchemaStatus]int `json:"types"`
	Predicates map[SchemaStatus]int `json:"predicates"`
}

SchemaHealthReport provides status counts for types and predicates.

type SchemaPredicateSlim

type SchemaPredicateSlim struct {
	Name        string   `json:"name"`
	Description string   `json:"description,omitempty"`
	SourceTypes []string `json:"sourceTypes,omitempty"`
	TargetTypes []string `json:"targetTypes,omitempty"`
	Cardinality string   `json:"cardinality"`
	Inverse     string   `json:"inverse,omitempty"`
}

SchemaPredicateSlim is a wire-format representation of PredicateDefinition.

func PredicateToSlim

func PredicateToSlim(p PredicateDefinition) SchemaPredicateSlim

PredicateToSlim converts a full PredicateDefinition to a slim wire type.

type SchemaPropertySlim

type SchemaPropertySlim struct {
	Name     string `json:"name"`
	Type     string `json:"type"`
	Required bool   `json:"required"`
}

SchemaPropertySlim is a wire-format representation of PropertyDef.

type SchemaStatus

type SchemaStatus string

SchemaStatus represents the lifecycle state of an ontology schema element.

const (
	SchemaProposed    SchemaStatus = "proposed"
	SchemaQuarantined SchemaStatus = "quarantined"
	SchemaShadow      SchemaStatus = "shadow"
	SchemaActive      SchemaStatus = "active"
	SchemaDeprecated  SchemaStatus = "deprecated"
)

type SchemaTypeSlim

type SchemaTypeSlim struct {
	Name        string               `json:"name"`
	Description string               `json:"description,omitempty"`
	Properties  []SchemaPropertySlim `json:"properties,omitempty"`
	Extends     string               `json:"extends,omitempty"`
}

SchemaTypeSlim is a wire-format representation of ObjectType.

func TypeToSlim

func TypeToSlim(t ObjectType) SchemaTypeSlim

TypeToSlim converts a full ObjectType to a slim wire type.

type ServiceImpl

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

ServiceImpl implements OntologyService.

func NewService

func NewService(reg Registry, graphStore graph.Store) *ServiceImpl

NewService creates a new OntologyService backed by the given registry. graphStore may be nil if not yet available (StoreTriple will return an error).

func (*ServiceImpl) Aliases

func (s *ServiceImpl) Aliases(ctx context.Context, canonicalID string) ([]string, error)

func (*ServiceImpl) AssertFact

func (s *ServiceImpl) AssertFact(ctx context.Context, input AssertionInput) (*AssertionResult, error)

func (*ServiceImpl) AssertP2PFact

func (s *ServiceImpl) AssertP2PFact(ctx context.Context, input P2PFactInput) (*AssertionResult, error)

func (*ServiceImpl) ConflictSet

func (s *ServiceImpl) ConflictSet(ctx context.Context, subject, predicate string) ([]Conflict, error)

func (*ServiceImpl) DeclareSameAs

func (s *ServiceImpl) DeclareSameAs(ctx context.Context, nodeA, nodeB, source string) error

func (*ServiceImpl) DeleteEntityProperties

func (s *ServiceImpl) DeleteEntityProperties(ctx context.Context, entityID string) error

func (*ServiceImpl) DeprecatePredicate

func (s *ServiceImpl) DeprecatePredicate(ctx context.Context, name string) error

func (*ServiceImpl) DeprecateType

func (s *ServiceImpl) DeprecateType(ctx context.Context, name string) error

func (*ServiceImpl) ExecuteAction

func (s *ServiceImpl) ExecuteAction(ctx context.Context, actionName string, params map[string]string) (*ActionResult, error)

func (*ServiceImpl) ExportSchema

func (s *ServiceImpl) ExportSchema(ctx context.Context) (*SchemaBundle, error)

func (*ServiceImpl) FactsAt

func (s *ServiceImpl) FactsAt(ctx context.Context, subject string, validAt time.Time) ([]graph.Triple, error)

func (*ServiceImpl) GetActionLog

func (s *ServiceImpl) GetActionLog(ctx context.Context, logID uuid.UUID) (*ActionLogEntry, error)

func (*ServiceImpl) GetEntity

func (s *ServiceImpl) GetEntity(ctx context.Context, entityID string) (*EntityResult, error)

func (*ServiceImpl) GetEntityProperties

func (s *ServiceImpl) GetEntityProperties(ctx context.Context, entityID string) (map[string]string, error)

func (*ServiceImpl) GetPredicate

func (s *ServiceImpl) GetPredicate(ctx context.Context, name string) (*PredicateDefinition, error)

func (*ServiceImpl) GetType

func (s *ServiceImpl) GetType(ctx context.Context, name string) (*ObjectType, error)

func (*ServiceImpl) ImportSchema

func (s *ServiceImpl) ImportSchema(ctx context.Context, bundle *SchemaBundle, opts ImportOptions) (*ImportResult, error)

func (*ServiceImpl) ListActionLogs

func (s *ServiceImpl) ListActionLogs(ctx context.Context, actionName string, limit int) ([]ActionLogEntry, error)

func (*ServiceImpl) ListActions

func (s *ServiceImpl) ListActions(_ context.Context) ([]ActionSummary, error)

func (*ServiceImpl) ListPredicates

func (s *ServiceImpl) ListPredicates(ctx context.Context) ([]PredicateDefinition, error)

func (*ServiceImpl) ListTypes

func (s *ServiceImpl) ListTypes(ctx context.Context) ([]ObjectType, error)

func (*ServiceImpl) MergeEntities

func (s *ServiceImpl) MergeEntities(ctx context.Context, canonical, duplicate string) (*MergeResult, error)

func (*ServiceImpl) OpenConflicts

func (s *ServiceImpl) OpenConflicts(ctx context.Context) ([]Conflict, error)

func (*ServiceImpl) PredicateValidator

func (s *ServiceImpl) PredicateValidator() func(name string) bool

PredicateValidator returns a context-free closure for hot-path use. The closure checks the cached active predicate set without DB queries. Cache is refreshed by mutation methods (Register/Deprecate/Promote/Import), NOT by this getter — safe to call on every request.

func (*ServiceImpl) PromotePredicate

func (s *ServiceImpl) PromotePredicate(ctx context.Context, predName string, targetStatus SchemaStatus, _ string) error

func (*ServiceImpl) PromoteType

func (s *ServiceImpl) PromoteType(ctx context.Context, typeName string, targetStatus SchemaStatus, _ string) error

func (*ServiceImpl) QueryEntities

func (s *ServiceImpl) QueryEntities(ctx context.Context, q PropertyQuery) ([]EntityResult, error)

func (*ServiceImpl) QueryTriples

func (s *ServiceImpl) QueryTriples(ctx context.Context, subject string) ([]graph.Triple, error)

QueryTriples resolves subject via alias then queries graph store.

func (*ServiceImpl) RegisterPredicate

func (s *ServiceImpl) RegisterPredicate(ctx context.Context, p PredicateDefinition) error

func (*ServiceImpl) RegisterType

func (s *ServiceImpl) RegisterType(ctx context.Context, t ObjectType) error

func (*ServiceImpl) Resolve

func (s *ServiceImpl) Resolve(ctx context.Context, rawID string) (string, error)

func (*ServiceImpl) ResolveConflict

func (s *ServiceImpl) ResolveConflict(ctx context.Context, conflictID uuid.UUID, winnerObject, reason string) error

func (*ServiceImpl) RetractFact

func (s *ServiceImpl) RetractFact(ctx context.Context, subject, predicate, object, reason string) error

func (*ServiceImpl) SchemaHealth

func (s *ServiceImpl) SchemaHealth(ctx context.Context) (*SchemaHealthReport, error)

func (*ServiceImpl) SchemaVersion

func (s *ServiceImpl) SchemaVersion(ctx context.Context) (int, error)

func (*ServiceImpl) SetACLPolicy

func (s *ServiceImpl) SetACLPolicy(p ACLPolicy)

SetACLPolicy injects the ACL policy after construction. When nil, all operations are permitted (backward compatible).

func (*ServiceImpl) SetActionExecutor

func (s *ServiceImpl) SetActionExecutor(e *ActionExecutor)

SetActionExecutor injects the ActionExecutor after construction.

func (*ServiceImpl) SetEntityProperty

func (s *ServiceImpl) SetEntityProperty(ctx context.Context, entityID, entityType, property, value string) error

func (*ServiceImpl) SetEntityResolver

func (s *ServiceImpl) SetEntityResolver(er EntityResolver)

SetEntityResolver injects the EntityResolver after construction.

func (*ServiceImpl) SetGovernanceEngine

func (s *ServiceImpl) SetGovernanceEngine(g *GovernanceEngine)

SetGovernanceEngine injects the GovernanceEngine after construction. Must be called AFTER SeedDefaults to ensure seed types bypass governance.

func (*ServiceImpl) SetPropertyStore

func (s *ServiceImpl) SetPropertyStore(ps *PropertyStore)

SetPropertyStore injects the PropertyStore after construction.

func (*ServiceImpl) SetTruthMaintainer

func (s *ServiceImpl) SetTruthMaintainer(tm TruthMaintainer)

SetTruthMaintainer injects the TruthMaintainer after construction.

func (*ServiceImpl) SplitEntity

func (s *ServiceImpl) SplitEntity(ctx context.Context, canonical, splitOut string) error

func (*ServiceImpl) StoreTriple

func (s *ServiceImpl) StoreTriple(ctx context.Context, t graph.Triple) error

func (*ServiceImpl) TypeUsage

func (s *ServiceImpl) TypeUsage(ctx context.Context, typeName string) (*TypeUsageInfo, error)

func (*ServiceImpl) ValidateTriple

func (s *ServiceImpl) ValidateTriple(ctx context.Context, t graph.Triple) error

func (*ServiceImpl) VerifyP2PFact

func (s *ServiceImpl) VerifyP2PFact(ctx context.Context, subject, predicate, object string) error

type TruthMaintainer

type TruthMaintainer interface {
	// AssertFact stores a triple with temporal metadata and detects conflicts
	// based on predicate cardinality (OneToOne, ManyToOne).
	AssertFact(ctx context.Context, input AssertionInput) (*AssertionResult, error)

	// RetractFact sets ValidTo=now on a matching triple (soft delete).
	RetractFact(ctx context.Context, subject, predicate, object, reason string) error

	// ConflictSet returns conflicts for a given subject-predicate pair.
	ConflictSet(ctx context.Context, subject, predicate string) ([]Conflict, error)

	// ResolveConflict picks a winner and retracts losers.
	ResolveConflict(ctx context.Context, conflictID uuid.UUID, winnerObject, reason string) error

	// FactsAt returns triples valid at a specific point in time.
	FactsAt(ctx context.Context, subject string, validAt time.Time) ([]graph.Triple, error)

	// OpenConflicts returns all unresolved conflicts.
	OpenConflicts(ctx context.Context) ([]Conflict, error)
}

TruthMaintainer manages bi-temporal fact assertion, retraction, and conflict resolution.

func NewTruthMaintainer

func NewTruthMaintainer(svc OntologyService, store graph.Store, cs *ConflictStore) TruthMaintainer

NewTruthMaintainer creates a TruthMaintainer backed by the given stores.

type TypeUsageInfo

type TypeUsageInfo struct {
	TypeName  string       `json:"typeName"`
	Status    SchemaStatus `json:"status"`
	Version   int          `json:"version"`
	CreatedAt time.Time    `json:"createdAt"`
}

TypeUsageInfo provides basic information about a type's status and age.

Jump to

Keyboard shortcuts

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