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
- Variables
- func AllValidTypes() []string
- func AllocateBudget(totalBudget int, priorities map[string]int) map[string]int
- func AllocateBudgetByPercentage(totalBudget int, percentages map[string]int) map[string]int
- func CompactContent(content string) string
- func EstimateTokens(text string) int
- func FindWorkspaceRoot(startPath string) (string, error)
- func IsKebabCase(s string) bool
- func IsValidDate(s string) bool
- func MessageWeight(depth int) float64
- func SortTiersByPriority(tiers []*types.ContextTier)
- func TruncateToTokens(content string, maxTokens int) (string, bool)
- func ValidateCogdocSimple(path string) error
- func ValidateType(t string) bool
- type BaseProjector
- type CogdocFrontmatter
- type CogdocIndex
- func (idx *CogdocIndex) Count() int
- func (idx *CogdocIndex) GetBackrefs(uri string) []string
- func (idx *CogdocIndex) GetByStatus(status string) []*IndexedCogdoc
- func (idx *CogdocIndex) GetByTag(tag string) []*IndexedCogdoc
- func (idx *CogdocIndex) GetByType(t types.CogdocType) []*IndexedCogdoc
- func (idx *CogdocIndex) GetByURI(uri string) *IndexedCogdoc
- func (idx *CogdocIndex) GetRefs(uri string) []TypedRef
- func (idx *CogdocIndex) Query(q *IndexQuery) []*IndexedCogdoc
- func (idx *CogdocIndex) Statuses() []string
- func (idx *CogdocIndex) Tags() []string
- func (idx *CogdocIndex) Types() []types.CogdocType
- func (idx *CogdocIndex) URIs() []string
- type ContentStats
- type ContentType
- type ContextBuilder
- func (b *ContextBuilder) Build(ctx context.Context) (*types.ContextState, error)
- func (b *ContextBuilder) Exclude(patterns ...string) *ContextBuilder
- func (b *ContextBuilder) Include(uris ...string) *ContextBuilder
- func (b *ContextBuilder) WithBudget(budget int) *ContextBuilder
- func (b *ContextBuilder) WithSession(sessionID string) *ContextBuilder
- func (b *ContextBuilder) WithTier(tier types.ContextTierName) *ContextBuilder
- type IndexQuery
- type IndexedCogdoc
- type InferenceOption
- type Kernel
- func (k *Kernel) BuildIndex() (*CogdocIndex, error)
- func (k *Kernel) Close() error
- func (k *Kernel) CogDir() string
- func (k *Kernel) FileExists(relativePath string) bool
- func (k *Kernel) GetProjector(namespace string) Projector
- func (k *Kernel) Infer(ctx context.Context, prompt string, opts ...InferenceOption) (*types.InferenceResponse, error)
- func (k *Kernel) IsClosed() bool
- func (k *Kernel) MemoryDir() string
- func (k *Kernel) Mutate(uri string, mutation *Mutation) error
- func (k *Kernel) MutateContext(ctx context.Context, uri string, mutation *Mutation) error
- func (k *Kernel) NextEventSeq() int64
- func (k *Kernel) Project(uri string, into any) error
- func (k *Kernel) ProjectContext(ctx context.Context, uri string, into any) error
- func (k *Kernel) ReadFile(relativePath string) ([]byte, error)
- func (k *Kernel) RegisterProjector(p Projector)
- func (k *Kernel) Resolve(uri string) (*Resource, error)
- func (k *Kernel) ResolveContext(ctx context.Context, uri string) (*Resource, error)
- func (k *Kernel) Root() string
- func (k *Kernel) StateDir() string
- func (k *Kernel) Watch(ctx context.Context, uri string) (<-chan *Resource, error)
- func (k *Kernel) WatchURI(ctx context.Context, uriPattern string) (*Watcher, error)
- func (k *Kernel) WriteFile(relativePath string, data []byte, perm os.FileMode) error
- type Mutation
- type MutationOp
- type ParsedURI
- func (p *ParsedURI) GetQuery(key string) string
- func (p *ParsedURI) GetQueryBool(key string) bool
- func (p *ParsedURI) GetQueryFloat(key string, defaultVal float64) float64
- func (p *ParsedURI) GetQueryInt(key string, defaultVal int) int
- func (p *ParsedURI) HasPath() bool
- func (p *ParsedURI) IsNamespace() bool
- func (p *ParsedURI) PathSegments() []string
- func (p *ParsedURI) String() string
- func (p *ParsedURI) WithQuery(key, value string) *ParsedURI
- type Projector
- type Resource
- func (r *Resource) Count() int
- func (r *Resource) GetMetadata(key string) (any, bool)
- func (r *Resource) GetMetadataString(key string) string
- func (r *Resource) IsCollection() bool
- func (r *Resource) IsEmpty() bool
- func (r *Resource) JSON(v any) error
- func (r *Resource) SetMetadata(key string, value any) *Resource
- func (r *Resource) String() string
- func (r *Resource) WithHash(hash string) *Resource
- func (r *Resource) WithModTime(t time.Time) *Resource
- func (r *Resource) WithRelevance(rel float64) *Resource
- type SDKError
- func IncoherentError(driftedFiles []string) *SDKError
- func InvalidURIError(uri, reason string) *SDKError
- func NewError(op string, cause error) *SDKError
- func NewPathError(op, path string, cause error) *SDKError
- func NewURIError(op, uri string, cause error) *SDKError
- func NotFoundError(op, uri string) *SDKError
- type SRCConstants
- type TypedRef
- type ValidationResult
- type WatchEvent
- type WatchEventType
- type Watcher
Constants ¶
const TokensPerChar = 4
TokensPerChar is the approximate characters per token. Claude uses ~4 characters per token on average for English text.
const Version = "0.1.0"
Version is the SDK version.
Variables ¶
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.
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.
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 ¶
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 ¶
AllocateBudgetByPercentage distributes budget using percentages. Percentages should sum to 100 for expected behavior.
func CompactContent ¶
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 ¶
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 ¶
FindWorkspaceRoot searches upward from the given path for a .cog directory. Returns the workspace root, or error if not found.
func IsKebabCase ¶
IsKebabCase validates that a string is kebab-case.
func MessageWeight ¶
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 ¶
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 ¶
ValidateCogdocSimple performs simple validation (errors only, no warnings). Returns an error if validation fails, nil otherwise.
func ValidateType ¶
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) 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 ¶
func (b *ContextBuilder) Build(ctx context.Context) (*types.ContextState, error)
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 ¶
func (b *ContextBuilder) WithTier(tier types.ContextTierName) *ContextBuilder
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 ¶
Connect establishes a connection to the workspace kernel.
The workspaceRoot should be the directory containing .cog/. Use "." for the current directory.
Connect will:
- Find and validate the workspace root
- Verify the workspace structure (.cog/id.cog exists)
- Create and configure the Kernel
- 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 ¶
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) FileExists ¶
FileExists checks if a file exists relative to workspace root.
func (*Kernel) GetProjector ¶
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) Mutate ¶
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 ¶
MutateContext is like Mutate but accepts a context.
func (*Kernel) NextEventSeq ¶
NextEventSeq returns the next event sequence number.
func (*Kernel) Project ¶
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 ¶
ProjectContext is like Project but accepts a context.
func (*Kernel) ReadFile ¶
ReadFile is a convenience method to read a file relative to workspace root.
func (*Kernel) RegisterProjector ¶
RegisterProjector adds a projector to the kernel.
func (*Kernel) Resolve ¶
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 ¶
ResolveContext is like Resolve but accepts a context for cancellation.
func (*Kernel) Watch ¶
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 ¶
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)
}
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 ¶
NewAppendMutation creates a mutation that adds to a collection.
func NewDeleteMutation ¶
func NewDeleteMutation() *Mutation
NewDeleteMutation creates a mutation that removes a resource.
func NewPatchMutation ¶
NewPatchMutation creates a mutation that merges with existing content.
func NewSetJSONMutation ¶
NewSetJSONMutation creates a mutation that replaces content with JSON.
func NewSetMutation ¶
NewSetMutation creates a mutation that replaces content.
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 ¶
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 ¶
GetQuery returns a query parameter value, or empty string if not present.
func (*ParsedURI) GetQueryBool ¶
GetQueryBool returns a query parameter as bool. Returns true for "true", "1", "yes"; false otherwise.
func (*ParsedURI) GetQueryFloat ¶
GetQueryFloat returns a query parameter as float64, or default if not present/invalid.
func (*ParsedURI) GetQueryInt ¶
GetQueryInt returns a query parameter as int, or default if not present/invalid.
func (*ParsedURI) IsNamespace ¶
IsNamespace returns true if this URI refers to just a namespace (no path).
func (*ParsedURI) PathSegments ¶
PathSegments returns the path split by "/".
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 ¶
NewJSONResource creates a Resource with JSON content.
func NewResource ¶
NewResource creates a Resource with raw content.
func (*Resource) Count ¶
Count returns the number of items (1 for single resource, len for collection).
func (*Resource) GetMetadata ¶
GetMetadata retrieves a metadata value by key.
func (*Resource) GetMetadataString ¶
GetMetadataString retrieves a metadata value as string.
func (*Resource) IsCollection ¶
IsCollection returns true if this resource contains child resources.
func (*Resource) JSON ¶
JSON unmarshals the Content into the given value. Returns error if ContentType is not JSON or unmarshaling fails.
func (*Resource) SetMetadata ¶
SetMetadata sets a metadata key-value pair.
func (*Resource) WithModTime ¶
WithModTime sets the modification time and returns the resource.
func (*Resource) WithRelevance ¶
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 ¶
IncoherentError returns an SDKError wrapping ErrIncoherent.
func InvalidURIError ¶
InvalidURIError returns an SDKError wrapping ErrInvalidURI with details.
func NewPathError ¶
NewPathError creates a new SDKError for a filesystem operation.
func NewURIError ¶
NewURIError creates a new SDKError for a URI operation.
func NotFoundError ¶
NotFoundError returns an SDKError wrapping ErrNotFound.
func (*SDKError) WithRecover ¶
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.
Source Files
¶
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. |