types

package
v0.1.0-alpha.3 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 6 Imported by: 0

README

Types Package

Core type definitions for the semantic event mesh, extracted to avoid import cycles.

Overview

This package contains foundational types that are shared across multiple packages. It was extracted from message/ to allow component/ to reference these types without creating an import cycle.

Types

Keyable

Interface for types that produce dotted notation keys for NATS subjects:

type Keyable interface {
    Key() string
}
Type

Message type identifier with three parts: domain, category, version.

msgType := types.Type{Domain: "agentic", Category: "task", Version: "v1"}
subject := "events." + msgType.Key() // "events.agentic.task.v1"
EntityType

Entity type identifier with two parts: domain, type.

entityType := types.EntityType{Domain: "robotics", Type: "drone"}
key := entityType.Key() // "robotics.drone"
EntityID

Six-part federated entity identifier in the canonical order org.platform.system.domain.type.instance (ADR-102): org.platform is the minting deployment authority (platform.org / platform.id), system is the source that produced the entity, domain.type is a delegated taxonomy, instance is the leaf.

The taxonomy vocabulary is shared: more than one producer may declare the same domain, and the framework permits it (owner ruling 2026-08-28, superseding #1095 O-5). Sharing web between two products collides nothing — system at position 3 keeps acme.prod.semsource.web.page.001 and acme.prod.semdragon.web.doc.001 apart, and ADR-099 level 0 is source x taxonomy, so they are distinct communities. It is also what makes org.platform.*.<domain>.*.* useful: that pattern is "this taxonomy across every source", and it only has more than one answer because domains can be shared; a system prefix narrows it back to one source.

Nothing reports an overlap and there is no policy object to construct. EntityDomainDelegation is a declaration whose only reader is the entity-ID corpus audit, which AST-scans the literals in production Go for the registered set its domain_unregistered rule consults. Two products meaning different things by one token is a vocabulary problem, not a composition-time one.

entityID := types.EntityID{
    Org: "c360", Platform: "prod", System: "gcs1",
    Domain: "robotics", Type: "drone", Instance: "42",
}
key := entityID.Key() // "c360.prod.gcs1.robotics.drone.42"

// Parse from string
parsed, err := types.ParseEntityID("c360.prod.gcs1.robotics.drone.42")

Import Pattern

The message/ package aliases one of these types, Type, so payload code can say message.Type. EntityID, EntityType and Keyable are used from pkg/types directly:

// These are equivalent:
import "github.com/c360studio/semengine/pkg/types"
var t types.Type

import "github.com/c360studio/semengine/message"
var t message.Type  // Alias of types.Type

Why This Package Exists

The payload registry in component/ needs to validate that payload Schema() methods return the correct type. This requires access to the Type struct. However:

  • message/ imports component/ for CreatePayload() in UnmarshalJSON
  • component/ cannot import message/ (would create cycle)

Solution: Extract Type and related types to pkg/types/, which both packages can import.

pkg/types/   <── component/ imports for Schema validation
     ^
     |
message/     <── aliases Type as message.Type
     |
     v
component/   <── message/ imports for CreatePayload()

Documentation

Overview

Package types provides core type definitions for the semantic event mesh.

This package contains foundational types that are shared across multiple packages without creating import cycles. It includes:

  • Keyable interface: Foundation for dotted notation semantic keys
  • Type: Message type identifier (domain.category.version)
  • EntityType: Entity type identifier (domain.type)
  • EntityID: 6-part federated entity identifier

These types enable NATS wildcard queries and consistent storage patterns through their Key() methods which produce dotted notation strings.

Example Usage

// Message type for routing
msgType := types.Type{Domain: "sensors", Category: "gps", Version: "v1"}
subject := "events." + msgType.Key() // "events.sensors.gps.v1"

// Entity identification
entityID := types.EntityID{
    Org: "c360", Platform: "prod", System: "gcs1",
    Domain: "robotics", Type: "drone", Instance: "42",
}
key := entityID.Key() // "c360.prod.gcs1.robotics.drone.42"

Index

Constants

View Source
const (
	StatusSuccess = "success"
	StatusFailed  = "failed"
	StatusPending = "pending"
)

Status constants for agent results and workflow steps. Using constants prevents typos and enables IDE autocompletion.

View Source
const (
	SourceTypeGraphEntity       = "graph_entity"
	SourceTypeGraphRelationship = "graph_relationship"
	SourceTypeDocument          = "document"
)

Source type constants for ContextSource.Type

View Source
const (
	// MaxEntityIDBytes is the maximum serialized size of a canonical entity ID,
	// including its five separators. There is no independent segment bound.
	MaxEntityIDBytes = 256

	// ErrorCodeEntityIDInvalid classifies an invalid literal entity ID.
	ErrorCodeEntityIDInvalid = "entity_id_invalid"
	// ErrorCodeEntityIDPatternInvalid classifies an invalid declaration pattern.
	ErrorCodeEntityIDPatternInvalid = "entity_id_pattern_invalid"
	// ErrorCodeEntityIDPrefixInvalid classifies an invalid query prefix.
	ErrorCodeEntityIDPrefixInvalid = "entity_id_prefix_invalid"

	// EntityIDReasonEmpty identifies an empty whole input.
	EntityIDReasonEmpty = "empty"
	// EntityIDReasonBytes identifies a serialized byte-limit violation.
	EntityIDReasonBytes = "bytes"
	// EntityIDReasonArity identifies an invalid number of positions.
	EntityIDReasonArity = "arity"
	// EntityIDReasonEmptySegment identifies an empty position.
	EntityIDReasonEmptySegment = "empty_segment"
	// EntityIDReasonFirstByte identifies a non-alphanumeric segment start.
	EntityIDReasonFirstByte = "first_byte"
	// EntityIDReasonAlphabet identifies a forbidden segment byte.
	EntityIDReasonAlphabet = "alphabet"

	// EntityIDDetailReason is the stable reason detail key.
	EntityIDDetailReason = "reason"
	// EntityIDDetailMeasuredBytes reports the rejected serialized byte count.
	EntityIDDetailMeasuredBytes = "measured_bytes"
	// EntityIDDetailAllowedBytes reports the serialized byte limit.
	EntityIDDetailAllowedBytes = "allowed_bytes"
	// EntityIDDetailMeasuredParts reports the rejected position count.
	EntityIDDetailMeasuredParts = "measured_parts"
	// EntityIDDetailAllowedParts reports the position-count limit.
	EntityIDDetailAllowedParts = "allowed_parts"
	// EntityIDDetailSegmentIndex reports the zero-based failing position.
	EntityIDDetailSegmentIndex = "segment_index"

	// EntityIDLiteralPattern is the anchored JSON-Schema-compatible regular
	// expression for a canonical six-part literal entity ID.
	EntityIDLiteralPattern = `^` + entityIDLiteralBodyPattern + `$`
	// EntityIDDeclarationPattern is the anchored JSON-Schema-compatible
	// regular expression for an exact six-position entity ID declaration
	// pattern whose positions are canonical literals or the complete token "*".
	EntityIDDeclarationPattern = `^` + entityIDPatternBodyPattern + `$`
	// EntityIDLiteralPrefixPattern is the anchored JSON-Schema-compatible
	// regular expression for a canonical one-to-six-part literal query prefix.
	EntityIDLiteralPrefixPattern = `^` + entityIDLiteralSegmentPattern + `(?:\.` + entityIDLiteralSegmentPattern + `){0,5}$`
	// OptionalEntityIDLiteralPattern is EntityIDLiteralPattern plus the explicit
	// empty-string sentinel used by optional configuration fields.
	OptionalEntityIDLiteralPattern = `^(?:$|` + entityIDLiteralBodyPattern + `)$`
)
View Source
const (
	// ErrorCodeEntityIDAuthorityInvalid classifies an authority rejection: the
	// candidate is structurally canonical but its positions 1-2 do not match
	// the lane it arrived on. Distinct from ErrorCodeEntityIDInvalid so a
	// caller can tell "malformed" from "not yours".
	ErrorCodeEntityIDAuthorityInvalid = "entity_id_authority_invalid"

	// EntityIDReasonForeignAuthority identifies a candidate whose org.platform
	// differs from the deployment's own on a lane that is not an import lane.
	EntityIDReasonForeignAuthority = "foreign_authority"
	// EntityIDReasonLocalAuthorityClaimed identifies a candidate claiming the
	// deployment's own org.platform on a declared import lane.
	EntityIDReasonLocalAuthorityClaimed = "local_authority_claimed"

	// EntityIDDetailLane reports which lane the candidate arrived on.
	EntityIDDetailLane = "lane"
	// EntityIDLaneLocal is the lane value for every non-import lane.
	EntityIDLaneLocal = "local"
	// EntityIDLaneImport is the lane value for a declared import lane.
	EntityIDLaneImport = "import"
)

Variables

This section is empty.

Functions

func IsFrameworkEntityDomain

func IsFrameworkEntityDomain(domain string) bool

IsFrameworkEntityDomain reports whether domain is framework-reserved.

func IsReservedInstanceToken

func IsReservedInstanceToken(token string) bool

IsReservedInstanceToken reports whether token is a reserved instance token.

func IsValidEntityID

func IsValidEntityID(value string) bool

IsValidEntityID is the boolean convenience over ValidateEntityID.

func MatchEntityIDPattern

func MatchEntityIDPattern(pattern, entityID string) (bool, error)

MatchEntityIDPattern reports whether entityID matches an exact six-position declaration pattern. Both inputs are validated by the canonical contract; callers never receive a partial or best-effort match for malformed data.

func MaxAuthorityPairBytes

func MaxAuthorityPairBytes() int

MaxAuthorityPairBytes is the family-table budget for len(platform.org)+len(platform.id): the canonical bound minus the longest fixed family suffix, so every framework identity fits under every admitted authority. 170 bytes while the rule trigger family binds.

It bounds the EFFECTIVE pair. Configuration load bounds the DECLARED pair more tightly, reserving the entropy suffix the framework mints onto platform.id at first boot (ADR-104); that reserve lives with the mint, in package config, because this table knows nothing about it.

func ValidateEntityID

func ValidateEntityID(value string) error

ValidateEntityID validates one canonical six-part entity identity without rewriting, encoding, or normalizing any input byte.

func ValidateEntityIDAuthority

func ValidateEntityIDAuthority(candidate, org, platform string, importLane bool) error

ValidateEntityIDAuthority checks positions 1-2 of candidate against the deployment's own org and platform for the lane the candidate arrived on. Structural validation runs first; an authority reason never masks a structural one. On a non-import lane a foreign pair is rejected with foreign_authority; on an import lane the deployment's own pair is rejected with local_authority_claimed and any foreign pair is accepted unchanged.

It takes strings rather than types.PlatformMeta because that type lives in the root types package, which pkg/types must not import. Details carry only reason, segment_index, and lane — never identity bytes.

func ValidateEntityIDPattern

func ValidateEntityIDPattern(value string) error

ValidateEntityIDPattern validates an exact six-position declaration pattern. Each position is either one canonical literal segment or "*".

func ValidateEntityIDPrefix

func ValidateEntityIDPrefix(value string) error

ValidateEntityIDPrefix validates a non-empty one-to-six-position literal query prefix. Match-all surfaces must handle empty before calling this API.

Types

type ConstructedContext

type ConstructedContext struct {
	Content       string          `json:"content"`                  // Formatted context for LLM
	TokenCount    int             `json:"token_count"`              // Exact token count
	Entities      []string        `json:"entities,omitempty"`       // Entity IDs included
	Sources       []ContextSource `json:"sources,omitempty"`        // Provenance tracking
	ConstructedAt time.Time       `json:"constructed_at,omitempty"` // When context was built
}

ConstructedContext is pre-built context ready to embed in task payload. When present in a TaskMessage, the agent loop uses this directly instead of performing discovery or hydration, enabling the "embed context, don't make agents discover it" pattern.

type ContextSource

type ContextSource struct {
	Type string `json:"type"` // "graph_entity", "graph_relationship", "document"
	ID   string `json:"id"`   // Entity/doc ID
}

ContextSource tracks where context came from, providing provenance information for debugging and auditing.

type EntityDomainDelegation

type EntityDomainDelegation struct {
	Producer string
	Domain   string
	Type     string
}

EntityDomainDelegation declares that one named producer mints entities under an exact entity domain (Type empty) or one exact domain.type. Producer identity is supplied by the trusted composition boundary; it is never inferred from Triple.Source or a payload type. Wildcards are not supported.

It is a DECLARATION, not an authorization policy. Its consumer is the entity-ID corpus audit, which AST-scans these literals in production Go for the registered set its domain_unregistered rule consults (internal/entityidaudit/segment_rules.go collectRegisteredDomains) — no runtime code reads it. The EntityDomainAuthority/Authorize policy that once accompanied it was deleted by the owner ruling of 2026-08-28: two producers sharing one domain is PERMITTED, so there was nothing left to authorize, and detecting a mis-chosen token is a vocabulary question rather than a composition-time one.

type EntityID

type EntityID struct {
	// Deployment authority (2 parts): the composition root's own identity.
	Org      string // Organization namespace (e.g., "acme")
	Platform string // Minting deployment authority (e.g., "dep1"), from platform.id

	// Source (1 part): who produced the entity; never the product name.
	System string // Source (e.g., "src", "gcs1", "agentic-loop")

	// Taxonomy (2 parts): a delegated domain and its type.
	Domain string // Delegated taxonomy (e.g., "git", "agent")
	Type   string // Entity type within the domain (e.g., "commit", "execution")

	// Leaf (1 part): unbounded cardinality, always last.
	Instance string // Leaf identifier (e.g., "a1", a UUID, a digest)
}

EntityID is one complete entity identity in the canonical order org.platform.system.domain.type.instance (ADR-102). Each position has one meaning and one owner:

pos  name      meaning                                   supplied by
1    org       organization namespace                    platform.org (config)
2    platform  minting deployment authority              platform.id (config, via deps.Platform)
3    system    the source that produced the entity       the producer (feed, repo, world, framework component)
4    domain    delegated taxonomy                        a registered EntityDomainDelegation, or a framework-reserved domain
5    type      entity type within the domain             the same delegation as domain
6    instance  the producer's leaf identifier            the producer; the only unbounded-cardinality position, always last

Positions 1-2 are never a payload value, a constant, or a product name; a product is provenance (Triple.Source, the envelope source), not identity.

Examples:

  • EntityID{Org: "acme", Platform: "dep1", System: "src", Domain: "git", Type: "commit", Instance: "a1"} -> "acme.dep1.src.git.commit.a1"
  • EntityID{Org: "acme", Platform: "dep1", System: "agentic-loop", Domain: "agent", Type: "execution", Instance: "<uuid>"}

func ParseEntityID

func ParseEntityID(s string) (EntityID, error)

ParseEntityID creates EntityID from dotted string format. Expects exactly 6 parts in the canonical order org.platform.system.domain.type.instance and assigns every field from its named position. Returns a coded error if the format is invalid.

func (EntityID) DeploymentPrefix

func (eid EntityID) DeploymentPrefix() string

DeploymentPrefix returns the two-position prefix org.platform.

func (EntityID) EntityType

func (eid EntityID) EntityType() EntityType

EntityType returns the EntityType component of this EntityID

func (EntityID) HasPrefix

func (eid EntityID) HasPrefix(prefix string) bool

HasPrefix reports whether this EntityID lies under the given literal prefix on a position boundary.

Example:

eid := EntityID{Org: "acme", Platform: "dep1", System: "src", Domain: "git", Type: "commit", Instance: "a1"}
eid.HasPrefix("acme.dep1.src.git.commit") // true (same type)
eid.HasPrefix("acme.dep1.src")            // true (same source)
eid.HasPrefix("acme.dep1.other")          // false (different source)

func (EntityID) IsSibling

func (eid EntityID) IsSibling(other EntityID) bool

IsSibling reports whether other shares this EntityID's type prefix and is not the same instance.

func (EntityID) IsValid

func (eid EntityID) IsValid() bool

IsValid reports whether the exact serialized fields form a canonical ID.

func (EntityID) Key

func (eid EntityID) Key() string

Key returns the canonical six-part dotted key in org.platform.system.domain.type.instance order. It implements the Keyable interface for unified semantic keys.

func (EntityID) SourcePrefix

func (eid EntityID) SourcePrefix() string

SourcePrefix returns the three-position prefix org.platform.system — the federation triple.

func (EntityID) String

func (eid EntityID) String() string

String returns the same as Key() for backwards compatibility

func (EntityID) TaxonomyPrefix

func (eid EntityID) TaxonomyPrefix() string

TaxonomyPrefix returns the four-position prefix org.platform.system.domain.

func (EntityID) TypePrefix

func (eid EntityID) TypePrefix() string

TypePrefix returns the five-position prefix org.platform.system.domain.type shared by every instance of one type (siblings).

type EntityType

type EntityType struct {
	// Domain identifies the business or system domain (lowercase)
	Domain string
	// Type identifies the specific entity type within the domain (lowercase)
	Type string
}

EntityType represents a structured entity type identifier using dotted notation.

Format: EntityType{Domain: "domain", Type: "type"} -> Key() returns "domain.type"

Examples:

  • EntityType{Domain: "robotics", Type: "drone"} -> "robotics.drone"
  • EntityType{Domain: "robotics", Type: "battery"} -> "robotics.battery"
  • EntityType{Domain: "sensors", Type: "gps"} -> "sensors.gps"

EntityType is used by Identifiable payloads to specify their entity type, enabling entity extraction and property graph construction with consistent dotted keys.

func (EntityType) Key

func (et EntityType) Key() string

Key returns the dotted notation representation: "domain.type" This implements the Keyable interface for unified semantic keys.

func (EntityType) String

func (et EntityType) String() string

String returns the same as Key() for backwards compatibility

type FrameworkIdentityFamily

type FrameworkIdentityFamily struct {
	// Name is the stable family name used in configuration-load errors.
	Name string
	// System is position 3: the minting framework component.
	System string
	// Domain is position 4: a framework-reserved domain.
	Domain string
	// Type is position 5.
	Type string
	// InstanceBytes is the fixed byte length of position 6.
	InstanceBytes int
}

FrameworkIdentityFamily is one framework-minted entity family whose positions 3-6 have a fixed byte length by construction (a digest or a fixed-width hash in the instance position). The table is the single home for those families' prefixes — builders compose their identity from it so the authority-pair budget at configuration load is derived, never hand-copied (ADR-102 amends ADR-076 d2; ruled O-14).

func LongestFrameworkIdentityFamily

func LongestFrameworkIdentityFamily() FrameworkIdentityFamily

LongestFrameworkIdentityFamily returns the family with the most fixed bytes: the one that binds the authority-pair budget.

func RuleAlertIdentityFamily

func RuleAlertIdentityFamily() FrameworkIdentityFamily

RuleAlertIdentityFamily is the ADR-076 rule alert family under the deployment's own authority.

func RuleTriggerIdentityFamily

func RuleTriggerIdentityFamily() FrameworkIdentityFamily

RuleTriggerIdentityFamily is the ADR-076 rule trigger family under the deployment's own authority; the longest fixed suffix today.

func WebObservationIdentityFamily

func WebObservationIdentityFamily() FrameworkIdentityFamily

WebObservationIdentityFamily is the agent web-observation family (sha256-16 of the canonical URL in the instance position).

func (FrameworkIdentityFamily) EntityID

func (f FrameworkIdentityFamily) EntityID(org, platform, instance string) (string, error)

EntityID composes and validates a member identity under the given authority. It fails closed on any non-canonical part, including an empty or dotted authority segment and an instance of the wrong length.

func (FrameworkIdentityFamily) FixedBytes

func (f FrameworkIdentityFamily) FixedBytes() int

FixedBytes is every byte of a member identity that is not the authority pair: the five separators plus positions 3-6.

type GraphContextSpec

type GraphContextSpec struct {
	Entities      []string `json:"entities,omitempty"`      // Entity IDs to hydrate
	Relationships bool     `json:"relationships,omitempty"` // Include relationships
	Depth         int      `json:"depth,omitempty"`         // Traversal depth (default 1)
	MaxTokens     int      `json:"max_tokens,omitempty"`    // Token budget for graph context
}

GraphContextSpec defines what graph context to inject into an agent. This is used declaratively in workflow definitions to specify context needs.

type Keyable

type Keyable interface {
	// Key returns the dotted notation representation of this semantic type.
	// Examples: "robotics.drone", "telemetry.robotics.drone.1", "robotics.battery.v1"
	Key() string
}

Keyable interface represents types that can be converted to semantic keys using dotted notation. This is the foundation of the unified semantic architecture enabling NATS wildcard queries and consistent storage patterns.

type Relationship

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

Relationship represents a relationship between entities in the knowledge graph. Used by context building and graph query operations.

type Type

type Type struct {
	// Domain identifies the business or system domain.
	// Examples: "sensors", "robotics", "finance"
	Domain string `json:"domain"`

	// Category identifies the specific message type within the domain.
	// Examples: "gps", "temperature", "heartbeat", "trade"
	Category string `json:"category"`

	// Version identifies the schema version.
	// Format: "v1", "v2", etc. Enables schema evolution.
	Version string `json:"version"`
}

Type provides structured type information for messages. It enables type-safe routing and processing by clearly identifying the domain, category, and version of each message.

Type constants should be defined in domain packages to maintain clear ownership and avoid coupling. This package only provides the type definition itself.

Example definition in a domain package:

var GPSMessage = types.Type{
    Domain:   "sensors",
    Category: "gps",
    Version:  "v1",
}

func (Type) Equal

func (mt Type) Equal(other Type) bool

Equal compares two Type instances for equality. Returns true if all fields (Domain, Category, Version) are identical.

func (Type) IsValid

func (mt Type) IsValid() bool

IsValid reports whether Validate accepts the Type.

func (Type) Key

func (mt Type) Key() string

Key returns the dotted notation representation: "domain.category.version" This implements the Keyable interface for unified semantic keys.

func (Type) String

func (mt Type) String() string

String returns the same as Key() for backwards compatibility

func (Type) Validate

func (mt Type) Validate() error

Validate reports whether the Type can round-trip through Key() and JSON: every component must be non-empty, free of the "." separator, and valid UTF-8 (encoding/json would write each invalid byte as U+FFFD, a different type on the wire; owner ruling, semengine #9 comment 5970334875). It is the one owner of message-type component grammar — the payload registry refuses a registration that fails it and a projection contract refuses a bound type that fails it, so nothing downstream ever needs to parse a key back into its components.

Jump to

Keyboard shortcuts

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