Documentation
¶
Overview ¶
Package store provides shared persistence types, validation, and helper primitives.
Index ¶
- Constants
- Variables
- func AppendLimit(query string, args []any, limit int) (string, []any)
- func AppendWhere(query string, where []string) string
- func Apply(ctx context.Context, db *sql.DB, stream MigrationStream) error
- func BootWatermarkBinary() (string, error)
- func BootWatermarkBuildIdentity(release string, commit string, size int64, modTime int64, ...) (string, error)
- func BuildAndQuery(prefix string, suffix string, input ...Clause) (string, []any)
- func BuildClauses(input ...Clause) ([]string, []any)
- func BuildWhereQuery(prefix string, suffix string, input ...Clause) (string, []any)
- func Checkpoint(ctx context.Context, db *sql.DB) (retErr error)
- func CheckpointPassive(ctx context.Context, db *sql.DB) error
- func CheckpointPassiveConnection(ctx context.Context, connection *sql.Conn) error
- func CheckpointTruncateConnection(ctx context.Context, conn *sql.Conn) error
- func CloseCheckpointedDatabase(ctx context.Context, db *sql.DB, worker *PassiveCheckpointer) error
- func ContextWithMutationCommitFence(ctx context.Context, fence MutationCommitFence) context.Context
- func EncodeSessionPermissionPolicy(policy SessionPermissionPolicy) (string, error)
- func EncodeSessionSpawnBudget(budget SessionSpawnBudget) (string, error)
- func ExecuteWrite(ctx context.Context, db *sql.DB, fn func(context.Context, *WriteTx) error) error
- func ExecuteWriteOperation(ctx context.Context, db *sql.DB, operation string, ...) error
- func FormatNullableTimestamp(value time.Time) string
- func FormatTimestamp(value time.Time) string
- func HierarchyParentSessionID(lineage *SessionLineage) string
- func IsHumanSessionInputOriginClass(class string) bool
- func IsSQLiteBusy(err error) bool
- func IsSQLiteIdentityConstraint(err error) bool
- func IsStorageUnavailable(err error) bool
- func IsSubagentDeliveryFinal(delivery string) bool
- func IsSubagentStatusTerminal(status string) bool
- func LineageKindValues() []string
- func LocalDay(value time.Time) string
- func LocalDayStart(value time.Time, daysBack int) time.Time
- func LowerSessionCatalogSearchText(value string) string
- func MigrationStreamHead(stream MigrationStream) (string, error)
- func NewID(prefix string) (string, error)
- func NormalizeMentionsJSON(raw string) string
- func NormalizeSQLiteIdentifier(value string) (string, error)
- func NormalizeSessionFolderName(name string) (string, error)
- func NormalizeSessionLayoutIDs(ids []string, limit int) ([]string, error)
- func NormalizeSessionType(value string) string
- func NormalizeWorkspaceLayoutProfile(profileID string) (string, error)
- func NullFloat64(value sql.NullFloat64) *float64
- func NullInt64(value sql.NullInt64) *int64
- func NullString(value sql.NullString) *string
- func NullableFloat64(value *float64) any
- func NullableInt64(value *int64) any
- func NullableString(value string) any
- func NullableStringPointer(value *string) any
- func OpenSQLiteDatabase(ctx context.Context, path string, ...) (*sql.DB, error)
- func OpenSQLiteDatabaseWithPragmas(ctx context.Context, path string, pragmas []string, ...) (*sql.DB, error)
- func OpenSQLiteReadPool(ctx context.Context, path string, initializers ...SQLiteReadInitializer) (*sql.DB, error)
- func ParseNullableTimestamp(value string) (*time.Time, error)
- func ParseTimestamp(value string) (time.Time, error)
- func ReadBootWatermarks[T any](path string, profile string) map[string]T
- func RecoverSessionWorktreeTransition(ctx context.Context, catalog SessionWorktreeBindingStore, path string, ...) error
- func RefuseLegacyDatabaseAtPath(ctx context.Context, path string, stream MigrationStream) (err error)
- func ReplyWatchID(target, message string) string
- func RequireAutomationOverlayActive(ctx context.Context, tx workspaceAdmissionReader, kind, id string, ...) error
- func RequireAutomationWorkspaceActive(ctx context.Context, tx workspaceAdmissionReader, ...) error
- func RequireCurrent(ctx context.Context, db *sql.DB, stream MigrationStream) error
- func RequireWorkspaceActive(ctx context.Context, tx workspaceAdmissionReader, ids ...string) error
- func SQLNullString(value string) sql.NullString
- func SQLNullStringPointer(value *string) sql.NullString
- func SessionActivityIdleSeconds(meta *SessionActivityMeta, now time.Time) int64
- func SessionAdvertisedCommandsEqual(left SessionAdvertisedCommand, right SessionAdvertisedCommand) bool
- func SessionDBFile(sessionDir string) string
- func SessionInputOriginClassFor(ownerKind string, origin json.RawMessage) (class, senderSessionID string)
- func SessionMetaFile(sessionDir string) string
- func SessionRuntimeFailurePointer(value string) *string
- func SessionRuntimeFailureValue(value *string) string
- func SessionRuntimeRecoveryReasonValues() []string
- func SetWriteObserver(observer WriteObserver)
- func SqliteFilePath(path string) string
- func SteerDeliveryModeValues() []string
- func SubagentChildActivityValues() []string
- func SubagentUrgencyRank(row SessionSubagent) int
- func TryBootstrap(ctx context.Context, db *sql.DB, stream MigrationStream) (bool, error)
- func UpgradeSessionLineageKind(sessionType string, lineage *SessionLineage) bool
- func UpsertLoopOutputBlob(ctx context.Context, exec LoopOutputBlobExecutor, outputRef string, ...) error
- func ValidFailureKind(kind FailureKind) bool
- func ValidFailureReasonCode(code FailureReasonCode) bool
- func ValidPendingInteractionKind(kind string) bool
- func ValidPendingInteractionStatus(status string) bool
- func ValidStopReason(r StopReason) bool
- func ValidateChildSessionToolSubset(parent SessionPermissionPolicy, child SessionPermissionPolicy) error
- func ValidateMentionsJSON(raw string) error
- func ValidateSessionACPOptionSelections(selections []SessionACPOptionSelection) error
- func ValidateSessionInputRuntime(runtime SessionInputRuntime) error
- func ValidateSessionLineage(sessionID string, lineage *SessionLineage) error
- func ValidateSessionLineageForType(sessionType string, lineage *SessionLineage) error
- func ValidateSessionRuntime(status SessionRuntimeStatus, transition SessionRuntimeTransition, ...) error
- func ValidateSessionRuntimeRecovery(status SessionRuntimeStatus, generation int64, ...) error
- func ValidateSessionRuntimeSelection(selection *SessionRuntimeSelection, revision int64) error
- func ValidateSessionRuntimeSelectionState(state *SessionRuntimeSelectionState) error
- func WithMigrationLogger(ctx context.Context, logger *slog.Logger) context.Context
- func WithWALTruncation(thresholdBytes int64) func(*PassiveCheckpointer)
- func WithWriteAttribution(ctx context.Context, attribution WriteAttribution) context.Context
- func WriteBootWatermarks[T any](path string, profile string, entries map[string]T) error
- func WriteSessionMeta(path string, meta *SessionMeta) error
- type BackgroundWriteOperation
- type BackgroundWriter
- type Clause
- func ActiveWorkspaceClause(column, workspaceID string) Clause
- func Int64Clause(column string, op string, value int64) Clause
- func NotStringClause(column string, value string) Clause
- func OpaqueStringClause(column string, value string) Clause
- func ReadScopeClause(column string, scope ReadScope) Clause
- func ReadScopeCoalescedClause(columns []string, scope ReadScope) Clause
- func SessionWorkspaceClause(value string) Clause
- func StringClause(column string, value string) Clause
- func StringCompareClause(column string, op string, value string) Clause
- func TimeClause(column string, op string, value time.Time) Clause
- type ConversationRewindBaselineRefresher
- type ConversationRewindReader
- type ConversationRewindRequest
- type ConversationRewindResult
- type ConversationRewindState
- type ConversationRewindTarget
- type ConversationRewinder
- type DBTX
- type DeadEntity
- type DeadEntityKey
- type DeadEntityKind
- type DeadEntityStore
- type EventArchiveFilter
- type EventArchiveRequest
- type EventArchiveResult
- type EventArchiver
- type EventCloser
- type EventCorrelation
- type EventHourWeekdayBucket
- type EventMetadata
- type EventMetadataReadCloser
- type EventMetadataReader
- type EventQuery
- type EventReadCloser
- type EventReader
- type EventRecorder
- type EventSummary
- type EventSummaryBatchWriter
- type EventSummaryContentState
- type EventSummaryQuery
- type EventSummaryStore
- type EventWriter
- type FailureKind
- type FailureReasonCode
- type FileStamp
- type HookDispatchCounts
- type HookRunQuery
- type IndeterminatePromptReport
- type InstancePauseTrip
- type InstancePromptTarget
- type LineageKind
- type LongestSessionSample
- type LoopOutputBlobExecutor
- type MarketplaceCatalogEntry
- type MarketplaceCatalogReplacement
- type MarketplaceCatalogRepository
- type MarketplaceCatalogSnapshot
- type MarketplaceCatalogSourcesSnapshot
- type MarketplaceCatalogState
- type MarketplaceSourceConfiguration
- type MarketplaceSourceDefinition
- type MarketplaceSourceNameRetainedError
- type MigrationBootstrap
- type MigrationPlanSummary
- type MigrationQuerier
- type MigrationReconciliation
- type MigrationStepper
- type MigrationStream
- type MutationCommitFence
- type NativeReplayCursor
- type NativeSubagentResultEnrichment
- type ObservabilityRetentionSweepResult
- type OnboardingStatus
- type OnboardingStore
- type OverviewDayQuery
- type OverviewSinceQuery
- type OverviewWorkspaceQuery
- type PassiveCheckpointer
- type PendingInteraction
- type PendingInteractionCreate
- type PendingInteractionPayload
- type PendingInteractionTransition
- type PermissionDailyRollup
- type PermissionEntriesQuery
- type PermissionLogEntry
- type PermissionLogQuery
- type PermissionRollupQuery
- type ProfileAdmissionError
- type ProfileSessionCatalogFacets
- type ReadScope
- type ReconcileResult
- type ReplyWatch
- type ReplyWatchFilter
- type ReplyWatchFire
- type ReplyWatchRegistration
- type ReplyWatchStore
- type SQLiteCorruptionError
- type SQLiteReadInitializer
- type SessionACPOptionSelection
- type SessionAcceptedRoute
- type SessionActivityMeta
- type SessionAdvertisedCommand
- type SessionAdvertisedCommandInput
- type SessionAdvertisedCommandState
- type SessionAgentMetrics
- type SessionAgentMetricsQuery
- type SessionAgentMetricsReader
- type SessionArchiveFilter
- type SessionArchiveLiveMemberError
- type SessionArchiveStore
- type SessionAttach
- type SessionAttachRequest
- type SessionAttachState
- type SessionAttention
- type SessionAttentionCommit
- type SessionAttentionFence
- type SessionAttentionStore
- type SessionAttentionSummary
- type SessionAutomationRunCandidate
- type SessionAutomationRunReader
- type SessionBoardCounts
- type SessionBranchKey
- type SessionCatalog
- type SessionCatalogAttentionRank
- type SessionCatalogBranchReader
- type SessionCatalogFacetReader
- type SessionCatalogFacetResult
- type SessionCatalogFacets
- type SessionCatalogOwnerReader
- type SessionCatalogPage
- type SessionCatalogPageQuery
- type SessionCatalogPager
- type SessionCatalogPosition
- type SessionCatalogRelationReader
- type SessionCatalogRelations
- type SessionCatalogRelationsQuery
- type SessionChangeReconcileResult
- type SessionChangeReconciler
- type SessionCreationIdentity
- type SessionCreationIdentityStore
- type SessionCreationOptions
- type SessionCreationProfile
- func (p SessionCreationProfile) CanonicalJSON() ([]byte, error)
- func (p SessionCreationProfile) CreationDigest(opts SessionCreationOptions) (string, error)
- func (p SessionCreationProfile) MarshalJSON() ([]byte, error)
- func (p SessionCreationProfile) PolicySpecDigest() (string, error)
- func (p SessionCreationProfile) Ref() (string, error)
- func (p *SessionCreationProfile) UnmarshalJSON(data []byte) error
- func (p SessionCreationProfile) Validate() error
- type SessionCreationProfileStore
- type SessionCreationRegistration
- type SessionCreationStore
- type SessionDBOwner
- type SessionDerivation
- type SessionDerivationOutcome
- type SessionDerivationReceipt
- type SessionDerivationStore
- type SessionEvent
- type SessionEventMetadataOpener
- type SessionExecutionLocationState
- type SessionFailure
- type SessionFilesStamp
- type SessionFirstPrompt
- type SessionFolder
- type SessionImportedContext
- type SessionImportedContextConsumption
- type SessionInfo
- func (s *SessionInfo) ACPOptionsValue() []SessionACPOptionSelection
- func (s *SessionInfo) AttachExpiresAtValue() *time.Time
- func (s *SessionInfo) AttachedToValue() string
- func (s *SessionInfo) AttentionSnapshot() SessionAttention
- func (s *SessionInfo) LaterReturnedAtValue() *time.Time
- func (s *SessionInfo) LaterState() *SessionLater
- func (s *SessionInfo) RuntimeRecoveryValue() *SessionRuntimeRecovery
- func (s *SessionInfo) SetACPOptions(selections []SessionACPOptionSelection)
- func (s *SessionInfo) SetAttach(attachedTo string, expiresAt *time.Time)
- func (s *SessionInfo) SetRuntimeRecovery(recovery *SessionRuntimeRecovery)
- func (s *SessionInfo) Validate() error
- type SessionInputAttachment
- type SessionInputClearError
- type SessionInputClearRequest
- type SessionInputClearResult
- type SessionInputClearStore
- type SessionInputClearTrace
- type SessionInputCoalesce
- type SessionInputHold
- type SessionInputNotQueuedError
- type SessionInputQueueEntry
- type SessionInputQueueFullError
- type SessionInputQueueInsert
- type SessionInputQueueStore
- type SessionInputQueueSummary
- type SessionInputRuntime
- type SessionInputSyntheticPrompt
- type SessionLater
- type SessionLaterFilter
- type SessionLaterPark
- type SessionLaterReturn
- type SessionLaterStore
- type SessionLayoutScope
- type SessionLayoutStore
- type SessionLedgerRecord
- type SessionLineage
- type SessionLineageStore
- type SessionLineageUpdate
- type SessionListQuery
- type SessionLivenessMeta
- type SessionMessageLedger
- type SessionMessageWindow
- type SessionMeta
- func (m *SessionMeta) ACPOptionsValue() []SessionACPOptionSelection
- func (m *SessionMeta) AdvertisedCommandsValue() []SessionAdvertisedCommand
- func (m *SessionMeta) CWDValue() string
- func (m *SessionMeta) DatabaseOwner() (SessionDBOwner, error)
- func (m *SessionMeta) EffectivePermissionsValue() string
- func (m *SessionMeta) EffectiveProviderAuthModeValue() string
- func (m *SessionMeta) PendingResumeReplayValue() string
- func (m *SessionMeta) RuntimeFailureValue() string
- func (m *SessionMeta) RuntimeRecoveryValue() *SessionRuntimeRecovery
- func (m *SessionMeta) RuntimeSelectionValue() *SessionRuntimeSelectionState
- func (m *SessionMeta) SetACPOptions(selections []SessionACPOptionSelection)
- func (m *SessionMeta) SetAdvertisedCommands(commands []SessionAdvertisedCommand)
- func (m *SessionMeta) SetCWD(cwd string)
- func (m *SessionMeta) SetEffectivePermissions(permissions string)
- func (m *SessionMeta) SetEffectiveProviderAuthMode(mode string)
- func (m *SessionMeta) SetPendingResumeReplay(block string)
- func (m *SessionMeta) SetRuntimeFailure(failure string)
- func (m *SessionMeta) SetRuntimeRecovery(recovery *SessionRuntimeRecovery)
- func (m *SessionMeta) SetRuntimeSelection(selection *SessionRuntimeSelectionState)
- func (m *SessionMeta) SetWorktreeID(worktreeID string)
- func (m *SessionMeta) Validate() error
- func (m *SessionMeta) WorktreeIDValue() string
- type SessionNativeBootstrap
- type SessionOwner
- type SessionPendingRoute
- type SessionPermissionPolicy
- type SessionPermissionRule
- type SessionPlacement
- type SessionProfileMove
- type SessionProfileMoveStore
- type SessionPromptAdmission
- type SessionPromptAdmissionRequest
- type SessionPromptAdmissionResult
- type SessionPromptAdmissionStore
- type SessionPromptReport
- type SessionProviderExecutionState
- type SessionRestartCheckpoint
- type SessionRuntimeBindingState
- type SessionRuntimeDetails
- type SessionRuntimeRecovery
- type SessionRuntimeRecoveryReason
- type SessionRuntimeSelection
- func CloneSessionRuntimeSelection(selection *SessionRuntimeSelection) *SessionRuntimeSelection
- func NormalizeSessionRuntimeSelection(selection *SessionRuntimeSelection) *SessionRuntimeSelection
- func SessionRuntimeSelectionStateValues(state *SessionRuntimeSelectionState) (*SessionRuntimeSelection, int64)
- type SessionRuntimeSelectionState
- type SessionRuntimeStatus
- type SessionRuntimeTransition
- type SessionSoulSnapshotUpdate
- type SessionSpawnBudget
- type SessionStateUpdate
- type SessionSubagent
- type SessionSubagentWake
- type SessionTranscriptEpochStore
- type SessionTranscriptEpochUpdate
- type SessionTreeArchive
- type SessionTreeStore
- type SessionWorkLink
- type SessionWorkMember
- type SessionWorktreeBindingStore
- type SessionWorktreeBindingUpdate
- type SessionWorktreeTransition
- type SkillExposureOwnerScope
- type SkillExposureRecord
- type SkillExposureRepository
- type SteerDeliveryMode
- type StopReason
- type StreamStatus
- type SubagentChildActivity
- type SubagentDisposeFilter
- type SubagentFinalize
- type SubagentListQuery
- type SubagentPage
- type SubagentStore
- type SubagentSummary
- type SubagentUsage
- type SubagentWorktreeFacts
- type SubagentWorktreeState
- type TaskClosedDay
- type TaskDesignationRollup
- type TaskDesignationRollupQuery
- type TaskRunOutcomeDay
- type TerminalApprovalCount
- type TokenStats
- type TokenStatsCostSummary
- type TokenStatsQuery
- type TokenStatsUpdate
- type TokenUsage
- type TokenUsageAgentTotal
- type TokenUsageCostGroup
- type TokenUsageDailyUpdate
- type TokenUsageDay
- type TokenUsageProfileTotal
- type TranscriptAnchorReader
- type TranscriptUserAnchor
- type TurnHistory
- type TurnWriteAccount
- type WorkspaceAttentionSummary
- type WorkspaceFolder
- type WorkspaceLayout
- type WorkspaceLayoutStore
- type WorkspacePlacement
- type WorkspaceSessionCatalogFacets
- type WriteAttribution
- type WriteContentionError
- type WriteObservation
- type WriteObserver
- type WriteTx
- func (tx *WriteTx) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
- func (tx *WriteTx) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
- func (tx *WriteTx) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
- func (tx *WriteTx) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
Constants ¶
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" )
const ( PendingInteractionKindPermission = "permission" PendingInteractionKindClarify = "clarify" PendingInteractionStatusPending = "pending" PendingInteractionStatusOrphaned = "orphaned" PendingInteractionStatusResolved = "resolved" PendingInteractionStatusTimedOut = "timed_out" PendingInteractionStatusCanceled = "canceled" PendingInteractionTitleMaxBytes = 200 PendingInteractionPayloadMaxBytes = 4096 PendingInteractionResolutionMaxBytes = 240 PendingInteractionChoiceMaxBytes = 120 )
const ( PendingInteractionOutcomeApplied = "applied" PendingInteractionOutcomeAnswered = "answered" PendingInteractionOutcomeResolvedAfterRestart = "resolved-after-restart" PendingInteractionOutcomeAlreadyResolved = "already-resolved" PendingInteractionOutcomeQueueFull = "queue-full" )
const ( SessionBoardNeedsYou = "needs_you" SessionBoardWorking = "working" SessionBoardWaiting = "waiting" SessionBoardInReview = "in_review" SessionBoardDone = "done" )
const ( SessionInputAttachmentKindImage = attachmentspkg.KindImage SessionInputAttachmentKindFile = attachmentspkg.KindFile )
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.
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" )
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" )
const ( SessionInputQueueStatusQueued = "queued" SessionInputQueueStatusDispatching = "dispatching" SessionInputQueueStatusSent = "sent" SessionInputQueueStatusFailed = "failed" SessionInputQueueStatusCanceled = "canceled" )
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 )
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" )
const ( SessionNativeStatePending = "pending" SessionNativeStateLoaded = "loaded" SessionNativeStateFailed = "failed" )
Native bootstrap states of a native-fork child (settled at its first bind).
const ( SessionPromptOperationPrompt = "prompt" SessionPromptOperationSteer = "steer" SessionPromptAdmissionReserved = "reserved" SessionPromptAdmissionDispatchCommitted = "dispatch_committed" SessionPromptAdmissionCompleted = "completed" SessionPromptAdmissionIndeterminate = "indeterminate" )
const ( SessionPromptResultStatusAccepted = "accepted" SessionPromptResultStatusQueued = "queued" SessionPromptResultStatusSteering = "steering" SessionPromptResultStatusInterrupting = "interrupting" SessionPromptResultStatusCanceled = "canceled" )
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 )
const ( SubagentOriginDelegated = "delegated" SubagentOriginProviderNative = "provider_native" )
Subagent origins.
const ( SubagentStatusQueued = "queued" SubagentStatusRunning = "running" SubagentStatusWaiting = "waiting" SubagentStatusCompleted = "completed" SubagentStatusFailed = "failed" SubagentStatusCanceled = "canceled" SubagentStatusInterrupted = "interrupted" )
Subagent statuses. Terminal statuses are final.
const ( SubagentWorkStateWorking = "working" SubagentWorkStateWaitingForChildren = "waiting_for_children" SubagentWorkStateResultAvailable = "result_available" )
Subagent work states.
const ( SubagentDeliveryNone = "none" SubagentDeliveryPending = "pending" SubagentDeliveryClaimed = "claimed" SubagentDeliveryDelivered = "delivered" SubagentDeliveryAcknowledged = "acknowledged" SubagentDeliveryDisposed = "disposed" )
Subagent delivery states. Delivered, acknowledged, and disposed are final.
const ( SubagentWakePolicyAlways = "always" SubagentWakePolicySettledOnly = "settled_only" )
Subagent wake policies.
const ( SubagentWakeStateOpen = "open" SubagentWakeStateDispatched = "dispatched" SubagentWakeStateSettled = "settled" SubagentWakeStateCanceled = "canceled" SubagentWakeRouteQueue = "queue" SubagentWakeRouteSteer = "steer" )
Subagent wake batch states and routes.
const ( SubagentOrderNewest = "newest" SubagentOrderUrgency = "urgency" )
Subagent list orders.
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" )
const ( TokenCostStatusActual = "actual" TokenCostStatusEstimated = "estimated" TokenCostStatusIncluded = "included" TokenCostStatusUnknown = "unknown" TokenCostSourceAgentReported = "agent_reported" TokenCostSourceCatalogConfig = "catalog_config" TokenCostSourceModelsDev = "models_dev" TokenCostSourceBuiltin = "builtin" TokenCostSourceNone = "none" )
const ( SessionDerivationSeedReplay = "replay" SessionDerivationSeedNativeFork = "native_fork" SessionDerivationFirstPromptStaged = "staged" SessionDerivationFirstPromptAdmitted = "admitted" )
Derived-session seed modes and first-prompt states recorded in an outcome.
const ( // MaxWorkspaceFolders bounds one profile's root workspace folders. MaxWorkspaceFolders = 200 // MaxWorkspaceLayoutOrder bounds one manual workspace reorder request. MaxWorkspaceLayoutOrder = 500 )
const DefaultProfileID = "00000000000000000000000000"
DefaultProfileID is the permanent zero-ULID owner seeded by migration 00082.
const (
// DefaultSQLiteBusyTimeoutMS is the shared SQLite busy timeout in milliseconds.
DefaultSQLiteBusyTimeoutMS = defaultBusyTimeoutMS
)
const EmptyMentionsJSON = "[]"
EmptyMentionsJSON is the persisted mentions_json of an input without composer mentions.
const SessionCreationProfileVersion = 6
const SessionInputOwnerSynthetic = "synthetic"
SessionInputOwnerSynthetic identifies daemon-authored follow-ups in the shared queue.
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.
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.
const SessionManualUnplacedPosition = -1
SessionManualUnplacedPosition is the manual-sort position of a session without a placement; unplaced sessions lead their container.
const SubagentSpawnRole = "subagent"
SubagentSpawnRole marks child sessions created by subagent delegation.
const UserSessionCreationProfileVersion = 7
UserSessionCreationProfileVersion binds new User sessions to @user and a profile.
Variables ¶
var ( ErrMarketplaceCatalogGenerationStale = errors.New("marketplace catalog: source generation is stale") ErrMarketplaceSourceNameRetained = errors.New("marketplace_source_name_retained") )
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") )
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") )
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") )
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") )
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") )
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") )
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", ) )
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") )
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") )
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") )
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") )
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") )
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") )
var ErrInvalidDeadEntity = errors.New("store: invalid dead entity")
var ErrMigrationPlanInvalid = errors.New("store: embedded migration plan is invalid")
ErrMigrationPlanInvalid reports embedded migrations this binary cannot verify or compile.
var ErrReadScopeInvalid = errors.New("store: read scope is invalid")
var ErrSQLiteCorrupt = errors.New("store: sqlite database is corrupt")
var ErrSessionAttentionChanged = errors.New("store: session attention changed")
ErrSessionAttentionChanged rejects a dismissal whose observed occurrence was replaced.
var ( // ErrSessionCreationIdentityMismatch rejects adoption of a same-ID session with different creation truth. ErrSessionCreationIdentityMismatch = errors.New("store: session creation identity mismatch") )
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.
var ( // ErrSessionMetadataSchemaBehind reports metadata that predates the runtime binding contract. ErrSessionMetadataSchemaBehind = errors.New("store: session metadata schema is behind this binary") )
var ErrSessionProfileMoveExists = errors.New("store: session profile move already open")
ErrSessionProfileMoveExists reports an open move already journaled for the session.
var ErrSessionWorktreeConflict = errors.New("store: session worktree binding conflict")
var ErrWorkspaceArchived = errors.New("workspace is archived; unarchive it before starting work")
Functions ¶
func AppendLimit ¶
AppendLimit appends a LIMIT clause when the limit is positive.
func AppendWhere ¶
AppendWhere appends a WHERE block when any clauses are present.
func BootWatermarkBinary ¶
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 ¶
BuildAndQuery composes validated clauses after an existing WHERE boundary.
func BuildClauses ¶
BuildClauses compacts optional clauses into WHERE fragments and args.
func BuildWhereQuery ¶
BuildWhereQuery composes validated clauses after a new WHERE boundary.
func Checkpoint ¶
Checkpoint truncates the WAL for an open SQLite database.
func CheckpointPassive ¶
CheckpointPassive runs a non-truncating SQLite WAL checkpoint.
func CheckpointPassiveConnection ¶
CheckpointPassiveConnection runs a checkpoint on an already acquired connection. Owners can coordinate physical file mutation without opening a connection under their lease.
func CheckpointTruncateConnection ¶
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 ¶
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 ¶
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 ¶
FormatNullableTimestamp renders zero timestamps as empty strings for optional columns.
func FormatTimestamp ¶
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 ¶
IsHumanSessionInputOriginClass reports whether a class belongs to the human cap and priority tier.
func IsSQLiteBusy ¶
IsSQLiteBusy reports whether err is a SQLite BUSY or LOCKED condition.
func IsSQLiteIdentityConstraint ¶
IsSQLiteIdentityConstraint reports whether err is a primary-key or unique-key collision.
func IsStorageUnavailable ¶
IsStorageUnavailable identifies storage failures independently of provider or SQL contract failures.
func IsSubagentDeliveryFinal ¶
IsSubagentDeliveryFinal reports whether a delivery state can no longer change.
func IsSubagentStatusTerminal ¶
IsSubagentStatusTerminal reports whether status is final.
func LineageKindValues ¶
func LineageKindValues() []string
LineageKindValues returns every persisted lineage kind in canonical order.
func LocalDay ¶
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 ¶
LocalDayStart returns daemon-local midnight daysBack days before value's day.
func LowerSessionCatalogSearchText ¶
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 NormalizeMentionsJSON ¶
NormalizeMentionsJSON trims raw and maps a blank value to EmptyMentionsJSON.
func NormalizeSQLiteIdentifier ¶
NormalizeSQLiteIdentifier validates a SQLite identifier for use in helper queries.
func NormalizeSessionFolderName ¶
NormalizeSessionFolderName trims a folder name and enforces its bounds.
func NormalizeSessionLayoutIDs ¶
NormalizeSessionLayoutIDs trims, bounds, and rejects duplicate or blank IDs.
func NormalizeSessionType ¶
NormalizeSessionType applies the default session type when empty.
func NormalizeWorkspaceLayoutProfile ¶
NormalizeWorkspaceLayoutProfile trims and requires the owning profile.
func NullFloat64 ¶
func NullFloat64(value sql.NullFloat64) *float64
NullFloat64 converts sql.NullFloat64 into a pointer.
func NullString ¶
func NullString(value sql.NullString) *string
NullString converts sql.NullString into a trimmed string pointer.
func NullableFloat64 ¶
NullableFloat64 maps nil pointers to SQL NULL.
func NullableInt64 ¶
NullableInt64 maps nil pointers to SQL NULL.
func NullableString ¶
NullableString maps blank strings to SQL NULL.
func NullableStringPointer ¶
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 ¶
ParseNullableTimestamp parses optional canonical timestamps.
func ParseTimestamp ¶
ParseTimestamp parses the canonical SQLite text timestamp.
func ReadBootWatermarks ¶
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 ¶
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 ¶
RequireCurrent validates that a migration stream is exactly at the embedded head without creating tables or applying migrations.
func RequireWorkspaceActive ¶
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 ¶
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 ¶
SessionMetaFile returns the canonical metadata file path for a session directory.
func SessionRuntimeFailurePointer ¶
SessionRuntimeFailurePointer normalizes an optional persisted runtime diagnostic.
func SessionRuntimeFailureValue ¶
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 ¶
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 ¶
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 ¶
ValidPendingInteractionKind reports whether kind belongs to the durable vocabulary.
func ValidPendingInteractionStatus ¶
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 ¶
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 ¶
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 ¶
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 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 ¶
ActiveWorkspaceClause excludes archived projects from aggregate overview reads. An explicitly selected project retains its historical data.
func Int64Clause ¶
Int64Clause builds a numeric comparison clause when the value is positive.
func NotStringClause ¶
NotStringClause builds an inequality clause when the value is non-empty.
func OpaqueStringClause ¶
OpaqueStringClause builds an equality clause without rewriting the value.
func ReadScopeClause ¶
ReadScopeClause builds the SQL predicate for a validated scope. Invalid input produces an always-false predicate as a second fail-closed guard.
func ReadScopeCoalescedClause ¶
ReadScopeCoalescedClause builds a scoped owner predicate across nullable, ordered owner columns.
func SessionWorkspaceClause ¶
SessionWorkspaceClause keeps an explicit User selection distinct from an unfiltered catalog.
func StringClause ¶
StringClause builds an equality clause when the value is non-empty.
func StringCompareClause ¶
StringCompareClause builds a validated string comparison when the value is non-empty.
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 ConversationRewindState ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
StatFileStamp stamps one regular file. A missing file reports false without an error.
type HookDispatchCounts ¶
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 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 MarketplaceSourceNameRetainedError ¶
func (*MarketplaceSourceNameRetainedError) Error ¶
func (e *MarketplaceSourceNameRetainedError) Error() string
func (*MarketplaceSourceNameRetainedError) Unwrap ¶
func (e *MarketplaceSourceNameRetainedError) Unwrap() error
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.
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 ¶
MutationCommitFence revalidates an authenticated mutation at its commit boundary.
type NativeReplayCursor ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
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 ¶
func (r PendingInteractionCreate) Normalize() PendingInteractionCreate
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 ¶
func (r PendingInteractionTransition) Normalize() PendingInteractionTransition
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 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 ¶
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 ¶
ReadScope selects exactly one profile or the explicit labeled aggregate.
type ReconcileResult ¶
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 ReplyWatchFire ¶
type ReplyWatchRegistration ¶
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 ¶
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 ¶
func (r SessionAcceptedRoute) Normalize() SessionAcceptedRoute
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 (e *SessionArchiveLiveMemberError) Error() string
func (*SessionArchiveLiveMemberError) Unwrap ¶
func (e *SessionArchiveLiveMemberError) Unwrap() error
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 ¶
func (r SessionAttachRequest) Normalize() SessionAttachRequest
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 ¶
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 ¶
func (a SessionAttention) Fence() SessionAttentionFence
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 ¶
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 ¶
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
// ExcludeRootSessionID leaves out that session and every session rooted at it.
ExcludeRootSessionID 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"`
// 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
// ContinuedTreeParents maps a continued session's source to the hierarchy parent of
// the first session in its continue chain; a chain that began top-level is absent.
ContinuedTreeParents map[string]string
}
type SessionCatalogRelationsQuery ¶
type SessionCatalogRelationsQuery struct {
DefaultBranches map[string][]string
WorkspaceID string
WorkspaceIDs []string
ReadScope ReadScope
SessionIDs []string
ParentIDs []string
ActiveIDs []string
// ContinuedSourceIDs are the sources of the page's continued sessions; each resolves
// to the parent its continuation chain started under (ContinuedTreeParents).
ContinuedSourceIDs []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 ¶
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.
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 ¶
func (a SessionInputAttachment) Normalize() SessionInputAttachment
Normalize returns trimmed attachment identity fields.
type SessionInputClearError ¶
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 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 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 ¶
SessionInputHold summarizes queued input blocked by an instance pause.
type SessionInputNotQueuedError ¶
func (*SessionInputNotQueuedError) Error ¶
func (e *SessionInputNotQueuedError) Error() string
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 ¶
func (*SessionInputQueueFullError) Error ¶
func (e *SessionInputQueueFullError) Error() string
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 ¶
func (r SessionInputQueueInsert) Normalize() SessionInputQueueInsert
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 ¶
func (r SessionInputRuntime) Normalize() SessionInputRuntime
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 ¶
func (p *SessionInputSyntheticPrompt) Clone() *SessionInputSyntheticPrompt
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 ¶
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 ¶
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 ¶
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 ¶
func (r SessionPromptAdmissionRequest) Normalize() SessionPromptAdmissionRequest
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 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 ¶
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 ¶
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 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 ¶
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 ¶
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 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 ¶
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 ¶
TaskDesignationRollupQuery filters designation rollup reads.
func (TaskDesignationRollupQuery) Validate ¶
func (q TaskDesignationRollupQuery) Validate() error
Validate ensures rollup reads cannot become unbounded.
type TaskRunOutcomeDay ¶
TaskRunOutcomeDay is one daemon-local day of terminal worker-run outcomes.
type TerminalApprovalCount ¶
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 ¶
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 ¶
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 ¶
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.
type WorkspaceAttentionSummary ¶
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 ¶
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 ¶
ExecContext executes a statement inside the active write transaction.
func (*WriteTx) PrepareContext ¶
PrepareContext prepares a statement inside the active write transaction.
func (*WriteTx) QueryContext ¶
QueryContext executes a query inside the active write transaction.
Source Files
¶
- boot_watermark.go
- boot_watermark_identity_linux.go
- dead_entity_store.go
- event_store.go
- event_summary_content.go
- event_summary_store.go
- failure.go
- id.go
- loop_output_blob.go
- marketplace_catalog.go
- meta.go
- migrate.go
- migrate_logging.go
- migration_bootstrap.go
- migration_database.go
- migration_manifest.go
- migration_manifest_cache.go
- migration_plan.go
- migration_plan_fs.go
- migration_preflight.go
- migration_reconciliation.go
- migration_refusal.go
- migration_sql_parser.go
- migration_status.go
- migration_stepper.go
- mutation_fence.go
- onboarding_store.go
- profile_identity.go
- read_scope.go
- reply_watch.go
- session_accepted_route.go
- session_advertised_command.go
- session_attention.go
- session_catalog.go
- session_catalog_agent_metrics.go
- session_catalog_branches.go
- session_catalog_facets.go
- session_catalog_owner.go
- session_catalog_page.go
- session_catalog_relations.go
- session_creation_identity.go
- session_creation_legacy.go
- session_creation_profile.go
- session_db_owner.go
- session_input_attachment.go
- session_input_clear.go
- session_input_errors.go
- session_input_origin.go
- session_input_queue.go
- session_input_synthetic.go
- session_later.go
- session_layout.go
- session_lineage.go
- session_liveness.go
- session_message.go
- session_meta_derivation.go
- session_meta_types.go
- session_permission_policy.go
- session_prompt_admission.go
- session_prompt_reports.go
- session_runtime.go
- session_runtime_options.go
- session_runtime_recovery.go
- session_runtime_selection.go
- session_spawn_budget.go
- session_steer.go
- session_store_errors.go
- session_subagents.go
- session_type.go
- session_work_links.go
- session_worktree_binding.go
- skill_exposure.go
- sql_clause.go
- sql_null.go
- sqlite.go
- sqlite_busy.go
- sqlite_checkpoint.go
- sqlite_cleanup.go
- sqlite_config.go
- sqlite_corruption.go
- sqlite_file_identity.go
- sqlite_header.go
- sqlite_identifier.go
- sqlite_probe.go
- sqlite_read_connection.go
- sqlite_unicode.go
- sqlite_wal_restart.go
- store.go
- store_paths.go
- timestamp.go
- token_stats_cost.go
- types_conversation_rewind.go
- types_dead_entity.go
- types_event.go
- types_event_summary.go
- types_observability_retention.go
- types_observe_overview.go
- types_permission_log.go
- types_reconcile.go
- types_session.go
- types_session_derive.go
- types_session_profile_move.go
- types_task_designation_rollup.go
- types_token_stats.go
- types_transcript_anchor.go
- validation.go
- workspace_admission.go
- workspace_layout.go
- write.go
- write_admission.go
- write_attribution.go
- write_batch.go
- write_diagnostics.go
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. |