store

package
v0.3.0-beta.10 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: MIT Imports: 38 Imported by: 0

Documentation

Overview

Package store provides shared persistence types, validation, and helper primitives.

Index

Constants

View Source
const (
	// NetworkSurfaceThread stores a public thread conversation container.
	NetworkSurfaceThread = "thread"
	// NetworkSurfaceDirect stores a two-party direct-room conversation container.
	NetworkSurfaceDirect = "direct"

	// NetworkFanoutPolicyCapabilityMatch activates peers by declared capability.
	NetworkFanoutPolicyCapabilityMatch = "capability_match"
	// NetworkFanoutPolicyCoordinator activates the configured channel coordinator.
	NetworkFanoutPolicyCoordinator = "coordinator"
	// NetworkFanoutPolicyAllMembers activates every eligible local channel member.
	NetworkFanoutPolicyAllMembers = "all_members"

	// NetworkSubscriptionModeMute suppresses unmentioned matching traffic.
	NetworkSubscriptionModeMute = "mute"
	// NetworkSubscriptionModeFull preserves full prompt injection.
	NetworkSubscriptionModeFull = "full"

	// NetworkKindGreet stores a presence announcement.
	NetworkKindGreet = "greet"
	// NetworkKindWhois stores a peer identity request or response.
	NetworkKindWhois = "whois"
	// NetworkKindSay stores a text conversation message.
	NetworkKindSay = "say"
	// NetworkKindCapability stores a capability transfer message.
	NetworkKindCapability = "capability"
	// NetworkKindReceipt stores an admission receipt message.
	NetworkKindReceipt = "receipt"
	// NetworkKindTrace stores a work lifecycle trace message.
	NetworkKindTrace = "trace"

	// NetworkWorkStateSubmitted is the initial work state.
	NetworkWorkStateSubmitted = "submitted"
	// NetworkWorkStateWorking marks active work.
	NetworkWorkStateWorking = "working"
	// NetworkWorkStateNeedsInput marks blocked work awaiting input.
	NetworkWorkStateNeedsInput = "needs_input"
	// NetworkWorkStateCompleted marks successful terminal work.
	NetworkWorkStateCompleted = "completed"
	// NetworkWorkStateFailed marks failed terminal work.
	NetworkWorkStateFailed = "failed"
	// NetworkWorkStateCanceled marks canceled terminal work.
	NetworkWorkStateCanceled = "canceled"
)
View Source
const (
	NetworkConversationSortRecentActivity = "recent_activity"
	NetworkConversationSortCreated        = "created"
	NetworkConversationSortAlphabetical   = "alphabetical"

	NetworkConversationListDefaultLimit = 50
	NetworkConversationListMaxLimit     = 200
	NetworkMessageDefaultLimit          = 120
	NetworkMessageMaxLimit              = 200
)
View Source
const (
	SessionCreationSandboxNone = "none"
	SessionCreationSandboxRef  = "ref"
)
View Source
const (
	// SessionInputQueueModeQueue stores operator input to run after the active turn ends.
	SessionInputQueueModeQueue = "queue"
	// SessionInputQueueModeSteer stores operator guidance that replaces the active turn.
	SessionInputQueueModeSteer = "steer"
	// SessionInputQueueModeInterrupt stores replacement input after an explicit interrupt.
	SessionInputQueueModeInterrupt = "interrupt"
)
View Source
const (
	// SessionInputDeliveryNone reports commands that do not submit replacement input.
	SessionInputDeliveryNone = "none"
	// SessionInputDeliveryDirect streams input immediately on an idle session.
	SessionInputDeliveryDirect = "direct"
	// SessionInputDeliveryAfterTurn dispatches input after the active turn settles.
	SessionInputDeliveryAfterTurn = "after_turn"
	// SessionInputDeliveryInterruptThenPrompt interrupts the target turn before dispatch.
	SessionInputDeliveryInterruptThenPrompt = "interrupt_then_prompt"
)
View Source
const (
	SessionInputQueueStatusQueued      = "queued"
	SessionInputQueueStatusDispatching = "dispatching"
	SessionInputQueueStatusSent        = "sent"
	SessionInputQueueStatusFailed      = "failed"
	SessionInputQueueStatusCanceled    = "canceled"
)
View Source
const (
	// SessionStallStateDetected marks a session whose ACP activity timed out
	// while the subprocess still appeared alive during recovery.
	SessionStallStateDetected = "stalled"

	// SessionStallReasonActivityTimeout reports that no ACP activity was observed
	// within the configured supervision window.
	SessionStallReasonActivityTimeout = "activity_timeout"

	// SessionStallReasonPromptDeadlineExceeded reports that the prompt-level
	// supervision deadline elapsed before completion.
	SessionStallReasonPromptDeadlineExceeded = "prompt_deadline_exceeded"

	// SessionStallReasonProcessUnhealthy reports that subprocess health checks
	// failed while a prompt was still active.
	SessionStallReasonProcessUnhealthy = "process_unhealthy"
)
View Source
const (
	SessionPromptOperationPrompt = "prompt"
	SessionPromptOperationSteer  = "steer"

	SessionPromptAdmissionReserved          = "reserved"
	SessionPromptAdmissionDispatchCommitted = "dispatch_committed"
	SessionPromptAdmissionCompleted         = "completed"
	SessionPromptAdmissionIndeterminate     = "indeterminate"
)
View Source
const (
	SessionPromptResultStatusAccepted     = "accepted"
	SessionPromptResultStatusQueued       = "queued"
	SessionPromptResultStatusSteering     = "steering"
	SessionPromptResultStatusInterrupting = "interrupting"
	SessionPromptResultStatusCanceled     = "canceled"
)
View Source
const (
	// SessionDatabaseName is the filename for per-session event storage.
	SessionDatabaseName = "events.db"
	// GlobalDatabaseName is the filename for the global CompozyOS index database.
	GlobalDatabaseName = "compozy.db"
	// SessionMetaName is the filename for quick session metadata lookups.
	SessionMetaName = "meta.json"
)
View Source
const (
	TokenCostStatusActual    = "actual"
	TokenCostStatusEstimated = "estimated"
	TokenCostStatusIncluded  = "included"
	TokenCostStatusUnknown   = "unknown"

	TokenCostSourceAgentReported = "agent_reported"
	TokenCostSourceCatalogConfig = "catalog_config"
	TokenCostSourceModelsDev     = "models_dev"
	TokenCostSourceBuiltin       = "builtin"
	TokenCostSourceNone          = "none"
)
View Source
const (
	NetworkDispositionDeliver = "deliver"
	NetworkDispositionIgnore  = "ignore"
)
View Source
const (
	NetworkWakeTriggerNone    = ""
	NetworkWakeTriggerDirect  = "direct"
	NetworkWakeTriggerMention = "mention"
)
View Source
const (
	NetworkWakeSkipNotLive         = "not_live"
	NetworkWakeSkipNotEligible     = "not_eligible"
	NetworkWakeSkipNotAddressed    = "not_addressed"
	NetworkWakeSkipDuplicate       = "duplicate"
	NetworkWakeSkipDepthExceeded   = "depth_exceeded"
	NetworkWakeSkipCoalesced       = "coalesced"
	NetworkWakeSkipInFlight        = "in_flight"
	NetworkWakeSkipBudgetExhausted = "budget_exhausted"
	NetworkWakeSkipNetworkDisabled = "network_disabled"
)
View Source
const (
	NetworkWakeStateSucceeded        = "succeeded"
	NetworkWakeStateFailed           = "failed"
	NetworkWakeStateCanceled         = "canceled"
	NetworkWakeStateDeadlineExceeded = "deadline_exceeded"
)
View Source
const (
	NetworkWakeUsageActual      = "actual"
	NetworkWakeUsageUnavailable = "usage_unavailable"
)
View Source
const (
	NetworkWakeUsageReserved       = "reserved"
	DefaultNetworkUsageLimit       = 50
	MaxNetworkUsageLimit           = 200
	MaxJavaScriptSafeInteger int64 = 9_007_199_254_740_991
)
View Source
const (
	// DefaultSQLiteBusyTimeoutMS is the shared SQLite busy timeout in milliseconds.
	DefaultSQLiteBusyTimeoutMS = defaultBusyTimeoutMS
)
View Source
const SessionCreationProfileVersion = 1

Variables

View Source
var (
	// ErrLegacyDatabase reports a database created by the removed migration runner.
	ErrLegacyDatabase = errors.New("store: database was created by the removed pre-goose migration runner")
	// ErrSchemaBehind reports a database older than the running binary.
	ErrSchemaBehind = errors.New("store: database schema is behind this binary")
	// ErrSchemaAhead reports a database newer than the running binary.
	ErrSchemaAhead = errors.New("store: database schema is ahead of this binary")
	// ErrMigrationConnectionCapacity reports a pool too small for a non-transactional migration.
	ErrMigrationConnectionCapacity = errors.New("store: migration database connection capacity is insufficient")
)
View Source
var (
	// ErrNetworkConversationNotFound reports a missing network conversation container.
	ErrNetworkConversationNotFound = errors.New("store: network conversation not found")
	// ErrNetworkDirectRoomCollision reports a direct_id bound to another peer pair.
	ErrNetworkDirectRoomCollision = errors.New("store: network direct room collision")
	// ErrNetworkWorkContainerMismatch reports a work_id used outside its bound container.
	ErrNetworkWorkContainerMismatch = errors.New("store: network work container mismatch")
	// ErrNetworkWorkClosed reports a non-duplicate message for terminal work.
	ErrNetworkWorkClosed = errors.New("store: network work closed")
	// ErrNetworkCursorInvalid reports a malformed or query-mismatched network list cursor.
	ErrNetworkCursorInvalid = errors.New("store: network cursor invalid")
	// ErrNetworkChannelExists reports an attempted create for an existing workspace channel.
	ErrNetworkChannelExists = errors.New("store: network channel already exists")
)
View Source
var (
	// ErrSessionArchived reports an attempt to reactivate an archived session.
	ErrSessionArchived = errors.New("store: session is archived")
	// ErrSessionArchiveRequiresStopped reports an archive attempt for a live session.
	ErrSessionArchiveRequiresStopped = errors.New("store: session must be stopped before archiving")
)
View Source
var (
	// ErrSessionInputQueueFull reports that accepting an entry would exceed the configured capacity.
	ErrSessionInputQueueFull = errors.New("store: session input queue full")
	// ErrSessionInputQueueEntryNotFound reports that a queued input entry does not exist for a session.
	ErrSessionInputQueueEntryNotFound = errors.New("store: session input queue entry not found")
	// ErrSessionInputQueueEntryNotQueued reports that a pending input has already left the mutable queue state.
	ErrSessionInputQueueEntryNotQueued = errors.New("store: session input queue entry is not queued")
	// ErrSessionInputMutationConflict reports reuse of a mutation identity with different input.
	ErrSessionInputMutationConflict = errors.New("store: session input mutation identity conflict")
)
View Source
var (
	ErrSessionPromptAdmissionInProgress   = errors.New("store: session prompt admission is in progress")
	ErrSessionPromptIdempotencyConflict   = errors.New("store: session prompt idempotency conflict")
	ErrSessionPromptMessageConflict       = errors.New("store: session prompt message identity conflict")
	ErrSessionPromptDispatchIndeterminate = errors.New(
		"store: session prompt dispatch is indeterminate",
	)
)
View Source
var (
	// ErrClosed reports that a session database no longer accepts writes.
	ErrClosed = errors.New("store: session database closed")
	// ErrDrainTimeout reports that shutdown timed out before queued writes drained.
	ErrDrainTimeout = errors.New("store: writer drain timeout")
	// ErrSessionWorkspaceMismatch reports an attempt to reassign a durable session identity.
	ErrSessionWorkspaceMismatch = errors.New("store: session workspace owner does not match")
)
View Source
var (
	ErrConversationRewindTargetNotFound      = errors.New("store: conversation rewind target not found")
	ErrConversationRewindTargetInvalid       = errors.New("store: conversation rewind target is invalid")
	ErrConversationRewindFenceConflict       = errors.New("store: conversation rewind fence conflict")
	ErrConversationRewindIdempotencyConflict = errors.New("store: conversation rewind idempotency conflict")
)
View Source
var (
	ErrNetworkUsageQueryInvalid  = errors.New("network_usage_query_invalid")
	ErrNetworkUsageLimitInvalid  = errors.New("network_usage_limit_invalid")
	ErrNetworkUsageCursorInvalid = errors.New("network_usage_cursor_invalid")
	ErrNetworkUsageUnsafeInteger = errors.New("network_usage_unsafe_integer")
)
View Source
var (
	// ErrSessionNotFound reports that a persisted session row does not exist.
	ErrSessionNotFound = errors.New("store: session not found")
	// ErrSessionAttachLocked reports that another holder owns a live attach lease.
	ErrSessionAttachLocked = errors.New("store: session attach locked")
	// ErrSessionNotAttachable reports that a session is not eligible for attach/resume.
	ErrSessionNotAttachable = errors.New("store: session not attachable")
	// ErrSessionParticipationMismatch rejects a same-ID refresh with different immutable Network participation.
	ErrSessionParticipationMismatch = errors.New("store: session participation mismatch")
)
View Source
var ErrInvalidDeadEntity = errors.New("store: invalid dead entity")
View Source
var ErrSQLiteCorrupt = errors.New("store: sqlite database is corrupt")
View Source
var (
	// ErrSessionCreationIdentityMismatch rejects adoption of a same-ID session with different creation truth.
	ErrSessionCreationIdentityMismatch = errors.New("store: session creation identity mismatch")
)
View Source
var (
	// ErrSessionMetadataSchemaBehind reports metadata that predates the runtime binding contract.
	ErrSessionMetadataSchemaBehind = errors.New("store: session metadata schema is behind this binary")
)

Functions

func AppendLimit

func AppendLimit(query string, args []any, limit int) (string, []any)

AppendLimit appends a LIMIT clause when the limit is positive.

func AppendWhere

func AppendWhere(query string, where []string) string

AppendWhere appends a WHERE block when any clauses are present.

func Apply

func Apply(ctx context.Context, db *sql.DB, stream MigrationStream) error

Apply validates and applies all pending SQL migrations for stream.

func BuildClauses

func BuildClauses(input ...Clause) ([]string, []any)

BuildClauses compacts optional clauses into WHERE fragments and args.

func Checkpoint

func Checkpoint(ctx context.Context, db *sql.DB) error

Checkpoint truncates the WAL for an open SQLite database.

func CheckpointPassive

func CheckpointPassive(ctx context.Context, db *sql.DB) error

CheckpointPassive runs a non-truncating SQLite WAL checkpoint.

func ContextWithMutationCommitFence

func ContextWithMutationCommitFence(ctx context.Context, fence MutationCommitFence) context.Context

ContextWithMutationCommitFence carries a commit-time authorization check through service layers.

func EncodeNetworkUsageCursor

func EncodeNetworkUsageCursor(
	query NetworkUsageQuery,
	position NetworkUsageCursorPosition,
) (string, error)

EncodeNetworkUsageCursor binds one keyset position to the normalized filter set.

func EncodeSessionPermissionPolicy

func EncodeSessionPermissionPolicy(policy SessionPermissionPolicy) (string, error)

EncodeSessionPermissionPolicy marshals normalized permission policy metadata.

func EncodeSessionSpawnBudget

func EncodeSessionSpawnBudget(budget SessionSpawnBudget) (string, error)

EncodeSessionSpawnBudget marshals budget metadata for the global session catalog.

func ExecuteWrite

func ExecuteWrite(ctx context.Context, db *sql.DB, fn func(context.Context, *WriteTx) error) error

ExecuteWrite runs fn inside a BEGIN IMMEDIATE transaction with bounded SQLITE_BUSY retries.

func FormatNullableTimestamp

func FormatNullableTimestamp(value time.Time) string

FormatNullableTimestamp renders zero timestamps as empty strings for optional columns.

func FormatTimestamp

func FormatTimestamp(value time.Time) string

FormatTimestamp renders a timestamp in the canonical SQLite text layout.

func IsSQLiteBusy

func IsSQLiteBusy(err error) bool

IsSQLiteBusy reports whether err is a SQLite BUSY or LOCKED condition.

func LocalDay

func LocalDay(value time.Time) string

LocalDay formats one instant as the daemon-local calendar day bucket used by the daily usage rollup and the SQLite 'localtime' overview aggregates.

func LocalDayStart

func LocalDayStart(value time.Time, daysBack int) time.Time

LocalDayStart returns daemon-local midnight daysBack days before value's day.

func NetworkDirectRoomIdentity

func NetworkDirectRoomIdentity(
	workspaceID string,
	channel string,
	sessionA string,
	sessionB string,
) (string, string, string, error)

NetworkDirectRoomIdentity derives the stable direct-room id for one ordered session pair.

func NewID

func NewID(prefix string) (string, error)

NewID returns a random identifier with an optional prefix.

func NormalizeNetworkConversationListLimit

func NormalizeNetworkConversationListLimit(limit int) int

NormalizeNetworkConversationListLimit applies the bounded catalog contract.

func NormalizeNetworkConversationSort

func NormalizeNetworkConversationSort(sort string) string

NormalizeNetworkConversationSort applies the default recent-activity order.

func NormalizeNetworkDirectRoomSessions

func NormalizeNetworkDirectRoomSessions(sessionA string, sessionB string) (string, string, error)

NormalizeNetworkDirectRoomSessions validates and orders a two-party room pair.

func NormalizeNetworkFanoutPolicy

func NormalizeNetworkFanoutPolicy(policy string) string

NormalizeNetworkFanoutPolicy applies the default channel activation policy.

func NormalizeNetworkMessageLimit

func NormalizeNetworkMessageLimit(limit int) int

NormalizeNetworkMessageLimit applies the bounded message-history contract.

func NormalizeNetworkPeerIDs

func NormalizeNetworkPeerIDs(values []string, field string) ([]string, error)

NormalizeNetworkPeerIDs trims, validates, deduplicates, and sorts peer ids.

func NormalizeNetworkUsageQuery

func NormalizeNetworkUsageQuery(
	query NetworkUsageQuery,
) (NetworkUsageQuery, *NetworkUsageCursorPosition, error)

NormalizeNetworkUsageQuery validates filters, applies defaults, and decodes the cursor.

func NormalizeSQLiteIdentifier

func NormalizeSQLiteIdentifier(value string) (string, error)

NormalizeSQLiteIdentifier validates a SQLite identifier for use in helper queries.

func NormalizeSessionType

func NormalizeSessionType(value string) string

NormalizeSessionType applies the default session type when empty.

func NullFloat64

func NullFloat64(value sql.NullFloat64) *float64

NullFloat64 converts sql.NullFloat64 into a pointer.

func NullInt64

func NullInt64(value sql.NullInt64) *int64

NullInt64 converts sql.NullInt64 into a pointer.

func NullString

func NullString(value sql.NullString) *string

NullString converts sql.NullString into a trimmed string pointer.

func NullableFloat64

func NullableFloat64(value *float64) any

NullableFloat64 maps nil pointers to SQL NULL.

func NullableInt64

func NullableInt64(value *int64) any

NullableInt64 maps nil pointers to SQL NULL.

func NullableString

func NullableString(value string) any

NullableString maps blank strings to SQL NULL.

func NullableStringPointer

func NullableStringPointer(value *string) any

NullableStringPointer maps nil or blank string pointers to SQL NULL.

func OpenSQLiteDatabase

func OpenSQLiteDatabase(
	ctx context.Context,
	path string,
	initialize func(context.Context, *sql.DB) error,
) (*sql.DB, error)

OpenSQLiteDatabase opens a SQLite database and applies shared configuration.

func OpenSQLiteDatabaseWithPragmas

func OpenSQLiteDatabaseWithPragmas(
	ctx context.Context,
	path string,
	pragmas []string,
	initialize func(context.Context, *sql.DB) error,
) (*sql.DB, error)

OpenSQLiteDatabaseWithPragmas opens a SQLite database with additional driver-level pragmas.

func ParseNullableTimestamp

func ParseNullableTimestamp(value string) (*time.Time, error)

ParseNullableTimestamp parses optional canonical timestamps.

func ParseTimestamp

func ParseTimestamp(value string) (time.Time, error)

ParseTimestamp parses the canonical SQLite text timestamp.

func RequireCurrent

func RequireCurrent(ctx context.Context, db *sql.DB, stream MigrationStream) error

RequireCurrent validates that a migration stream is exactly at the embedded head without creating tables or applying migrations.

func SQLNullString

func SQLNullString(value string) sql.NullString

SQLNullString maps an optional string to a canonical trimmed sql.NullString.

func SQLNullStringPointer

func SQLNullStringPointer(value *string) sql.NullString

SQLNullStringPointer maps a nil or blank string pointer to an invalid sql.NullString.

func SessionActivityIdleSeconds

func SessionActivityIdleSeconds(meta *SessionActivityMeta, now time.Time) int64

SessionActivityIdleSeconds reports the age of the last recorded runtime activity relative to now.

func SessionAdvertisedCommandsEqual

func SessionAdvertisedCommandsEqual(left SessionAdvertisedCommand, right SessionAdvertisedCommand) bool

SessionAdvertisedCommandsEqual compares two typed command values.

func SessionDBFile

func SessionDBFile(sessionDir string) string

SessionDBFile returns the canonical events database path for a session directory.

func SessionMetaFile

func SessionMetaFile(sessionDir string) string

SessionMetaFile returns the canonical metadata file path for a session directory.

func SessionRuntimeFailurePointer

func SessionRuntimeFailurePointer(value string) *string

SessionRuntimeFailurePointer normalizes an optional persisted runtime diagnostic.

func SessionRuntimeFailureValue

func SessionRuntimeFailureValue(value *string) string

SessionRuntimeFailureValue returns the normalized runtime diagnostic value.

func SqliteFilePath

func SqliteFilePath(path string) string

SqliteFilePath normalizes a filesystem path for use as a file:// URL Path in a SQLite DSN. url.URL requires an absolute path starting with "/" to produce the three-slash form "file:///...". On Windows, filepath.IsAbs returns true for drive-letter paths (e.g. "C:\..."), but filepath.ToSlash yields "C:/..." which url.URL serializes as "file://C:/..." — the SQLite URI parser then interprets "C:" as the network authority rather than a drive letter (failing with "invalid uri authority: C:"). Prepend "/" only for absolute paths that lack one; relative paths are left unchanged so callers that pass relative paths are unaffected. Exported so sibling packages (e.g. internal/store/sessiondb) build SQLite DSNs through the same canonical normalization instead of duplicating the logic.

func UpsertLoopOutputBlob

func UpsertLoopOutputBlob(
	ctx context.Context,
	exec LoopOutputBlobExecutor,
	outputRef string,
	payload []byte,
	at time.Time,
) error

UpsertLoopOutputBlob persists a content-addressed loop output and refreshes its usage timestamp.

func ValidFailureKind

func ValidFailureKind(kind FailureKind) bool

ValidFailureKind reports whether kind is a supported failure enum member.

func ValidStopReason

func ValidStopReason(r StopReason) bool

ValidStopReason reports whether r is a supported stop reason enum member.

func ValidateChildSessionToolSubset

func ValidateChildSessionToolSubset(parent SessionPermissionPolicy, child SessionPermissionPolicy) error

ValidateChildSessionToolSubset ensures child concrete tool atoms cannot exceed the parent.

func ValidateJavaScriptSafeInteger

func ValidateJavaScriptSafeInteger(field string, value int64) error

ValidateJavaScriptSafeInteger rejects counters that cannot round-trip through JSON numbers.

func ValidateNetworkChannelFanoutConfiguration

func ValidateNetworkChannelFanoutConfiguration(policy string, coordinatorPeerID string) error

ValidateNetworkChannelFanoutConfiguration checks policy and coordinator coupling.

func ValidateNetworkFanoutPolicy

func ValidateNetworkFanoutPolicy(policy string) error

ValidateNetworkFanoutPolicy checks one channel activation policy value.

func ValidateNetworkSubscriptionMode

func ValidateNetworkSubscriptionMode(mode string) error

ValidateNetworkSubscriptionMode checks one delivery preference mode.

func ValidateSessionLineage

func ValidateSessionLineage(sessionID string, lineage *SessionLineage) error

ValidateSessionLineage ensures lineage is structurally usable by spawn policy enforcement.

func ValidateSessionRuntime

func ValidateSessionRuntime(status SessionRuntimeStatus, transition SessionRuntimeTransition, failure string) error

ValidateSessionRuntime validates one durable runtime binding projection.

func ValidateSessionRuntimeSelection

func ValidateSessionRuntimeSelection(selection *SessionRuntimeSelection, revision int64) error

ValidateSessionRuntimeSelection ensures a persisted preference and revision are well formed.

func ValidateSessionRuntimeSelectionState

func ValidateSessionRuntimeSelectionState(state *SessionRuntimeSelectionState) error

ValidateSessionRuntimeSelectionState ensures persisted selection state is well formed.

func WithMigrationLogger

func WithMigrationLogger(ctx context.Context, logger *slog.Logger) context.Context

WithMigrationLogger overrides migration observability for operations using ctx.

func WriteSessionMeta

func WriteSessionMeta(path string, meta SessionMeta) error

WriteSessionMeta writes the metadata file atomically via temp file and rename.

Types

type AcceptNetworkMessageRequest

type AcceptNetworkMessageRequest struct {
	Message      NetworkConversationMessage
	Dispositions []NetworkMessageDisposition
	Admissions   []NetworkWakeAdmissionInput
}

AcceptNetworkMessageRequest is the complete input to the atomic acceptance boundary.

type AcceptNetworkMessageResult

type AcceptNetworkMessageResult struct {
	AcceptanceSeq     int64
	AvailabilityEpoch int64
	Duplicate         bool
	Conversation      NetworkConversationWriteResult
	Dispositions      []NetworkMessageDisposition
	Admitted          []WakeReservation
	Skipped           []WakeSkip
	Notify            []CommittedNetworkNotification
}

AcceptNetworkMessageResult reports the exact durable acceptance outcome.

type Clause

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

Clause represents an optional SQL filter clause plus its bound argument.

func Int64Clause

func Int64Clause(column string, op string, value int64) Clause

Int64Clause builds a numeric comparison clause when the value is positive.

func NotStringClause

func NotStringClause(column string, value string) Clause

NotStringClause builds an inequality clause when the value is non-empty.

func OpaqueStringClause

func OpaqueStringClause(column string, value string) Clause

OpaqueStringClause builds an equality clause without rewriting the value.

func StringClause

func StringClause(column string, value string) Clause

StringClause builds an equality clause when the value is non-empty.

func TimeClause

func TimeClause(column string, op string, value time.Time) Clause

TimeClause builds a timestamp comparison clause when the value is non-zero.

type CommittedNetworkNotification

type CommittedNetworkNotification struct {
	WorkspaceID        string
	RecipientSessionID string
	TaskRunID          string
	AcceptanceSeq      int64
	ReadyAt            time.Time
}

CommittedNetworkNotification is safe to dispatch only after acceptance commits.

type ConversationRewindReader

type ConversationRewindReader interface {
	ConversationRewindTarget(context.Context, string) (ConversationRewindTarget, error)
	ConversationRewindState(context.Context) (ConversationRewindState, bool, error)
	ConversationRewindReceipt(context.Context, string, string) (ConversationRewindResult, bool, error)
}

type ConversationRewindRequest

type ConversationRewindRequest struct {
	MessageID           string
	IdempotencyKey      string
	RequestHash         string
	ExpectedGeneration  int64
	ExpectedMaxSequence int64
	TranscriptEpoch     int64
	BaselineJSON        string
}

func (ConversationRewindRequest) Validate

func (r ConversationRewindRequest) Validate() error

type ConversationRewindResult

type ConversationRewindResult struct {
	IdempotencyKey       string
	TargetMessageID      string
	ArchivedFromSequence int64
	ArchivedToSequence   int64
	ArchivedEventCount   int64
	Generation           int64
	MaxSequence          int64
	TranscriptEpoch      int64
	DraftText            string
	CreatedAt            time.Time
	Replayed             bool
}

type ConversationRewindState

type ConversationRewindState struct {
	TargetMessageID        string
	CoveredThroughSequence int64
	MessagesJSON           string
	UpdatedAt              time.Time
}

type ConversationRewindTarget

type ConversationRewindTarget struct {
	MessageID     string
	StartSequence int64
	DraftText     string
	Generation    int64
	MaxSequence   int64
}

type ConversationRewinder

type ConversationRewinder interface {
	ConversationRewindReader
	RewindConversation(context.Context, ConversationRewindRequest) (ConversationRewindResult, error)
}

type DeadEntity

type DeadEntity struct {
	DeadEntityKey
	Reason   string
	MarkedAt time.Time
}

DeadEntity is one durable confirmed-dead external runtime.

func (DeadEntity) Normalize

func (e DeadEntity) Normalize() DeadEntity

Normalize returns the canonical durable row.

func (DeadEntity) Validate

func (e DeadEntity) Validate() error

Validate ensures the durable row is complete and bounded.

type DeadEntityKey

type DeadEntityKey struct {
	WorkspaceID string
	Kind        DeadEntityKind
	EntityID    string
}

DeadEntityKey identifies one workspace-scoped external runtime.

func (DeadEntityKey) Normalize

func (k DeadEntityKey) Normalize() DeadEntityKey

Normalize returns the canonical dead-entity key.

func (DeadEntityKey) Validate

func (k DeadEntityKey) Validate() error

Validate ensures the key is workspace-scoped and uses a closed kind.

type DeadEntityKind

type DeadEntityKind string

DeadEntityKind identifies one workspace-scoped external runtime family.

const (
	DeadEntityKindExtension  DeadEntityKind = "extension"
	DeadEntityKindBridge     DeadEntityKind = "bridge"
	DeadEntityKindMCPSidecar DeadEntityKind = "mcp_sidecar"
	DeadEntityKindLoopTarget DeadEntityKind = "loop_target"
)

type DeadEntityStore

type DeadEntityStore interface {
	MarkDeadEntity(ctx context.Context, entity DeadEntity) error
	ClearDeadEntity(ctx context.Context, workspaceID string, kind DeadEntityKind, entityID string) error
	FindDeadEntity(
		ctx context.Context,
		workspaceID string,
		kind DeadEntityKind,
		entityID string,
	) (DeadEntity, bool, error)
	ListDeadEntities(ctx context.Context, workspaceID string) ([]DeadEntity, error)
}

DeadEntityStore manages workspace-scoped confirmed-dead external runtimes.

type EventArchiveFilter

type EventArchiveFilter string

EventArchiveFilter selects rows by their non-destructive archive state.

const (
	// EventArchiveAll keeps archived and unarchived rows visible for history queries.
	EventArchiveAll EventArchiveFilter = ""
	// EventArchiveUnarchived selects rows eligible for transcript replay.
	EventArchiveUnarchived EventArchiveFilter = "unarchived"
	// EventArchiveArchived selects rows retained only for forensic history.
	EventArchiveArchived EventArchiveFilter = "archived"
)

func (EventArchiveFilter) Validate

func (f EventArchiveFilter) Validate() error

Validate rejects unsupported archive filters.

type EventArchiveRequest

type EventArchiveRequest struct {
	FromSequence int64
	ToSequence   int64
}

EventArchiveRequest identifies one closed event sequence range to archive.

func (EventArchiveRequest) Validate

func (r EventArchiveRequest) Validate() error

Validate ensures an archive request names one positive ordered range.

type EventArchiveResult

type EventArchiveResult struct {
	FromSequence  int64
	ToSequence    int64
	ArchivedCount int64
}

EventArchiveResult reports the idempotent mutation applied to one range.

type EventArchiver

type EventArchiver interface {
	ArchiveEvents(ctx context.Context, request EventArchiveRequest) (EventArchiveResult, error)
}

EventArchiver marks closed replay spans without deleting their forensic rows.

type EventCloser

type EventCloser interface {
	Close(ctx context.Context) error
}

EventCloser releases a session event-store handle.

type EventCorrelation

type EventCorrelation struct {
	TaskID               string     `json:"task_id,omitempty"`
	RunID                string     `json:"run_id,omitempty"`
	WorkflowID           string     `json:"workflow_id,omitempty"`
	ClaimTokenHash       string     `json:"claim_token_hash,omitempty"`
	LeaseUntil           *time.Time `json:"lease_until,omitempty"`
	CoordinatorSessionID string     `json:"coordinator_session_id,omitempty"`
	SchedulerReason      string     `json:"scheduler_reason,omitempty"`
	HookEvent            string     `json:"hook_event,omitempty"`
	HookName             string     `json:"hook_name,omitempty"`
	ActorKind            string     `json:"actor_kind,omitempty"`
	ActorID              string     `json:"actor_id,omitempty"`
	ReleaseReason        string     `json:"release_reason,omitempty"`
}

EventCorrelation carries the canonical cross-surface correlation keys for session and observability events.

func (EventCorrelation) IsZero

func (c EventCorrelation) IsZero() bool

IsZero reports whether the correlation payload carries any fields.

func (EventCorrelation) Normalize

func (c EventCorrelation) Normalize() EventCorrelation

Normalize trims string fields and canonicalizes timestamps.

type EventHourWeekdayBucket

type EventHourWeekdayBucket struct {
	Weekday int
	Hour    int
	Events  int
}

EventHourWeekdayBucket is one hour-by-weekday event count; weekday 0 is Sunday.

type EventMetadata

type EventMetadata struct {
	ID        string
	SessionID string
	Sequence  int64
	TurnID    string
	Type      string
	AgentName string
	Timestamp time.Time
}

EventMetadata is the content-excluded projection of a durable session event.

type EventMetadataReadCloser

type EventMetadataReadCloser interface {
	EventMetadataReader
	EventCloser
}

EventMetadataReadCloser owns a read-only metadata handle for one session.

type EventMetadataReader

type EventMetadataReader interface {
	MaxEventSequence(ctx context.Context) (int64, error)
	QueryEventMetadata(ctx context.Context, query EventQuery) ([]EventMetadata, error)
}

EventMetadataReader reads the sequence and projection needed by replay cursors.

type EventQuery

type EventQuery struct {
	Type           string
	AgentName      string
	TurnID         string
	Since          time.Time
	Limit          int
	AfterSequence  int64
	BeforeSequence int64
	Archive        EventArchiveFilter
}

EventQuery filters per-session events while preserving follow-friendly ordering.

func (EventQuery) Validate

func (q EventQuery) Validate() error

Validate ensures the query is internally consistent.

type EventReadCloser

type EventReadCloser interface {
	EventReader
	EventCloser
}

EventReadCloser is the complete contract exposed by read-only event stores.

type EventReader

type EventReader interface {
	Query(ctx context.Context, query EventQuery) ([]SessionEvent, error)
	History(ctx context.Context, query EventQuery) ([]TurnHistory, error)
	ListTokenUsage(ctx context.Context) ([]TokenUsage, error)
}

EventReader reads durable session events and turn history.

type EventRecorder

type EventRecorder interface {
	EventReadCloser
	EventWriter
}

EventRecorder is the complete mutable per-session event-store contract.

type EventSummary

type EventSummary struct {
	ID          string
	SessionID   string
	WorkspaceID string
	Sequence    int64
	Type        string
	AgentName   string
	Provider    string
	Outcome     string
	Content     json.RawMessage
	EventCorrelation
	ParentSessionID string
	RootSessionID   string
	SpawnDepth      int
	Summary         string
	Timestamp       time.Time
}

func (EventSummary) Validate

func (s EventSummary) Validate() error

Validate ensures the summary contains the required identifying fields.

type EventSummaryBatchWriter

type EventSummaryBatchWriter interface {
	WriteEventSummaries(ctx context.Context, summaries []EventSummary) error
}

EventSummaryBatchWriter persists related summaries atomically.

type EventSummaryQuery

type EventSummaryQuery struct {
	SessionID     string
	WorkspaceID   string
	AgentName     string
	Type          string
	TaskID        string
	RunID         string
	ActorKind     string
	ActorID       string
	Provider      string
	Outcome       string
	Component     string
	ErrorOnly     bool
	AfterSequence int64
	Since         time.Time
	Limit         int
}

EventSummaryQuery filters global event summary queries.

func (EventSummaryQuery) Validate

func (q EventSummaryQuery) Validate() error

Validate ensures the query uses sane bounds.

type EventSummaryStore

type EventSummaryStore interface {
	WriteEventSummary(ctx context.Context, summary EventSummary) error
	ListEventSummaries(ctx context.Context, query EventSummaryQuery) ([]EventSummary, error)
}

EventSummaryStore manages persisted observability event summaries.

type EventWriter

type EventWriter interface {
	Record(ctx context.Context, event SessionEvent) error
	RecordTokenUsage(ctx context.Context, usage TokenUsage) error
}

EventWriter appends session events and token usage.

type FailureKind

type FailureKind string

FailureKind classifies ACP/session lifecycle failures at the source and keeps them transport-stable across storage, API, SSE, and CLI surfaces.

const (
	FailureStartup      FailureKind = "startup_failure"
	FailureHandshake    FailureKind = "handshake_failure"
	FailureLoad         FailureKind = "load_session_failure"
	FailureProtocol     FailureKind = "protocol_failure"
	FailurePrompt       FailureKind = "prompt_failure"
	FailureCanceled     FailureKind = "cancellation"
	FailurePermission   FailureKind = "permission_failure"
	FailureProviderAuth FailureKind = "provider_auth_failure"
	FailureProcess      FailureKind = "process_exit"
	FailureTransport    FailureKind = "transport_failure"
	FailureTimeout      FailureKind = "timeout"
	FailureUnknown      FailureKind = "unknown_failure"
)

type HookDispatchCounts

type HookDispatchCounts struct {
	Runs     int
	Failures int
}

HookDispatchCounts summarizes hook dispatch completions inside a window.

type HookRunQuery

type HookRunQuery struct {
	SessionID string
	Event     string
	Outcome   hookspkg.HookRunOutcome
	Since     time.Time
	Limit     int
}

HookRunQuery filters persisted per-session hook run records.

func (HookRunQuery) Validate

func (q HookRunQuery) Validate() error

Validate ensures the query uses sane bounds.

type LongestSessionSample

type LongestSessionSample struct {
	SessionID      string
	AgentName      string
	StartedAt      time.Time
	RuntimeSeconds int64
}

LongestSessionSample is the longest-running user session inside a window.

type LoopOutputBlobExecutor

type LoopOutputBlobExecutor interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}

LoopOutputBlobExecutor is the SQL surface required to persist one loop output blob.

type MarketplaceCatalogEntry

type MarketplaceCatalogEntry struct {
	Kind         string
	EntryID      string
	Name         string
	Description  string
	Version      string
	PublishedAt  string
	UpdatedAt    string
	DigestSHA256 string
	Tier         string
	InstallSlug  string
	PayloadJSON  string
	FetchedAt    string
}

MarketplaceCatalogEntry is the storage-boundary projection for one curated entry.

type MarketplaceCatalogReplacement

type MarketplaceCatalogReplacement struct {
	Kind            string
	ManifestVersion int64
	GeneratedAt     string
	FetchedAt       string
	Entries         []MarketplaceCatalogEntry
}

MarketplaceCatalogReplacement is one validated, atomic per-kind projection.

type MarketplaceCatalogRepository

type MarketplaceCatalogRepository interface {
	ReplaceMarketplaceCatalog(context.Context, MarketplaceCatalogReplacement) error
	MarkMarketplaceCatalogStale(context.Context, string, string) error
	ListMarketplaceCatalogEntries(context.Context, string, int64) ([]MarketplaceCatalogEntry, error)
	GetMarketplaceCatalogEntry(context.Context, string, string) (MarketplaceCatalogEntry, error)
	GetMarketplaceExtensionByInstallSlug(context.Context, string, string) (MarketplaceCatalogEntry, error)
	ListMarketplaceSkillsByInstallSlugs(context.Context, []string) ([]MarketplaceCatalogEntry, error)
	GetMarketplaceCatalogState(context.Context, string) (MarketplaceCatalogState, error)
}

MarketplaceCatalogRepository owns the global SQLite projection and its transactions.

type MarketplaceCatalogState

type MarketplaceCatalogState struct {
	Kind            string
	ManifestVersion int64
	GeneratedAt     string
	FetchedAt       string
	Stale           bool
	LastError       string
	EntryCount      int64
}

MarketplaceCatalogState is the storage-boundary freshness record for one kind.

type MigrationBootstrap

type MigrationBootstrap struct {
	FS           fs.FS
	MigrationDir string
	SchemaSource string
	SeedSource   string
	// Initialize writes instance-specific state after schema and seed SQL and
	// before migration versions are recorded, all in the same transaction.
	Initialize func(context.Context, *sql.Tx) error
}

MigrationBootstrap describes the declarative schema for a migration head.

type MigrationStream

type MigrationStream struct {
	Name         string
	FS           fs.FS
	Dir          string
	VersionTable string
	LegacyTables []string
	Bootstrap    *MigrationBootstrap
}

MigrationStream describes one independently versioned embedded schema.

type MutationCommitFence

type MutationCommitFence func(context.Context) error

MutationCommitFence revalidates an authenticated mutation at its commit boundary.

type NetworkAcceptanceStore

type NetworkAcceptanceStore interface {
	AcceptNetworkMessage(
		ctx context.Context,
		req AcceptNetworkMessageRequest,
	) (AcceptNetworkMessageResult, error)
}

NetworkAcceptanceStore owns atomic message acceptance and wake accounting.

type NetworkAuditEntry

type NetworkAuditEntry struct {
	ID          string
	SessionID   string
	Direction   string
	Kind        string
	WorkspaceID string
	Channel     string
	Surface     string
	ThreadID    string
	DirectID    string
	WorkID      string
	PeerFrom    string
	PeerTo      string
	MessageID   string
	Reason      string
	Size        int
	Timestamp   time.Time
}

func (NetworkAuditEntry) Validate

func (e NetworkAuditEntry) Validate() error

Validate ensures the network audit entry is complete and internally consistent.

type NetworkAuditQuery

type NetworkAuditQuery struct {
	SessionID   string
	WorkspaceID string
	// Global explicitly allows daemon-admin aggregate callers to scan audit rows
	// across workspaces. Workspace-scoped API surfaces must leave this false.
	Global    bool
	Direction string
	Kind      string
	Channel   string
	Surface   string
	ThreadID  string
	DirectID  string
	WorkID    string
	MessageID string
	Since     time.Time
	Limit     int
}

NetworkAuditQuery filters network audit lookups.

func (NetworkAuditQuery) Validate

func (q NetworkAuditQuery) Validate() error

Validate ensures the query uses sane bounds.

type NetworkAuditStore

type NetworkAuditStore interface {
	WriteNetworkAudit(ctx context.Context, entry NetworkAuditEntry) error
	ListNetworkAudit(ctx context.Context, query NetworkAuditQuery) ([]NetworkAuditEntry, error)
}

NetworkAuditStore manages network message audit entries.

type NetworkAvailability

type NetworkAvailability struct {
	Enabled   bool
	Epoch     int64
	UpdatedAt time.Time
	UpdatedBy string
}

NetworkAvailability is the persisted admission kill-switch state.

type NetworkAvailabilityStore

type NetworkAvailabilityStore interface {
	GetNetworkAvailability(ctx context.Context) (NetworkAvailability, error)
	SetNetworkAvailability(
		ctx context.Context,
		enabled bool,
		updatedBy string,
	) (NetworkAvailability, error)
}

NetworkAvailabilityStore serializes availability changes with network admission writes.

type NetworkBudgetUsage

type NetworkBudgetUsage struct {
	OwnerKey         string
	WakesUsed        int
	WallTimeUsed     time.Duration
	InputTokensUsed  int64
	OutputTokensUsed int64
	ExhaustedReason  string
	UpdatedAt        time.Time
}

NetworkBudgetUsage reports the durable consumption counters for one participation owner.

type NetworkCausationStore

type NetworkCausationStore interface {
	ResolveNetworkCausation(
		ctx context.Context,
		workspaceID string,
		causationID string,
	) (rootID string, depth int, found bool, err error)
}

NetworkCausationStore resolves durable wake ancestry for bounded reply chains.

type NetworkChannelEntry

type NetworkChannelEntry struct {
	Channel           string
	WorkspaceID       string
	Purpose           string
	FanoutPolicy      string
	CoordinatorPeerID string
	CreatedBy         string
	CreatedAt         time.Time
	UpdatedAt         time.Time
}

NetworkChannelEntry stores durable channel metadata for the operator-facing network workspace.

func (NetworkChannelEntry) Validate

func (e NetworkChannelEntry) Validate() error

Validate ensures the persisted channel metadata is complete.

type NetworkChannelKindCount

type NetworkChannelKindCount struct {
	WorkspaceID string
	Channel     string
	Kind        string
	Count       int
}

NetworkChannelKindCount is one materialized public-message kind total.

type NetworkChannelPatch

type NetworkChannelPatch struct {
	Purpose           *string
	FanoutPolicy      *string
	CoordinatorPeerID *string
	UpdatedAt         time.Time
}

NetworkChannelPatch describes a partial channel metadata update. Nil fields are left unchanged.

func (NetworkChannelPatch) Apply

Apply returns the entry that would result from applying the patch.

func (NetworkChannelPatch) HasChanges

func (p NetworkChannelPatch) HasChanges() bool

HasChanges reports whether the patch includes at least one mutable field.

type NetworkChannelProjection

type NetworkChannelProjection struct {
	WorkspaceID                string
	Channel                    string
	MessageCount               int
	PresenceCount              int
	HistoricalParticipantCount int
	LastActivityAt             *time.Time
	LastActivitySequence       int64
	LastPresenceAt             *time.Time
	LastPresenceSequence       int64
	LastMessageSequence        int64
	LastMessagePreview         string
}

NetworkChannelProjection is the bounded read model for one channel's persisted timeline activity.

func (NetworkChannelProjection) Validate

func (p NetworkChannelProjection) Validate() error

Validate ensures the projection remains workspace-qualified and additive.

type NetworkChannelProjectionQuery

type NetworkChannelProjectionQuery struct {
	WorkspaceID string
	Channel     string
	Limit       int
}

NetworkChannelProjectionQuery scopes bounded projection reads.

func (NetworkChannelProjectionQuery) Validate

func (q NetworkChannelProjectionQuery) Validate() error

Validate ensures projection reads cannot cross a workspace.

type NetworkChannelProjectionStore

type NetworkChannelProjectionStore interface {
	ListNetworkChannelProjections(
		ctx context.Context,
		query NetworkChannelProjectionQuery,
	) ([]NetworkChannelProjection, error)
	ListNetworkChannelKindCounts(
		ctx context.Context,
		ref NetworkChannelRef,
	) ([]NetworkChannelKindCount, error)
}

NetworkChannelProjectionStore reads materialized channel timeline totals.

type NetworkChannelQuery

type NetworkChannelQuery struct {
	Channel     string
	WorkspaceID string
	Limit       int
}

NetworkChannelQuery filters persisted network channel metadata lookups.

func (NetworkChannelQuery) Validate

func (q NetworkChannelQuery) Validate() error

Validate ensures the query uses sane bounds.

type NetworkChannelRef

type NetworkChannelRef struct {
	WorkspaceID string
	Channel     string
}

NetworkChannelRef identifies one workspace-qualified network channel.

func (NetworkChannelRef) Validate

func (r NetworkChannelRef) Validate() error

Validate ensures the channel reference is workspace-qualified.

type NetworkChannelStore

type NetworkChannelStore interface {
	CreateNetworkChannel(ctx context.Context, entry NetworkChannelEntry) error
	WriteNetworkChannel(ctx context.Context, entry NetworkChannelEntry) error
	GetNetworkChannel(ctx context.Context, ref NetworkChannelRef) (NetworkChannelEntry, error)
	ListNetworkChannels(ctx context.Context, query NetworkChannelQuery) ([]NetworkChannelEntry, error)
	PatchNetworkChannel(ctx context.Context, ref NetworkChannelRef, patch NetworkChannelPatch) error
	DeleteNetworkChannel(ctx context.Context, ref NetworkChannelRef) error
}

NetworkChannelStore manages durable network channel metadata.

type NetworkConversationMessage

type NetworkConversationMessage struct {
	Sequence    int64
	MessageID   string
	SessionID   string
	WorkspaceID string
	Channel     string
	Surface     string
	ThreadID    string
	DirectID    string
	Direction   string
	PeerFrom    string
	PeerTo      string
	Kind        string
	WorkID      string
	ReplyTo     string
	TraceID     string
	CausationID string
	Intent      string
	Text        string
	PreviewText string
	Mentions    []string
	ExtJSON     json.RawMessage
	Body        json.RawMessage
	SizeBytes   int64
	Timestamp   time.Time
}

NetworkConversationMessage is one persisted network conversation or presence message.

func (NetworkConversationMessage) Validate

func (e NetworkConversationMessage) Validate() error

Validate ensures the persisted network message is complete and internally consistent.

type NetworkConversationMessageQuery

type NetworkConversationMessageQuery struct {
	BeforeMessageID string
	AfterMessageID  string
	Kind            string
	WorkID          string
	Limit           int
}

NetworkConversationMessageQuery filters conversation message lookups.

func (NetworkConversationMessageQuery) Validate

Validate ensures the query uses sane bounds and one cursor direction.

type NetworkConversationRef

type NetworkConversationRef struct {
	WorkspaceID string
	Channel     string
	Surface     string
	ThreadID    string
	DirectID    string
}

NetworkConversationRef identifies one persisted network conversation container.

func (NetworkConversationRef) ContainerID

func (r NetworkConversationRef) ContainerID() string

ContainerID returns the thread or direct-room id selected by the surface.

func (NetworkConversationRef) Validate

func (r NetworkConversationRef) Validate() error

Validate ensures the reference identifies exactly one supported container.

type NetworkConversationStore

type NetworkConversationStore interface {
	ResolveDirectRoom(ctx context.Context, entry NetworkDirectRoomEntry) (NetworkDirectRoomSummary, error)
	WriteConversationMessage(
		ctx context.Context,
		entry NetworkConversationMessage,
	) (NetworkConversationWriteResult, error)
	ListThreads(ctx context.Context, ref NetworkChannelRef, query NetworkThreadQuery) (NetworkThreadPage, error)
	GetThread(ctx context.Context, ref NetworkChannelRef, threadID string) (NetworkThreadSummary, error)
	ListDirectRooms(
		ctx context.Context,
		ref NetworkChannelRef,
		query NetworkDirectRoomQuery,
	) (NetworkDirectRoomPage, error)
	GetDirectRoom(ctx context.Context, ref NetworkChannelRef, directID string) (NetworkDirectRoomSummary, error)
	ListConversationMessages(
		ctx context.Context,
		ref NetworkConversationRef,
		query NetworkConversationMessageQuery,
	) ([]NetworkConversationMessage, error)
	GetWork(ctx context.Context, workspaceID string, workID string) (NetworkWorkEntry, error)
}

NetworkConversationStore manages durable conversation containers and work rows.

type NetworkConversationWriteResult

type NetworkConversationWriteResult struct {
	MessageID          string
	Duplicate          bool
	ConversationOpened bool
	WorkOpened         bool
	WorkTransitioned   bool
	WorkState          string
	LastActivityAt     time.Time
}

NetworkConversationWriteResult reports the transactional write outcome.

type NetworkDirectRoomEntry

type NetworkDirectRoomEntry struct {
	WorkspaceID    string
	Channel        string
	DirectID       string
	SessionA       string
	SessionB       string
	OpenedAt       time.Time
	LastActivityAt time.Time
}

NetworkDirectRoomEntry is the write DTO for a direct-room row.

func (NetworkDirectRoomEntry) Validate

func (e NetworkDirectRoomEntry) Validate() error

Validate ensures direct-room membership is stable and ordered.

type NetworkDirectRoomPage

type NetworkDirectRoomPage struct {
	Directs    []NetworkDirectRoomSummary
	NextCursor string
	HasMore    bool
	Total      int
	Limit      int
}

NetworkDirectRoomPage is one bounded, counted page of direct-room summaries.

type NetworkDirectRoomQuery

type NetworkDirectRoomQuery struct {
	Search    string
	SessionID string
	Sort      string
	HasWork   *bool
	Limit     int
	After     string
}

NetworkDirectRoomQuery filters and orders direct-room summary lookups.

func (NetworkDirectRoomQuery) Normalize

Normalize applies canonical whitespace, sort, and server-owned bounds.

func (NetworkDirectRoomQuery) Validate

func (q NetworkDirectRoomQuery) Validate() error

Validate ensures the query uses a supported order and sane bounds.

type NetworkDirectRoomSummary

type NetworkDirectRoomSummary struct {
	WorkspaceID          string
	Channel              string
	DirectID             string
	SessionA             string
	SessionB             string
	OpenedAt             time.Time
	OpenedSequence       int64
	LastActivityAt       time.Time
	LastActivitySequence int64
	MessageCount         int
	OpenWorkCount        int
	LastMessagePreview   string
}

NetworkDirectRoomSummary is the list/detail projection for a direct room.

func (NetworkDirectRoomSummary) Validate

func (s NetworkDirectRoomSummary) Validate() error

Validate ensures the direct-room summary is internally consistent.

type NetworkInboxStore

type NetworkInboxStore interface {
	ListNetworkInbox(
		ctx context.Context,
		workspaceID string,
		sessionID string,
		channel string,
		limit int,
	) ([]NetworkMessageEntry, error)
}

NetworkInboxStore reads immutable delivered dispositions by durable session identity.

type NetworkMessageDisposition

type NetworkMessageDisposition struct {
	RecipientSessionID string
	Decision           string
}

NetworkMessageDisposition is one immutable pre-message recipient decision.

func (NetworkMessageDisposition) Validate

func (d NetworkMessageDisposition) Validate() error

Validate ensures the decision is bound to one durable session identity.

type NetworkMessageEntry

type NetworkMessageEntry = NetworkConversationMessage

NetworkMessageEntry is the persisted network timeline row used by existing store interfaces.

type NetworkMessageQuery

type NetworkMessageQuery struct {
	SessionID       string
	WorkspaceID     string
	Channel         string
	PeerID          string
	PeerFrom        string
	PeerTo          string
	Kind            string
	Direction       string
	MessageID       string
	BeforeMessageID string
	AfterMessageID  string
	DirectedOnly    bool
	PublicOnly      bool
	IncludePresence bool
	Since           time.Time
	Limit           int
}

NetworkMessageQuery filters persisted network timeline lookups.

func (NetworkMessageQuery) Validate

func (q NetworkMessageQuery) Validate() error

Validate ensures the query uses sane bounds.

type NetworkMessageStore

type NetworkMessageStore interface {
	WriteNetworkMessage(ctx context.Context, entry NetworkMessageEntry) error
	ListNetworkMessages(ctx context.Context, query NetworkMessageQuery) ([]NetworkMessageEntry, error)
}

NetworkMessageStore manages persisted network timeline messages.

type NetworkPreferenceStore

type NetworkPreferenceStore interface {
	PutNetworkSubscription(ctx context.Context, entry NetworkSubscriptionEntry) error
	PutNetworkSubscriptionWithChannel(
		ctx context.Context,
		channel NetworkChannelEntry,
		entry NetworkSubscriptionEntry,
	) error
	ListNetworkSubscriptions(ctx context.Context, query NetworkSubscriptionQuery) ([]NetworkSubscriptionEntry, error)
	DeleteNetworkSubscription(ctx context.Context, ref NetworkSubscriptionRef) error
	PutNetworkTaskThreadOrigin(ctx context.Context, origin NetworkTaskThreadOrigin) error
	ListNetworkTaskThreadOrigins(
		ctx context.Context,
		query NetworkTaskThreadOriginQuery,
	) ([]NetworkTaskThreadOrigin, error)
	PutTaskDesignationRollup(ctx context.Context, rollup TaskDesignationRollup) error
	ListTaskDesignationRollups(ctx context.Context, query TaskDesignationRollupQuery) ([]TaskDesignationRollup, error)
}

NetworkPreferenceStore manages network delivery preferences and network-task links.

type NetworkRecentQuery

type NetworkRecentQuery struct {
	WorkspaceID string
	Limit       int
}

NetworkRecentQuery limits the cross-channel recent-conversation projection.

func (NetworkRecentQuery) Validate

func (q NetworkRecentQuery) Validate() error

Validate ensures recents never cross workspace boundaries.

type NetworkRecentStore

type NetworkRecentStore interface {
	ListNetworkRecents(ctx context.Context, query NetworkRecentQuery) ([]NetworkRecentSummary, error)
}

NetworkRecentStore reads cross-channel recent conversation summaries.

type NetworkRecentSummary

type NetworkRecentSummary struct {
	WorkspaceID          string
	Channel              string
	Surface              string
	ContainerID          string
	LastActivityAt       time.Time
	LastActivitySequence int64
	LastMessagePreview   string
	Title                string
	ParticipantCount     int
	SessionA             string
	SessionB             string
}

NetworkRecentSummary is one cross-channel thread or direct-room list item.

type NetworkSubscriptionEntry

type NetworkSubscriptionEntry struct {
	WorkspaceID string
	Channel     string
	ThreadID    string
	SessionID   string
	Mode        string
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

NetworkSubscriptionEntry stores one session delivery preference.

func (NetworkSubscriptionEntry) Validate

func (e NetworkSubscriptionEntry) Validate() error

Validate ensures one subscription row is usable by zero-token routing.

type NetworkSubscriptionQuery

type NetworkSubscriptionQuery struct {
	WorkspaceID string
	Channel     string
	ThreadID    string
	SessionID   string
	ExactThread bool
	Limit       int
}

NetworkSubscriptionQuery filters session delivery preferences.

func (NetworkSubscriptionQuery) Validate

func (q NetworkSubscriptionQuery) Validate() error

Validate ensures subscription reads remain workspace-scoped.

type NetworkSubscriptionRef

type NetworkSubscriptionRef struct {
	WorkspaceID string
	Channel     string
	ThreadID    string
	SessionID   string
}

NetworkSubscriptionRef identifies one session's channel or thread delivery mode.

func (NetworkSubscriptionRef) Validate

func (r NetworkSubscriptionRef) Validate() error

Validate ensures the subscription target is workspace-qualified.

type NetworkTaskStatusProjection

type NetworkTaskStatusProjection struct {
	NetworkTaskStatusPublication
	RecipientSessionID string
}

NetworkTaskStatusProjection is one recipient-scoped durable projection.

type NetworkTaskStatusProjectionPayload

type NetworkTaskStatusProjectionPayload struct {
	EventID                  string             `json:"event_id"`
	EventType                string             `json:"event_type"`
	TaskID                   string             `json:"task_id"`
	RunID                    string             `json:"run_id,omitempty"`
	TaskStatus               string             `json:"task_status"`
	RunStatus                string             `json:"run_status,omitempty"`
	NetworkParticipation     participation.Spec `json:"network_participation"`
	ConversationAvailable    bool               `json:"conversation_available"`
	ConversationAvailability string             `json:"conversation_availability"`
	ProjectedAt              string             `json:"projected_at"`
}

NetworkTaskStatusProjectionPayload is the immutable transition snapshot stored for one event and its exact recipients.

type NetworkTaskStatusProjectionQuery

type NetworkTaskStatusProjectionQuery struct {
	WorkspaceID        string
	RecipientSessionID string
	TaskID             string
	Limit              int
}

NetworkTaskStatusProjectionQuery filters durable recipient projections.

func (NetworkTaskStatusProjectionQuery) Validate

Validate keeps projection reads workspace-scoped and bounded.

type NetworkTaskStatusPublication

type NetworkTaskStatusPublication struct {
	EventID        string
	EventType      string
	TaskID         string
	RunID          string
	WorkspaceID    string
	Channel        string
	ThreadID       string
	ProjectionJSON json.RawMessage
	ProjectedAt    time.Time
}

NetworkTaskStatusPublication is one typed task transition bound to its Network origin thread.

func (NetworkTaskStatusPublication) Validate

func (p NetworkTaskStatusPublication) Validate() error

Validate ensures a publication is thread-scoped and contains typed JSON.

type NetworkTaskThreadOrigin

type NetworkTaskThreadOrigin struct {
	TaskID           string
	WorkspaceID      string
	Channel          string
	ThreadID         string
	OriginMessageID  string
	Digest           string
	SourceMessageIDs []string
	CreatedAt        time.Time
	UpdatedAt        time.Time
}

func (NetworkTaskThreadOrigin) Validate

func (o NetworkTaskThreadOrigin) Validate() error

Validate ensures the origin is thread-scoped and compact.

type NetworkTaskThreadOriginQuery

type NetworkTaskThreadOriginQuery struct {
	TaskID      string
	WorkspaceID string
	Channel     string
	ThreadID    string
	Limit       int
}

NetworkTaskThreadOriginQuery filters promoted task origin links.

func (NetworkTaskThreadOriginQuery) Validate

func (q NetworkTaskThreadOriginQuery) Validate() error

Validate ensures origin reads are either task-specific or thread-specific.

type NetworkThreadPage

type NetworkThreadPage struct {
	Threads    []NetworkThreadSummary
	NextCursor string
	HasMore    bool
	Total      int
	Limit      int
}

NetworkThreadPage is one bounded, counted page of public-thread summaries.

type NetworkThreadParticipant

type NetworkThreadParticipant struct {
	WorkspaceID    string
	Channel        string
	ThreadID       string
	SessionID      string
	FirstMessageID string
	FirstSeenAt    time.Time
	LastSeenAt     time.Time
}

NetworkThreadParticipant is one session recorded as present in a public thread.

func (NetworkThreadParticipant) Validate

func (p NetworkThreadParticipant) Validate() error

Validate ensures the participant belongs to one concrete public thread.

type NetworkThreadQuery

type NetworkThreadQuery struct {
	Search    string
	SessionID string
	Sort      string
	HasWork   *bool
	Limit     int
	After     string
}

NetworkThreadQuery filters and orders public-thread summary lookups.

func (NetworkThreadQuery) Normalize

func (q NetworkThreadQuery) Normalize() NetworkThreadQuery

Normalize applies canonical whitespace, sort, and server-owned bounds.

func (NetworkThreadQuery) Validate

func (q NetworkThreadQuery) Validate() error

Validate ensures the query uses a supported order and sane bounds.

type NetworkThreadSessionTokenStats

type NetworkThreadSessionTokenStats struct {
	WorkspaceID           string
	Channel               string
	ThreadID              string
	SessionID             string
	DeliveredCount        int64
	PromptSizeBytes       int64
	EstimatedPromptTokens int64
	FirstDeliveredAt      time.Time
	LastDeliveredAt       time.Time
	UpdatedAt             time.Time
}

NetworkThreadSessionTokenStats aggregates delivered prompt cost by thread session.

type NetworkThreadSessionTokenStatsQuery

type NetworkThreadSessionTokenStatsQuery struct {
	WorkspaceID string
	Channel     string
	ThreadID    string
	SessionID   string
	Limit       int
}

NetworkThreadSessionTokenStatsQuery filters thread/session prompt-cost aggregates.

func (NetworkThreadSessionTokenStatsQuery) Validate

Validate ensures aggregate reads cannot cross workspace/thread boundaries.

type NetworkThreadSessionTokenStatsUpdate

type NetworkThreadSessionTokenStatsUpdate struct {
	WorkspaceID           string
	Channel               string
	ThreadID              string
	SessionID             string
	DeliveredCount        int64
	PromptSizeBytes       int64
	EstimatedPromptTokens int64
	DeliveredAt           time.Time
	UpdatedAt             time.Time
}

NetworkThreadSessionTokenStatsUpdate increments one thread/session prompt-cost row.

func (NetworkThreadSessionTokenStatsUpdate) Validate

Validate ensures the prompt-cost update is scoped and additive.

type NetworkThreadSummary

type NetworkThreadSummary struct {
	WorkspaceID           string
	Channel               string
	ThreadID              string
	RootMessageID         string
	Title                 string
	OpenedByPeerID        string
	OpenedSessionID       string
	OpenedAt              time.Time
	OpenedSequence        int64
	LastActivityAt        time.Time
	LastActivitySequence  int64
	MessageCount          int
	ParticipantCount      int
	OpenWorkCount         int
	DeliveredCount        int64
	PromptSizeBytes       int64
	EstimatedPromptTokens int64
	LastMessagePreview    string
}

NetworkThreadSummary is the list/detail projection for a public thread.

func (NetworkThreadSummary) Validate

func (s NetworkThreadSummary) Validate() error

Validate ensures the public-thread summary is internally consistent.

type NetworkUsageCursorPosition

type NetworkUsageCursorPosition struct {
	ReservedAt time.Time `json:"reserved_at"`
	WakeID     string    `json:"wake_id"`
}

NetworkUsageCursorPosition is the stable descending keyset position of one page.

type NetworkUsageQuery

type NetworkUsageQuery struct {
	WorkspaceID string
	Owner       *participation.OwnerRef
	Channel     string
	RunID       string
	Cursor      string
	Limit       int
	LimitSet    bool
}

NetworkUsageQuery scopes wake accounting to one authenticated workspace.

type NetworkUsageReport

type NetworkUsageReport struct {
	Details    []NetworkWakeUsageDetail
	Total      NetworkUsageSummary
	Budget     *NetworkBudgetUsage
	NextCursor string
}

NetworkUsageReport pairs a bounded page with full-filter totals and budget truth.

type NetworkUsageStore

type NetworkUsageStore interface {
	GetNetworkUsage(ctx context.Context, query NetworkUsageQuery) (NetworkUsageReport, error)
}

NetworkUsageStore reads truthful wake-ledger detail and aggregates.

type NetworkUsageSummary

type NetworkUsageSummary struct {
	WakeCount            int
	ReservedWakeCount    int
	ActualWakeCount      int
	UnavailableWakeCount int
	ChargedWallTime      time.Duration
	InputTokens          int64
	OutputTokens         int64
}

NetworkUsageSummary aggregates the complete filtered ledger scope.

type NetworkWakeAdmissionInput

type NetworkWakeAdmissionInput struct {
	WorkspaceID        string
	RecipientSessionID string
	OwnerKey           string
	Spec               participation.Spec
	Trigger            string
	Eligible           bool
	Addressed          bool
	RootID             string
	Depth              int
	WakeID             string
	TaskRunID          string
}

NetworkWakeAdmissionInput carries policy resolved before the acceptance transaction.

func (NetworkWakeAdmissionInput) Validate

func (i NetworkWakeAdmissionInput) Validate() error

Validate ensures an admission candidate is immutable and fully identified.

type NetworkWakeOutcome

type NetworkWakeOutcome struct {
	State              string
	ActualWallTime     time.Duration
	ActualInputTokens  int64
	ActualOutputTokens int64
	UsageState         string
	Reason             string
}

NetworkWakeOutcome is the terminal truth applied by the wake runner.

func (NetworkWakeOutcome) Validate

func (o NetworkWakeOutcome) Validate() error

Validate rejects non-terminal or internally contradictory settlement facts.

type NetworkWakeQueueStore

type NetworkWakeQueueStore interface {
	ListQueuedNetworkWakes(ctx context.Context, limit int) ([]CommittedNetworkNotification, error)
	LoadNetworkWake(
		ctx context.Context,
		workspaceID string,
		wakeID string,
	) (WakeReservation, []NetworkMessageEntry, error)
}

NetworkWakeQueueStore reads committed wake work for daemon execution.

type NetworkWakeUsageDetail

type NetworkWakeUsageDetail struct {
	WakeID          string
	TaskRunID       string
	OwnerKey        string
	WorkspaceID     string
	Channel         string
	RootID          string
	Depth           int
	State           string
	UsageState      string
	ChargedWallTime time.Duration
	InputTokens     int64
	OutputTokens    int64
	ReservedAt      time.Time
	SettledAt       *time.Time
	Reason          string
}

NetworkWakeUsageDetail is the charged usage truth for one admitted wake.

type NetworkWorkEntry

type NetworkWorkEntry struct {
	WorkID            string
	WorkspaceID       string
	Channel           string
	Surface           string
	ThreadID          string
	DirectID          string
	OpenedBySessionID string
	TargetSessionID   string
	State             string
	OpenedAt          time.Time
	LastActivityAt    time.Time
	TerminalAt        *time.Time
}

NetworkWorkEntry stores lifecycle metadata for work inside one conversation.

func (NetworkWorkEntry) Validate

func (e NetworkWorkEntry) Validate() error

Validate ensures a work row is bound to exactly one conversation container.

type ObservabilityRetentionSweepResult

type ObservabilityRetentionSweepResult struct {
	CutoffAt               time.Time
	DeletedEventSummaries  int64
	DeletedTokenStats      int64
	DeletedTokenUsageDaily int64
	DeletedPermissionLogs  int64
}

ObservabilityRetentionSweepResult reports how many global observability rows were deleted by one retention sweep.

type OnboardingStatus

type OnboardingStatus struct {
	Completed   bool
	CompletedAt string
}

OnboardingStatus describes the global first-run onboarding completion state.

type OnboardingStore

type OnboardingStore interface {
	GetOnboardingStatus(ctx context.Context) (OnboardingStatus, error)
	CompleteOnboarding(ctx context.Context, completedAt string) (OnboardingStatus, error)
	ResetOnboarding(ctx context.Context) (OnboardingStatus, error)
}

OnboardingStore manages the domain lifecycle for first-run onboarding.

type OverviewDayQuery

type OverviewDayQuery struct {
	WorkspaceID string
	SinceDay    string
}

OverviewDayQuery bounds one daily-rollup aggregate by day bucket and optional workspace.

func (OverviewDayQuery) Validate

func (q OverviewDayQuery) Validate() error

Validate ensures the rollup window starts on a canonical day bucket.

type OverviewSinceQuery

type OverviewSinceQuery struct {
	WorkspaceID string
	Since       time.Time
}

OverviewSinceQuery bounds one overview aggregate by timestamp and optional workspace.

func (OverviewSinceQuery) Validate

func (q OverviewSinceQuery) Validate() error

Validate ensures the aggregate window carries an explicit lower bound.

type PermissionLogEntry

type PermissionLogEntry struct {
	ID         string
	SessionID  string
	AgentName  string
	Action     string
	Resource   string
	Decision   string
	PolicyUsed string
	Timestamp  time.Time
}

PermissionLogEntry is an audit log entry for a daemon permission decision.

func (PermissionLogEntry) Validate

func (e PermissionLogEntry) Validate() error

Validate ensures the permission audit entry is complete.

type PermissionLogQuery

type PermissionLogQuery struct {
	SessionID string
	AgentName string
	Decision  string
	Since     time.Time
	Limit     int
}

PermissionLogQuery filters permission audit queries.

func (PermissionLogQuery) Validate

func (q PermissionLogQuery) Validate() error

Validate ensures the query uses sane bounds.

type ReconcileResult

type ReconcileResult struct {
	Indexed  []string
	Orphaned []string
}

type SQLiteCorruptionError

type SQLiteCorruptionError struct {
	Path  string
	Cause error
}

SQLiteCorruptionError reports corruption without attempting to mutate or replace the database family. Recovery belongs to a stopped composition root that can preserve every related database and companion file together.

func (*SQLiteCorruptionError) Error

func (e *SQLiteCorruptionError) Error() string

func (*SQLiteCorruptionError) Is

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

func (*SQLiteCorruptionError) Unwrap

func (e *SQLiteCorruptionError) Unwrap() error

type SessionActivityMeta

type SessionActivityMeta struct {
	TurnID             string     `json:"turn_id,omitempty"`
	TurnSource         string     `json:"turn_source,omitempty"`
	TurnStartedAt      *time.Time `json:"turn_started_at,omitempty"`
	LastActivityAt     *time.Time `json:"last_activity_at,omitempty"`
	LastActivityKind   string     `json:"last_activity_kind,omitempty"`
	LastActivityDetail string     `json:"last_activity_detail,omitempty"`
	CurrentTool        string     `json:"current_tool,omitempty"`
	ToolCallID         string     `json:"tool_call_id,omitempty"`
	LastProgressAt     *time.Time `json:"last_progress_at,omitempty"`
	IterationCurrent   int        `json:"iteration_current,omitempty"`
	IterationMax       int        `json:"iteration_max,omitempty"`
	IdleSeconds        int64      `json:"idle_seconds,omitempty"`
}

SessionActivityMeta is the persisted prompt/runtime activity snapshot for one ACP-backed session.

func CloneSessionActivityMeta

func CloneSessionActivityMeta(meta *SessionActivityMeta) *SessionActivityMeta

CloneSessionActivityMeta returns a deep copy of the runtime activity payload.

func (*SessionActivityMeta) Validate

func (m *SessionActivityMeta) Validate() error

Validate ensures the activity payload remains internally consistent.

type SessionAdvertisedCommand

type SessionAdvertisedCommand struct {
	Name        string                         `json:"name"`
	Description string                         `json:"description"`
	Input       *SessionAdvertisedCommandInput `json:"input,omitempty"`
}

SessionAdvertisedCommand is one ACP command in the latest replacement set for a session.

func CloneSessionAdvertisedCommands

func CloneSessionAdvertisedCommands(commands []SessionAdvertisedCommand) []SessionAdvertisedCommand

CloneSessionAdvertisedCommands returns an ownership-safe copy of a command replacement set.

func (SessionAdvertisedCommand) Validate

func (c SessionAdvertisedCommand) Validate() error

Validate enforces the durable advertised-command projection contract.

type SessionAdvertisedCommandInput

type SessionAdvertisedCommandInput struct {
	Hint string `json:"hint"`
}

SessionAdvertisedCommandInput describes the optional unstructured command argument.

type SessionAgentMetrics

type SessionAgentMetrics struct {
	AgentName      string
	Total          int
	Active         int
	Failed         int
	RuntimeSeconds int64
	LastActivityAt time.Time
}

SessionAgentMetrics contains exact visible-session aggregates for one agent.

type SessionAgentMetricsQuery

type SessionAgentMetricsQuery struct {
	WorkspaceID         string
	ExcludeIDs          []string
	ExcludeSessionTypes []string
	ExcludeSpawnRoles   []string
}

SessionAgentMetricsQuery describes one workspace-scoped grouped catalog read. Active runtime session IDs are excluded before the session manager overlays their current snapshots.

func (SessionAgentMetricsQuery) Validate

func (q SessionAgentMetricsQuery) Validate() error

Validate ensures grouped metrics cannot cross workspace boundaries.

type SessionAgentMetricsReader

type SessionAgentMetricsReader interface {
	AggregateSessionsByAgent(
		ctx context.Context,
		query SessionAgentMetricsQuery,
	) ([]SessionAgentMetrics, error)
}

SessionAgentMetricsReader exposes one grouped durable-catalog read for agent projections.

type SessionArchiveFilter

type SessionArchiveFilter string

SessionArchiveFilter controls whether archived rows participate in a catalog read.

const (
	SessionArchiveExclude SessionArchiveFilter = "exclude"
	SessionArchiveOnly    SessionArchiveFilter = "only"
	SessionArchiveInclude SessionArchiveFilter = "include"
)

func (SessionArchiveFilter) Validate

func (f SessionArchiveFilter) Validate() error

Validate reports whether the archive filter is supported. An empty filter leaves internal catalog reads unfiltered.

type SessionArchiveStore

type SessionArchiveStore interface {
	SessionArchivedAt(ctx context.Context, workspaceID string, sessionID string) (*time.Time, error)
	SetSessionArchived(
		ctx context.Context,
		workspaceID string,
		sessionID string,
		archived bool,
	) (SessionInfo, error)
}

SessionArchiveStore owns the workspace-scoped archive metadata for sessions.

type SessionAttach

type SessionAttach struct {
	SessionID       string
	AttachedTo      string
	AttachExpiresAt time.Time
	AttachedAt      time.Time
}

SessionAttach records one acquired attach lock.

type SessionAttachRequest

type SessionAttachRequest struct {
	SessionID  string
	AttachedTo string
	Now        time.Time
	TTL        time.Duration
}

SessionAttachRequest identifies one explicit attach lock acquisition.

func (SessionAttachRequest) Normalize

Normalize trims the attach request and applies UTC timestamps.

func (SessionAttachRequest) Validate

func (r SessionAttachRequest) Validate() error

Validate ensures the attach request carries the fields needed for a CAS lock.

type SessionCatalog

type SessionCatalog interface {
	RegisterSession(ctx context.Context, session SessionInfo) error
	UpdateSessionState(ctx context.Context, update SessionStateUpdate) error
	DeleteSession(ctx context.Context, sessionID string) error
	ListSessions(ctx context.Context, query SessionListQuery) ([]SessionInfo, error)
	AttachSession(ctx context.Context, req SessionAttachRequest) (SessionAttach, error)
	ReconcileSessions(ctx context.Context, sessions []SessionInfo) (ReconcileResult, error)
}

SessionCatalog manages global session index records.

type SessionCatalogOwnerReader

type SessionCatalogOwnerReader interface {
	ListSessions(ctx context.Context, query SessionListQuery) ([]SessionInfo, error)
}

SessionCatalogOwnerReader is the narrow durable-catalog read required for immutable owner authorization.

type SessionCatalogPage

type SessionCatalogPage struct {
	Sessions []SessionInfo
	Total    int
}

SessionCatalogPage is one bounded durable-catalog result. Total is counted before the keyset anchor and excludes IDs owned by the active overlay.

type SessionCatalogPageQuery

type SessionCatalogPageQuery struct {
	WorkspaceID         string
	State               string
	SessionType         string
	AgentName           string
	ParentSessionID     string
	RootSessionID       string
	Search              string
	Resumable           bool
	Archive             SessionArchiveFilter
	Sort                string
	Limit               int
	After               *SessionCatalogPosition
	ExcludeIDs          []string
	ExcludeSessionTypes []string
	ExcludeSpawnRoles   []string
}

SessionCatalogPageQuery describes one bounded durable-catalog read. Cursor decoding and active-session overlay belong to the session manager.

func (SessionCatalogPageQuery) Validate

func (q SessionCatalogPageQuery) Validate() error

Validate ensures the durable query is bounded and its anchor is usable.

type SessionCatalogPager

type SessionCatalogPager interface {
	PageSessions(ctx context.Context, query SessionCatalogPageQuery) (SessionCatalogPage, error)
}

SessionCatalogPager exposes the bounded catalog read used by public session lists.

type SessionCatalogPosition

type SessionCatalogPosition struct {
	PrimaryAt   time.Time `json:"primary_at"`
	SecondaryAt time.Time `json:"secondary_at"`
	CreatedAt   time.Time `json:"created_at"`
	ID          string    `json:"id"`
}

SessionCatalogPosition is the stable keyset anchor used by bounded catalog reads.

func (SessionCatalogPosition) Validate

func (p SessionCatalogPosition) Validate() error

Validate ensures the keyset anchor is complete.

type SessionCreationIdentity

type SessionCreationIdentity struct {
	CreationProfileRef string
	PolicySpecDigest   string
	CreationDigest     string
}

SessionCreationIdentity is the immutable idempotency witness for one created session.

func (SessionCreationIdentity) Validate

func (i SessionCreationIdentity) Validate() error

Validate requires the complete non-secret creation identity triple.

type SessionCreationIdentityStore

type SessionCreationIdentityStore interface {
	RegisterSessionWithCreationIdentity(
		context.Context,
		SessionInfo,
		SessionCreationIdentity,
	) (SessionCreationRegistration, error)
	GetSessionCreationIdentity(context.Context, string) (SessionCreationIdentity, error)
}

SessionCreationIdentityStore persists the immutable per-session witness.

type SessionCreationOptions

type SessionCreationOptions struct {
	SessionID            string             `json:"session_id"`
	Name                 string             `json:"name,omitempty"`
	NetworkOwnerKey      string             `json:"network_owner_key"`
	NetworkParticipation participation.Spec `json:"network_participation"`
	SessionType          string             `json:"session_type"`
}

SessionCreationOptions are deterministic per-session options excluded from the stable policy digest but included in the creation digest.

type SessionCreationProfile

type SessionCreationProfile struct {
	Version         int      `json:"version"`
	AgentName       string   `json:"agent_name"`
	Provider        string   `json:"provider"`
	Model           string   `json:"model,omitempty"`
	ReasoningEffort string   `json:"reasoning_effort,omitempty"`
	WorkspaceID     string   `json:"workspace_id"`
	CWD             string   `json:"cwd"`
	SandboxMode     string   `json:"sandbox_mode"`
	SandboxRef      string   `json:"sandbox_ref,omitempty"`
	Permissions     string   `json:"permissions"`
	AllowedTools    []string `json:"allowed_tools,omitempty"`
	AgentTools      []string `json:"agent_tools,omitempty"`
	AgentToolsets   []string `json:"agent_toolsets,omitempty"`
	DeniedTools     []string `json:"denied_tools,omitempty"`
	RuntimeMode     string   `json:"runtime_mode,omitempty"`
	PromptOverlay   string   `json:"prompt_overlay,omitempty"`
	ContractOverlay string   `json:"contract_overlay,omitempty"`
}

SessionCreationProfile is the immutable, secret-free runtime policy used to create or reseed a session. New fields require a profile version bump.

func NormalizeSessionCreationProfile

func NormalizeSessionCreationProfile(profile SessionCreationProfile) SessionCreationProfile

NormalizeSessionCreationProfile produces the only canonical digest input.

func (SessionCreationProfile) CanonicalJSON

func (p SessionCreationProfile) CanonicalJSON() ([]byte, error)

CanonicalJSON returns the stable serialized profile used by persistence and hashing.

func (SessionCreationProfile) CreationDigest

func (p SessionCreationProfile) CreationDigest(opts SessionCreationOptions) (string, error)

CreationDigest binds a stable policy to one preallocated session identity.

func (SessionCreationProfile) PolicySpecDigest

func (p SessionCreationProfile) PolicySpecDigest() (string, error)

PolicySpecDigest hashes stable effective policy/profile/contract inputs.

func (SessionCreationProfile) Ref

func (p SessionCreationProfile) Ref() (string, error)

Ref returns the content-addressed immutable profile reference.

func (SessionCreationProfile) Validate

func (p SessionCreationProfile) Validate() error

Validate enforces the complete immutable profile contract.

type SessionCreationProfileStore

type SessionCreationProfileStore interface {
	PutSessionCreationProfile(context.Context, SessionCreationProfile) (string, error)
	GetSessionCreationProfile(context.Context, string) (SessionCreationProfile, error)
}

SessionCreationProfileStore persists and loads content-addressed profiles.

type SessionCreationRegistration

type SessionCreationRegistration struct {
	SessionID string
	Created   bool
	Identity  SessionCreationIdentity
}

SessionCreationRegistration reports whether an atomic registration created or matched a row.

type SessionCreationStore

type SessionCreationStore interface {
	SessionCreationIdentityStore
	SessionCreationProfileStore
}

SessionCreationStore is the complete durable idempotent-creation catalog.

type SessionDBOwner

type SessionDBOwner struct {
	SessionID   string
	WorkspaceID string
}

SessionDBOwner is the immutable identity authorized to access one events.db.

func LookupSessionDBOwner

func LookupSessionDBOwner(
	ctx context.Context,
	catalog SessionCatalogOwnerReader,
	sessionID string,
) (SessionDBOwner, error)

LookupSessionDBOwner resolves one session's immutable database owner from the durable catalog. It rejects missing and conflicting catalog rows.

func (SessionDBOwner) Normalize

func (o SessionDBOwner) Normalize() (SessionDBOwner, error)

Normalize validates and canonicalizes a session database owner.

type SessionEvent

type SessionEvent struct {
	ID        string
	SessionID string
	Sequence  int64
	TurnID    string
	Type      string
	AgentName string
	Content   string
	Archived  bool
	Timestamp time.Time
}

SessionEvent is a persisted event row for a single Compozy session.

func (SessionEvent) Validate

func (e SessionEvent) Validate() error

Validate ensures the event has the required fields for persistence.

type SessionEventMetadataOpener

type SessionEventMetadataOpener func(
	ctx context.Context,
	owner SessionDBOwner,
) (EventMetadataReadCloser, error)

SessionEventMetadataOpener opens the metadata reader for one known session.

type SessionFailure

type SessionFailure struct {
	Kind            FailureKind `json:"kind"`
	Summary         string      `json:"summary,omitempty"`
	CrashBundlePath string      `json:"crash_bundle_path,omitempty"`
}

SessionFailure is the durable, redacted diagnostic summary attached to a session terminal state and projected through public read paths.

func CloneSessionFailure

func CloneSessionFailure(failure *SessionFailure) *SessionFailure

CloneSessionFailure returns a deep copy of a session failure pointer.

func (SessionFailure) IsZero

func (f SessionFailure) IsZero() bool

IsZero reports whether the failure carries no diagnostic fields.

func (SessionFailure) Normalize

func (f SessionFailure) Normalize() SessionFailure

Normalize returns a trimmed copy of f.

func (SessionFailure) Validate

func (f SessionFailure) Validate() error

Validate checks that non-empty failure records use known kinds.

type SessionInfo

type SessionInfo struct {
	ID                       string
	Name                     string
	AgentName                string
	Provider                 string
	Model                    string
	ReasoningEffort          string
	Speed                    speedpkg.Speed
	SpeedResolution          *speedpkg.Resolution
	RuntimeStatus            SessionRuntimeStatus
	RuntimeTransition        SessionRuntimeTransition
	RuntimeFailure           string
	SelectedRuntime          *SessionRuntimeSelection
	RuntimeSelectionRevision int64
	WorkspaceID              string
	*SessionNetworkState
	SessionType      string
	Lineage          *SessionLineage
	State            string
	ACPSessionID     *string
	StopReason       StopReason
	StopDetail       string
	Failure          *SessionFailure
	Liveness         *SessionLivenessMeta
	Sandbox          *SessionSandboxMeta
	SoulSnapshotID   string
	SoulDigest       string
	ParentSoulDigest string
	AttachedTo       string
	AttachExpiresAt  *time.Time
	TranscriptEpoch  int64
	ArchivedAt       *time.Time
	CreatedAt        time.Time
	UpdatedAt        time.Time
}

SessionInfo is the canonical session index row stored in the global database.

func (SessionInfo) NetworkSpecSnapshot

func (s SessionInfo) NetworkSpecSnapshot() participation.Spec

NetworkSpecSnapshot returns the immutable snapshot, defaulting uninitialized in-memory sessions to Local.

func (*SessionInfo) SetNetworkSpec

func (s *SessionInfo) SetNetworkSpec(spec participation.Spec)

SetNetworkSpec replaces the immutable participation snapshot.

func (SessionInfo) Validate

func (s SessionInfo) Validate() error

Validate ensures the session record contains the required fields.

type SessionInputQueueEntry

type SessionInputQueueEntry struct {
	ID                       string
	SessionID                string
	PromptAdmissionID        string
	MessageID                string
	IdempotencyKey           string
	TurnID                   string
	TargetTurnID             string
	EventID                  string
	Status                   string
	Mode                     string
	Delivery                 string
	Text                     string
	Runtime                  SessionInputRuntime
	SkillInvocations         []commandpkg.Invocation
	SessionGeneration        int64
	TaskRunID                string
	RunGeneration            *int64
	LoopRunID                string
	OwnerKind                string
	OwnerEpoch               *int64
	BindingEpoch             *int64
	PromptID                 string
	PromptKind               string
	OperationUsageBaseTokens *int64
	PromptAttempt            int
	Dispatchable             bool
	DispatchTokenHash        string
	AttemptCount             int
	EnqueuedAt               time.Time
	ActivatedAt              *time.Time
	DispatchStartedAt        *time.Time
	SentAt                   *time.Time
	FailedAt                 *time.Time
	FailureSummary           string
	CanceledAt               *time.Time
	FenceKind                string
	FenceDisposition         string
	FenceReasonCode          string
	FencedAt                 *time.Time
	TerminalEventStartSeq    *int64
	TerminalEventEndSeq      *int64
	TerminalKind             string
	TerminalStopReason       string
	TerminalDisposition      string
	TerminalReasonCode       string
	TerminalTokensReported   bool
	TerminalTokensUsed       *int64
	TerminalAt               *time.Time
	UpdatedAt                time.Time
}

SessionInputQueueEntry is one persisted busy-input item.

type SessionInputQueueInsert

type SessionInputQueueInsert struct {
	ID                string
	SessionID         string
	PromptAdmissionID string
	MessageID         string
	IdempotencyKey    string
	TurnID            string
	TargetTurnID      string
	EventID           string
	Mode              string
	Delivery          string
	Text              string
	Runtime           SessionInputRuntime
	SkillInvocations  []commandpkg.Invocation
	SessionGeneration int64
	TaskRunID         string
	RunGeneration     *int64
	QueueCap          int
	Now               time.Time
}

SessionInputQueueInsert captures the atomic insert request for busy input.

func (SessionInputQueueInsert) Normalize

Normalize returns a trimmed, UTC-normalized insert request.

func (SessionInputQueueInsert) Validate

func (r SessionInputQueueInsert) Validate() error

Validate ensures the insert request can be persisted.

type SessionInputQueueStore

type SessionInputQueueStore interface {
	EnqueueSessionInput(
		ctx context.Context,
		req SessionInputQueueInsert,
	) (SessionInputQueueEntry, int, error)
	EnqueueInterruptSessionInput(
		ctx context.Context,
		req SessionInputQueueInsert,
	) (SessionInputQueueEntry, int, error)
	StageSessionSteer(
		ctx context.Context,
		req SessionInputQueueInsert,
	) (SessionInputQueueEntry, error)
	ListPendingSessionInputs(ctx context.Context, sessionID string) ([]SessionInputQueueEntry, error)
	ReplaceSessionInput(
		ctx context.Context,
		sessionID string,
		entryID string,
		replacement SessionInputQueueInsert,
	) (SessionInputQueueEntry, bool, error)
	PromoteSessionInputToSteer(
		ctx context.Context,
		sessionID string,
		entryID string,
		replacement SessionInputQueueInsert,
	) (SessionInputQueueEntry, bool, error)
	ClaimNextSessionInput(
		ctx context.Context,
		sessionID string,
		now time.Time,
	) (SessionInputQueueEntry, bool, error)
	PeekNextSessionInput(
		ctx context.Context,
		sessionID string,
	) (SessionInputQueueEntry, bool, error)
	GetSessionInputQueueEntry(
		ctx context.Context,
		sessionID string,
		entryID string,
	) (SessionInputQueueEntry, error)
	MarkSessionInputSent(
		ctx context.Context,
		sessionID string,
		entryID string,
		now time.Time,
	) error
	ReleaseSessionInput(ctx context.Context, sessionID string, entryID string, now time.Time) error
	MarkSessionInputFailed(
		ctx context.Context,
		sessionID string,
		entryID string,
		summary string,
		now time.Time,
	) error
	CancelSessionInput(
		ctx context.Context,
		sessionID string,
		entryID string,
		now time.Time,
	) (SessionInputQueueEntry, error)
	CancelPendingSessionInputs(
		ctx context.Context,
		sessionID string,
		generation int64,
		now time.Time,
	) (int, error)
	AdvanceSessionInputGeneration(ctx context.Context, sessionID string, now time.Time) (int64, error)
	CurrentSessionInputGeneration(ctx context.Context, sessionID string) (int64, error)
	SessionInputQueueSummary(ctx context.Context, sessionID string) (SessionInputQueueSummary, error)
}

SessionInputQueueStore persists operator busy-input entries.

type SessionInputQueueSummary

type SessionInputQueueSummary struct {
	SessionID     string
	Generation    int64
	PendingActive int
	PendingQueued int
	PendingSteer  int
	PendingLeased int
}

SessionInputQueueSummary captures the current generation and pending entries for recap/status reads.

type SessionInputRuntime

type SessionInputRuntime struct {
	Provider        string
	Model           string
	ReasoningEffort string
	Speed           string
}

SessionInputRuntime is the immutable runtime selection captured when busy input is admitted. It intentionally uses storage-native fields so queued work remains independent from the live session binding and selector state.

func (SessionInputRuntime) Normalize

Normalize returns the canonical persisted runtime selection.

type SessionLedgerRecord

type SessionLedgerRecord struct {
	SessionID    string
	WorkspaceID  string
	AgentName    string
	SessionType  string
	EventsDBPath string
	Lineage      *SessionLineage
	StartedAt    time.Time
	EndedAt      time.Time
}

SessionLedgerRecord carries the durable session evidence needed to materialize a forensic session ledger after the live event store has been closed.

type SessionLineage

type SessionLineage struct {
	ParentSessionID  string                  `json:"parent_session_id,omitempty"`
	RootSessionID    string                  `json:"root_session_id,omitempty"`
	SpawnDepth       int                     `json:"spawn_depth"`
	SpawnRole        string                  `json:"spawn_role,omitempty"`
	TTLExpiresAt     *time.Time              `json:"ttl_expires_at,omitempty"`
	AutoStopOnParent bool                    `json:"auto_stop_on_parent"`
	SpawnBudget      SessionSpawnBudget      `json:"spawn_budget"`
	PermissionPolicy SessionPermissionPolicy `json:"permission_policy"`
}

SessionLineage is the persisted parent/root metadata used for safe spawned sessions.

func CloneSessionLineage

func CloneSessionLineage(lineage *SessionLineage) *SessionLineage

CloneSessionLineage returns a deep copy of lineage metadata.

func NormalizeSessionLineage

func NormalizeSessionLineage(sessionID string, lineage *SessionLineage) *SessionLineage

NormalizeSessionLineage returns lineage with trimmed identifiers and a root record for first-class manual sessions when no lineage was supplied.

type SessionListQuery

type SessionListQuery struct {
	ID              string
	State           string
	AgentName       string
	WorkspaceID     string
	SessionType     string
	ParentSessionID string
	RootSessionID   string
	SpawnRole       string
	Resumable       bool
	Archive         SessionArchiveFilter
	Sort            string
	Limit           int
}

SessionListQuery filters global session index queries.

func (SessionListQuery) Validate

func (q SessionListQuery) Validate() error

Validate ensures the query uses sane bounds.

type SessionLivenessMeta

type SessionLivenessMeta struct {
	SubprocessPID       int                  `json:"subprocess_pid,omitempty"`
	SubprocessStartedAt *time.Time           `json:"subprocess_started_at,omitempty"`
	LastUpdateAt        *time.Time           `json:"last_update_at,omitempty"`
	StallState          string               `json:"stall_state,omitempty"`
	StallReason         string               `json:"stall_reason,omitempty"`
	Activity            *SessionActivityMeta `json:"activity,omitempty"`
}

SessionLivenessMeta is the persisted runtime supervision state for one ACP-backed session.

func CloneSessionLivenessMeta

func CloneSessionLivenessMeta(meta *SessionLivenessMeta) *SessionLivenessMeta

CloneSessionLivenessMeta returns a deep copy of the liveness payload.

func (*SessionLivenessMeta) Validate

func (m *SessionLivenessMeta) Validate() error

Validate ensures the liveness payload remains internally consistent.

type SessionMeta

type SessionMeta struct {
	ID                   string                        `json:"id"`
	Name                 string                        `json:"name,omitempty"`
	AgentName            string                        `json:"agent_name"`
	Provider             string                        `json:"provider,omitempty"`
	Model                string                        `json:"model,omitempty"`
	ReasoningEffort      string                        `json:"reasoning_effort,omitempty"`
	Speed                speedpkg.Speed                `json:"speed,omitempty"`
	SpeedResolution      *speedpkg.Resolution          `json:"speed_resolution,omitempty"`
	RuntimeStatus        SessionRuntimeStatus          `json:"runtime_status"`
	RuntimeTransition    SessionRuntimeTransition      `json:"runtime_transition,omitempty"`
	RuntimeFailure       *string                       `json:"runtime_failure,omitempty"`
	RuntimeSelection     *SessionRuntimeSelectionState `json:"runtime_selection,omitempty"`
	EffectivePermissions string                        `json:"effective_permissions,omitempty"`
	WorkspaceID          string                        `json:"workspace_id,omitempty"`
	CWD                  string                        `json:"cwd,omitempty"`
	NetworkParticipation *participation.Spec           `json:"network_participation"`
	SessionType          string                        `json:"session_type,omitempty"`
	Lineage              *SessionLineage               `json:"lineage,omitempty"`
	State                string                        `json:"state"`
	StopReason           *StopReason                   `json:"stop_reason,omitempty"`
	StopDetail           string                        `json:"stop_detail,omitempty"`
	Failure              *SessionFailure               `json:"failure,omitempty"`
	ACPSessionID         *string                       `json:"acp_session_id,omitempty"`
	Liveness             *SessionLivenessMeta          `json:"liveness,omitempty"`
	Sandbox              *SessionSandboxMeta           `json:"sandbox,omitempty"`
	CreationProfile      *SessionCreationProfile       `json:"creation_profile,omitempty"`
	CreationOptions      *SessionCreationOptions       `json:"creation_options,omitempty"`
	CreationProfileRef   string                        `json:"creation_profile_ref,omitempty"`
	PolicySpecDigest     string                        `json:"policy_spec_digest,omitempty"`
	CreationDigest       string                        `json:"creation_digest,omitempty"`
	AdvertisedCommands   []SessionAdvertisedCommand    `json:"advertised_commands,omitempty"`
	SoulSnapshotID       string                        `json:"soul_snapshot_id,omitempty"`
	SoulDigest           string                        `json:"soul_digest,omitempty"`
	ParentSoulDigest     string                        `json:"parent_soul_digest,omitempty"`
	CreatedAt            time.Time                     `json:"created_at"`
	UpdatedAt            time.Time                     `json:"updated_at"`
}

SessionMeta is the atomically-written session metadata document.

func ReadSessionMeta

func ReadSessionMeta(path string) (SessionMeta, error)

ReadSessionMeta loads a session metadata document from disk.

func (SessionMeta) NetworkOwnerKeySnapshot

func (m SessionMeta) NetworkOwnerKeySnapshot() string

NetworkOwnerKeySnapshot returns the immutable budget owner stored in creation metadata.

func (SessionMeta) NetworkSpecSnapshot

func (m SessionMeta) NetworkSpecSnapshot() participation.Spec

NetworkSpecSnapshot returns the immutable participation snapshot stored in metadata.

func (SessionMeta) Validate

func (m SessionMeta) Validate() error

Validate ensures the metadata file remains aligned with the session index schema.

type SessionNetworkState

type SessionNetworkState struct {
	NetworkSpec participation.Spec
}

SessionNetworkState keeps immutable participation off the hot SessionInfo value.

type SessionPermissionPolicy

type SessionPermissionPolicy struct {
	Tools           []string `json:"tools"`
	Skills          []string `json:"skills"`
	MCPServers      []string `json:"mcp_servers"`
	WorkspacePaths  []string `json:"workspace_paths"`
	NetworkChannels []string `json:"network_channels"`
	SandboxProfiles []string `json:"sandbox_profiles"`
}

SessionPermissionPolicy captures concrete permission atoms available to a session.

func DecodeSessionPermissionPolicy

func DecodeSessionPermissionPolicy(raw string) (SessionPermissionPolicy, error)

DecodeSessionPermissionPolicy unmarshals permission policy metadata from the global session catalog.

func NormalizeSessionPermissionPolicy

func NormalizeSessionPermissionPolicy(policy SessionPermissionPolicy) SessionPermissionPolicy

NormalizeSessionPermissionPolicy returns a policy with stable, trimmed atom lists.

type SessionPromptAdmission

type SessionPromptAdmission struct {
	ID                  string
	WorkspaceID         string
	SessionID           string
	MessageID           string
	IdempotencyKey      string
	Operation           string
	FingerprintVersion  string
	RequestFingerprint  string
	State               string
	Mode                string
	AuthoredText        string
	Runtime             SessionInputRuntime
	SkillInvocations    []commandpkg.Invocation
	TurnID              string
	EventID             string
	Result              *SessionPromptAdmissionResult
	IndeterminateReason string
	CreatedAt           time.Time
	DispatchCommittedAt *time.Time
	CompletedAt         *time.Time
	UpdatedAt           time.Time
}

SessionPromptAdmission is the durable command receipt for one external prompt or steer request.

type SessionPromptAdmissionRequest

type SessionPromptAdmissionRequest struct {
	ID                 string
	WorkspaceID        string
	SessionID          string
	MessageID          string
	IdempotencyKey     string
	Operation          string
	FingerprintVersion string
	RequestFingerprint string
	Mode               string
	AuthoredText       string
	Runtime            SessionInputRuntime
	SkillInvocations   []commandpkg.Invocation
	TurnID             string
	EventID            string
	Now                time.Time
}

SessionPromptAdmissionRequest carries immutable command identity and request material.

func (SessionPromptAdmissionRequest) Normalize

Normalize trims identity fields and normalizes the request clock.

func (SessionPromptAdmissionRequest) Validate

func (r SessionPromptAdmissionRequest) Validate() error

Validate ensures an admission has complete, stable identity before persistence.

type SessionPromptAdmissionResult

type SessionPromptAdmissionResult struct {
	Status                string          `json:"status"`
	Mode                  string          `json:"mode,omitempty"`
	QueueEntryID          string          `json:"queue_entry_id,omitempty"`
	QueuePosition         int             `json:"queue_position,omitempty"`
	QueueGeneration       int64           `json:"queue_generation,omitempty"`
	Delivery              string          `json:"delivery,omitempty"`
	PreviousTurnID        string          `json:"previous_turn_id,omitempty"`
	NewTurnID             string          `json:"new_turn_id,omitempty"`
	CanceledQueuedEntries int             `json:"canceled_queued_entries,omitempty"`
	Goal                  json.RawMessage `json:"goal,omitempty"`
}

SessionPromptAdmissionResult is the durable non-streaming result replayed for one admitted command.

type SessionPromptAdmissionStore

type SessionPromptAdmissionStore interface {
	ReplaySessionPromptAdmission(
		ctx context.Context,
		request SessionPromptAdmissionRequest,
	) (SessionPromptAdmission, bool, error)
	ClaimSessionPromptAdmission(
		ctx context.Context,
		request SessionPromptAdmissionRequest,
	) (SessionPromptAdmission, bool, error)
	CommitSessionPromptDispatch(
		ctx context.Context,
		workspaceID string,
		sessionID string,
		idempotencyKey string,
		now time.Time,
	) error
	CompleteSessionPromptAdmission(
		ctx context.Context,
		workspaceID string,
		sessionID string,
		idempotencyKey string,
		result SessionPromptAdmissionResult,
		now time.Time,
	) (SessionPromptAdmission, error)
	MarkSessionPromptAdmissionIndeterminate(
		ctx context.Context,
		workspaceID string,
		sessionID string,
		idempotencyKey string,
		reason string,
		now time.Time,
	) error
	EnqueueAdmittedSessionInput(
		ctx context.Context,
		request SessionPromptAdmissionRequest,
		queueInput SessionInputQueueInsert,
	) (SessionPromptAdmission, SessionInputQueueEntry, int, bool, error)
	StageAdmittedSessionSteer(
		ctx context.Context,
		request SessionPromptAdmissionRequest,
		queueInput SessionInputQueueInsert,
	) (SessionPromptAdmission, SessionInputQueueEntry, bool, error)
}

SessionPromptAdmissionStore persists command receipts and their queue-linked admission decisions.

type SessionRuntimeSelection

type SessionRuntimeSelection struct {
	Provider        string         `json:"provider"`
	Model           string         `json:"model,omitempty"`
	ReasoningEffort string         `json:"reasoning_effort,omitempty"`
	Speed           speedpkg.Speed `json:"speed,omitempty"`
}

SessionRuntimeSelection is the durable runtime preference for future prompts.

func CloneSessionRuntimeSelection

func CloneSessionRuntimeSelection(selection *SessionRuntimeSelection) *SessionRuntimeSelection

CloneSessionRuntimeSelection returns an independent canonical selection.

func NormalizeSessionRuntimeSelection

func NormalizeSessionRuntimeSelection(selection *SessionRuntimeSelection) *SessionRuntimeSelection

NormalizeSessionRuntimeSelection returns an independent canonical selection.

func SessionRuntimeSelectionStateValues

func SessionRuntimeSelectionStateValues(
	state *SessionRuntimeSelectionState,
) (*SessionRuntimeSelection, int64)

SessionRuntimeSelectionStateValues returns independent values from persisted selection state.

type SessionRuntimeSelectionState

type SessionRuntimeSelectionState struct {
	Selected *SessionRuntimeSelection `json:"selected,omitempty"`
	Revision int64                    `json:"revision"`
}

SessionRuntimeSelectionState keeps a selected runtime and its revision together.

func NewSessionRuntimeSelectionState

func NewSessionRuntimeSelectionState(
	selection *SessionRuntimeSelection,
	revision int64,
) *SessionRuntimeSelectionState

NewSessionRuntimeSelectionState returns canonical persisted selection state.

type SessionRuntimeStatus

type SessionRuntimeStatus string

SessionRuntimeStatus is the persisted lifecycle of a logical session's ACP binding.

const (
	SessionRuntimeUnbound       SessionRuntimeStatus = "unbound"
	SessionRuntimeBinding       SessionRuntimeStatus = "binding"
	SessionRuntimeReady         SessionRuntimeStatus = "ready"
	SessionRuntimeReconfiguring SessionRuntimeStatus = "reconfiguring"
	SessionRuntimeFailed        SessionRuntimeStatus = "failed"
)

type SessionRuntimeTransition

type SessionRuntimeTransition string

SessionRuntimeTransition identifies the most recent successful binding strategy.

const (
	SessionRuntimeTransitionNone               SessionRuntimeTransition = ""
	SessionRuntimeTransitionInitialBind        SessionRuntimeTransition = "initial_bind"
	SessionRuntimeTransitionLiveConfiguration  SessionRuntimeTransition = "live_configuration"
	SessionRuntimeTransitionProcessReplacement SessionRuntimeTransition = "process_replacement"
)

type SessionSandboxMeta

type SessionSandboxMeta struct {
	SandboxID             string          `json:"sandbox_id,omitempty"`
	Backend               string          `json:"backend"`
	Profile               string          `json:"profile,omitempty"`
	State                 string          `json:"state,omitempty"`
	InstanceID            string          `json:"instance_id,omitempty"`
	RuntimeRootDir        string          `json:"runtime_root_dir,omitempty"`
	RuntimeAdditionalDirs []string        `json:"runtime_additional_dirs,omitempty"`
	ProviderState         json.RawMessage `json:"provider_state,omitempty"`
	SSHAccessExpiresAt    *time.Time      `json:"ssh_access_expires_at,omitempty"`
	LastSyncAt            *time.Time      `json:"last_sync_at,omitempty"`
	LastSyncError         string          `json:"last_sync_error,omitempty"`
}

SessionSandboxMeta is the persisted runtime sandbox state for a session.

type SessionSoulSnapshotUpdate

type SessionSoulSnapshotUpdate struct {
	ID               string
	SoulSnapshotID   string
	SoulDigest       string
	ParentSoulDigest string
	UpdatedAt        time.Time
}

SessionSoulSnapshotUpdate updates the Soul provenance attached to a session.

func (SessionSoulSnapshotUpdate) Validate

func (u SessionSoulSnapshotUpdate) Validate() error

Validate ensures session Soul provenance is internally consistent.

type SessionSpawnBudget

type SessionSpawnBudget struct {
	MaxChildren           int   `json:"max_children"`
	MaxDepth              int   `json:"max_depth"`
	TTLSeconds            int64 `json:"ttl_seconds"`
	MaxActivePerWorkspace int   `json:"max_active_per_workspace,omitempty"`
}

SessionSpawnBudget captures durable spawn limits attached to a session.

func DecodeSessionSpawnBudget

func DecodeSessionSpawnBudget(raw string) (SessionSpawnBudget, error)

DecodeSessionSpawnBudget unmarshals budget metadata from the global session catalog.

type SessionStateUpdate

type SessionStateUpdate struct {
	ID                       string
	State                    string
	ACPSessionID             *string
	RuntimeSet               bool
	Provider                 string
	Model                    string
	ReasoningEffort          string
	Speed                    speedpkg.Speed
	SpeedResolution          *speedpkg.Resolution
	RuntimeStatus            SessionRuntimeStatus
	RuntimeTransition        SessionRuntimeTransition
	RuntimeFailure           string
	SelectedRuntimeSet       bool
	SelectedRuntime          *SessionRuntimeSelection
	RuntimeSelectionRevision int64
	StopReasonSet            bool
	StopReason               *string
	StopDetail               string
	FailureSet               bool
	Failure                  *SessionFailure
	Liveness                 *SessionLivenessMeta
	Sandbox                  *SessionSandboxMeta
	UpdatedAt                time.Time
}

SessionStateUpdate updates only the stateful fields of an indexed session.

func (SessionStateUpdate) Validate

func (u SessionStateUpdate) Validate() error

Validate ensures the update contains the required fields.

type SessionTranscriptEpochStore

type SessionTranscriptEpochStore interface {
	SessionTranscriptEpoch(ctx context.Context, sessionID string) (int64, error)
	EnsureSessionTranscriptEpoch(ctx context.Context, update SessionTranscriptEpochUpdate) (int64, error)
}

SessionTranscriptEpochStore manages destructive transcript reset epochs.

type SessionTranscriptEpochUpdate

type SessionTranscriptEpochUpdate struct {
	SessionID string
	Minimum   int64
}

SessionTranscriptEpochUpdate advances a session transcript epoch after destructive transcript resets.

func (SessionTranscriptEpochUpdate) Validate

func (u SessionTranscriptEpochUpdate) Validate() error

Validate ensures the epoch update targets a known session and positive epoch.

type StopReason

type StopReason string
const (
	StopCompleted      StopReason = "completed"
	StopUserCanceled   StopReason = "user_canceled"
	StopMaxIterations  StopReason = "max_iterations"
	StopLoopDetected   StopReason = "loop_detected"
	StopTimeout        StopReason = "timeout"
	StopBudgetExceeded StopReason = "budget_exceeded"
	StopError          StopReason = "error"
	StopAgentCrashed   StopReason = "agent_crashed"
	StopHookStopped    StopReason = "hook_stopped"
	StopShutdown       StopReason = "shutdown"
)

type StreamStatus

type StreamStatus struct {
	Stream       string
	Version      int64
	AppliedCount int
	SumDigest    string
}

StreamStatus describes the applied state of one migration stream.

func Status

func Status(ctx context.Context, db *sql.DB, stream MigrationStream) (StreamStatus, error)

Status returns stream state without creating or mutating a version table.

type TaskClosedDay

type TaskClosedDay struct {
	Day    string
	Closed int
}

TaskClosedDay is one daemon-local day of completed-task closures.

type TaskDesignationRollup

type TaskDesignationRollup struct {
	DesignationGroupID string
	TaskID             string
	SummaryJSON        json.RawMessage
	CreatedAt          time.Time
}

TaskDesignationRollup stores the terminal summary for a designated run group.

func (TaskDesignationRollup) Validate

func (r TaskDesignationRollup) Validate() error

Validate ensures the rollup can be retrieved by task and group.

type TaskDesignationRollupQuery

type TaskDesignationRollupQuery struct {
	DesignationGroupID string
	TaskID             string
	Limit              int
}

TaskDesignationRollupQuery filters designation rollup reads.

func (TaskDesignationRollupQuery) Validate

func (q TaskDesignationRollupQuery) Validate() error

Validate ensures rollup reads cannot become unbounded.

type TaskRunOutcomeDay

type TaskRunOutcomeDay struct {
	Day       string
	Completed int
	Failed    int
	Canceled  int
}

TaskRunOutcomeDay is one daemon-local day of terminal worker-run outcomes.

type TokenStats

type TokenStats struct {
	ID           string
	SessionID    string
	AgentName    string
	InputTokens  *int64
	OutputTokens *int64
	TotalTokens  *int64
	TotalCost    *float64
	CostCurrency *string
	CostStatus   string
	CostSource   string
	TurnCount    int64
	UpdatedAt    time.Time
}

TokenStats is the aggregated usage record for a session in the global database.

type TokenStatsCostSummary

type TokenStatsCostSummary struct {
	TotalCost *float64
	Currency  *string
	Status    string
	Source    string
}

TokenStatsCostSummary is the compatible cost projection across token-stat rows.

func AggregateTokenStatsCost

func AggregateTokenStatsCost(stats []TokenStats) TokenStatsCostSummary

AggregateTokenStatsCost sums only rows with identical truthful provenance and currency.

type TokenStatsQuery

type TokenStatsQuery struct {
	SessionID string
	AgentName string
	Limit     int
}

TokenStatsQuery filters token aggregation lookups.

func (TokenStatsQuery) Validate

func (q TokenStatsQuery) Validate() error

Validate ensures the query uses sane bounds.

type TokenStatsUpdate

type TokenStatsUpdate struct {
	SessionID    string
	AgentName    string
	InputTokens  *int64
	OutputTokens *int64
	TotalTokens  *int64
	CostAmount   *float64
	CostCurrency *string
	CostStatus   string
	CostSource   string
	Turns        int64
	UpdatedAt    time.Time
}

TokenStatsUpdate adds one or more turns of usage into a session aggregate.

func (TokenStatsUpdate) Validate

func (u TokenStatsUpdate) Validate() error

Validate ensures the aggregate update contains the required identifying fields.

type TokenUsage

type TokenUsage struct {
	TurnID           string
	InputTokens      *int64
	OutputTokens     *int64
	TotalTokens      *int64
	ThoughtTokens    *int64
	CacheReadTokens  *int64
	CacheWriteTokens *int64
	ContextUsed      *int64
	ContextSize      *int64
	CostAmount       *float64
	CostCurrency     *string
	Timestamp        time.Time
}

TokenUsage captures per-turn usage data reported by an ACP provider.

func (TokenUsage) Validate

func (u TokenUsage) Validate() error

Validate ensures the usage payload has the required fields.

type TokenUsageAgentTotal

type TokenUsageAgentTotal struct {
	AgentName   string
	TotalTokens int64
}

TokenUsageAgentTotal is one agent's summed token usage inside a rollup window.

type TokenUsageCostGroup

type TokenUsageCostGroup struct {
	CostStatus      string
	CostSource      string
	CostCurrency    string
	TotalCost       float64
	RowsWithoutCost int64
	RowsTotal       int64
}

TokenUsageCostGroup is one provenance-uniform cost bucket inside a rollup window.

type TokenUsageDailyUpdate

type TokenUsageDailyUpdate struct {
	Day          string
	WorkspaceID  string
	AgentName    string
	InputTokens  *int64
	OutputTokens *int64
	TotalTokens  *int64
	CostAmount   *float64
	CostCurrency *string
	CostStatus   string
	CostSource   string
	Turns        int64
	UpdatedAt    time.Time
}

TokenUsageDailyUpdate merges one turn of token usage into the daily rollup.

func (TokenUsageDailyUpdate) Validate

func (u TokenUsageDailyUpdate) Validate() error

Validate ensures the rollup update carries a canonical day bucket, non-negative token deltas, and a valid cost shape.

type TokenUsageDay

type TokenUsageDay struct {
	Day          string
	InputTokens  int64
	OutputTokens int64
	TotalTokens  int64
}

TokenUsageDay is one daemon-local day of summed token usage.

type TurnHistory

type TurnHistory struct {
	TurnID string
	Events []SessionEvent
}

TurnHistory groups ordered events by their turn identifier.

type WakeReservation

type WakeReservation struct {
	WakeID           string
	TaskRunID        string
	WorkspaceID      string
	OwnerKey         string
	EnvelopeIDs      []string
	ReservedWallTime string
	CoalesceUntil    time.Time
}

WakeReservation is durable admission evidence paired one-to-one with a task run.

type WakeSkip

type WakeSkip struct {
	RecipientSessionID string
	OwnerKey           string
	Reason             string
	WakeID             string
}

WakeSkip records why an admission candidate accumulated without a new wake.

type WriteTx

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

WriteTx is the single-connection transaction handle passed to ExecuteWrite callbacks.

func (*WriteTx) ExecContext

func (tx *WriteTx) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

ExecContext executes a statement inside the active write transaction.

func (*WriteTx) PrepareContext

func (tx *WriteTx) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)

PrepareContext prepares a statement inside the active write transaction.

func (*WriteTx) QueryContext

func (tx *WriteTx) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)

QueryContext executes a query inside the active write transaction.

func (*WriteTx) QueryRowContext

func (tx *WriteTx) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row

QueryRowContext executes a single-row query inside the active write transaction.

Source Files

Directories

Path Synopsis
schema
Package schema embeds the global database schema and migration directory.
Package schema embeds the global database schema and migration directory.
schema
Package schema embeds the session database schema and migration directory.
Package schema embeds the session database schema and migration directory.
Package workspacedb owns per-workspace SQLite database lifecycle helpers.
Package workspacedb owns per-workspace SQLite database lifecycle helpers.
schema
Package schema embeds the workspace database schema and migration directory.
Package schema embeds the workspace database schema and migration directory.

Jump to

Keyboard shortcuts

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