store

package
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 47 Imported by: 0

Documentation

Overview

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

Index

Constants

View Source
const (
	ReplyWatchArmed       = "armed"
	ReplyWatchFired       = "fired"
	ReplyWatchDelivered   = "delivered"
	ReplyWatchAbandoned   = "abandoned"
	ReplyOutcomeCompleted = "completed"
	ReplyOutcomeFailed    = "failed"
	ReplyOutcomeCanceled  = "canceled"
	ReplyOutcomeDropped   = "dropped"
	ReplyOutcomeUnknown   = "unknown"
	// ReplyOutcomeExpired reports an armed watch released by its TTL before the target answered.
	ReplyOutcomeExpired = "expired"
)
View Source
const (
	PendingInteractionKindPermission = "permission"
	PendingInteractionKindClarify    = "clarify"

	PendingInteractionStatusPending  = "pending"
	PendingInteractionStatusOrphaned = "orphaned"
	PendingInteractionStatusResolved = "resolved"
	PendingInteractionStatusTimedOut = "timed_out"
	PendingInteractionStatusCanceled = "canceled"

	PendingInteractionTitleMaxBytes      = 200
	PendingInteractionPayloadMaxBytes    = 4096
	PendingInteractionResolutionMaxBytes = 240
	PendingInteractionChoiceMaxBytes     = 120
)
View Source
const (
	PendingInteractionOutcomeApplied              = "applied"
	PendingInteractionOutcomeAnswered             = "answered"
	PendingInteractionOutcomeResolvedAfterRestart = "resolved-after-restart"
	PendingInteractionOutcomeAlreadyResolved      = "already-resolved"
	PendingInteractionOutcomeQueueFull            = "queue-full"
)
View Source
const (
	SessionBoardNeedsYou = "needs_you"
	SessionBoardWorking  = "working"
	SessionBoardWaiting  = "waiting"
	SessionBoardInReview = "in_review"
	SessionBoardDone     = "done"
)
View Source
const (
	SessionInputAttachmentKindImage = attachmentspkg.KindImage
	SessionInputAttachmentKindFile  = attachmentspkg.KindFile
)
View Source
const (
	SessionInputOriginClassHuman     = "human"
	SessionInputOriginClassAgent     = "agent"
	SessionInputOriginClassSynthetic = "synthetic"
)

Session input origin classes rank queued input for dispatch: human operator input first, then input sent by another session, then daemon-owned wakes.

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 (
	// MaxSessionFolders bounds one profile's folders inside one workspace.
	MaxSessionFolders = 200
	// MaxSessionFolderNameLength bounds a folder display name in characters,
	// matching the schema's SQLite length() check and the Web form.
	MaxSessionFolderNameLength = 120
	// MaxSessionLayoutOrder bounds one manual reorder request.
	MaxSessionLayoutOrder = 500
	// MaxSessionPlacementLookup bounds one placement decoration read.
	MaxSessionPlacementLookup = 1000
)
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 (
	SessionNativeStatePending = "pending"
	SessionNativeStateLoaded  = "loaded"
	SessionNativeStateFailed  = "failed"
)

Native bootstrap states of a native-fork child (settled at its first bind).

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 (
	// DefaultSpawnMaxChildren is the live governed-child cap a session gets when its
	// stored budget leaves max_children unset.
	DefaultSpawnMaxChildren = 5
	// DefaultSpawnMaxDepth is the governed spawn depth a session gets when its stored
	// budget leaves max_depth unset.
	DefaultSpawnMaxDepth = 1
)
View Source
const (
	SubagentOriginDelegated      = "delegated"
	SubagentOriginProviderNative = "provider_native"
)

Subagent origins.

View Source
const (
	SubagentStatusQueued      = "queued"
	SubagentStatusRunning     = "running"
	SubagentStatusWaiting     = "waiting"
	SubagentStatusCompleted   = "completed"
	SubagentStatusFailed      = "failed"
	SubagentStatusCanceled    = "canceled"
	SubagentStatusInterrupted = "interrupted"
)

Subagent statuses. Terminal statuses are final.

View Source
const (
	SubagentWorkStateWorking            = "working"
	SubagentWorkStateWaitingForChildren = "waiting_for_children"
	SubagentWorkStateResultAvailable    = "result_available"
)

Subagent work states.

View Source
const (
	SubagentDeliveryNone         = "none"
	SubagentDeliveryPending      = "pending"
	SubagentDeliveryClaimed      = "claimed"
	SubagentDeliveryDelivered    = "delivered"
	SubagentDeliveryAcknowledged = "acknowledged"
	SubagentDeliveryDisposed     = "disposed"
)

Subagent delivery states. Delivered, acknowledged, and disposed are final.

View Source
const (
	SubagentWakePolicyAlways      = "always"
	SubagentWakePolicySettledOnly = "settled_only"
)

Subagent wake policies.

View Source
const (
	SubagentWakeStateOpen       = "open"
	SubagentWakeStateDispatched = "dispatched"
	SubagentWakeStateSettled    = "settled"
	SubagentWakeStateCanceled   = "canceled"

	SubagentWakeRouteQueue = "queue"
	SubagentWakeRouteSteer = "steer"
)

Subagent wake batch states and routes.

View Source
const (
	SubagentOrderNewest  = "newest"
	SubagentOrderUrgency = "urgency"
)

Subagent list orders.

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 (
	SessionDerivationSeedReplay     = "replay"
	SessionDerivationSeedNativeFork = "native_fork"

	SessionDerivationFirstPromptStaged   = "staged"
	SessionDerivationFirstPromptAdmitted = "admitted"
)

Derived-session seed modes and first-prompt states recorded in an outcome.

View Source
const (
	// MaxWorkspaceFolders bounds one profile's root workspace folders.
	MaxWorkspaceFolders = 200
	// MaxWorkspaceLayoutOrder bounds one manual workspace reorder request.
	MaxWorkspaceLayoutOrder = 500
)
View Source
const DefaultProfileID = "00000000000000000000000000"

DefaultProfileID is the permanent zero-ULID owner seeded by migration 00082.

View Source
const (
	// DefaultSQLiteBusyTimeoutMS is the shared SQLite busy timeout in milliseconds.
	DefaultSQLiteBusyTimeoutMS = defaultBusyTimeoutMS
)
View Source
const EmptyMentionsJSON = "[]"

EmptyMentionsJSON is the persisted mentions_json of an input without composer mentions.

View Source
const SessionCreationProfileVersion = 6
View Source
const SessionInputOwnerSynthetic = "synthetic"

SessionInputOwnerSynthetic identifies daemon-authored follow-ups in the shared queue.

View Source
const SessionInputStaleDispatchSummary = "daemon restarted while this input was dispatching; delivery outcome unknown"

SessionInputStaleDispatchSummary is the failure summary of a lease that a daemon restart left without a known dispatch outcome.

View Source
const SessionManualRootRank = 1_000_000_000

SessionManualRootRank is the manual-sort folder rank of sessions outside any folder; it orders the workspace root after every folder.

View Source
const SessionManualUnplacedPosition = -1

SessionManualUnplacedPosition is the manual-sort position of a session without a placement; unplaced sessions lead their container.

View Source
const SubagentSpawnRole = "subagent"

SubagentSpawnRole marks child sessions created by subagent delegation.

View Source
const UserSessionCreationProfileVersion = 7

UserSessionCreationProfileVersion binds new User sessions to @user and a profile.

Variables

View Source
var (
	ErrMarketplaceCatalogGenerationStale = errors.New("marketplace catalog: source generation is stale")
	ErrMarketplaceSourceNameRetained     = errors.New("marketplace_source_name_retained")
)
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 (
	ErrPendingInteractionNotFound        = errors.New("store: pending interaction not found")
	ErrPendingInteractionAlreadyResolved = errors.New("store: pending interaction already resolved")
	ErrPendingInteractionConflict        = errors.New("store: pending interaction conflict")
	ErrPendingInteractionStatusInvalid   = errors.New("store: pending interaction status is invalid")
)
View Source
var (
	ErrSessionIsInstanceMain = errors.New("session_is_instance_main")
	// ErrSubagentArchiveFollowsParent rejects independent subagent archive changes.
	ErrSubagentArchiveFollowsParent = errors.New("store: subagent archive follows parent")
	// 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 (
	//nolint:revive,staticcheck // This sentinel carries the exact public queue mutation refusal message.
	ErrSessionInputAgentAuthored = errors.New(
		"This message was sent by another session and can't be edited. Cancel it instead.",
	)
	// 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 (
	// ErrSessionInLater reports an attempt to reactivate a session parked in Later.
	ErrSessionInLater = errors.New("store: session is in later")
	// ErrSessionLaterRequiresStopped reports a park attempt for a live session.
	ErrSessionLaterRequiresStopped = errors.New("store: session must be stopped before moving to later")
)
View Source
var (
	// ErrSessionFolderNotFound reports a folder outside the caller's profile and workspace.
	ErrSessionFolderNotFound = errors.New("store: session folder not found")
	// ErrSessionFolderLimit reports that the scope already holds MaxSessionFolders folders.
	ErrSessionFolderLimit = errors.New("store: session folder limit reached")
	// ErrSessionLayoutInvalid reports a malformed layout mutation.
	ErrSessionLayoutInvalid = errors.New("store: session layout request is invalid")
	// ErrSessionLayoutConflict reports an order that does not match current layout state.
	ErrSessionLayoutConflict = errors.New("store: session layout changed concurrently")
	// ErrSessionLayoutSubagent reports a layout mutation for a subagent session,
	// which always follows its parent.
	ErrSessionLayoutSubagent = errors.New("store: subagent sessions follow their parent")
)
View Source
var (
	// ErrInstancePromptTargetChanged asks the named sender to re-resolve before admission.
	ErrInstancePromptTargetChanged        = errors.New("store: instance prompt target changed")
	ErrSessionSuperseded                  = errors.New("session_superseded")
	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 (
	// ErrSubagentNotFound reports a missing or out-of-scope subagent row.
	ErrSubagentNotFound = errors.New("store: subagent not found")
	// ErrSubagentWakeNotFound reports a missing subagent wake batch.
	ErrSubagentWakeNotFound = errors.New("store: subagent wake not found")
	// ErrSubagentIdempotencyConflict reports a reused idempotency key with a different request.
	ErrSubagentIdempotencyConflict = errors.New("store: subagent idempotency key reused with a different request")
)
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 (
	// 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")
)
View Source
var (
	// ErrTranscriptAnchorNotFound reports a message id with no active transcript entry.
	ErrTranscriptAnchorNotFound = errors.New("store: transcript anchor not found")
	// ErrTranscriptAnchorInvalid reports an anchor that is not a complete user entry.
	ErrTranscriptAnchorInvalid = errors.New("store: transcript anchor is not a complete user message")
)
View Source
var (
	// ErrWorkspaceFolderNotFound reports a workspace folder outside the caller's profile.
	ErrWorkspaceFolderNotFound = errors.New("store: workspace folder not found")
	// ErrWorkspaceLayoutTargetNotFound reports a placement for an unregistered workspace.
	ErrWorkspaceLayoutTargetNotFound = errors.New("store: workspace not found")
	// ErrWorkspaceFolderLimit reports that the profile already holds MaxWorkspaceFolders folders.
	ErrWorkspaceFolderLimit = errors.New("store: workspace folder limit reached")
	// ErrWorkspaceLayoutInvalid reports a malformed workspace layout mutation.
	ErrWorkspaceLayoutInvalid = errors.New("store: workspace layout request is invalid")
	// ErrWorkspaceLayoutConflict reports an order that does not match current layout state.
	ErrWorkspaceLayoutConflict = errors.New("store: workspace layout changed concurrently")
)
View Source
var ErrInvalidDeadEntity = errors.New("store: invalid dead entity")
View Source
var ErrMigrationPlanInvalid = errors.New("store: embedded migration plan is invalid")

ErrMigrationPlanInvalid reports embedded migrations this binary cannot verify or compile.

View Source
var ErrReadScopeInvalid = errors.New("store: read scope is invalid")
View Source
var ErrSQLiteCorrupt = errors.New("store: sqlite database is corrupt")
View Source
var ErrSessionAttentionChanged = errors.New("store: session attention changed")

ErrSessionAttentionChanged rejects a dismissal whose observed occurrence was replaced.

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 ErrSessionDerivationExists = errors.New("store: session derivation receipt already exists")

ErrSessionDerivationExists reports a receipt already recorded for the same (workspace_id, idempotency_key); the losing registration writes nothing.

View Source
var (
	// ErrSessionMetadataSchemaBehind reports metadata that predates the runtime binding contract.
	ErrSessionMetadataSchemaBehind = errors.New("store: session metadata schema is behind this binary")
)
View Source
var ErrSessionProfileMoveExists = errors.New("store: session profile move already open")

ErrSessionProfileMoveExists reports an open move already journaled for the session.

View Source
var ErrSessionWorktreeConflict = errors.New("store: session worktree binding conflict")
View Source
var ErrWorkspaceArchived = errors.New("workspace is archived; unarchive it before starting work")

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 BootWatermarkBinary

func BootWatermarkBinary() (string, error)

BootWatermarkBinary identifies the running build. Proofs recorded by another build are never honored, because the checks that build ran at boot may differ from this one's. The identity is resolved once per process.

func BootWatermarkBuildIdentity

func BootWatermarkBuildIdentity(
	release string,
	commit string,
	size int64,
	modTime int64,
	contentDigest func() (string, error),
) (string, error)

BootWatermarkBuildIdentity names one build. Executable size and modification time can collide across builds, so they are only ever combined with a build-specific identifier: the stamped release version and commit, or, for a build that carries no commit stamp, a digest of the executable's content. A build that can supply neither has no identity.

func BuildAndQuery

func BuildAndQuery(prefix string, suffix string, input ...Clause) (string, []any)

BuildAndQuery composes validated clauses after an existing WHERE boundary.

func BuildClauses

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

BuildClauses compacts optional clauses into WHERE fragments and args.

func BuildWhereQuery

func BuildWhereQuery(prefix string, suffix string, input ...Clause) (string, []any)

BuildWhereQuery composes validated clauses after a new WHERE boundary.

func Checkpoint

func Checkpoint(ctx context.Context, db *sql.DB) (retErr 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 CheckpointPassiveConnection

func CheckpointPassiveConnection(ctx context.Context, connection *sql.Conn) error

CheckpointPassiveConnection runs a checkpoint on an already acquired connection. Owners can coordinate physical file mutation without opening a connection under their lease.

func CheckpointTruncateConnection

func CheckpointTruncateConnection(ctx context.Context, conn *sql.Conn) error

CheckpointTruncateConnection truncates the WAL on an already acquired connection, waiting for readers until ctx ends. A deadline bounds how long a live owner lets readers delay it.

func CloseCheckpointedDatabase

func CloseCheckpointedDatabase(ctx context.Context, db *sql.DB, worker *PassiveCheckpointer) error

CloseCheckpointedDatabase retains database ownership until maintenance has exited.

func ContextWithMutationCommitFence

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

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

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 bounded immediate writes; callbacks propagate ctx and reuse WriteTx for the same database.

func ExecuteWriteOperation

func ExecuteWriteOperation(
	ctx context.Context,
	db *sql.DB,
	operation string,
	fn func(context.Context, *WriteTx) error,
) error

ExecuteWriteOperation names a code-owned operation, never SQL or request data.

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 HierarchyParentSessionID

func HierarchyParentSessionID(lineage *SessionLineage) string

HierarchyParentSessionID returns the parent a session nests under, or "" for a root session and for a continued or forked one: continue and fork name their source as provenance only, so a user-derived session is a new top-level session.

func IsHumanSessionInputOriginClass

func IsHumanSessionInputOriginClass(class string) bool

IsHumanSessionInputOriginClass reports whether a class belongs to the human cap and priority tier.

func IsSQLiteBusy

func IsSQLiteBusy(err error) bool

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

func IsSQLiteIdentityConstraint

func IsSQLiteIdentityConstraint(err error) bool

IsSQLiteIdentityConstraint reports whether err is a primary-key or unique-key collision.

func IsStorageUnavailable

func IsStorageUnavailable(err error) bool

IsStorageUnavailable identifies storage failures independently of provider or SQL contract failures.

func IsSubagentDeliveryFinal

func IsSubagentDeliveryFinal(delivery string) bool

IsSubagentDeliveryFinal reports whether a delivery state can no longer change.

func IsSubagentStatusTerminal

func IsSubagentStatusTerminal(status string) bool

IsSubagentStatusTerminal reports whether status is final.

func LineageKindValues

func LineageKindValues() []string

LineageKindValues returns every persisted lineage kind in canonical order.

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 LowerSessionCatalogSearchText

func LowerSessionCatalogSearchText(value string) string

LowerSessionCatalogSearchText preserves the desktop's full Unicode lowercase semantics. Casers are stateful, so each operation owns its transformer.

func MigrationStreamHead

func MigrationStreamHead(stream MigrationStream) (string, error)

MigrationStreamHead identifies the embedded head a binary verifies databases against. Two binaries with the same head accept exactly the same recorded migration history.

func NewID

func NewID(prefix string) (string, error)

NewID returns a random identifier with an optional prefix.

func NormalizeMentionsJSON

func NormalizeMentionsJSON(raw string) string

NormalizeMentionsJSON trims raw and maps a blank value to EmptyMentionsJSON.

func NormalizeSQLiteIdentifier

func NormalizeSQLiteIdentifier(value string) (string, error)

NormalizeSQLiteIdentifier validates a SQLite identifier for use in helper queries.

func NormalizeSessionFolderName

func NormalizeSessionFolderName(name string) (string, error)

NormalizeSessionFolderName trims a folder name and enforces its bounds.

func NormalizeSessionLayoutIDs

func NormalizeSessionLayoutIDs(ids []string, limit int) ([]string, error)

NormalizeSessionLayoutIDs trims, bounds, and rejects duplicate or blank IDs.

func NormalizeSessionType

func NormalizeSessionType(value string) string

NormalizeSessionType applies the default session type when empty.

func NormalizeWorkspaceLayoutProfile

func NormalizeWorkspaceLayoutProfile(profileID string) (string, error)

NormalizeWorkspaceLayoutProfile trims and requires the owning profile.

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 OpenSQLiteReadPool

func OpenSQLiteReadPool(ctx context.Context, path string, initializers ...SQLiteReadInitializer) (*sql.DB, error)

OpenSQLiteReadPool reserves read-only connections independently of writer admission and capacity.

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 ReadBootWatermarks

func ReadBootWatermarks[T any](path string, profile string) map[string]T

ReadBootWatermarks loads a boot watermark index. The index is a disposable proof cache: a missing, unreadable, foreign-format, or foreign-profile document yields no entries, which makes every session take its full boot path.

func RecoverSessionWorktreeTransition

func RecoverSessionWorktreeTransition(
	ctx context.Context,
	catalog SessionWorktreeBindingStore,
	path string,
	meta *SessionMeta,
) error

RecoverSessionWorktreeTransition finishes only an already persisted binding intent.

func RefuseLegacyDatabaseAtPath

func RefuseLegacyDatabaseAtPath(ctx context.Context, path string, stream MigrationStream) (err error)

RefuseLegacyDatabaseAtPath checks legacy markers through a read-only handle before a writable SQLite connection can mutate the database header.

func ReplyWatchID

func ReplyWatchID(target, message string) string

ReplyWatchID is stable across admission retries and process restarts.

func RequireAutomationOverlayActive

func RequireAutomationOverlayActive(
	ctx context.Context,
	tx workspaceAdmissionReader,
	kind, id string,
	override *bool,
) error

RequireAutomationOverlayActive validates the resulting effective definition before an override write. Resources are authoritative when present; legacy definitions remain supported during boot imports.

func RequireAutomationWorkspaceActive

func RequireAutomationWorkspaceActive(ctx context.Context, tx workspaceAdmissionReader,
	kind, id, workspaceID, loopWorkspaceID string, enabled, managed bool,
) error

RequireAutomationWorkspaceActive accounts for runtime overrides on managed definitions.

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 RequireWorkspaceActive

func RequireWorkspaceActive(ctx context.Context, tx workspaceAdmissionReader, ids ...string) error

RequireWorkspaceActive runs inside the same write transaction as admission. The archive writer holds the same SQLite write lock while checking blockers.

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 SessionInputOriginClassFor

func SessionInputOriginClassFor(ownerKind string, origin json.RawMessage) (class, senderSessionID string)

SessionInputOriginClassFor derives the persisted origin class and sender session from the owner kind and the stored prompt origin. Rows owned by the daemon (synthetic wakes, Goal prompts) are synthetic; rows carrying a session origin are agent-authored; everything else is human operator input.

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 SessionRuntimeRecoveryReasonValues

func SessionRuntimeRecoveryReasonValues() []string

SessionRuntimeRecoveryReasonValues returns the public recovery reason vocabulary.

func SetWriteObserver

func SetWriteObserver(observer WriteObserver)

SetWriteObserver installs the process-wide write observer; nil removes it.

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 SteerDeliveryModeValues

func SteerDeliveryModeValues() []string

SteerDeliveryModeValues supplies the canonical delivery vocabulary to public schemas.

func SubagentChildActivityValues

func SubagentChildActivityValues() []string

SubagentChildActivityValues returns the known (non-empty) child activities.

func SubagentUrgencyRank

func SubagentUrgencyRank(row SessionSubagent) int

SubagentUrgencyRank orders rows most urgent first, as clients display them: waiting, failed, working (a resumed child included), queued, then settled. It mirrors the ranking in ListSubagentsByParentUrgency.

func TryBootstrap

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

TryBootstrap initializes an untouched stream from its declarative schema. Existing version tables always return false so cross-file migration owners can retain their ordered upgrade steps without replaying history on fresh homes.

func UpgradeSessionLineageKind

func UpgradeSessionLineageKind(sessionType string, lineage *SessionLineage) bool

UpgradeSessionLineageKind fills Kind for lineage written before kinds existed, by the same rule as the catalog backfill: spawn when the session type is spawned or a spawn role is set; provenance when only a parent is set; root otherwise. It is idempotent, preserves every other field, and reports whether it changed anything.

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 ValidFailureReasonCode

func ValidFailureReasonCode(code FailureReasonCode) bool

ValidFailureReasonCode reports whether code is a supported failure reason.

func ValidPendingInteractionKind

func ValidPendingInteractionKind(kind string) bool

ValidPendingInteractionKind reports whether kind belongs to the durable vocabulary.

func ValidPendingInteractionStatus

func ValidPendingInteractionStatus(status string) bool

ValidPendingInteractionStatus reports whether status belongs to the durable vocabulary.

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 ValidateMentionsJSON

func ValidateMentionsJSON(raw string) error

ValidateMentionsJSON rejects a normalized mentions_json value that is not a JSON array.

func ValidateSessionACPOptionSelections

func ValidateSessionACPOptionSelections(selections []SessionACPOptionSelection) error

ValidateSessionACPOptionSelections checks the persisted typed option shape.

func ValidateSessionInputRuntime

func ValidateSessionInputRuntime(runtime SessionInputRuntime) error

ValidateSessionInputRuntime checks the typed options carried with queued or admitted prompt input without imposing provider-specific capability rules.

func ValidateSessionLineage

func ValidateSessionLineage(sessionID string, lineage *SessionLineage) error

ValidateSessionLineage ensures lineage is structurally usable by spawn policy enforcement.

func ValidateSessionLineageForType

func ValidateSessionLineageForType(sessionType string, lineage *SessionLineage) error

ValidateSessionLineageForType checks the lineage kind against the owning session type.

func ValidateSessionRuntime

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

ValidateSessionRuntime validates one durable runtime binding projection.

func ValidateSessionRuntimeRecovery

func ValidateSessionRuntimeRecovery(
	status SessionRuntimeStatus,
	generation int64,
	recovery *SessionRuntimeRecovery,
) error

ValidateSessionRuntimeRecovery validates one durable recovery 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 WithWALTruncation

func WithWALTruncation(thresholdBytes int64) func(*PassiveCheckpointer)

WithWALTruncation enables nonwaiting reclamation above thresholdBytes; nonpositive values disable it.

func WithWriteAttribution

func WithWriteAttribution(ctx context.Context, attribution WriteAttribution) context.Context

WithWriteAttribution attaches attribution to a context the caller owns.

func WriteBootWatermarks

func WriteBootWatermarks[T any](path string, profile string, entries map[string]T) error

WriteBootWatermarks atomically replaces a boot watermark index.

func WriteSessionMeta

func WriteSessionMeta(path string, meta *SessionMeta) error

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

Types

type BackgroundWriteOperation

type BackgroundWriteOperation struct {
	Name string
	Run  func(context.Context, *WriteTx) error
}

type BackgroundWriter

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

BackgroundWriter owns a bounded queue of coalesced writes until Close drains it.

func NewBackgroundWriter

func NewBackgroundWriter(db *sql.DB) *BackgroundWriter

func (*BackgroundWriter) Close

func (w *BackgroundWriter) Close(ctx context.Context) error

Close stops admission and waits for every accepted item to receive its commit outcome.

func (*BackgroundWriter) Submit

func (w *BackgroundWriter) Submit(
	ctx context.Context, operation string, fn func(context.Context, *WriteTx) error,
) error

Submit acknowledges only committed writes; cancellation before execution removes the item.

func (*BackgroundWriter) SubmitBatch

func (w *BackgroundWriter) SubmitBatch(ctx context.Context, operations []BackgroundWriteOperation) []error

SubmitBatch returns one committed outcome per operation, in submission order.

type Clause

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

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

func ActiveWorkspaceClause

func ActiveWorkspaceClause(column, workspaceID string) Clause

ActiveWorkspaceClause excludes archived projects from aggregate overview reads. An explicitly selected project retains its historical data.

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 ReadScopeClause

func ReadScopeClause(column string, scope ReadScope) Clause

ReadScopeClause builds the SQL predicate for a validated scope. Invalid input produces an always-false predicate as a second fail-closed guard.

func ReadScopeCoalescedClause

func ReadScopeCoalescedClause(columns []string, scope ReadScope) Clause

ReadScopeCoalescedClause builds a scoped owner predicate across nullable, ordered owner columns.

func SessionWorkspaceClause

func SessionWorkspaceClause(value string) Clause

SessionWorkspaceClause keeps an explicit User selection distinct from an unfiltered catalog.

func StringClause

func StringClause(column string, value string) Clause

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

func StringCompareClause

func StringCompareClause(column string, op string, value string) Clause

StringCompareClause builds a validated string comparison 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 ConversationRewindBaselineRefresher

type ConversationRewindBaselineRefresher interface {
	RefreshConversationRewindBaseline(context.Context, int64, string) error
}

ConversationRewindBaselineRefresher atomically refreshes the retained replay prefix.

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
	BaselineStale          bool
	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 DBTX

type DBTX interface {
	ExecContext(context.Context, string, ...any) (sql.Result, error)
	PrepareContext(context.Context, string) (*sql.Stmt, error)
	QueryContext(context.Context, string, ...any) (*sql.Rows, error)
	QueryRowContext(context.Context, string, ...any) *sql.Row
}

DBTX allows registration to join the admission owner's transaction.

type DeadEntity

type DeadEntity struct {
	DeadEntityKey
	ProfileName     string
	ProfileColor    string
	ProfileIcon     string
	ProfileEmoji    string
	ProfileArchived bool
	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 {
	ProfileID   string
	WorkspaceID string
	Kind        DeadEntityKind
	EntityID    string
}

DeadEntityKey identifies one profile- and 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 profile- and workspace-scoped and uses a closed kind.

type DeadEntityKind

type DeadEntityKind string

DeadEntityKind identifies one workspace-scoped external runtime family.

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

type DeadEntityStore

type DeadEntityStore interface {
	MarkDeadEntity(ctx context.Context, entity DeadEntity) error
	ClearDeadEntity(ctx context.Context, key DeadEntityKey) error
	FindDeadEntity(
		ctx context.Context,
		key DeadEntityKey,
	) (DeadEntity, bool, error)
	ListDeadEntities(ctx context.Context, readScope ReadScope, 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 {
	WorktreeID           string     `json:"worktree_id,omitempty"`
	TaskID               string     `json:"task_id,omitempty"`
	RunID                string     `json:"run_id,omitempty"`
	Generation           int64      `json:"generation,omitzero"`
	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 {
	// Forward selects the next bounded page even when AfterSequence is zero.
	Forward        bool
	ID             string
	Type           string
	Types          []string // Types selects a union intersected with Type when both are set.
	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
	EventMetadataReader
	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
	ProfileID       string
	ProfileName     string
	ProfileColor    string
	ProfileIcon     string
	ProfileEmoji    string
	ProfileArchived bool
	SessionID       string
	WorkspaceID     string
	Sequence        int64
	Type            string
	AgentName       string
	Provider        string
	Outcome         string
	*EventSummaryContentState
	EventCorrelation
	ParentSessionID string
	RootSessionID   string
	SpawnDepth      int
	Summary         string
	Timestamp       time.Time
}

func (EventSummary) ContentValue

func (s EventSummary) ContentValue() json.RawMessage

ContentValue returns an isolated copy of the event payload.

func (*EventSummary) SetContent

func (s *EventSummary) SetContent(content json.RawMessage)

SetContent replaces the event payload with an isolated copy.

func (EventSummary) Validate

func (s EventSummary) Validate() error

Validate ensures the summary contains the required identifying fields.

func (EventSummary) ValidateUserSession

func (s EventSummary) ValidateUserSession() error

ValidateUserSession validates a summary of a session that the catalog records in the User scope, which has no workspace registration.

type EventSummaryBatchWriter

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

EventSummaryBatchWriter persists related summaries atomically.

type EventSummaryContentState

type EventSummaryContentState struct {
	Content json.RawMessage
}

EventSummaryContentState keeps the optional payload compact while preserving EventSummary's value-oriented Content field for readers.

type EventSummaryQuery

type EventSummaryQuery struct {
	// SequenceOrder selects a bounded recent stream window; Forward selects its next page, including cursor zero.
	SequenceOrder bool
	Forward       bool
	ReadScope     ReadScope
	SessionID     string
	WorkspaceID   string
	WorktreeID    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 event summaries through one explicit profile or the AllProfiles aggregate.

func (EventSummaryQuery) Validate

func (q EventSummaryQuery) Validate() error

Validate rejects an implicit profile lens before checking query 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 FailureReasonCode

type FailureReasonCode string

FailureReasonCode identifies a stable machine-readable cause within a failure kind.

const (
	FailureReasonPromptStreamIncomplete   FailureReasonCode = "prompt_stream_incomplete"
	FailureReasonPromptDeliveryReadFailed FailureReasonCode = "prompt_delivery_read_failed"
	FailureReasonNPXPrepare               FailureReasonCode = "npx_prepare_failed"
	FailureReasonNPXInitialize            FailureReasonCode = "npx_initialize_timeout"
	FailureReasonNPXResolve               FailureReasonCode = "npx_resolution_failed"
)

type FileStamp

type FileStamp struct {
	Name    string `json:"name"`
	Size    int64  `json:"size"`
	ModTime int64  `json:"mtime_ns"`
	// Identity is the device, inode, and inode-change time. It is empty on a platform that
	// exposes none, and a stamp without it never proves anything.
	Identity string `json:"identity,omitempty"`
	// Head digests the leading bytes of a database family member.
	Head string `json:"head,omitempty"`
}

FileStamp is the cheap evidence a boot watermark compares instead of reopening a file. Size and modification time alone do not prove unchanged content, so a stamp also carries the file's platform identity and, for a database family member, a digest of its leading bytes.

What the evidence proves: the same inode on the same device was neither written, truncated, renamed, nor re-timestamped since the stamp (each of those moves the inode-change time, which no caller can set back), and an atomic replacement is a different inode. What stays unproven: a filesystem that does not maintain inode-change times, a raw write below the filesystem, or a rewrite landing in the very clock tick the stamp was taken in; the header digest still catches those whenever the replacing content committed through SQLite at a different change counter, page count, schema cookie, or log salt, but not a same-header change confined to data pages.

func StatFileStamp

func StatFileStamp(path string) (FileStamp, bool, error)

StatFileStamp stamps one regular file. A missing file reports false without an error.

func (FileStamp) Settled

func (s FileStamp) Settled(now time.Time) bool

Settled reports whether the file was last modified long enough before now for its stamp to distinguish any later write.

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 IndeterminatePromptReport

type IndeterminatePromptReport struct {
	At        time.Time
	ID        string
	SessionID string
	TurnID    string
}

type InstancePauseTrip

type InstancePauseTrip struct {
	InstanceID, ProfileID, WorkspaceID, AgentName, MainSessionID, Reason string
	CreatedAt, PausedAt                                                  time.Time
}

InstancePauseTrip is the committed snapshot of a pause caused by a queue dispatch. It must survive a concurrent resume without turning the pause event into an active event.

type InstancePromptTarget

type InstancePromptTarget struct {
	ProfileID, WorkspaceID, AgentName string
}

InstancePromptTarget is an authenticated, profile-scoped address, never a session alias.

type LineageKind

type LineageKind string

LineageKind is the typed relation between a session and its parent.

const (
	// LineageKindRoot marks a session without a relation kind (root sessions).
	LineageKindRoot LineageKind = ""
	// LineageKindProvenance marks a user session created with an explicit parent.
	LineageKindProvenance LineageKind = "provenance"
	// LineageKindSpawn marks a governed spawned or spawn-role session.
	LineageKindSpawn LineageKind = "spawn"
	// LineageKindContinue marks a session continued from another session.
	LineageKindContinue LineageKind = "continue"
	// LineageKindFork marks a session forked from another session.
	LineageKindFork LineageKind = "fork"
	// LineageKindRecovery marks a parented session created to recover the parent.
	LineageKindRecovery LineageKind = "recovery"
)

func (LineageKind) Derived

func (k LineageKind) Derived() bool

Derived reports whether kind is written by the continue/fork derive path.

func (LineageKind) Valid

func (k LineageKind) Valid() bool

Valid reports whether kind is one of the persisted lineage kinds.

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 {
	Source         string
	Layout         string
	Icon           string
	Installable    bool
	InstallBlocker string
	ResolvedRef    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 marketplace source entry.

type MarketplaceCatalogReplacement

type MarketplaceCatalogReplacement struct {
	SourceRef       string
	Kind            string
	DocumentDigest  string
	DocumentPath    string
	Owner           string
	DiagnosticsJSON string
	Source          string
	Generation      int64
	Revision        string
	ManifestVersion int64
	GeneratedAt     string
	FetchedAt       string
	Entries         []MarketplaceCatalogEntry
}

MarketplaceCatalogReplacement is one validated, atomic source projection.

type MarketplaceCatalogRepository

type MarketplaceCatalogRepository interface {
	ConfigureMarketplaceSources(
		context.Context,
		[]MarketplaceSourceDefinition,
		string,
	) (MarketplaceSourceConfiguration, error)
	ReadMarketplaceCatalogSources(context.Context, []string, int64) (MarketplaceCatalogSourcesSnapshot, error)
	ReplaceMarketplaceCatalog(context.Context, MarketplaceCatalogReplacement) error
	ReadMarketplaceCatalogSnapshot(context.Context, string, int64) (MarketplaceCatalogSnapshot, error)
	MarkMarketplaceCatalogStale(context.Context, string, int64, string, string) error
	ListMarketplaceCatalogEntries(context.Context, string, int64) ([]MarketplaceCatalogEntry, error)
	GetMarketplaceCatalogEntry(context.Context, string, string) (MarketplaceCatalogEntry, error)
	GetMarketplaceExtensionByInstallSlug(context.Context, string, string) (MarketplaceCatalogEntry, error)
	GetMarketplaceCatalogState(context.Context, string) (MarketplaceCatalogState, error)
}

MarketplaceCatalogRepository owns the global SQLite projection and its transactions.

type MarketplaceCatalogSnapshot

type MarketplaceCatalogSnapshot struct {
	Entries []MarketplaceCatalogEntry
	State   MarketplaceCatalogState
}

type MarketplaceCatalogSourcesSnapshot

type MarketplaceCatalogSourcesSnapshot struct {
	Generation int64
	Sources    []MarketplaceCatalogSnapshot
}

MarketplaceCatalogSnapshot keeps content and its revision in one database snapshot.

type MarketplaceCatalogState

type MarketplaceCatalogState struct {
	SourceRef       string
	Kind            string
	Enabled         bool
	DocumentDigest  string
	DocumentPath    string
	Owner           string
	DiagnosticsJSON string
	Installable     int64
	ErrorClass      string
	Source          string
	Generation      int64
	Revision        string
	ManifestVersion int64
	GeneratedAt     string
	FetchedAt       string
	Stale           bool
	LastError       string
	EntryCount      int64
}

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

type MarketplaceSourceConfiguration

type MarketplaceSourceConfiguration struct {
	SourceGenerations map[string]int64
	Generation        int64
	Revision          string
}

type MarketplaceSourceDefinition

type MarketplaceSourceDefinition struct {
	ConfigurationRevision string
	Name                  string
	Ref                   string
	Kind                  string
	Enabled               bool
}

type MarketplaceSourceNameRetainedError

type MarketplaceSourceNameRetainedError struct {
	Source     string
	RetainedBy []string
}

func (*MarketplaceSourceNameRetainedError) Error

func (*MarketplaceSourceNameRetainedError) Unwrap

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 MigrationPlanSummary

type MigrationPlanSummary struct {
	Stream string
	// DatabaseExists is false when the file is absent and a fresh database would be created.
	DatabaseExists bool
	Version        int64
	HeadVersion    int64
	Pending        int
}

MigrationPlanSummary describes what Apply would do for one stream without doing it.

func PlanMigrationsAtPath

func PlanMigrationsAtPath(
	ctx context.Context,
	path string,
	stream MigrationStream,
) (summary MigrationPlanSummary, err error)

PlanMigrationsAtPath reports the pending migrations of stream for the database at path through a read-only handle. It never creates the database, a version table, or applies a migration. Legacy and ahead databases fail with the same sentinels Apply returns.

type MigrationQuerier

type MigrationQuerier interface {
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

MigrationQuerier is the read surface a reconciliation uses to detect its schema change.

type MigrationReconciliation

type MigrationReconciliation struct {
	// Name identifies the reconciliation in logs and errors.
	Name string
	// Version is the migration this reconciliation completes.
	Version int64
	// Detect reports whether the migration's schema change already exists.
	Detect func(context.Context, MigrationQuerier) (bool, error)
	// Complete runs the migration's remaining statements idempotently.
	Complete func(context.Context, *WriteTx) error
}

MigrationReconciliation completes one named, already published migration on a database that carries the migration's schema change without its recorded version. Replaying the immutable migration would fail on such a database, so the owning stream supplies an idempotent form of the same statements.

Apply runs it only when every earlier version is recorded, Version is not, and Detect reports the schema change. Completion and the version record commit in one immediate transaction; any other database state is left to Goose.

type MigrationStepper

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

MigrationStepper applies a validated migration stream to explicit version boundaries without rebuilding its migration plan between steps.

func NewMigrationStepper

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

NewMigrationStepper validates the stream and prepares one reusable provider. It does not apply the stream's declarative bootstrap; callers explicitly step through the ordered SQL migrations.

func (*MigrationStepper) UpTo

func (s *MigrationStepper) UpTo(ctx context.Context, version int64) (int, error)

UpTo applies every pending migration through version and returns the number of migrations applied by this call.

type MigrationStream

type MigrationStream struct {
	Name         string
	FS           fs.FS
	Dir          string
	VersionTable string
	LegacyTables []string
	Bootstrap    *MigrationBootstrap
	// Reconciliation optionally completes one published migration whose schema
	// change already exists without its recorded version.
	Reconciliation *MigrationReconciliation
}

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 NativeReplayCursor

type NativeReplayCursor struct {
	SettledAt time.Time
	ID        string
}

NativeReplayCursor is the (settled_at, id) position of the last replay candidate returned; the zero value starts from the newest row.

type NativeSubagentResultEnrichment

type NativeSubagentResultEnrichment struct {
	ID                 string
	WorkspaceID        string
	ParentSessionID    string
	ParentTurnID       string
	ProviderToolCallID string
	Status             string
	Result             string
	Error              *string
	ResultTruncated    bool
	At                 time.Time
}

NativeSubagentResultEnrichment fills the missing result of a settled provider-native row from a later provider summary. Every guard must match: the row's identity, origin, expected terminal status, and a NULL result.

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 {
	ReadScope   ReadScope
	WorkspaceID string
	SinceDay    string
}

OverviewDayQuery bounds one daily-rollup aggregate by day bucket, optional workspace, and an explicit profile or AllProfiles lens.

func (OverviewDayQuery) Validate

func (q OverviewDayQuery) Validate() error

Validate rejects an implicit profile lens before checking the day bucket.

type OverviewSinceQuery

type OverviewSinceQuery struct {
	ReadScope   ReadScope
	WorkspaceID string
	Since       time.Time
}

OverviewSinceQuery bounds one overview aggregate by timestamp, optional workspace, and an explicit profile or AllProfiles lens.

func (OverviewSinceQuery) Validate

func (q OverviewSinceQuery) Validate() error

Validate rejects an implicit profile lens before checking the lower bound.

type OverviewWorkspaceQuery

type OverviewWorkspaceQuery struct {
	ReadScope   ReadScope
	WorkspaceID string
}

OverviewWorkspaceQuery scopes one workspace-optional overview projection by profile.

func (OverviewWorkspaceQuery) Validate

func (q OverviewWorkspaceQuery) Validate() error

Validate rejects an implicit profile lens before the projection runs.

type PassiveCheckpointer

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

PassiveCheckpointer owns WAL maintenance and joins it before final shutdown.

func OpenPassiveCheckpointer

func OpenPassiveCheckpointer(
	ctx context.Context,
	path string,
	options ...func(*PassiveCheckpointer),
) (*PassiveCheckpointer, error)

OpenPassiveCheckpointer starts periodic PASSIVE checkpoints on an existing database. PASSIVE never waits for readers or the WAL writer; unfinished work is retried on the next tick instead of extending a foreground COMMIT.

func OpenRestartCheckpointer

func OpenRestartCheckpointer(ctx context.Context, path string) (*PassiveCheckpointer, error)

OpenRestartCheckpointer also assigns WAL-header synchronization to maintenance.

func (*PassiveCheckpointer) Close

func (p *PassiveCheckpointer) Close(ctx context.Context) error

Close cancels maintenance and waits until it exits or ctx ends.

type PendingInteraction

type PendingInteraction struct {
	ExpiresAt         *time.Time
	InteractionID     string
	SessionID         string
	Kind              string
	ProviderRequestID string
	TurnID            string
	Title             string
	Payload           PendingInteractionPayload
	Status            string
	CreatedAt         time.Time
	ResolvedAt        *time.Time
	Resolution        string
	ResolvedBy        string
}

PendingInteraction is one restart-durable operator decision request.

func SanitizePendingInteraction

func SanitizePendingInteraction(interaction PendingInteraction) PendingInteraction

SanitizePendingInteraction applies the public redaction and size boundary to a canonical record.

type PendingInteractionCreate

type PendingInteractionCreate struct {
	ExpiresAt         *time.Time
	InteractionID     string
	SessionID         string
	Kind              string
	ProviderRequestID string
	TurnID            string
	Title             string
	Payload           PendingInteractionPayload
	CreatedAt         time.Time
}

PendingInteractionCreate records one new pending provider request.

func (PendingInteractionCreate) Normalize

Normalize redacts and bounds content before it can reach persistence.

func (PendingInteractionCreate) Validate

func (r PendingInteractionCreate) Validate() error

Validate rejects incomplete identities and payloads that cannot fit the public contract.

type PendingInteractionPayload

type PendingInteractionPayload struct {
	Action    string   `json:"action,omitempty"`
	Resource  string   `json:"resource,omitempty"`
	Choices   []string `json:"choices,omitempty"`
	Decisions []string `json:"decisions,omitempty"`
	ToolID    string   `json:"tool_id,omitempty"`
	// ToolKind is the ACP tool kind of a permission request (edit, execute, ...); Action holds
	// the ACP operation that raised it.
	ToolKind string `json:"tool_kind,omitempty"`
}

PendingInteractionPayload is the allowlisted display-only interaction body.

type PendingInteractionTransition

type PendingInteractionTransition struct {
	InteractionID string
	Status        string
	Resolution    string
	ResolvedBy    string
	At            time.Time
	OrphanInput   *SessionInputQueueInsert
}

PendingInteractionTransition moves one pending record to another lifecycle status.

func (PendingInteractionTransition) Normalize

Normalize applies the same secret and size boundary used by every read surface.

func (PendingInteractionTransition) Validate

func (r PendingInteractionTransition) Validate() error

Validate ensures terminal transitions are explicit and attributable.

type PermissionDailyRollup

type PermissionDailyRollup struct {
	Day       string
	AgentName string
	Decision  string
	Count     int64
}

type PermissionEntriesQuery

type PermissionEntriesQuery struct {
	PermissionRollupQuery
	Limit int
}

PermissionEntriesQuery reads the newest audit rows in the caller's reach.

type PermissionLogEntry

type PermissionLogEntry struct {
	InitiatorKind string
	InitiatorID   string
	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 {
	Unattended bool
	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 PermissionRollupQuery

type PermissionRollupQuery struct {
	ReadScope   ReadScope
	WorkspaceID string
	AgentName   string
	Unattended  bool
	Since       time.Time
	Until       time.Time
}

PermissionRollupQuery selects the complete population for daily audit totals.

type ProfileAdmissionError

type ProfileAdmissionError struct {
	ProfileID string
	Archived  bool
}

func (*ProfileAdmissionError) Action

func (e *ProfileAdmissionError) Action() string

func (*ProfileAdmissionError) Code

func (e *ProfileAdmissionError) Code() string

func (*ProfileAdmissionError) Error

func (e *ProfileAdmissionError) Error() string

func (*ProfileAdmissionError) Message

func (e *ProfileAdmissionError) Message() string

type ProfileSessionCatalogFacets

type ProfileSessionCatalogFacets struct {
	ProfileID string
	Facets    SessionCatalogFacets
}

type ReadScope

type ReadScope struct {
	ProfileID   string
	AllProfiles bool
}

ReadScope selects exactly one profile or the explicit labeled aggregate.

func (ReadScope) Matches

func (s ReadScope) Matches(profileID string) bool

Matches reports whether an owner belongs to this validated read boundary.

func (ReadScope) Validate

func (s ReadScope) Validate() error

Validate rejects every implicit or contradictory read boundary.

type ReconcileResult

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

type ReplyWatch

type ReplyWatch struct {
	ID                string
	WorkspaceID       string
	SenderSessionID   string
	TargetWorkspaceID string
	TargetSessionID   string
	MessageID         string
	AdmissionID       string
	TurnID            string
	QueueEntryID      string
	DeliveredInputID  string
	AbandonReason     string
	Hop               int
	State             string
	Outcome           string
	ReplyText         string
	ReplyTruncated    bool
	CreatedAt         time.Time
	FiredAt           *time.Time
	DeliveredAt       *time.Time
}

type ReplyWatchFilter

type ReplyWatchFilter struct {
	State           string
	WorkspaceID     string
	SenderSessionID string
	TargetSessionID string
}

type ReplyWatchFire

type ReplyWatchFire struct {
	Outcome   string
	Text      string
	Truncated bool
}

type ReplyWatchRegistration

type ReplyWatchRegistration struct {
	WorkspaceID       string
	SenderSessionID   string
	TargetWorkspaceID string
	TargetSessionID   string
	MessageID         string
	AdmissionID       string
	TurnID            string
	QueueEntryID      string
	Hop               int
	CreatedAt         time.Time
}

type ReplyWatchStore

type ReplyWatchStore interface {
	InsertReplyWatchTx(context.Context, DBTX, ReplyWatchRegistration) (ReplyWatch, error)
	GetReplyWatch(context.Context, string) (ReplyWatch, error)
	ListReplyWatches(context.Context, ReplyWatchFilter) ([]ReplyWatch, error)
	// ListPendingReplyWatchesBySender reads one sender's armed and fired watches through its index.
	ListPendingReplyWatchesBySender(context.Context, string) ([]ReplyWatch, error)
	BindReplyWatch(context.Context, string, string, string) error
	FireReplyWatch(context.Context, string, ReplyWatchFire) (bool, error)
	DeliverReplyWatch(context.Context, string, SessionInputQueueInsert) (bool, error)
	AbandonReplyWatch(context.Context, string, string) error
	ReplyWatchEvidence(context.Context, ReplyWatch) (SessionPromptAdmission, []SessionInputQueueEntry, error)
	// ReplyWatchByMessage reads the watch armed for one message admitted into a target session.
	ReplyWatchByMessage(context.Context, string, string) (ReplyWatch, bool, error)
}

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 SQLiteReadInitializer

type SQLiteReadInitializer func(context.Context, driver.ExecerContext) error

SQLiteReadInitializer configures connection-local attachments and views. The database files remain mode=ro; query_only is enabled after creating temporary views.

type SessionACPOptionSelection

type SessionACPOptionSelection struct {
	ID        string `json:"id"`
	ValueID   string `json:"value_id,omitempty"`
	BoolValue *bool  `json:"bool_value,omitzero"`
}

SessionACPOptionSelection is one typed provider option captured by a session or prompt. Exactly one of ValueID and BoolValue must be set.

func CloneSessionACPOptionSelections

func CloneSessionACPOptionSelections(
	selections []SessionACPOptionSelection,
) []SessionACPOptionSelection

CloneSessionACPOptionSelections returns an ownership-safe copy of selections.

func NormalizeSessionACPOptionSelections

func NormalizeSessionACPOptionSelections(
	selections []SessionACPOptionSelection,
) []SessionACPOptionSelection

Normalize trims values, copies boolean pointers, and orders selections by ID.

type SessionAcceptedRoute

type SessionAcceptedRoute struct {
	// Attempt is the chain index that was accepted: 0 is the primary route.
	Attempt            int    `json:"attempt"`
	Provider           string `json:"provider"`
	Model              string `json:"model"`
	AuthMode           string `json:"auth_mode"`
	HomePolicy         string `json:"home_policy"`
	CommandFingerprint string `json:"command_fingerprint"`
}

SessionAcceptedRoute is the binding ACP accepted, committed together with acp_session_id. It carries no command text: the command is identified only by its sha256 fingerprint, so resume can match a configured route without persisting secrets.

func CloneSessionAcceptedRoute

func CloneSessionAcceptedRoute(route *SessionAcceptedRoute) *SessionAcceptedRoute

CloneSessionAcceptedRoute isolates an accepted-route record.

func (SessionAcceptedRoute) Normalize

Normalize returns a trimmed copy of the record.

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,omitzero"`
	IterationMax       int        `json:"iteration_max,omitzero"`
	IdleSeconds        int64      `json:"idle_seconds,omitzero"`
}

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,omitzero"`
}

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 SessionAdvertisedCommandState

type SessionAdvertisedCommandState struct {
	AdvertisedCommands []SessionAdvertisedCommand `json:"advertised_commands,omitempty"`
}

SessionAdvertisedCommandState keeps the optional command catalog compact inside SessionMeta. Embedding preserves the flat session metadata JSON contract.

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 {
	ReadScope           ReadScope
	WorkspaceID         string
	ExcludeIDs          []string
	ExcludeSessionTypes []string
	ExcludeSpawnRoles   []string
}

SessionAgentMetricsQuery describes a profile-scoped grouped read; an empty workspace selects Global.

func (SessionAgentMetricsQuery) Validate

func (q SessionAgentMetricsQuery) Validate() error

Validate requires an explicit profile read scope.

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 SessionArchiveLiveMemberError

type SessionArchiveLiveMemberError struct {
	SessionID string
}

SessionArchiveLiveMemberError names the archive-family session that is not stopped, so a caller that may stop sessions knows which one blocks archiving.

func (*SessionArchiveLiveMemberError) Error

func (*SessionArchiveLiveMemberError) Unwrap

Unwrap keeps the live-member refusal classified as ErrSessionArchiveRequiresStopped.

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 SessionAttachState

type SessionAttachState struct {
	AttachedTo      string
	AttachExpiresAt *time.Time
}

SessionInfo is the canonical session index row stored in the global database. SessionAttachState keeps the optional attach binding compact inside SessionInfo. Embedding preserves the flat field access the catalog projections rely on.

type SessionAttention

type SessionAttention struct {
	FailureIdentity        string
	PendingPermissionCount int
	PendingClarifyCount    int
	AttentionRevision      int64
	LastSettledRevision    int64
	LastSeenRevision       int64
	LastSeenAt             *time.Time
	AttentionChangedAt     *time.Time
	// EndedEarlyTurnID names the settled turn that ended without a delivery or open
	// work signal; empty when the session's last turn did not stop early.
	EndedEarlyTurnID string
	// Later is the operator's deferral of a stopped session; nil when it is not parked.
	Later *SessionLater
	// LaterReturnedAt marks a session the daemon brought back from Later until the
	// operator sees or resumes it.
	LaterReturnedAt *time.Time
	// FailureSeenAt records when the operator marked a stopped session's failure as
	// seen; the failure then leaves Needs you until the session changes state or fails again.
	FailureSeenAt *time.Time
}

SessionAttention is the catalog-owned attention projection for one session.

func CloneSessionAttention

func CloneSessionAttention(attention *SessionAttention) *SessionAttention

CloneSessionAttention returns an isolated copy of an optional attention projection.

func (SessionAttention) Fence

Fence returns the occurrence fence of this attention projection.

func (SessionAttention) Unseen

func (a SessionAttention) Unseen() bool

Unseen reports whether the latest settled turn has not been observed.

type SessionAttentionCommit

type SessionAttentionCommit struct {
	Before      SessionAttention
	After       SessionAttention
	Interaction *PendingInteraction
	Outcome     string
}

SessionAttentionCommit reports one committed canonical attention mutation.

type SessionAttentionFence

type SessionAttentionFence struct {
	FailureIdentity   string
	AttentionRevision int64
	EndedEarlyTurnID  string
}

SessionAttentionFence identifies the revision, early-stop turn, and failure occurrence the operator saw.

type SessionAttentionStore

type SessionAttentionStore interface {
	GetSessionAttention(ctx context.Context, sessionID string) (SessionAttention, error)
	CreatePendingInteraction(ctx context.Context, req PendingInteractionCreate) (SessionAttentionCommit, error)
	TransitionPendingInteraction(
		ctx context.Context,
		req PendingInteractionTransition,
	) (SessionAttentionCommit, error)
	ListPendingInteractions(ctx context.Context, sessionID string, statuses []string) ([]PendingInteraction, error)
	HasPermissionOccurrence(ctx context.Context, sessionID, requestID, turnID string, createdAt time.Time) (bool, error)
	MarkSessionSettled(ctx context.Context, sessionID string, seen bool, at time.Time) (SessionAttentionCommit, error)
	MarkSessionSeen(ctx context.Context, sessionID string, at time.Time) (SessionAttentionCommit, error)
	// MarkSessionEndedEarly records the early-stopped turn; an empty turn id clears it.
	MarkSessionEndedEarly(ctx context.Context, sessionID string, turnID string) (SessionAttentionCommit, error)
	// DismissSessionAttention marks the operator-dismissible Needs you sources as seen
	// while the occurrence still matches fence; Outcome is "unchanged" when none was
	// raised, and ErrSessionAttentionChanged reports a newer occurrence.
	DismissSessionAttention(
		ctx context.Context,
		sessionID string,
		fence SessionAttentionFence,
		at time.Time,
	) (SessionAttentionCommit, error)
}

SessionAttentionStore owns canonical pending interactions and revision fences.

type SessionAttentionSummary

type SessionAttentionSummary struct {
	TerminalApprovals []TerminalApprovalCount
	NeedsYou          int
	Finished          int
	ByWorkspace       []WorkspaceAttentionSummary
}

SessionAttentionSummary is the exact operator-wide attention aggregate.

type SessionAutomationRunCandidate

type SessionAutomationRunCandidate struct {
	ID           string
	InitiatorID  string
	FamilyRootID string
}

SessionAutomationRunCandidate is one live hierarchy member the ExcludeAutomation rule classifies. InitiatorID and FamilyRootID classify a session whose row is not saved yet; an empty FamilyRootID names the session itself. Forks and continuations are top-level sessions and never candidates.

type SessionAutomationRunReader

type SessionAutomationRunReader interface {
	AutomationRunSessionIDs(ctx context.Context, candidates []SessionAutomationRunCandidate) ([]string, error)
}

SessionAutomationRunReader names which live sessions belong to an automation job or trigger run family the operator has not prompted, so live rows follow the durable ExcludeAutomation rule.

type SessionBoardCounts

type SessionBoardCounts struct {
	NeedsYou int
	Working  int
	Waiting  int
	InReview int
	Done     int
}

SessionBoardCounts counts sessions in each derived board column.

func (*SessionBoardCounts) Add

func (counts *SessionBoardCounts) Add(column string, count int)

func (SessionBoardCounts) Total

func (counts SessionBoardCounts) Total() int

Total counts the sessions across every column.

type SessionBranchKey

type SessionBranchKey struct{ WorkspaceID, Branch string }

SessionBranchKey identifies one branch without hydrating its session history.

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)
	// SessionInstanceID is a keyed read of one session's instance binding ("" when
	// unbound); a missing session returns ErrSessionNotFound.
	SessionInstanceID(ctx context.Context, sessionID string) (string, error)
	AttachSession(ctx context.Context, req SessionAttachRequest) (SessionAttach, error)
	ReconcileSessions(ctx context.Context, sessions []SessionInfo) (ReconcileResult, error)
}

SessionCatalog manages global session index records.

type SessionCatalogAttentionRank

type SessionCatalogAttentionRank int

SessionCatalogAttentionRank is the stable attention-class component of a catalog cursor.

const (
	SessionCatalogAttentionRankNeedsYou SessionCatalogAttentionRank = iota
	SessionCatalogAttentionRankFinished
	SessionCatalogAttentionRankNone
)

type SessionCatalogBranchReader

type SessionCatalogBranchReader interface {
	SessionCatalogBranches(context.Context, SessionCatalogPageQuery) ([]SessionBranchKey, error)
}

type SessionCatalogFacetReader

type SessionCatalogFacetReader interface {
	SessionCatalogFacets(context.Context, SessionCatalogPageQuery) (SessionCatalogFacetResult, error)
}

SessionCatalogFacetReader is the metadata-only catalog count boundary.

type SessionCatalogFacetResult

type SessionCatalogFacetResult struct {
	TerminalApprovals []TerminalApprovalCount
	Facets            SessionCatalogFacets
	ByWorkspace       []WorkspaceSessionCatalogFacets
	ByProfile         []ProfileSessionCatalogFacets
	// Later counts the scope's sessions parked in Later, whatever the read's
	// Later filter, so one facets read serves both the list and its Later toggle.
	Later int
}

SessionCatalogFacetResult aggregates durable metadata without hydrating rows.

type SessionCatalogFacets

type SessionCatalogFacets struct {
	Board             SessionBoardCounts
	All               int
	NeedsYou          int
	Working           int
	Finished          int
	TerminalApprovals int
	Idle              int
}

SessionCatalogFacets is exact metadata across an eligible catalog population. Search and selected badge are excluded so the chip counts remain scope counts.

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 {
	BoardExcludedIDs   []string
	DefaultBranches    map[string][]string
	RepositoryKeys     map[string]string
	Columns            []string
	HideChildren       bool
	ExcludeVerdictOnly bool
	// ExcludeFinishedAutomation hides settled automation-run session families.
	ExcludeFinishedAutomation bool
	// ExcludeAutomation hides every automation job or trigger run family the
	// operator has not prompted, whatever its state.
	ExcludeAutomation   bool
	Subagents           string
	SkipTotal           bool
	ReadScope           ReadScope
	WorkspaceIDs        []string
	WorkspaceID         string
	WorktreeID          string
	State               string
	SessionType         string
	AgentName           string
	ParentSessionID     string
	RootSessionID       string
	LineageKind         LineageKind
	SearchFields        string
	Search              string
	AttentionOnly       bool
	Badges              []string
	Resumable           bool
	Archive             SessionArchiveFilter
	Later               SessionLaterFilter
	Sort                string
	Limit               int
	After               *SessionCatalogPosition
	ExcludeIDs          []string
	ExcludeSessionTypes []string
	ExcludeSpawnRoles   []string
}

SessionCatalogPageQuery describes one bounded durable-catalog read through one explicit profile or the AllProfiles aggregate. 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 {
	Name          *string `json:"name,omitzero"`
	NavigatorBand *int    `json:"navigator_band,omitzero"`
	// ManualFolderRank and ManualPosition anchor the manual sort; see
	// SessionManualRootRank for sessions outside any folder.
	ManualFolderRank *int                        `json:"manual_folder_rank,omitzero"`
	ManualPosition   *int                        `json:"manual_position,omitzero"`
	AttentionRank    SessionCatalogAttentionRank `json:"attention_rank"`
	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 SessionCatalogRelationReader

type SessionCatalogRelationReader interface {
	SessionCatalogRelations(context.Context, SessionCatalogRelationsQuery) (SessionCatalogRelations, error)
}

type SessionCatalogRelations

type SessionCatalogRelations struct {
	Children     map[string]SessionBoardCounts
	ParentTitles map[string]string
}

type SessionCatalogRelationsQuery

type SessionCatalogRelationsQuery struct {
	DefaultBranches map[string][]string
	WorkspaceID     string
	WorkspaceIDs    []string
	ReadScope       ReadScope
	SessionIDs      []string
	ParentIDs       []string
	ActiveIDs       []string
	RepositoryKeys  map[string]string
}

SessionCatalogRelationsQuery scopes page relationship metadata independently of row filters.

type SessionChangeReconcileResult

type SessionChangeReconcileResult struct {
	ReconcileResult
	Written []SessionInfo
}

SessionChangeReconcileResult is a change reconcile's outcome together with the catalog rows it wrote. Each row in Written was read back inside the transaction that wrote it, in the shape ListSessions returns, so a caller can tell that row apart from one another writer left later.

type SessionChangeReconciler

type SessionChangeReconciler interface {
	ReconcileSessionChanges(
		ctx context.Context,
		changed []SessionInfo,
		unchanged []string,
	) (SessionChangeReconcileResult, error)
}

SessionChangeReconciler reconciles the catalog against a session directory whose unchanged members were proven identical to an earlier reconcile instead of being read again. Catalog sessions that are neither changed nor unchanged are marked orphaned.

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"`

	SessionType string `json:"session_type"`
	// contains filtered or unexported fields
}

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

func (SessionCreationOptions) MarshalJSON

func (o SessionCreationOptions) MarshalJSON() ([]byte, error)

MarshalJSON retains the option order used by version three through five.

func (*SessionCreationOptions) UnmarshalJSON

func (o *SessionCreationOptions) UnmarshalJSON(data []byte) error

UnmarshalJSON keeps retired Network policy as opaque, hash-bound provenance.

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"`
	Speed           speedpkg.Speed              `json:"speed"`
	ACPOptions      []SessionACPOptionSelection `json:"acp_options,omitempty"`
	ProfileID       string                      `json:"profile_id"`
	WorkspaceID     string                      `json:"workspace_id"`
	CWD             string                      `json:"cwd"`
	WorktreeRef     string                      `json:"worktree_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"`
	// contains filtered or unexported fields
}

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) MarshalJSON

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

MarshalJSON preserves each retained version's original content address.

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) UnmarshalJSON

func (p *SessionCreationProfile) UnmarshalJSON(data []byte) error

UnmarshalJSON retains retired policy fields at the persistence boundary.

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 (SessionDBOwner) Normalize

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

Normalize validates and canonicalizes a session database owner.

type SessionDerivation

type SessionDerivation struct {
	Kind            LineageKind             `json:"kind"`
	SourceSessionID string                  `json:"source_session_id"`
	IdempotencyKey  string                  `json:"idempotency_key"`
	Seed            string                  `json:"seed"`
	Native          *SessionNativeBootstrap `json:"native,omitzero"`
	PendingRoute    *SessionPendingRoute    `json:"pending_route,omitzero"`
	FirstPrompt     SessionFirstPrompt      `json:"first_prompt"`
	CreatedAt       time.Time               `json:"created_at"`
}

SessionDerivation is the derive record persisted in a continued or forked child's metadata document. It is written once at creation; only the native bootstrap state, the pending route (cleared by an explicit runtime choice), and the first-prompt state change afterwards.

func CloneSessionDerivation

func CloneSessionDerivation(derivation *SessionDerivation) *SessionDerivation

CloneSessionDerivation deep-copies a derivation record.

type SessionDerivationOutcome

type SessionDerivationOutcome struct {
	Seed                 string `json:"seed"`
	NativeState          string `json:"native_state,omitempty"`
	ACPSessionID         string `json:"acp_session_id,omitempty"`
	NativeForkError      string `json:"native_fork_error,omitempty"`
	OriginMessageID      string `json:"origin_message_id,omitempty"`
	OriginAgentName      string `json:"origin_agent_name,omitempty"`
	ThroughTurnID        string `json:"through_turn_id"`
	ReplayMessageCount   int    `json:"replay_message_count"`
	ReplayBytes          int    `json:"replay_bytes"`
	Truncated            bool   `json:"truncated"`
	OmittedCount         int    `json:"omitted_count"`
	SourceTurnInProgress bool   `json:"source_turn_in_progress"`
	SourceEpoch          int64  `json:"source_epoch"`
	SourceGeneration     int64  `json:"source_generation"`
	SourceMaxSequence    int64  `json:"source_max_sequence"`
	FirstPrompt          string `json:"first_prompt"`
	FirstAdmissionKey    string `json:"first_admission_key,omitempty"`
}

SessionDerivationOutcome is the immutable answer recorded for one derive request.

func (SessionDerivationOutcome) Validate

func (o SessionDerivationOutcome) Validate() error

Validate checks the outcome enums recorded with a receipt.

type SessionDerivationReceipt

type SessionDerivationReceipt struct {
	WorkspaceID        string
	ProfileID          string
	IdempotencyKey     string
	RequestFingerprint string
	SourceSessionID    string
	ChildSessionID     string
	Kind               LineageKind
	Outcome            SessionDerivationOutcome
	CreatedAt          time.Time
	ChildDeletedAt     *time.Time
}

SessionDerivationReceipt is the durable, never-deleted record of one derive request.

func (SessionDerivationReceipt) Validate

func (r SessionDerivationReceipt) Validate() error

Validate checks the receipt identity, kind, and outcome.

type SessionDerivationStore

type SessionDerivationStore interface {
	// RegisterDerivedSession writes the child's catalog row, its creation identity, and
	// the receipt with its immutable outcome in ONE transaction. A receipt with the same
	// (workspace_id, idempotency_key) makes the whole transaction fail with
	// ErrSessionDerivationExists; nothing is written on that path.
	RegisterDerivedSession(
		ctx context.Context,
		info *SessionInfo,
		identity SessionCreationIdentity,
		receipt SessionDerivationReceipt,
	) error
	// SessionDerivationReceipt loads one receipt by its workspace-scoped key.
	SessionDerivationReceipt(
		ctx context.Context,
		workspaceID string,
		idempotencyKey string,
		profileID string,
	) (SessionDerivationReceipt, bool, error)
	// MarkDerivationChildDeleted is called by the session delete path; the receipt survives.
	MarkDerivationChildDeleted(ctx context.Context, childSessionID string, at time.Time) error
}

SessionDerivationStore persists derive receipts together with the child registration.

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 SessionExecutionLocationState

type SessionExecutionLocationState struct {
	WorktreeID string `json:"worktree_id,omitempty"`
	CWD        string `json:"cwd,omitempty"`
}

SessionExecutionLocationState keeps the optional execution location compact inside SessionMeta. Embedding preserves the flat session metadata JSON contract.

type SessionFailure

type SessionFailure struct {
	Kind            FailureKind       `json:"kind"`
	ReasonCode      FailureReasonCode `json:"reason_code,omitempty"`
	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 SessionFilesStamp

type SessionFilesStamp struct {
	Meta     FileStamp   `json:"meta"`
	Database []FileStamp `json:"database"`
}

SessionFilesStamp identifies the durable files one session's boot checks read: its metadata document and every member of its events database family. The shared-memory index is transient and an empty write-ahead log holds no frames, so neither takes part.

func StatSessionFiles

func StatSessionFiles(sessionDir string) (SessionFilesStamp, bool, error)

StatSessionFiles stamps a session directory. It reports false when the directory has no readable metadata document, which always means "inspect this session in full".

func (SessionFilesStamp) Equal

func (s SessionFilesStamp) Equal(other SessionFilesStamp) bool

Equal reports whether both stamps carry the same evidence for every session file. It is false whenever any file's identity could not be established, which sends the session down the full path instead of trusting size and modification time.

func (SessionFilesStamp) Settled

func (s SessionFilesStamp) Settled(now time.Time) bool

Settled reports whether every stamped file is old enough to be recorded in a watermark.

type SessionFirstPrompt

type SessionFirstPrompt struct {
	State        string `json:"state"`
	AdmissionKey string `json:"admission_key,omitempty"`
	MessageID    string `json:"message_id,omitempty"`
}

SessionFirstPrompt records whether the derive admitted a first message.

type SessionFolder

type SessionFolder struct {
	ID           string
	ProfileID    string
	WorkspaceID  string
	Name         string
	Position     int
	SessionCount int
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

SessionFolder is one named, ordered group of sessions.

type SessionImportedContext

type SessionImportedContext struct {
	SourceSessionID      string                             `json:"source_session_id"`
	Kind                 LineageKind                        `json:"kind"`
	OriginAgentName      string                             `json:"origin_agent_name"`
	OriginMessageID      string                             `json:"origin_message_id,omitempty"`
	ThroughTurnID        string                             `json:"through_turn_id"`
	MessagesJSON         string                             `json:"messages_json"`
	MessageCount         int                                `json:"message_count"`
	Bytes                int                                `json:"bytes"`
	Truncated            bool                               `json:"truncated"`
	OmittedCount         int                                `json:"omitted_count"`
	SourceTurnInProgress bool                               `json:"source_turn_in_progress"`
	SourceEpoch          int64                              `json:"source_epoch"`
	SourceGeneration     int64                              `json:"source_generation"`
	SourceMaxSequence    int64                              `json:"source_max_sequence"`
	Consumed             *SessionImportedContextConsumption `json:"consumed,omitzero"`
	CreatedAt            time.Time                          `json:"created_at"`
}

SessionImportedContext is the immutable carried context of a derived child: the bounded, pruned canonical transcript taken from one source snapshot. MessagesJSON is never rewritten; Consumed records the prompt dispatch that first carried it.

func CloneSessionImportedContext

func CloneSessionImportedContext(context *SessionImportedContext) *SessionImportedContext

CloneSessionImportedContext deep-copies an imported context.

type SessionImportedContextConsumption

type SessionImportedContextConsumption struct {
	AdmissionKey string    `json:"admission_key,omitempty"`
	MessageID    string    `json:"message_id,omitempty"`
	At           time.Time `json:"at"`
}

SessionImportedContextConsumption names the prompt dispatch that first carried the imported context to an agent.

type SessionInfo

type SessionInfo struct {
	InstanceID               string
	InitiatorKind            string
	InitiatorID              string
	EffectiveWorkspaceAccess string
	VerdictOnly              bool `json:"-"`
	ID                       string
	ProfileID                string
	Name                     string
	AgentName                string
	Provider                 string
	Model                    string
	ReasoningEffort          string
	Speed                    speedpkg.Speed
	*SessionRuntimeDetails
	SpeedResolution          *speedpkg.Resolution
	RuntimeStatus            SessionRuntimeStatus
	RuntimeTransition        SessionRuntimeTransition
	RuntimeFailure           string
	RuntimeGeneration        int64
	SelectedRuntime          *SessionRuntimeSelection
	RuntimeSelectionRevision int64
	WorkspaceID              string
	WorktreeID               string

	SessionType            string
	Lineage                *SessionLineage
	State                  string
	ACPSessionID           *string
	StopReason             StopReason
	StopEscalated          bool
	StopVerificationFailed bool
	StopDetail             string
	Failure                *SessionFailure
	Liveness               *SessionLivenessMeta
	SoulSnapshotID         string
	SoulDigest             string
	ParentSoulDigest       string

	*SessionAttachState
	TranscriptEpoch int64
	Attention       *SessionAttention
	ArchivedAt      *time.Time
	CreatedAt       time.Time
	UpdatedAt       time.Time
}

func (*SessionInfo) ACPOptionsValue

func (s *SessionInfo) ACPOptionsValue() []SessionACPOptionSelection

ACPOptionsValue returns the indexed session option selections.

func (*SessionInfo) AttachExpiresAtValue

func (s *SessionInfo) AttachExpiresAtValue() *time.Time

AttachExpiresAtValue returns the optional attach expiry without exposing nil embedding details.

func (*SessionInfo) AttachedToValue

func (s *SessionInfo) AttachedToValue() string

AttachedToValue returns the optional attach owner without exposing nil embedding details.

func (*SessionInfo) AttentionSnapshot

func (s *SessionInfo) AttentionSnapshot() SessionAttention

AttentionSnapshot returns an isolated zero-safe attention projection.

func (*SessionInfo) LaterReturnedAtValue

func (s *SessionInfo) LaterReturnedAtValue() *time.Time

LaterReturnedAtValue returns when the daemon brought the session back from Later.

func (*SessionInfo) LaterState

func (s *SessionInfo) LaterState() *SessionLater

LaterState returns the parked state of the session; nil when it is not parked.

func (*SessionInfo) RuntimeRecoveryValue

func (s *SessionInfo) RuntimeRecoveryValue() *SessionRuntimeRecovery

RuntimeRecoveryValue returns independent indexed recovery metadata.

func (*SessionInfo) SetACPOptions

func (s *SessionInfo) SetACPOptions(selections []SessionACPOptionSelection)

SetACPOptions stores an ownership-safe indexed option selection set.

func (*SessionInfo) SetAttach

func (s *SessionInfo) SetAttach(attachedTo string, expiresAt *time.Time)

SetAttach updates the optional attach binding with value semantics.

func (*SessionInfo) SetRuntimeRecovery

func (s *SessionInfo) SetRuntimeRecovery(recovery *SessionRuntimeRecovery)

SetRuntimeRecovery stores independent indexed recovery metadata.

func (*SessionInfo) Validate

func (s *SessionInfo) Validate() error

Validate accepts persisted Global sessions without a workspace and validates their remaining identity.

type SessionInputAttachment

type SessionInputAttachment struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	MIMEType string `json:"mime_type"`
	Bytes    int64  `json:"bytes"`
	SHA256   string `json:"sha256"`
	Kind     string `json:"kind"`
	Width    int    `json:"width"`
	Height   int    `json:"height"`
}

SessionInputAttachment is the storage-native attachment snapshot on queued input and prompt admissions.

func (SessionInputAttachment) Normalize

Normalize returns trimmed attachment identity fields.

type SessionInputClearError

type SessionInputClearError struct {
	EntryID string
	Cause   error
}

SessionInputClearError identifies the entry whose failed mutation rolled back a clear.

func (*SessionInputClearError) Error

func (e *SessionInputClearError) Error() string

func (*SessionInputClearError) Unwrap

func (e *SessionInputClearError) Unwrap() error

type SessionInputClearRequest

type SessionInputClearRequest struct {
	SessionID string
	TurnID    string
	ActorKind string
	ActorID   string
	Now       time.Time
}

type SessionInputClearResult

type SessionInputClearResult struct {
	Inputs     []SessionInputQueueEntry
	Cleared    int
	Generation int64
}

type SessionInputClearStore

type SessionInputClearStore interface {
	ClearSessionInputs(context.Context, SessionInputClearRequest) (SessionInputClearResult, error)
	ListPendingSessionInputClearTraces(context.Context, string) ([]SessionInputClearTrace, error)
	MarkSessionInputClearTraceProjected(context.Context, string, string, time.Time) error
}

type SessionInputClearTrace

type SessionInputClearTrace struct {
	EntryID    string
	SessionID  string
	TurnID     string
	ActorKind  string
	ActorID    string
	Generation int64
	CreatedAt  time.Time
}

type SessionInputCoalesce

type SessionInputCoalesce struct {
	// CompactText replaces the wake's text once the row holds MaxFullBytes, so a burst drops output tails
	// rather than outcomes.
	CompactText  string
	MaxFullBytes int
	// MaxMembers refuses a further wake with ErrSessionInputQueueFull until the row is delivered.
	MaxMembers int
}

SessionInputCoalesce asks the store to merge a synthetic wake into the session's open row of the same key. Such a row sits outside the capacity pools: it is one row, bounded by MaxMembers.

type SessionInputHold

type SessionInputHold struct {
	InstanceID, Reason string
	Since              time.Time
}

SessionInputHold summarizes queued input blocked by an instance pause.

type SessionInputNotQueuedError

type SessionInputNotQueuedError struct {
	EntryID string
	Status  string
	Text    string
}

func (*SessionInputNotQueuedError) Error

func (*SessionInputNotQueuedError) Unwrap

func (e *SessionInputNotQueuedError) Unwrap() error

type SessionInputQueueEntry

type SessionInputQueueEntry struct {
	HeldReason     string
	HeldInstanceID string
	Held           bool
	PausedInstance *InstancePauseTrip
	Priority       int
	// SupersededIDs identifies entries canceled by the transaction creating this input.
	SupersededIDs     []string
	SupersededBy      string
	ID                string
	SessionID         string
	PromptAdmissionID string
	MessageID         string
	IdempotencyKey    string
	TurnID            string
	TargetTurnID      string
	EventID           string
	Status            string
	Mode              string
	Delivery          string
	SteerDelivery     SteerDeliveryMode
	Text              string
	Runtime           SessionInputRuntime
	SkillInvocations  []commandpkg.Invocation
	// MentionsJSON is the JSON array of resolved composer mentions; blank persists as [].
	MentionsJSON string
	// HumanIngress records that the human operator authored this input; unknown or agent authorship is false.
	HumanIngress             bool
	Origin                   json.RawMessage
	OriginClass              string
	OriginSessionID          string
	Attachments              []SessionInputAttachment
	SessionGeneration        int64
	TaskRunID                string
	RunGeneration            *int64
	LoopRunID                string
	OwnerKind                string
	SyntheticPrompt          *SessionInputSyntheticPrompt
	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 SessionInputQueueFullError

type SessionInputQueueFullError struct {
	SessionID string
	Cap       int
	Count     int
}

func (*SessionInputQueueFullError) Error

func (*SessionInputQueueFullError) Unwrap

func (e *SessionInputQueueFullError) Unwrap() error

type SessionInputQueueInsert

type SessionInputQueueInsert struct {
	Priority          int
	OwnerKind         string
	SyntheticPrompt   *SessionInputSyntheticPrompt
	ID                string
	SessionID         string
	PromptAdmissionID string
	MessageID         string
	IdempotencyKey    string
	TurnID            string
	TargetTurnID      string
	EventID           string
	Mode              string
	Delivery          string
	SteerDelivery     SteerDeliveryMode
	Text              string
	Runtime           SessionInputRuntime
	SkillInvocations  []commandpkg.Invocation
	// MentionsJSON is the JSON array of resolved composer mentions; blank persists as [].
	MentionsJSON string
	Origin       json.RawMessage
	// OriginClass and OriginSessionID default from OwnerKind and Origin; set
	// OriginClass explicitly only when a human re-authors an agent row.
	OriginClass     string
	OriginSessionID string
	// Supersede cancels the same sender's older undispatched messages to this session in the
	// transaction that inserts this agent-authored queue entry.
	Supersede bool
	// HumanIngress records that the human operator authored this input; unknown or agent authorship is false.
	HumanIngress      bool
	HumanSpawnOrigin  bool
	Attachments       []SessionInputAttachment
	SessionGeneration int64
	TaskRunID         string
	RunGeneration     *int64
	QueueCap          int
	Now               time.Time
}

SessionInputQueueInsert captures the atomic insert request for busy input.

func (SessionInputQueueInsert) CoalesceBounds

func (r SessionInputQueueInsert) CoalesceBounds() *SessionInputCoalesce

CoalesceBounds returns the merge request of a synthetic wake, or nil.

func (SessionInputQueueInsert) Normalize

Normalize trims scalar and attachment fields, clones slices, and normalizes the request clock to UTC.

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
	ACPOptions      []SessionACPOptionSelection
}

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 SessionInputSyntheticPrompt

type SessionInputSyntheticPrompt struct {
	Delivery string          `json:"delivery,omitempty"`
	RunID    string          `json:"run_id"`
	Metadata json.RawMessage `json:"metadata"`
	// CoalesceKey marks a wake row that absorbs later wakes of the same key while it waits. Rows without
	// it (including every row queued before coalescing shipped) stay individual entries.
	CoalesceKey string `json:"coalesce_key,omitempty"`
	// CoalescedMessageIDs lists the wakes merged behind the row's own message id. It is the admission
	// ledger for those wakes, so a replayed wake finds its row across a restart.
	CoalescedMessageIDs []string `json:"coalesced_message_ids,omitempty"`
	// Coalesce is the merge request for this admission only; it never persists.
	Coalesce *SessionInputCoalesce `json:"-"`
}

SessionInputSyntheticPrompt preserves execution identity and opaque ACP metadata.

func (*SessionInputSyntheticPrompt) Clone

Clone isolates queued metadata from the caller's mutable buffer.

func (*SessionInputSyntheticPrompt) CoalescedWakes

func (p *SessionInputSyntheticPrompt) CoalescedWakes() int

CoalescedWakes reports how many wakes a coalesced row carries; zero for any other row.

type SessionLater

type SessionLater struct {
	ParkedAt time.Time
	Reason   string
	ReturnAt *time.Time
	// PendingMessages counts agent messages queued while the session is parked.
	PendingMessages int
}

SessionLater is the persisted Later state of a stopped session. ReturnAt is the optional wall-clock time when the daemon brings the session back.

func CloneSessionLater

func CloneSessionLater(later *SessionLater) *SessionLater

CloneSessionLater returns an isolated copy of optional Later state.

type SessionLaterFilter

type SessionLaterFilter string

SessionLaterFilter controls whether parked rows participate in a catalog read.

const (
	SessionLaterExclude SessionLaterFilter = "exclude"
	SessionLaterOnly    SessionLaterFilter = "only"
	SessionLaterInclude SessionLaterFilter = "include"
)

func (SessionLaterFilter) Validate

func (f SessionLaterFilter) Validate() error

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

type SessionLaterPark

type SessionLaterPark struct {
	WorkspaceID string
	SessionID   string
	Reason      string
	ReturnAt    *time.Time
}

SessionLaterPark parks one stopped session. Reason and ReturnAt belong to the session the operator parked; descendants parked with it carry neither.

type SessionLaterReturn

type SessionLaterReturn struct {
	WorkspaceID string
	SessionID   string
	ProfileID   string
	Name        string
	Reason      string
	ReturnedAt  time.Time
}

SessionLaterReturn names a parked session the daemon brought back because its return time passed.

type SessionLaterStore

type SessionLaterStore interface {
	// SessionLaterState reads the Later state and back-from-Later mark of one session.
	SessionLaterState(ctx context.Context, workspaceID string, sessionID string) (*SessionLater, *time.Time, error)
	// ParkSession marks one stopped, unarchived session as parked.
	ParkSession(ctx context.Context, park SessionLaterPark) (SessionInfo, error)
	// UnparkSession clears Later state; it reports false when the session was not parked.
	UnparkSession(ctx context.Context, workspaceID string, sessionID string) (bool, error)
	// UnparkSessions clears Later state for every listed session in one transaction.
	UnparkSessions(ctx context.Context, workspaceID string, sessionIDs []string) error
	// UnparkSessionParkedAt clears Later state only when it is still the park made at parkedAt.
	UnparkSessionParkedAt(ctx context.Context, workspaceID string, sessionID string, parkedAt time.Time) (bool, error)
	// ReturnDueLaterSessions brings back at most limit parked sessions whose
	// return time is at or before now, marking each as back from Later.
	ReturnDueLaterSessions(ctx context.Context, now time.Time, limit int) ([]SessionLaterReturn, error)
	// ClearLaterReturn clears the back-from-Later mark; it reports whether one was set.
	ClearLaterReturn(ctx context.Context, sessionID string) (bool, error)
}

SessionLaterStore owns the persisted Later state of sessions.

type SessionLayoutScope

type SessionLayoutScope struct {
	ProfileID   string
	WorkspaceID string
}

SessionLayoutScope selects one profile's layout inside one workspace.

func (SessionLayoutScope) Normalize

func (s SessionLayoutScope) Normalize() (SessionLayoutScope, error)

Normalize trims and validates the scope.

type SessionLayoutStore

type SessionLayoutStore interface {
	ListSessionFolders(ctx context.Context, scope SessionLayoutScope) ([]SessionFolder, error)
	CreateSessionFolder(ctx context.Context, scope SessionLayoutScope, id string, name string) (SessionFolder, error)
	RenameSessionFolder(ctx context.Context, scope SessionLayoutScope, id string, name string) (SessionFolder, error)
	DeleteSessionFolder(ctx context.Context, scope SessionLayoutScope, id string) error
	ReorderSessionFolders(ctx context.Context, scope SessionLayoutScope, ids []string) ([]SessionFolder, error)
	MoveSession(ctx context.Context, scope SessionLayoutScope, sessionID string, folderID string) error
	ReorderSessions(ctx context.Context, scope SessionLayoutScope, folderID string, sessionIDs []string) error
	SessionPlacements(ctx context.Context, sessionIDs []string) (map[string]SessionPlacement, error)
}

SessionLayoutStore persists session folders and manual session order.

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"`
	Kind             LineageKind             `json:"kind,omitempty"`
	OriginMessageID  string                  `json:"origin_message_id,omitempty"`
	OriginAgentName  string                  `json:"origin_agent_name,omitempty"`
	TTLExpiresAt     *time.Time              `json:"ttl_expires_at,omitempty"`
	AutoStopOnParent bool                    `json:"auto_stop_on_parent"`
	NotifyCreator    bool                    `json:"notify_creator"`
	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 SessionLineageStore

type SessionLineageStore interface {
	// UpdateSessionLineages applies every update in one transaction and fails
	// when any targeted session is missing from the workspace.
	UpdateSessionLineages(ctx context.Context, workspaceID string, updates []SessionLineageUpdate) error
}

SessionLineageStore rewrites persisted session hierarchy for a reparent.

type SessionLineageUpdate

type SessionLineageUpdate struct {
	SessionID string
	Lineage   SessionLineage
	UpdatedAt time.Time
}

SessionLineageUpdate replaces the hierarchy fields of one session's lineage: parent, root, depth, kind, and auto-stop. Governance fields stay untouched.

type SessionListQuery

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

SessionListQuery filters session index queries through one explicit profile or the AllProfiles aggregate.

func (SessionListQuery) Validate

func (q SessionListQuery) Validate() error

Validate rejects an implicit profile lens before checking query bounds.

type SessionLivenessMeta

type SessionLivenessMeta struct {
	SubprocessPID       int                  `json:"subprocess_pid,omitzero"`
	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,omitzero"`
}

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 SessionMessageLedger

type SessionMessageLedger interface {
	// SessionMessageWindow counts the sender's admissions into the target session created at or after since.
	SessionMessageWindow(
		ctx context.Context,
		targetWorkspaceID, targetSessionID, senderSessionID string,
		since time.Time,
	) (SessionMessageWindow, error)
	// LookupSessionPromptAdmissionByMessageID reads one admission by its message identity.
	LookupSessionPromptAdmissionByMessageID(
		ctx context.Context,
		workspaceID, sessionID, messageID string,
	) (SessionPromptAdmission, bool, error)
}

SessionMessageLedger reads durable session-message admissions for the agent messaging guards.

type SessionMessageWindow

type SessionMessageWindow struct {
	Count    int
	OldestAt time.Time
}

SessionMessageWindow summarizes one sender's admitted messages to a target inside a rate window.

type SessionMeta

type SessionMeta struct {
	PermissionModeDegraded   bool                    `json:"permission_mode_degraded,omitzero"`
	EffectiveSessionApproval string                  `json:"effective_session_approval,omitempty"`
	PermissionRules          []SessionPermissionRule `json:"permission_rules,omitempty"`
	InitiatorKind            string                  `json:"initiator_kind,omitempty"`
	InitiatorID              string                  `json:"initiator_id,omitempty"`
	EffectiveWorkspaceAccess string                  `json:"effective_workspace_access"`
	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"`
	*SessionRuntimeDetails
	SpeedResolution   *speedpkg.Resolution     `json:"speed_resolution,omitzero"`
	RuntimeStatus     SessionRuntimeStatus     `json:"runtime_status"`
	RuntimeTransition SessionRuntimeTransition `json:"runtime_transition,omitempty"`
	RuntimeGeneration int64                    `json:"runtime_generation,omitzero"`
	*SessionRuntimeBindingState
	*SessionProviderExecutionState
	ProfileID   string `json:"profile_id"`
	WorkspaceID string `json:"workspace_id,omitempty"`
	*SessionExecutionLocationState
	// Absent in older documents: their persisted execution location remains unchanged.
	WorktreeTransition *SessionWorktreeTransition `json:"worktree_transition,omitzero"`
	// Completed move provenance gates cleanup after the open journal is deleted.
	CompletedProfileMove *SessionProfileMove `json:"completed_profile_move,omitzero"`

	SessionType            string          `json:"session_type,omitempty"`
	Lineage                *SessionLineage `json:"lineage,omitzero"`
	State                  string          `json:"state"`
	StopReason             *StopReason     `json:"stop_reason,omitzero"`
	StopEscalated          bool            `json:"stop_escalated,omitzero"`
	StopVerificationFailed bool            `json:"stop_verification_failed,omitzero"`
	StopDetail             string          `json:"stop_detail,omitempty"`
	Failure                *SessionFailure `json:"failure,omitempty"`
	ACPSessionID           *string         `json:"acp_session_id,omitzero"`
	// AcceptedRoute is the binding ACP accepted; it is written with ACPSessionID and
	// cleared with it, and drives resume affinity.
	AcceptedRoute *SessionAcceptedRoute `json:"accepted_route,omitzero"`
	Liveness      *SessionLivenessMeta  `json:"liveness,omitzero"`
	// RestartBoundary snapshots the last dispatched turn without adding transcript events.
	// Older metadata omits it and is recovered from the existing prompt history.
	RestartBoundary *SessionRestartCheckpoint `json:"restart_boundary,omitzero"`
	// Derivation and ImportedContext are present only on continued or forked children.
	Derivation      *SessionDerivation      `json:"derivation,omitzero"`
	ImportedContext *SessionImportedContext `json:"imported_context,omitzero"`

	CreationProfile    *SessionCreationProfile `json:"creation_profile,omitzero"`
	CreationOptions    *SessionCreationOptions `json:"creation_options,omitzero"`
	CreationProfileRef string                  `json:"creation_profile_ref,omitempty"`
	PolicySpecDigest   string                  `json:"policy_spec_digest,omitempty"`
	CreationDigest     string                  `json:"creation_digest,omitempty"`
	*SessionAdvertisedCommandState

	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"`
}

func ReadSessionMeta

func ReadSessionMeta(path string) (SessionMeta, error)

ReadSessionMeta loads a session metadata document from disk.

func (*SessionMeta) ACPOptionsValue

func (m *SessionMeta) ACPOptionsValue() []SessionACPOptionSelection

ACPOptionsValue returns the persisted session option selections.

func (*SessionMeta) AdvertisedCommandsValue

func (m *SessionMeta) AdvertisedCommandsValue() []SessionAdvertisedCommand

AdvertisedCommandsValue returns the optional advertised command catalog.

func (*SessionMeta) CWDValue

func (m *SessionMeta) CWDValue() string

CWDValue returns the optional execution directory without exposing nil embedding details.

func (*SessionMeta) DatabaseOwner

func (m *SessionMeta) DatabaseOwner() (SessionDBOwner, error)

DatabaseOwner preserves the immutable events.db identity after catalog scope migrates to Global. The catalog must still authorize this metadata witness.

func (*SessionMeta) EffectivePermissionsValue

func (m *SessionMeta) EffectivePermissionsValue() string

EffectivePermissionsValue returns the persisted permission mode.

func (*SessionMeta) EffectiveProviderAuthModeValue

func (m *SessionMeta) EffectiveProviderAuthModeValue() string

EffectiveProviderAuthModeValue returns the persisted provider authentication owner.

func (*SessionMeta) PendingResumeReplayValue

func (m *SessionMeta) PendingResumeReplayValue() string

func (*SessionMeta) RuntimeFailureValue

func (m *SessionMeta) RuntimeFailureValue() string

RuntimeFailureValue returns the normalized persisted runtime diagnostic.

func (*SessionMeta) RuntimeRecoveryValue

func (m *SessionMeta) RuntimeRecoveryValue() *SessionRuntimeRecovery

RuntimeRecoveryValue returns independent persisted recovery metadata.

func (*SessionMeta) RuntimeSelectionValue

func (m *SessionMeta) RuntimeSelectionValue() *SessionRuntimeSelectionState

RuntimeSelectionValue returns the persisted runtime selection state without exposing nil embedding details.

func (*SessionMeta) SetACPOptions

func (m *SessionMeta) SetACPOptions(selections []SessionACPOptionSelection)

SetACPOptions stores an ownership-safe session option selection set.

func (*SessionMeta) SetAdvertisedCommands

func (m *SessionMeta) SetAdvertisedCommands(commands []SessionAdvertisedCommand)

SetAdvertisedCommands stores an ownership-safe advertised command catalog.

func (*SessionMeta) SetCWD

func (m *SessionMeta) SetCWD(cwd string)

SetCWD updates the optional execution directory with value semantics.

func (*SessionMeta) SetEffectivePermissions

func (m *SessionMeta) SetEffectivePermissions(permissions string)

SetEffectivePermissions updates the optional persisted permission mode.

func (*SessionMeta) SetEffectiveProviderAuthMode

func (m *SessionMeta) SetEffectiveProviderAuthMode(mode string)

SetEffectiveProviderAuthMode updates the optional provider authentication owner.

func (*SessionMeta) SetPendingResumeReplay

func (m *SessionMeta) SetPendingResumeReplay(block string)

func (*SessionMeta) SetRuntimeFailure

func (m *SessionMeta) SetRuntimeFailure(failure string)

SetRuntimeFailure updates the optional runtime diagnostic with value semantics.

func (*SessionMeta) SetRuntimeRecovery

func (m *SessionMeta) SetRuntimeRecovery(recovery *SessionRuntimeRecovery)

SetRuntimeRecovery stores independent persisted recovery metadata.

func (*SessionMeta) SetRuntimeSelection

func (m *SessionMeta) SetRuntimeSelection(selection *SessionRuntimeSelectionState)

SetRuntimeSelection updates the optional runtime selection state with value semantics.

func (*SessionMeta) SetWorktreeID

func (m *SessionMeta) SetWorktreeID(worktreeID string)

SetWorktreeID updates the optional worktree binding with value semantics.

func (*SessionMeta) Validate

func (m *SessionMeta) Validate() error

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

func (*SessionMeta) WorktreeIDValue

func (m *SessionMeta) WorktreeIDValue() string

WorktreeIDValue returns the optional worktree binding without exposing nil embedding details.

type SessionNativeBootstrap

type SessionNativeBootstrap struct {
	ACPSessionID       string     `json:"acp_session_id"`
	Provider           string     `json:"provider"`
	AuthMode           string     `json:"auth_mode"`
	HomePolicy         string     `json:"home_policy"`
	CommandFingerprint string     `json:"command_fingerprint"`
	State              string     `json:"state"`
	Error              string     `json:"error,omitempty"`
	SettledAt          *time.Time `json:"settled_at,omitempty"`
}

SessionNativeBootstrap pins a native clone id to the provider identity it loads under.

type SessionOwner

type SessionOwner struct {
	SessionID        string
	ProfileID        string
	WorkspaceID      string
	DatabaseOwner    SessionDBOwner
	CreationIdentity *SessionCreationIdentity
}

SessionOwner separates current catalog scope from immutable events.db ownership. A migrated Global session retains its original database owner in its creation witness.

func LookupSessionOwner

func LookupSessionOwner(
	ctx context.Context,
	catalog SessionCatalogOwnerReader,
	creations SessionCreationStore,
	sessionID string,
) (SessionOwner, error)

LookupSessionOwner proves current scope and database ownership from the durable catalog. Global history requires its retained, content-verified creation witness.

func (SessionOwner) BindMetadata

func (o SessionOwner) BindMetadata(meta *SessionMeta) error

BindMetadata proves the immutable owner before applying migrated catalog scope to an in-memory read. It does not rewrite metadata or its creation witness.

type SessionPendingRoute

type SessionPendingRoute struct {
	Index              int                         `json:"index"`
	Provider           string                      `json:"provider"`
	Model              string                      `json:"model"`
	ReasoningEffort    string                      `json:"reasoning_effort,omitempty"`
	Speed              speedpkg.Speed              `json:"speed,omitempty"`
	ACPOptions         []SessionACPOptionSelection `json:"acp_options,omitempty"`
	CommandFingerprint string                      `json:"command_fingerprint,omitempty"`
}

SessionPendingRoute is the declared route chosen at derive time, applied at the child's first bind. Index is 1-based in the target agent's fallback_chain.

func CloneSessionPendingRoute

func CloneSessionPendingRoute(route *SessionPendingRoute) *SessionPendingRoute

CloneSessionPendingRoute deep-copies a pending route.

type SessionPermissionPolicy

type SessionPermissionPolicy struct {
	Tools          []string `json:"tools"`
	Skills         []string `json:"skills"`
	MCPServers     []string `json:"mcp_servers"`
	WorkspacePaths []string `json:"workspace_paths"`
	// Materialized fields distinguish generated delegation budgets from authored ceilings.
	// They are internal persistence metadata and are omitted by public contract mappers.
	MaterializedTools      bool `json:"materialized_tools,omitempty"`
	MaterializedMCPServers bool `json:"materialized_mcp_servers,omitempty"`
}

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 SessionPermissionRule

type SessionPermissionRule struct {
	Kind     string `json:"kind,omitempty"`
	Path     string `json:"path,omitempty"`
	Decision string `json:"decision"`
}

SessionMeta is the atomically-written session metadata document.

type SessionPlacement

type SessionPlacement struct {
	SessionID      string
	FolderID       string
	Position       int
	FolderPosition int
}

SessionPlacement is one session's folder membership and manual position. FolderID is empty for a session pinned in the workspace root.

type SessionProfileMove

type SessionProfileMove struct {
	SessionID       string
	WorkspaceID     string
	ProfileID       string
	TargetProfileID string
	// CopyKey is the derive idempotency key of the copy in the target profile.
	CopyKey string
	// SourceWorktreeID, Branch, and HeadSHA are the source checkout; empty without one.
	SourceWorktreeID string
	Branch           string
	HeadSHA          string
	// TargetWorktreeID is the copy's checkout; RestoreWorktreeID is the checkout a
	// rollback creates for the source when its own was already released.
	TargetWorktreeID  string
	RestoreWorktreeID string
	CreatedAt         time.Time
	UpdatedAt         time.Time
}

SessionProfileMove journals one open move of a session to another profile. It is written before the source is archived and deleted once the move completes or rolls back. Every id is chosen before the step that creates it, so the move's progress reads from durable state: the archive flag, the worktree rows, and the copy's derive receipt under CopyKey.

type SessionProfileMoveStore

type SessionProfileMoveStore interface {
	// InsertSessionProfileMove fails with ErrSessionProfileMoveExists when the session
	// already has an open move.
	InsertSessionProfileMove(ctx context.Context, move SessionProfileMove) error
	SessionProfileMove(ctx context.Context, sessionID string) (SessionProfileMove, bool, error)
	ListSessionProfileMoves(ctx context.Context) ([]SessionProfileMove, error)
	// SetSessionProfileMoveRestoreWorktree replaces the restore checkout id after a
	// restore attempt left its row unusable.
	SetSessionProfileMoveRestoreWorktree(ctx context.Context, sessionID string, worktreeID string) error
	DeleteSessionProfileMove(ctx context.Context, sessionID string) error
	// CloseCompletedSessionProfileMove deletes the row only while the copy its derive
	// receipt names still exists, in one statement, so a concurrent delete of the copy
	// either lands first (and the move rolls back) or deletes a completed move's copy.
	CloseCompletedSessionProfileMove(ctx context.Context, sessionID string) (bool, error)
}

SessionProfileMoveStore persists the move-to-profile journal.

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
	// MentionsJSON is the JSON array of resolved composer mentions; blank persists as [].
	MentionsJSON string
	// HumanIngress records that the human operator authored this input; unknown or agent authorship is false.
	HumanIngress        bool
	Origin              json.RawMessage
	Attachments         []SessionInputAttachment
	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 {
	// InstanceTarget fences a named send against the current main inside admission.
	InstanceTarget *InstancePromptTarget
	// HumanSpawnOrigin inherits dispatch class only, never human permission or mention authority.
	HumanSpawnOrigin bool
	// DirectDispatch marks a prompt admitted against an idle session: its turn starts
	// directly, so a steer busy-mode default never applies and it carries reports.
	DirectDispatch           bool
	ID                       string
	WorkspaceID              string
	SessionID                string
	MessageID                string
	IdempotencyKey           string
	Operation                string
	FingerprintVersion       string
	RequestFingerprint       string
	LegacyRequestFingerprint string
	Mode                     string
	AuthoredText             string
	Runtime                  SessionInputRuntime
	SkillInvocations         []commandpkg.Invocation
	// MentionsJSON is the JSON array of resolved composer mentions; blank persists as [].
	MentionsJSON string
	// HumanIngress records that the human operator authored this input; unknown or agent authorship is false.
	HumanIngress bool
	Origin       json.RawMessage
	Attachments  []SessionInputAttachment
	TurnID       string
	EventID      string
	Now          time.Time
}

SessionPromptAdmissionRequest carries immutable command identity and request material.

func (SessionPromptAdmissionRequest) Normalize

Normalize trims scalar and attachment fields, clones slices, and normalizes the request clock to UTC.

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,omitzero"`
	QueueGeneration       int64             `json:"queue_generation,omitzero"`
	HeldReason            string            `json:"held_reason,omitempty"`
	HeldInstanceID        string            `json:"held_instance_id,omitempty"`
	Delivery              string            `json:"delivery,omitempty"`
	SteerDelivery         SteerDeliveryMode `json:"steer_delivery,omitempty"`
	PreviousTurnID        string            `json:"previous_turn_id,omitempty"`
	NewTurnID             string            `json:"new_turn_id,omitempty"`
	CanceledQueuedEntries int               `json:"canceled_queued_entries,omitzero"`
	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 SessionPromptReport

type SessionPromptReport struct {
	ID         string          `json:"report_id"`
	InstanceID string          `json:"instance_id"`
	SourceKey  string          `json:"source_key"`
	Kind       string          `json:"kind"`
	Payload    json.RawMessage `json:"payload"`
}

type SessionProviderExecutionState

type SessionProviderExecutionState struct {
	EffectivePermissions      string `json:"effective_permissions,omitempty"`
	EffectiveProviderAuthMode string `json:"effective_provider_auth_mode,omitempty"`
}

SessionProviderExecutionState keeps resolved provider execution settings compact inside SessionMeta. Embedding preserves the flat session metadata JSON contract.

type SessionRestartCheckpoint

type SessionRestartCheckpoint struct {
	TurnID          string                `json:"turn_id"`
	RuntimeRevision int64                 `json:"runtime_revision,omitempty"`
	Delivery        string                `json:"delivery,omitempty"`
	PolicyDigest    string                `json:"policy_digest,omitempty"`
	Route           *SessionAcceptedRoute `json:"route,omitzero"`
	Permissions     string                `json:"permissions,omitempty"`
	WorktreeID      string                `json:"worktree_id,omitempty"`
	CWD             string                `json:"cwd,omitempty"`
	Reason          string                `json:"reason,omitempty"`
}

SessionRestartCheckpoint binds recovery to the policy and route accepted at dispatch.

func CloneSessionRestartCheckpoint

func CloneSessionRestartCheckpoint(checkpoint *SessionRestartCheckpoint) *SessionRestartCheckpoint

CloneSessionRestartCheckpoint isolates a persisted recovery snapshot from later routing changes.

type SessionRuntimeBindingState

type SessionRuntimeBindingState struct {
	RuntimeFailure      *string                       `json:"runtime_failure,omitzero"`
	RuntimeSelection    *SessionRuntimeSelectionState `json:"runtime_selection,omitzero"`
	PendingResumeReplay string                        `json:"pending_resume_replay,omitempty"`
}

SessionRuntimeBindingState keeps optional runtime failure and selection state compact inside SessionMeta. Embedding preserves the flat session metadata JSON contract.

type SessionRuntimeDetails

type SessionRuntimeDetails struct {
	ACPOptions      []SessionACPOptionSelection `json:"acp_options,omitempty"`
	RuntimeRecovery *SessionRuntimeRecovery     `json:"runtime_recovery,omitzero"`
}

SessionRuntimeDetails keeps optional ACP selections and recovery metadata compact while preserving their flat session metadata JSON fields.

type SessionRuntimeRecovery

type SessionRuntimeRecovery struct {
	Reason        SessionRuntimeRecoveryReason `json:"reason,omitempty"`
	Attempt       int                          `json:"attempt"`
	MaxAttempts   int                          `json:"max_attempts"`
	Generation    int64                        `json:"generation"`
	StartedAt     time.Time                    `json:"started_at"`
	LastAttemptAt time.Time                    `json:"last_attempt_at"`
	NextAttemptAt *time.Time                   `json:"next_attempt_at,omitempty"`
	LastError     string                       `json:"last_error,omitempty"`
}

SessionRuntimeRecovery is the durable projection of an automatic runtime recovery attempt.

func CloneSessionRuntimeRecovery

func CloneSessionRuntimeRecovery(recovery *SessionRuntimeRecovery) *SessionRuntimeRecovery

CloneSessionRuntimeRecovery returns an ownership-safe recovery projection.

type SessionRuntimeRecoveryReason

type SessionRuntimeRecoveryReason string

SessionRuntimeRecoveryReason names the failure an automatic recovery is waiting out.

const (
	// SessionRuntimeRecoveryRuntimeExit replaces a provider runtime that exited or disconnected mid-turn.
	SessionRuntimeRecoveryRuntimeExit SessionRuntimeRecoveryReason = "runtime_exit"
	// SessionRuntimeRecoveryProviderAuth waits for a provider sign-in that went missing mid-turn.
	SessionRuntimeRecoveryProviderAuth SessionRuntimeRecoveryReason = "provider_auth"
)

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"`
	ACPOptions      []SessionACPOptionSelection `json:"acp_options,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,omitzero"`
	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"
	SessionRuntimeRecovering    SessionRuntimeStatus = "recovering"
	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"
	SessionRuntimeTransitionAutomaticRecovery  SessionRuntimeTransition = "automatic_recovery"
)

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,omitzero"`
}

SessionSpawnBudget captures durable spawn limits attached to a session. A zero MaxChildren or MaxDepth means unset; EffectiveSessionSpawnBudget resolves it.

func DecodeSessionSpawnBudget

func DecodeSessionSpawnBudget(raw string) (SessionSpawnBudget, error)

DecodeSessionSpawnBudget unmarshals budget metadata from the global session catalog.

func EffectiveSessionSpawnBudget

func EffectiveSessionSpawnBudget(budget SessionSpawnBudget) SessionSpawnBudget

EffectiveSessionSpawnBudget resolves unset caps to the defaults the spawn engine enforces, so every read surface reports the budget that actually applies.

type SessionStateUpdate

type SessionStateUpdate struct {
	ID                       string
	State                    string
	ACPSessionID             *string
	RuntimeSet               bool
	Provider                 string
	Model                    string
	ReasoningEffort          string
	Speed                    speedpkg.Speed
	ACPOptions               []SessionACPOptionSelection
	SpeedResolution          *speedpkg.Resolution
	RuntimeStatus            SessionRuntimeStatus
	RuntimeTransition        SessionRuntimeTransition
	RuntimeFailure           string
	RuntimeGeneration        int64
	RuntimeRecovery          *SessionRuntimeRecovery
	SelectedRuntimeSet       bool
	SelectedRuntime          *SessionRuntimeSelection
	RuntimeSelectionRevision int64
	StopReasonSet            bool
	StopReason               *string
	StopEscalated            bool
	StopVerificationFailed   bool
	StopDetail               string
	FailureSet               bool
	Failure                  *SessionFailure
	AttentionTransition      bool
	Liveness                 *SessionLivenessMeta

	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 SessionSubagent

type SessionSubagent struct {
	Isolation string
	Worktree  *SubagentWorktreeState
	// Usage is the provider's running total; nil until it reports one.
	Usage *SubagentUsage

	ID                 string
	WorkspaceID        string
	ParentSessionID    string
	ParentTurnID       string
	ParentToolCallID   string
	ChildSessionID     *string
	Origin             string
	ProviderToolCallID string
	IdempotencyKey     string
	RequestFingerprint string
	Title              string
	Role               string
	// These three share one word: the row sits right below the hugeParam limit.
	TaskChars       int32
	ResultTruncated bool
	ChildActivity   SubagentChildActivity
	// PendingTask holds the child's first-prompt text from reserve until the
	// first prompt is admitted (MarkFirstPromptAdmitted clears it), so boot
	// recovery can re-admit it. NULL afterwards; the task then lives in the
	// child transcript.
	PendingTask        *string
	RuntimeAgent       string
	RuntimeProvider    string
	RuntimeModel       string
	RuntimeEffort      string
	RuntimeSpeed       string
	Depth              int
	Status             string
	WorkState          string
	Progress           string
	Result             *string
	Error              *string
	WakePolicy         string
	Delivery           string
	WakeMessageID      *string
	AcknowledgedTurnID string
	StartedAt          *time.Time
	SettledAt          *time.Time
	CreatedAt          time.Time
	UpdatedAt          time.Time
}

func (SessionSubagent) WorktreeState

func (s SessionSubagent) WorktreeState() SubagentWorktreeState

WorktreeState returns the optional checkout state as a value, safe for shared rows.

type SessionSubagentWake

type SessionSubagentWake struct {
	WakeMessageID   string
	WorkspaceID     string
	ParentSessionID string
	State           string
	Route           string
	InputEntryID    string
	SteerRequeued   bool
	Attempts        int
	CreatedAt       time.Time
	UpdatedAt       time.Time
}

SessionSubagentWake is one batched parent wake (mailbox pointer turn or steer).

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 SessionTreeArchive

type SessionTreeArchive struct {
	Root        SessionInfo
	Descendants []SessionInfo
}

SessionTreeArchive is one session tree after ArchiveSessionTree.

type SessionTreeStore

type SessionTreeStore interface {
	ListSessionDescendants(ctx context.Context, workspaceID string, sessionID string) ([]SessionInfo, error)
	ArchiveSessionTree(ctx context.Context, workspaceID string, sessionID string) (SessionTreeArchive, error)
}

SessionTreeStore owns the session list hierarchy below one session: children recursively, within the root's workspace and profile. Continued and forked sessions and daemon-internal children are never members.

type SessionWorkLink struct {
	SessionID       string
	WorkspaceID     string
	Repository      string
	Branch          string
	PRNumber        int
	WorktreeID      string
	WorktreeName    string
	Provenance      string
	Unlinked        bool
	WorktreeRemoved bool
}

SessionWorkLink retains identity independently of worktree lifetime. Unlinked rows are tombstones so automatic discovery cannot undo a user's removal.

type SessionWorkMember

type SessionWorkMember struct{ RootID, ID, WorkspaceID, ProfileID, Name, WorktreeID, WorktreeName string }

type SessionWorktreeBindingStore

type SessionWorktreeBindingStore interface {
	UpdateSessionWorktreeBinding(context.Context, SessionWorktreeBindingUpdate) error
	RecoverSessionWorktreeBinding(context.Context, SessionWorktreeBindingUpdate) error
}

type SessionWorktreeBindingUpdate

type SessionWorktreeBindingUpdate struct {
	SessionID          string
	WorkspaceID        string
	ProfileID          string
	ExpectedWorktreeID string
	WorktreeID         string
	UpdatedAt          time.Time
}

type SessionWorktreeTransition

type SessionWorktreeTransition struct {
	Previous      SessionExecutionLocationState `json:"previous"`
	Current       SessionExecutionLocationState `json:"current"`
	Pending       bool                          `json:"pending,omitzero"`
	NoticePending bool                          `json:"notice_pending,omitzero"`
}

SessionWorktreeTransition records an accepted change until both stores converge.

func CloneSessionWorktreeTransition

func CloneSessionWorktreeTransition(value *SessionWorktreeTransition) *SessionWorktreeTransition

type SkillExposureOwnerScope

type SkillExposureOwnerScope string

SkillExposureOwnerScope identifies the shared owner of one provider-root link.

const (
	SkillExposureOwnerUser      SkillExposureOwnerScope = "user"
	SkillExposureOwnerWorkspace SkillExposureOwnerScope = "workspace"
)

type SkillExposureRecord

type SkillExposureRecord struct {
	ID           int64
	SkillName    string
	CanonicalDir string
	TargetSlug   string
	LinkPath     string
	LinkTarget   string
	OwnerScope   SkillExposureOwnerScope
	WorkspaceID  string
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

SkillExposureRecord is the durable ownership proof for one created skill link.

type SkillExposureRepository

type SkillExposureRepository interface {
	CreateSkillExposure(context.Context, SkillExposureRecord) (SkillExposureRecord, error)
	GetSkillExposureByOwnerTarget(
		context.Context,
		string,
		SkillExposureOwnerScope,
		string,
		string,
	) (SkillExposureRecord, error)
	ListSkillExposuresByOwner(
		context.Context,
		string,
		SkillExposureOwnerScope,
		string,
	) ([]SkillExposureRecord, error)
	ListSkillExposuresByCanonicalDir(context.Context, string) ([]SkillExposureRecord, error)
	DeleteSkillExposure(context.Context, int64) error
}

SkillExposureRepository persists exposure ownership independently from link health.

type SteerDeliveryMode

type SteerDeliveryMode string
const (
	SteerDeliveryInjected          SteerDeliveryMode = "injected"
	SteerDeliveryPendingBoundary   SteerDeliveryMode = "pending_boundary"
	SteerDeliveryAfterTurn         SteerDeliveryMode = "after_turn"
	SteerDeliveryPendingInjection  SteerDeliveryMode = "pending_injection"
	SteerDeliveryInterruptFallback SteerDeliveryMode = "interrupt_fallback"
)

func (SteerDeliveryMode) Validate

func (m SteerDeliveryMode) Validate() error

Validate accepts known delivery modes and the unset value used before negotiation.

type StopReason

type StopReason string
const (
	StopCompleted      StopReason = "completed"
	StopOwnerReleased  StopReason = "owner_released"
	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 SubagentChildActivity

type SubagentChildActivity uint8

SubagentChildActivity describes a delegated child session's liveness, independent of the row's (possibly terminal) status. Unknown covers provider-native rows and rows written before the field existed. It is a byte (persisted as its String form) so SessionSubagent stays within the pass-by-value size budget.

const (
	SubagentChildActivityUnknown SubagentChildActivity = iota
	SubagentChildActivityWorking
	SubagentChildActivityIdle
	SubagentChildActivityStopped
)

func ParseSubagentChildActivity

func ParseSubagentChildActivity(value string) (SubagentChildActivity, error)

ParseSubagentChildActivity reads the persisted form; empty is unknown.

func (SubagentChildActivity) String

func (a SubagentChildActivity) String() string

String returns the persisted and wire form; unknown is empty.

type SubagentDisposeFilter

type SubagentDisposeFilter struct {
	ParentSessionID string
	ParentTurnID    string   // "" = all turns of the parent
	IDs             []string // optional explicit set
}

SubagentDisposeFilter selects non-final deliveries to dispose.

type SubagentFinalize

type SubagentFinalize struct {
	WorktreeFacts   *SubagentWorktreeFacts
	ID              string
	Status          string
	WorkState       string
	ChildActivity   SubagentChildActivity
	Result          *string
	Error           *string
	ResultTruncated bool
	SettledAt       time.Time
}

SubagentFinalize settles a row to a terminal status.

type SubagentListQuery

type SubagentListQuery struct {
	WorkspaceID     string
	ParentSessionID string
	Origins         []string
	Statuses        []string
	// Order is SubagentOrderNewest (default) or SubagentOrderUrgency; urgency
	// applies to one parent's rows.
	Order  string
	Cursor string
	Limit  int
}

SubagentListQuery pages a parent's (or a workspace's) subagent rows, newest first.

type SubagentPage

type SubagentPage struct {
	Items      []SessionSubagent
	NextCursor string
}

SubagentPage is one page of subagent rows.

type SubagentStore

type SubagentStore interface {
	HasSubagentCommittedAdmission(ctx context.Context, workspaceID, childID, subagentID string) (bool, error)
	AssociateSubagentWorktree(ctx context.Context, row SessionSubagent) error
	SetSubagentWorktreeCleanup(ctx context.Context, id, state string) error
	ListSubagentWorktreeCleanupPending(ctx context.Context) ([]SessionSubagent, error)
	ReserveSubagent(ctx context.Context, row SessionSubagent) (SessionSubagent, bool, error)
	LinkChild(ctx context.Context, id, childSessionID string, startedAt time.Time) (SessionSubagent, error)
	// MarkFirstPromptAdmitted clears PendingTask once the child's first prompt is admitted.
	MarkFirstPromptAdmitted(ctx context.Context, id string) error
	// DeleteReserved removes a row still `queued` with no child (spawn.pre_create denial:
	// no session and no row, IT-022). It returns ErrSubagentNotFound for any other row.
	DeleteReserved(ctx context.Context, id string) error
	GetSubagent(ctx context.Context, workspaceID, id string) (SessionSubagent, error)
	GetSubagentByID(ctx context.Context, id string) (SessionSubagent, error)
	GetSubagentByChild(ctx context.Context, childSessionID string) (SessionSubagent, error)
	ListSubagents(ctx context.Context, q SubagentListQuery) (SubagentPage, error)
	Summaries(ctx context.Context, parentIDs []string) (map[string]SubagentSummary, error)
	UpdateProgress(ctx context.Context, id, progress string, at time.Time) error
	UpdateNativeSubagentTitle(ctx context.Context, id, title string, at time.Time) (SessionSubagent, bool, error)
	// UpdateNativeSubagentRuntime fills what a later streamed event of the launching call names.
	// An empty value keeps the recorded one.
	UpdateNativeSubagentRuntime(
		ctx context.Context, id, model, role string, at time.Time,
	) (SessionSubagent, bool, error)
	// UpdateSubagentUsage raises a native row's usage; totals never move backwards.
	UpdateSubagentUsage(
		ctx context.Context, id string, usage SubagentUsage, at time.Time,
	) (SessionSubagent, bool, error)
	UpdateSubagentState(ctx context.Context, id, status, workState string, at time.Time) (SessionSubagent, bool, error)
	ResumeNativeSubagent(ctx context.Context, id, turn string, at time.Time) (SessionSubagent, bool, error)
	FinalizeSubagent(ctx context.Context, in SubagentFinalize) (SessionSubagent, bool, error)
	// UpdateSubagentChildActivity records a delegated child's liveness; it never changes status.
	UpdateSubagentChildActivity(
		ctx context.Context, id string, activity SubagentChildActivity, at time.Time,
	) (SessionSubagent, bool, error)
	// ReconcileStoppedChildActivity marks settled delegated rows whose child session is stopped.
	ReconcileStoppedChildActivity(ctx context.Context) ([]SessionSubagent, error)

	OpenOrJoinWake(ctx context.Context, parentID string, ids []string, newWakeID string) (SessionSubagentWake, error)
	GetWake(ctx context.Context, wakeID string) (SessionSubagentWake, []SessionSubagent, error)
	ListWakesByParent(ctx context.Context, parentID string, states []string) ([]SessionSubagentWake, error)
	SetWakeInput(ctx context.Context, wakeID, route, inputEntryID string) error
	RewriteSubagentWakeInput(ctx context.Context, wakeID, text string, metadata json.RawMessage) error
	MarkWakeSteerRequeued(ctx context.Context, wakeID string) error
	MarkWakeDispatched(ctx context.Context, wakeID string) error
	FailWake(ctx context.Context, wakeID string) (SessionSubagentWake, []SessionSubagent, error)
	SettleWake(ctx context.Context, wakeID string, canceled bool) ([]SessionSubagent, error)
	SetPending(ctx context.Context, ids []string) error
	Acknowledge(ctx context.Context, id, observedTurnID string) (SessionSubagent, *SessionSubagentWake, error)
	Dispose(ctx context.Context, filter SubagentDisposeFilter) ([]SessionSubagent, error)
	UpgradeWakePolicy(ctx context.Context, id string) (SessionSubagent, error)

	ListStaleReserved(ctx context.Context, olderThan time.Time) ([]SessionSubagent, error)
	ListUnfinalizedDelegated(ctx context.Context) ([]SessionSubagent, error)
	ListUnfinalizedNative(ctx context.Context) ([]SessionSubagent, error)
	// EnrichNativeSubagentResult fills a terminal native row's missing result. It
	// never changes status, settlement, delivery, or child activity.
	EnrichNativeSubagentResult(ctx context.Context, in NativeSubagentResultEnrichment) (SessionSubagent, bool, error)
	// ListNativeReplayCandidates returns at most limit terminal native rows settled
	// since the cutoff, including rows with results, newest first, strictly
	// after the cursor (zero for the first page).
	ListNativeReplayCandidates(
		ctx context.Context, since time.Time, after NativeReplayCursor, limit int,
	) ([]SessionSubagent, error)
	ListOpenWakes(ctx context.Context) ([]SessionSubagentWake, error)
	ListPending(ctx context.Context, parentID string) ([]SessionSubagent, error)
	ListOrphanSubagentSessions(ctx context.Context) ([]string, error)
}

SubagentStore persists subagent rows and wake batches. Every wake/delivery transition runs in one transaction; callers hold the parent's mutex.

type SubagentSummary

type SubagentSummary struct {
	Live       int
	Resumed    int
	Total      int
	Failed     int
	Attention  int
	MostUrgent string
}

SubagentSummary is the per-parent roll-up exposed on session payloads. Live counts nonterminal rows, which gate parent settlement. Resumed counts settled delegations whose child session is working again: they display as running, so Failed leaves them out and MostUrgent treats them as live.

type SubagentUsage

type SubagentUsage struct {
	TotalTokens int64
	ToolUses    int64
}

SessionSubagent is the durable parent-side record of one subagent. SubagentUsage is what the provider reports a native subagent has spent so far.

type SubagentWorktreeFacts

type SubagentWorktreeFacts struct {
	HeadSHA                  string
	CommitsAhead, DirtyFiles *int
	ObservedAt               time.Time
	PRStatus, PRURL          string
	PRNumber                 *int
}

type SubagentWorktreeState

type SubagentWorktreeState struct {
	ID, Name, Branch, BaseRef, Path, BaseSHA, Cleanup string
	Facts                                             SubagentWorktreeFacts
}

SubagentWorktreeState is present only after an isolated checkout is associated.

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 TerminalApprovalCount

type TerminalApprovalCount struct {
	WorkspaceID string
	ProfileID   string
	Count       int
}

TerminalApprovalCount retains the exact workspace/profile intersection for shell badges.

type TokenStats

type TokenStats struct {
	ID               string
	SessionID        string
	AgentName        string
	CacheReadTokens  *int64
	CacheWriteTokens *int64
	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
	CacheReadTokens  *int64
	CacheWriteTokens *int64
	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
	ReportedCostAmount *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
	ProfileID    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 TokenUsageProfileTotal

type TokenUsageProfileTotal struct {
	ProfileID   string
	ProfileName string
	Color       string
	Icon        string
	Emoji       string
	Archived    bool
	TotalTokens int64
}

TokenUsageProfileTotal is one owner-labeled profile bucket inside a usage window.

type TranscriptAnchorReader

type TranscriptAnchorReader interface {
	TranscriptUserAnchor(ctx context.Context, messageID string) (TranscriptUserAnchor, error)
}

TranscriptAnchorReader resolves durable user-message anchors for non-destructive cuts.

type TranscriptUserAnchor

type TranscriptUserAnchor struct {
	MessageID     string
	TurnID        string
	StartSequence int64
	Complete      bool
}

TranscriptUserAnchor is a durable user message resolved to its turn. The lookup sits below rewind's destructive-eligibility rules: an archived prefix before the anchor does not invalidate it.

type TurnHistory

type TurnHistory struct {
	TurnID string
	Events []SessionEvent
}

TurnHistory groups ordered events by their turn identifier.

type TurnWriteAccount

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

TurnWriteAccount accumulates one turn's executed writes; safe for concurrent use. A nil account ignores Add.

func NewTurnWriteAccount

func NewTurnWriteAccount() *TurnWriteAccount

NewTurnWriteAccount returns an open account.

func (*TurnWriteAccount) Add

func (a *TurnWriteAccount) Add(d time.Duration)

Add counts one write of duration d; it is a no-op after Close.

func (*TurnWriteAccount) Close

func (a *TurnWriteAccount) Close() (flushes int64, total time.Duration)

Close stops accounting and returns the counted writes and their summed duration.

type WorkspaceAttentionSummary

type WorkspaceAttentionSummary struct {
	WorkspaceID string
	NeedsYou    int
	Finished    int
}

WorkspaceAttentionSummary is one exact workspace aggregate.

type WorkspaceFolder

type WorkspaceFolder struct {
	ID             string
	ProfileID      string
	Name           string
	Position       int
	WorkspaceCount int
	CreatedAt      time.Time
	UpdatedAt      time.Time
}

WorkspaceFolder is one named root folder that groups workspaces in one profile's All-projects sidebar.

type WorkspaceLayout

type WorkspaceLayout struct {
	Folders    []WorkspaceFolder
	Placements []WorkspacePlacement
}

WorkspaceLayout is one profile's complete workspace layout: folders in order, then placements ordered by container (folders first, root last).

type WorkspaceLayoutStore

type WorkspaceLayoutStore interface {
	WorkspaceLayout(ctx context.Context, profileID string) (WorkspaceLayout, error)
	CreateWorkspaceFolder(ctx context.Context, profileID string, id string, name string) (WorkspaceFolder, error)
	RenameWorkspaceFolder(ctx context.Context, profileID string, id string, name string) (WorkspaceFolder, error)
	DeleteWorkspaceFolder(ctx context.Context, profileID string, id string) error
	ReorderWorkspaceFolders(ctx context.Context, profileID string, ids []string) error
	MoveWorkspace(ctx context.Context, profileID string, workspaceID string, folderID string) error
	ReorderWorkspaces(ctx context.Context, profileID string, folderID string, workspaceIDs []string) error
}

WorkspaceLayoutStore persists root workspace folders and manual workspace order.

type WorkspacePlacement

type WorkspacePlacement struct {
	WorkspaceID string
	FolderID    string
	Position    int
}

WorkspacePlacement is one workspace's folder membership and manual position. WorkspaceID is empty for the User scope; FolderID is empty for a workspace pinned in the root.

type WorkspaceSessionCatalogFacets

type WorkspaceSessionCatalogFacets struct {
	WorkspaceID string
	Facets      SessionCatalogFacets
}

WorkspaceSessionCatalogFacets supplies each registered group's exact counts.

type WriteAttribution

type WriteAttribution struct {
	Turn      *TurnWriteAccount // nil outside a turn
	Coalesced bool
}

WriteAttribution names the turn a write counts toward and whether the write is a shared coalesced batch. It rides on the write's context as a value only; it never changes which context executes the write.

func WriteAttributionFrom

func WriteAttributionFrom(ctx context.Context) (WriteAttribution, bool)

WriteAttributionFrom returns the attribution attached to ctx.

type WriteContentionError

type WriteContentionError struct {
	Operation     string
	Phase         string
	Attempts      int
	Wait          time.Duration
	Owner         string
	TransactionID uint64
	OwnerElapsed  time.Duration
	Err           error
}

WriteContentionError preserves SQLite error identity and safe write provenance. Owner is empty when the lock belongs to an untracked transaction or another process; SQLite does not expose that owner's identity.

func (*WriteContentionError) Error

func (e *WriteContentionError) Error() string

func (*WriteContentionError) Unwrap

func (e *WriteContentionError) Unwrap() error

type WriteObservation

type WriteObservation struct {
	Operation     string
	Coalesced     bool
	Started       time.Time
	AdmissionWait time.Duration
	Duration      time.Duration
	Err           error
}

WriteObservation describes one finished ExecuteWrite or ExecuteWriteOperation call. Duration spans admission, every retry, and commit; AdmissionWait is the part spent waiting for write admission.

type WriteObserver

type WriteObserver func(context.Context, WriteObservation)

WriteObserver receives every finished write with the write caller's context. It runs on the writing goroutine and must not block. internal/store cannot import telemetry, so the composition root supplies it.

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 telemetrydb owns append-only observability independently of the core database.
Package telemetrydb owns append-only observability independently of the core database.
schema
Package schema embeds the telemetry schema and its independent migration history.
Package schema embeds the telemetry schema and its independent migration history.
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