vocabulary

package
v0.1.0-alpha.1 Latest Latest
Warning

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

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

README

Vocabulary Package

Purpose: Semantic vocabulary management with dotted notation predicates and optional IRI mappings for standards compliance.

Design Philosophy: Pragmatic Semantic Web

The vocabulary package follows a pragmatic semantic web approach that balances clean internal architecture with customer requirements for standards compliance.

Core Principles

Internal: Always use dotted notation (domain.category.property)

  • Clean, human-readable predicates
  • NATS wildcard query support
  • No URI/IRI complexity in internal code

External: Optional IRI mappings at API boundaries

  • RDF/Turtle export with standard vocabularies
  • OGC compliance (GeoSPARQL, SSN/SOSA)
  • Integration with existing semantic systems

No Leakage: Standards complexity does NOT leak inward

  • Internal code never sees IRIs
  • Triples always use dotted predicates
  • NATS subjects use dotted notation

Predicate Structure

All predicates follow three-level dotted notation:

domain.category.property

Examples:

  • sensor.temperature.celsius - Sensor domain, temperature category
  • geo.location.latitude - Geospatial domain, location category
  • time.lifecycle.created - Temporal domain, lifecycle category
  • robotics.battery.level - Robotics domain, battery category

Naming Conventions:

  • domain: lowercase, business domain (sensors, geo, time, robotics)
  • category: lowercase, groups related properties (temperature, location, lifecycle)
  • property: lowercase, specific property name (celsius, latitude, created)
  • No underscores or special characters (dots only for level separation)

Why This Works:

  • ✅ NATS wildcards: robotics.battery.* finds all battery predicates
  • ✅ Human-readable: Clear semantic meaning without URIs
  • ✅ Consistent: Matches EntityID.Key() and Type.Key() patterns
  • ✅ Simple: No namespace prefixes or IRI complexity

Quick Start

1. Define Domain Predicates
package robotics

const (
    BatteryLevel   = "robotics.battery.level"
    BatteryVoltage = "robotics.battery.voltage"
    FlightModeArmed = "robotics.flight.armed"
)
2. Register with Metadata
func init() {
    vocabulary.Register(BatteryLevel,
        vocabulary.WithDescription("Battery charge level percentage"),
        vocabulary.WithDataType(vocabulary.DataTypeFloat),
        vocabulary.WithUnits("percent"),
        vocabulary.WithRange("0-100"),
        vocabulary.WithIRI("http://schema.org/batteryLevel"))

    vocabulary.Register(BatteryVoltage,
        vocabulary.WithDescription("Battery voltage"),
        vocabulary.WithDataType(vocabulary.DataTypeFloat),
        vocabulary.WithUnits("volts"))

    vocabulary.Register(FlightModeArmed,
        vocabulary.WithDescription("Flight mode armed status"),
        vocabulary.WithDataType(vocabulary.DataTypeBool))
}
3. Use in Messages
// Create triples - always dotted notation
triple := message.Triple{
    Subject:   entityID,
    Predicate: robotics.BatteryLevel,  // "robotics.battery.level"
    Object:    85.5,
}

// NATS queries work naturally
nc.Subscribe("robotics.battery.*", handler)  // All battery predicates

Functional Options API

The Register() function uses functional options for clean, composable configuration:

Available Options
WithDescription(desc string)

Human-readable description of the predicate.

vocabulary.Register("sensor.temperature.celsius",
    vocabulary.WithDescription("Temperature in degrees Celsius"))
WithDataType(dataType string)

The pragmatic type of the object value — one of seven canonical constants. Not the Go type of the value: the serializer observes that directly, and the authoritative ENTITY_STATES JSON round trip erases it anyway (a declared whole number arrives back as float64 every time). Declare only what observation cannot recover.

vocabulary.Register("sensor.temperature.celsius",
    vocabulary.WithDataType(vocabulary.DataTypeFloat))

One declaration renders three ways. The Go column is what the serializer typically sees, not what you declare; the RDF column is owned by vocabulary/export (ADR-107 keeps semantic-web vocabulary at the export edge, never on the declaration surface). vocabulary/export renders the RDF column in Turtle, N-Triples, and JSON-LD; the JSON Schema column states the schema mapping (semengine-entity-id is the entity-ID format name):

Constant Value Typical Go value RDF (Turtle / N-Triples) JSON Schema
DataTypeString string string "text" (xsd:string, omitted) {"type":"string"}
DataTypeEntityID entity_id string (6-part ID) <iri> — a resource, never a literal {"type":"string","format":"semengine-entity-id"}
DataTypeInt int float64 after the round trip "5"^^xsd:integer {"type":"integer"}
DataTypeFloat float float64 "5.5"^^xsd:double {"type":"number"}
DataTypeBool bool bool "true"^^xsd:boolean {"type":"boolean"}
DataTypeDateTime datetime time.Time, or RFC 3339 string "…Z"^^xsd:dateTime {"type":"string","format":"date-time"}
DataTypeJSON json string "…"^^rdf:JSON {"type":"string","contentMediaType":"application/json"}

Declaring nothing is legal. Anything else panics at registration, naming the offending value and the accepted vocabulary. The framework translates nothing — there is no legacy-spelling map, so float64, number, double, time.Time, timestamp, int64, array, entity_ref, reference and boolean all halt the binary rather than becoming their canonical equivalent. If you declare any of them today, see SemStreams' docs/operations/migration-predicate-datatype.md (not in this repository), which is the whole migration.

Export honors the declaration, and ignores it for any triple whose observed value contradicts it — a fractional value under an int declaration serializes as xsd:double, not as a rounded integer.

WithUnits(units string)

Measurement units, as free-form documentation. No framework path validates, normalizes, interprets, or honors it — unlike WithDataType, which is honored at export.

vocabulary.Register("sensor.temperature.celsius",
    vocabulary.WithUnits("celsius"))
WithRange(valueRange string)

Valid value ranges, as free-form documentation. "0-100", "-90 to 90" and "positive" are three incompatible grammars, which is why nothing parses it. No framework path validates, normalizes, interprets, or honors it.

vocabulary.Register("robotics.battery.level",
    vocabulary.WithRange("0-100"))
WithIRI(iri string)

W3C/RDF equivalent IRI for standards compliance.

Use constants from standards.go for common vocabularies.

vocabulary.Register("entity.label.preferred",
    vocabulary.WithIRI(vocabulary.DcTitle))
WithAlias(aliasType, priority int)

Mark as entity alias for resolution.

vocabulary.Register("robotics.communication.callsign",
    vocabulary.WithAlias(vocabulary.AliasTypeCommunication, 0))  // Priority 0 = highest
Complete Example
vocabulary.Register("robotics.battery.level",
    vocabulary.WithDescription("Battery charge level percentage"),
    vocabulary.WithDataType(vocabulary.DataTypeFloat),
    vocabulary.WithUnits("percent"),
    vocabulary.WithRange("0-100"),
    vocabulary.WithIRI("http://schema.org/batteryLevel"))

Alias Predicates for Entity Resolution

Some predicates represent entity aliases (identifiers, labels, call signs). The registry tracks these for entity resolution and correlation.

Alias Types

AliasTypeIdentity - Entity equivalence

  • RDF equivalents: owl:sameAs, schema:sameAs
  • Use for: Federated entity IDs, external system UUIDs
  • Resolution: ✅ Can resolve to entity IDs

AliasTypeAlternate - Secondary unique identifiers

  • RDF equivalents: schema:alternateName, dc:alternative
  • Use for: Model numbers, registration IDs
  • Resolution: ✅ Can resolve to entity IDs

AliasTypeExternal - External system identifiers

  • Go constants: vocabulary.DcIdentifier
  • RDF equivalents: dc:identifier, schema:identifier
  • Use for: Manufacturer serial numbers, legacy system IDs
  • Resolution: ✅ Can resolve to entity IDs

AliasTypeCommunication - Communication identifiers

  • RDF equivalent: foaf:accountName
  • Use for: Radio call signs, network hostnames, MQTT client IDs
  • Resolution: ✅ Can resolve to entity IDs

AliasTypeLabel - Display names

  • RDF equivalents: rdfs:label, skos:prefLabel, schema:name
  • Use for: Human-readable display names
  • Resolution: ❌ NOT for resolution (ambiguous - many entities share labels)

Note: The RDF notation shown (e.g., owl:sameAs) is shorthand for full IRIs. In Go code, always use the provided constants from standards.go (e.g., vocabulary.DcIdentifier).

Example: Registering Aliases
// Communication identifier - highest priority
vocabulary.Register("robotics.communication.callsign",
    vocabulary.WithDescription("Radio call sign for ATC"),
    vocabulary.WithDataType(vocabulary.DataTypeString),
    vocabulary.WithAlias(vocabulary.AliasTypeCommunication, 0))

// External identifier
vocabulary.Register("robotics.identifier.serial",
    vocabulary.WithDescription("Manufacturer serial number"),
    vocabulary.WithDataType(vocabulary.DataTypeString),
    vocabulary.WithAlias(vocabulary.AliasTypeExternal, 1),
    vocabulary.WithIRI(vocabulary.DcIdentifier))

// Display label - NOT used for resolution
vocabulary.Register("entity.label.display",
    vocabulary.WithDescription("Human-readable display name"),
    vocabulary.WithDataType(vocabulary.DataTypeString),
    vocabulary.WithAlias(vocabulary.AliasTypeLabel, 10))  // Low priority
Discovering Aliases
// Get all alias predicates with priorities
aliases := vocabulary.DiscoverAliasPredicates()
// Returns: map["robotics.communication.callsign"]int(0), etc.

Standards Mappings

Common standard vocabulary IRIs are provided in standards.go:

SKOS (Simple Knowledge Organization System)
const (
    SkosBroader  = "http://www.w3.org/2004/02/skos/core#broader"
    SkosNarrower = "http://www.w3.org/2004/02/skos/core#narrower"
)
Dublin Core
const (
    DcIdentifier = "http://purl.org/dc/terms/identifier"
    DcTitle      = "http://purl.org/dc/terms/title"
)

See standards.go for the complete list of standard vocabulary IRIs.

Registry API

Registration
// Register a predicate with functional options (including WithProjection)
vocabulary.Register(name string, opts ...Option)

// Register an entity-type (<domain>.<type>) class mapping
vocabulary.RegisterEntityType(domainType string, opts ...EntityTypeOption)

// Load and fail-closed register a declarative JSON or YAML vocabulary pack
pack, err := vocabulary.LoadPackYAML(r)
err = vocabulary.RegisterPack(pack, vocabulary.WithPrefixRegistrar(export.RegisterPrefixes))
Retrieval and Reverse Lookup
// Get metadata for a predicate
meta := vocabulary.GetPredicateMetadata("robotics.battery.level")
if meta != nil {
    fmt.Println(meta.Description)
    fmt.Println(meta.StandardIRI)
}

// Reverse-lookup canonical predicates by standard IRI (sorted)
preds := vocabulary.LookupByIRI("http://schema.org/batteryLevel")

// Look up entity-type metadata or reverse-lookup domain.type keys by class/superclass IRI
etMeta := vocabulary.GetEntityTypeMetadata("uxs.uas")
types := vocabulary.LookupEntityTypesByClassIRI("https://confirm.mil/diekm/UnmannedAerialSystem")

// List all registered predicates and entity types
predicates := vocabulary.ListRegisteredPredicates()
entityTypes := vocabulary.ListRegisteredEntityTypes()

// Discover alias predicates
aliases := vocabulary.DiscoverAliasPredicates()
Testing
// Snapshot and restore registry state around a test
defer vocabulary.SnapshotRegistry()()
vocabulary.ClearRegistry()

Internal vs External Usage

Internal: Always Dotted Notation
// Creating triples
triple := message.Triple{
    Subject:   "c360.platform1.robotics.drone.001",
    Predicate: "robotics.battery.level",  // Dotted, not IRI
    Object:    85.5,
}

// NATS subscriptions
nc.Subscribe("robotics.battery.*", handler)

// Entity properties
entityState.SetProperty("geo.location.latitude", 37.7749)

// NO IRIs in internal code!

Best Practices

Predicate Definition
  1. Use Package Constants

    • Define predicates as package constants
    • Don't inline predicate strings
    • Group by domain and category
  2. Register in init()

    • Register all domain predicates during package initialization
    • Use functional options for clarity
    • Include IRI mappings for customer-facing predicates
  3. Consistent Naming

    • Follow domain.category.property strictly
    • Use lowercase throughout
    • Choose semantic, descriptive names
IRI Mappings
  1. Only When Needed

    • Map to standard IRIs for customer integrations
    • Skip IRI for internal-only predicates
    • Use well-known standards (Schema.org, OWL, SKOS)
  2. At API Boundaries

    • Translate dotted → IRI in RDF export
    • Translate IRI → dotted in RDF import
    • Keep internal code IRI-free
  3. Document Mappings

    • Explain why specific IRI chosen
    • Reference standard vocabulary documentation
    • Note any semantic differences
Entity Resolution
  1. Mark Alias Predicates

    • Use WithAlias() for identity-related predicates
    • Set appropriate priority for conflict resolution
    • Choose correct AliasType for semantics
  2. Avoid Label Confusion

    • Don't use AliasTypeLabel for resolution
    • Labels are for display only (ambiguous)
    • Use identity/alternate/external for unique IDs

Graph Domain Predicates

The vocabulary package provides standard relationship predicates for linking entities in the semantic graph. These graph.rel.* predicates enable rich semantic relationships with mappings to standard vocabularies.

Relationship Types

All relationship predicates follow the pattern graph.rel.* and are registered with PROV-O mappings where applicable.

Hierarchical Relationships
vocabulary.GraphRelContains     // Parent contains child
  • graph.rel.contains → prov:hadMember - Hierarchical containment (platform contains sensors)
Usage Example
import "github.com/c360studio/semengine/vocabulary"

// Create containment relationship between platform and sensor
triple := message.Triple{
    Subject:   "platform-001",
    Predicate: vocabulary.GraphRelContains,  // "graph.rel.contains"
    Object:    "sensor-001",
}

// Query all relationships using NATS wildcards
nc.Subscribe("graph.rel.*", handler)  // All relationship types
nc.Subscribe("graph.rel.contains", handler)  // Only containment
Standards Compliance

Relationship predicates map to established semantic web vocabularies:

  • PROV-O - Provenance and membership relationships

See relationships.go for the complete registration and standards.go for IRI constants.

Framework Predicates

The vocabulary package provides framework predicates in predicates.go.

Applications should define their own domain-specific vocabularies.

  • doc.go - Comprehensive package documentation
  • standards.go - Standard vocabulary IRI constants (SKOS, Dublin Core, PROV-O)
  • message/triple.go - Triple structure for semantic facts
  • message/types.go - EntityID, EntityType, Type patterns

The vocabulary package focuses on predicate management, not IRI generation. For entity-level IRI needs, use the entity's own methods.

Documentation

Overview

Package vocabulary provides semantic vocabulary management for SemEngine. It defines predicates using dotted notation and provides optional IRI mappings for standards compliance at API boundaries.

Architecture Philosophy: Pragmatic Semantic Web

The vocabulary package follows a "pragmatic semantic web" approach:

**Internal**: Clean dotted notation everywhere (domain.category.property)

**External**: Optional IRI/URI mappings at API boundaries for standards compliance

**No Leakage**: Standards complexity does NOT leak into internal architecture

Core Design Principles

1. **Dotted Notation Internally**

  • Predicates: "robotics.battery.level" (not URIs)
  • Enables NATS wildcard queries: "robotics.battery.*"
  • Human-readable and semantic
  • Consistent with message.Type and EntityID patterns

2. **IRI Mappings at Boundaries**

  • Optional StandardIRI field for RDF/OGC export
  • Bidirectional translation (dotted ↔ IRI)
  • Used only for customer integrations
  • Internal code never sees IRIs

3. **Customer Standards Support**

  • RDF/Turtle export with standard vocabularies
  • OGC compliance (GeoSPARQL, SSN/SOSA ontologies)
  • Integration with existing semantic systems
  • Support for domain-specific ontologies

Predicate Structure

Predicates follow three-level dotted notation:

domain.category.property

Examples:

  • sensor.temperature.celsius
  • geo.location.latitude
  • time.lifecycle.created
  • robotics.battery.level

Naming conventions:

  • domain: lowercase, business domain (sensors, geo, time, robotics)
  • category: lowercase, groups related properties (temperature, location, lifecycle)
  • property: lowercase, specific property name (celsius, latitude, created)
  • No underscores or special characters (dots only for level separation)

Predicate Registration

Register domain-specific predicates using functional options:

vocabulary.Register("robotics.battery.level",
    vocabulary.WithDescription("Battery charge level percentage"),
    vocabulary.WithDataType(vocabulary.DataTypeFloat),
    vocabulary.WithUnits("percent"),
    vocabulary.WithRange("0-100"),
    vocabulary.WithIRI("http://schema.org/batteryLevel"))

The registry provides:

  • Metadata about each predicate (type, description, units)
  • Optional IRI mappings for RDF export
  • Alias semantics for entity resolution
  • Runtime predicate discovery

Internal Usage (Always Dotted)

// Creating triples - always use dotted notation
triple := message.Triple{
    Subject:   entityID,
    Predicate: "robotics.battery.level",  // Clean, dotted
    Object:    85.5,
}

// Querying via NATS - wildcards work naturally
nc.Subscribe("robotics.battery.*", handler)  // All battery predicates

// No IRI usage in internal code!

External Usage (IRI Mappings at API Boundaries)

// RDF export - translate dotted to IRI
if meta := vocabulary.GetPredicateMetadata(triple.Predicate); meta != nil {
    if meta.StandardIRI != "" {
        rdfTriple.Predicate = meta.StandardIRI  // "http://schema.org/batteryLevel"
    }
}

Alias Predicates for Entity Resolution

Some predicates represent entity aliases (identifiers, labels, call signs). The registry tracks these for entity resolution:

vocabulary.Register("robotics.communication.callsign",
    vocabulary.WithDescription("Radio call sign for ATC"),
    vocabulary.WithAlias(vocabulary.AliasTypeCommunication, 0))  // Priority 0 = highest

Alias types:

  • AliasTypeIdentity: Entity equivalence (owl:sameAs, schema:sameAs)
  • AliasTypeAlternate: Secondary unique identifiers (model numbers, registration IDs)
  • AliasTypeExternal: External system identifiers (serial numbers, legacy IDs)
  • AliasTypeCommunication: Communication identifiers (call signs, hostnames)
  • AliasTypeLabel: Display names (NOT used for resolution - ambiguous)

Domain Vocabulary Examples

Applications define domain-specific vocabularies:

package robotics

const (
    BatteryLevel = "robotics.battery.level"
    BatteryVoltage = "robotics.battery.voltage"
    FlightModeArmed = "robotics.flight.armed"
)

func init() {
    vocabulary.Register(BatteryLevel,
        vocabulary.WithDescription("Battery charge percentage"),
        vocabulary.WithDataType(vocabulary.DataTypeFloat),
        vocabulary.WithUnits("percent"),
        vocabulary.WithRange("0-100"),
        vocabulary.WithIRI("http://schema.org/batteryLevel"))
    // ... register other predicates
}

Standards Mappings

Common standard vocabulary IRIs are provided in standards.go:

const (
    SkosBroader = "http://www.w3.org/2004/02/skos/core#broader"
    DcTitle = "http://purl.org/dc/terms/title"
    ProvHadMember = ProvNamespace + "hadMember"
    // ... the others in standards.go
)

Use these constants when registering predicates with standard mappings:

vocabulary.Register("entity.label.preferred",
    vocabulary.WithIRI(vocabulary.DcTitle))

Best Practices

## Predicate Definition

1. **Use Package Constants**

  • Define predicates as package constants
  • Don't inline predicate strings at call sites
  • Group by domain and category

2. **Register in init()**

  • Register all domain predicates during package initialization
  • Use functional options for clarity
  • Include IRI mappings for customer-facing predicates

3. **Consistent Naming**

  • Follow domain.category.property pattern strictly
  • Use lowercase throughout
  • Choose semantic, descriptive names

## IRI Mappings

1. **Only When Needed**

  • Map to standard IRIs for customer integrations
  • Skip IRI for internal-only predicates
  • Use well-known standards (Schema.org, OWL, SKOS, etc.)

2. **At API Boundaries**

  • Translate dotted → IRI in RDF export
  • Translate IRI → dotted in RDF import
  • Keep internal code IRI-free

3. **Document Mappings**

  • Explain why specific IRI chosen
  • Reference standard vocabulary documentation
  • Note any semantic differences

## Entity Resolution

1. **Mark Alias Predicates**

  • Use WithAlias() for identity-related predicates
  • Set appropriate priority for conflict resolution
  • Choose correct AliasType for semantics

2. **Avoid Label Confusion**

  • Don't use AliasTypeLabel for resolution
  • Labels are for display only (ambiguous)
  • Use identity/alternate/external for unique IDs

Registry API

The global predicate and entity-type registry provides:

// Register a predicate
Register(name string, opts ...Option)

// Retrieve metadata or reverse-lookup canonical predicates by IRI
GetPredicateMetadata(name string) *PredicateMetadata
LookupByIRI(iri string) []string

// Register and look up entity-type (<domain>.<type>) class metadata
RegisterEntityType(domainType string, opts ...EntityTypeOption)
GetEntityTypeMetadata(domainType string) *EntityTypeMetadata
LookupEntityTypesByClassIRI(classIRI string) []string

// Load and fail-closed register declarative JSON/YAML vocabulary packs
LoadPackJSON(r io.Reader) (PackSpec, error)
LoadPackYAML(r io.Reader) (PackSpec, error)
RegisterPack(pack PackSpec, opts ...PackOption) error

// List all registered
ListRegisteredPredicates() []string
ListRegisteredEntityTypes() []string

// Discover aliases
DiscoverAliasPredicates() map[string]int

// Clear (testing only)
ClearRegistry()

Design Philosophy Summary

The vocabulary package embodies these principles:

1. **Simplicity**: Dotted notation is clean and human-readable 2. **NATS-friendly**: Wildcards work naturally with dotted predicates 3. **Standards-compliant**: Optional IRI mappings at boundaries 4. **No Leakage**: External complexity stays external 5. **Customer Value**: Support RDF/OGC without internal cost

This "pragmatic semantic web" approach gives you:

  • Clean internal architecture
  • Standards compliance where needed
  • Customer integration support
  • NATS query power
  • Human-readable code

Package vocabulary provides semantic vocabulary definitions and mappings.

Index

Constants

View Source
const (
	// LifecycleTransitionFrom records the phase an occurrence left.
	LifecycleTransitionFrom = "lifecycle.transition.from"
	// LifecycleTransitionTo records the phase an occurrence entered.
	LifecycleTransitionTo = "lifecycle.transition.to"
	// LifecycleTransitionAt records the occurrence timestamp.
	LifecycleTransitionAt = "lifecycle.transition.at"
	// LifecycleTransitionSource records the typed transition trigger.
	LifecycleTransitionSource = "lifecycle.transition.source"
	// LifecycleTransitionNote records an optional operator-facing annotation.
	LifecycleTransitionNote = "lifecycle.transition.note"
)
View Source
const (
	// MaxPredicateSegmentBytes bounds each domain/category/property token.
	MaxPredicateSegmentBytes = 64
	// MaxPredicateBytes is three maximum-length segments plus two separators.
	MaxPredicateBytes = 3*MaxPredicateSegmentBytes + 2
)
View Source
const (
	// GeoLocationLatitude is float64, degrees (-90 to 90)
	GeoLocationLatitude = "geo.location.latitude"
	// GeoLocationLongitude is float64, degrees (-180 to 180)
	GeoLocationLongitude = "geo.location.longitude"
	// GeoLocationAltitude is float64, meters above sea level
	GeoLocationAltitude = "geo.location.altitude"
)
View Source
const (
	// HierarchyDomainMember indicates entity belongs to a domain (3-part prefix match).
	// Subject is the entity, object is the domain prefix (e.g., "acme.dep1.sensor").
	// StandardIRI: skos:broader (entity is narrower than domain)
	// InverseOf: HierarchyDomainContains
	// Example: sensor-temp-001 hierarchy.domain.member acme.dep1.sensor
	HierarchyDomainMember = "hierarchy.domain.member"

	// HierarchyDomainContains indicates domain contains an entity (inverse of HierarchyDomainMember).
	// Subject is the domain, object is the entity.
	// StandardIRI: skos:narrower (domain contains narrower entities)
	// InverseOf: HierarchyDomainMember
	// Example: acme.dep1.sensor hierarchy.domain.contains sensor-temp-001
	HierarchyDomainContains = "hierarchy.domain.contains"

	// HierarchySystemMember indicates entity belongs to a system (4-part prefix match).
	// Subject is the entity, object is the system prefix (e.g., "acme.dep1.document.sensor").
	// StandardIRI: skos:broader (entity is narrower than system)
	// InverseOf: HierarchySystemContains
	// Example: sensor-temp-001 hierarchy.system.member acme.dep1.document.sensor
	HierarchySystemMember = "hierarchy.system.member"

	// HierarchySystemContains indicates system contains an entity (inverse of HierarchySystemMember).
	// Subject is the system, object is the entity.
	// StandardIRI: skos:narrower (system contains narrower entities)
	// InverseOf: HierarchySystemMember
	// Example: acme.dep1.document.sensor hierarchy.system.contains sensor-temp-001
	HierarchySystemContains = "hierarchy.system.contains"

	// HierarchyTypeSibling indicates entities share the same type (5-part prefix match).
	// Bidirectional relationship between entities with same type prefix.
	// StandardIRI: skos:related (symmetric relationship)
	// IsSymmetric: true (if A is sibling of B, B is sibling of A)
	// Example: sensor-temp-001 hierarchy.type.sibling sensor-temp-002
	HierarchyTypeSibling = "hierarchy.type.sibling"

	// HierarchyTypeMember indicates entity belongs to a type container (5-part prefix + .group).
	// Subject is the entity, object is the type container entity ID.
	// StandardIRI: skos:broader (entity is narrower than type container)
	// InverseOf: HierarchyTypeContains
	// Example: acme.iot.sensors.hvac.temperature.001 hierarchy.type.member acme.iot.sensors.hvac.temperature.group
	HierarchyTypeMember = "hierarchy.type.member"

	// HierarchyTypeContains indicates type container contains an entity (inverse of HierarchyTypeMember).
	// Subject is the type container, object is the entity.
	// StandardIRI: skos:narrower (container contains narrower entities)
	// InverseOf: HierarchyTypeMember
	// Example: acme.iot.sensors.hvac.temperature.group hierarchy.type.contains acme.iot.sensors.hvac.temperature.001
	HierarchyTypeContains = "hierarchy.type.contains"
)
View Source
const (
	// IndexingProfileContent is the retrieval corpus (embed yes, community yes):
	// memory, documents, research facts, lessons, prose-bearing entities.
	IndexingProfileContent = "content"
	// IndexingProfileControl is low-cardinality lifecycle/harness/run machinery
	// (embed yes — the cardinality guard excludes high-fan-out control types —
	// community yes). The substrate stays semantically reachable. Default floor.
	IndexingProfileControl = "control"
	// IndexingProfileSignal is telemetry readings (embed only summarized
	// rollups, community aggregate only). Raw readings stay graph-visible, not
	// embedded.
	IndexingProfileSignal = "signal"
	// IndexingProfileTrace is mechanically generated audit/trace entities (embed
	// no, community no). Fully graph-visible and queryable, but never embedded.
	IndexingProfileTrace = "trace"
)
View Source
const (
	// DataTypeString declares plain text.
	DataTypeString = "string"
	// DataTypeEntityID declares that the object is a canonical 6-part entity
	// ID rather than text that happens to resemble one.
	DataTypeEntityID = "entity_id"
	// DataTypeInt declares that the number is semantically whole, whatever the
	// JSON round trip left in the Go value.
	DataTypeInt = "int"
	// DataTypeFloat declares a real number.
	DataTypeFloat = "float"
	// DataTypeBool declares a truth value.
	DataTypeBool = "bool"
	// DataTypeDateTime declares an instant, whether carried as a time.Time or
	// as an RFC 3339 string.
	DataTypeDateTime = "datetime"
	// DataTypeJSON declares that the string holds a structured document.
	DataTypeJSON = "json"
)
View Source
const (
	// SkosNotation provides a notation (code or identifier) within a concept scheme.
	// Used for: AliasTypeAlternate
	SkosNotation = "http://www.w3.org/2004/02/skos/core#notation"

	// SkosBroader indicates a hierarchical link to a more general concept.
	// Used for: hierarchy.*.member predicates (entity → container membership)
	// Example: sensor-001 skos:broader temperature-group (sensor is narrower than group)
	SkosBroader = "http://www.w3.org/2004/02/skos/core#broader"

	// SkosNarrower indicates a hierarchical link to a more specific concept.
	// Inverse of SkosBroader.
	// Example: temperature-group skos:narrower sensor-001 (group contains sensor)
	SkosNarrower = "http://www.w3.org/2004/02/skos/core#narrower"

	// SkosRelated indicates an associative (non-hierarchical) link between concepts.
	// Used for: hierarchy.type.sibling predicates (symmetric relationship)
	// Example: sensor-001 skos:related sensor-002 (siblings in same type group)
	SkosRelated = "http://www.w3.org/2004/02/skos/core#related"
)

SKOS (Simple Knowledge Organization System) Standard IRIs

View Source
const (
	// DcIdentifier provides an unambiguous reference to the resource.
	// Used for: AliasTypeExternal
	// Example: ISBN, DOI, serial number
	DcIdentifier = "http://purl.org/dc/terms/identifier"

	// DcTitle provides the name given to the resource.
	// Used for: AliasTypeLabel
	DcTitle = "http://purl.org/dc/terms/title"
)

Dublin Core Metadata Terms Standard IRIs

View Source
const (
	// ContentClassificationTag is a multi-valued string classification tag
	// (one triple per tag) carrying thematic vocabulary for content entities.
	ContentClassificationTag = "content.classification.tag"
)

Content Domain Predicates Product-neutral content-classification convention. Products that classify content emit these; the framework recognizes them for synthesis/enrichment.

View Source
const (
	// DCTermsTitle is the dotted notation predicate for resource title.
	// Maps to: DcTitle (http://purl.org/dc/terms/title)
	DCTermsTitle = "dc.terms.title"
)

Dublin Core Dotted Notation Predicates These constants provide dotted notation predicates for use in Triples. They map semantically to the Dublin Core IRIs above.

View Source
const EntityIndexingProfile = "entity.indexing.profile"

EntityIndexingProfile is the reserved single-valued predicate carrying an entity's indexing profile (one of the IndexingProfile* values below). Stamped at entity creation (replace-on-write); read by indexing consumers.

View Source
const (
	// GraphRelContains represents hierarchical containment (parent contains child)
	// Example: A platform contains sensors, a system contains components
	GraphRelContains = "graph.rel.contains"
)
View Source
const (
	// ProvGeneratedAtTime indicates when an entity was generated.
	// Domain: Entity, Range: xsd:dateTime
	ProvGeneratedAtTime = ProvNamespace + "generatedAtTime"
)

PROV-O Time Properties Properties for expressing when activities occurred and entities existed.

View Source
const (
	// ProvHadMember indicates membership in a collection.
	// Domain: Collection, Range: Entity
	// Used for: GraphRelContains
	ProvHadMember = ProvNamespace + "hadMember"
)

PROV-O Association Relations Relations expressing how agents are associated with activities.

View Source
const (
	// ProvNamespace is the base IRI prefix for all PROV-O terms.
	ProvNamespace = "http://www.w3.org/ns/prov#"
)

PROV-O Namespace

View Source
const (
	// ProvWasAttributedTo indicates who an entity was attributed to.
	// Domain: Entity, Range: Agent
	ProvWasAttributedTo = ProvNamespace + "wasAttributedTo"
)

PROV-O Derivation Relations Relations expressing how entities derive from other entities.

View Source
const (
	SemEngineBase = "https://semengine.semanticstream.ing"
)

Base IRI constants for the SemEngine vocabulary

Variables

This section is empty.

Functions

func ClearRegistry

func ClearRegistry()

ClearRegistry clears all registered predicates and entity types. This is primarily useful for testing.

func DiscoverAliasPredicates

func DiscoverAliasPredicates() map[string]int

DiscoverAliasPredicates discovers all predicates marked as aliases in the registry. Returns a map of predicate name to priority (lower number = higher priority). Used by AliasIndex to determine which predicates to index.

If no alias predicates are registered, returns an empty map. Applications must register their domain-specific alias predicates using Register().

func DiscoverLabelPredicates

func DiscoverLabelPredicates() map[string]int

DiscoverLabelPredicates discovers all predicates marked as human-readable labels (AliasTypeLabel) in the registry. Returns predicate name → priority (lower number = higher salience).

These are the display-name predicates the alias index deliberately EXCLUDES (labels are ambiguous for ID resolution — CanResolveToEntityID is false for AliasTypeLabel), and are exactly what the name index keys on for name→ranked-IDs lookup. Applications register their own label predicates via Register(pred, WithAlias(AliasTypeLabel, priority)), the same mechanism as aliases. Empty when none are registered.

func GetInversePredicate

func GetInversePredicate(predicate string) string

GetInversePredicate returns the inverse predicate name, if defined. Returns an empty string if no inverse is defined for the given predicate.

For symmetric predicates (IsSymmetric=true), returns the predicate itself since symmetric predicates are their own inverse.

Example:

GetInversePredicate("hierarchy.type.member")   // Returns "hierarchy.type.contains"
GetInversePredicate("hierarchy.type.sibling")  // Returns "hierarchy.type.sibling" (symmetric)
GetInversePredicate("sensor.temperature.celsius")  // Returns "" (no inverse)

func IsRuleOpaque

func IsRuleOpaque(predicate string) bool

IsRuleOpaque reports whether a predicate is marked rule-opaque. Returns false for unregistered predicates so that vocabulary registration is the only path to opacity — undeclared predicates stay rule-matchable by default. See ADR-036.

func IsValidIndexingProfile

func IsValidIndexingProfile(s string) bool

IsValidIndexingProfile reports whether s is one of the four recognized indexing profiles. Empty and unrecognized strings are invalid (callers treat invalid as "absent" and fall through to the fallback floor rather than failing, per ADR-054 lenient Phase 1 semantics).

func IsValidPredicate

func IsValidPredicate(predicate string) bool

IsValidPredicate reports whether predicate satisfies the canonical lower-kebab domain.category.property contract. ParsePredicate returns the typed reason.

func ListRegisteredEntityTypes

func ListRegisteredEntityTypes() []string

ListRegisteredEntityTypes returns all registered "<domain>.<type>" keys sorted in lexicographical order.

func ListRegisteredPredicates

func ListRegisteredPredicates() []string

ListRegisteredPredicates returns a list of all registered predicate names. Useful for debugging and introspection.

func LookupByIRI

func LookupByIRI(iri string) []string

LookupByIRI returns a newly allocated slice of all canonical 3-part dotted predicates registered with StandardIRI equal to iri, sorted in lexicographical order, or nil when iri is empty or no predicate is registered for iri.

func LookupEntityTypesByClassIRI

func LookupEntityTypesByClassIRI(classIRI string) []string

LookupEntityTypesByClassIRI returns all registered "<domain>.<type>" keys whose ClassIRI or Superclasses contain classIRI, sorted in lexicographical order, or nil when classIRI is empty or matches no registered entity type.

func ParseEntityTypeKey

func ParseEntityTypeKey(domainType string) (domain, entityType string, err error)

ParseEntityTypeKey validates and decomposes a two-segment lower-kebab ASCII entity-type key "<domain>.<type>". Each segment follows the vocabulary predicate segment grammar ([a-z][a-z0-9-]* with no trailing '-', at most MaxPredicateSegmentBytes bytes), which is deliberately narrower than the general segment grammar accepted by pkg/types.ValidateEntityID.

func Register

func Register(name string, opts ...Option)

Register registers (or amends) a predicate's metadata in the global registry. This should be called during package initialization (init functions) by domain vocabularies.

The predicate name must follow three-level dotted notation: domain.category.property

AMEND semantics (gh#410): a re-Register of an already-registered predicate starts from the EXISTING metadata, then applies the given options. Options override every field they set; fields the re-Register OMITS are RETAINED, not cleared. This lets a product attach its own Description/IRI to a framework-registered predicate WITHOUT silently stripping the framework's declared roles (e.g. a WithAlias(AliasTypeLabel, …) on dc.terms.title, which the NAME_INDEX / graph.query.byName / fusion-readiness path depends on). A first registration starts from a zero struct, so single-registration behavior is unchanged.

Amend cannot CLEAR a field by omitting its option; pass the explicit zero (WithRuleOpaque(false), WithWeight(0), WithDescription(""), …) to clear one. The alias flag has no un-alias option.

Example:

Register("robotics.battery.level",
    WithDescription("Battery charge level percentage"),
    WithDataType(DataTypeFloat),
    WithUnits("percent"),
    WithRange("0-100"),
    WithIRI("http://schema.org/batteryLevel"))

func RegisterEntityType

func RegisterEntityType(domainType string, opts ...EntityTypeOption)

RegisterEntityType registers or amends metadata for a "<domain>.<type>" entity-type key. It panics if domainType does not satisfy ParseEntityTypeKey or if any option supplies an empty or whitespace-containing IRI.

func RegisterPack

func RegisterPack(pack PackSpec, opts ...PackOption) error

RegisterPack validates every prefix, predicate, and entity type in pack before mutating state. If any entry is invalid or if the optional batch prefix registrar returns an error, RegisterPack leaves the predicate and entity-type registries unchanged.

func RequireDeclaredPredicate

func RequireDeclaredPredicate(predicate string) error

RequireDeclaredPredicate enforces the v1 first-party authoring policy. The predicate must be canonical and registered by a trusted composition-root or vocabulary package before a configuration, workflow, ownership claim, or generated mutation surface may expose it. Runtime graph persistence uses the syntax-only final-candidate seam instead; caller-controlled fields never manufacture declaration authority.

func SnapshotRegistry

func SnapshotRegistry() func()

SnapshotRegistry captures the current registry state and returns a restore function. Intended for tests that register predicates transiently and need to undo without leaving stub entries behind.

Example:

defer vocabulary.SnapshotRegistry()()
vocabulary.Register("test.foo.bar", ...)
// test runs; deferred restore reverts the registry to its pre-test state.

Types

type AliasType

type AliasType string

AliasType defines the semantic meaning of an alias predicate.

Each type corresponds to standard W3C/RDF vocabularies for semantic web interoperability. See vocabulary/standards.go for IRI constants to use in PredicateMetadata.StandardIRI.

const (
	// AliasTypeIdentity represents entity equivalence.
	//
	// Standard Mappings:
	//   - owl:sameAs (OWL_SAME_AS)
	//   - schema:sameAs (SCHEMA_SAME_AS)
	//
	// Used for: Federated entity IDs, external system UUIDs, cross-system identity
	// Resolution: ✅ Can resolve to entity IDs
	// Example: "uuid:abc-123" identifies the same entity as "c360.platform.test.drone.001"
	AliasTypeIdentity AliasType = "identity"

	// AliasTypeLabel represents human-readable display names.
	//
	// Standard Mappings:
	//   - skos:prefLabel (SKOS_PREF_LABEL) - preferred label
	//   - skos:altLabel (SKOS_ALT_LABEL) - alternative label
	//   - rdfs:label (RDFS_LABEL) - generic label
	//   - dc:title (DC_TITLE) - title
	//   - schema:name (SCHEMA_NAME) - name
	//   - foaf:name (FOAF_NAME) - name
	//
	// Used for: Display names, titles, human-readable descriptions
	// Resolution: ❌ NOT used for entity resolution (ambiguous - many entities can share labels)
	// Example: "Alpha Drone", "Battery 1" - for display only
	AliasTypeLabel AliasType = "label"

	// AliasTypeAlternate represents secondary unique identifiers.
	//
	// Standard Mappings:
	//   - schema:alternateName (SCHEMA_ALTERNATE_NAME)
	//   - dc:alternative (DC_ALTERNATIVE)
	//   - skos:notation (SKOS_NOTATION)
	//   - foaf:nick (FOAF_NICK)
	//
	// Used for: Model numbers, registration IDs, alternative unique identifiers
	// Resolution: ✅ Can resolve to entity IDs
	// Example: "MODEL-X1000", "REG-12345"
	AliasTypeAlternate AliasType = "alternate"

	// AliasTypeExternal represents external system identifiers.
	//
	// Standard Mappings:
	//   - dc:identifier (DC_IDENTIFIER)
	//   - schema:identifier (SCHEMA_IDENTIFIER)
	//   - dc:source (DC_SOURCE)
	//
	// Used for: Manufacturer serial numbers, legacy system IDs, third-party references
	// Resolution: ✅ Can resolve to entity IDs
	// Example: "SN-12345", "LEGACY-DB-ID-789", "VENDOR-REF-456"
	AliasTypeExternal AliasType = "external"

	// AliasTypeCommunication represents communication system identifiers.
	//
	// Standard Mappings:
	//   - foaf:accountName (FOAF_ACCOUNT_NAME)
	//
	// Used for: Radio call signs, network hostnames, MQTT client IDs, communication endpoints
	// Resolution: ✅ Can resolve to entity IDs
	// Example: "ALPHA-1" (call sign), "drone.local" (hostname), "mqtt-client-001"
	AliasTypeCommunication AliasType = "communication"
)

func (AliasType) CanResolveToEntityID

func (at AliasType) CanResolveToEntityID() bool

CanResolveToEntityID returns true if this alias type can be used for entity resolution

func (AliasType) String

func (at AliasType) String() string

String returns the string representation of the alias type

type EntityTypeMetadata

type EntityTypeMetadata struct {
	// DomainType is the canonical "<domain>.<type>" key (for example, "uxs.uas").
	DomainType string

	// Domain is the first segment of DomainType (0-indexed segment 2 of an entity ID).
	Domain string

	// Type is the second segment of DomainType (0-indexed segment 4 of an entity ID).
	Type string

	// Description provides human-readable documentation for the entity type.
	Description string

	// ClassIRI is the primary RDF/OWL class IRI for entities of this type.
	ClassIRI string

	// Superclasses holds additional RDF/OWL class IRIs (for example, parent
	// CCO/BFO classes) in registration order without duplicates.
	Superclasses []string
	// contains filtered or unexported fields
}

EntityTypeMetadata maps a two-segment lower-kebab entity-type key (<domain>.<type>, naming the domain and type segments at 0-indexed positions 2 and 4 of a 6-part entity ID) to its RDF/OWL class IRI and superclass IRIs.

func GetEntityTypeMetadata

func GetEntityTypeMetadata(domainType string) *EntityTypeMetadata

GetEntityTypeMetadata returns a defensive copy of the registered metadata for domainType, or nil if domainType is not registered.

type EntityTypeOption

type EntityTypeOption func(*EntityTypeMetadata)

EntityTypeOption configures an EntityTypeMetadata registration.

func WithClassIRI

func WithClassIRI(iri string) EntityTypeOption

WithClassIRI sets the primary RDF/OWL class IRI for an entity type. Passing an empty or whitespace-containing IRI causes RegisterEntityType to panic.

func WithEntityTypeDescription

func WithEntityTypeDescription(desc string) EntityTypeOption

WithEntityTypeDescription sets the human-readable description of an entity type.

func WithSuperclass

func WithSuperclass(iri string) EntityTypeOption

WithSuperclass appends a superclass IRI to an entity type's Superclasses slice if it is not already present. Passing an empty or whitespace-containing IRI causes RegisterEntityType to panic.

type EntityTypeSpec

type EntityTypeSpec struct {
	DomainType   string   `json:"domain_type" yaml:"domain_type"`
	Description  string   `json:"description,omitempty" yaml:"description,omitempty"`
	ClassIRI     string   `json:"class_iri,omitempty" yaml:"class_iri,omitempty"`
	Superclasses []string `json:"superclasses,omitempty" yaml:"superclasses,omitempty"`
}

EntityTypeSpec declares a canonical 2-part "<domain>.<type>" entity-type key and its RDF/OWL class mappings in a declarative vocabulary pack.

type Option

type Option func(*PredicateMetadata)

Option is a functional option for configuring predicate registration.

func WithAlias

func WithAlias(aliasType AliasType, priority int) Option

WithAlias marks this predicate as representing an entity alias. Aliases are used for entity resolution and identity correlation.

Parameters:

  • aliasType: The semantic meaning (identity, alternate, external, communication, label)
  • priority: Conflict resolution order (lower number = higher priority)

Example:

Register("robotics.communication.callsign",
    WithAlias(AliasTypeCommunication, 0))  // Highest priority

func WithDataType

func WithDataType(dataType string) Option

WithDataType declares the pragmatic type of the object value. Pass one of the seven canonical constants — DataTypeString, DataTypeEntityID, DataTypeInt, DataTypeFloat, DataTypeBool, DataTypeDateTime, DataTypeJSON.

It is NOT the Go type of the value: the serializer observes that directly, and the authoritative JSON round trip erases it anyway. Declare only what observation cannot recover — that an object is an entity reference, that a number is semantically whole, that a string holds a structured document.

The parameter stays a plain string so existing call sites keep compiling, but any value outside the closed vocabulary panics at registration, naming the accepted set. Nothing is normalized: a legacy spelling is refused like any other non-canonical value, and the adopter migrates (docs/operations/migration-predicate-datatype.md). Declaring nothing is legal (gh#1267, ADR-107).

Example:

Register("robotics.battery.cycles",
    WithDescription("Battery charge cycles"),
    WithDataType(DataTypeInt))

func WithDescription

func WithDescription(desc string) Option

WithDescription sets the human-readable description of the predicate.

func WithIRI

func WithIRI(iri string) Option

WithIRI sets the W3C/RDF equivalent IRI for standards compliance. This enables RDF/JSON-LD export and semantic web interoperability. Use constants from standards.go for common vocabularies.

Examples:

func WithInverseOf

func WithInverseOf(inversePredicate string) Option

WithInverseOf declares the inverse predicate name. The inverse predicate should also be registered with its own metadata, pointing back to this predicate as its inverse.

Example:

Register("hierarchy.type.member",
    WithIRI(SkosBroader),
    WithInverseOf("hierarchy.type.contains"))

Register("hierarchy.type.contains",
    WithIRI(SkosNarrower),
    WithInverseOf("hierarchy.type.member"))

Note: The registry stores the inverse relationship but does not auto-generate inverse triples at runtime. Applications can use GetInversePredicate() to look up the inverse name for display or reasoning purposes.

func WithProjection

func WithProjection(spec ProjectionSpec) Option

WithProjection attaches a reified ontology projection specification to a predicate registration. Passing an empty Steps slice or a malformed step panics at registration.

func WithRange

func WithRange(valueRange string) Option

WithRange describes valid values as free-form DOCUMENTATION on the declaration. Examples: "0-100", "-90 to 90", "positive" — three incompatible grammars, which is why nothing parses it.

No framework path validates, normalizes, interprets, or honors the value. See WithUnits (gh#1267 Q4, tracked on gh#1264).

func WithRuleOpaque

func WithRuleOpaque(opaque bool) Option

WithRuleOpaque marks the predicate as carrying free-form content that rules must not predicate on. The rule-validator rejects rule conditions whose `field` names a rule-opaque predicate at config-load time. See ADR-036 for the asymmetric-ownership rationale.

Example:

Register("agent.todo.record",
    WithDescription("Free-form private todo record"),
    WithDataType(DataTypeString),
    WithRuleOpaque(true))

func WithSymmetric

func WithSymmetric(symmetric bool) Option

WithSymmetric marks the predicate as symmetric (its own inverse). Symmetric predicates imply bidirectional relationships: if A relates to B, then B relates to A with the same predicate.

Example:

Register("hierarchy.type.sibling",
    WithIRI(SkosRelated),
    WithSymmetric(true))

When IsSymmetric is true, GetInversePredicate() returns the predicate itself. Do not set both WithSymmetric(true) and WithInverseOf() on the same predicate.

func WithUnits

func WithUnits(units string) Option

WithUnits carries measurement units as free-form DOCUMENTATION on the declaration. Examples: "percent", "meters", "celsius", "pascals".

No framework path validates, normalizes, interprets, or honors the value — unlike WithDataType, which is honored at export. Saying so is a smaller promise than the field's presence beside DataType currently implies, and it is one the framework actually keeps (gh#1267 Q4, tracked on gh#1264).

func WithWeight

func WithWeight(weight float64) Option

WithWeight declares the predicate's salience weight, SIGNED: positive = more salient (boost), 0 = neutral, NEGATIVE = down-rank (demote). Lets a ranker prefer entities carrying salient facts — or push down structurally- identifiable noise (tests, generated code, mocks) that carries the same boosted predicates as the real thing — without a per-product weight table (ADR-062 increment 5, semsource ask #2; negative weights gh#441). The fusion ranker folds an entity's strongest boost and strongest demotion together, so a negative weight is a bounded reordering, never an exclusion.

Example (demote tests below their impl, both carrying the same doc-comment salience):

Register("code.artifact.test", WithWeight(-1.5))

type PackOption

type PackOption func(*packConfig)

PackOption configures how RegisterPack applies a PackSpec.

func WithPrefixRegistrar

func WithPrefixRegistrar(fn func(prefixes []PrefixSpec) error) PackOption

WithPrefixRegistrar supplies an atomic batch callback (such as export.RegisterPrefixes) that RegisterPack invokes with the pack's PrefixSpec slice after all pack entries pass validation.

type PackSpec

type PackSpec struct {
	Name        string           `json:"name" yaml:"name"`
	Version     string           `json:"version,omitempty" yaml:"version,omitempty"`
	Prefixes    []PrefixSpec     `json:"prefixes,omitempty" yaml:"prefixes,omitempty"`
	Predicates  []PredicateSpec  `json:"predicates,omitempty" yaml:"predicates,omitempty"`
	EntityTypes []EntityTypeSpec `json:"entity_types,omitempty" yaml:"entity_types,omitempty"`
}

PackSpec is a declarative JSON or YAML vocabulary pack containing namespace prefixes, predicates, and entity-type class mappings (such as BFO, CCO, or DIEKM domain packs).

func LoadPackJSON

func LoadPackJSON(r io.Reader) (PackSpec, error)

LoadPackJSON decodes a PackSpec from JSON, refusing unknown fields, malformed syntax, empty input, or trailing JSON values.

func LoadPackYAML

func LoadPackYAML(r io.Reader) (PackSpec, error)

LoadPackYAML decodes a PackSpec from YAML, refusing unknown fields, malformed syntax, empty input, or trailing YAML documents.

type PredicateMetadata

type PredicateMetadata struct {
	// Name is the predicate constant (e.g., "sensor.temperature.celsius")
	// Uses dotted notation for NATS stream query compatibility
	Name string

	// Description provides human-readable documentation
	Description string

	// DataType declares the pragmatic type of the object value, as one of
	// the seven canonical DataType* values, or is absent.
	//
	// It is NOT the Go type of the value. The serializer observes the Go type
	// directly, and a value read back through the authoritative ENTITY_STATES
	// JSON round trip no longer carries the Go type its author predicted — a
	// declared whole number arrives as float64 every time. The declaration
	// therefore carries only what observation cannot recover.
	//
	// Any value outside the closed vocabulary is refused at registration, and
	// nothing is normalized — what is declared here is what every reader
	// observes. Absent is legal.
	// RDF export honors the declaration, and ignores it for any triple whose
	// observed value contradicts it (gh#1267, ADR-107).
	DataType string

	// Units carries human-readable measurement units, as free-form
	// DOCUMENTATION on the declaration. Examples: "percent", "celsius".
	//
	// No framework path validates, normalizes, interprets, or honors it. That
	// is stated rather than left implicit because the alternative failure is
	// silent: a field that looks typed, sits beside DataType which IS honored,
	// and is frozen into a released surface reads as a promise the system does
	// not keep. When a consumer is named it arrives with its own change; a
	// closed vocabulary is deliberately not invented ahead of one (gh#1267 Q4,
	// tracked on gh#1264).
	Units string

	// Range carries a human-readable description of valid values, as free-form
	// DOCUMENTATION on the declaration. Examples: "0-100", "-90 to 90",
	// "positive" — three incompatible grammars, which is why no framework path
	// validates, normalizes, interprets, or honors it. See Units (gh#1267 Q4,
	// tracked on gh#1264).
	Range string

	// Domain identifies which domain owns this predicate
	Domain string

	// Category identifies the predicate category within the domain
	Category string

	// StandardIRI provides the W3C/RDF equivalent IRI for standards compliance (optional)
	// Examples: "http://www.w3.org/2002/07/owl#sameAs", "http://www.w3.org/2004/02/skos/core#prefLabel"
	// This enables RDF/JSON-LD export and semantic web interoperability while maintaining
	// dotted notation for NATS compatibility internally.
	// See vocabulary/standards.go for common constants.
	StandardIRI string

	// Alias semantics (for entity resolution and alias indexing)
	// IsAlias marks predicates that represent entity aliases
	IsAlias bool

	// AliasType defines the semantic meaning (identity, label, external, etc.)
	// Only meaningful when IsAlias is true. See AliasType documentation for
	// standard vocabulary mappings (OWL, SKOS, Schema.org).
	AliasType AliasType

	// AliasPriority defines conflict resolution order (lower number = higher priority)
	// Only meaningful when IsAlias is true
	AliasPriority int

	// InverseOf names the predicate that represents the inverse relationship.
	// Example: "hierarchy.type.member" has InverseOf = "hierarchy.type.contains"
	// When entity A → hierarchy.type.member → B, the inverse relationship is
	// B → hierarchy.type.contains → A.
	//
	// Important: Both predicates in an inverse pair should be registered with
	// their InverseOf pointing to each other. The registry stores relationships;
	// it does not auto-generate inverse triples at runtime.
	//
	// StandardIRI equivalent: owl:inverseOf
	InverseOf string

	// IsSymmetric indicates the predicate is its own inverse.
	// Example: "hierarchy.type.sibling" - if A is sibling of B, then B is sibling of A.
	// Symmetric predicates don't need InverseOf set; GetInversePredicate() returns
	// the predicate itself for symmetric cases.
	//
	// StandardIRI equivalent: owl:SymmetricProperty
	IsSymmetric bool

	// RuleOpaque marks the predicate as carrying free-form content that
	// rules MUST NOT predicate on. The rule-validator rejects rule
	// conditions whose `field` names a rule-opaque predicate at
	// config-load time.
	//
	// Used for agent-private observable state (ADR-036): the owning
	// agent is the sole writer and sole interpreter of content; rules
	// may match structural facts (counts, status enums, transitions)
	// but not the content itself. The asymmetric ownership pattern
	// avoids LLM-on-LLM checklist Goodhart by keeping content out of
	// the rule-engine's branching surface.
	RuleOpaque bool

	// Weight is the predicate's salience weight for ranking, SIGNED: positive =
	// more salient (boost), 0 = unweighted (neutral), negative = down-rank
	// (demote, gh#441). Lets a ranker prefer entities carrying salient facts, or
	// push down structurally-identifiable noise (tests, generated code, mocks)
	// that carries the same boosted predicates as the real thing, without
	// hard-coding a per-product table.
	Weight float64

	// Projection declares an optional reified ontology projection chain (for
	// example, a BFO/CCO ActOfMeasuring intermediate node and value predicate)
	// used by external RDF/SPARQL projection adapters without storing blank
	// nodes in ENTITY_STATES.
	Projection *ProjectionSpec
}

PredicateMetadata provides semantic information about each predicate This enables validation, type checking, and documentation generation

func GetPredicateMetadata

func GetPredicateMetadata(predicate string) *PredicateMetadata

GetPredicateMetadata retrieves metadata for a predicate from the registry. Returns nil if the predicate is not registered. This function is thread-safe and can be called concurrently.

type PredicateNamespace

type PredicateNamespace struct {
	Domain   string
	Category string
}

PredicateNamespace is an exact vocabulary namespace delegation. Category is empty for a domain-wide delegation and non-empty for a domain.category delegation. Wildcards and property-level namespaces are not supported.

func ParsePredicateNamespace

func ParsePredicateNamespace(namespace string) (PredicateNamespace, error)

ParsePredicateNamespace validates an exact domain or domain.category namespace using the same lower-kebab segment grammar and byte bound as stored predicates.

func (PredicateNamespace) String

func (n PredicateNamespace) String() string

String returns the exact delegated namespace.

type PredicateParts

type PredicateParts struct {
	Domain   string
	Category string
	Property string
}

PredicateParts is the canonical semantic decomposition of a predicate.

func ParsePredicate

func ParsePredicate(predicate string) (PredicateParts, error)

ParsePredicate validates and decomposes a canonical predicate. Each of the three segments is lower-kebab ASCII: [a-z][a-z0-9]*(-[a-z0-9]+)*. Previously-validated predicates are served from the memo above; results are identical to a cold parse.

func (PredicateParts) String

func (p PredicateParts) String() string

String reconstructs the exact canonical predicate identity.

type PredicateSpec

type PredicateSpec struct {
	Name          string          `json:"name" yaml:"name"`
	Description   string          `json:"description,omitempty" yaml:"description,omitempty"`
	DataType      string          `json:"data_type,omitempty" yaml:"data_type,omitempty"`
	Units         string          `json:"units,omitempty" yaml:"units,omitempty"`
	Range         string          `json:"range,omitempty" yaml:"range,omitempty"`
	IRI           string          `json:"iri,omitempty" yaml:"iri,omitempty"`
	IsAlias       bool            `json:"is_alias,omitempty" yaml:"is_alias,omitempty"`
	AliasType     AliasType       `json:"alias_type,omitempty" yaml:"alias_type,omitempty"`
	AliasPriority int             `json:"alias_priority,omitempty" yaml:"alias_priority,omitempty"`
	InverseOf     string          `json:"inverse_of,omitempty" yaml:"inverse_of,omitempty"`
	Symmetric     bool            `json:"symmetric,omitempty" yaml:"symmetric,omitempty"`
	RuleOpaque    bool            `json:"rule_opaque,omitempty" yaml:"rule_opaque,omitempty"`
	Weight        float64         `json:"weight,omitempty" yaml:"weight,omitempty"`
	Projection    *ProjectionSpec `json:"projection,omitempty" yaml:"projection,omitempty"`
}

PredicateSpec declares a canonical 3-part dotted predicate and its metadata in a declarative vocabulary pack.

type PredicateValidationError

type PredicateValidationError struct {
	Predicate string
	Reason    PredicateValidationReason
	Segment   int
}

PredicateValidationError reports why a predicate does not satisfy the canonical lower-kebab domain.category.property contract.

func (*PredicateValidationError) Error

func (e *PredicateValidationError) Error() string

Error implements error.

type PredicateValidationReason

type PredicateValidationReason string

PredicateValidationReason is a stable machine-readable predicate rejection reason.

const (
	// PredicateReasonEmpty means the identity is empty.
	PredicateReasonEmpty PredicateValidationReason = "empty"
	// PredicateReasonLength means the complete identity exceeds its byte bound.
	PredicateReasonLength PredicateValidationReason = "length"
	// PredicateReasonArity means the identity does not have exactly three segments.
	PredicateReasonArity PredicateValidationReason = "arity"
	// PredicateReasonSegmentEmpty means one semantic segment is empty.
	PredicateReasonSegmentEmpty PredicateValidationReason = "segment_empty"
	// PredicateReasonSegmentLength means one segment exceeds its byte bound.
	PredicateReasonSegmentLength PredicateValidationReason = "segment_length"
	// PredicateReasonSegmentStart means a segment does not start with lowercase ASCII.
	PredicateReasonSegmentStart PredicateValidationReason = "segment_start"
	// PredicateReasonSegmentCharacter means a segment contains a forbidden character.
	PredicateReasonSegmentCharacter PredicateValidationReason = "segment_character"
	// PredicateReasonSegmentHyphen means a segment has invalid hyphen placement.
	PredicateReasonSegmentHyphen PredicateValidationReason = "segment_hyphen"
)

type PrefixSpec

type PrefixSpec struct {
	Prefix    string `json:"prefix" yaml:"prefix"`
	Namespace string `json:"namespace" yaml:"namespace"`
}

PrefixSpec declares a namespace prefix mapping in a declarative vocabulary pack.

func (PrefixSpec) Validate

func (p PrefixSpec) Validate() error

Validate checks that Prefix is a non-empty W3C Turtle PN_PREFIX label (starting with a PN_CHARS_BASE letter, containing only PN_CHARS or '.', and not ending in '.' or containing ':' or whitespace) and Namespace is a non-empty IRI without whitespace.

type ProjectionSpec

type ProjectionSpec struct {
	Steps []ProjectionStep `json:"steps" yaml:"steps"`
}

ProjectionSpec declares an ordered sequence of reification steps that external projection adapters (such as semsparql) use to expand a flat SemEngine triple into a multi-hop ontology pattern without storing blank nodes in ENTITY_STATES.

type ProjectionStep

type ProjectionStep struct {
	// PredicateIRI is the object-property IRI traversed from the current subject
	// (the entity on step 0, or the previous intermediate node on step > 0).
	PredicateIRI string `json:"predicate_iri" yaml:"predicate_iri"`

	// NodeClassIRI is the optional RDF/OWL class IRI of the intermediate node
	// materialized by this step (for example, cco:ActOfMeasuring). Required on
	// every non-terminal step in a multi-step chain.
	NodeClassIRI string `json:"node_class_iri,omitempty" yaml:"node_class_iri,omitempty"`

	// ValuePredicateIRI is the optional datatype- or object-property IRI that
	// attaches the triple's terminal value to the node reached at the final step
	// (for example, cco:has_decimal_value).
	ValuePredicateIRI string `json:"value_predicate_iri,omitempty" yaml:"value_predicate_iri,omitempty"`
}

ProjectionStep describes one hop in a reified ontology projection chain (such as a BFO/CCO measurement or act chain) from an entity's flat triple to an expanded RDF/SPARQL graph pattern.

Directories

Path Synopsis
Package export serializes []message.Triple to standard RDF formats.
Package export serializes []message.Triple to standard RDF formats.

Jump to

Keyboard shortcuts

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