messaging

package
v0.14.2 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: Apache-2.0 Imports: 33 Imported by: 0

Documentation

Overview

Package messaging provides image extraction from GitHub issue content.

Package messaging provides the MessageStore interface for collaboration hub storage. This interface enables pluggable backends (SQLite, Firestore, etc.) for cloud deployment.

Package messaging provides the collaboration hub's messaging infrastructure. This file implements automatic event emission from package system operations for the package messaging graph (M-PKG-MSG).

Package messaging provides the collaboration hub's messaging infrastructure. This file implements package-scoped inbox addressing and routing for the package messaging graph (M-PKG-MSG).

Package messaging provides the collaboration hub's messaging infrastructure. This file defines typed package coordination message schemas for the package messaging graph (M-PKG-MSG design doc).

Package messaging provides the collaboration hub's messaging infrastructure. This file implements message lifecycle management and triage for the package messaging graph (M-PKG-MSG).

Index

Constants

View Source
const (
	SlotIntent     = "intent"     // What is being asked? Auto-computed from title + payload prefix.
	SlotCode       = "code"       // What code is affected? From file paths + code snippets.
	SlotContext    = "context"    // What was the sender working on? From recent files, errors, tools.
	SlotSkill      = "skill"      // What expertise is needed? From compiler phases, AST nodes, file patterns.
	SlotResolution = "resolution" // How was this resolved? From git diff + commit message (post-completion).
)

EnvelopeSlot names the 5 semantic embedding spaces in a message envelope.

View Source
const (
	InboxStatusUnread   = "unread"
	InboxStatusRead     = "read"
	InboxStatusArchived = "archived"
	InboxStatusDeleted  = "deleted"
)

Inbox message statuses

View Source
const (
	InboxTypeNotification = "notification"
	InboxTypeRequest      = "request"
	InboxTypeResponse     = "response"
)

Inbox message types

View Source
const (
	CategoryBug      = "bug"
	CategoryFeature  = "feature"
	CategoryGeneral  = "general"
	CategoryDocs     = "docs"
	CategoryResearch = "research"
	CategoryRefactor = "refactor"
	CategoryTest     = "test"
)

Message categories (for GitHub sync and coordinator routing)

View Source
const (
	PkgStatusOpen         = "open"
	PkgStatusAcknowledged = "acknowledged"
	PkgStatusInProgress   = "in_progress"
	PkgStatusBlocked      = "blocked"
	PkgStatusCompleted    = "completed"
	PkgStatusRejected     = "rejected"
	PkgStatusSuperseded   = "superseded"
)

Package message lifecycle states

View Source
const MaxChunkSize = 6000

MaxChunkSize is the maximum characters per chunk for embedding embeddinggemma has 2K context (~8000 chars), we use 6000 to be safe

View Source
const PackageMessageSchema = "ailang.package-message/v1"

PackageMessageSchema is the canonical schema version for package coordination messages.

Variables

AllPackageMessageKinds lists all valid package message kinds.

AllSlots lists every valid envelope slot name.

View Source
var ErrAccountMismatch = errors.New("GitHub account mismatch")

ErrAccountMismatch is returned when the active gh user doesn't match expected_user. This is a sentinel error that can be checked with errors.Is() for special handling.

Functions

func CleanupImageCache

func CleanupImageCache(imagePaths []string) error

CleanupImageCache removes cached images for a list of paths.

func CleanupOldImages

func CleanupOldImages(olderThanDays int) (int, error)

CleanupOldImages removes cached images older than the specified duration. Returns the number of files removed.

func CosineSimilarity

func CosineSimilarity(a, b []float32) float64

CosineSimilarity computes cosine similarity between two embeddings

func DatabaseExists

func DatabaseExists(dbPath string) bool

DatabaseExists checks if the collaboration database exists at the given path.

func DimensionMatch

func DimensionMatch(a, b *EnvelopeVector) error

DimensionMatch checks if two envelope vectors have compatible dimensions. Returns an error if dimensions differ, nil if compatible or either is nil.

func EmbeddingFromJSON

func EmbeddingFromJSON(data string) ([]float32, error)

EmbeddingFromJSON parses an embedding from JSON string

func EmbeddingToJSON

func EmbeddingToJSON(embedding []float32) string

EmbeddingToJSON converts an embedding to JSON string for storage

func EmitEffectWideningWarning

func EmitEffectWideningWarning(store *Store, pkgName string, old, new PackageVersionInfo, recipients []string) (string, error)

EmitEffectWideningWarning emits an effect-widening-warning when a package's effect ceiling has expanded.

func EmitFromLockfileDiff

func EmitFromLockfileDiff(store *Store, oldPkgs, newPkgs []PackageVersionInfo, workspace string) (int, error)

EmitFromLockfileDiff compares two sets of locked packages and emits upgrade-available messages for each changed dependency. Returns the number of messages emitted.

func EmitInterfaceChangeNotice

func EmitInterfaceChangeNotice(store *Store, old, new PackageVersionInfo, recipients []string) (string, error)

EmitInterfaceChangeNotice emits an interface-change-notice when a package's exported API has changed (interface hash delta).

func EmitUpgradeAvailable

func EmitUpgradeAvailable(store *Store, old, new PackageVersionInfo, recipients []string) (string, error)

EmitUpgradeAvailable compares old and new package versions and emits an upgrade-available message if there are meaningful changes. Returns the sent message ID, or empty string if no message was needed.

func EnsureConfigDir

func EnsureConfigDir() error

EnsureConfigDir creates the ~/.ailang directory if it doesn't exist

func EnsureDatabase

func EnsureDatabase(dbPath string) (bool, error)

EnsureDatabase creates the database if it doesn't exist. Returns true if database was created, false if it already exists.

func ExtractAndCacheImages

func ExtractAndCacheImages(ctx context.Context, content string, issueID int, repo string) (string, []string, error)

ExtractAndCacheImages finds markdown images in content, downloads them to local cache, and returns modified content with local file paths replacing URLs.

Parameters:

  • ctx: context for cancellation
  • content: markdown content potentially containing images
  • issueID: GitHub issue number (for organizing cache)
  • repo: repository name in "owner/repo" or "owner-repo" format

Returns:

  • modified content with local paths
  • list of cached image paths
  • error if critical failure (individual image failures are logged but don't fail)

func FormatPackageInbox

func FormatPackageInbox(pkgName string) string

FormatPackageInbox returns the canonical inbox address for a package.

func FormatTeamInbox

func FormatTeamInbox(teamName string) string

FormatTeamInbox returns the canonical inbox address for a team.

func FormatWorkspaceInbox

func FormatWorkspaceInbox(workspaceName string) string

FormatWorkspaceInbox returns the canonical inbox address for a workspace.

func GetConfigPath

func GetConfigPath() string

GetConfigPath returns the path to the AILANG config file

func GetDefaultDatabasePath

func GetDefaultDatabasePath() string

GetDefaultDatabasePath returns the default path for the collaboration database.

func InitDB

func InitDB(dbPath string) (*sql.DB, error)

InitDB creates and initializes a new SQLite database with the collaboration hub schema. Returns the database connection and any error encountered.

The database is configured with: - WAL mode for write concurrency - NORMAL synchronous mode for performance - 5 second busy timeout for lock contention

func MigrateDB

func MigrateDB(db *sql.DB) error

MigrateDB applies any necessary schema migrations to an existing database. This is called after InitDB to ensure existing databases are up-to-date.

func PackageEnvelopeToJSON

func PackageEnvelopeToJSON(env *PackageMessageEnvelope) (string, error)

PackageEnvelopeToJSON serializes a PackageMessageEnvelope to JSON.

func ValidateGitHubConfig

func ValidateGitHubConfig(config *GitHubConfig) error

ValidateGitHubConfig validates the GitHub configuration Returns an error if required fields are missing

func ValidatePackageMessage

func ValidatePackageMessage(env *PackageMessageEnvelope) error

ValidatePackageMessage checks that a PackageMessageEnvelope has all required fields for its kind. Returns nil if valid.

func ValidateSlot

func ValidateSlot(slot string) error

ValidateSlot checks that a slot name is one of the 5 known slots.

func WriteExampleConfig

func WriteExampleConfig() (bool, error)

WriteExampleConfig writes an example config file if none exists Returns true if the file was created, false if it already exists

Types

type ActiveAgent

type ActiveAgent struct {
	ID           string `json:"id"`
	Label        string `json:"label"`
	MessagesSent int    `json:"messages_sent"`
	MessagesRecv int    `json:"messages_recv"`
	LastActivity string `json:"last_activity"`
}

ActiveAgent represents an agent that has sent or received messages

type AgentInfo

type AgentInfo struct {
	ID         string `json:"id"`
	LastActive int64  `json:"last_active,omitempty"`
	Status     string `json:"status,omitempty"`
	Label      string `json:"label,omitempty"`
}

AgentInfo represents information about a known agent

type AgentStats

type AgentStats struct {
	AgentID          string        `json:"agent_id"`
	Status           string        `json:"status"` // "active", "idle", "pending"
	ThreadCount      int           `json:"thread_count"`
	UnreadMessages   int           `json:"unread_messages"`
	PendingApprovals int           `json:"pending_approvals"`
	RunningProcesses int           `json:"running_processes"`
	LastActivity     string        `json:"last_activity,omitempty"`
	Threads          []ThreadStats `json:"threads,omitempty"`
}

AgentStats represents detailed statistics for a single agent

type AggregateStats

type AggregateStats struct {
	TotalAgents      int            `json:"total_agents"`
	ActiveAgents     int            `json:"active_agents"`
	IdleAgents       int            `json:"idle_agents"`
	PendingApprovals int            `json:"pending_approvals"`
	RunningProcesses int            `json:"running_processes"`
	TotalThreads     int            `json:"total_threads"`
	Execution        ExecutionStats `json:"execution"`
}

AggregateStats represents overall statistics across all agents

type AggregatedMetrics

type AggregatedMetrics struct {
	ScopeType     string  `json:"scope_type"`
	ScopeID       string  `json:"scope_id"`
	TotalRuns     int     `json:"total_runs"`
	TotalTokens   int     `json:"total_tokens"`
	TotalCost     float64 `json:"total_cost"` // Dollars (cents / 100)
	TotalDuration int     `json:"total_duration_ms"`
	TotalFiles    int     `json:"total_files_modified"`
	AvgTokens     float64 `json:"avg_tokens_per_run"`
	AvgCost       float64 `json:"avg_cost_per_run"`
	AvgDuration   float64 `json:"avg_duration_per_run"`
	PendingTasks  int     `json:"pending_tasks"` // Number of currently running/pending tasks
}

AggregatedMetrics represents pre-computed metrics for a scope

type Approval

type Approval struct {
	ID              string    `json:"id"`
	ThreadID        string    `json:"thread_id"`
	ThreadTitle     string    `json:"thread_title,omitempty"` // Title of the associated thread
	InstanceID      string    `json:"instance_id"`
	CreatedAt       time.Time `json:"created_at"`
	EffectDeltaJSON string    `json:"effect_delta_json"`
	Proposal        string    `json:"proposal"`
	Impact          string    `json:"impact"`
	EstimatedCost   float64   `json:"estimated_cost"`
	Status          string    `json:"status"`
	ReviewedBy      string    `json:"reviewed_by,omitempty"`
	ReviewedAt      time.Time `json:"reviewed_at,omitempty"`
	ReviewNotes     string    `json:"review_notes,omitempty"`
	CapabilityToken string    `json:"capability_token,omitempty"`
	TokenExpiresAt  time.Time `json:"token_expires_at,omitempty"`
}

Approval represents an approval request for effect-gated actions

type ApprovalHistoryEntry

type ApprovalHistoryEntry struct {
	ID              string   `json:"id"`
	ApprovalID      string   `json:"approval_id"`
	ThreadID        string   `json:"thread_id"`
	AgentID         string   `json:"agent_id"`
	Action          string   `json:"action"` // created, approved, rejected, expired
	Actor           string   `json:"actor"`
	Proposal        string   `json:"proposal,omitempty"`
	Impact          string   `json:"impact,omitempty"`
	EstimatedCost   *float64 `json:"estimated_cost,omitempty"`
	CapabilityToken string   `json:"capability_token,omitempty"`
	CreatedAt       int64    `json:"created_at"`
}

ApprovalHistoryEntry represents a single audit entry for an approval action

type Badge

type Badge struct {
	Type  string `json:"type"`  // "unread", "pending", "running"
	Count int    `json:"count"` // Number of items
}

Badge represents a status badge on a hierarchy node

type CapabilityToken

type CapabilityToken struct {
	ThreadID   string    `json:"thread_id"`
	InstanceID string    `json:"instance_id"`
	ApprovalID string    `json:"approval_id"`
	Effects    string    `json:"effects"` // JSON-encoded EffectDelta
	IssuedAt   time.Time `json:"issued_at"`
	ExpiresAt  time.Time `json:"expires_at"`
	Signature  string    `json:"signature"`
}

CapabilityToken represents a signed capability token

func VerifyCapabilityToken

func VerifyCapabilityToken(tokenString string) (*CapabilityToken, error)

VerifyCapabilityToken verifies an HMAC-signed capability token

type Client

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

Client provides an interface for AILANG instances to interact with the collaboration hub

func NewClient

func NewClient(dbPath string, instanceID string) (*Client, error)

NewClient creates a new messaging client for an AILANG instance

func (*Client) AcknowledgeMessage

func (c *Client) AcknowledgeMessage(messageID string) error

AcknowledgeMessage marks a message as acknowledged

func (*Client) BroadcastStatus

func (c *Client) BroadcastStatus(threadID, status string) (*Message, error)

BroadcastStatus sends a status update to all agents watching a thread

func (*Client) CheckApprovalStatus

func (c *Client) CheckApprovalStatus(approvalID string) (string, error)

CheckApprovalStatus checks the status of an approval request

func (*Client) ClaimMessage

func (c *Client) ClaimMessage(messageID string) error

ClaimMessage atomically claims a message for processing. This prevents other agents from processing the same message. Returns nil if successfully claimed, error if already claimed by another agent.

func (*Client) Close

func (c *Client) Close() error

Close closes the client and releases resources

func (*Client) GetCapabilityToken

func (c *Client) GetCapabilityToken(approvalID string) (string, error)

GetCapabilityToken retrieves the capability token for an approved request

func (*Client) GetThread

func (c *Client) GetThread(threadID string) (*Thread, error)

GetThread retrieves thread information

func (*Client) GetThreadWorkspace

func (c *Client) GetThreadWorkspace(threadID string) (string, error)

GetThreadWorkspace retrieves the workspace path for a thread

func (*Client) PollMessages

func (c *Client) PollMessages() ([]*Message, error)

PollMessages checks for new messages addressed to this instance Returns messages that haven't been acknowledged yet

func (*Client) PublishMessage

func (c *Client) PublishMessage(threadID, toType, toID, kind, content string) (*Message, error)

PublishMessage sends a message to a recipient

func (*Client) PublishMessageWithMetadata

func (c *Client) PublishMessageWithMetadata(threadID, toType, toID, kind, content, metadataJSON string) (*Message, error)

PublishMessageWithMetadata sends a message to a recipient with optional metadata

func (*Client) RequestApproval

func (c *Client) RequestApproval(threadID string, effectDelta *EffectDelta, proposal, impact string, estimatedCost float64) (string, error)

RequestApproval creates an approval request for effect-gated actions Returns the approval ID that can be checked later

func (*Client) SendQuestion

func (c *Client) SendQuestion(threadID, question string) (*Message, error)

SendQuestion sends a question to the human in a thread

func (*Client) SendResult

func (c *Client) SendResult(threadID, result string) (*Message, error)

SendResult sends a completion result to the human in a thread

func (*Client) SendResultWithMetadata

func (c *Client) SendResultWithMetadata(threadID, result, metadataJSON string) (*Message, error)

SendResultWithMetadata sends a completion result with structured execution stats

func (*Client) SendStatus

func (c *Client) SendStatus(threadID, status string) (*Message, error)

SendStatus sends a status update message to the human in a thread

func (*Client) SendStatusToAgent

func (c *Client) SendStatusToAgent(threadID, targetAgentID, status string) (*Message, error)

SendStatusToAgent sends a status update to another agent instance

func (*Client) StartPolling

func (c *Client) StartPolling(interval time.Duration, callback func([]*Message) error)

StartPolling starts a background polling loop that checks for new messages every interval The callback is invoked with each batch of new messages

func (*Client) StopPolling

func (c *Client) StopPolling()

StopPolling stops the background polling loop

func (*Client) SubscribeToThread

func (c *Client) SubscribeToThread(threadID string) error

SubscribeToThread subscribes this instance to a thread

func (*Client) UpdateAckSeq

func (c *Client) UpdateAckSeq(threadID string, ackSeq int) error

UpdateAckSeq updates the last acknowledged sequence number for a thread

func (*Client) WaitForApproval

func (c *Client) WaitForApproval(approvalID string, timeout time.Duration) (bool, error)

WaitForApproval waits for an approval request to be approved or rejected Returns true if approved, false if rejected Timeout after the specified duration

type CompatEvidence

type CompatEvidence struct {
	FailingExports     []string `json:"failing_exports,omitempty"`
	ContractViolations []string `json:"contract_violations,omitempty"`
	LockfileSnapshot   string   `json:"lockfile_snapshot,omitempty"`
	Summary            string   `json:"summary,omitempty"`
}

CompatEvidence holds structured evidence for compatibility reports.

type Config

type Config struct {
	GitHub     *GitHubConfig         `yaml:"github"`
	Embeddings *EmbeddingsYAMLConfig `yaml:"embeddings"`
	PubSub     *PubSubConfig         `yaml:"pubsub"`
}

Config holds the full AILANG configuration

func LoadConfig

func LoadConfig() (*Config, error)

LoadConfig loads configuration from ~/.ailang/config.yaml Returns nil if the config file doesn't exist (not an error)

type CreateIssueInput

type CreateIssueInput struct {
	Title     string   // Issue title (will be prefixed with [from])
	Body      string   // Issue body content
	FromAgent string   // Agent name for attribution
	Category  string   // bug, feature, or general
	Repo      string   // Optional repo override (owner/repo)
	Labels    []string // Additional labels
}

CreateIssueInput contains the parameters for creating a GitHub issue.

type DuplicateGroup

type DuplicateGroup struct {
	Representative InboxMessage   `json:"representative"` // Oldest message in group (kept)
	Duplicates     []InboxMessage `json:"duplicates"`     // Similar messages (to be marked)
	MinScore       float64        `json:"min_score"`      // Minimum similarity in group
	ScoreKind      string         `json:"score_kind"`     // "simhash" or "embedding"
}

DuplicateGroup represents a cluster of near-duplicate messages

type EffectDelta

type EffectDelta struct {
	CapType     string   `json:"cap_type"`     // e.g., "FS", "IO", "Net"
	Paths       []string `json:"paths"`        // e.g., ["src/", "docs/"]
	BudgetDelta float64  `json:"budget_delta"` // e.g., 0.50 (50 cents)
}

EffectDelta represents the effect capabilities being requested

type EmbedConfig

type EmbedConfig struct {
	Provider string            `yaml:"provider"` // "ollama", "openai", "gemini", or "none"
	Ollama   OllamaConfig      `yaml:"ollama"`
	OpenAI   OpenAIEmbedConfig `yaml:"openai"`
	Gemini   GeminiEmbedConfig `yaml:"gemini"`
}

EmbedConfig configures the embedding provider

func DefaultEmbedConfig

func DefaultEmbedConfig() EmbedConfig

DefaultEmbedConfig returns the default embedding configuration

func LoadEmbedConfigFromEnv

func LoadEmbedConfigFromEnv() EmbedConfig

LoadEmbedConfigFromEnv loads embedding config from config file and environment variables Priority: env vars > config file > defaults

type Embedder

type Embedder interface {
	Embed(text string) ([]float32, error)
	EmbedBatch(texts []string) ([][]float32, error)
	Dimension() int
	ModelName() string
}

Embedder provides text embedding capabilities for semantic search

func NewEmbedderFromConfig

func NewEmbedderFromConfig(cfg EmbedConfig) (Embedder, error)

NewEmbedderFromConfig creates the appropriate Embedder based on config. Returns (nil, nil) if provider is "none" — callers should check for nil.

type EmbeddingsYAMLConfig

type EmbeddingsYAMLConfig struct {
	// Provider: "ollama", "openai", "gemini", or "none"
	Provider string `yaml:"provider"`

	// Ollama-specific settings
	Ollama struct {
		Model     string `yaml:"model"`
		Endpoint  string `yaml:"endpoint"`
		Dimension int    `yaml:"dimension"`
		Timeout   string `yaml:"timeout"` // e.g., "30s"
		BatchSize int    `yaml:"batch_size"`
	} `yaml:"ollama"`

	// OpenAI-specific settings (M-SEMANTIC-ENVELOPE)
	OpenAI struct {
		APIKey    string `yaml:"api_key"`   // Falls back to OPENAI_API_KEY env
		Model     string `yaml:"model"`     // e.g. "text-embedding-3-small"
		Dimension int    `yaml:"dimension"` // 0 = model default
		Timeout   string `yaml:"timeout"`
	} `yaml:"openai"`

	// Gemini-specific settings (M-SEMANTIC-ENVELOPE)
	Gemini struct {
		APIKey    string `yaml:"api_key"`   // Falls back to GOOGLE_API_KEY env
		Model     string `yaml:"model"`     // e.g. "text-embedding-004"
		Dimension int    `yaml:"dimension"` // 0 = model default
		Timeout   string `yaml:"timeout"`
	} `yaml:"gemini"`

	// Search behavior
	Search struct {
		DefaultMode       string  `yaml:"default_mode"` // "simhash" or "neural"
		AutoEmbedOnInsert bool    `yaml:"auto_embed_on_insert"`
		SimhashThreshold  float64 `yaml:"simhash_threshold"`
		NeuralThreshold   float64 `yaml:"neural_threshold"`
	} `yaml:"search"`
}

EmbeddingsYAMLConfig holds YAML configuration for embeddings

func LoadEmbeddingsConfig

func LoadEmbeddingsConfig() (*EmbeddingsYAMLConfig, error)

LoadEmbeddingsConfig loads the embeddings configuration Returns nil if embeddings config is not present (not an error)

type Envelope

type Envelope struct {
	Slots map[string]*EnvelopeVector `json:"slots"`
}

Envelope holds named embedding vectors for a message, each capturing a different aspect of the message's meaning.

Slots are optional — most messages will only have "intent" (auto-computed). Other slots are populated explicitly via EnvelopeBuilder options or CLI flags.

func EnvelopeFromJSON

func EnvelopeFromJSON(data string) *Envelope

EnvelopeFromJSON parses an envelope from a JSON string. Returns an empty envelope (not nil) for empty/invalid input.

func NewEnvelope

func NewEnvelope() *Envelope

NewEnvelope creates an empty envelope.

func (*Envelope) Get

func (e *Envelope) Get(slot string) *EnvelopeVector

Get returns the vector for the named slot, or nil if not present.

func (*Envelope) GetVector

func (e *Envelope) GetVector(slot string) []float32

GetVector returns just the float32 slice for the named slot, or nil.

func (*Envelope) IsEmpty

func (e *Envelope) IsEmpty() bool

IsEmpty returns true if the envelope has no populated slots.

func (*Envelope) Merge

func (e *Envelope) Merge(other *Envelope)

Merge copies non-nil slots from other into e without overwriting existing slots.

func (*Envelope) MergeOverwrite

func (e *Envelope) MergeOverwrite(other *Envelope)

MergeOverwrite copies all non-nil slots from other into e, overwriting existing slots.

func (*Envelope) PopulatedSlots

func (e *Envelope) PopulatedSlots() []string

PopulatedSlots returns the names of slots that have vectors.

func (*Envelope) Set

func (e *Envelope) Set(slot string, vector []float32, model string)

Set stores a vector in the named slot.

func (*Envelope) ToJSON

func (e *Envelope) ToJSON() string

ToJSON serializes the envelope to a JSON string for SQLite storage.

type EnvelopeBuilder

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

EnvelopeBuilder computes envelope vectors from contextual inputs. Usage:

env, err := NewEnvelopeBuilder(embedder).
    WithCodeContext([]string{"internal/types/unify.go"}, []string{"func unify(a, b Type)..."}).
    WithResolution("fix: handle recursive types", "diff --git a/...").
    Build(msg)

func NewEnvelopeBuilder

func NewEnvelopeBuilder(embedder Embedder) *EnvelopeBuilder

NewEnvelopeBuilder creates a builder that will compute envelope vectors using the given embedder.

func (*EnvelopeBuilder) Build

func (b *EnvelopeBuilder) Build(msg *InboxMessage) (*Envelope, error)

Build computes the envelope for the given message. The "intent" slot is always computed from title + payload prefix. Other slots are only computed if the corresponding With* method was called.

func (*EnvelopeBuilder) WithCodeContext

func (b *EnvelopeBuilder) WithCodeContext(filePaths []string, codeSnippets []string) *EnvelopeBuilder

WithCodeContext sets file paths and code snippets for the "code" envelope slot. This captures what code is affected by the message.

func (*EnvelopeBuilder) WithResolution

func (b *EnvelopeBuilder) WithResolution(commitMsg, diff string) *EnvelopeBuilder

WithResolution sets the commit message and diff for the "resolution" slot. This captures how a task was resolved (called post-completion).

func (*EnvelopeBuilder) WithSessionContext

func (b *EnvelopeBuilder) WithSessionContext(recentFiles, recentErrors, recentTools []string) *EnvelopeBuilder

WithSessionContext sets recent files, errors, and tools for the "context" slot. This captures what the sender was working on.

func (*EnvelopeBuilder) WithSkillHints

func (b *EnvelopeBuilder) WithSkillHints(phases, nodeTypes, filePatterns []string) *EnvelopeBuilder

WithSkillHints sets compiler phases, AST node types, and file patterns for the "skill" slot. This captures what expertise is needed to handle the message.

type EnvelopeOption

type EnvelopeOption func(b *EnvelopeBuilder)

EnvelopeOption is a functional option for building an envelope.

type EnvelopeVector

type EnvelopeVector struct {
	Vector    []float32 `json:"vector"`
	Model     string    `json:"model"`     // e.g. "ollama:nomic-embed-text"
	Dimension int       `json:"dimension"` // e.g. 768
}

EnvelopeVector holds a single named embedding vector with its model metadata.

type ExecutionMetadata

type ExecutionMetadata struct {
	Success             bool     `json:"success"`
	DurationMS          int      `json:"duration_ms"`
	NumTurns            int      `json:"num_turns"`
	Cost                float64  `json:"cost"`
	SessionID           string   `json:"session_id"`
	InputTokens         int      `json:"input_tokens"`
	OutputTokens        int      `json:"output_tokens"`
	CacheReadTokens     int      `json:"cache_read_tokens"`
	CacheCreationTokens int      `json:"cache_creation_tokens"`
	FilesCreatedCount   int      `json:"files_created_count"`
	FilesCreated        []string `json:"files_created"`
	Workspace           string   `json:"workspace"`
}

ExecutionMetadata contains per-message execution details including file list

type ExecutionStats

type ExecutionStats struct {
	TotalExecutions        int     `json:"total_executions"`
	SuccessfulExecutions   int     `json:"successful_executions"`
	FailedExecutions       int     `json:"failed_executions"`
	TotalDurationMS        int64   `json:"total_duration_ms"`
	TotalCost              float64 `json:"total_cost"`
	TotalInputTokens       int     `json:"total_input_tokens"`
	TotalOutputTokens      int     `json:"total_output_tokens"`
	TotalCacheReadTokens   int     `json:"total_cache_read_tokens"`
	TotalCacheCreateTokens int     `json:"total_cache_create_tokens"`
	TotalFilesCreated      int     `json:"total_files_created"`
}

ExecutionStats represents aggregated execution statistics

type GeminiEmbedConfig

type GeminiEmbedConfig struct {
	APIKey    string        `yaml:"api_key"`   // Defaults to GOOGLE_API_KEY env
	Model     string        `yaml:"model"`     // e.g. "text-embedding-004"
	Dimension int           `yaml:"dimension"` // Output dimension (0 = model default)
	Timeout   time.Duration `yaml:"timeout"`
}

GeminiEmbedConfig configures the Gemini embedding provider

type GeminiEmbedder

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

GeminiEmbedder implements Embedder using the Gemini Embedding API.

func NewGeminiEmbedder

func NewGeminiEmbedder(cfg GeminiEmbedConfig) (*GeminiEmbedder, error)

NewGeminiEmbedder creates a new Gemini-based embedder.

func (*GeminiEmbedder) Dimension

func (e *GeminiEmbedder) Dimension() int

Dimension returns the embedding dimension.

func (*GeminiEmbedder) Embed

func (e *GeminiEmbedder) Embed(text string) ([]float32, error)

Embed generates an embedding for a single text. For long texts, it chunks and averages the embeddings.

func (*GeminiEmbedder) EmbedBatch

func (e *GeminiEmbedder) EmbedBatch(texts []string) ([][]float32, error)

EmbedBatch generates embeddings for multiple texts.

func (*GeminiEmbedder) ModelName

func (e *GeminiEmbedder) ModelName() string

ModelName returns the model identifier.

type GitHubClient

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

GitHubClient provides integration with GitHub via the gh CLI. All methods require gh to be installed and authenticated.

func NewGitHubClient

func NewGitHubClient(config *GitHubConfig) *GitHubClient

NewGitHubClient creates a new GitHub client with the given configuration.

func (*GitHubClient) AddComment

func (c *GitHubClient) AddComment(repo string, number int, body string) error

AddComment adds a comment to an existing issue.

func (*GitHubClient) AddLabelToIssue

func (c *GitHubClient) AddLabelToIssue(repo string, number int, label string) error

AddLabelToIssue adds a label to an existing issue.

func (*GitHubClient) CheckGHAuth

func (c *GitHubClient) CheckGHAuth() (string, error)

CheckGHAuth verifies that gh is authenticated and returns the active username. Returns an error with authentication instructions if not logged in.

func (*GitHubClient) CheckGHInstalled

func (c *GitHubClient) CheckGHInstalled() (string, error)

CheckGHInstalled verifies that the gh CLI is installed and returns the version. Returns an error with installation instructions if not found.

func (*GitHubClient) CloseIssue

func (c *GitHubClient) CloseIssue(repo string, number int, comment string) error

CloseIssue closes an issue with an optional comment.

func (*GitHubClient) CreateIssue

func (c *GitHubClient) CreateIssue(input CreateIssueInput) (int, error)

CreateIssue creates a new GitHub issue and returns the issue number. The title is prefixed with [from:agent-name] and a from:agent-name label is added. Labels are automatically created if they don't exist.

func (*GitHubClient) EnsureLabel

func (c *GitHubClient) EnsureLabel(repo, name, description, color string) error

EnsureLabel creates a label if it doesn't already exist. Returns nil if label exists or was created successfully.

func (*GitHubClient) EnsureLabelsForIssue

func (c *GitHubClient) EnsureLabelsForIssue(repo string, labels []string) error

EnsureLabelsForIssue ensures all labels needed for an issue exist.

func (*GitHubClient) GetConfig

func (c *GitHubClient) GetConfig() *GitHubConfig

GetConfig returns the GitHub configuration (may be nil if not configured).

func (*GitHubClient) GetIssue

func (c *GitHubClient) GetIssue(repo string, number int) (*GitHubIssue, error)

GetIssue retrieves a single issue by number.

func (*GitHubClient) GetIssueComments

func (c *GitHubClient) GetIssueComments(repo string, number int) ([]GitHubComment, error)

GetIssueComments retrieves all comments on an issue.

func (*GitHubClient) GetIssueLabels

func (c *GitHubClient) GetIssueLabels(repo string, number int) ([]string, error)

GetIssueLabels returns the labels on an issue.

func (*GitHubClient) ListIssuesByLabel

func (c *GitHubClient) ListIssuesByLabel(repo string, labels []string) ([]GitHubIssue, error)

ListIssuesByLabel returns all open issues matching the specified labels. If no labels provided, uses watch_labels from config.

func (*GitHubClient) PreFlightChecks

func (c *GitHubClient) PreFlightChecks() error

PreFlightChecks runs all pre-flight checks before GitHub operations. Returns nil if all checks pass, or the first error encountered. If autoSwitch is enabled on the client, attempts to auto-switch on account mismatch.

func (*GitHubClient) RemoveLabelFromIssue

func (c *GitHubClient) RemoveLabelFromIssue(repo string, number int, label string) error

RemoveLabelFromIssue removes a label from an existing issue.

func (*GitHubClient) SetAutoSwitch

func (c *GitHubClient) SetAutoSwitch(enabled bool)

SetAutoSwitch enables or disables automatic account switching on mismatch. When enabled, PreFlightChecks will attempt `gh auth switch` to the expected user. Use this in daemon/background contexts where auto-switching is acceptable.

func (*GitHubClient) SetOverrideUser

func (c *GitHubClient) SetOverrideUser(user string)

SetOverrideUser sets a user to accept instead of (or in addition to) the expected_user. When set, if the active gh user matches this override, validation passes. This allows CLI users to bypass the expected_user check with --github-user flag.

func (*GitHubClient) ValidateUser

func (c *GitHubClient) ValidateUser() error

ValidateUser checks that the authenticated gh user matches the expected user. Returns nil if they match, or an error with instructions if they don't. This is a HARD FAIL - callers should not proceed if this returns an error.

If SetOverrideUser() was called, that user is also accepted.

func (*GitHubClient) ValidateUserWithAutoSwitch

func (c *GitHubClient) ValidateUserWithAutoSwitch() error

ValidateUserWithAutoSwitch checks that the authenticated gh user matches the expected user. If there's a mismatch, it will attempt to auto-switch to the expected account. Returns nil if validation passes (either immediately or after auto-switch). Use this in daemon/background contexts where auto-switching is acceptable.

type GitHubComment

type GitHubComment struct {
	ID        int64  `json:"id"`
	Body      string `json:"body"`
	Author    string `json:"author"`
	CreatedAt string `json:"createdAt"`
}

GitHubComment represents a comment on a GitHub issue.

type GitHubConfig

type GitHubConfig struct {
	// DefaultRepo is the default repository for --github flag (e.g., "sunholo-data/ailang")
	DefaultRepo string `yaml:"default_repo"`

	// InboxRepos maps inbox names (or prefixes) to specific GitHub repositories.
	// This allows messages sent to different inboxes to create issues in the correct repo.
	// Supports exact matches and prefix matches (e.g., "pkg:" matches "pkg:sunholo/auth").
	InboxRepos map[string]string `yaml:"inbox_repos"`

	// ExpectedUser is the expected GitHub username (must match gh auth status)
	// This prevents accidentally creating issues under the wrong account
	ExpectedUser string `yaml:"expected_user"`

	// CreateLabels are labels to add when creating issues
	CreateLabels []string `yaml:"create_labels"`

	// WatchLabels are labels to watch for incoming messages (import)
	WatchLabels []string `yaml:"watch_labels"`

	// AutoImport enables automatic import on session start (default: true)
	AutoImport *bool `yaml:"auto_import"`
}

GitHubConfig holds configuration for GitHub integration

func LoadGitHubConfig

func LoadGitHubConfig() (*GitHubConfig, error)

LoadGitHubConfig loads just the GitHub configuration Returns nil if GitHub config is not present (not an error)

func (*GitHubConfig) IsAutoImportEnabled

func (c *GitHubConfig) IsAutoImportEnabled() bool

IsAutoImportEnabled returns whether auto-import is enabled (defaults to true)

func (*GitHubConfig) RepoForInbox

func (c *GitHubConfig) RepoForInbox(inbox string) string

RepoForInbox returns the GitHub repository for a given inbox name. Resolution order: exact match in inbox_repos, then prefix match, then default_repo.

type GitHubIssue

type GitHubIssue struct {
	Number    int      `json:"number"`
	Title     string   `json:"title"`
	Body      string   `json:"body"`
	State     string   `json:"state"`
	Labels    []string `json:"labels"`
	CreatedAt string   `json:"createdAt"`
	Author    string   `json:"author"`
	URL       string   `json:"url"`
}

GitHubIssue represents a GitHub issue returned from the API.

type HierarchyNode

type HierarchyNode struct {
	Type     string          `json:"type"`               // "root", "agent", "thread"
	ID       string          `json:"id"`                 // Unique identifier
	Label    string          `json:"label"`              // Display label
	Status   string          `json:"status,omitempty"`   // "active", "idle", "pending"
	Badges   []Badge         `json:"badges,omitempty"`   // Status badges
	Children []HierarchyNode `json:"children,omitempty"` // Child nodes
}

HierarchyNode represents a node in the agent/thread hierarchy tree

type HierarchyResponse

type HierarchyResponse struct {
	Root      HierarchyNode  `json:"root"`
	Aggregate AggregateStats `json:"aggregate"`
}

HierarchyResponse is the response for the /api/hierarchy endpoint

type InboxAddress

type InboxAddress struct {
	Type InboxAddressType
	Name string // The part after the prefix (e.g., "sunholo/auth" from "pkg:sunholo/auth")
	Raw  string // Original full address string
}

InboxAddress is a parsed inbox address with type and name.

func ParseInboxAddress

func ParseInboxAddress(addr string) InboxAddress

ParseInboxAddress parses an inbox address string into its type and name. Supported formats:

"pkg:sunholo/auth"     → {Type: "pkg", Name: "sunholo/auth"}
"workspace:docparse"   → {Type: "workspace", Name: "docparse"}
"team:registry-admin"  → {Type: "team", Name: "registry-admin"}
"user"                 → {Type: "plain", Name: "user"}

type InboxAddressType

type InboxAddressType string

InboxAddressType classifies inbox address prefixes.

const (
	InboxAddrPackage   InboxAddressType = "pkg"
	InboxAddrWorkspace InboxAddressType = "workspace"
	InboxAddrTeam      InboxAddressType = "team"
	InboxAddrPlain     InboxAddressType = "plain"
)

type InboxListOptions

type InboxListOptions struct {
	Inbox       string // Filter by inbox name (empty = all)
	Status      string // Filter by status (empty = all)
	UnreadOnly  bool   // Only unread messages
	FromAgent   string // Filter by sender
	Limit       int    // Max results (0 = no limit)
	IncludeRead bool   // Include read messages (default: true unless UnreadOnly)
	Collapsed   bool   // Hide messages where dup_of IS NOT NULL (semantic dedup)
	DupOf       string // Only messages that are duplicates of this ID
	StartDate   string // Filter messages created >= this date (YYYY-MM-DD)
	EndDate     string // Filter messages created <= this date (YYYY-MM-DD)
}

InboxListOptions specifies filters for listing inbox messages

type InboxMessage

type InboxMessage struct {
	ID                 string     `json:"id"`
	MessageID          string     `json:"message_id"`
	CorrelationID      string     `json:"correlation_id,omitempty"`
	FromAgent          string     `json:"from_agent"`
	ToInbox            string     `json:"to_inbox"`
	MessageType        string     `json:"message_type"`
	Title              string     `json:"title"`
	Payload            string     `json:"payload,omitempty"`
	Category           string     `json:"category,omitempty"`             // bug, feature, general (for GitHub sync)
	GitHubIssue        *int       `json:"github_issue,omitempty"`         // GitHub issue number
	GitHubRepo         string     `json:"github_repo,omitempty"`          // GitHub repo (owner/repo)
	Simhash            *int64     `json:"simhash,omitempty"`              // SimHash for semantic search (v1.2.0)
	DupOf              string     `json:"dup_of,omitempty"`               // ID of message this is a duplicate of (v1.2.0)
	Embedding          string     `json:"embedding,omitempty"`            // JSON-encoded float32 array (v1.3.0)
	EmbeddingModel     string     `json:"embedding_model,omitempty"`      // e.g., "ollama:nomic-embed-text" (v1.3.0)
	EmbeddingUpdatedAt *int64     `json:"embedding_updated_at,omitempty"` // Unix millis (v1.3.0)
	ParentTaskID       string     `json:"parent_task_id,omitempty"`       // Parent task for hierarchy (v1.5.0, M-UNIFIED-AI-CONTROL-PLANE)
	ChainID            string     `json:"chain_id,omitempty"`             // Execution chain ID for unified hierarchy (M-CHAINS-SIMPLIFY)
	Iteration          int        `json:"iteration,omitempty"`            // Iteration number for feedback loops (M-TASK-HIERARCHY)
	Envelope           *Envelope  `json:"envelope,omitempty"`             // Multi-aspect semantic embeddings (v1.8.0, M-SEMANTIC-ENVELOPE)
	Status             string     `json:"status"`
	CreatedAt          time.Time  `json:"created_at"`
	ReadAt             *time.Time `json:"read_at,omitempty"`
	ExpiresAt          *time.Time `json:"expires_at,omitempty"`
}

InboxMessage represents a message in the unified inbox system

type InstanceHistoryEntry

type InstanceHistoryEntry struct {
	ID            string `json:"id"`
	AgentID       string `json:"agent_id"`
	InstanceID    string `json:"instance_id"`
	StartedAt     int64  `json:"started_at"`
	EndedAt       *int64 `json:"ended_at,omitempty"`
	ExitCode      *int   `json:"exit_code,omitempty"`
	TotalTokens   int    `json:"total_tokens"`
	TotalCostCent int    `json:"total_cost_cents"`
	ThreadCount   int    `json:"thread_count"`
}

InstanceHistoryEntry represents lifecycle data for an agent instance

type Message

type Message struct {
	ID            string    `json:"id"`
	ThreadID      string    `json:"thread_id"`
	MessageSeq    int       `json:"message_seq"`
	CreatedAt     time.Time `json:"created_at"`
	FromType      string    `json:"from_type"`
	FromID        string    `json:"from_id"`
	ToType        string    `json:"to_type"`
	ToID          string    `json:"to_id"`
	Kind          string    `json:"kind"`
	Content       string    `json:"content"`
	MetadataJSON  string    `json:"metadata_json"`
	DeliveryState string    `json:"delivery_state"`
	BusinessState string    `json:"business_state"`
}

Message represents a message in the collaboration hub (simplified view for CLI)

type MessageExecutionStats

type MessageExecutionStats struct {
	DurationMS   int      `json:"duration_ms"`
	InputTokens  int      `json:"input_tokens"`
	OutputTokens int      `json:"output_tokens"`
	CostCents    int      `json:"cost_cents"`
	FilesCreated []string `json:"files_created"`
}

MessageExecutionStats represents metrics extracted from a single result message

func ParseMessageExecutionStats

func ParseMessageExecutionStats(metadataJSON string) (*MessageExecutionStats, error)

ParseMessageExecutionStats extracts execution stats from message metadata JSON

type MessageFlowEdge

type MessageFlowEdge struct {
	FromAgent    string `json:"from_agent"`
	ToInbox      string `json:"to_inbox"`
	MessageCount int    `json:"message_count"`
	LastActivity string `json:"last_activity,omitempty"`
}

MessageFlowEdge represents an edge between agents based on actual message handoffs

type MessageStore

type MessageStore interface {
	// Lifecycle
	Close() error

	CreateThread(title, createdByType, createdByID, targetAgent string) (*Thread, error)
	CreateThreadWithWorkspace(title, createdByType, createdByID, targetAgent, workspace string) (*Thread, error)
	GetOrCreateThreadWithWorkspace(title, createdByType, createdByID, targetAgent, workspace string) (*Thread, bool, error)
	GetThreadByTitleAndAgent(title, targetAgent string) (*Thread, error)
	GetThread(threadID string) (*Thread, error)
	SetThreadWorkspace(threadID, workspace string) error
	GetThreadWorkspace(threadID string) (string, error)
	SetThreadTargetAgent(threadID, targetAgent string) error
	UpdateThreadTitle(threadID, title string) error
	DeleteThread(threadID string) error
	GetThreadsByStatus(status string, limit int) ([]Thread, error)
	NewThreadFilter(status, workspace string, limit int) ThreadFilter
	GetThreadsFiltered(filter ThreadFilter) ([]Thread, error)
	GetDistinctWorkspaces() ([]string, error)
	GetThreadAggregateStats() (*ThreadAggregateStats, error)

	GetMessages(toType, toID string, deliveryState string) ([]Message, error)
	MarkAsAcked(messageID string) error
	MarkAsUnacked(messageID string) error
	ClaimMessage(messageID, claimedBy string) error
	MarkAllAsAcked(toType, toID string) (int64, error)
	CreateMessage(threadID, fromType, fromID, toType, toID, kind, content, metadataJSON string) (*Message, error)
	GetMessagesFromSeq(threadID string, fromSeq int, limit int) ([]Message, error)
	Subscribe(instanceID, threadID string) error
	UpdateAckSeq(instanceID, threadID string, ackSeq int) error

	InsertInboxMessage(msg *InboxMessage) error
	InsertInboxMessageWithContext(ctx context.Context, msg *InboxMessage) error
	ListInboxMessages(opts InboxListOptions) ([]InboxMessage, error)
	GetInboxMessage(id string) (*InboxMessage, error)
	FindMessageByPrefix(prefix string) (string, error)
	MarkInboxMessageRead(id string) error
	MarkInboxMessageUnread(id string) error
	MarkAllInboxMessagesRead(inbox string) (int64, error)
	ForwardInboxMessage(id string, toInbox string) error
	InboxMessageExistsByGitHub(repo string, issueNumber int) (bool, error)
	InboxMessageExistsByTitle(inbox string, title string) (string, error)
	UpdateInboxMessageGitHub(messageID string, issueNumber int, repo string) error
	CleanupInboxMessages(olderThan time.Duration, expiredOnly bool) (int64, error)
	CountInboxMessagesByStatus(inbox string) (map[string]int64, error)
	GetMessageFlowEdges() ([]MessageFlowEdge, error)
	GetActiveAgents() ([]ActiveAgent, error)

	CreateApproval(threadID, instanceID string, effectDelta *EffectDelta, proposal, impact string, estimatedCost float64) (*Approval, error)
	GetApproval(approvalID string) (*Approval, error)
	GetApprovalsByStatus(status string, limit int) ([]Approval, error)
	ApproveApproval(approvalID, reviewedBy string, reviewNotes string, tokenDuration time.Duration) error
	RejectApproval(approvalID, reviewedBy string, reviewNotes string) error

	RecordApprovalHistory(approvalID, threadID, agentID, action, actor, proposal, impact string, estimatedCost *float64, capabilityToken string) error
	GetApprovalHistory(threadID string, limit int) ([]ApprovalHistoryEntry, error)
	RecordInstanceStart(agentID, instanceID string) error
	RecordInstanceEnd(instanceID string, exitCode int, totalTokens, totalCostCents, threadCount int) error
	GetInstanceHistory(agentID string, limit int) ([]InstanceHistoryEntry, error)
	CleanupOldHistory(retentionDays int) (int64, int64, error)

	SemanticSearch(opts SearchOptions) ([]SearchHit, error)
	FindSimilar(msgID string, threshold float64, limit int) ([]SearchHit, error)
	FindDuplicates(inbox string, threshold float64) ([]DuplicateGroup, error)
	ApplyDuplicates(groups []DuplicateGroup, runID string) error
	ClearDuplicateMarker(msgID string) error
	UpdateMessageEmbedding(msgID string, embedding []float32, model string) error
	UpdateMessageEnvelope(msgID string, env *Envelope, overwrite bool) error

	RecordMetrics(threadID, agentID string, stats *MessageExecutionStats) error
	GetMetrics(scopeType, scopeID string) (*AggregatedMetrics, error)
	GetGlobalMetrics() (*AggregatedMetrics, error)
	GetAgentMetrics(agentID string) (*AggregatedMetrics, error)
	GetThreadMetrics(threadID string) (*AggregatedMetrics, error)
	GetMetricsTrends(scopeType, scopeID, period string, limit int) ([]map[string]interface{}, error)

	GetAggregatedExecutionStats() (*ExecutionStats, error)
	GetExecutionStatsByThread(threadID string) (*ExecutionStats, error)
	GetHierarchy() (*HierarchyResponse, error)
	GetAgentStats(agentID string) (*AgentStats, error)
	GetKnownAgents() ([]AgentInfo, error)

	RegisterAgent(agentID, label, status string) error
	UpdateAgentStatus(agentID, status string) error
	RecordAgentInstance(agentID, instanceID string) error
}

MessageStore defines the abstract storage interface for the collaboration hub. The concrete SQLite implementation is Store; cloud backends (Firestore, etc.) can implement this interface to enable AILANG_STORAGE=gcp mode.

type OllamaConfig

type OllamaConfig struct {
	Model     string        `yaml:"model"`
	Endpoint  string        `yaml:"endpoint"`
	Dimension int           `yaml:"dimension"`
	Timeout   time.Duration `yaml:"timeout"`
	BatchSize int           `yaml:"batch_size"`
}

OllamaConfig configures the Ollama embedding provider

type OllamaEmbedder

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

OllamaEmbedder implements Embedder using local Ollama

func NewOllamaEmbedder

func NewOllamaEmbedder(cfg OllamaConfig) (*OllamaEmbedder, error)

NewOllamaEmbedder creates a new Ollama-based embedder

func (*OllamaEmbedder) Dimension

func (e *OllamaEmbedder) Dimension() int

Dimension returns the embedding dimension

func (*OllamaEmbedder) Embed

func (e *OllamaEmbedder) Embed(text string) ([]float32, error)

Embed generates an embedding for a single text For long texts, it chunks and averages the embeddings

func (*OllamaEmbedder) EmbedBatch

func (e *OllamaEmbedder) EmbedBatch(texts []string) ([][]float32, error)

EmbedBatch generates embeddings for multiple texts

func (*OllamaEmbedder) ModelName

func (e *OllamaEmbedder) ModelName() string

ModelName returns the model identifier

type OpenAIEmbedConfig

type OpenAIEmbedConfig struct {
	APIKey    string        `yaml:"api_key"`   // Defaults to OPENAI_API_KEY env
	Model     string        `yaml:"model"`     // e.g. "text-embedding-3-small"
	Dimension int           `yaml:"dimension"` // Output dimension (0 = model default)
	Timeout   time.Duration `yaml:"timeout"`
}

OpenAIEmbedConfig configures the OpenAI embedding provider

type OpenAIEmbedder

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

OpenAIEmbedder implements Embedder using the OpenAI Embeddings API.

func NewOpenAIEmbedder

func NewOpenAIEmbedder(cfg OpenAIEmbedConfig) (*OpenAIEmbedder, error)

NewOpenAIEmbedder creates a new OpenAI-based embedder.

func (*OpenAIEmbedder) Dimension

func (e *OpenAIEmbedder) Dimension() int

Dimension returns the embedding dimension.

func (*OpenAIEmbedder) Embed

func (e *OpenAIEmbedder) Embed(text string) ([]float32, error)

Embed generates an embedding for a single text. For long texts, it chunks and averages the embeddings.

func (*OpenAIEmbedder) EmbedBatch

func (e *OpenAIEmbedder) EmbedBatch(texts []string) ([][]float32, error)

EmbedBatch generates embeddings for multiple texts.

func (*OpenAIEmbedder) ModelName

func (e *OpenAIEmbedder) ModelName() string

ModelName returns the model identifier.

type PackageMessageEnvelope

type PackageMessageEnvelope struct {
	Schema    string             `json:"schema"`
	MessageID string             `json:"message_id,omitempty"`
	Kind      PackageMessageKind `json:"kind"`
	From      string             `json:"from"`
	To        []string           `json:"to"`
	Timestamp time.Time          `json:"timestamp"`
	Package   PackageRef         `json:"package"`

	// Optional fields
	Summary           string          `json:"summary,omitempty"`
	RecommendedAction string          `json:"recommended_action,omitempty"`
	Refs              *PackageRefs    `json:"refs,omitempty"`
	Status            string          `json:"status,omitempty"`
	Supersedes        string          `json:"supersedes,omitempty"`
	RelatedMessages   []string        `json:"related_messages,omitempty"`
	Evidence          *CompatEvidence `json:"evidence,omitempty"`
	BlockReason       string          `json:"block_reason,omitempty"`
}

PackageMessageEnvelope is the canonical envelope for package coordination messages. It is stored as JSON in InboxMessage.Payload.

func ExtractPackageEnvelope

func ExtractPackageEnvelope(msg *InboxMessage) (*PackageMessageEnvelope, error)

ExtractPackageEnvelope attempts to parse a PackageMessageEnvelope from an InboxMessage's Payload. Returns nil, nil if the payload is not a package message (no schema field or wrong schema).

func PackageEnvelopeFromJSON

func PackageEnvelopeFromJSON(data string) (*PackageMessageEnvelope, error)

PackageEnvelopeFromJSON deserializes a PackageMessageEnvelope from JSON.

func (*PackageMessageEnvelope) ToInboxMessage

func (env *PackageMessageEnvelope) ToInboxMessage() (*InboxMessage, error)

ToInboxMessage converts a PackageMessageEnvelope to an InboxMessage suitable for storage in the messaging system. The envelope is serialized into the Payload field as JSON.

type PackageMessageKind

type PackageMessageKind string

PackageMessageKind identifies the type of package coordination event.

const (
	PkgMsgUpgradeAvailable    PackageMessageKind = "upgrade-available"
	PkgMsgInterfaceChange     PackageMessageKind = "interface-change-notice"
	PkgMsgEffectWidening      PackageMessageKind = "effect-widening-warning"
	PkgMsgCompatibilityReq    PackageMessageKind = "compatibility-request"
	PkgMsgCompatibilityReport PackageMessageKind = "compatibility-report"
	PkgMsgContractRegression  PackageMessageKind = "contract-regression"
	PkgMsgMigrationRequest    PackageMessageKind = "migration-request"
	PkgMsgDeprecationNotice   PackageMessageKind = "deprecation-notice"
	PkgMsgUpgradeComplete     PackageMessageKind = "upgrade-complete"
	PkgMsgBlocked             PackageMessageKind = "blocked"
	PkgMsgSuperseded          PackageMessageKind = "superseded"
)

type PackageMessageStats

type PackageMessageStats struct {
	TotalMessages     int            `json:"total_messages"`
	ByKind            map[string]int `json:"by_kind"`
	ByStatus          map[string]int `json:"by_status"`
	OpenUpgrades      int            `json:"open_upgrades"`
	BlockedMigrations int            `json:"blocked_migrations"`
	LastActivity      *time.Time     `json:"last_activity,omitempty"`
}

PackageMessageStats returns aggregate stats for package messages.

type PackageRef

type PackageRef struct {
	Name              string   `json:"name"`
	FromVersion       string   `json:"from_version,omitempty"`
	ToVersion         string   `json:"to_version,omitempty"`
	FromInterfaceHash string   `json:"from_interface_hash,omitempty"`
	ToInterfaceHash   string   `json:"to_interface_hash,omitempty"`
	FromContentHash   string   `json:"from_content_hash,omitempty"`
	ToContentHash     string   `json:"to_content_hash,omitempty"`
	ChangeClass       string   `json:"change_class,omitempty"`
	EffectDelta       []string `json:"effect_delta,omitempty"`
	Breaking          *bool    `json:"breaking,omitempty"`

	// For effect-widening-warning
	PrevEffectCeiling []string `json:"prev_effect_ceiling,omitempty"`
	NewEffectCeiling  []string `json:"new_effect_ceiling,omitempty"`

	// For contract-regression
	AffectedExports []string `json:"affected_exports,omitempty"`
	PrevContract    string   `json:"prev_contract,omitempty"`
	NewContract     string   `json:"new_contract,omitempty"`

	// For compatibility-report
	Result          string `json:"result,omitempty"` // "pass", "fail", "partial"
	TargetWorkspace string `json:"target_workspace,omitempty"`
}

PackageRef identifies a package and describes version/hash deltas.

type PackageRefs

type PackageRefs struct {
	PackageURL   string `json:"package_url,omitempty"`
	ReleaseNotes string `json:"release_notes,omitempty"`
	LockfileRef  string `json:"lockfile_ref,omitempty"`
}

PackageRefs holds optional reference links.

type PackageVersionInfo

type PackageVersionInfo struct {
	Name          string
	Version       string
	InterfaceHash string
	ContentHash   string
	Effects       []string
	Exports       []string
}

PackageVersionInfo holds the metadata needed to emit package events. Callers should populate this from manifests, lockfiles, or registry metadata.

type PubSubConfig

type PubSubConfig struct {
	Enabled            bool   `yaml:"enabled"`
	ProjectID          string `yaml:"project_id"`          // Defaults to AILANG_CLOUD_PROJECT
	TopicPrefix        string `yaml:"topic_prefix"`        // Defaults to "ailang"
	LaptopSubscription bool   `yaml:"laptop_subscription"` // Create pull subscription for laptop
}

PubSubConfig holds Pub/Sub messaging configuration (M-PUBSUB).

type PubSubNotifier

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

PubSubNotifier wraps a Pub/Sub publisher for sending message notifications. It is created from config and provides a simple Notify() method for dual-write.

func NewPubSubNotifier

func NewPubSubNotifier(cfg *PubSubConfig) (*PubSubNotifier, error)

NewPubSubNotifier creates a notifier from the messaging config. Returns nil (not an error) if pubsub is not enabled.

func (*PubSubNotifier) Close

func (n *PubSubNotifier) Close()

Close releases Pub/Sub resources.

func (*PubSubNotifier) Notify

func (n *PubSubNotifier) Notify(ctx context.Context, msg *InboxMessage) error

Notify publishes a message notification to Pub/Sub. This should be called AFTER the message is durably stored in SQLite/Firestore.

type SearchHit

type SearchHit struct {
	Message   InboxMessage `json:"message"`
	Score     float64      `json:"score"`      // Similarity score (0.0-1.0)
	ScoreKind string       `json:"score_kind"` // "simhash", "embedding", or "envelope:<slot>"
}

SearchHit represents a search result with similarity score

type SearchOptions

type SearchOptions struct {
	Query         string   // Natural language query
	Threshold     float64  // Minimum similarity (0.0-1.0), default 0.70
	Limit         int      // Max results, default 20
	MaxScan       int      // Max messages to scan, default 1000
	Inbox         string   // Filter by inbox (optional)
	UseNeural     bool     // Use embedding search via Ollama
	Embedder      Embedder // Optional embedder instance (created if nil and UseNeural=true)
	EnvelopeSpace string   // Search within a specific envelope slot (e.g., "code", "intent")
}

SearchOptions configures semantic search parameters

type Store

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

Store provides CRUD operations for the collaboration hub database.

func NewStore

func NewStore(db *sql.DB) *Store

NewStore creates a new store instance from an existing database connection.

func OpenStore

func OpenStore(dbPath string) (*Store, error)

OpenStore opens or creates a SQLite database at the given path. If dbPath doesn't exist, creates a new database with schema. Also applies any pending schema migrations.

func (*Store) ApplyDuplicates

func (s *Store) ApplyDuplicates(groups []DuplicateGroup, runID string) error

ApplyDuplicates marks duplicate messages by setting dup_of and status

func (*Store) ApproveApproval

func (s *Store) ApproveApproval(approvalID, reviewedBy string, reviewNotes string, tokenDuration time.Duration) error

ApproveApproval approves an approval request and generates a capability token

func (*Store) ClaimMessage

func (s *Store) ClaimMessage(messageID, claimedBy string) error

ClaimMessage atomically claims a pending message for processing. Returns nil if the message was successfully claimed by this caller. Returns error if message doesn't exist or was already claimed by another agent.

func (*Store) CleanupInboxMessages

func (s *Store) CleanupInboxMessages(olderThan time.Duration, expiredOnly bool) (int64, error)

CleanupInboxMessages removes old messages

func (*Store) CleanupOldHistory

func (s *Store) CleanupOldHistory(retentionDays int) (int64, int64, error)

CleanupOldHistory removes history entries older than the retention period

func (*Store) ClearDuplicateMarker

func (s *Store) ClearDuplicateMarker(msgID string) error

ClearDuplicateMarker clears the dup_of field for a message (undo deduplication)

func (*Store) Close

func (s *Store) Close() error

Close closes the database connection.

func (*Store) CountInboxMessagesByStatus

func (s *Store) CountInboxMessagesByStatus(inbox string) (map[string]int64, error)

CountInboxMessagesByStatus returns counts of messages by status

func (*Store) CountPackageMessages

func (s *Store) CountPackageMessages(pkgName string) (map[string]int, error)

CountPackageMessages returns the count of messages per status for a package inbox.

func (*Store) CreateApproval

func (s *Store) CreateApproval(threadID, instanceID string, effectDelta *EffectDelta, proposal, impact string, estimatedCost float64) (*Approval, error)

CreateApproval creates a new approval request

func (*Store) CreateMessage

func (s *Store) CreateMessage(threadID, fromType, fromID, toType, toID, kind, content, metadataJSON string) (*Message, error)

CreateMessage creates a new message in a thread with automatic message_seq allocation. This function atomically increments threads.last_seq and assigns it to the new message.

func (*Store) CreateThread

func (s *Store) CreateThread(title, createdByType, createdByID, targetAgent string) (*Thread, error)

CreateThread creates a new thread in the database. targetAgent specifies which agent this conversation is with (optional).

func (*Store) CreateThreadWithWorkspace

func (s *Store) CreateThreadWithWorkspace(title, createdByType, createdByID, targetAgent, workspace string) (*Thread, error)

CreateThreadWithWorkspace creates a new thread with an optional workspace context. workspace is the source project/directory that originated this thread.

func (*Store) DB

func (s *Store) DB() *sql.DB

DB returns the underlying database connection for advanced operations.

func (*Store) DeduplicatePackageReports

func (s *Store) DeduplicatePackageReports(pkgName string) (int, error)

DeduplicatePackageReports finds and marks duplicate compatibility reports for the same package + version combination.

func (*Store) DeleteThread

func (s *Store) DeleteThread(threadID string) error

DeleteThread deletes a thread and all its messages.

func (*Store) FindDuplicates

func (s *Store) FindDuplicates(inbox string, threshold float64) ([]DuplicateGroup, error)

FindDuplicates identifies clusters of near-duplicate messages

func (*Store) FindMessageByPrefix

func (s *Store) FindMessageByPrefix(prefix string) (string, error)

FindMessageByPrefix resolves a short ID prefix to a full message ID using SQL. Returns error if no match or multiple matches (ambiguous prefix).

func (*Store) FindSimilar

func (s *Store) FindSimilar(msgID string, threshold float64, limit int) ([]SearchHit, error)

FindSimilar finds messages similar to a given message by ID

func (*Store) ForwardInboxMessage

func (s *Store) ForwardInboxMessage(id string, toInbox string) error

ForwardInboxMessage moves a message to a different inbox

func (*Store) GetActiveAgents

func (s *Store) GetActiveAgents() ([]ActiveAgent, error)

GetActiveAgents returns agents that have sent or received messages

func (*Store) GetAgentMetrics

func (s *Store) GetAgentMetrics(agentID string) (*AggregatedMetrics, error)

GetAgentMetrics returns metrics for a specific agent

func (*Store) GetAgentStats

func (s *Store) GetAgentStats(agentID string) (*AgentStats, error)

GetAgentStats returns detailed statistics for a single agent

func (*Store) GetAggregatedExecutionStats

func (s *Store) GetAggregatedExecutionStats() (*ExecutionStats, error)

GetAggregatedExecutionStats aggregates execution stats from all result messages

func (*Store) GetApproval

func (s *Store) GetApproval(approvalID string) (*Approval, error)

GetApproval retrieves an approval by ID

func (*Store) GetApprovalHistory

func (s *Store) GetApprovalHistory(threadID string, limit int) ([]ApprovalHistoryEntry, error)

GetApprovalHistory returns approval history entries, optionally filtered by thread

func (*Store) GetApprovalsByStatus

func (s *Store) GetApprovalsByStatus(status string, limit int) ([]Approval, error)

GetApprovalsByStatus retrieves approvals by status, including thread titles

func (*Store) GetDistinctWorkspaces

func (s *Store) GetDistinctWorkspaces() ([]string, error)

GetDistinctWorkspaces returns a list of all unique workspaces from threads

func (*Store) GetExecutionStatsByThread

func (s *Store) GetExecutionStatsByThread(threadID string) (*ExecutionStats, error)

GetExecutionStatsByThread aggregates execution stats for a specific thread

func (*Store) GetGlobalMetrics

func (s *Store) GetGlobalMetrics() (*AggregatedMetrics, error)

GetGlobalMetrics returns global aggregated metrics

func (*Store) GetHierarchy

func (s *Store) GetHierarchy() (*HierarchyResponse, error)

GetHierarchy returns the complete agent/thread hierarchy tree

func (*Store) GetInboxMessage

func (s *Store) GetInboxMessage(id string) (*InboxMessage, error)

GetInboxMessage returns a single message by ID (UUID or message_id)

func (*Store) GetInstanceHistory

func (s *Store) GetInstanceHistory(agentID string, limit int) ([]InstanceHistoryEntry, error)

GetInstanceHistory returns instance history entries, optionally filtered by agent

func (*Store) GetKnownAgents

func (s *Store) GetKnownAgents() ([]AgentInfo, error)

GetKnownAgents returns a list of known agent IDs from the database

func (*Store) GetMessageFlowEdges

func (s *Store) GetMessageFlowEdges() ([]MessageFlowEdge, error)

GetMessageFlowEdges returns edges derived from actual from_agent → to_inbox message flows

func (*Store) GetMessages

func (s *Store) GetMessages(toType, toID string, deliveryState string) ([]Message, error)

GetMessages retrieves messages for a specific recipient. If deliveryState is empty, returns all messages regardless of state.

func (*Store) GetMessagesFromSeq

func (s *Store) GetMessagesFromSeq(threadID string, fromSeq int, limit int) ([]Message, error)

GetMessagesFromSeq retrieves messages in a thread starting from a given sequence number. This enables cursor-based resumption for WebSocket subscriptions.

func (*Store) GetMetrics

func (s *Store) GetMetrics(scopeType, scopeID string) (*AggregatedMetrics, error)

GetMetrics returns aggregated metrics for a given scope

func (*Store) GetMetricsTrends

func (s *Store) GetMetricsTrends(scopeType, scopeID, period string, limit int) ([]map[string]interface{}, error)

GetMetricsTrends returns time-series metrics for a given scope and period

func (*Store) GetOrCreateThreadWithWorkspace

func (s *Store) GetOrCreateThreadWithWorkspace(title, createdByType, createdByID, targetAgent, workspace string) (*Thread, bool, error)

GetOrCreateThreadWithWorkspace returns an existing thread with the same title and target agent, or creates a new one if none exists. This prevents duplicate threads for the same task.

func (*Store) GetPackageMessageStats

func (s *Store) GetPackageMessageStats(pkgName string) (*PackageMessageStats, error)

GetPackageMessageStats returns statistics about package messages for a given package.

func (*Store) GetThread

func (s *Store) GetThread(threadID string) (*Thread, error)

GetThread retrieves a thread by ID.

func (*Store) GetThreadAggregateStats

func (s *Store) GetThreadAggregateStats() (*ThreadAggregateStats, error)

GetThreadAggregateStats returns aggregate statistics about threads

func (*Store) GetThreadByTitleAndAgent

func (s *Store) GetThreadByTitleAndAgent(title, targetAgent string) (*Thread, error)

GetThreadByTitleAndAgent finds a thread by title and target agent. Returns nil, nil if no matching thread is found.

func (*Store) GetThreadMetrics

func (s *Store) GetThreadMetrics(threadID string) (*AggregatedMetrics, error)

GetThreadMetrics returns metrics for a specific thread

func (*Store) GetThreadWorkspace

func (s *Store) GetThreadWorkspace(threadID string) (string, error)

GetThreadWorkspace returns the workspace path for a thread.

func (*Store) GetThreadsByStatus

func (s *Store) GetThreadsByStatus(status string, limit int) ([]Thread, error)

GetThreadsByStatus returns all threads matching a status filter If status is empty, returns all threads

func (*Store) GetThreadsFiltered

func (s *Store) GetThreadsFiltered(filter ThreadFilter) ([]Thread, error)

GetThreadsFiltered returns threads matching the given filter

func (*Store) InboxMessageExistsByGitHub

func (s *Store) InboxMessageExistsByGitHub(repo string, issueNumber int) (bool, error)

InboxMessageExistsByGitHub checks if a message with the given GitHub issue already exists

func (*Store) InboxMessageExistsByTitle

func (s *Store) InboxMessageExistsByTitle(inbox string, title string) (string, error)

InboxMessageExistsByTitle checks if a message with the same title already exists in the inbox Returns the existing message ID if found, or empty string if no duplicate

func (*Store) InsertInboxMessage

func (s *Store) InsertInboxMessage(msg *InboxMessage) error

InsertInboxMessage adds a new message to the inbox. For trace context propagation, use InsertInboxMessageWithContext instead.

func (*Store) InsertInboxMessageWithContext

func (s *Store) InsertInboxMessageWithContext(ctx context.Context, msg *InboxMessage) error

InsertInboxMessageWithContext adds a new message to the inbox with trace context propagation. Use this when you want the messages.send span to be a child of the caller's trace.

func (*Store) ListInboxMessages

func (s *Store) ListInboxMessages(opts InboxListOptions) ([]InboxMessage, error)

ListInboxMessages returns messages matching the given options

func (*Store) ListPackageInboxes

func (s *Store) ListPackageInboxes() ([]string, error)

ListPackageInboxes returns distinct package-scoped inboxes from the store.

func (*Store) ListWorkspaceInboxes

func (s *Store) ListWorkspaceInboxes() ([]string, error)

ListWorkspaceInboxes returns distinct workspace-scoped inboxes from the store.

func (*Store) MarkAllAsAcked

func (s *Store) MarkAllAsAcked(toType, toID string) (int64, error)

MarkAllAsAcked updates all pending/visible messages for a recipient to 'acked'.

func (*Store) MarkAllInboxMessagesRead

func (s *Store) MarkAllInboxMessagesRead(inbox string) (int64, error)

MarkAllInboxMessagesRead marks all messages in an inbox as read

func (*Store) MarkAsAcked

func (s *Store) MarkAsAcked(messageID string) error

MarkAsAcked updates a message's delivery_state to 'acked'.

func (*Store) MarkAsUnacked

func (s *Store) MarkAsUnacked(messageID string) error

MarkAsUnacked updates a message's delivery_state back to 'pending'.

func (*Store) MarkInboxMessageRead

func (s *Store) MarkInboxMessageRead(id string) error

MarkInboxMessageRead marks a message as read

func (*Store) MarkInboxMessageUnread

func (s *Store) MarkInboxMessageUnread(id string) error

MarkInboxMessageUnread marks a message as unread

func (*Store) NewThreadFilter

func (s *Store) NewThreadFilter(status, workspace string, limit int) ThreadFilter

NewThreadFilter creates a new ThreadFilter with the given parameters

func (*Store) RecordAgentInstance

func (s *Store) RecordAgentInstance(agentID, instanceID string) error

RecordAgentInstance creates an instance history entry for an agent run.

func (*Store) RecordApprovalHistory

func (s *Store) RecordApprovalHistory(approvalID, threadID, agentID, action, actor, proposal, impact string, estimatedCost *float64, capabilityToken string) error

RecordApprovalHistory adds an audit entry for an approval action

func (*Store) RecordInstanceEnd

func (s *Store) RecordInstanceEnd(instanceID string, exitCode int, totalTokens, totalCostCents, threadCount int) error

RecordInstanceEnd records the end of an agent instance with final stats

func (*Store) RecordInstanceStart

func (s *Store) RecordInstanceStart(agentID, instanceID string) error

RecordInstanceStart records the start of an agent instance

func (*Store) RecordMetrics

func (s *Store) RecordMetrics(threadID, agentID string, stats *MessageExecutionStats) error

RecordMetrics updates aggregated metrics when a result message is created This should be called after creating a result message

func (*Store) RegisterAgent

func (s *Store) RegisterAgent(agentID, label, status string) error

RegisterAgent registers or updates an agent in the collaboration hub. If the agent already exists, updates its status and last_active_at timestamp.

func (*Store) RejectApproval

func (s *Store) RejectApproval(approvalID, reviewedBy string, reviewNotes string) error

RejectApproval rejects an approval request

func (*Store) SearchByEnvelope

func (s *Store) SearchByEnvelope(opts SearchOptions) ([]SearchHit, error)

SearchByEnvelope finds messages by comparing the query embedding against a specific envelope slot across all messages. Returns results sorted by similarity score.

func (*Store) SemanticSearch

func (s *Store) SemanticSearch(opts SearchOptions) ([]SearchHit, error)

SemanticSearch finds messages similar to the query using SimHash or embeddings

func (*Store) SetThreadTargetAgent

func (s *Store) SetThreadTargetAgent(threadID, targetAgent string) error

SetThreadTargetAgent updates the target agent for a thread. This should be called when a task is re-routed to a different agent.

func (*Store) SetThreadWorkspace

func (s *Store) SetThreadWorkspace(threadID, workspace string) error

SetThreadWorkspace updates the workspace path for a thread. This persists the workspace so all messages in the thread use the same working directory.

func (*Store) Subscribe

func (s *Store) Subscribe(instanceID, threadID string) error

Subscribe creates or updates a subscription for an instance to a thread.

func (*Store) SupersedeOlderMessages

func (s *Store) SupersedeOlderMessages(pkgName, newVersion string) (int, error)

SupersedeOlderMessages marks older upgrade-available messages for the same package as superseded when a newer version is published.

func (*Store) UpdateAckSeq

func (s *Store) UpdateAckSeq(instanceID, threadID string, ackSeq int) error

UpdateAckSeq updates the last acknowledged sequence number for a subscription.

func (*Store) UpdateAgentStatus

func (s *Store) UpdateAgentStatus(agentID, status string) error

UpdateAgentStatus updates the status and last_active_at for an agent.

func (*Store) UpdateInboxMessageGitHub

func (s *Store) UpdateInboxMessageGitHub(messageID string, issueNumber int, repo string) error

UpdateInboxMessageGitHub updates the GitHub issue number and repo for a message

func (*Store) UpdateMessageEmbedding

func (s *Store) UpdateMessageEmbedding(msgID string, embedding []float32, model string) error

UpdateMessageEmbedding stores an embedding for a message

func (*Store) UpdateMessageEnvelope

func (s *Store) UpdateMessageEnvelope(msgID string, env *Envelope, overwrite bool) error

UpdateMessageEnvelope merges new envelope slots into a message's existing envelope. Existing slots are preserved unless overwrite is true.

func (*Store) UpdatePackageMessageStatus

func (s *Store) UpdatePackageMessageStatus(msgID, newStatus string) error

UpdatePackageMessageStatus updates the status of a package message, enforcing valid lifecycle transitions. The status is stored in the message payload's "status" field.

func (*Store) UpdateThreadTitle

func (s *Store) UpdateThreadTitle(threadID, title string) error

UpdateThreadTitle updates the title of a thread.

type Thread

type Thread struct {
	ID            string    `json:"id"`
	Title         string    `json:"title"`
	CreatedAt     time.Time `json:"created_at"`
	CreatedByType string    `json:"created_by_type"`
	CreatedByID   string    `json:"created_by_id"`
	Status        string    `json:"status"`
	ContextJSON   string    `json:"context_json,omitempty"`
	TargetAgent   string    `json:"target_agent,omitempty"` // Which agent this conversation is with
	Workspace     string    `json:"workspace,omitempty"`    // Working directory for this thread
	LastSeq       int       `json:"last_seq"`
	UpdatedAt     time.Time `json:"updated_at"`
}

Thread represents a conversation thread

type ThreadAggregateStats

type ThreadAggregateStats struct {
	TotalThreads int            `json:"total_threads"`
	ByStatus     map[string]int `json:"by_status"`
	ByWorkspace  map[string]int `json:"by_workspace"`
}

ThreadAggregateStats provides aggregate statistics about threads

type ThreadContext

type ThreadContext struct {
	TargetAgent string `json:"target_agent,omitempty"`
	Workspace   string `json:"workspace,omitempty"`
}

ThreadContext represents the parsed context_json for a thread

type ThreadFilter

type ThreadFilter struct {
	Status    string // Filter by status (active, paused, resolved, archived)
	Workspace string // Filter by workspace
	Limit     int    // Maximum number of results
}

ThreadFilter represents filter options for querying threads

type ThreadStats

type ThreadStats struct {
	ID               string `json:"id"`
	Title            string `json:"title"`
	UnreadCount      int    `json:"unread_count"`
	PendingApprovals int    `json:"pending_approvals"`
	RunningProcesses int    `json:"running_processes"`
	LastMessageAt    string `json:"last_message_at,omitempty"`
}

ThreadStats represents statistics for a thread within an agent

type TriageActionability

type TriageActionability string

TriageActionability classifies what action a package message requires.

const (
	TriageNoAction    TriageActionability = "no_action"
	TriageVerifyLocal TriageActionability = "verify_local"
	TriageMigrate     TriageActionability = "migrate"
	TriageEscalate    TriageActionability = "escalate"
	TriagePolicyBlock TriageActionability = "policy_block"
)

type TriageResult

type TriageResult struct {
	Action      TriageActionability `json:"action"`
	Reason      string              `json:"reason"`
	MessageKind PackageMessageKind  `json:"message_kind"`
	PackageName string              `json:"package_name"`
}

TriageResult holds the triage classification for a package message.

func TriagePackageMessage

func TriagePackageMessage(env *PackageMessageEnvelope) TriageResult

TriagePackageMessage classifies the actionability of a package message.

Jump to

Keyboard shortcuts

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