sdk

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: 24 Imported by: 0

Documentation

Overview

Package sdk provides the CogOS SDK for cognitive workspace integration.

The SDK provides holographic projection of workspace state through URI resolution. URIs are the source of truth. The kernel projects. Widgets consume projections.

Quick Start

kernel, err := sdk.Connect(".")
if err != nil {
    log.Fatal(err)
}
defer kernel.Close()

// Resolve a URI
resource, _ := kernel.Resolve("cog:mem/semantic/insights")

// Project into typed struct
var coherence types.CoherenceState
kernel.Project("cog:coherence", &coherence)

URI Scheme

All workspace access is through cog: URIs:

cog:mem/*         - Cogdocs (knowledge, sessions, etc.)
cog:signals/*     - Signal field (stigmergic coordination)
cog:context       - Four-tier context for inference
cog:thread/*      - Conversation threads
cog:coherence     - Workspace coherence state
cog:identity      - Workspace identity
cog:src           - SRC constants (immutable)
cog:adr/*         - Architecture Decision Records
cog:ledger/*      - Event ledger

Query parameters act as projections (filters, shapes):

cog:mem/semantic?q=topic&limit=10
cog:signals/inference?above=0.3
cog:context?budget=50000

SRC Constants

The SDK embeds the Self-Reference Coherence constants:

src := sdk.Constants()
fmt.Printf("τ₂ = %f\n", src.Tau2)  // 1.386... (2*ln(2))
fmt.Printf("g_eff = %f\n", src.GEff)  // 0.333... (1/3)

These constants are derived from mathematics, not configuration. They are available without a workspace connection.

Package sdk provides the CogOS SDK for workspace integration.

The SDK provides holographic projection of workspace state through URI resolution. URIs are the source of truth. The kernel projects. Widgets consume projections.

Package sdk provides cogdoc indexing for Cognitive Query Language (CQL).

The index provides fast lookups by URI, type, tag, status, and reference graph. This is ported from the kernel's BuildCogdocIndex functionality.

Package sdk provides cogdoc validation functionality.

This implements two-tier validation matching the kernel: - Structural refs (frontmatter refs field) -> errors if broken - Inline refs (markdown body) -> warnings if broken

Index

Constants

View Source
const TokensPerChar = 4

TokensPerChar is the approximate characters per token. Claude uses ~4 characters per token on average for English text.

View Source
const Version = "0.1.0"

Version is the SDK version.

Variables

View Source
var (
	// ErrNotFound indicates the requested resource does not exist.
	ErrNotFound = errors.New("resource not found")

	// ErrInvalidURI indicates the URI could not be parsed or is malformed.
	ErrInvalidURI = errors.New("invalid URI")

	// ErrUnknownNamespace indicates the URI namespace has no registered projector.
	ErrUnknownNamespace = errors.New("unknown namespace")

	// ErrIncoherent indicates the workspace state has drifted from canonical.
	ErrIncoherent = errors.New("workspace incoherent")

	// ErrNotConnected indicates an operation was attempted without a kernel connection.
	ErrNotConnected = errors.New("not connected to workspace")

	// ErrReadOnly indicates a mutation was attempted on a read-only projector.
	ErrReadOnly = errors.New("projector is read-only")

	// ErrValidation indicates a cogdoc or mutation failed validation.
	ErrValidation = errors.New("validation failed")

	// ErrWorkspaceNotFound indicates no .cog directory was found.
	ErrWorkspaceNotFound = errors.New("workspace not found")

	// ErrVersionMismatch indicates SDK version is incompatible with workspace.
	ErrVersionMismatch = errors.New("version mismatch")
)

Sentinel errors for common failure modes. Use errors.Is() to check for these.

View Source
var Namespaces = map[string]bool{

	"mem":      true,
	"adr":      true,
	"docs":     true,
	"ontology": true,

	"conf":      true,
	"config":    true,
	"kernel":    true,
	"canonical": true,

	"identity":  true,
	"src":       true,
	"coherence": true,

	"hooks": true,

	"ledger":  true,
	"crystal": true,

	"spec":   true,
	"specs":  true,
	"status": true,
	"work":   true,

	"agent":  true,
	"agents": true,
	"role":   true,
	"roles":  true,
	"skill":  true,
	"skills": true,

	"handoff":   true,
	"handoffs":  true,
	"artifact":  true,
	"artifacts": true,

	"context":   true,
	"signals":   true,
	"thread":    true,
	"inference": true,
}

Namespaces is the SDK-layer copy of the canonical namespace whitelist. SINGLE SOURCE OF TRUTH: pkg/uri/namespace.go — keep in sync with that file. The sdk module cannot import pkg/uri directly (separate Go modules); this copy must be identical to pkg/uri.Namespaces.

View Source
var ValidRefRelations = map[string]bool{
	"refs":       true,
	"implements": true,
	"extends":    true,
	"supersedes": true,
	"describes":  true,
	"requires":   true,
	"suggests":   true,
}

ValidRefRelations defines the allowed relationship types for typed refs.

Functions

func AllValidTypes

func AllValidTypes() []string

AllValidTypes returns all valid cogdoc type strings.

func AllocateBudget

func AllocateBudget(totalBudget int, priorities map[string]int) map[string]int

AllocateBudget distributes a token budget across items. Items with higher priority get larger allocations.

The allocation uses a proportional scheme:

  • Higher priority items get (1/priority) weight
  • Weights are normalized to sum to totalBudget

func AllocateBudgetByPercentage

func AllocateBudgetByPercentage(totalBudget int, percentages map[string]int) map[string]int

AllocateBudgetByPercentage distributes budget using percentages. Percentages should sum to 100 for expected behavior.

func CompactContent

func CompactContent(content string) string

CompactContent attempts to reduce content size while preserving meaning. Uses simple heuristics - not a true summarizer.

Strategies:

  • Remove excessive whitespace
  • Collapse repeated blank lines
  • Trim leading/trailing whitespace from lines

func EstimateTokens

func EstimateTokens(text string) int

EstimateTokens estimates the token count for text. Uses the 4 chars per token heuristic.

This is a rough estimate - actual tokenization varies by:

  • Model (different tokenizers)
  • Language (CJK uses more tokens)
  • Content type (code vs prose)

For budget allocation, this is sufficiently accurate.

func FindWorkspaceRoot

func FindWorkspaceRoot(startPath string) (string, error)

FindWorkspaceRoot searches upward from the given path for a .cog directory. Returns the workspace root, or error if not found.

func IsKebabCase

func IsKebabCase(s string) bool

IsKebabCase validates that a string is kebab-case.

func IsValidDate

func IsValidDate(s string) bool

IsValidDate validates YYYY-MM-DD format.

func MessageWeight

func MessageWeight(depth int) float64

MessageWeight computes recency weight for thread messages using ln(2) decay. At depth 0: weight = 1.0 At depth 1: weight = 0.5 At depth 2: weight = 0.25 ... halving each step

This is not arbitrary exponential decay - it's the natural half-life determined by the cost of distinction.

func SortTiersByPriority

func SortTiersByPriority(tiers []*types.ContextTier)

SortTiersByPriority sorts tiers by their priority (ascending).

func TruncateToTokens

func TruncateToTokens(content string, maxTokens int) (string, bool)

TruncateToTokens truncates content to fit a token budget. Returns the truncated content and whether truncation occurred.

The truncation is approximate - it may be slightly under budget. Attempts to truncate at word boundaries for readability.

func ValidateCogdocSimple

func ValidateCogdocSimple(path string) error

ValidateCogdocSimple performs simple validation (errors only, no warnings). Returns an error if validation fails, nil otherwise.

func ValidateType

func ValidateType(t string) bool

ValidateType checks if a type string is a valid cogdoc type.

Types

type BaseProjector

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

BaseProjector provides a default implementation for read-only projectors.

func NewBaseProjector

func NewBaseProjector(namespace string) BaseProjector

NewBaseProjector creates a new BaseProjector with the given namespace.

func (BaseProjector) CanMutate

func (b BaseProjector) CanMutate() bool

CanMutate returns false for base projectors.

func (BaseProjector) Mutate

func (b BaseProjector) Mutate(ctx context.Context, uri *ParsedURI, mutation *Mutation) error

Mutate returns ErrReadOnly for base projectors.

func (BaseProjector) Namespace

func (b BaseProjector) Namespace() string

Namespace returns the namespace.

type CogdocFrontmatter

type CogdocFrontmatter struct {
	Type    string      `yaml:"type"`
	ID      string      `yaml:"id"`
	Title   string      `yaml:"title"`
	Created string      `yaml:"created"`
	Status  string      `yaml:"status,omitempty"`
	Tags    []string    `yaml:"tags,omitempty"`
	Refs    interface{} `yaml:"refs,omitempty"`
}

CogdocFrontmatter represents the parsed frontmatter of a cogdoc.

func ParseFrontmatter

func ParseFrontmatter(content string) (*CogdocFrontmatter, string, error)

ParseFrontmatter extracts and parses the frontmatter from cogdoc content.

type CogdocIndex

type CogdocIndex struct {
	// ByURI maps URI to cogdoc
	ByURI map[string]*IndexedCogdoc

	// ByType maps type to cogdocs of that type
	ByType map[types.CogdocType][]*IndexedCogdoc

	// ByTag maps tag to cogdocs with that tag
	ByTag map[string][]*IndexedCogdoc

	// ByStatus maps status to cogdocs with that status
	ByStatus map[string][]*IndexedCogdoc

	// RefGraph maps URI to its forward refs
	RefGraph map[string][]TypedRef

	// InverseRefs maps URI to URIs that reference it (backward refs)
	InverseRefs map[string][]string
}

CogdocIndex is an in-memory index of all cogdocs. This mirrors the kernel's CogdocIndex structure.

func (*CogdocIndex) Count

func (idx *CogdocIndex) Count() int

Count returns the total number of indexed cogdocs.

func (*CogdocIndex) GetBackrefs

func (idx *CogdocIndex) GetBackrefs(uri string) []string

GetBackrefs returns URIs that reference the given URI.

func (*CogdocIndex) GetByStatus

func (idx *CogdocIndex) GetByStatus(status string) []*IndexedCogdoc

GetByStatus returns all cogdocs with a given status.

func (*CogdocIndex) GetByTag

func (idx *CogdocIndex) GetByTag(tag string) []*IndexedCogdoc

GetByTag returns all cogdocs with a given tag.

func (*CogdocIndex) GetByType

func (idx *CogdocIndex) GetByType(t types.CogdocType) []*IndexedCogdoc

GetByType returns all cogdocs of a given type.

func (*CogdocIndex) GetByURI

func (idx *CogdocIndex) GetByURI(uri string) *IndexedCogdoc

GetByURI returns a cogdoc by its URI.

func (*CogdocIndex) GetRefs

func (idx *CogdocIndex) GetRefs(uri string) []TypedRef

GetRefs returns the forward refs for a URI.

func (*CogdocIndex) Query

func (idx *CogdocIndex) Query(q *IndexQuery) []*IndexedCogdoc

Query executes a query against the index.

func (*CogdocIndex) Statuses

func (idx *CogdocIndex) Statuses() []string

Statuses returns all statuses present in the index.

func (*CogdocIndex) Tags

func (idx *CogdocIndex) Tags() []string

Tags returns all tags present in the index.

func (*CogdocIndex) Types

func (idx *CogdocIndex) Types() []types.CogdocType

Types returns all types present in the index.

func (*CogdocIndex) URIs

func (idx *CogdocIndex) URIs() []string

URIs returns all indexed URIs sorted.

type ContentStats

type ContentStats struct {
	// Chars is the character count (runes).
	Chars int `json:"chars"`

	// Words is the approximate word count.
	Words int `json:"words"`

	// Lines is the line count.
	Lines int `json:"lines"`

	// Tokens is the estimated token count.
	Tokens int `json:"tokens"`
}

ContentStats returns statistics about content.

func AnalyzeContent

func AnalyzeContent(content string) *ContentStats

AnalyzeContent returns statistics about the content.

type ContentType

type ContentType string

ContentType indicates the type of content in a Resource.

const (
	// ContentTypeRaw is unprocessed bytes (default).
	ContentTypeRaw ContentType = "raw"

	// ContentTypeJSON is JSON-encoded structured data.
	ContentTypeJSON ContentType = "json"

	// ContentTypeYAML is YAML-encoded structured data.
	ContentTypeYAML ContentType = "yaml"

	// ContentTypeMarkdown is Markdown text (possibly with YAML frontmatter).
	ContentTypeMarkdown ContentType = "markdown"

	// ContentTypeCogdoc is a validated cogdoc (Markdown + YAML frontmatter).
	ContentTypeCogdoc ContentType = "cogdoc"
)

type ContextBuilder

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

ContextBuilder provides a fluent interface for building context.

func NewContextBuilder

func NewContextBuilder(kernel *Kernel) *ContextBuilder

NewContextBuilder creates a new context builder.

func (*ContextBuilder) Build

Build assembles the context.

func (*ContextBuilder) Exclude

func (b *ContextBuilder) Exclude(patterns ...string) *ContextBuilder

Exclude adds URI patterns to exclude.

func (*ContextBuilder) Include

func (b *ContextBuilder) Include(uris ...string) *ContextBuilder

Include adds URIs to include.

func (*ContextBuilder) WithBudget

func (b *ContextBuilder) WithBudget(budget int) *ContextBuilder

WithBudget sets the token budget.

func (*ContextBuilder) WithSession

func (b *ContextBuilder) WithSession(sessionID string) *ContextBuilder

WithSession sets the session ID for temporal context.

func (*ContextBuilder) WithTier

WithTier filters to a specific tier.

type IndexQuery

type IndexQuery struct {
	// URIPrefix filters to URIs starting with this prefix
	URIPrefix string

	// Type filters to cogdocs of this type
	Type types.CogdocType

	// Status filters to cogdocs with this status
	Status string

	// Tags filters to cogdocs containing ALL these tags
	Tags []string

	// Limit caps the number of results (0 = unlimited)
	Limit int
}

Query performs a filtered query on the index.

type IndexedCogdoc

type IndexedCogdoc struct {
	URI        string           `json:"uri"`         // cog:mem/episodic/decisions/foo
	Path       string           `json:"path"`        // .cog/mem/episodic/decisions/foo.cog.md
	Type       types.CogdocType `json:"type"`        // decision, session, guide, etc.
	ID         string           `json:"id"`          // kebab-case identifier
	Title      string           `json:"title"`       // Human-readable title
	Created    string           `json:"created"`     // YYYY-MM-DD
	Status     string           `json:"status"`      // proposed, active, deprecated, etc.
	Tags       []string         `json:"tags"`        // Tags for categorization
	Refs       []TypedRef       `json:"refs"`        // Structural references from frontmatter
	InlineRefs []string         `json:"inline_refs"` // Navigational references from content
}

IndexedCogdoc represents a cogdoc with full metadata for indexing.

type InferenceOption

type InferenceOption func(*types.InferenceRequest)

InferenceOption configures an inference request.

func WithContext

func WithContext(uris ...string) InferenceOption

WithContext sets context URIs for inference.

func WithMaxTokens

func WithMaxTokens(maxTokens int) InferenceOption

WithMaxTokens sets the maximum tokens.

func WithModel

func WithModel(model string) InferenceOption

WithModel sets the model for inference.

func WithOrigin

func WithOrigin(origin string) InferenceOption

WithOrigin sets the request origin.

func WithSchema

func WithSchema(schema json.RawMessage) InferenceOption

WithSchema sets the JSON schema for structured output.

func WithSystemPrompt

func WithSystemPrompt(prompt string) InferenceOption

WithSystemPrompt sets the system prompt.

type Kernel

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

Kernel is the holographic projector - the single entry point for all workspace operations.

The kernel resolves cog:// URIs into Resources. It maintains:

  • A registry of projectors (one per namespace)
  • The workspace root path
  • Event sequence for ordering

Create a Kernel using Connect(). Close it when done with Close().

func Connect

func Connect(workspaceRoot string) (*Kernel, error)

Connect establishes a connection to the workspace kernel.

The workspaceRoot should be the directory containing .cog/. Use "." for the current directory.

Connect will:

  1. Find and validate the workspace root
  2. Verify the workspace structure (.cog/id.cog exists)
  3. Create and configure the Kernel
  4. Register default projectors

Returns ErrWorkspaceNotFound if no .cog directory exists.

Example:

kernel, err := sdk.Connect(".")
if err != nil {
    log.Fatal(err)
}
defer kernel.Close()

func MustConnect

func MustConnect(workspaceRoot string) *Kernel

MustConnect is like Connect but panics on error.

func (*Kernel) BuildIndex

func (k *Kernel) BuildIndex() (*CogdocIndex, error)

BuildIndex scans .cog/mem/ and builds an in-memory index of all cogdocs. This is the SDK equivalent of the kernel's BuildCogdocIndex.

func (*Kernel) Close

func (k *Kernel) Close() error

Close releases kernel resources.

func (*Kernel) CogDir

func (k *Kernel) CogDir() string

CogDir returns the .cog directory path.

func (*Kernel) FileExists

func (k *Kernel) FileExists(relativePath string) bool

FileExists checks if a file exists relative to workspace root.

func (*Kernel) GetProjector

func (k *Kernel) GetProjector(namespace string) Projector

GetProjector returns the projector for the given namespace.

func (*Kernel) Infer

func (k *Kernel) Infer(ctx context.Context, prompt string, opts ...InferenceOption) (*types.InferenceResponse, error)

Infer is a convenience function to run inference with the SDK. This provides a simpler interface than using Mutate directly.

func (*Kernel) IsClosed

func (k *Kernel) IsClosed() bool

IsClosed returns true if the kernel has been closed.

func (*Kernel) MemoryDir

func (k *Kernel) MemoryDir() string

MemoryDir returns the .cog/mem directory path.

func (*Kernel) Mutate

func (k *Kernel) Mutate(uri string, mutation *Mutation) error

Mutate writes or updates the resource at the given URI.

Example:

mutation := sdk.NewSetMutation([]byte("# New Content\n..."))
err := kernel.Mutate("cog:mem/semantic/insights/new-insight", mutation)

func (*Kernel) MutateContext

func (k *Kernel) MutateContext(ctx context.Context, uri string, mutation *Mutation) error

MutateContext is like Mutate but accepts a context.

func (*Kernel) NextEventSeq

func (k *Kernel) NextEventSeq() int64

NextEventSeq returns the next event sequence number.

func (*Kernel) Project

func (k *Kernel) Project(uri string, into any) error

Project resolves a URI and unmarshals the result into the given value.

This is a convenience method that combines Resolve with type-safe unmarshaling.

Example:

var coherence types.CoherenceState
err := kernel.Project("cog:coherence", &coherence)

func (*Kernel) ProjectContext

func (k *Kernel) ProjectContext(ctx context.Context, uri string, into any) error

ProjectContext is like Project but accepts a context.

func (*Kernel) ReadFile

func (k *Kernel) ReadFile(relativePath string) ([]byte, error)

ReadFile is a convenience method to read a file relative to workspace root.

func (*Kernel) RegisterProjector

func (k *Kernel) RegisterProjector(p Projector)

RegisterProjector adds a projector to the kernel.

func (*Kernel) Resolve

func (k *Kernel) Resolve(uri string) (*Resource, error)

Resolve reads and projects the resource at the given URI.

This is THE core operation of the SDK. Everything goes through Resolve.

Examples:

// Read a single cogdoc
resource, err := kernel.Resolve("cog:mem/semantic/insights/eigenform")

// Search memory with query
resource, err := kernel.Resolve("cog:mem/semantic?q=topic&limit=10")

// Get active signals
resource, err := kernel.Resolve("cog:signals/inference?above=0.3")

// Get coherence state
resource, err := kernel.Resolve("cog:coherence")

func (*Kernel) ResolveContext

func (k *Kernel) ResolveContext(ctx context.Context, uri string) (*Resource, error)

ResolveContext is like Resolve but accepts a context for cancellation.

func (*Kernel) Root

func (k *Kernel) Root() string

Root returns the workspace root directory.

func (*Kernel) StateDir

func (k *Kernel) StateDir() string

StateDir returns the .cog/.state directory path.

func (*Kernel) Watch

func (k *Kernel) Watch(ctx context.Context, uri string) (<-chan *Resource, error)

Watch returns a channel that emits resources when the URI's data changes. The channel is closed when the context is cancelled.

Not implemented in Phase 1 - returns error.

func (*Kernel) WatchURI

func (k *Kernel) WatchURI(ctx context.Context, uriPattern string) (*Watcher, error)

WatchURI subscribes to changes on a URI pattern.

Supports wildcards in the path:

  • cog:mem/semantic/* watches all files in semantic/
  • cog:mem/semantic/** watches all files recursively
  • cog:signals/* watches all signal namespaces

The returned Watcher's Events channel will emit WatchEvents when resources matching the pattern change.

Call Watcher.Close() when done to release resources.

Example:

watcher, err := kernel.WatchURI(ctx, "cog:mem/semantic/*")
if err != nil {
    return err
}
defer watcher.Close()

for event := range watcher.Events {
    fmt.Printf("Changed: %s (%s)\n", event.URI, event.Type)
}

func (*Kernel) WriteFile

func (k *Kernel) WriteFile(relativePath string, data []byte, perm os.FileMode) error

WriteFile is a convenience method to write a file relative to workspace root. Uses atomic write pattern (temp file + rename).

type Mutation

type Mutation struct {
	// Op is the type of mutation.
	Op MutationOp `json:"op"`

	// Content is the new content (for Set, Patch, Append).
	Content []byte `json:"content,omitempty"`

	// Metadata contains additional mutation parameters.
	// For example, {"validate": true} to enforce cogdoc validation.
	Metadata map[string]any `json:"metadata,omitempty"`
}

Mutation describes a change to be made to a resource.

Mutations are the write-side counterpart to Resources. They are validated by the projector before being applied.

func NewAppendMutation

func NewAppendMutation(item []byte) *Mutation

NewAppendMutation creates a mutation that adds to a collection.

func NewDeleteMutation

func NewDeleteMutation() *Mutation

NewDeleteMutation creates a mutation that removes a resource.

func NewPatchMutation

func NewPatchMutation(patch []byte) *Mutation

NewPatchMutation creates a mutation that merges with existing content.

func NewSetJSONMutation

func NewSetJSONMutation(data any) (*Mutation, error)

NewSetJSONMutation creates a mutation that replaces content with JSON.

func NewSetMutation

func NewSetMutation(content []byte) *Mutation

NewSetMutation creates a mutation that replaces content.

func (*Mutation) IsAppend

func (m *Mutation) IsAppend() bool

IsAppend returns true if this is an Append mutation.

func (*Mutation) IsDelete

func (m *Mutation) IsDelete() bool

IsDelete returns true if this is a Delete mutation.

func (*Mutation) IsPatch

func (m *Mutation) IsPatch() bool

IsPatch returns true if this is a Patch mutation.

func (*Mutation) IsSet

func (m *Mutation) IsSet() bool

IsSet returns true if this is a Set mutation.

func (*Mutation) WithMetadata

func (m *Mutation) WithMetadata(key string, value any) *Mutation

WithMetadata adds metadata to the mutation.

type MutationOp

type MutationOp string

MutationOp defines the type of mutation to perform.

const (
	// MutationSet replaces the entire content.
	MutationSet MutationOp = "set"

	// MutationPatch merges with existing content (for JSON/YAML).
	MutationPatch MutationOp = "patch"

	// MutationAppend adds to a collection.
	MutationAppend MutationOp = "append"

	// MutationDelete removes the resource.
	MutationDelete MutationOp = "delete"
)

type ParsedURI

type ParsedURI struct {
	// Namespace is the first path component (memory, signals, context, etc.)
	Namespace string

	// Path is everything after the namespace (may be empty).
	Path string

	// Query contains parsed query parameters.
	Query url.Values

	// Fragment is the portion after # (may be empty).
	Fragment string

	// Raw is the original unparsed URI string.
	Raw string
}

ParsedURI represents a parsed cog: URI with its components.

URI format: cog:namespace/path[?query][#fragment]

Examples:

cog:mem/semantic/insights/eigenform
cog:signals/inference?above=0.3
cog:context?budget=50000&model=sonnet
cog:thread/current#last-10
cog:coherence
cog:src

func ParseURI

func ParseURI(rawURI string) (*ParsedURI, error)

ParseURI parses a cog: URI into its components. Both the bare form (cog:namespace/path) and the legacy authority form (cog://namespace/path) are accepted per ADR-067.

Returns ErrInvalidURI if the URI is malformed or uses an unknown scheme. Returns ErrUnknownNamespace if the namespace is not recognized.

Example:

parsed, err := sdk.ParseURI("cog:mem/semantic/insights?q=topic&limit=10")
// parsed.Namespace = "mem"
// parsed.Path = "semantic/insights"
// parsed.Query = {"q": ["topic"], "limit": ["10"]}

func (*ParsedURI) GetQuery

func (p *ParsedURI) GetQuery(key string) string

GetQuery returns a query parameter value, or empty string if not present.

func (*ParsedURI) GetQueryBool

func (p *ParsedURI) GetQueryBool(key string) bool

GetQueryBool returns a query parameter as bool. Returns true for "true", "1", "yes"; false otherwise.

func (*ParsedURI) GetQueryFloat

func (p *ParsedURI) GetQueryFloat(key string, defaultVal float64) float64

GetQueryFloat returns a query parameter as float64, or default if not present/invalid.

func (*ParsedURI) GetQueryInt

func (p *ParsedURI) GetQueryInt(key string, defaultVal int) int

GetQueryInt returns a query parameter as int, or default if not present/invalid.

func (*ParsedURI) HasPath

func (p *ParsedURI) HasPath() bool

HasPath returns true if the URI has a non-empty path.

func (*ParsedURI) IsNamespace

func (p *ParsedURI) IsNamespace() bool

IsNamespace returns true if this URI refers to just a namespace (no path).

func (*ParsedURI) PathSegments

func (p *ParsedURI) PathSegments() []string

PathSegments returns the path split by "/".

func (*ParsedURI) String

func (p *ParsedURI) String() string

String returns the canonical string representation of the URI. Always emits the bare cog: form (no //) per ADR-067.

func (*ParsedURI) WithQuery

func (p *ParsedURI) WithQuery(key, value string) *ParsedURI

WithQuery returns a new ParsedURI with additional query parameters.

type Projector

type Projector interface {
	// Namespace returns the namespace this projector handles.
	Namespace() string

	// Resolve reads and projects the resource at the given URI.
	Resolve(ctx context.Context, uri *ParsedURI) (*Resource, error)

	// CanMutate returns true if this projector supports mutations.
	CanMutate() bool

	// Mutate writes or updates the resource at the given URI.
	Mutate(ctx context.Context, uri *ParsedURI, mutation *Mutation) error
}

Projector is the interface that all namespace handlers must implement.

type Resource

type Resource struct {
	// URI is the original URI that was resolved.
	URI string `json:"uri"`

	// Content is the raw content bytes.
	Content []byte `json:"content,omitempty"`

	// ContentType indicates how to interpret Content.
	ContentType ContentType `json:"content_type"`

	// Metadata contains type-specific structured data.
	// For cogdocs, this includes frontmatter fields.
	// For signals, this includes decay parameters.
	Metadata map[string]any `json:"metadata,omitempty"`

	// Hash is the content-addressable hash (SHA-256) of Content.
	// Empty if not computed.
	Hash string `json:"hash,omitempty"`

	// ModTime is when the underlying data was last modified.
	ModTime time.Time `json:"mod_time,omitempty"`

	// Relevance is the computed relevance score [0, 1].
	// For signals, this is based on decay formula.
	// For memory, this may be based on search ranking.
	Relevance float64 `json:"relevance,omitempty"`

	// Children contains nested resources for collection responses.
	// Used when resolving a namespace or directory.
	Children []*Resource `json:"children,omitempty"`
}

Resource is the universal return type for Resolve operations. It wraps content with metadata about the resolution.

Resources are the "atoms" of the holographic projection - they are what the kernel renders from URIs.

func NewJSONResource

func NewJSONResource(uri string, data any) (*Resource, error)

NewJSONResource creates a Resource with JSON content.

func NewResource

func NewResource(uri string, content []byte) *Resource

NewResource creates a Resource with raw content.

func (*Resource) Count

func (r *Resource) Count() int

Count returns the number of items (1 for single resource, len for collection).

func (*Resource) GetMetadata

func (r *Resource) GetMetadata(key string) (any, bool)

GetMetadata retrieves a metadata value by key.

func (*Resource) GetMetadataString

func (r *Resource) GetMetadataString(key string) string

GetMetadataString retrieves a metadata value as string.

func (*Resource) IsCollection

func (r *Resource) IsCollection() bool

IsCollection returns true if this resource contains child resources.

func (*Resource) IsEmpty

func (r *Resource) IsEmpty() bool

IsEmpty returns true if the resource has no content.

func (*Resource) JSON

func (r *Resource) JSON(v any) error

JSON unmarshals the Content into the given value. Returns error if ContentType is not JSON or unmarshaling fails.

func (*Resource) SetMetadata

func (r *Resource) SetMetadata(key string, value any) *Resource

SetMetadata sets a metadata key-value pair.

func (*Resource) String

func (r *Resource) String() string

String returns the Content as a string.

func (*Resource) WithHash

func (r *Resource) WithHash(hash string) *Resource

WithHash sets the content hash and returns the resource.

func (*Resource) WithModTime

func (r *Resource) WithModTime(t time.Time) *Resource

WithModTime sets the modification time and returns the resource.

func (*Resource) WithRelevance

func (r *Resource) WithRelevance(rel float64) *Resource

WithRelevance sets the relevance score and returns the resource.

type SDKError

type SDKError struct {
	// Op is the operation that failed (e.g., "Resolve", "Mutate", "Connect").
	Op string

	// URI is the URI being operated on, if applicable.
	URI string

	// Path is the filesystem path, if applicable.
	Path string

	// Cause is the underlying error.
	Cause error

	// Recover is a human-readable suggestion for recovery.
	Recover string
}

SDKError provides structured error information for debugging. It wraps underlying errors with operation context and recovery hints.

func IncoherentError

func IncoherentError(driftedFiles []string) *SDKError

IncoherentError returns an SDKError wrapping ErrIncoherent.

func InvalidURIError

func InvalidURIError(uri, reason string) *SDKError

InvalidURIError returns an SDKError wrapping ErrInvalidURI with details.

func NewError

func NewError(op string, cause error) *SDKError

NewError creates a new SDKError with the given operation and cause.

func NewPathError

func NewPathError(op, path string, cause error) *SDKError

NewPathError creates a new SDKError for a filesystem operation.

func NewURIError

func NewURIError(op, uri string, cause error) *SDKError

NewURIError creates a new SDKError for a URI operation.

func NotFoundError

func NotFoundError(op, uri string) *SDKError

NotFoundError returns an SDKError wrapping ErrNotFound.

func (*SDKError) Error

func (e *SDKError) Error() string

Error implements the error interface.

func (*SDKError) Is

func (e *SDKError) Is(target error) bool

Is checks if target matches this error's cause.

func (*SDKError) Unwrap

func (e *SDKError) Unwrap() error

Unwrap returns the underlying error for errors.Is/As.

func (*SDKError) WithRecover

func (e *SDKError) WithRecover(hint string) *SDKError

WithRecover adds a recovery suggestion to an error.

type SRCConstants

type SRCConstants struct {
	// Ln2 is the cost of one distinction (Landauer/Shannon/Eigen).
	// This is the fundamental unit: ln(2) ≈ 0.693147.
	// Every bit flip, every observation, every distinction costs exactly ln(2) nats.
	Ln2 float64

	// Tau1 is the coherence threshold - the correlation half-life.
	// Equal to Ln2. Signals below this threshold are half-decayed.
	Tau1 float64

	// Tau2 is the stability boundary - escape velocity of self-reference.
	// Equal to 2*Ln2 ≈ 1.386. This is where patterns start degrading.
	// One ln(2) per aspect (Gravity dimension, Time dimension).
	Tau2 float64

	// GEff is the self-reference coupling constant: g_eff = 1/(pinch_depth + 1) = 1/3.
	// This determines how much of context budget goes to identity (stable core)
	// versus temporal (changing context). The 1/3 split is derived, not chosen.
	GEff float64

	// VarianceRatio is the thought/action efficiency: Var(X)/Var(X̂) = 6 (exact).
	// When γ = κ = 1: (2γ+κ)(γ+κ)/κ² = (3)(2)/1 = 6. General: (2r+1)(r+1) where r=γ/κ.
	// This is why minds exist: thinking is 6x cheaper than doing.
	VarianceRatio int

	// CorrelationThreshold is the geometric coherence limit: ρ_max = sqrt(2/3).
	// This is the maximum correlation achievable in the viable manifold.
	// Signals start at this value and decay from here.
	CorrelationThreshold float64
}

SRCConstants encodes the crystal's mathematical structure. These are not configuration - they are derived truths from Self-Reference Coherence theory.

The constants derive from the primordial distinction (0 ≠ 1) and the cost of oscillation. See: .cog/ontology/crystal.cog.md for full derivations.

func Constants

func Constants() SRCConstants

Constants returns the immutable SRC constants. This is a function, not a variable, to prevent mutation.

These constants are compiled into the SDK, not read from files. They are available without a workspace connection.

Example:

src := sdk.Constants()
decayRate := src.Tau2       // Use for signal decay timescales
chunkSize := src.VarianceRatio // Use for summarization threshold
idBudget := src.GEff       // 1/3 of context for identity

func (SRCConstants) CorrelationThresholdVal

func (s SRCConstants) CorrelationThresholdVal() float64

CorrelationThresholdVal returns sqrt(2/3) (≈ 0.816).

func (SRCConstants) GEffVal

func (s SRCConstants) GEffVal() float64

GEffVal returns the coupling constant (1/3).

func (SRCConstants) Ln2Val

func (s SRCConstants) Ln2Val() float64

Ln2 returns the cost of one distinction (≈ 0.693).

func (SRCConstants) Tau1Val

func (s SRCConstants) Tau1Val() float64

Tau1Val returns the coherence threshold (= Ln2).

func (SRCConstants) Tau2Val

func (s SRCConstants) Tau2Val() float64

Tau2Val returns the stability boundary (= 2*Ln2). This is the Coherence Horizon - escape velocity of self-reference.

func (SRCConstants) VarianceRatioVal

func (s SRCConstants) VarianceRatioVal() int

VarianceRatioVal returns the thought/action efficiency ratio (6).

type TypedRef

type TypedRef struct {
	URI string `yaml:"uri" json:"uri"`
	Rel string `yaml:"rel,omitempty" json:"rel,omitempty"` // implements, extends, supersedes, describes, requires, suggests
}

TypedRef represents a reference with relationship type. Mirrors the kernel's TypedRef structure.

type ValidationResult

type ValidationResult struct {
	Path           string     `json:"path"`
	Valid          bool       `json:"valid"`
	Errors         []string   `json:"errors,omitempty"`
	Warnings       []string   `json:"warnings,omitempty"`
	StructuralRefs []TypedRef `json:"structural_refs,omitempty"`
	InlineRefs     []string   `json:"inline_refs,omitempty"`
}

ValidationResult holds the result of cogdoc validation.

func ValidateCogdoc

func ValidateCogdoc(path string) *ValidationResult

ValidateCogdoc performs full two-tier validation on a cogdoc file. Returns a ValidationResult with errors (blocking) and warnings (advisory).

func ValidateFrontmatter

func ValidateFrontmatter(fmContent string) *ValidationResult

ValidateFrontmatter validates just the frontmatter portion of a cogdoc.

type WatchEvent

type WatchEvent struct {
	// URI is the cog:// URI of the changed resource.
	URI string `json:"uri"`

	// Type indicates what kind of change occurred.
	Type WatchEventType `json:"type"`

	// Timestamp is when the event was detected.
	Timestamp time.Time `json:"timestamp"`

	// Resource is the updated resource (nil for Deleted events).
	Resource *Resource `json:"resource,omitempty"`

	// FilePath is the underlying file path that changed.
	FilePath string `json:"file_path,omitempty"`
}

WatchEvent represents a change to a watched resource.

type WatchEventType

type WatchEventType string

WatchEventType indicates the type of change that occurred.

const (
	// WatchCreated indicates a resource was created.
	WatchCreated WatchEventType = "created"

	// WatchModified indicates a resource was modified.
	WatchModified WatchEventType = "modified"

	// WatchDeleted indicates a resource was deleted.
	WatchDeleted WatchEventType = "deleted"
)

type Watcher

type Watcher struct {
	// URI is the URI pattern being watched.
	URI string

	// Events is the channel that receives watch events.
	Events <-chan WatchEvent
	// contains filtered or unexported fields
}

Watcher observes URI changes and emits events.

func (*Watcher) Close

func (w *Watcher) Close() error

Close stops watching and releases resources.

Directories

Path Synopsis
Package clients provides ergonomic convenience wrappers over the SDK kernel.
Package clients provides ergonomic convenience wrappers over the SDK kernel.
Package constellation implements a knowledge graph over cogdocs.
Package constellation implements a knowledge graph over cogdocs.
Package httputil provides HTTP interfaces for the CogOS SDK.
Package httputil provides HTTP interfaces for the CogOS SDK.
internal
fs
Package fs provides filesystem primitives for the SDK.
Package fs provides filesystem primitives for the SDK.
git
Package git provides git primitives for the SDK.
Package git provides git primitives for the SDK.
Package project contains the projector interface and registry.
Package project contains the projector interface and registry.
Package types contains the projection target types for SDK resources.
Package types contains the projection target types for SDK resources.

Jump to

Keyboard shortcuts

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