cogfield

package module
v0.0.0-...-dddc2fe Latest Latest
Warning

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

Go to latest
Published: May 4, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package cogfield implements the schema system for CogOS structured data.

CogFields define typed, validatable schemas for CogBlock payloads and configuration surfaces. The system supports schema evolution, cross-reference resolution, and compile-time type generation from field definitions.

Package cogfield defines the CogField knowledge graph schema types.

CogField is the workspace knowledge graph, built from constellation.db and runtime sources (buses, sessions, signals, components). These types define the graph structure shared between the kernel (which builds the graph) and consumers (frontends, adapters, conditions).

The graph consists of:

  • Nodes: documents, sessions, buses, signals, components, resources
  • Edges: explicit references, shared tags, siblings, temporal links
  • Stats: aggregate counts and most-connected nodes

Type normalization maps 64+ document types to 11 CogField entity types. Sector inference determines memory sector from document paths.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ComputeRelevance

func ComputeRelevance(ps *PersistedSignal, now time.Time) float64

ComputeRelevance computes the current signal relevance using the SRC decay formula. relevance = strength * exp(-age/tau2) * sqrt(2/3)

func ExtractTimestamp

func ExtractTimestamp(evt SessionJSONLEvent) string

ExtractTimestamp pulls the timestamp from either JSONL format.

func InferSector

func InferSector(path, dbSector string) string

InferSector determines the memory sector from a document path and optional DB sector. Falls back to path-based inference when the DB sector is NULL (98% of docs).

func NormalizeEntityType

func NormalizeEntityType(docType string) string

NormalizeEntityType maps constellation.db document types to CogField entity types. The 64+ document types in the DB are normalized to 11 canonical entity types.

func ParseCSVSet

func ParseCSVSet(csv string) map[string]bool

ParseCSVSet splits a comma-separated string into a set for O(1) lookup. Returns nil if the input is empty (meaning "no filter").

func ParseConditionQueryString

func ParseConditionQueryString(query string) map[string]string

ParseConditionQueryString parses a simple query string (key=value&key=value).

func SignalIsActive

func SignalIsActive(ps *PersistedSignal, now time.Time) bool

SignalIsActive returns true if the signal relevance exceeds the activity threshold. Threshold is e^(-1) * sqrt(2/3) ~ 0.30.

func StrengthFromMetrics

func StrengthFromMetrics(substanceRatio float64, refCount, wordCount int) float64

StrengthFromMetrics calculates a 0-10 strength value from document substance metrics.

Types

type AdapterNodeConfig

type AdapterNodeConfig struct {
	BlockTypes    map[string]BlockTypeConfig `json:"block_types"`
	DefaultSector string                     `json:"default_sector"`
	ChainThread   string                     `json:"chain_thread"`
}

AdapterNodeConfig describes how an adapter's block types map to graph rendering.

type Block

type Block struct {
	V         int                    `json:"v"`
	ID        string                 `json:"id,omitempty"`
	BusID     string                 `json:"bus_id,omitempty"`
	Seq       int                    `json:"seq,omitempty"`
	Ts        string                 `json:"ts"`
	From      string                 `json:"from"`
	To        string                 `json:"to,omitempty"`
	Type      string                 `json:"type"`
	Payload   map[string]interface{} `json:"payload,omitempty"`
	Digest    string                 `json:"digest,omitempty"`     // ADR-084: "sha256:<hex>" content hash of by-reference payload
	MediaType string                 `json:"media_type,omitempty"` // ADR-084: OCI media type of the payload (e.g. application/vnd.cogos.trace.assessment.v1+json)
	Prev      []string               `json:"prev,omitempty"`
	PrevHash  string                 `json:"prev_hash,omitempty"` // V1 compat
	Hash      string                 `json:"hash"`
	Merkle    string                 `json:"merkle,omitempty"`
	Sig       string                 `json:"sig,omitempty"`
	Size      int                    `json:"size,omitempty"`
}

Block is the canonical content atom for the CogOS bus protocol (ADR-059). V1 blocks use PrevHash (string); V2 blocks use Prev ([]string) for DAG-style linking. Both fields are written during the transition period for backward compatibility.

ADR-084 v1 — by-reference payload. When Digest and MediaType are set, the envelope carries a content-addressed reference to the payload bytes stored in BlobStore; Payload may be empty, and the actual bytes are fetched via GET /v1/blobs/:digest. The inline Payload field is preserved for backward compatibility during the Phase 1 schema-additive migration — producers may emit either shape, and consumers MUST tolerate both. Size is shared by both forms and indicates the payload size in bytes.

type BlockAdapter

type BlockAdapter interface {
	ID() string
	NodeConfig() AdapterNodeConfig
	SummaryNodes(root string) ([]Node, []Edge)
	ExpandNode(root, nodeID string) ([]Node, []Edge, error)
}

BlockAdapter lets any data source produce graph nodes for CogField.

type BlockTypeConfig

type BlockTypeConfig struct {
	EntityType string `json:"entity_type"`
	Shape      string `json:"shape"`
	Color      string `json:"color,omitempty"`
	Label      string `json:"label"`
}

BlockTypeConfig describes the visual config for a block type.

type BusDetail

type BusDetail struct {
	BusID        string   `json:"bus_id"`
	State        string   `json:"state"`
	Participants []string `json:"participants"`
	Created      string   `json:"created"`
	Modified     string   `json:"modified"`
	EventCount   int      `json:"event_count"`
	Events       []Block  `json:"events"`
}

BusDetail is the response for GET /api/cogfield/buses/{id}.

type BusRegistryEntry

type BusRegistryEntry struct {
	BusID        string   `json:"bus_id"`
	State        string   `json:"state"`
	Participants []string `json:"participants"`
	Transport    string   `json:"transport"`
	Endpoint     string   `json:"endpoint"`
	CreatedAt    string   `json:"created_at"`
	LastEventSeq int      `json:"last_event_seq"`
	LastEventAt  string   `json:"last_event_at"`
	EventCount   int      `json:"event_count"`
}

BusRegistryEntry matches the JSON format in .cog/.state/buses/registry.json.

type DocRef

type DocRef struct {
	ID       string `json:"id"`
	Title    string `json:"title"`
	Relation string `json:"relation"`
	Type     string `json:"type"`
	Sector   string `json:"sector"`
}

DocRef represents a reference to/from another document.

type DocumentDetail

type DocumentDetail struct {
	ID        string   `json:"id"`
	Title     string   `json:"title"`
	Type      string   `json:"type"`
	Sector    string   `json:"sector"`
	Path      string   `json:"path"`
	Created   string   `json:"created"`
	Modified  string   `json:"modified"`
	Content   string   `json:"content"`
	Tags      []string `json:"tags"`
	Refs      []DocRef `json:"refs"`
	Backlinks []DocRef `json:"backlinks"`
}

DocumentDetail is the full response for a document content request.

type Edge

type Edge struct {
	Source   string  `json:"source"`
	Target   string  `json:"target"`
	Relation string  `json:"relation"`
	Weight   float64 `json:"weight,omitempty"`
	Thread   string  `json:"thread"`
}

Edge represents a directed relationship between two nodes.

type ExpandNodeResponse

type ExpandNodeResponse struct {
	ParentID string            `json:"parent_id"`
	Nodes    []Node            `json:"nodes"`
	Edges    []Edge            `json:"edges"`
	Config   AdapterNodeConfig `json:"config"`
}

ExpandNodeResponse is the response for GET /api/cogfield/expand/{nodeId}.

type FieldCondition

type FieldCondition struct {
	Name      string            `yaml:"name" json:"name"`
	Query     string            `yaml:"query" json:"query"`
	Condition string            `yaml:"condition" json:"condition"`
	Match     map[string]string `yaml:"match,omitempty" json:"match,omitempty"`
	Threshold int               `yaml:"threshold,omitempty" json:"threshold,omitempty"`
	Cooldown  int               `yaml:"cooldown" json:"cooldown"`
	Handler   string            `yaml:"handler" json:"handler"`
	Context   string            `yaml:"context,omitempty" json:"context,omitempty"`
}

FieldCondition defines a reactive condition on the field graph.

type FieldConditionState

type FieldConditionState struct {
	CyclesSinceFired map[string]int // condition name -> cycles since last fire
}

FieldConditionState tracks cooldown counters per condition.

type Graph

type Graph struct {
	Nodes []Node `json:"nodes"`
	Edges []Edge `json:"edges"`
	Stats Stats  `json:"stats"`
}

Graph is the top-level CogField knowledge graph container.

type GraphBlock

type GraphBlock struct {
	URI      string // cog://bus/{busID}/{seq}
	Type     string // bus.message, session.turn, etc.
	From     string
	Ts       string
	Hash     string
	PrevHash string
	Payload  map[string]interface{}
	Meta     map[string]interface{}
}

GraphBlock is the intermediate representation for CogField graph rendering. Adapters convert their native data into GraphBlocks for visualization.

type Node

type Node struct {
	ID           string                 `json:"id"`
	Label        string                 `json:"label"`
	EntityType   string                 `json:"entity_type"`
	Sector       string                 `json:"sector"`
	Tags         []string               `json:"tags"`
	Created      string                 `json:"created"`
	Modified     string                 `json:"modified"`
	BackrefCount int                    `json:"backref_count"`
	Strength     float64                `json:"strength"`
	Meta         map[string]interface{} `json:"meta,omitempty"`
}

Node represents a single entity in the CogField knowledge graph.

func BFSSubgraph

func BFSSubgraph(nodes []Node, edges []Edge, startID string, maxDepth int) []Node

BFSSubgraph performs a BFS from startID up to maxDepth hops, returning only nodes from the input set that are reachable. Edges are treated as undirected for traversal.

func FilterByMeta

func FilterByMeta(nodes []Node, match map[string]string) []Node

FilterByMeta filters nodes whose Meta fields match the given criteria.

func FilterNodes

func FilterNodes(nodes []Node, types, sectors, tags map[string]bool, minStrength float64) []Node

FilterNodes returns nodes matching all provided filters (AND logic). A nil/empty filter set means "accept all" for that dimension.

func GraphBlockToNode

func GraphBlockToNode(block GraphBlock) Node

GraphBlockToNode converts a GraphBlock into a Node for graph rendering.

type PersistedSignal

type PersistedSignal struct {
	SignalType  string         `json:"signal_type"`
	Strength    float64        `json:"strength"`
	DepositedBy string         `json:"deposited_by"`
	DepositedAt float64        `json:"deposited_at"`
	HalfLife    float64        `json:"half_life"`
	DecayType   string         `json:"decay_type"`
	Metadata    map[string]any `json:"metadata,omitempty"`
}

PersistedSignal mirrors the kernel's signal format from sdk/signals.go.

type SessionDetail

type SessionDetail struct {
	ID           string           `json:"id"`
	Created      string           `json:"created"`
	Modified     string           `json:"modified"`
	EventCount   int              `json:"event_count"`
	MessageCount int              `json:"message_count"`
	Messages     []SessionMessage `json:"messages"`
	Source       string           `json:"source,omitempty"`
}

SessionDetail is the response for GET /api/cogfield/sessions/{id}.

type SessionJSONLEvent

type SessionJSONLEvent struct {
	// Flat format fields
	ID        string `json:"id,omitempty"`
	Seq       int    `json:"seq,omitempty"`
	SessionID string `json:"session_id,omitempty"`
	Ts        string `json:"ts,omitempty"`
	Type      string `json:"type,omitempty"`

	// Hashed payload envelope format
	HashedPayload *struct {
		Type      string                 `json:"type"`
		Timestamp string                 `json:"timestamp"`
		SessionID string                 `json:"session_id"`
		Data      map[string]interface{} `json:"data"`
	} `json:"hashed_payload,omitempty"`
	Metadata *struct {
		Seq int `json:"seq"`
	} `json:"metadata,omitempty"`

	// Reconciler/bridge format
	Data map[string]interface{} `json:"data,omitempty"`
}

SessionJSONLEvent is the union type for the two JSONL formats found in .cog/.state/events/.

type SessionMessage

type SessionMessage struct {
	Seq       int                    `json:"seq"`
	Type      string                 `json:"type"`
	Timestamp string                 `json:"timestamp"`
	Role      string                 `json:"role,omitempty"`
	Content   string                 `json:"content,omitempty"`
	Meta      map[string]interface{} `json:"meta,omitempty"`
}

SessionMessage represents a single event in a session conversation.

type SignalFieldState

type SignalFieldState struct {
	Signals map[string]map[string]*PersistedSignal `json:"signals"` // location -> type -> signal
	SavedAt float64                                `json:"saved_at"`
}

SignalFieldState mirrors the persisted format from sdk/signals.go.

type Stats

type Stats struct {
	TotalNodes      int            `json:"total_nodes"`
	TotalEdges      int            `json:"total_edges"`
	NodesByType     map[string]int `json:"nodes_by_type"`
	NodesBySector   map[string]int `json:"nodes_by_sector"`
	EdgesByRelation map[string]int `json:"edges_by_relation"`
	EdgesByThread   map[string]int `json:"edges_by_thread"`
	MostConnected   []string       `json:"most_connected"`
}

Stats holds aggregate statistics for a CogField graph.

func ComputeStats

func ComputeStats(nodes []Node, edges []Edge) Stats

ComputeStats builds Stats from the given nodes and edges.

type TriggeredCondition

type TriggeredCondition struct {
	Condition    FieldCondition
	MatchedNodes []Node
	MatchCount   int
}

TriggeredCondition represents a condition that matched during evaluation.

func EvaluateFieldConditions

func EvaluateFieldConditions(graph *Graph, conditions []FieldCondition, state *FieldConditionState) []TriggeredCondition

EvaluateFieldConditions checks all conditions against the current field graph.

Jump to

Keyboard shortcuts

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