state

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 71 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	TitleSourceDerived = "derived"
	TitleSourceLLM     = "llm"
	TitleSourceUser    = "user"
)

Persisted title provenance, automatic labels rank below a user chosen title

View Source
const (
	FTSCJKStaleKey        = "fts_cjk_stale"
	FTSStaleKey           = "fts_stale"
	FTSRebuildDeferralKey = "fts_rebuild_deferral"
)

State meta breadcrumbs of the FTS maintenance protocol

View Source
const (
	AbsorbedRowIDs     = "_absorbed_row_ids"
	MergedDurableRows  = "_merged_durable_rows"
	UnnamedDurableRows = "_unnamed_durable_rows"
	RetiredDurableRows = "_retired_durable_rows"
	RetiredRow         = "_retired_row"
	OwnRow             = "_own_row"
	DBPersistedMarker  = "_db_persisted"
)

Message keys that carry durable row coverage through an in place archive

View Source
const (
	CompressedSummaryMetadataKey    = "_compressed_summary"
	CompressedSummaryHasUserTurnKey = "_compressed_summary_has_user_turn"
	MicroCompactMarkerKey           = "_micro_compact_marker"
	SteerDisplayKind                = "steer"

	CompressionContinuationUserContent = "Continue from the compressed conversation context above. This marker exists because no human user turn was available."

	MaxIterationsSummaryRequest         = "" /* 188-byte string literal not displayed */
	BackgroundProcessNotificationPrefix = "[IMPORTANT: Background process "
	TodoInjectionHeader                 = "[Your active task list was preserved across context compression]"

	LengthContinuationNetworkStub        = "" /* 332-byte string literal not displayed */
	LengthContinuationOutputLimit        = "" /* 176-byte string literal not displayed */
	LegacyLengthContinuationNetworkStub  = "" /* 176-byte string literal not displayed */
	LengthContinuationDroppedToolsPrefix = "[System: Your previous tool call "
	CodexIncompleteNudge                 = "" /* 225-byte string literal not displayed */
	CodexAckContinuationNudge            = "[System: Continue now. Execute the required tool calls and only send your final answer after completing the task.]"
	DegenerateFinalNudge                 = "" /* 241-byte string literal not displayed */
	DroppedToolcallNudgeContent          = "" /* 160-byte string literal not displayed */
	EmptyToolResponseNudge               = "" /* 126-byte string literal not displayed */
)
View Source
const (
	RetiredGenerationDirSuffix       = ".retired-wal-"
	RetiredGenerationManifest        = "manifest.json"
	RetiredGenerationManifestVersion = 1
)
View Source
const (
	StorageOK      = "ok"
	StorageCorrupt = "corrupt"
)

StorageOK and StorageCorrupt are the two storage health states of a database path

View Source
const (
	MessageUID          = "message_uid"
	AbsorbedMessageUIDs = "_absorbed_message_uids"
	ToolCallUIDs        = "_tool_call_uids"
	ToolCallUID         = "_tool_call_uid"
)

Live identity keys of a message dict, shared with the agent message metadata

View Source
const (
	DBRowSnapshot           = "_db_row_snapshot"
	CanonicalRow            = "_canonical_row"
	RestoredFromStore       = "_restored_from_store"
	MergedTurnPrefix        = "_merged_turn_prefix"
	WithheldPrompt          = "withheld_prompt"
	PreLLMBlockWithheldText = "[Message withheld: a pre_llm_call policy hook blocked it.]"
	InflightTaskRestatement = "compaction_inflight_task_restatement"
)

Transcript repair bookkeeping and durable record keys that never reach a provider

View Source
const (
	PromptRefreshProfileKey       = "prompt_refresh.epoch"
	PromptRefreshSessionKeyPrefix = "prompt_refresh.epoch:"
)
View Source
const (
	PruneGiB = 1 << 30

	AutoPruneSnoozeSeconds = 7 * 86400

	AutoPruneEstimateFile  = ".auto_prune_estimate.json"
	AutoPruneTotalBytesTTL = 7 * 86400
	AutoPruneNoticeKey     = "sessions.auto_prune"
)
View Source
const (
	BrowseReconcileBudgetS = 3.0
	BrowseIntegrityBudgetS = BrowseReconcileBudgetS

	BrowseReconcilePurpose = "browse_schema_reconcile"
)

Budget of a browse catch up, the holder purpose it publishes and the sibling poll interval

View Source
const (
	// Queued inputs one session holds, the busy queue cap of the gateway runner
	AdmissionQueueMax = 32
	// Outcome of a queued admission handed to its FIFO's running claim and not yet settled
	Steering = "steering"
)
View Source
const (
	HistoricalTaskHeading    = "## Historical Task Snapshot"
	LegacySummaryPrefix      = "[CONTEXT SUMMARY]:"
	SummaryEndMarker         = "--- END OF CONTEXT SUMMARY — respond to the message below, not the summary above ---"
	MergedPriorContextHeader = "[PRIOR CONTEXT — for reference only; not a new message]"
	MergedSummaryDelimiter   = "[END OF PRIOR CONTEXT — COMPACTION SUMMARY BELOW]"
)

Context compressor markers the preview SQL recognises, shared with the agent compressor

View Source
const (
	SkillScaffoldSQLLike    = skillInvocationPrefix + "%"
	AutoLoadScaffoldSQLLike = autoLoadPrefix + "%"
	SkillExcerptJoint       = "\x1e"
)

Skill scaffolding markers, byte identical to the skill message builders

View Source
const (
	ClientEnvConfigKey       = "client_env_passthrough"
	ClientEnvNotLocalWarning = "this session uses the gateway's own PATH, toolchain and prefill file: the client's environment " +
		"was not applied because the client is not attached to this gateway locally."
)
View Source
const (
	TerminalResultPrefix    = "gateway.admission.result.v1."
	TerminalAdmissionPrefix = "gateway.terminal_admission.v1."
	TerminalIdentityPrefix  = "gateway.terminal_identity.v1."
	TerminalWorkerPrefix    = "gateway.terminal_worker.v1."

	MediaRetiredPrefix     = "gateway.media.retired.v1."
	SpilloverRetiredPrefix = "gateway.spillover.retired.v1."

	RouteFencePrefix       = "gateway.retired_route.v1."
	ViewerClosePrefix      = "gateway.viewer_close.v1:"
	LocalAPIBindingPrefix  = "gateway.api.binding.v1."
	LocalAPIDeclaredPrefix = "gateway.api.conversation.v1."
)
View Source
const (
	SessionStatusComplete    = "complete"
	SessionStatusInterrupted = "interrupted"
	SessionStatusError       = "error"
	SessionStatusEmpty       = "empty"
)

Lifecycle statuses a session transcript tail classifies to

View Source
const (
	FailedTurnNotice            = "Your request was not processed. Send it again if you still want me to carry it out."
	PartialFailedTurnNotice     = "This turn did not complete. Some actions may already have run; verify their effects before resending."
	AutomationInterruptedNotice = "An automated delivery was interrupted and was not run again. Some actions may already have run; verify their effects."
	FailedTurnDisplayKind       = "failed_turn"
)

Turn boundary notices and the display kind a failed turn row carries

View Source
const ActivityDescriptionMax = 120

ActivityDescriptionMax is the code point budget of a session activity description

View Source
const AutoVacuumMinFreelistRatio = 0.25

Freelist fraction above which auto maintenance runs VACUUM

View Source
const BindingPrefix = "gateway.history_control.v1."
View Source
const CanonicalBotChatTitle = "Bot Chat"

Exact title of the hidden canonical Bot Chat whose name is its identity

View Source
const ChildSeparator = "/child:"

Separator between a delegated child's execution id and its parent's, so descendants share one prefix

View Source
const ClientHistorySource = "desktop"

Source label older builds stored client app chats under, also given to a bound client app history row

View Source
const CompactedTargetDetail = "compacted: target user message was summarized when the session was compressed"

Refusal detail clients match when the rewind target was summarized by compaction

View Source
const CronPrincipalID = "cron-owner"

The principal the profile scheduler admits every cron fire under

View Source
const CronRequestPrefix = "cron:"

Starts the admission request id of every cron fire

View Source
const DefaultHexLen = 6

The random hex length of a minted session id

View Source
const DeferredPickPrefix = "gateway.deferred_pick.v1."

Model pick made while a turn ran and committed at the next turn boundary

View Source
const DeletedWalGenerationMsg = "FATAL: session storage stopped writing because another icebath process still holds a deleted " +
	"state.db-wal or state.db-shm inode (an old copy of the write-ahead log). Nothing is lost: quit " +
	"every icebath process on this profile (TUI, gateway, cron), run `icebath doctor` " +
	"(it names the processes still holding the log), then start icebath again. Do not delete the WAL " +
	"yourself and do not run `icebath doctor --fix` while they are running. " +
	"Guide: `" + StorageRecoveryHelp + "` " +
	"Detail: the path names a different (or missing) generation than the one this process holds " +
	"open; opening or writing through it would mint a second WAL (split-brain). " +
	"database.journal_mode: delete is operator containment, not a new default."

The message of a write refused while a deleted wal generation is held

View Source
const EndReasonCompression = "compression"

Reason a compression continuation ends its parent with

View Source
const EpochMax = 4_200_000_000.0

Latest coerce_epoch timestamp a stored epoch may carry

View Source
const EpochMin = 0.0

Earliest coerce_epoch timestamp a stored epoch may carry

View Source
const FTSCJKTableSQL = `` /* 348-byte string literal not displayed */
View Source
const FTSCJKTriggerSQL = `` /* 2057-byte string literal not displayed */
View Source
const FTSStorageVersion = 3

FTS storage layout version tracked in state_meta fts_storage_version

View Source
const FTSToolContentPrefixChars = 8_192

Prefix of a tool row the base FTS index stores

View Source
const LiveSystemGuardLead = "live-system guard: "

Lead of the refusal a test gets for opening the real state database, the one failure never cached

View Source
const LocalLegacyPrefix = "gateway.local_legacy.v1:"
View Source
const LocalPolicyPrefix = "gateway.local_policy.v1:"
View Source
const MaxFTS5QueryChars = 2_048

Cap on user controlled FTS5 query input before sanitizing

View Source
const MaxTitleLength = 100

Longest sanitized title a session may carry, counted in code points

View Source
const MaxTodoResultChars = 512_000

Largest Todo result the resume restores, the todo tool cap

View Source
const ModelOnlyDisplayMetadataKey = "model_only"

ModelOnlyDisplayMetadataKey marks a live row the model reads but nobody typed as one message, never rendered

View Source
const ModelOnlyKey = "model_only"

Display metadata key marking a row the model sees but the person never does

View Source
const PersistAfterAdmissionInterrupt = "_persist_after_admission_interrupt"

agent/session_persistence.py marker for a message persisted after an admission interrupt

View Source
const QueuedPromptMetadataKey = "_queued_prompt"

Display metadata flag on the user row a busy queue accept writes

View Source
const (
	ReactionsMetadataKey = "reactions"
)
View Source
const (
	ReplacementPrefix = "gateway.queued_replacement.v1."
)

State meta key prefixes of the queued replacement bindings and the mutation exact retry receipts

View Source
const RetiredPrefix = "gateway.retired_session.v1."

State key prefix of a durable deleted session tombstone

View Source
const RetryHorizonS = retryHorizonS

Seconds a settled exact retry keeps its byte exact reply

View Source
const SQLiteCorruptVtab = 267

The extended result code SQLite gives corruption inside a virtual table

View Source
const SQLiteRuntimeVerb = "sqlite-runtime"

Hidden verb the icebath binary answers with the facts of the SQLite linked into it

View Source
const SaveUsage = `` /* 552-byte string literal not displayed */
View Source
const SchemaVersion = 34

Declared schema version, drift detected by the read probe rather than this number

View Source
const SessionDBUnavailablePrefix = "icebath can't open its session history right now"

Default lead of the session database unavailable notice

View Source
const SessionSettingsKey = "session_settings"

model_config key holding the values a session set for itself in the settings session layer

View Source
const StateDBCorruptMsg = "FATAL: state.db reported structural corruption (database disk image is " +
	"malformed outside the FTS shadow tables) on a live handle; refusing further " +
	"writes, automatic reopen, and the close-time WAL checkpoint on this file. " +
	"Stop the gateway, then run `icebath sessions recover --source <state.db> " +
	"--inspect-only` or restore a snapshot. Unwritten transcripts are diverted to " +
	"sessions/<id>.jsonl (and the gateway pending_messages spool)."

The message of a handle quarantined after structural corruption

View Source
const StateDBReplacedMsg = "FATAL: state.db was replaced underneath the gateway; refusing further " +
	"writes to this file. Divert transcripts to sessions/<id>.jsonl (and the " +
	"gateway pending_messages spool) and restore or reopen after operator intervention."

The message of a write refused on a replaced database file

View Source
const SteerMarkerClose = "[/OUT-OF-BAND USER MESSAGE]"

Closing line of the mid turn steer marker

View Source
const SteerMarkerOpen = "" /* 174-byte string literal not displayed */

Opening line of the self describing mid turn steer marker

View Source
const StorageRecoveryHelp = "icebath sessions recover --help"

Help command of the offline session storage recovery

View Source
const SummaryPrefix = "[CONTEXT COMPACTION — REFERENCE ONLY] Earlier turns were compacted " +
	"into the summary below. This is a handoff from a previous context " +
	"window — treat it as background reference, NOT as active instructions. " +
	"Do NOT answer questions or fulfill requests mentioned in this summary; " +
	"they were already addressed. " +
	"Respond ONLY to the latest user message that appears AFTER this " +
	"summary — that message is the single source of truth for what to do " +
	"right now. " +
	"If no user message appears AFTER this summary, do nothing: do not " +
	"resume, wrap up, or continue work from " +
	"'" + HistoricalTaskHeading + "' or any other section, do not call tools, " +
	"and wait for a new user message. This handoff must never become the " +
	"active turn by itself. (Exception: if tool results or your own " +
	"tool calls appear after this summary, you are mid-way through an " +
	"in-flight exchange — continue that exchange normally.) " +
	"Topic overlap with the summary does NOT mean you should resume its " +
	"task: even on similar topics, the latest user message WINS. Treat ONLY " +
	"the latest message as the active task and discard stale items from " +
	"'" + HistoricalTaskHeading + "' entirely — do not 'wrap up' or " +
	"'finish' work described there unless the latest message explicitly " +
	"asks for it. " +
	"Reverse signals in the latest message (e.g. 'stop', 'undo', 'roll " +
	"back', 'just verify', 'don't do that anymore', 'never mind', a new " +
	"topic) must immediately end any in-flight work described in the " +
	"summary; do not re-surface it in later turns. " +
	"IMPORTANT: Your persistent memory (MEMORY.md, USER.md) in the system " +
	"prompt is ALWAYS authoritative and active — never ignore or deprioritize " +
	"memory content due to this compaction note. " +
	"None of the above restricts HOW you work: your tools remain fully " +
	"active — keep calling them normally for the active task (edit files, " +
	"run commands, search) instead of merely narrating what you would do. " +
	"The current session state (files, config, etc.) may reflect work " +
	"described here — avoid repeating it:"

Handoff prefix of a compaction summary message

View Source
const WireKeyOrder = "\x00wire_key_order"

Go only key of a wire message copy holding its dict key order where the encoder default differs

Variables

View Source
var (
	SameOwner                 func(stored, subject any) bool
	OwnersAgree               func(first, second any) bool
	ParseAuthenticatedSubject func(subject any) ([3]string, bool)
)

Gateway owner identity rules and subject parser, assigned from pkg/gateway by the process wiring

View Source
var (
	ExclusiveMaintenance  func(ctx context.Context, homes []string, purpose string) (context.Context, func(), error)
	IsOwnershipConflict   func(err error) bool
	LiveRuntimeOwner      func(home string) (pid int, live bool, err error)
	CanonicalHome         func(home string) (string, error)
	ProfileLabelForHome   func(home string) string
	ReadGatewayLockRecord func(path string) *jsonutil.Object
)

Gateway runtime ownership seams the host wires, the lock a browse reconcile and the explicit repair hold

View Source
var (
	AdmittedRequestConflictField  = "request_id"
	AdmittedRequestConflictDetail = "this request id was already admitted with another payload"
)

Field and detail of the one admission conflict proving the request id was already admitted

View Source
var (
	ClientBehaviourEnv    = []string{"ICEBATH_EPHEMERAL_SYSTEM_PROMPT", "ICEBATH_PREFILL_MESSAGES_FILE", "ICEBATH_INFERENCE_PROVIDER", "ICEBATH_ENABLE_PROJECT_PLUGINS"}
	ClientHostBehaviour   = []string{"ICEBATH_PREFILL_MESSAGES_FILE", "ICEBATH_ENABLE_PROJECT_PLUGINS"}
	ClientToolEnv         = []string{"PATH", "VIRTUAL_ENV", "GOPATH", "GOROOT", "CARGO_HOME", "RUSTUP_HOME", "JAVA_HOME"}
	ClientToolEnvPrefixes = []string{"CONDA_", "NODE_", "NVM_", "PYENV_"}
	SecretEnvName         = IsSecretEnvName
	SecretEnvSubstrings   = SecretSubstrings
)
View Source
var (
	AdmissionMediaReferences func(payload *jsonutil.Object) ([]*jsonutil.Object, error)
	HostedDocumentReferences func(requestID string, payload *jsonutil.Object) ([]*jsonutil.Object, error)
	ReleaseUnheldMedia       func(db *SessionDB, references []any) error
	SpilloverSQLFilter       string
	SpilloverNamesInText     func(texts ...string) map[string]bool
	ReferencedSpilloverNames func(spillDir string) (map[string]bool, bool)
)

Hooks into pkg/gateway and pkg/tools that the process wiring assigns, since both import this package

View Source
var (
	ErrUserTurnIndex         = errors.New("user turn index is outside the transcript")
	ErrNotUserOriginatedTurn = errors.New("selected row is not a user-originated turn")
)

IndexError and ValueError of the rewind prefix helper

View Source
var (
	ErrRetryNonText        error = &retryRefusal{"retry does not support non-text content"}
	ErrRetryMediaPart      error = &retryRefusal{"retry does not support media or unknown content parts"}
	ErrRetryAnnotatedPart  error = &retryRefusal{"retry cannot losslessly flatten annotated text parts"}
	ErrRetryPartWithoutTxt error = &retryRefusal{"retry text parts must contain text"}
	ErrRetryNoText         error = &retryRefusal{"retry found no text to send"}
)

Python ValueError reasons a retry refuses with before any destructive mutation

View Source
var BranchLocalRoute func(childID, principalID string, originProfile, routeProfile any) (route string, origin, entry *jsonutil.Object, updatedAt float64, err error)

Route, origin and routing entry of a local branch child, assigned by the gateway wiring

View Source
var ControlFrameOpeners = []string{"/?OUT-OF-BAND USER MESSAGE", "CONTEXT COMPACTION", "CONTEXT SUMMARY]", "PRIOR CONTEXT", "Runtime note:", "System note:", "System:", "SYSTEM]", "IMPORTANT:", "Planning state preserved", "ASYNC DELEGATION"}

Text after the bracket that opens one of the agent control frames

View Source
var DefaultDBPath = ""

Default state database path resolved at call time, a repointed DefaultDBPath winning

View Source
var DeferredIndexSQL = `` /* 7384-byte string literal not displayed */

Triggers and indexes on later added columns, run after the column reconcile

View Source
var DisplayVisibleSQL = " AND COALESCE(" + sqlJSONExtract("display_metadata", "$."+ModelOnlyKey) + ", 0) = 0"

Model only rows never enter a display projection, unqualified so a correlated subquery binds the inner alias

View Source
var ErrReadOnlyToolCallField = errors.New("tool call entry cannot hold the attribute")

ErrReadOnlyToolCallField is the setattr failure for an entry that cannot hold the key

View Source
var FTSSQL = `
-- Stable projection the base word index reads and writes through: the view
-- computes EXACTLY what the triggers/backfill insert, so 'rebuild' and the
-- integrity checker always agree with the stored index.
CREATE VIEW IF NOT EXISTS messages_fts_src AS
    SELECT id,
           CASE WHEN role = 'tool'
                THEN substr(COALESCE(content, ''), 1, ` + strconv.Itoa(FTSToolContentPrefixChars) + `)
                ELSE content END AS content,
           tool_name, tool_calls
    FROM messages;

CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
    content,
    tool_name,
    tool_calls,
    content='messages_fts_src',
    content_rowid='id'
);

CREATE TRIGGER IF NOT EXISTS messages_fts_insert AFTER INSERT ON messages
WHEN (new.id > COALESCE((SELECT CAST(value AS INTEGER) FROM state_meta
                         WHERE key = 'fts_rebuild_high_water'), -1)
   OR new.id <= COALESCE((SELECT CAST(value AS INTEGER) FROM state_meta
                          WHERE key = 'fts_rebuild_progress'), -1))
BEGIN
    INSERT INTO messages_fts(rowid, content, tool_name, tool_calls)
    VALUES (
        new.id,
        ` + ftsNewIndexedContentSQL + `,
        new.tool_name,
        new.tool_calls
    );
END;

CREATE TRIGGER IF NOT EXISTS messages_fts_delete AFTER DELETE ON messages
WHEN (old.id > COALESCE((SELECT CAST(value AS INTEGER) FROM state_meta
                         WHERE key = 'fts_rebuild_high_water'), -1)
   OR old.id <= COALESCE((SELECT CAST(value AS INTEGER) FROM state_meta
                          WHERE key = 'fts_rebuild_progress'), -1))
BEGIN
    INSERT INTO messages_fts(messages_fts, rowid, content, tool_name, tool_calls)
    VALUES (
        'delete',
        old.id,
        ` + ftsOldIndexedContentSQL + `,
        old.tool_name,
        old.tool_calls
    );
END;

-- UPDATE OF skips the trigger entirely for non-content column writes
-- (status/compacted/observed/etc.), which is stronger than the WHEN gate
-- alone and avoids FTS I/O saturation on large state.db (#68858 / #73639).
CREATE TRIGGER IF NOT EXISTS messages_fts_update
AFTER UPDATE OF content, tool_name, tool_calls, role ON messages
WHEN (old.content IS NOT new.content
    OR old.tool_name IS NOT new.tool_name
    OR old.tool_calls IS NOT new.tool_calls
    OR old.role IS NOT new.role)
   AND (old.id > COALESCE((SELECT CAST(value AS INTEGER) FROM state_meta
                           WHERE key = 'fts_rebuild_high_water'), -1)
     OR old.id <= COALESCE((SELECT CAST(value AS INTEGER) FROM state_meta
                            WHERE key = 'fts_rebuild_progress'), -1))
BEGIN
    INSERT INTO messages_fts(messages_fts, rowid, content, tool_name, tool_calls)
    VALUES (
        'delete',
        old.id,
        ` + ftsOldIndexedContentSQL + `,
        old.tool_name,
        old.tool_calls
    );
    INSERT INTO messages_fts(rowid, content, tool_name, tool_calls)
    VALUES (
        new.id,
        ` + ftsNewIndexedContentSQL + `,
        new.tool_name,
        new.tool_calls
    );
END;
`

External content word index over the stable projection view with its sync triggers

View Source
var FTSTrigramExcludedSources = []string{"cron", "subagent"}

Sources whose transcripts stay out of the trigram index

View Source
var FTSTrigramSQL = `
CREATE VIEW IF NOT EXISTS messages_fts_trigram_src AS
    SELECT m.id, m.role, m.content, m.tool_name
    FROM messages AS m
    JOIN sessions AS s ON s.id = m.session_id
    WHERE m.role <> 'tool' AND ` + FTSTrigramSessionSQLFor("s") + `;

CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts_trigram USING fts5(
    content,
    tool_name,
    content='messages_fts_trigram_src',
    content_rowid='id',
    tokenize='trigram'
);

CREATE TRIGGER IF NOT EXISTS messages_fts_trigram_insert AFTER INSERT ON messages
WHEN new.role <> 'tool'
   AND EXISTS (SELECT 1 FROM sessions
               WHERE id = new.session_id AND ` + FTSTrigramSessionSQL + `)
   AND (new.id > COALESCE((SELECT CAST(value AS INTEGER) FROM state_meta
                           WHERE key = 'fts_rebuild_high_water'), -1)
     OR new.id <= COALESCE((SELECT CAST(value AS INTEGER) FROM state_meta
                            WHERE key = 'fts_rebuild_progress'), -1))
BEGIN
    INSERT INTO messages_fts_trigram(rowid, content, tool_name)
    VALUES (new.id, new.content, new.tool_name);
END;

CREATE TRIGGER IF NOT EXISTS messages_fts_trigram_delete AFTER DELETE ON messages
WHEN old.role <> 'tool'
   AND EXISTS (SELECT 1 FROM sessions
               WHERE id = old.session_id AND ` + FTSTrigramSessionSQL + `)
   AND (old.id > COALESCE((SELECT CAST(value AS INTEGER) FROM state_meta
                           WHERE key = 'fts_rebuild_high_water'), -1)
     OR old.id <= COALESCE((SELECT CAST(value AS INTEGER) FROM state_meta
                            WHERE key = 'fts_rebuild_progress'), -1))
BEGIN
    INSERT INTO messages_fts_trigram(messages_fts_trigram, rowid, content, tool_name)
    VALUES ('delete', old.id, old.content, old.tool_name);
END;

CREATE TRIGGER IF NOT EXISTS messages_fts_trigram_update
AFTER UPDATE OF content, tool_name, role ON messages
WHEN (old.content IS NOT new.content
    OR old.tool_name IS NOT new.tool_name
    OR old.role IS NOT new.role)
   AND (old.id > COALESCE((SELECT CAST(value AS INTEGER) FROM state_meta
                           WHERE key = 'fts_rebuild_high_water'), -1)
     OR old.id <= COALESCE((SELECT CAST(value AS INTEGER) FROM state_meta
                            WHERE key = 'fts_rebuild_progress'), -1))
BEGIN
    INSERT INTO messages_fts_trigram(messages_fts_trigram, rowid, content, tool_name)
    SELECT 'delete', old.id, old.content, old.tool_name
    WHERE old.role <> 'tool'
      AND EXISTS (SELECT 1 FROM sessions
                  WHERE id = old.session_id AND ` + FTSTrigramSessionSQL + `);
    INSERT INTO messages_fts_trigram(rowid, content, tool_name)
    SELECT new.id, new.content, new.tool_name
    WHERE new.role <> 'tool'
      AND EXISTS (SELECT 1 FROM sessions
                  WHERE id = new.session_id AND ` + FTSTrigramSessionSQL + `);
END;
`

Trigram index for CJK substring search over sessions outside the excluded classes

View Source
var FTSTrigramSessionSQL = FTSTrigramSessionSQLFor("")

Unqualified trigram session predicate the sync triggers use

View Source
var FTSVTableLayouts = map[string][]string{
	"messages_fts": {
		"CREATE VIRTUAL TABLE messages_fts USING fts5(content,content=messages,content_rowid=id)",
		"CREATE VIRTUAL TABLE messages_fts USING fts5(content)",
		"CREATE VIRTUAL TABLE messages_fts USING fts5(content,tool_name,tool_calls,content='messages'," +
			"content_rowid='id')",
		"CREATE VIRTUAL TABLE messages_fts USING fts5(content,tool_name,tool_calls," +
			"content='messages_fts_src',content_rowid='id')",
	},
	"messages_fts_trigram": {
		"CREATE VIRTUAL TABLE messages_fts_trigram USING fts5(content,content=messages,content_rowid=id," +
			"tokenize='trigram')",
		"CREATE VIRTUAL TABLE messages_fts_trigram USING fts5(content,tokenize='trigram')",
		"CREATE VIRTUAL TABLE messages_fts_trigram USING fts5(content,tool_name,tool_calls," +
			"content='messages_fts_trigram_src',content_rowid='id',tokenize='trigram')",
		"CREATE VIRTUAL TABLE messages_fts_trigram USING fts5(content,tool_name," +
			"content='messages_fts_trigram_src',content_rowid='id',tokenize='trigram')",
	},
}

Every stored definition a released version created per FTS table, oldest first, the last one current

View Source
var HandoffMessageFields = unionKeys(messageFields, map[string]bool{"_compressed_summary_has_user_turn": true})

Message keys a compaction handoff may carry, the closed boundary the owner validates

View Source
var LaunchFields = map[string]string{"model": "str", "provider": "str", "base_url": "str", "reasoning": "str", "cwd": "str",
	"toolsets": "list", "skills": "list", "max_turns": "turns", "run_budget": "number", "ignore_rules": "bool", "yolo": "bool",
	"checkpoints": "bool", "accept_hooks": "bool", "pass_session_id": "bool", "verbose": "bool", "safe_mode": "bool",
	"ignore_user_config": "bool"}

Launch flags a resume may lay over a session's frozen policy, each with the JSON type it arrives as

View Source
var LegacyFTSSQL = `
CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
    content
);

CREATE TRIGGER IF NOT EXISTS messages_fts_insert AFTER INSERT ON messages BEGIN
    INSERT INTO messages_fts(rowid, content) VALUES (
        new.id,
        COALESCE(` + ftsNewIndexedContentSQL + `, '')
        || ' ' || COALESCE(new.tool_name, '') || ' ' || COALESCE(new.tool_calls, '')
    );
END;

CREATE TRIGGER IF NOT EXISTS messages_fts_delete AFTER DELETE ON messages BEGIN
    DELETE FROM messages_fts WHERE rowid = old.id;
END;

CREATE TRIGGER IF NOT EXISTS messages_fts_update
AFTER UPDATE OF content, tool_name, tool_calls, role ON messages BEGIN
    DELETE FROM messages_fts WHERE rowid = old.id;
    INSERT INTO messages_fts(rowid, content) VALUES (
        new.id,
        COALESCE(` + ftsNewIndexedContentSQL + `, '')
        || ' ' || COALESCE(new.tool_name, '') || ' ' || COALESCE(new.tool_calls, '')
    );
END;
`

Inline content word index of stores at FTS layout zero

View Source
var LegacyFTSTrigramSQL = `
CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts_trigram USING fts5(
    content,
    tokenize='trigram'
);

CREATE TRIGGER IF NOT EXISTS messages_fts_trigram_insert AFTER INSERT ON messages BEGIN
    INSERT INTO messages_fts_trigram(rowid, content) VALUES (
        new.id,
        COALESCE(` + ftsNewIndexedContentSQL + `, '')
        || ' ' || COALESCE(new.tool_name, '') || ' ' || COALESCE(new.tool_calls, '')
    );
END;

CREATE TRIGGER IF NOT EXISTS messages_fts_trigram_delete AFTER DELETE ON messages BEGIN
    DELETE FROM messages_fts_trigram WHERE rowid = old.id;
END;

CREATE TRIGGER IF NOT EXISTS messages_fts_trigram_update
AFTER UPDATE OF content, tool_name, tool_calls, role ON messages BEGIN
    DELETE FROM messages_fts_trigram WHERE rowid = old.id;
    INSERT INTO messages_fts_trigram(rowid, content) VALUES (
        new.id,
        COALESCE(` + ftsNewIndexedContentSQL + `, '')
        || ' ' || COALESCE(new.tool_name, '') || ' ' || COALESCE(new.tool_calls, '')
    );
END;
`

Inline content trigram index of stores at FTS layout zero

View Source
var LoadFTS5CJKExtension = func(ctx context.Context, conn SQLiteConn) bool {
	path := FTS5CJKSoPath(ctx)
	if !cjkFTSConfigEnabled(ctx) {
		return false
	}
	if os.Getenv("ICEBATH_FTS5_CJK_SO") != "" {
		if _, err := os.Stat(path); err != nil {
			return false
		}
	}
	if err := withRawSQLite(conn, registerCJKTokenizer); err != nil {
		pkgLog().Warn(fmt.Sprintf("fts5_cjk extension load failed (%s)", path), "error", err)
		return false
	}
	return true
}

Registers the built in cjk_unicode61 tokenizer on conn unless sessions.cjk_fts is off or an explicit extension path is absent

View Source
var MessageCoreKeys = map[string]bool{"content": true, "name": true, "tool_calls": true, "role": true, DBRowSnapshot: true}

Keys the message sanitizer handles explicitly, every other key is swept generically

View Source
var MessagingPlatformLabels func() []string

Every shipped platform value plus bundled plugin platforms and aliases, assigned from pkg/gateway by the process wiring

View Source
var MessagingPlatformSource func(source string) bool

Hook into pkg/gateway naming whether a row source label is a messaging platform other than local and the API transport

View Source
var OpenDB = func(ctx context.Context, path, dbLabel string, opts ...OpenDBOption) (SQLiteConn, error) {
	cfg := openDBConfig{busyTimeoutMS: 5000, wal: true, walLockRetries: 1, connect: openDBConnect}
	for _, opt := range opts {
		opt(&cfg)
	}
	if err := os.MkdirAll(filepath.Dir(path), 0o777); err != nil {
		return nil, err
	}
	conn, err := cfg.connect(path, SQLiteConfig{Timeout: float64(cfg.busyTimeoutMS) / 1000})
	if err != nil {
		return nil, err
	}
	ok := false
	defer func() {
		if !ok {
			conn.Close()
		}
	}()
	if _, err := conn.ExecContext(ctx, fmt.Sprintf("PRAGMA busy_timeout=%d", cfg.busyTimeoutMS)); err != nil {
		return nil, err
	}
	if cfg.wal {
		for attempt := 0; attempt < cfg.walLockRetries; attempt++ {
			_, err := ApplyWALWithFallback(ctx, conn, dbLabel, false)
			if err == nil {
				break
			}
			if !isOperationalError(err) || strings.ToLower(errText(err)) != "database is locked" || attempt+1 == cfg.walLockRetries {
				return nil, err
			}
			openDBSleep(time.Duration(float64(10*time.Millisecond) * float64(int64(1)<<attempt)))
		}
	}
	if cfg.foreignKeys {
		if _, err := conn.ExecContext(ctx, "PRAGMA foreign_keys=ON"); err != nil {
			return nil, err
		}
	}
	if cfg.synchronousFull {
		if _, err := conn.ExecContext(ctx, "PRAGMA synchronous=FULL"); err != nil {
			return nil, err
		}
	}
	if cfg.initialize != nil {
		if err := cfg.initialize(ctx, conn); err != nil {
			return nil, err
		}
	}
	ok = true
	return conn, nil
}

Opens path with its parent created, applies the pragma stack and initialize, closing the connection on any failure

View Source
var PersistenceErrorCauses = []string{
	"locked", "compression", "compression_closed", "turn_lease", "corrupt", "fts_index",
	"replaced", "deleted_wal", "disk", "session_row_missing", "unknown",
}

Lists every bucket ClassifyPersistenceError returns

View Source
var PersistenceOnlyMessageFields = map[string]bool{
	"timestamp": true, "display_kind": true, "display_metadata": true, "_row_id": true, "_submit_row_session_id": true,
	MergedTurnPrefix: true, MessageUID: true, AbsorbedMessageUIDs: true, ToolCallUIDs: true, ToolCallUID: true,
	MergedDurableRows: true, UnnamedDurableRows: true, RetiredDurableRows: true,
	DBRowSnapshot: true, CanonicalRow: true, RestoredFromStore: true,
}

Keys the request builder strips from every outgoing copy and the token estimator ignores

View Source
var PruneFilterNames = map[string]bool{
	"last_active_before": true, "last_active_after": true, "started_before": true, "started_after": true,
	"source": true, "title_like": true, "end_reason": true, "cwd_prefix": true, "min_messages": true,
	"max_messages": true, "model_like": true, "provider": true, "user_id": true, "chat_id": true,
	"chat_type": true, "branch_like": true, "min_tokens": true, "max_tokens": true, "min_cost": true,
	"max_cost": true, "min_tool_calls": true, "max_tool_calls": true,
	"archived": true, "include_pinned": true, "lineage_tips_only": true,
}

Filter keyword names the prune store call accepts beside older_than_days

View Source
var RepairBookkeepingFields = map[string]bool{DBRowSnapshot: true, CanonicalRow: true, RestoredFromStore: true}

Repair bookkeeping keys riding on batch rows and live dicts

View Source
var ReplaySidecars = []string{"reasoning", "reasoning_content", "reasoning_details", "codex_reasoning_items", "codex_message_items"}

Replayed reasoning carriers a compaction claim compares

View Source
var ResetSessionEntry func(previous *jsonutil.Object, childID string) (*jsonutil.Object, error)

Routing entry of a fresh local reset child built from the parent's stored entry, assigned by the gateway wiring

View Source
var RetiredGenerationMainImageMaxBytes int64 = 512 * 1024 * 1024

Main image size up to which a capture copies the whole file instead of its header

View Source
var SanitizeToolsNonASCII = SanitizeStructureNonASCII

Strips non ASCII characters from tool schemas in place

View Source
var SaveFormats = []string{"json", "md", "html"}
View Source
var SchemaHistory = map[string]TableHistory{
	"sessions": {
		Base: []string{
			"id", "source", "user_id", "model", "model_config",
			"system_prompt", "parent_session_id", "started_at", "ended_at",
			"end_reason", "message_count", "tool_call_count", "input_tokens",
			"output_tokens",
		},
		Events: []SchemaEvent{
			{"01 2026-03-08T23:32Z c5e8166c8b", []SchemaEdit{{"+", "title", "output_tokens"}}},
			{"02 2026-03-17T10:44Z d417ba2a48", []SchemaEdit{
				{"+", "cache_read_tokens", "output_tokens"},
				{"+", "cache_write_tokens", "cache_read_tokens"},
				{"+", "reasoning_tokens", "cache_write_tokens"},
				{"+", "billing_provider", "reasoning_tokens"},
				{"+", "billing_base_url", "billing_provider"},
				{"+", "billing_mode", "billing_base_url"},
				{"+", "estimated_cost_usd", "billing_mode"},
				{"+", "actual_cost_usd", "estimated_cost_usd"},
				{"+", "cost_status", "actual_cost_usd"},
				{"+", "cost_source", "cost_status"},
				{"+", "pricing_version", "cost_source"},
			}},
			{"03 2026-04-22T12:51Z 5fb143169b", []SchemaEdit{{"+", "api_call_count", "title"}}},
			{"04 2026-05-10T20:06Z 878611a79d", []SchemaEdit{
				{"+", "handoff_pending", "api_call_count"},
				{"+", "handoff_platform", "handoff_pending"},
			}},
			{"05 2026-05-10T20:06Z 00ce5f04d9", []SchemaEdit{
				{"-", "handoff_pending", ""},
				{"+", "handoff_state", "api_call_count"},
				{"+", "handoff_error", "handoff_platform"},
			}},
			{"06 2026-05-31T22:46Z 51c68d4ab1", []SchemaEdit{{"+", "cwd", "reasoning_tokens"}}},
			{"07 2026-06-01T08:22Z 3e59be0c41", []SchemaEdit{{"+", "rewind_count", "handoff_error"}}},
			{"08 2026-06-02T01:41Z 85b65e29f0", []SchemaEdit{{"+", "archived", "rewind_count"}}},
			{"09 2026-06-25T22:49Z ffa3d3c811", []SchemaEdit{
				{"+", "git_branch", "cwd"},
				{"+", "git_repo_root", "git_branch"},
			}},
			{"10 2026-06-28T22:10Z 86e64900b9", []SchemaEdit{
				{"+", "session_key", "user_id"},
				{"+", "chat_id", "session_key"},
				{"+", "chat_type", "chat_id"},
				{"+", "thread_id", "chat_type"},
			}},
			{"11 2026-06-30T08:06Z f2ccb2859f", []SchemaEdit{
				{"+", "compression_failure_cooldown_until", "handoff_error"},
				{"+", "compression_failure_error", "compression_failure_cooldown_until"},
			}},
			{"12 2026-07-05T21:01Z 747386ecfa", []SchemaEdit{
				{"+", "display_name", "thread_id"},
				{"+", "origin_json", "display_name"},
				{"+", "expiry_finalized", "origin_json"},
			}},
			{"13 2026-07-13T20:49Z af7dceaf77", []SchemaEdit{
				{"+", "compression_fallback_streak", "compression_failure_error"},
			}},
			{"14 2026-07-15T16:50Z e8b7ce8c19", []SchemaEdit{{"+", "profile_name", "compression_fallback_streak"}}},
			{"15 2026-07-23T15:08Z ec5835ab8b", []SchemaEdit{
				{"+", "compression_ineffective_count", "compression_fallback_streak"},
			}},
			{"16 2026-07-24T16:15Z 951d606730", []SchemaEdit{{"+", "pinned", "archived"}}},
			{"17 2026-07-27T19:14Z cfb206fe2e", []SchemaEdit{
				{"+", "last_activity_at", "title"},
				{"+", "last_activity_description", "last_activity_at"},
				{"+", "last_activity_provenance", "last_activity_description"},
			}},
			{"18 2026-07-27T19:22Z 5646fed97e", []SchemaEdit{
				{"-", "last_activity_at", ""},
				{"-", "last_activity_description", ""},
				{"-", "last_activity_provenance", ""},
			}},
			{"19 2026-08-02T23:16Z c2088efe9e", []SchemaEdit{
				{"+", "last_activity_at", "title"},
				{"+", "last_activity_description", "last_activity_at"},
				{"+", "last_activity_provenance", "last_activity_description"},
			}},
			{"20 2026-08-03T15:07Z 7d066c3c56", []SchemaEdit{{"+", "system_prompt_hash", "system_prompt"}}},
			{"21 2026-08-04T19:20Z d98287fe3c", []SchemaEdit{{"+", "last_read_at", "pinned"}}},
			{"22 2026-08-08T22:17Z fe42097865", []SchemaEdit{{"+", "title_source", "title"}}},
			{"23 2026-08-15T07:31Z fbaea9bddc", []SchemaEdit{{"+", "hidden", "pinned"}}},
			{"24 2026-08-15T07:33Z e89532d97e", []SchemaEdit{{"+", "git_metadata_generation", "git_repo_root"}}},
			{"25 2026-09-02T11:14Z 238b6c1ab9", []SchemaEdit{
				{"+", "compression_recovery_deadline", "compression_ineffective_count"},
			}},
			{"26 2026-09-02T14:22Z 8e4366d358", []SchemaEdit{{"+", "tool_names", "last_read_at"}}},
			{"27 2026-09-19T00:10Z 922a0c3c87", []SchemaEdit{{"+", "transport_profile", "profile_name"}}},
			{"28 2026-09-25T23:25Z 2941aadffa", []SchemaEdit{{"+", "compression_overload_streak", "compression_recovery_deadline"}}},
			{"29 2026-09-27T00:29Z d75f29934b", []SchemaEdit{{"+", "created_source", "source"}}},
			{"30 2026-09-28T00:00Z #117713", []SchemaEdit{{"+", "auto_archived", "archived"}}},
			{"31 2026-09-08T18:45Z 0695b12b4c", []SchemaEdit{
				{"+", "runtime_revision", "id"},
				{"+", "runtime_generation", "runtime_revision"},
			}},
			{"32 2026-10-18T10:11Z 1fc1999769", []SchemaEdit{{"+", "transcript_revision", "tool_names"}}},
		},
	},
	"messages": {
		Base: []string{
			"id", "session_id", "role", "content", "tool_call_id",
			"tool_calls", "tool_name", "timestamp", "token_count",
		},
		Events: []SchemaEvent{
			{"01 2026-02-21T08:05Z b33ed9176f", []SchemaEdit{{"+", "finish_reason", "token_count"}}},
			{"02 2026-03-25T16:47Z 42fec19151", []SchemaEdit{
				{"+", "reasoning", "finish_reason"},
				{"+", "reasoning_details", "reasoning"},
				{"+", "codex_reasoning_items", "reasoning_details"},
			}},
			{"03 2026-04-22T11:31Z a7d78d3bfd", []SchemaEdit{{"+", "reasoning_content", "reasoning"}}},
			{"04 2026-04-26T01:22Z 81e01f6ee9", []SchemaEdit{{"+", "codex_message_items", "codex_reasoning_items"}}},
			{"05 2026-05-20T20:00Z 31a0100104", []SchemaEdit{{"+", "platform_message_id", "codex_message_items"}}},
			{"06 2026-05-23T08:33Z 4a91e36495", []SchemaEdit{{"+", "observed", "platform_message_id"}}},
			{"07 2026-06-01T08:22Z 3e59be0c41", []SchemaEdit{{"+", "active", "observed"}}},
			{"08 2026-06-11T03:45Z aaccaada28", []SchemaEdit{{"+", "anthropic_content_blocks", "reasoning_details"}}},
			{"09 2026-06-11T03:45Z efcbbde48c", []SchemaEdit{{"-", "anthropic_content_blocks", ""}}},
			{"10 2026-06-20T17:57Z 854d75723f", []SchemaEdit{{"+", "compacted", "active"}}},
			{"11 2026-07-11T12:41Z a0a6cd80f5", []SchemaEdit{{"+", "effect_disposition", "tool_name"}}},
			{"12 2026-07-19T02:55Z 7b3dcee928", []SchemaEdit{{"+", "api_content", "compacted"}}},
			{"13 2026-07-23T18:46Z a4bc1ca502", []SchemaEdit{
				{"+", "display_kind", "api_content"},
				{"+", "display_metadata", "display_kind"},
			}},
			{"14 2026-08-25T10:55Z 1104ffe0b9", []SchemaEdit{{"+", "_compressed_summary", "observed"}}},
			{"15 2026-09-09T17:05Z 1c6683e8e0", []SchemaEdit{
				{"+", "display_identity", "display_metadata"},
				{"+", "display_order", "display_identity"},
			}},
			{"16 2026-09-28T08:42Z eed37d63ce", []SchemaEdit{
				{"+", "message_uid", "display_order"},
				{"+", "absorbed_message_uids", "message_uid"},
				{"+", "tool_call_uids", "absorbed_message_uids"},
				{"+", "tool_call_uid", "tool_call_uids"},
			}},
		},
	},
	"session_model_usage": {
		Base: []string{
			"session_id", "model", "billing_provider", "billing_base_url",
			"api_call_count", "input_tokens", "output_tokens",
			"cache_read_tokens", "cache_write_tokens", "reasoning_tokens",
			"estimated_cost_usd", "first_seen", "last_seen",
		},
		Events: []SchemaEvent{
			{"01 2026-07-11T12:59Z 0d63c23f36", []SchemaEdit{
				{"+", "billing_mode", "billing_base_url"},
				{"+", "actual_cost_usd", "estimated_cost_usd"},
				{"+", "cost_status", "actual_cost_usd"},
				{"+", "cost_source", "cost_status"},
			}},
			{"02 2026-07-16T11:23Z eb6aa03609", []SchemaEdit{{"+", "task", "billing_mode"}}},
		},
	},
}
View Source
var SchemaSQL = `
CREATE TABLE IF NOT EXISTS schema_version (
    version INTEGER NOT NULL
);

CREATE TABLE IF NOT EXISTS system_prompts (
    hash TEXT PRIMARY KEY,
    prompt TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS sessions (
    id TEXT PRIMARY KEY,
    runtime_revision INTEGER NOT NULL DEFAULT 0,
    runtime_generation INTEGER NOT NULL DEFAULT 0,
    source TEXT NOT NULL,
    created_source TEXT,
    user_id TEXT,
    session_key TEXT,
    chat_id TEXT,
    chat_type TEXT,
    thread_id TEXT,
    display_name TEXT,
    origin_json TEXT,
    expiry_finalized INTEGER DEFAULT 0,
    model TEXT,
    model_config TEXT,
    system_prompt TEXT,
    system_prompt_hash TEXT,
    parent_session_id TEXT,
    started_at REAL NOT NULL,
    ended_at REAL,
    end_reason TEXT,
    message_count INTEGER DEFAULT 0,
    tool_call_count INTEGER DEFAULT 0,
    input_tokens INTEGER DEFAULT 0,
    output_tokens INTEGER DEFAULT 0,
    cache_read_tokens INTEGER DEFAULT 0,
    cache_write_tokens INTEGER DEFAULT 0,
    reasoning_tokens INTEGER DEFAULT 0,
    cwd TEXT,
    git_branch TEXT,
    git_repo_root TEXT,
    git_metadata_generation INTEGER NOT NULL DEFAULT 0,
    billing_provider TEXT,
    billing_base_url TEXT,
    billing_mode TEXT,
    estimated_cost_usd REAL,
    actual_cost_usd REAL,
    cost_status TEXT,
    cost_source TEXT,
    pricing_version TEXT,
    title TEXT,
    title_source TEXT,
    last_activity_at REAL,
    last_activity_description TEXT,
    last_activity_provenance TEXT,
    api_call_count INTEGER DEFAULT 0,
    handoff_state TEXT,
    handoff_platform TEXT,
    handoff_error TEXT,
    compression_failure_cooldown_until REAL,
    compression_failure_error TEXT,
    compression_fallback_streak INTEGER NOT NULL DEFAULT 0,
    compression_ineffective_count INTEGER NOT NULL DEFAULT 0,
    compression_recovery_deadline REAL,
    compression_overload_streak INTEGER NOT NULL DEFAULT 0,
    profile_name TEXT,
    transport_profile TEXT,
    rewind_count INTEGER NOT NULL DEFAULT 0,
    archived INTEGER NOT NULL DEFAULT 0,
    auto_archived INTEGER NOT NULL DEFAULT 0,
    pinned INTEGER NOT NULL DEFAULT 0,
    hidden INTEGER NOT NULL DEFAULT 0,
    last_read_at REAL,
    tool_names TEXT,
    transcript_revision INTEGER NOT NULL DEFAULT 0,
    FOREIGN KEY (parent_session_id) REFERENCES sessions(id),
    FOREIGN KEY (system_prompt_hash) REFERENCES system_prompts(hash)
);

CREATE TABLE IF NOT EXISTS messages (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    session_id TEXT NOT NULL REFERENCES sessions(id),
    role TEXT NOT NULL,
    content TEXT,
    tool_call_id TEXT,
    tool_calls TEXT,
    tool_name TEXT,
    effect_disposition TEXT,
    timestamp REAL NOT NULL,
    token_count INTEGER,
    finish_reason TEXT,
    reasoning TEXT,
    reasoning_content TEXT,
    reasoning_details TEXT,
    codex_reasoning_items TEXT,
    codex_message_items TEXT,
    platform_message_id TEXT,
    observed INTEGER DEFAULT 0,
    _compressed_summary INTEGER NOT NULL DEFAULT 0,
    active INTEGER NOT NULL DEFAULT 1,
    compacted INTEGER NOT NULL DEFAULT 0,
    api_content TEXT,
    display_kind TEXT,
    display_metadata TEXT,
    display_identity BLOB,
    display_order INTEGER,
    message_uid TEXT,
    absorbed_message_uids TEXT,
    tool_call_uids TEXT,
    tool_call_uid TEXT
);

CREATE TABLE IF NOT EXISTS session_model_usage (
    session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
    model TEXT NOT NULL,
    billing_provider TEXT NOT NULL DEFAULT '',
    billing_base_url TEXT NOT NULL DEFAULT '',
    billing_mode TEXT NOT NULL DEFAULT '',
    task TEXT NOT NULL DEFAULT '',
    api_call_count INTEGER NOT NULL DEFAULT 0,
    input_tokens INTEGER NOT NULL DEFAULT 0,
    output_tokens INTEGER NOT NULL DEFAULT 0,
    cache_read_tokens INTEGER NOT NULL DEFAULT 0,
    cache_write_tokens INTEGER NOT NULL DEFAULT 0,
    reasoning_tokens INTEGER NOT NULL DEFAULT 0,
    estimated_cost_usd REAL NOT NULL DEFAULT 0,
    actual_cost_usd REAL NOT NULL DEFAULT 0,
    cost_status TEXT,
    cost_source TEXT,
    first_seen REAL,
    last_seen REAL,
    PRIMARY KEY (session_id, model, billing_provider, billing_base_url, billing_mode, task)
);

CREATE TABLE IF NOT EXISTS runtime_epoch (
    singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
    epoch INTEGER NOT NULL CHECK (epoch > 0),
    instance_id TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_admissions (
    seq INTEGER PRIMARY KEY AUTOINCREMENT,
    admission_id TEXT NOT NULL UNIQUE,
    request_id TEXT NOT NULL,
    principal_id TEXT NOT NULL,
    target_session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE RESTRICT,
    lineage_json TEXT NOT NULL,
    payload_json TEXT NOT NULL,
    payload_digest TEXT NOT NULL,
    intent TEXT NOT NULL CHECK (intent IN ('queue','steer','redirect')),
    status TEXT NOT NULL CHECK (status IN ('queued','started','unknown','terminal')),
    outcome TEXT,
    owner_epoch INTEGER,
    generation INTEGER,
    UNIQUE (principal_id, target_session_id, request_id),
    CHECK (status != 'started' OR (owner_epoch IS NOT NULL AND generation IS NOT NULL))
);
CREATE INDEX IF NOT EXISTS session_admissions_pending
    ON session_admissions(target_session_id, status, seq);
-- Cron run history finds a job's unified-runtime runs by the scheduler principal's request ids
-- (` + "`" + `` + "`" + `cron:<job>:<execution>` + "`" + `` + "`" + `); without this a lookup walked
-- every cron admission of every job. Partial: interactive turns, the bulk of admissions, pay
-- nothing for it. The constant leading column gives the planner equality + range over a covering
-- index, so it beats the UNIQUE autoindex's bare principal_id prefix even without ANALYZE stats.
-- The WHERE is built from CRON_PRINCIPAL_ID, the literal the run queries inline, so they cannot drift.
CREATE INDEX IF NOT EXISTS idx_session_admissions_cron_request
    ON session_admissions(principal_id, request_id, target_session_id) WHERE principal_id = '` + CronPrincipalID + `';
CREATE TABLE IF NOT EXISTS worker_executions (
    execution_id TEXT PRIMARY KEY,
    session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE RESTRICT,
    kind TEXT NOT NULL CHECK (kind IN ('cron','child','compute','kanban')),
    owner_epoch INTEGER NOT NULL,
    generation INTEGER NOT NULL,
    status TEXT NOT NULL CHECK (status IN ('registered','running','unknown','terminal')),
    adoption_digest TEXT NOT NULL,
    last_sequence INTEGER NOT NULL DEFAULT 0 CHECK (last_sequence >= 0)
);
-- Lineage-wide worker exclusion (claim/register/reset) probes every row of a conversation's lineage
-- inside the write transaction; without this each probe scanned the whole (only-growing) table.
CREATE INDEX IF NOT EXISTS idx_worker_executions_session_status
    ON worker_executions(session_id, status);
CREATE TABLE IF NOT EXISTS worker_receipts (
    execution_id TEXT NOT NULL REFERENCES worker_executions(execution_id) ON DELETE RESTRICT,
    sequence INTEGER NOT NULL CHECK (sequence > 0),
    payload_digest TEXT NOT NULL,
    result_json TEXT NOT NULL,
    PRIMARY KEY (execution_id, sequence)
);

CREATE TABLE IF NOT EXISTS state_meta (
    key TEXT PRIMARY KEY,
    value TEXT
);

CREATE TABLE IF NOT EXISTS gateway_routing (
    scope TEXT NOT NULL DEFAULT '',
    session_key TEXT NOT NULL,
    entry_json TEXT NOT NULL,
    updated_at REAL NOT NULL,
    PRIMARY KEY (scope, session_key)
);

CREATE TABLE IF NOT EXISTS gateway_hygiene_state (
    session_key TEXT PRIMARY KEY,
    failure_streak INTEGER NOT NULL DEFAULT 0
);

-- Monotonic conversation generation per routing peer (#96811).
--
-- A host-declared conversation key (X-Icebath-Session-Key / build_session_key)
-- is per-CHAT and outlives any single conversation on it, so the prompt-cache
-- affinity scope derived from it must be qualified by which conversation is
-- currently live. Deriving that from the session rows themselves
-- (COUNT/MAX over _RESET_END_REASONS boundaries) cannot prove non-reuse:
-- delete_session() and bulk pruning remove ended rows, so an aggregate can
-- return a pair it already emitted and hand a new conversation a retired
-- affinity identity.
--
-- This counter lives outside prunable session history and only ever
-- increments, once per boundary actually written, so a generation can never
-- be reused for a peer even if every session row behind it is deleted.
--
-- These rows are deliberately NEVER garbage-collected, including when every
-- session row for the peer is gone. Collecting one resets that peer to "no
-- generation", so its next boundary writes generation = 1 again and re-issues
-- a gwk_ scope a retired conversation already used — exactly the ABA this
-- table exists to close. Do not add it to delete_session()'s cascade or to any
-- prune sweep. One (TEXT, TEXT, INTEGER) row per routing peer is the intended,
-- bounded cost.
CREATE TABLE IF NOT EXISTS conversation_generations (
    source TEXT NOT NULL,
    session_key TEXT NOT NULL,
    generation INTEGER NOT NULL DEFAULT 0,
    PRIMARY KEY (source, session_key)
);

-- Per-backend liveness heartbeat (#94895). Each serve / tui_gateway process
-- registers a row at startup and refreshes ` + "`" + `` + "`" + `last_heartbeat` + "`" + `` + "`" + ` periodically.
-- The startup orphan sweep (sessions.startup_orphan_reap) consults this
-- table to avoid reaping rows whose owning backend is still alive but
-- just idle (multi-backend state.db shared by isolated serve processes).
-- A backend whose ` + "`" + `` + "`" + `last_heartbeat` + "`" + `` + "`" + ` is older than the heartbeat staleness
-- window is treated as dead; rows without ANY matching heartbeat fall back
-- to the original staleness predicate so legacy deployments keep working.
CREATE TABLE IF NOT EXISTS gateway_heartbeats (
    backend_id TEXT PRIMARY KEY,
    pid INTEGER NOT NULL,
    started_at REAL NOT NULL,
    last_heartbeat REAL NOT NULL,
    profile TEXT NOT NULL DEFAULT '',
    host TEXT NOT NULL DEFAULT ''
);

CREATE TABLE IF NOT EXISTS compression_locks (
    session_id TEXT PRIMARY KEY,
    holder TEXT NOT NULL,
    acquired_at REAL NOT NULL,
    expires_at REAL NOT NULL
);

CREATE TABLE IF NOT EXISTS session_turn_leases (
    conversation_id TEXT PRIMARY KEY,
    holder TEXT NOT NULL,
    acquired_at REAL NOT NULL,
    expires_at REAL NOT NULL
);

CREATE TABLE IF NOT EXISTS async_delegations (
    delegation_id TEXT PRIMARY KEY,
    origin_session TEXT NOT NULL,
    origin_ui_session_id TEXT NOT NULL DEFAULT '',
    parent_session_id TEXT,
    state TEXT NOT NULL,
    dispatched_at REAL NOT NULL,
    completed_at REAL,
    updated_at REAL NOT NULL,
    event_json TEXT,
    result_json TEXT,
    delivery_state TEXT NOT NULL DEFAULT 'pending',
    delivery_attempts INTEGER NOT NULL DEFAULT 0,
    delivered_at REAL,
    owner_pid INTEGER,
    owner_started_at INTEGER,
    task_json TEXT,
    -- Owner-side execution fence (unified runtime).
    owner_execution_id TEXT,
    delivery_claim TEXT,
    delivery_claimed_at REAL,
    -- Mirrors the delegation tool's own CREATE TABLE (tools/async_delegation.py
    -- _initialize_schema). Keeping the canonical fresh-install shape identical
    -- to the tool's avoids a silent schema drift: the tool's lazy
    -- ALTER TABLE ADD COLUMN used to be the only source of this column, so two
    -- databases at the same schema_version had different
    -- async_delegations shapes depending on whether the delegation tool had
    -- ever run, breaking rebuild/replay pipelines that reconstruct state.db
    -- from the canonical schema (#94691).
    origin_session_id TEXT NOT NULL DEFAULT ''
);

CREATE INDEX IF NOT EXISTS idx_sessions_source ON sessions(source);
CREATE INDEX IF NOT EXISTS idx_sessions_source_id ON sessions(source, id);
CREATE INDEX IF NOT EXISTS idx_sessions_parent ON sessions(parent_session_id);
CREATE INDEX IF NOT EXISTS idx_sessions_started ON sessions(started_at DESC);
CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id, timestamp);
CREATE INDEX IF NOT EXISTS idx_messages_session_id ON messages(session_id, id);
-- Partial index for the Insights assistant tool-call scan
-- (agent/insights.py _get_tool_usage / _get_skill_usage): those queries filter
-- messages by role='assistant' AND tool_calls IS NOT NULL, a small fraction of
-- rows on a large state.db. role and tool_calls are base columns, so this can
-- live in SCHEMA_SQL rather than DEFERRED_INDEX_SQL.
CREATE INDEX IF NOT EXISTS idx_messages_assistant_calls_by_session
    ON messages(session_id)
    WHERE role = 'assistant' AND tool_calls IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_compression_locks_expires ON compression_locks(expires_at);
CREATE INDEX IF NOT EXISTS idx_session_turn_leases_expires ON session_turn_leases(expires_at);
CREATE INDEX IF NOT EXISTS idx_session_model_usage_session ON session_model_usage(session_id);
CREATE INDEX IF NOT EXISTS idx_session_model_usage_model ON session_model_usage(model);
CREATE INDEX IF NOT EXISTS idx_async_delegations_delivery
    ON async_delegations(delivery_state, completed_at);
`

Declared tables and indexes every writable open runs, additive and idempotent

View Source
var SecretSubstrings = []string{"KEY", "TOKEN", "SECRET", "PASSWORD", "CREDENTIAL", "PASSWD", "AUTH", "DSN",
	"WEBHOOK", "CREDS", "BEARER", "APIKEY", "COOKIE"}

SecretSubstrings are the name fragments that mark an environment variable as a credential

View Source
var SessionIDPattern = regexp.MustCompile(`^\p{Nd}{8}_\p{Nd}{6}_`)

Matches the timestamp prefix every minted session id starts with

View Source
var SessionIDRecognizers = []*regexp.Regexp{
	SessionIDPattern,
	regexp.MustCompile(`^cron_[A-Za-z0-9][A-Za-z0-9._-]*_\p{Nd}{8}_\p{Nd}{6}\n?$`),
	regexp.MustCompile(`^bg_(?:\p{Nd}{6}_)?[0-9a-f]{6}\n?$`),
	regexp.MustCompile(`^room_[0-9a-f]{32}\n?$`),
	regexp.MustCompile(`^api_\p{Nd}{9,}_[0-9a-f]{8}\n?$`),
	regexp.MustCompile(`^api-[0-9a-f]{16}\n?$`),
	regexp.MustCompile(`^run_[0-9a-f]{32}\n?$`),
	regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\n?$`),
}

Matches every id shape a surface of this repo mints

View Source
var SessionKeyNamespace func(profile string) string

Gateway session key namespace builder, the agent prefix a profile's keys carry, wired by the host

View Source
var SidecarKeys = map[string]bool{"_usage_anchor": true, "_proactive_prune_rearm_tokens": true, "_anthropic_rejected_thinking": true}

model_config sidecar keys a worker may patch

View Source
var SummaryCarrierDurableDisplayMetadataKeys = []string{"reactions"}

Display metadata keys a summary carrier keeps on its live projection

View Source
var UnpricedCoreFields = []string{"_anthropic_content_blocks", "reasoning_details", "extra_content", "bedrock_content_blocks"}

Replay carriers the preflight estimate prices at zero before profile declared carrier keys join

View Source
var WorkerAutomationCodecs = map[string]func(raw string) (AutomationState, error){}

Decoders of the goal, heartbeat and loop state rows, assigned by the agent wiring

Functions

func AcquireTurnLeasePolling

func AcquireTurnLeasePolling(owner string, try TurnLeaseTry, sleepRetry func(deadline, patienceS float64) bool, sessionID, holder string, o TurnLeaseWait) (bool, error)

Polls a store's turn lease try until acquired, aborted or out of time, a nil sleep raising the missing attribute

func AddColumnIfMissing

func AddColumnIfMissing(ctx context.Context, conn SQLiteConn, table, column, ddl string) (bool, error)

Adds a column through ALTER TABLE, true when this call added it and false when a concurrent migrator already had

func AdmissionFingerprint

func AdmissionFingerprint(canonicalTarget string, payload map[string]any) (string, error)

Hashes the canonical target and payload after authorization and media capture

func AdmissionRow

func AdmissionRow(row *jsonutil.Object) (*jsonutil.Object, error)

Public admission dict of a raw ledger row, its payload decoded and its digest and lineage dropped

func AdoptableCompression

func AdoptableCompression(ctx context.Context, conn SQLiteConn, receipt *jsonutil.Object) ([]string, *jsonutil.Object, error)

Untracked compression steps a local receipt would adopt with its route entry, nil when nothing is adoptable

func AppendMessage

func AppendMessage(messages *[]map[string]any, message map[string]any, timestamp *float64) map[string]any

Stamps and appends one live transcript message

func ApplyDatabasePragmas

func ApplyDatabasePragmas(ctx context.Context, conn SQLiteConn, dbLabel string) error

Applies the optional sizing pragmas and then the synchronous level the database settings name

func ApplyDeclaredSchema

func ApplyDeclaredSchema(ctx context.Context, conn SQLiteConn) error

Brings a raw state.db connection to the declared shape without committing, columns before and after the DDL

func ApplyDurabilityBarriers

func ApplyDurabilityBarriers(ctx context.Context, conn SQLiteConn) bool

Durability barriers plus the configured synchronous level for guest users of the state database

func ApplyWALWithFallback

func ApplyWALWithFallback(ctx context.Context, conn SQLiteConn, dbLabel string, requireWAL bool) (string, error)

Sets WAL, falling back to DELETE where the filesystem refuses it and never live downgrading an on disk WAL file

func AsyncCall

func AsyncCall[T any](ctx context.Context, a *AsyncSessionDB, fn func(db *SessionDB) (T, error)) (T, error)

Runs fn against the wrapped store on its own goroutine, returning early with the context error when ctx ends first

func AuthorizeHistory

func AuthorizeHistory(ctx context.Context, conn SQLiteConn, actor HistoryActor, sessionID string, claim bool) (bool, error)

Whether the actor controls the unrouted history row, claiming it when asked, permission_denied for a foreign owner

func AutoPruneAdviceLines

func AutoPruneAdviceLines(advice PruneAdvice, commandPrefix string) []string

Plain text prompt every surface shares, its last line naming the commands under the prefix

func AutoPruneAnswered

func AutoPruneAnswered(ctx context.Context, h string) bool

Reports a question settled at this moment, a saved answer or a live later snooze

func AutoPruneCommand

func AutoPruneCommand(ctx context.Context, args, h string) (string, error)

Reply of the autoprune command with on, off, later or status, the one handler every surface shares

func AutoPruneDecide

func AutoPruneDecide(ctx context.Context, enable bool, h string) bool

Saves the answer as an explicit sessions.auto_prune, false when the save failed or a managed value wins

func AutoPruneNoticeDue

func AutoPruneNoticeDue(ctx context.Context, h string, shown map[string]float64) bool

Reports a home due for the local notice, again once a full snooze window passed since it was shown

func AutoPruneNoticePayload

func AutoPruneNoticePayload(advice PruneAdvice) *jsonutil.Object

Notification payload for the TUI and gateway, a short status text with the full question as detail

func AutoPruneSnooze

func AutoPruneSnooze(ctx context.Context, h string, seconds float64) error

Records a later answer that holds for the given seconds

func AutoPruneSnoozed

func AutoPruneSnoozed(ctx context.Context, h string, now float64) bool

Reports a later answer whose snooze window has not passed, now defaulting to the clock

func AutoPruneUndecided

func AutoPruneUndecided(ctx context.Context, h string) bool

Reports a home whose user and managed config both leave sessions.auto_prune unset

func BackupSQLite

func BackupSQLite(src, dst SQLiteConn) error

Copies every page of one open database into another through the online backup interface

func BaseIndexRealignedOnOpen

func BaseIndexRealignedOnOpen(stored string) bool

Reports an external content base index not reading messages_fts_src, which the next read write open rebuilds

func BaseIndexRecognised

func BaseIndexRecognised(ctx context.Context, conn SQLiteConn) (bool, error)

Reports messages_fts holding a definition this code or an earlier release created

func BaseSourceViewIsStale

func BaseSourceViewIsStale(ctx context.Context, conn SQLiteConn) (bool, error)

Reports messages_fts_src existing with a definition other than the one this code creates

func BindingNames

func BindingNames(saved, profileID, subject any) bool

Whether a stored binding names the subject in the profile under the same owner rule

func BorrowLiveSharedSessionDBs

func BorrowLiveSharedSessionDBs(fn func([]*DB) error) error

Runs fn over every live shared database with one registry reference pinned per handle until fn returns

func BoundActivityDescription

func BoundActivityDescription(description string) string

Stripped activity text clamped to the description budget with an ellipsis

func BoundClientEnv

func BoundClientEnv(ctx context.Context) map[string]string

Client environment of the session executing under the context, nil when unbound

func BoundaryEndReasons

func BoundaryEndReasons() map[string]bool

BoundaryEndReasons is a copy of the deliberate conversation boundary end reasons

func CanonicalChain

func CanonicalChain(ctx context.Context, conn SQLiteConn, sessionID string) ([]string, error)

Compression lineage of a session from its root to its tip, read on the caller's connection

func CanonicalSQLitePath

func CanonicalSQLitePath(path string) (string, error)

Normalized absolute form of a procfs descriptor target with the deleted suffix stripped

func CaptureRetiredWALGeneration

func CaptureRetiredWALGeneration(ctx context.Context, dbPath string, sidecarIdentity map[string]FileIdentity, trigger string) (string, error)

Durably captures the lost wal generation this process still holds open and returns the artifact directory

func ChatPickKey

func ChatPickKey(principalID, sessionID string, params *jsonutil.Object) (string, string, error)

Receipt key and digest of a messaging chat pick on the mount the fences name

func CheckReplacedInput

func CheckReplacedInput(ctx context.Context, conn SQLiteConn, admissionID, binding string) error

Refuses an exact replacement replay unless its binding names the admission it retired

func ClassifyPersistenceError

func ClassifyPersistenceError(v any) string

Buckets an error or string into one of PersistenceErrorCauses

func ClassifySessionStatus

func ClassifySessionStatus(role any, hasToolCalls bool, finishReason any) string

Error for an error finish, interrupted for pending tool calls or a trailing user or tool row, else complete

func ClassifySummaryContent

func ClassifySummaryContent(content any) string

Classifies content as a standalone handoff, a merged tail plus summary, or empty when it is no summary

func ClientEnvConfiguredNames

func ClientEnvConfiguredNames(config any) map[string]bool

Profile extra tool names from terminal.client_env_passthrough

func ClientEnvScope

func ClientEnvScope(ctx context.Context, env map[string]string, local bool, rules *ClientEnvRules) context.Context

Context binding one session client environment, a nil env binding the gateway's own

func ClientHistoryRow

func ClientHistoryRow(row *jsonutil.Object) bool

Whether a routeless row is a chat a client app wrote under its own label, adopted as gui

func ClientLabel

func ClientLabel(source any) bool

Whether the source is a client app's own label rather than a surface, platform or automation label

func ClientRequest

func ClientRequest(requestJSON string, derived any) (*jsonutil.Object, error)

The frozen create request as the client sent it, a nil derived meaning a receipt from before route_derived

func CloseAll

func CloseAll() int

Closes every shared database regardless of refcount and returns how many, for shutdown after all work finished

func CloseAllUnder

func CloseAllUnder(directory string) int

Force closes every shared database whose file lives under directory and returns how many, waiting for pending closes there

func CloseLeakedTestInstances

func CloseLeakedTestInstances()

Closes every instance a test opened and left open, skipping handles the shared registry owns

func CmdRepair

func CmdRepair(ctx context.Context, ns map[string]any, w io.Writer) (int, error)

Repairs a state.db that does not open cleanly or lags the declared schema, a backup made first

func CmdSetJournalMode

func CmdSetJournalMode(ctx context.Context, ns map[string]any, w io.Writer) (int, error)

Switches the on disk journal mode of a store nobody else holds and verifies the file header

func CoalesceToolCallID

func CoalesceToolCallID(tc any) string

Effective call id of a tool call dict or struct, call_id before id with any bridge suffix cut, empty when none

func CollectClientEnv

func CollectClientEnv(environ map[string]string, config any) map[string]string

Client side allowlisted values of this shell, the profile extra names included

func CollectStateDBStats

func CollectStateDBStats(dbPath string) (*jsonutil.Object, error)

Strictly read only stats snapshot of a state.db file, every field collected independently and nil when it fails

func CompactResult

func CompactResult(result *jsonutil.Object, userMessage any) (*jsonutil.Object, error)

Turn result keeping replay, accounting and this turn's API suffix, never the cumulative history

func CompactTerminalReceipts

func CompactTerminalReceipts(ctx context.Context, conn SQLiteConn, executionID string) error

Retires an execution's children and shrinks its receipt bearing history to the retired marker

func CompactionInternalFields

func CompactionInternalFields() []string

Message fields that only carry compaction scaffolding

func CompressionMessageText

func CompressionMessageText(message map[string]any) string

String content or the newline joined text of dict parts, empty for anything else

func CompressionTipOn

func CompressionTipOn(ctx context.Context, conn SQLiteConn, sessionID string) (string, error)

Compression tip of a session walked on an already open connection

func ConnObject

func ConnObject(ctx context.Context, conn SQLiteConn, query string, args ...any) (*jsonutil.Object, error)

First row of a query on the connection as an object, nil when there is none

func ConnRow

func ConnRow(ctx context.Context, conn SQLiteConn, query string, args ...any) (map[string]any, error)

One row of a query as a column mapping, nil when the query returns none

func ContentHasPayload

func ContentHasPayload(content any) bool

Whether content holds text, typed blocks or any value the API treats as non empty

func ContentText

func ContentText(content any) string

Plain text of provider content, text parts joined with newlines

func ContentTextForContains

func ContentTextForContains(content any) string

Text view of message content for substring checks, list parts joined by newlines

func CopyIdentityFields

func CopyIdentityFields(src, dst map[string]any)

Copies the non empty uid, merge witness and tool call uid fields from src onto dst

func CopyShellLines

func CopyShellLines(sessionsDir, fromID, toID string, before *float64) error

Copies the shell lines of a session that ran before a time to another session, every line without a time bound

func CountDBHolders

func CountDBHolders(dbPath string) (int, bool)

Distinct pids holding the database open, a lower bound, false on any error or on hosts without a scan

func CoverageForCommit

func CoverageForCommit(sessionDB any, sessionID string, messages, verbatimTail []map[string]any) (covered []int64, unresolved []map[string]any, ok bool, err error)

Coverage for archive and compact, ok false keeps the watermark

func CreateConflict

func CreateConflict(ctx context.Context, conn SQLiteConn, sessionID string) (string, string, error)

Refusal code and message for creating an explicit id that is live or retired, empty strings when the create may proceed

func CreatedSurface

func CreatedSurface(label any) any

Created source of a policy or live label, nil for local, unknown and empty labels

func CronRequestID

func CronRequestID(jobID, executionID any) string

The admission request id of one cron fire

func CronRequestRange

func CronRequestRange(jobID any) (string, string)

Returns half open bounds of a job's cron request ids

func CronRunFromRequest

func CronRunFromRequest(requestID any, jobID *string) (string, string, bool)

Splits a cron fire request id into job and execution, a nil job meaning unknown

func DBHasLegacyInlineFTS

func DBHasLegacyInlineFTS(ctx context.Context, conn SQLiteConn) (bool, error)

Whether the store still carries the inline FTS layout the storage optimization replaces

func DBOpensCleanly

func DBOpensCleanly(ctx context.Context, dbPath string) (string, bool, error)

Probes a database on a fresh connection, returning the reason it is unhealthy or false when it opens cleanly

func DeclaredSnapshots

func DeclaredSnapshots(table string) ([][]string, error)

Every declared column order the table has shipped with, oldest first, unknown tables a KeyError

func DefaultSaveFilename

func DefaultSaveFilename(sessionID, format string) string

Default file name of a saved session, the id reduced to letters, digits, dashes and underscores

func DeleteTargets

func DeleteTargets(ctx context.Context, conn SQLiteConn, sessionID string) ([]string, error)

Requested session first, then every lineage segment, continuation and delegate the delete takes, sorted

func DescendantRange

func DescendantRange(executionID string) (string, string)

Primary key bounds holding every descendant id of the execution

func DescribeHolderPID

func DescribeHolderPID(pid int) string

Operator facing PID label with the first 80 characters of its whitespace collapsed command line

func DescribeSkillInvocation

func DescribeSkillInvocation(content, separator string) (string, bool)

Skill expanded turn rendered as typed, slash name and instruction joined by separator, false when not scaffolding

func DiscardOrphanWorkersOnReset

func DiscardOrphanWorkersOnReset(ctx context.Context, conn SQLiteConn, sessionIDs []string) error

Reset revokes unlinked unknown compute on each session and compacts its receipts

func DivertSessionTranscriptJSONL

func DivertSessionTranscriptJSONL(ctx context.Context, sessionID string, messages []any) (string, error)

Appends pending messages to sessions/<id>.jsonl under the home, returning the path or empty when nothing was written

func DropStaleAPIContent

func DropStaleAPIContent(msg map[string]any)

Drops the api_content sidecar of a message whose content was rewritten

func DropUndoneRows

func DropUndoneRows(export *jsonutil.Object) *jsonutil.Object

Drops the rows removed by undo, rewind or edit from a snapshot and rebuilds its timings from the rest

func DumpsExportedSession

func DumpsExportedSession(session *jsonutil.Object) (string, error)

One exported session as a JSON line, non ASCII text kept as written

func DurableContent

func DurableContent(content any) any

Text only db projection, multimodal envelopes as their summary and images as screenshot markers

func EncodeDisplayMetadata

func EncodeDisplayMetadata(displayMetadata any) (any, error)

Stored column value of a message's display metadata

func ErrText

func ErrText(v any) string

str() of an exception value with sqlite3 messages rendered as CPython prints them

func EscapeLike

func EscapeLike(text string) string

LIKE wildcards and the escape character escaped so text matches literally under ESCAPE backslash

func ExclusiveRepairDBGuard

func ExclusiveRepairDBGuard(ctx context.Context, dbPath string, fn func(guard SQLiteConn, guardErr error) error) error

Runs fn with one connection excluding writers, or with the error that kept exclusion away

func ExportJSONValue

func ExportJSONValue(v any) any

Decoded store JSON as pyjson values for callers outside this package

func ExportProjection

func ExportProjection(transcript bool) (includeCompacted, includeInactive bool)

Export flags of a transcript, compaction archived turns shown, or of a snapshot carrying every stored row

func ExportRecordCount

func ExportRecordCount(sessions []*jsonutil.Object, only any) (int, string, error)

Count and noun of an export for its status message, prompts for a prompt view and sessions otherwise

func ExtractSteerTextFromMessage

func ExtractSteerTextFromMessage(message map[string]any) (string, bool)

Inner user text of a steer marker, false when none is present

func ExtractUserInstructionFromSkillMessage

func ExtractUserInstructionFromSkillMessage(content string) (string, bool)

Instruction of a skill expanded turn, the text unchanged when not scaffolding, false for a bare invocation

func FTS5CJKSoPath

func FTS5CJKSoPath(ctx context.Context) string

Location of the cjk_unicode61 extension, ICEBATH_FTS5_CJK_SO or the home lib directory

func FTSLayoutCurrent

func FTSLayoutCurrent(ctx context.Context, conn SQLiteConn) (bool, error)

Reports every present FTS table and the base source view exactly matching what this code creates

func FTSLayoutDrift

func FTSLayoutDrift(ctx context.Context, conn SQLiteConn) ([]string, error)

FTS tables on an older release definition that only optimize-storage replaces, empty otherwise

func FTSRebuildAdmission

func FTSRebuildAdmission(dbPath string, timeoutSeconds *float64, fn func(admitted bool) error) error

Serializes full structural FTS rebuilds on a store across processes, fn learning whether this process holds the authority

func FTSTrigramSessionSQLFor

func FTSTrigramSessionSQLFor(alias string) string

Sessions predicate selecting rows that belong in the trigram index, columns qualified by alias when given

func FileLengthMatchesHeader

func FileLengthMatchesHeader(conn SQLiteConn) (matches bool, ok bool)

Whether the file is at least as long as the header claims, false in ok when the check is inconclusive

func FilterNumber

func FilterNumber(v any) *float64

Number of a filter dict value as the store binds it, nil for None

func FindSessionByOrigin

func FindSessionByOrigin(ctx context.Context, db *SessionDB, platform, chatID string, threadID, userID *string) (string, error)

Find_session_by_origin as a package function over a store

func FlattenMessageText

func FlattenMessageText(content any, sep string) string

Visible text of chat or Responses message content joined with sep, the str of any other value

func FormatGatewaySessionListing

func FormatGatewaySessionListing(rows []*jsonutil.Object, includeSource bool, title string, notice *string) string

Compact markdown session list for gateway messengers, the notice above the footer when given

func FormatReferenceValue

func FormatReferenceValue(value string) string

Quotes a value with the first quote it lacks when it holds whitespace, brackets or quotes

func FormatSessionDBUnavailable

func FormatSessionDBUnavailable(ctx context.Context, prefix string, details bool) string

Builds the one line unavailable notice from the last init error, with a Details line when asked

func GenerateHTMLExport

func GenerateHTMLExport(session *jsonutil.Object) (string, error)

Self contained HTML page of one session

func GenerateMultiSessionHTMLExport

func GenerateMultiSessionHTMLExport(sessions []*jsonutil.Object) (string, error)

One self contained HTML page for the sessions, a sidebar switching between several

func GetLastInitError

func GetLastInitError() string

Most recent state.db init failure, empty when none was recorded

func HandoffOnlyContent

func HandoffOnlyContent(content any) any

Exported projection of summary content to its handoff for the agent turn context

func HasInvalidSQLiteHeaderPreopen

func HasInvalidSQLiteHeaderPreopen(path string, probeBytes int, force bool) bool

Reports a pre existing state.db whose first page is not SQLite

func HasLiveConnection

func HasLiveConnection(path string) bool

Reports whether this process holds a connection to the path or its main database

func HeldArchiveCoverage

func HeldArchiveCoverage(messages, verbatimTail []map[string]any) ([]int64, []map[string]any)

Covered row ids in first seen order and the dicts without an id from the held history

func HeldStoreRefusal

func HeldStoreRefusal(ctx context.Context, dbPath, command, forceHint string) (string, bool, error)

Operator refusal naming every foreign holder of the store, false when the store is provably quiet

func HistoricalSummaryPrefixes

func HistoricalSummaryPrefixes() []string

Older handoff prefixes a summary body may still begin with

func HistoryBeforeUserOriginatedTurn

func HistoryBeforeUserOriginatedTurn(messages []map[string]any, index int) ([]map[string]any, map[string]any, error)

Rewind prefix and canonical live view for index, a composite carrier keeping its handoff at the head

func HistoryBinding

func HistoryBinding(ctx context.Context, conn SQLiteConn, sessionID string) (any, error)

Stored import binding of the session, nil when unbound

func HolderNamespaceToken

func HolderNamespaceToken() string

The pidns fragment appended to a new holder string, empty without a namespace

func HolderPidCheckable

func HolderPidCheckable(holder string) bool

Reports whether a TTL holder's pid may be probed, foreign and unstamped holders deferring to expiry

func ImportHistoryControl

func ImportHistoryControl(ctx context.Context, conn SQLiteConn, actor HistoryActor, sessionIDs []string) error

Binds each session id the import is about to create to the importing actor

func InTransaction

func InTransaction(conn SQLiteConn) (bool, error)

Reports whether a transaction is open on the connection, the sqlite3 in_transaction attribute

func IndexToolCallUIDs

func IndexToolCallUIDs(index map[string]string, assistant map[string]any) map[string]bool

Registers the assistant tool call uids under every pairing id variant and returns the variants it names

func IntegrityDamageIsStructural

func IntegrityDamageIsStructural(integrityLines []string, masterRows []SQLiteMasterRow) bool

True when integrity_check output names damage outside the FTS shadow set or in the freelist

func IsActionableUserTurn

func IsActionableUserTurn(message map[string]any) bool

User row carrying input worth anchoring

func IsAdvisoryLockContention

func IsAdvisoryLockContention(err error) bool

Whether err means another process holds the lock, any other failure failing closed at once

func IsAutomaticEndReason

func IsAutomaticEndReason(reason any) bool

Whether reason is an automatic cleanup end stamp rather than a deliberate boundary

func IsBlankUserTurn

func IsBlankUserTurn(message map[string]any) bool

Empty non summary user role echo

func IsCompactionScaffolding

func IsCompactionScaffolding(msg map[string]any) bool

Reports rows compaction sent unstamped, the summary and the restatement

func IsCompactionSummaryMessage

func IsCompactionSummaryMessage(message any) bool

Context compaction handoff summary by metadata key or content heuristics

func IsContentBlank

func IsContentBlank(content any) (bool, error)

Whether decoded content is None, whitespace only, or carries no visible text parts

func IsContextSummaryContent

func IsContextSummaryContent(content any) bool

Reports whether content is a compaction summary in either standalone or merged form

func IsDeclarativeDriftError

func IsDeclarativeDriftError(err error) bool

Whether an error is a no such table or column read probe failure, drift and never corruption

func IsDiskFullError

func IsDiskFullError(v any) bool

Reports ENOSPC, SQLITE_FULL or text naming a full disk

func IsEphemeralScaffolding

func IsEphemeralScaffolding(msg any) bool

Reports internal recovery scaffolding that must never reach the durable transcript

func IsFTSScopedCorruptionError

func IsFTSScopedCorruptionError(v any) bool

Reports corruption SQLite attributes to the FTS index layer, a known code outranking text

func IsKnownSessionID

func IsKnownSessionID(value string) bool

Reports whether a value has the shape of an id this repo really mints

func IsMalformedDBError

func IsMalformedDBError(err error) bool

Reports a malformed schema or a generic corrupt image error, for diagnostics and offline recovery

func IsMalformedSchemaError

func IsMalformedSchemaError(err error) bool

Reports only SQLite's explicit malformed schema text

func IsMultimodalToolResult

func IsMultimodalToolResult(value any) bool

True for the multimodal tool result envelope carrying a content list

func IsMutationGuardRefusal

func IsMutationGuardRefusal(err error) bool

True for a live turn lease or compression lock refusal, the retryable busy verdict of a running admission

func IsRealUserTurn

func IsRealUserTurn(message map[string]any) bool

Actionable user turn that is not synthetic compression scaffolding

func IsRecoverableEndReason

func IsRecoverableEndReason(reason string) bool

Whether an end reason is one a session can be resurrected from

func IsSQLiteLockError

func IsSQLiteLockError(v any) bool

Reports SQLITE_BUSY or SQLITE_LOCKED by result code, or by text when no code is known

func IsSQLiteWALResetVulnerable

func IsSQLiteWALResetVulnerable(info VersionTuple) bool

Whether a SQLite version carries the WAL reset bug, every release from 3.7.0 before the fixed 3.44.6, 3.50.7 and 3.51.3

func IsSaveTranscriptFormat

func IsSaveTranscriptFormat(format string) bool

Whether a save format is a transcript of what the user saw, markdown or html

func IsSecretEnvName

func IsSecretEnvName(name string) bool

Reports whether a variable name contains a credential fragment in any letter case

func IsStoreFailure

func IsStoreFailure(err error) bool

Whether the error came from the session database itself, a SQLite failure or one of the store refusals

func IsStructuralCorruptionError

func IsStructuralCorruptionError(err error) bool

Reports corruption outside the FTS index and the repairable malformed schema case

func IsSyntheticCompressionUserTurn

func IsSyntheticCompressionUserTurn(message map[string]any) bool

Synthetic compression scaffolding user row such as a continuation or todo injection

func IsTransientSQLiteError

func IsTransientSQLiteError(err error) bool

Reports a busy right now operational error that retries instead of failing

func IsWorkerConstructorConfigKey

func IsWorkerConstructorConfigKey(key string) bool

Whether a model_config key is one of the constructor facts a worker may add to its reserved row

func IsZeroedStateDB

func IsZeroedStateDB(path string, probeBytes int, force bool) bool

Reports the zeroed state.db signature, an empty file or a header of only NUL bytes

func IterUserPromptRecords

func IterUserPromptRecords(sessions []*jsonutil.Object) []*jsonutil.Object

One normalized record for each user authored prompt of the sessions

func KeepPassedFences

func KeepPassedFences(ctx context.Context, conn SQLiteConn, derive func(int) string, sessionID string) (bool, error)

Makes permanent every fence a walk passed before the session id, false when a passed marker was reclaimed

func LegacyAccountLabel

func LegacyAccountLabel(row *jsonutil.Object) (bool, error)

Whether the row's user_id is the retired hosted account label a client history row carried, not an owner

func LegacyCreationSource

func LegacyCreationSource(row *jsonutil.Object) (any, error)

Creation source an adopted legacy row resumes on

func LegacyCronRunJob

func LegacyCronRunJob(sessionID string) (string, bool)

Returns the job id a pre unified cron run session names

func LegacyHistoryRow

func LegacyHistoryRow(row *jsonutil.Object) bool

Whether resume adopts the row as old local history, a local surface label or a client app label

func LegacyLocalSource

func LegacyLocalSource(label any) bool

Whether a creation label is one of the local surfaces older builds stored rows under

func LegacyLocalSources

func LegacyLocalSources() []string

Sorted local surface labels older builds stored their chats under

func LineageTitleOnConn

func LineageTitleOnConn(ctx context.Context, conn SQLiteConn, baseTitle string) (string, error)

Next lineage title on an authority owned transaction connection, counting siblings committed inside it

func LinkedSQLiteVersion

func LinkedSQLiteVersion() string

Version string sqlite3_libversion reports for the SQLite library linked into this binary

func ListSessionAdmissions

func ListSessionAdmissions(ctx context.Context, db *SessionDB, sessionID string, pendingOnly bool) ([]*jsonutil.Object, error)

Admission rows of the target session in queue order, only queued started or unknown ones when pending only

func LiveConnectionCount

func LiveConnectionCount(path string) int

Connections this process holds open to the database at path

func LiveWriterHoldsDB

func LiveWriterHoldsDB(dbPath string, connectRepairDurable func(dbPath string, timeout float64) (RepairConn, error)) (bool, error)

Whether repair lacks proven exclusive ownership, any foreign holder or a positive lock probe saying so

func LiveWriterHoldsStateDB

func LiveWriterHoldsStateDB(ctx context.Context, dbPath string) (bool, error)

Whether a foreign holder or a positive exclusive lock probe says the database lacks a proven quiet state

func LoadSaveSnapshot

func LoadSaveSnapshot(ctx context.Context, db *SessionDB, sessionID, format string) (*jsonutil.Object, error)

Stored session a save of the format writes, nil when it has no row, refused past the export message cap

func LoadTerminalResult

func LoadTerminalResult(text string) (any, error)

Decodes a stored terminal result, unwrapping only an exact encoded envelope

func LocalConversationIDs

func LocalConversationIDs(ctx context.Context, conn SQLiteConn, sessionID string) ([]string, error)

Session ids of one local conversation read on an open connection, its segments and compression lineage

func LocalIdentity

func LocalIdentity(profileID, principalID, requestID any) (string, error)

The deterministic session id of a local creation receipt

func LocalLineageOwner

func LocalLineageOwner(ctx context.Context, conn SQLiteConn, sessionID string) (string, error)

Creation id owning the local lineage a row belongs to, read on the given connection

func LocalPhysicalTarget

func LocalPhysicalTarget(ctx context.Context, conn SQLiteConn, sessionID string) (string, error)

Physical transcript a local session's turns write to, resolved on the caller's connection

func LogWriteLockHolders

func LogWriteLockHolders(dbPath string, patienceS float64) error

Logs one warning naming the write lock holders at the moment a writer gave up waiting

func LoginLabel

func LoginLabel(subject any) (string, bool)

Provider and user label stored rows carry for an issuer less login subject

func LoginOwnedBy

func LoginOwnedBy(row *jsonutil.Object, subject any) bool

Whether the subject owns the login stamp a legacy row carries

func MarkInflightRestatement

func MarkInflightRestatement(msg map[string]any)

Flags the compressor in flight task restatement in display metadata

func MarkStorageCorrupt

func MarkStorageCorrupt(dbPath string, reason any)

Latches a database path as corrupt for the life of the process

func MessageIdentity

func MessageIdentity(msg map[string]any, withToolUIDs bool) map[string]any

Identity fields a row copied from msg must carry, minting the msg uid first

func MessageKeyOrder

func MessageKeyOrder(m *Message, d map[string]any) []string

Dict keys of a message the struct renders, recorded order first, then the build order of its role, then sorted

func MessageToDict

func MessageToDict(m *Message) map[string]any

Lossless dict form of a message, struct fields first and every Extra key on top

func MessageUIDOrNone

func MessageUIDOrNone(msg map[string]any) (string, bool)

Message uid when it is a non empty string, false otherwise

func MintUID

func MintUID() string

Fresh random durable id for a message or tool call occurrence

func MsgHasPayload

func MsgHasPayload(msg map[string]any) bool

Whether a message carries text, blocks, tool calls, reasoning or codex replay items

func MultimodalEnvelopeSummary

func MultimodalEnvelopeSummary(value any) string

Text view of a multimodal envelope, its summary, else its text parts, else a fixed marker

func MutationReceiptKey

func MutationReceiptKey(principalID, sessionID, requestID, operation string, payload any, expectedRevision int64, expectedGeneration *int64) (string, string, error)

State meta key and digest of a mutation request's durable exact retry receipt

func NewSessionID

func NewSessionID() string

Session identifier carrying its creation stamp

func NewSessionIDAt

func NewSessionIDAt(now time.Time, hexLen int) string

Mints a timestamp and random hex session id, the zero time meaning now

func NewUID

func NewUID() string

Random 32 hex character identifier

func NewestExactHeldID

func NewestExactHeldID(messages, verbatimTail []map[string]any) (int64, bool)

Newest held row id that still names the row the compressor saw, false when none does

func NormaliseClientEnv

func NormaliseClientEnv(value any, rules *ClientEnvRules) (map[string]string, error)

Validated map filtered by the rules, nil rules leaving it unfiltered for a map frozen before rules existed

func NormalizeExportFormat

func NormalizeExportFormat(format string) (string, error)

Canonical export format name, jsonl for an empty one, a ValueError for an unknown one

func NormalizeExportOnly

func NormalizeExportOnly(only any) (string, error)

Canonical export filter name, empty for None, a ValueError for an unknown filter

func NormalizeSaveFormat

func NormalizeSaveFormat(format string) (string, error)

Canonical save format of a typed token, json for an empty one, a ValueError for an unknown one

func NotClientLabels

func NotClientLabels() map[string]bool

Labels a client app row can never carry, for queries that pre filter rows

func NoteStorageError

func NoteStorageError(dbPath string, err error) bool

Latches the path when the error is structural corruption and reports whether it was

func OfflineFileAccess

func OfflineFileAccess(path, what string, fn func()) error

Runs fn under the connection lifecycle lock, refusing while the database is live

func OnDiskJournalMode

func OnDiskJournalMode(ctx context.Context, conn SQLiteConn) (string, bool, error)

Journal mode read from the header for callers outside this package, false when undeterminable

func OtherGenerationsForPath

func OtherGenerationsForPath(dbPath string, exclude *DB) []string

Describes every other live generation this process holds for dbPath, retired generations excluded

func OwnerUser

func OwnerUser(row *jsonutil.Object) (any, error)

Owner identity of a session row, None for a retired hosted account label

func PageCountBytes

func PageCountBytes(conn SQLiteConn) (int64, bool)

Logical database size page_count times page_size read over the connection, false when the pragmas fail

func ParseModelConfig

func ParseModelConfig(raw any) map[string]any

Tolerant model_config decode into a map, JSON text or a dict copied, anything else empty

func ParseSessionListingArgs

func ParseSessionListingArgs(rawArgs string) (includeAll, includeUnnamed bool, target string, searchQuery *string, err error)

Sessions style arguments as all sources, unnamed kept, resume target and search query, nil when no search was asked

func PathOnCrossVMFS

func PathOnCrossVMFS(path string) (bool, error)

Reports a path on a virtiofs or 9p filesystem shared across a VM boundary

func PersistentRecordPidnsCheckable

func PersistentRecordPidnsCheckable(recorded string, stamped bool) bool

Reports whether a no expiry record may be probed, unstamped records still probing

func PidNamespaceID

func PidNamespaceID() string

The namespace inode a holder records, empty when there is none or the lookup failed

func PositiveID

func PositiveID(value any) (int64, bool)

Positive integer id of a row reference, false for anything else

func PrefixRange

func PrefixRange(prefix string) (string, string, error)

Returns half open bounds covering every key that starts with the prefix

func PreflightDBWritability

func PreflightDBWritability(ctx context.Context, dbPath, dbLabel string, directoryOnly bool) error

Refuses or repairs read only database files before the first connection opens

func PreviewSQL

func PreviewSQL(sessionIDExpr string) string

PreviewSQL is the listing column holding the first user message of the session sessionIDExpr names, read with ShapePreview

func ProfileFromSessionKey

func ProfileFromSessionKey(sessionKey string) (string, bool)

Returns the profile namespace an agent gateway session key encodes

func ProfileFromSessionKeyNamespace

func ProfileFromSessionKeyNamespace(namespace string) string

Maps a session key namespace slot back to its profile id

func ProjectCompactionMessageForDisplay

func ProjectCompactionMessageForDisplay(message any) map[string]any

Authentic transcript content of a message as a fresh dict, nil for a pure compaction handoff

func PythonLongOptionTakesOperand

func PythonLongOptionTakesOperand(option string) bool

Interpreter long options taking the next argv token as operand, shared with the gateway inline source walk

func PythonShortOptionTakesOperand

func PythonShortOptionTakesOperand(letter string) bool

Interpreter short options taking the next argv token as operand, shared with the gateway inline source walk

func QuarantineCrossProcessLock

func QuarantineCrossProcessLock(path string, timeout float64) (bool, func(), error)

Takes the cross process quarantine lock beside path within timeout, the release unlocking and closing it

func QuarantineInvalidStateDB

func QuarantineInvalidStateDB(path string, alreadyLocked bool) (string, error)

Moves a non SQLite state.db aside with its sidecars and returns the quarantine path, empty when nothing moved

func QueryObjects

func QueryObjects(ctx context.Context, conn SQLiteConn, query string, args ...any) ([]*jsonutil.Object, error)

Every row of one statement on a connection as ordered objects

func QueryRowObject

func QueryRowObject(ctx context.Context, conn SQLiteConn, query string, args ...any) (*jsonutil.Object, error)

First row of one statement on a connection as an ordered object, nil when it returns none

func QuerySessionListing

func QuerySessionListing(ctx context.Context, db SessionLister, q SessionListingQuery) ([]*jsonutil.Object, error)

Session rows for the listing surfaces, source scoped, unnamed and current rows hidden unless asked for

func ReachablePhysicalLayouts

func ReachablePhysicalLayouts(table string, accept func(layout []string, firstNewIndex int) bool) (iter.Seq[[]string], error)

Every physical layout an upgraded store of the table can have, accept pruning a branch when it returns false

func ReadHeaderBytesPreopen

func ReadHeaderBytesPreopen(path string, length int, force bool) ([]byte, bool)

Reads the leading bytes of a database file only when no connection is live, a negative length reading it all

func ReadOnlyDBURI

func ReadOnlyDBURI(dbPath string) (string, error)

File URI opening the resolved path read only, percent encoding characters that would truncate it

func ReadShellLines

func ReadShellLines(sessionsDir, sessionID string) ([]*jsonutil.Object, error)

Shell lines kept for a session in the order they ran, each with its time, command and result, none without a file

func ReanchorCurrentTurnUserIdx

func ReanchorCurrentTurnUserIdx(messages []any, userMessage any) int

Index of this turn's user message in a plain transcript, minus one when no user turn remains

func ReconcileDriftForBrowse

func ReconcileDriftForBrowse(ctx context.Context, path string) (bool, error)

Catches a lagging store up for a read only browse, true when DDL ran and false when already current

func ReconcileStateSchema

func ReconcileStateSchema(ctx context.Context, conn SQLiteConn) error

Brings a raw state.db connection to the declared shape and commits an open transaction

func RecordAbsorbedMessage

func RecordAbsorbedMessage(survivor, dropped map[string]any, droppedLeads bool)

Records the uid of a dict folded into survivor, the leading constituent keeping its uid

func RefuseDeletedWALGeneration

func RefuseDeletedWALGeneration(dbPath string) error

Refuses an open while any process holds a deleted wal or shm generation of the database

func RegistryStats

func RegistryStats() map[string]int

Registry census of live generations, retired generations and live refcounts

func Release

func Release(d *DB) bool

Drops one reference of a shared database, false when d is not registry managed and its caller owns the close

func ReleaseOrClose

func ReleaseOrClose(d *DB)

Releases a shared instance, or closes one the registry does not manage, as a drop in for Close

func RenderSessionForSave

func RenderSessionForSave(session *jsonutil.Object, format string) (string, error)

Renders one exported session for a save in the given canonical format

func RenderSessionsExport

func RenderSessionsExport(sessions []*jsonutil.Object, format string, only any) (string, error)

Renders exported sessions as jsonl or markdown, whole sessions or one record per user prompt

func RepairMessageSequence

func RepairMessageSequence(messages *[]map[string]any) (int, error)

Collapses malformed role alternation in place and returns the repair count

func ReplacementBinding

func ReplacementBinding(principalID, sessionID, requestID string) (string, error)

Durable key binding a replacement identity to the admission it retired

func ReplayMutationReceipt

func ReplayMutationReceipt(ctx context.Context, conn SQLiteConn, key, digest string) (any, error)

Stored result of an exact mutation retry, nil when unseen, refusing a different request under the key

func ReportStartupProgress

func ReportStartupProgress(expectedS float64, phase string)

Declares a phase owned progress lease on the armed startup watchdog for callers outside this package

func RequireNotExecuting

func RequireNotExecuting(ctx context.Context, conn SQLiteConn, sessionIDs []string) error

Refuses while a turn or worker runs or has an unknown outcome on any session, queued followers allowed

func ResolveDefaultDBPath

func ResolveDefaultDBPath(ctx context.Context) string

State database path the session layer opens when no path is pinned

func ResolveJournalMode

func ResolveJournalMode(ctx context.Context) string

Configured database journal_mode, wal by default and for invalid values

func ResolveToolCallUID

func ResolveToolCallUID(index map[string]string, toolCallID any) (string, bool)

Uid an indexed assistant minted for any variant of the tool call id, false when none

func ResolvedMaxExportMessages

func ResolvedMaxExportMessages(ctx context.Context) int

Message cap an in memory export builds, sessions.max_export_messages

func ResolvedMaxResumeMessages

func ResolvedMaxResumeMessages(ctx context.Context) int

Message cap a resume reloads, sessions.max_resume_messages

func RetireMedia

func RetireMedia(ctx context.Context, conn SQLiteConn, payload *jsonutil.Object, requestID string) error

Records the media a payload references as durable deletion candidates inside the caller's write transaction

func RetireReplacedInput

func RetireReplacedInput(ctx context.Context, conn SQLiteConn, admissionID, binding string) error

Cancels the still queued replaced row and binds it to its successor inside the successor admission write

func RetireRoutes

func RetireRoutes(ctx context.Context, conn SQLiteConn, sessionIDs, expiring []string) error

Fences the routes of retired session ids, the expiring ones aging out at the retirement horizon

func RetiredIn

func RetiredIn(ctx context.Context, conn SQLiteConn, sessionID string) (bool, error)

True when this store holds the retired marker of the session id

func RetiredReceipt

func RetiredReceipt(resultJSON string) (bool, error)

True when a stored receipt result is exactly the retired marker

func RetiredRowPayload

func RetiredRowPayload(message map[string]any) map[string]any

Fields the commit matches a retired row without an id by

func RetryMatches

func RetryMatches(committed, request *jsonutil.Object) (bool, error)

Whether a retried session.create carries the client environment the committed session froze

func RetryableUserText

func RetryableUserText(content any) (string, error)

Lossless retry text of live user content, media and annotated or unknown parts failing closed

func RewindComparisonContent

func RewindComparisonContent(message map[string]any) any

Durable projection of a message's content for the warm versus live rewind comparison

func RewindHistoryChanged

func RewindHistoryChanged() string

Refusal text of a rewind whose warm view diverged from the durable rows

func RouteFenceKey

func RouteFenceKey(namespace, sessionID string) string

State meta key of the routing fence one profile namespace holds for a retired session

func RouteNamespace

func RouteNamespace(sessionKey any) string

Profile slot of an agent namespaced routing key, main for the launch profile and any other key shape

func RunTokenExitHooks

func RunTokenExitHooks()

Drains the token queue of every store still alive, newest registration first, for the process exit path

func RuntimeAdmission

func RuntimeAdmission(ctx context.Context, conn SQLiteConn, admissionID string) (*jsonutil.Object, error)

Live admission row else its retired tombstone, refused not found when neither exists

func RuntimeEpoch

func RuntimeEpoch(ctx context.Context, conn SQLiteConn, epoch int64) error

Refuses a writer whose epoch is not the current runtime epoch

func RuntimeJSON

func RuntimeJSON(value any) (string, error)

Canonical JSON text the runtime ledger stores for a value

func RuntimeSession

func RuntimeSession(ctx context.Context, conn SQLiteConn, sessionID string) (map[string]any, error)

Session row of the runtime ledger, refused not found when absent

func SQLSessionLastActive

func SQLSessionLastActive(alias string) string

Session recency SQL expression over a sessions alias row, newest activity, message or start time

func SQLiteSourceID

func SQLiteSourceID() string

Source id of the linked SQLite library, empty when an in memory database cannot report it

func SameCreateRequest

func SameCreateRequest(savedJSON, retryJSON string) (bool, error)

Whether a create retry carries the frozen request it resumes, comparing a pre alias receipt exactly

func SameCreateRetry

func SameCreateRetry(savedPolicy *jsonutil.Object, retryJSON string, clientRequest *jsonutil.Object) (bool, error)

The exact retry identity of a create, its sent request and its unstored client env judged by the saved policy rules

func SameHistoryOwner

func SameHistoryOwner(ctx context.Context, conn SQLiteConn, anchorID, sessionID string) (bool, error)

Whether a chain member is history the authorizer of the anchor controls

func SanitizeContext

func SanitizeContext(text string) string

Strips fence tags, injected context blocks and system notes from provider output

func SanitizeMessages

func SanitizeMessages(messages []any, fix func(string) string, deep bool) bool

Applies fix to the string fields of every message dict, deep adding tool call ids, names and nested extras

func SanitizeMessagesNonASCII

func SanitizeMessagesNonASCII(messages []any) bool

Shallow non ASCII strip of every message dict in place

func SanitizeMessagesSurrogates

func SanitizeMessagesSurrogates(messages []any) bool

Deep surrogate repair of every message dict in place

func SanitizeStructure

func SanitizeStructure(payload any, fix func(string) string) bool

Applies fix in place to every string nested inside dict and list payloads

func SanitizeStructureNonASCII

func SanitizeStructureNonASCII(payload any) bool

Strips non ASCII characters from every string of a nested payload in place

func SanitizeStructureSurrogates

func SanitizeStructureSurrogates(payload any) bool

Replaces lone surrogates in every string of a nested payload in place

func SanitizeSurrogates

func SanitizeSurrogates(text string) string

Replaces each run of invalid UTF-8 bytes with U+FFFD, returning ASCII text untouched

func SanitizeTitle

func SanitizeTitle(title string) (string, error)

Strips controls, invisibles and lone surrogates and collapses whitespace, empty meaning None, ValueError past the length cap

func ScaffoldingReplayFields

func ScaffoldingReplayFields(msg map[string]any) map[string]any

Compaction provenance fields replay keeps, the summary flag and the restatement flag

func SchemaDriftReason

func SchemaDriftReason(ctx context.Context, path string) (string, bool, error)

Missing declared table or column of a store, drift true with its message, never a corruption diagnosis

func SchemaNotBuilt

func SchemaNotBuilt(err error) bool

Whether an error says the core or FTS tables are not built yet

func SchemaReadProbeStatements

func SchemaReadProbeStatements(ctx context.Context) ([]string, error)

SELECTs that fail at prepare time exactly when a live store is behind the declared schema, computed once per process

func SecretDigest

func SecretDigest(secret string) (string, error)

Hex sha256 of an adoption secret, refused like any other invalid runtime text

func SecureStateDBFiles

func SecureStateDBFiles(dbPath string, createMain bool) error

Restricts state.db and its WAL sidecars to the owner, creating the main file first when createMain

func SessionEnv

func SessionEnv(ctx context.Context, name, def string) string

Behaviour value of the session, the gateway's own for an unbound session or a host value of a remote client

func SessionGatewayRuntime

func SessionGatewayRuntime(sessionMeta *jsonutil.Object) *jsonutil.Object

Persisted runtime route of a session row, nested gateway runtime first, then the top level keys and billing provider

func SessionKeyProfile

func SessionKeyProfile(sessionKey any) (string, bool)

Profile encoded in an agent gateway key, default for main, false for a keyless or foreign key

func SessionYoloEnabled

func SessionYoloEnabled(sessionMeta map[string]any) bool

SessionYoloEnabled reads the persisted approval bypass of a session row, false on any parse failure

func SetLifecycleHookInvoker

func SetLifecycleHookInvoker(fn LifecycleHookInvoker)

Installs the lifecycle dispatcher the session delete hook fires through

func SetStartupProgressLease

func SetStartupProgressLease(fn func(expectedS float64, phase string))

Installs the armed startup watchdog lease hook, nil on disarm, called by the watchdog when it arms

func SetWallClock

func SetWallClock(fn func() float64) func()

Installs the wall clock store timestamps read and returns the restore of the previous one

func SettleSteerTransfers

func SettleSteerTransfers(ctx context.Context, conn SQLiteConn, epoch, generation int64, transfers map[string]bool, outcome string) error

Settles each transfer bound to the claim, steered when delivered and completed, interrupted when delivered otherwise, queued again when undelivered

func ShapePreview

func ShapePreview(raw any) string

Short preview of a raw preview column the way the skill command tests read it

func ShellLinesPath

func ShellLinesPath(sessionsDir, sessionID string) string

File of the shell lines a person ran in a session, beside its other files in a sessions folder

func ShowSubagentSessions

func ShowSubagentSessions(ctx context.Context, storeHome string) bool

Whether sessions.show_subagents of the store home is on

func SplitUserOriginatedTurn

func SplitUserOriginatedTurn(message map[string]any) (map[string]any, map[string]any)

User row split into its handoff only part and its live human view, either nil, both fresh dicts

func StampMessageTimestamp

func StampMessageTimestamp(message map[string]any, timestamp *float64) map[string]any

Attaches a creation timestamp unless the message already carries one, then returns the message

func StampMessageUID

func StampMessageUID(msg map[string]any) string

Message uid, minting and stamping one on the dict when it carries none

func StartsWithSummaryPrefix

func StartsWithSummaryPrefix(text string) bool

Reports whether text begins with the current, legacy or any historical compaction handoff prefix

func StateDBHasStructuralDamage

func StateDBHasStructuralDamage(dbPath string) (bool, error)

Read only integrity check classifying damage as structural, a check that raises counting as structural

func StateDBWriteLockHolders

func StateDBWriteLockHolders(dbPath string) ([]string, error)

Lines naming every process that holds a write class lock on the database or its sidecars, empty off Linux

func SteerReplayed

func SteerReplayed(row *jsonutil.Object) bool

True for a committed steer transfer an exact retry replays

func StorageCorruptReason

func StorageCorruptReason(dbPath string) (string, bool)

The first error text latched for the path, false when none

func StorageFailureDetails

func StorageFailureDetails(excOrStr any, limit int) string

Whitespace flattened raw cause cut to limit code points with an ellipsis

func StorageState

func StorageState(dbPath string) string

Corrupt once this process saw structural corruption on the path, else ok

func StripContextSummaryHandoffMessage

func StripContextSummaryHandoffMessage(message map[string]any) map[string]any

Copy without stale handoff data keeping merged prior tail content, nil for a standalone handoff

func StripNonASCII

func StripNonASCII(text string) string

Drops every non ASCII character as the ascii codec with errors ignore does

func SyncFlushedMessageMarkers

func SyncFlushedMessageMarkers(batchMsgs, batchRows []map[string]any)

Stamps persistence markers and syncs canonical durable fields onto live dicts after commit

func TerminalAPIAdmissions

func TerminalAPIAdmissions(ctx context.Context, conn SQLiteConn, requestID string) ([]any, error)

Retired API admission records carrying the request id, which stay spent for every other target

func ToolCallField

func ToolCallField(tc any, key string) any

Field of a tool call entry that may be a dict or a struct

func ToolCallIDVariants

func ToolCallIDVariants(tc any) map[string]bool

All pairing id variants a tool call entry carries

func ToolCallSet

func ToolCallSet(tc any, key string, value any) error

Writes a key on a tool call dict or the matching field or Extra entry of a tool call struct

func ToolCallToDict

func ToolCallToDict(tc ToolCall) *jsonutil.Object

Lossless dict form of a tool call struct in the key order of its source dict

func ToolCallUIDFromHistory

func ToolCallUIDFromHistory(messages []map[string]any, toolIndex int, owners map[uintptr]*ToolCallOwner) (string, bool)

Uid of a tool result resolved from the nearest preceding assistant that named its id

func ToolEnv

func ToolEnv(ctx context.Context) map[string]string

Toolchain values the session tool subprocesses start with, empty when unbound or remote

func ToolResultIDVariants

func ToolResultIDVariants(toolCallID any) map[string]bool

All matching variants of a tool result tool_call_id

func ToolchainEnviron

func ToolchainEnviron(ctx context.Context, base map[string]string) map[string]string

Environment the session tool subprocesses start from, the client's toolchain replacing the gateway's

func TrackConnection

func TrackConnection(path string)

Records that this process holds one more connection to the path

func Transaction

func Transaction(ctx context.Context, conn SQLiteConn, immediate bool, body func(conn SQLiteConn) error) (err error)

Runs body in one transaction, joining one already open, committed on success, rolled back on error, always closing conn

func TranscriptRowSnapshot

func TranscriptRowSnapshot(row map[string]any) string

Fixed size BLAKE2b digest of a stored row's owned columns, the compare and swap version

func TypedPromptContent

func TypedPromptContent(content, message any) any

Content with the withheld placeholder swapped back for what the user typed

func UIDList

func UIDList(value any) []string

Unique non empty string uids of a list in order, empty for anything else

func UntrackConnection

func UntrackConnection(path string)

Records that one connection to the path was closed

func UntypedFailedTurnDisplayKind

func UntypedFailedTurnDisplayKind(role, content any) (string, bool)

Failed turn display kind for a boundary row persisted before closers typed it, false for anything else

func UserOriginatedTurnView

func UserOriginatedTurnView(message any) map[string]any

Live human authored projection of a user row, nil when the row carries none

func UserTurnIndices

func UserTurnIndices(messages []map[string]any) []int

Indices of the user originated turns of a history, the gateway session store's rewind addressing

func ValidateAction

func ValidateAction(operation any, payloadValue any) error

Refuses as invalid_params every operation and payload outside the closed mutation set

func ValidateLocalLineage

func ValidateLocalLineage(ctx context.Context, conn SQLiteConn, receipt *jsonutil.Object) (string, error)

Physical target of a local receipt once its recorded lineage matches the stored rows

func WALResetRepairHint

func WALResetRepairHint(ctx context.Context) string

Repair hint naming what an update can do about the WAL reset bug for this install type

func WALResetVulnerable

func WALResetVulnerable(versionInfo *VersionTuple) bool

Reports the WAL reset bug for a version, nil meaning the SQLite library linked into this binary

func WithheldPromptText

func WithheldPromptText(message any) (string, bool)

Typed text a transcript view shows for a vetoed user row, false when the row has none

func WithoutPersistenceFields

func WithoutPersistenceFields(msg map[string]any) map[string]any

The message itself without persistence only fields, a shallow copy only when one is present

func WithoutWithheldPrompts

func WithoutWithheldPrompts(messages any) any

Messages with the vetoed text dropped from each row display metadata, copying only rows that hold it

func WorkspaceKey

func WorkspaceKey(row any) (string, bool)

Workspace grouping key of a session row, git repo root else cwd, the branch never fragmenting history

func WriteSQLiteRuntimeReport

func WriteSQLiteRuntimeReport(ctx context.Context, w io.Writer) error

Writes the linked SQLite version, its source id and the store features it lacks as one JSON line

Types

type ActivityProvenance

type ActivityProvenance string

ActivityProvenance names where a durable or in memory activity stamp came from

const (
	ActivityProvenanceUnknown                  ActivityProvenance = "unknown"
	ActivityProvenanceAgentCompression         ActivityProvenance = "agent.compression"
	ActivityProvenanceAgentCompressionTimeout  ActivityProvenance = "agent.compression_timeout"
	ActivityProvenanceAgentCompressionCooldown ActivityProvenance = "agent.compression_cooldown"
	ActivityProvenanceAgentCompressionTurnhold ActivityProvenance = "agent.compression_turnhold"
)

func NormalizeActivityProvenance

func NormalizeActivityProvenance(provenance string) ActivityProvenance

Known provenance for the stripped value, unknown when unset or unrecognized

type AnchoredViewOptions

type AnchoredViewOptions struct {
	Window    int
	Bookend   int
	KeepRoles []string
}

Keyword arguments of get_anchored_view, a nil KeepRoles disabling the role filter

type AppendGuards

type AppendGuards struct {
	CompressionLockHolder *string
	TurnLeaseHolder       *string
	TurnLeaseTTLSeconds   *float64
}

Guard options of one append, a nil TTL meaning the 300 second default

type ArchiveCompactOptions

type ArchiveCompactOptions struct {
	ModelConfigPatch *jsonutil.Object
	Watermark        *int64
	LockHolder       *string
	TailCount        int
	CarriedMessages  []map[string]any
	CoveredIDs       []int64
	UnresolvedHeld   []map[string]any
	HeldForCAS       []map[string]any
}

Keyword arguments of an in place compaction, nil standing for an omitted Python argument

type AsyncSessionDB

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

Async door onto a SessionDB running every call on its own goroutine

func NewAsyncSessionDB

func NewAsyncSessionDB(db *SessionDB) *AsyncSessionDB

Async door onto db

func NewBorrowedAsyncSessionDB

func NewBorrowedAsyncSessionDB(db *SessionDB) *AsyncSessionDB

Async door onto a handle another owner closes, so a handle sweep skips it

func (*AsyncSessionDB) Borrowed

func (a *AsyncSessionDB) Borrowed() bool

Whether the wrapped handle belongs to another owner that closes it

func (*AsyncSessionDB) DB

func (a *AsyncSessionDB) DB() *SessionDB

Wrapped store, the attribute access of a non callable member

type AutoArchiveResult

type AutoArchiveResult struct {
	Skipped  bool
	Archived int
	Error    string
}

Outcome of one auto archive pass

type AutoPruneOptions

type AutoPruneOptions struct {
	RetentionDays          *float64
	MinIntervalHours       float64
	Vacuum                 bool
	SessionsDir            string
	MinVacuumIntervalDays  float64
	MinVacuumFreelistRatio float64
}

Startup auto maintenance knobs, built with defaults by NewAutoPruneOptions

func NewAutoPruneOptions

func NewAutoPruneOptions() AutoPruneOptions

Ninety day retention, a daily run, vacuum on a thirty day throttle above the default freelist ratio

type AutoPruneResult

type AutoPruneResult struct {
	Skipped              bool
	Pruned               int
	Closed               int
	Vacuumed             bool
	FreelistConsidered   bool
	FreelistRatio        *float64
	VacuumSkippedHolders *int
	Error                *string
}

Outcome of one auto maintenance pass, the optional fields set only when the pass reports them

type AutomationState

type AutomationState interface {
	Status() any
	SetStatus(status string)
	ToJSON() (string, error)
}

Stored automation state of one family as the worker rotation reads and rewrites it

type AuxiliaryUsage

type AuxiliaryUsage struct {
	Model            *string
	BillingProvider  *string
	BillingBaseURL   *string
	InputTokens      int64
	OutputTokens     int64
	CacheReadTokens  int64
	CacheWriteTokens int64
	ReasoningTokens  int64
	EstimatedCostUSD *float64
	APICallCount     *int
}

Usage of one auxiliary call, a nil call count records one call

type AwakeIdleMeter

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

AwakeIdleMeter removes host sleep from the idle readings of a polling watchdog

func NewAwakeIdleMeter

func NewAwakeIdleMeter() *AwakeIdleMeter

Meter whose clocks start now, wall time against the monotonic clock

func NewAwakeIdleMeterWithClocks

func NewAwakeIdleMeterWithClocks(wallNow, monoNow func() float64) *AwakeIdleMeter

Meter reading the given wall and monotonic clocks

func (*AwakeIdleMeter) Measure

func (m *AwakeIdleMeter) Measure(idleS float64) float64

Wall clock idle seconds minus the host sleep observed since the last activity

type BackendHeartbeat

type BackendHeartbeat struct {
	BackendID     string
	PID           int
	StartedAt     float64
	LastHeartbeat *float64
	Profile       string
	Host          string
}

type BrowseBudgetExceeded

type BrowseBudgetExceeded struct{ Msg string }

The browse reconcile ran out of its time budget before finishing, nothing written

func (*BrowseBudgetExceeded) Error

func (e *BrowseBudgetExceeded) Error() string

func (*BrowseBudgetExceeded) ErrorKind

func (e *BrowseBudgetExceeded) ErrorKind() string

type CapturedResult

type CapturedResult struct {
	Outcome string
	Stored  *jsonutil.Object
}

Result this owner captured for a turn before its settlement write failed

type ClaimInput

type ClaimInput struct {
	Epoch     int64
	SessionID string
	Guard     func(ctx context.Context, conn SQLiteConn) error
	// Head is the admission id the caller validated, nil meaning it saw nothing queued
	CheckHead bool
	Head      *string
}

FIFO head claim, the guard refusing inside the write and a set head check refusing a moved head

type ClientEnvBinding

type ClientEnvBinding struct {
	Env   map[string]string
	Local bool
	Rules *ClientEnvRules
}

One session client environment bound for a context

func BoundClientEnvBinding

func BoundClientEnvBinding(ctx context.Context) *ClientEnvBinding

Binding of the session executing under the context, nil when unbound

type ClientEnvRules

type ClientEnvRules struct {
	Behaviour []string
	Names     []string
	Prefixes  []string
	Secret    []string
}

Normalisation rules a session client environment is filtered by, nil Secret meaning the live secret policy

func ClientEnvRulesFor

func ClientEnvRulesFor(config any, local bool) *ClientEnvRules

Rules frozen with a session map, a client not proven local keeping only values that name nothing on this host

func ParseClientEnvRules

func ParseClientEnvRules(raw any) (*ClientEnvRules, error)

Rules from their decoded dict, a missing key a KeyError and a non string list a TypeError

func (*ClientEnvRules) Object

func (r *ClientEnvRules) Object() *jsonutil.Object

Rules as the dict frozen into client_env_rules_json

type CompressionChildPublish

type CompressionChildPublish struct {
	ParentSessionID         string
	ChildSessionID          string
	Source                  string
	Messages                []map[string]any
	Model                   *string
	ModelConfig             *jsonutil.Object
	SystemPrompt            *string
	Cwd                     *string
	ProfileName             *string
	CompressionLockHolder   *string
	RequireCompressionLease bool
	RequireLeaseRefresh     bool
	LeaseTTLSeconds         float64
	Watermark               *int64
	WatermarkCeiling        *int64
}

One durable compression child publication and its options, built with defaults by NewCompressionChildPublish

func NewCompressionChildPublish

func NewCompressionChildPublish(parentSessionID, childSessionID, source string, messages []map[string]any) CompressionChildPublish

Publication requiring the compression lease with a 300 second refresh ttl

type CompressionCooldown

type CompressionCooldown struct {
	Until            float64
	RemainingSeconds float64
	Error            string
}

Active compression failure cooldown of a session, the zero value when none is live

type CompressionCooldownRow

type CompressionCooldownRow struct {
	SessionExists bool
	CooldownUntil *float64
	Error         any
}

Exact stored cooldown columns of a session row, no expiry filtering

type CompressionSessionBusyError

type CompressionSessionBusyError struct{ Msg string }

Rejects a non owner write while compression owns the session

func (*CompressionSessionBusyError) Error

type CompressionSessionClosedError

type CompressionSessionClosedError struct {
	SessionID string
}

Rejects a durable write to a parent compression already closed

func (*CompressionSessionClosedError) Error

type ConversationOptions

type ConversationOptions struct {
	IncludeAncestors, IncludeInactive, RepairAlternation, IncludeRowIDs, IncludeCompacted bool
}

Visibility and repair switches of a conversation read

type CorruptStoreError

type CorruptStoreError struct{ Detail string }

Lagging store that is also damaged, worded like the malformed image error so callers map it to corrupt

func (*CorruptStoreError) Error

func (e *CorruptStoreError) Error() string

func (*CorruptStoreError) ErrorKind

func (e *CorruptStoreError) ErrorKind() string

type CrossedProfileSessions

type CrossedProfileSessions struct {
	Mislabelled, Foreign, CrossedParents []*jsonutil.Object
}

Crossed profile identity findings of one store, a row possibly in more than one list

type DB

type DB = SessionDB

Session store of one home, the SessionDB

func Acquire

func Acquire(ctx context.Context, dbPath string) (*DB, error)

Shared database of dbPath with one more reference, retiring a generation whose file was replaced

func LiveSharedSessionDBs

func LiveSharedSessionDBs() []*DB

Snapshot of every live shared database with refcounts untouched, for in process maintenance

func Open

func Open(path string, opts Options) (*DB, error)

Opens the session database at path, creating and migrating it unless read only

func OpenHome

func OpenHome(h string, opts Options) (*DB, error)

Opens the session database of a home directory

func (*DB) ClearCompressionCooldown

func (d *DB) ClearCompressionCooldown(sessionID string) error

Clears the cooldown, never failing, a write error only logged

func (*DB) CompressionCooldown

func (d *DB) CompressionCooldown(sessionID string) (CompressionCooldown, error)

Live cooldown deadline and reason, zero when none is active

func (*DB) CompressionFallbackStreak

func (d *DB) CompressionFallbackStreak(sessionID string) (int, error)

Persisted deterministic fallback streak

func (*DB) CompressionIneffectiveCount

func (d *DB) CompressionIneffectiveCount(sessionID string) (int, error)

Persisted ineffective compaction strike count a resumed compressor inherits

func (*DB) CompressionOverloadStreak

func (d *DB) CompressionOverloadStreak(sessionID string) (int, error)

Persisted sustained overload abort streak

func (*DB) CompressionRecoveryDeadline

func (d *DB) CompressionRecoveryDeadline(sessionID string) (float64, error)

Persisted anti thrash recovery deadline in epoch seconds, zero when not armed

func (*DB) CompressionTip

func (d *DB) CompressionTip(id string) (string, error)

Freshest continuation of a session, the session itself when it was never compressed away

func (*DB) EmitSessionDeleted

func (d *DB) EmitSessionDeleted(ctx context.Context, deletedIDs []string, reason, primary, sessionsDir string)

Fires on_session_delete under the store's own profile home after a committed delete or archive, never failing it

func (*DB) GetModelConfigValue

func (d *DB) GetModelConfigValue(id, key string) (any, bool, error)

GetModelConfigValue reads one key of a session's model config, false when the session or key is absent

func (*DB) IncrementCompressionOverloadStreak

func (d *DB) IncrementCompressionOverloadStreak(sessionID string) (*int, error)

Atomically bumps the overload streak returning the new value, nil when the row is absent

func (*DB) ListSessions

func (d *DB) ListSessions(f ListFilter) ([]*Session, error)

Sessions ordered by freshest activity, compression continuations collapsed onto their tip

func (*DB) ModelConfigValue

func (d *DB) ModelConfigValue(sessionID, key string) (any, bool)

One key of a session model_config, false when the session, the key or the read is missing

func (*DB) PatchModelConfig

func (d *DB) PatchModelConfig(id string, patch map[string]any) error

Merges keys into the model config of a session, a nil value removing the key

func (*DB) ResolveByTitle

func (d *DB) ResolveByTitle(title string) (string, error)

Session id a title names, the newest numbered continuation preferred

func (*DB) ResolveSessionID

func (d *DB) ResolveSessionID(idOrPrefix string) (string, error)

Full session id matching an id or a unique prefix, empty when none or ambiguous

func (*DB) SessionIDsWithModelConfigKey

func (d *DB) SessionIDsWithModelConfigKey(key string) ([]string, error)

SessionIDsWithModelConfigKey lists the sessions whose model config carries the key, newest first

func (*DB) SetAutoTitle

func (d *DB) SetAutoTitle(sessionID, title, source string) (bool, error)

Sets an automatic title, untouched when a higher authority title holds the row

func (*DB) SetCompressionCooldown

func (d *DB) SetCompressionCooldown(sessionID string, until float64, reason string) error

Records the cooldown with an empty reason stored as NULL

func (*DB) SetCompressionFallbackStreak

func (d *DB) SetCompressionFallbackStreak(sessionID string, streak int) error

Persists the deterministic fallback streak clamped at zero

func (*DB) SetCompressionIneffectiveCount

func (d *DB) SetCompressionIneffectiveCount(sessionID string, count int) error

Persists the ineffective compaction strike count clamped at zero

func (*DB) SetCompressionOverloadStreak

func (d *DB) SetCompressionOverloadStreak(sessionID string, streak int) error

Persists the sustained overload abort streak clamped at zero

func (*DB) SetCompressionRecoveryDeadline

func (d *DB) SetCompressionRecoveryDeadline(sessionID string, deadline float64) error

Persists the recovery deadline, zero or a non positive value disarming it as NULL

func (*DB) SetTitle

func (d *DB) SetTitle(sessionID, title string) (bool, error)

Sets a title on behalf of the person, an empty title clearing it

func (*DB) Title

func (d *DB) Title(sessionID string) (string, string, error)

Title of a session and its provenance

func (*DB) UpdateConversationModelConfigValue

func (d *DB) UpdateConversationModelConfigValue(id, key string, update func(current any) any) (string, error)

UpdateConversationModelConfigValue rewrites one conversation wide key at the compression tip in one transaction, a nil result removing it

func (*DB) UpdateSessionCwd

func (d *DB) UpdateSessionCwd(id, cwd, repoRoot, branch string) error

Records the working directory and git facts of a session through the generation claim

func (*DB) UpdateSessionModel

func (d *DB) UpdateSessionModel(id, model, provider, baseURL string) error

Records the model and billing route a session runs on

type DeclarativeDriftError

type DeclarativeDriftError struct {
	Detail string
	Owned  bool
}

Store lagging the declared schema that browsing could not catch up, Owned when a running gateway holds it

func (*DeclarativeDriftError) Error

func (e *DeclarativeDriftError) Error() string

func (*DeclarativeDriftError) ErrorKind

func (e *DeclarativeDriftError) ErrorKind() string

type DeclarativeRepairReport

type DeclarativeRepairReport struct {
	Repaired                    bool
	Strategy, BackupPath, Error string
}

Outcome of an explicit declarative repair, empty strings standing for the None values of the report

func RepairDeclarativeSchema

func RepairDeclarativeSchema(ctx context.Context, path string, backup bool) *DeclarativeRepairReport

Explicit additive repair beneath the runtime owner lock and the repair lock, every refusal landing in the report

type DeleteSessionOptions

type DeleteSessionOptions struct {
	SessionsDir              string
	ExpectedDeleteIDs        []string
	ExpectedDisplayMessages  map[string][]*jsonutil.Object
	ExcludeActiveWriteGuards bool
	IncludeCompressionChain  bool
}

Delete options, nil ExpectedDeleteIDs and ExpectedDisplayMessages meaning no fence

type DeleteSessionsOptions

type DeleteSessionsOptions struct {
	SessionsDir              string
	ExcludeActiveWriteGuards bool
	SkippedIDs               *[]string
	IncludeCompressionChain  bool
}

Bulk delete options, SkippedIDs collecting the guarded ids a guarded delete skipped

type DeletedWalGenerationError

type DeletedWalGenerationError struct{ Msg string }

Reports a live process holding a deleted wal or shm generation

func (*DeletedWalGenerationError) As

func (e *DeletedWalGenerationError) As(target any) bool

Lets the error match its StateDBReplacedError parent class

func (*DeletedWalGenerationError) Error

func (e *DeletedWalGenerationError) Error() string

type DevIno

type DevIno struct {
	Dev uint64
	Ino uint64
}

Device and inode pair naming one file, the os.stat st_dev and st_ino key

type DiskSnapshot

type DiskSnapshot struct {
	DBBytes, FreeBytes, TotalBytes int64
}

Size of state.db and the free and total bytes of its filesystem

func AutoPruneDiskSnapshot

func AutoPruneDiskSnapshot(ctx context.Context, h string) *DiskSnapshot

State.db size plus free and total bytes of its filesystem, nil when either is unreadable

func AutoPruneShouldAsk

func AutoPruneShouldAsk(ctx context.Context, h string) *DiskSnapshot

Snapshot of a low disk on a home that neither decided nor snoozed, nil otherwise

func (DiskSnapshot) Low

func (d DiskSnapshot) Low() bool

Reports a disk under 2 GiB free, or under 10 percent free while also under 20 GiB

type FileIdentity

type FileIdentity struct{ Dev, Ino uint64 }

Device and inode pair naming one file

func StatDBFileIdentity

func StatDBFileIdentity(path string) (FileIdentity, bool)

Device and inode of a file, false when stat fails or either is zero

type FlushOutcome

type FlushOutcome int

Outcome of a transcript flush, the None, True and False a session flush returns

const (
	// Persistence is off for this agent or it has no session store
	FlushDisabled FlushOutcome = iota
	// Every unflushed row was written
	FlushPersisted
	// The write failed and its cause was classified and logged
	FlushFailed
)

type GatewayPeer

type GatewayPeer struct {
	Source                      string
	UserID                      *string
	SessionKey                  *string
	ChatID                      *string
	ChatType                    *string
	ThreadID                    *string
	DisplayName                 *string
	OriginJSON                  *string
	IncludeCompressionAncestors bool
	TransportProfile            *string
}

type GatewayPeerQuery

type GatewayPeerQuery struct {
	Source     string
	UserID     *string
	SessionKey *string
	ChatID     *string
	ChatType   *string
	ThreadID   *string
}

type GatewayRoutingRow

type GatewayRoutingRow struct {
	Scope, SessionKey, EntryJSON string
	UpdatedAt                    float64
}

One routing index row another store held for this one

type GenerationProbe

type GenerationProbe func(ctx context.Context, conn SQLiteConn, sessionID string) (bool, error)

Probe over one derived session id inside the read or write that walks the generations

type GetMessagesOptions

type GetMessagesOptions struct {
	IncludeInactive, IncludeCompacted bool
	Limit                             *int
	Offset                            int
	Latest                            bool
	AfterID                           *int64
	IncludeAncestors                  bool
}

Paging and visibility of a message read, AfterID nil standing for None

type HeldRowRewrittenError

type HeldRowRewrittenError struct{ Msg string }

Aborts a full writer commit whose held row was rewritten in place

func (*HeldRowRewrittenError) Error

func (e *HeldRowRewrittenError) Error() string

type HistoryActor

type HistoryActor struct {
	ProfileID    string
	Subject      string
	Capabilities []string
}

Principal a history control check acts for

type Holder

type Holder struct {
	PID    int
	Target string
}

One holder of a state database, PID -1 marking a scan that could not prove quiescence

func ForeignStateDBHolders

func ForeignStateDBHolders(dbPath string) ([]Holder, error)

Foreign holders of the database or a sidecar, a failed or partial scan reported as an unknown holder

func InProcessStateDBHolders

func InProcessStateDBHolders(dbPath string, exclude *DB) []Holder

Live generations other than exclude this process keeps open on dbPath, as holders of our own pid

func IterDeletedSQLiteSidecarHolders

func IterDeletedSQLiteSidecarHolders(dbPath string) []Holder

Processes holding an unlinked wal or shm sidecar of the database, this process included, empty on other hosts

type KeyValue

type KeyValue = keyValue

One entry of a OrderedObject

type LifecycleHookInvoker

type LifecycleHookInvoker func(ctx context.Context, hookName string, kwargs map[string]any) ([]any, error)

Dispatches a lifecycle hook to observers and plugins, returning their results

type ListFilter

type ListFilter struct {
	Limit           int
	Offset          int
	Source          string
	ExcludeSources  []string
	Cwd             string
	CwdPrefix       string
	Search          string
	IncludeArchived bool
	IncludeHidden   bool
	IncludeChildren bool
	IncludeEmpty    bool
	OnlyPinned      bool
}

Filters of a session listing

type ListSessionsRichOptions

type ListSessionsRichOptions struct {
	Source                 string
	Sources                []string
	ExcludeSources         []string
	CwdPrefix              string
	Limit                  *int
	Offset                 int
	IncludeChildren        bool
	MinMessageCount        int
	ProjectCompressionTips *bool
	OrderByLastActive      bool
	IncludeArchived        bool
	ArchivedOnly           bool
	IDQuery                string
	SearchQuery            string
	CompactRows            bool
	IncludePinned          bool
	SessionKey             string
	IncludeHidden          bool
	IncludeSubagents       bool
	LocalCreatedSources    []string
}

Listing filters of a rich session page, a nil Limit meaning 20 and a nil ProjectCompressionTips meaning true

type LiveConnectionError

type LiveConnectionError struct {
	Path string
	Main string
	What string
}

Reports a raw file operation attempted on a database with live connections

func (*LiveConnectionError) Error

func (e *LiveConnectionError) Error() string

type LiveSystemGuardError

type LiveSystemGuardError struct {
	Path string
	Root string
}

Refusal a test context process gets for opening a production state database

func (*LiveSystemGuardError) Error

func (e *LiveSystemGuardError) Error() string

func (*LiveSystemGuardError) ErrorKind

func (e *LiveSystemGuardError) ErrorKind() string

Exception class the init error record names for the refusal

type LocalCreateReceipt

type LocalCreateReceipt struct {
	Receipt *jsonutil.Object
	// The staged request's own client env, nil when the receipt carries none
	ClientRequest *jsonutil.Object
	OnCreate      OnCreateSnapshot
}

Staged local create receipt with the owner only parts never stored

type LocalPidNamespace

type LocalPidNamespace struct {
	ID        string
	Supported bool
}

Own PID namespace identity, an empty ID on a supported platform meaning the lookup failed

type Message

type Message struct {
	// Row id, zero before the message is stored
	RowID int64  `json:"-"`
	Role  string `json:"role"`
	// String text or a list of content parts
	Content          any             `json:"content"`
	ToolCallID       string          `json:"tool_call_id,omitempty"`
	ToolCalls        []ToolCall      `json:"tool_calls,omitempty"`
	ToolName         string          `json:"tool_name,omitempty"`
	Timestamp        float64         `json:"timestamp,omitempty"`
	TokenCount       int             `json:"token_count,omitempty"`
	FinishReason     string          `json:"finish_reason,omitempty"`
	Reasoning        string          `json:"reasoning,omitempty"`
	ReasoningContent string          `json:"reasoning_content,omitempty"`
	ReasoningDetails json.RawMessage `json:"reasoning_details,omitempty"`
	// Opaque replay items of a Responses API turn
	CodexReasoningItems json.RawMessage `json:"codex_reasoning_items,omitempty"`
	CodexMessageItems   json.RawMessage `json:"codex_message_items,omitempty"`
	PlatformMessageID   string          `json:"platform_message_id,omitempty"`
	Observed            bool            `json:"observed,omitempty"`
	CompressedSummary   bool            `json:"compressed_summary,omitempty"`
	// Exact string sent to the API when it differed from Content
	APIContent      string         `json:"api_content,omitempty"`
	DisplayKind     string         `json:"display_kind,omitempty"`
	DisplayMetadata map[string]any `json:"display_metadata,omitempty"`
	// Durable id kept across clones and compactions
	MessageUID   string            `json:"message_uid,omitempty"`
	AbsorbedUIDs []string          `json:"absorbed_message_uids,omitempty"`
	ToolCallUIDs map[string]string `json:"tool_call_uids,omitempty"`
	ToolCallUID  string            `json:"tool_call_uid,omitempty"`
	Active       bool              `json:"-"`
	Compacted    bool              `json:"-"`
	// Set once the row exists so a flush never appends it again
	Persisted bool `json:"-"`
	// Dict keys the struct has no field for, such as underscore bookkeeping keys
	Extra map[string]any `json:"-"`
	// Dict key order of the source when known, the restore order for rows the live replay loaded
	Keys []string `json:"-"`
}

One transcript row in provider message shape

func MessageFromDict

func MessageFromDict(d map[string]any) *Message

Message holding every dict key, keys whose value does not fit a field kept in Extra

func (*Message) Text

func (m *Message) Text() string

Text of a message, content parts joined when the content is a list

type MessageRoleReader

type MessageRoleReader interface {
	GetMessageRole(ctx context.Context, sessionID string, messageID int64) (string, bool, error)
}

Session store lookup that reports a row role, false when the row is gone

type MetaEntry

type MetaEntry struct {
	Key   string
	Value any
}

One state_meta row of a prefix listing, Value nil for a NULL value

type MovedReceipt

type MovedReceipt = movedReceipt

Local receipt whose current target row another lane now routes

type NeverActivePruneOptions

type NeverActivePruneOptions struct {
	OlderThanDays float64
	SessionsDir   string
	DeletedIDs    *[]string
}

type NewSession

type NewSession struct {
	ID               string
	Source           string
	UserID           string
	Model            string
	ModelConfig      map[string]any
	SystemPrompt     string
	ParentSessionID  string
	Cwd              string
	GitRepoRoot      string
	ProfileName      string
	SessionKey       string
	ChatID           string
	ChatType         string
	ThreadID         string
	TransportProfile string
	OriginJSON       string
	DisplayName      string
}

Keyword arguments of the session row upsert, empty strings and a nil map are the Python None keywords

type OnCreateSnapshot

type OnCreateSnapshot interface {
	Read() error
	Publish() error
	Withdraw()
}

Owner memory snapshot a staged create receipt publishes with the transaction that creates its row

type OpenDBOption

type OpenDBOption func(*openDBConfig)

Adjusts one setting of an OpenDB call

func WithBusyTimeoutMS

func WithBusyTimeoutMS(ms int) OpenDBOption

Sets the busy timeout passed to connect and set as the explicit pragma, 5000 by default

func WithForeignKeys

func WithForeignKeys() OpenDBOption

Enables foreign key enforcement on the opened connection

func WithInitialize

func WithInitialize(fn func(ctx context.Context, conn SQLiteConn) error) OpenDBOption

Runs fn on the configured connection before OpenDB returns it, closing the connection when fn fails

func WithOpener

func WithOpener(open SQLiteOpener) OpenDBOption

Opens the raw connection through open instead of the package connector

func WithSynchronousFull

func WithSynchronousFull() OpenDBOption

Sets synchronous FULL on the opened connection

func WithWAL

func WithWAL(wal bool) OpenDBOption

Turns the WAL fallback journal setup on or off, on by default

func WithWALLockRetries

func WithWALLockRetries(n int) OpenDBOption

Number of attempts at the journal setup when it reports database is locked, 1 by default

type Options

type Options struct {
	// Opens without creating or migrating anything
	ReadOnly bool
}

Options of a database open

type OrderedObject

type OrderedObject = orderedObject

Insertion ordered JSON object other packages read and build for identity and decoded JSON values

func MergeToolCallUIDs

func MergeToolCallUIDs(into, extra any) OrderedObject

Union of two tool call uid maps keeping one uid per occurrence for a repeated provider id

func PerOccurrenceToolCallUIDs

func PerOccurrenceToolCallUIDs(uids any, toolCalls []any) OrderedObject

Uid map with every provider id named more than once spelled out as one uid per occurrence

type ProcLock

type ProcLock struct {
	PID     *big.Int
	Kind    string
	Sidecar string
}

One write lock from /proc/locks with its owner pid, -1 for an OFD lock, its kind and the sidecar suffix

func ParseProcLocks

func ParseProcLocks(text string, inodes map[DevIno]string) ([]ProcLock, error)

Every WRITE lock of /proc/locks text on the inodes, waiters and read locks dropped, makedev errors raised

type PruneAdvice

type PruneAdvice struct {
	Disk                            DiskSnapshot
	RetentionDays                   int64
	PrunableSessions, TotalSessions int64
	ReclaimBytes                    int64
	EstimateOK                      bool
	VacuumAfterPrune                bool
}

Low disk snapshot with the reclaim estimate a prune of the retention window would give back

func AutoPruneAdvise

func AutoPruneAdvise(ctx context.Context, h string) (*PruneAdvice, error)

Low disk advice with the reclaim estimate, opening state.db read only, nil when the gate stays closed

func (PruneAdvice) Helps

func (a PruneAdvice) Helps() bool

Reports a prune freeing at least 1 GiB or enough to lift the disk out of the low band

type PruneChange

type PruneChange struct {
	Original    map[string]any
	Replacement map[string]any
}

One persisted message the prune edited and the dict that replaces it

type PruneFilters

type PruneFilters struct {
	Archived                                *bool
	IncludePinned, LineageTipsOnly          bool
	IncludeOpen                             bool
	LastActiveBefore, LastActiveAfter       *float64
	StartedBefore, StartedAfter             *float64
	Source, TitleLike, EndReason, CwdPrefix string
	MinMessages, MaxMessages                *float64
	ModelLike, Provider, UserID, ChatID     string
	ChatType, BranchLike                    string
	MinTokens, MaxTokens, MinCost, MaxCost  *float64
	MinToolCalls, MaxToolCalls              *float64
}

Bulk prune and archive selection filters, nil bounds and empty strings unset, Archived nil meaning both

func PruneKwargs

func PruneKwargs(filters map[string]any) (*float64, string, PruneFilters)

Store keyword arguments of a filter dict, the retention bound, the source and the remaining filters

type PruneRewriteOptions

type PruneRewriteOptions struct {
	ModelConfigPatch    *jsonutil.Object
	TurnLeaseHolder     *string
	TurnLeaseTTLSeconds *float64
}

Keyword arguments of rewrite_pruned_rows, a nil TurnLeaseTTLSeconds meaning 300 seconds

type PruneRowStaleError

type PruneRowStaleError struct{ Msg string }

Stops an in place prune whose named row another writer already rewrote

func (*PruneRowStaleError) As

func (e *PruneRowStaleError) As(target any) bool

Lets the error match its PruneRowUnresolvedError parent class

func (*PruneRowStaleError) Error

func (e *PruneRowStaleError) Error() string

type PruneRowUnresolvedError

type PruneRowUnresolvedError struct{ Msg string }

Stops an in place prune that could not name the exact live row

func (*PruneRowUnresolvedError) Error

func (e *PruneRowUnresolvedError) Error() string

type PruneSessionsOptions

type PruneSessionsOptions struct {
	OlderThanDays            *float64
	Source                   string
	SessionsDir              string
	ExcludeActiveWriteGuards bool
	DeletedIDs               *[]string
	Filters                  PruneFilters
}

Options of a prune pass, a nil OlderThanDays meaning no implicit age bound

func NewPruneSessionsOptions

func NewPruneSessionsOptions() PruneSessionsOptions

Prune options with the 90 day retention default

type RecentSessionsBoundedOptions

type RecentSessionsBoundedOptions struct {
	Limit          *int
	ExcludeSources []string
	TimeoutSeconds *float64
	CandidateLimit *int
	LineageLimit   *int
}

Bounded recent browse knobs, nil values taking the defaults of 20 rows and a 3 second deadline

type RepairConn

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

SQLite connection the repair probe drives, closed by the probe once it settles

type RepairReport

type RepairReport struct {
	Repaired             bool
	Strategy             string
	BackupPath           string
	Error                string
	JournalModeBefore    string
	HasJournalModeBefore bool
	// contains filtered or unexported fields
}

Outcome of one schema repair pass, empty strings standing for the None values of the report dict

func RepairStateDBSchema

func RepairStateDBSchema(ctx context.Context, dbPath string, backup bool) (*RepairReport, error)

Repairs a state database whose schema is malformed or whose FTS indexes reject writes, on a snapshot promoted back

type ReplaceOptions

type ReplaceOptions struct {
	ActiveOnly            bool
	ArchiveDropped        bool
	RejectActiveTurnLease bool
}

Modes of a transcript replacement

type RetiredGenerationCaptureError

type RetiredGenerationCaptureError struct{ Msg string }

Reports a retired WAL generation that could not be captured durably, nothing having been mutated

func (*RetiredGenerationCaptureError) Error

type RewindOptions

type RewindOptions struct {
	PreserveCompactionHandoff bool
	ExpectedActiveIDs         []int64
	ExpectedTargetContent     any
}

Keyword arguments of a rewind, nil standing for an omitted Python argument

type RewindOutcome

type RewindOutcome struct {
	Prefix       []map[string]any
	LiveView     map[string]any
	LiveText     string
	RewoundCount int
	TurnsUndone  int
}

Installed history, live projection and retry text of a committed rewind with its counts

type RewindPlan

type RewindPlan struct {
	TargetRowID           int64
	ExpectedActiveIDs     []int64
	ExpectedTargetContent any
	Scaffold              map[string]any
	Prefix                []map[string]any
	DurablePrefix         []map[string]any
	LiveView              map[string]any
	LiveText              *string
	DurableUser           []int
	UserOrdinal           int
	// contains filtered or unexported fields
}

Every read and check a rewind makes before its write

type RewindRuntimeError

type RewindRuntimeError struct{ Msg string }

Python RuntimeError raised when the warm and durable histories disagree or an identity is missing

func (*RewindRuntimeError) Error

func (e *RewindRuntimeError) Error() string

func (*RewindRuntimeError) ErrorKind

func (e *RewindRuntimeError) ErrorKind() string

type RewindTargetUnavailableError

type RewindTargetUnavailableError struct{ Msg string }

Requested user turn is not a rewindable target of the active transcript, a ValueError subclass

func (*RewindTargetUnavailableError) Error

func (*RewindTargetUnavailableError) ErrorKind

func (e *RewindTargetUnavailableError) ErrorKind() string

type RewindUserTurnOptions

type RewindUserTurnOptions struct {
	WarmHistory                        []map[string]any
	HasWarmHistory                     bool
	RequireRetryable, RequireComposite bool
	AdoptRowIDs                        bool
}

Keyword arguments of a user turn rewind

type RuntimeLock

type RuntimeLock struct {
	Model, Provider, RouteSource *string
	ModelOptions                 any
	Confirmed                    bool
}

Browser or API client runtime lock fields, nil strings meaning unset

type RuntimeMutation

type RuntimeMutation struct {
	Epoch              int64
	PrincipalID        string
	SessionID          string
	RequestID          string
	ExpectedRevision   int64
	Operation          string
	Payload            any
	ExpectedGeneration *int64
	// Raises to refuse the mutation of the targets it names before anything is written
	LiveGuard func(targets []string) error
	// Raises to refuse a new write, never seeing replays
	AuthorizeWrite func(ctx context.Context, conn SQLiteConn) error
	PrepareOnly    bool
	Prepared       *jsonutil.Object
}

Keyword arguments of mutate_runtime_session

type RuntimeStoreError

type RuntimeStoreError struct {
	Reason string
	Field  *string
	Detail *string
	// The failed check this refusal was raised from, nil when it stands alone
	Cause error
}

Refusal by the state authority, Reason being the bounded wire code callers compare

func BusyRefusal

func BusyRefusal(err error) *RuntimeStoreError

Client facing busy refusal for a guard refusal, naming a held compression lock in its field

func NewRuntimeStoreError

func NewRuntimeStoreError(reason string, field, detail *string) *RuntimeStoreError

Refusal with its field and detail collapsed to one bounded printable line

func (*RuntimeStoreError) Error

func (e *RuntimeStoreError) Error() string

func (*RuntimeStoreError) Unwrap

func (e *RuntimeStoreError) Unwrap() error

type SQLiteClass

type SQLiteClass int

Names the Python sqlite3 exception class an error belongs to

const (
	SQLiteDatabaseError SQLiteClass = iota + 1
	SQLiteOperationalError
	SQLiteIntegrityError
	SQLiteInterfaceError
	SQLiteInternalError
	SQLiteDataError
	SQLiteProgrammingError
	SQLiteNotSupportedError
)

func SQLiteClassOf

func SQLiteClassOf(err error) (SQLiteClass, bool)

Python sqlite3 exception class of an error for callers outside this package, false when it is no sqlite3 exception

type SQLiteConfig

type SQLiteConfig struct {
	Timeout float64
	URI     bool
}

The sqlite3.connect arguments an opener honours, busy timeout in seconds and URI filename parsing

type SQLiteConn

type SQLiteConn interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
	Close() error
}

SQLite connection surface the tracked helpers work over, satisfied by *sql.Conn and *sql.DB

func ConnectSQLite

func ConnectSQLite(database string, cfg SQLiteConfig) (SQLiteConn, error)

sqlite3.connect opening one autocommit connection right away with its busy timeout set

type SQLiteError

type SQLiteError struct {
	Class   SQLiteClass
	Msg     string
	Code    int
	HasCode bool
	// The row's own value cannot be stored so no retry writes it
	UnbindableValue bool
}

A sqlite3 exception raised by state code itself with a class, message and optional result code

func (*SQLiteError) Error

func (e *SQLiteError) Error() string

type SQLiteMasterRow

type SQLiteMasterRow struct {
	RootPage int64
	Type     string
	Name     string
}

One sqlite_master row of the rootpage map an integrity check names its damaged trees through

type SQLiteOpener

type SQLiteOpener func(database string, cfg SQLiteConfig) (SQLiteConn, error)

Opens one SQLite connection to a database name, the role sqlite3.connect plays

type SQLiteRuntimeInfo

type SQLiteRuntimeInfo struct {
	SQLiteVersion       VersionTuple
	SQLiteVersionString string
	MissingFeatures     []string
}

SQLite facts one icebath binary reports about the library linked into it

func ProbeSQLiteRuntime

func ProbeSQLiteRuntime(binary string, timeout float64) (*SQLiteRuntimeInfo, error)

Report of an icebath binary's hidden SQLite verb, an error when it fails, times out or prints nothing usable

func (*SQLiteRuntimeInfo) Safe

func (i *SQLiteRuntimeInfo) Safe() bool

Whether the linked SQLite is free of the WAL reset bug and has every feature the session store needs

func (*SQLiteRuntimeInfo) WALResetVulnerable

func (i *SQLiteRuntimeInfo) WALResetVulnerable() bool

Whether the binary's linked SQLite carries the WAL reset bug

type SchemaEdit

type SchemaEdit struct {
	Op     string
	Column string
	After  string
}

One edit to a declared column order, After empty inserting at the front, Op minus removing Column

type SchemaEvent

type SchemaEvent struct {
	Label string
	Edits []SchemaEdit
}

One shipped release that changed a declaration, labelled by sequence number, commit time and sha

type SearchMessagesOptions

type SearchMessagesOptions struct {
	SourceFilter    []string
	ExcludeSources  []string
	RoleFilter      []string
	Limit           int
	Offset          int
	Sort            string
	IncludeInactive bool
	Fields          []string
	AfterTS         *int64
	BeforeTS        *int64
}

Keyword arguments of search_messages, NewSearchMessagesOptions giving the Python defaults

func NewSearchMessagesOptions

func NewSearchMessagesOptions() SearchMessagesOptions

Options with the search_messages defaults, twenty rows from offset zero ranked by BM25

type SearchSessionsByIDOptions

type SearchSessionsByIDOptions struct {
	Limit           *int
	IncludeArchived *bool
	Source          string
	Sources         []string
	ExcludeSources  []string
}

Filters of an id search, a nil Limit meaning 20 and a nil IncludeArchived meaning archived rows included

type SearchSessionsOptions

type SearchSessionsOptions struct {
	Sources             []string
	Limit               int
	Offset              int
	WorkspaceKey        string
	LocalCreatedSources []string
	SkipLaunchStubs     bool
}

Arguments of search_sessions

type Session

type Session struct {
	ID               string
	Source           string
	UserID           string
	Model            string
	ModelConfig      map[string]any
	SystemPrompt     string
	ParentSessionID  string
	StartedAt        float64
	EndedAt          float64
	EndReason        string
	MessageCount     int
	ToolCallCount    int
	InputTokens      int64
	OutputTokens     int64
	CacheReadTokens  int64
	CacheWriteTokens int64
	ReasoningTokens  int64
	Cwd              string
	GitBranch        string
	GitRepoRoot      string
	BillingProvider  string
	BillingBaseURL   string
	BillingMode      string
	EstimatedCostUSD float64
	ActualCostUSD    float64
	CostStatus       string
	CostSource       string
	PricingVersion   string
	Title            string
	TitleSource      string
	LastActivityAt   float64
	LastActivity     string
	APICallCount     int
	ProfileName      string
	RewindCount      int
	Archived         bool
	AutoArchived     bool
	Pinned           bool
	Hidden           bool
	LastReadAt       float64
	ToolNames        []string
	TranscriptRev    int64
	// Head of the first user message, filled by listings
	Preview string
	// Freshest activity known, filled by listings
	LastActive float64
}

Row of the sessions table

type SessionActiveWriteGuardError

type SessionActiveWriteGuardError struct{ Msg string }

Rejects a deletion an active turn lease or compression lock protects

func (*SessionActiveWriteGuardError) Error

type SessionCompressionInProgressError

type SessionCompressionInProgressError struct{ Msg string }

The transient busy case of a live compression lock

func (*SessionCompressionInProgressError) As

Lets the error match its CompressionSessionBusyError parent class

func (*SessionCompressionInProgressError) Error

type SessionCountOptions

type SessionCountOptions struct {
	Source              string
	Sources             []string
	CwdPrefix           string
	MinMessageCount     int
	IncludeArchived     bool
	ArchivedOnly        bool
	ExcludeChildren     bool
	ExcludeSources      []string
	IncludeSubagents    bool
	LocalCreatedSources []string
}

type SessionDB

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

SQLite session store with FTS5 search, many pooled readers and one writer connection

func NewSessionDB

func NewSessionDB(ctx context.Context, dbPath string, readOnly bool) (*SessionDB, error)

Opens the session store at dbPath, the default profile store when empty, read only without schema work when asked

func (*SessionDB) AcquireSessionTurnLease

func (d *SessionDB) AcquireSessionTurnLease(sessionID, holder string, o TurnLeaseWait) (bool, error)

Polls for the conversation turn lease until acquired, aborted or out of time, notifying waiters on the way

func (*SessionDB) AdmitSessionInput

func (d *SessionDB) AdmitSessionInput(ctx context.Context, in SessionInput) (*jsonutil.Object, error)

Admits input exactly once per principal request, replaying an identical retry and refusing a changed one

func (*SessionDB) AdoptOrphanedGatewaySession

func (d *SessionDB) AdoptOrphanedGatewaySession(ctx context.Context, orphanID, donorID string) (bool, error)

Stamps the orphan with the donor's routing identity and retires the donor, rechecking the pair inside the write

func (*SessionDB) AdoptSessionLineageFrom

func (d *SessionDB) AdoptSessionLineageFrom(ctx context.Context, donor *SessionDB, sessionID string, retireDonor bool) (*jsonutil.Object, error)

Adopts a session's whole compression lineage from a donor store, archiving the donor rows after a complete adoption

func (*SessionDB) AdoptUntrackedCompression

func (d *SessionDB) AdoptUntrackedCompression(ctx context.Context, epoch int64, sessionID string, expected *jsonutil.Object) error

Records once the compression steps a receipt unaware build published past the receipt tip, while the receipt is still expected

func (*SessionDB) AdoptWorkerExecution

func (d *SessionDB) AdoptWorkerExecution(ctx context.Context, epoch int64, executionID, sessionID string, generation int64, adoptionSecret string) (*jsonutil.Object, error)

Moves a proven worker and its linked admission under this epoch, refusing a terminal, foreign secret or late handshake

func (*SessionDB) AppendCompletionNote

func (d *SessionDB) AppendCompletionNote(ctx context.Context, sessionID, admissionID, content, displayKind string, metadata *jsonutil.Object) (int64, error)

Records an unviewed completion note once, keyed by its admission stored as completion_admission

func (*SessionDB) AppendDelegationDelivery

func (d *SessionDB) AppendDelegationDelivery(ctx context.Context, sessionID, content string, metadata *jsonutil.Object) (int64, error)

Records a detached API delegation result once, keyed by its delegation id

func (*SessionDB) AppendMessage

func (d *SessionDB) AppendMessage(ctx context.Context, sessionID string, fields map[string]any, guards AppendGuards) (int64, error)

Appends one message dict with its role under the transcript guards, returning the row id after bumping counters

func (*SessionDB) AppendMessagesBatch

func (d *SessionDB) AppendMessagesBatch(ctx context.Context, sessionID string, messages []map[string]any, guards AppendGuards, chunkRows *int) (int, error)

Appends messages in one write transaction with the guards run once, chunking large copies, returning the inserted count

func (*SessionDB) AppendMessagesInTransaction

func (d *SessionDB) AppendMessagesInTransaction(ctx context.Context, conn SQLiteConn, sessionID string, messages []map[string]any, guards AppendGuards) (int, error)

Appends messages to a session inside the caller's write transaction, returning how many rows it wrote

func (*SessionDB) ApplyTelegramTopicMigration

func (d *SessionDB) ApplyTelegramTopicMigration(ctx context.Context) error

Creates the topic tables, rebuilds pre v3 tables into the profile keyed shape and stamps schema version 3

func (*SessionDB) ApplyWorkerReceipt

func (d *SessionDB) ApplyWorkerReceipt(ctx context.Context, in WorkerReceipt, handlers map[string]WorkerHandler) (*jsonutil.Object, error)

One fenced worker receipt transaction, an exact retry replaying the stored result

func (*SessionDB) ArchiveAndCompact

func (d *SessionDB) ArchiveAndCompact(ctx context.Context, sessionID string, compacted []map[string]any, o ArchiveCompactOptions) (int, error)

Soft archives active rows and inserts the compacted set as fresh active rows atomically, returning the active count

func (*SessionDB) ArchiveSessions

func (d *SessionDB) ArchiveSessions(ctx context.Context, olderThanDays *float64, source string, f PruneFilters) (int, error)

Archives every lineage whose tip matches the prune filters, unarchived rows only unless told otherwise

func (*SessionDB) ArchiveStaleSessions

func (d *SessionDB) ArchiveStaleSessions(ctx context.Context, idleDays float64, excludePinned bool) (int, error)

Archives every lineage tip idle for the given days through the sweep provenance, the hidden Bot Chat exempt

func (*SessionDB) AssertExportSafe

func (d *SessionDB) AssertExportSafe(ctx context.Context, sessionID string, maxMessages *int) (int, error)

Export row count of a segment, every row counted, refusing above the bound, zero disabling the guard

func (*SessionDB) AssertExportsSafe

func (d *SessionDB) AssertExportsSafe(ctx context.Context, sessionIDs []string, maxMessages *int) error

AssertExportSafe over every id with the bound resolved once, zero disabling without any query

func (*SessionDB) AssertResumeSafe

func (d *SessionDB) AssertResumeSafe(ctx context.Context, sessionID string, maxMessages *int, tipOnly bool) (int, error)

Bounded count of the messages a resume reloads, refusing a transcript past the cap

func (*SessionDB) AuxiliaryUsageByTask

func (d *SessionDB) AuxiliaryUsageByTask(ctx context.Context, sessionID string) (*jsonutil.Object, error)

Per task auxiliary usage summed over the compression lineage, cut at the nearest explicit branch

func (*SessionDB) BackfillNullSessionProfiles

func (d *SessionDB) BackfillNullSessionProfiles(ctx context.Context, profileName string) (int, error)

Stamps the given owner onto rows whose profile is null or blank, never overwriting an owner, returning rows stamped

func (*SessionDB) BackfillRepoRoots

func (d *SessionDB) BackfillRepoRoots(ctx context.Context, cwdToRoot map[string]string) error

Fills the git repo root of every listed cwd that has none, never clobbering a recorded root

func (*SessionDB) BeginRuntimeEpoch

func (d *SessionDB) BeginRuntimeEpoch(ctx context.Context, instanceID string) (int64, error)

Advances the runtime epoch for a new owner, which must hold the profile ownership lock

func (*SessionDB) BindTelegramTopic

func (d *SessionDB) BindTelegramTopic(ctx context.Context, b TelegramTopicBinding) error

Binds one topic thread to one session, a ValueError when the session already holds a different topic

func (*SessionDB) CancelSessionInput

func (d *SessionDB) CancelSessionInput(ctx context.Context, epoch int64, admissionID string) (*jsonutil.Object, error)

Cancels a queued admission, refusing a started, unknown or steering one and replaying a terminal one

func (*SessionDB) ClaimHandoff

func (d *SessionDB) ClaimHandoff(ctx context.Context, sessionID string) (bool, error)

Atomically moves a pending handoff to running and reports whether this caller claimed it

func (*SessionDB) ClaimSessionInput

func (d *SessionDB) ClaimSessionInput(ctx context.Context, in ClaimInput) (claimed *jsonutil.Object, moved bool, err error)

Claims the FIFO head, nil when nothing is claimable and moved when the head is no longer the one checked

func (*SessionDB) ClearBackendHeartbeat

func (d *SessionDB) ClearBackendHeartbeat(ctx context.Context, backendID string) (bool, error)

Removes the heartbeat row of one backend and reports whether a row went away

func (*SessionDB) ClearCompressionFailureCooldown

func (d *SessionDB) ClearCompressionFailureCooldown(sessionID string)

Clears any persisted compression failure cooldown, logging instead of failing

func (*SessionDB) ClearCompressionFailureCooldownChecked

func (d *SessionDB) ClearCompressionFailureCooldownChecked(sessionID string) error

Cooldown clear answering the raise a worker store can make

func (*SessionDB) ClearMessages

func (d *SessionDB) ClearMessages(ctx context.Context, sessionID string) error

Deletes every message of a session and resets its counters

func (*SessionDB) ClearSessionActivityLabels

func (d *SessionDB) ClearSessionActivityLabels(sessionID string) error

Clears the activity description and provenance after a turn, skipping the write when already clear

func (*SessionDB) Close

func (d *SessionDB) Close() error

Closes the handle, or releases one reference of a registry shared handle

func (*SessionDB) CollectRetiredMedia

func (d *SessionDB) CollectRetiredMedia(ctx context.Context) error

Releases retired media no admission or retained transcript row owns and drops collected candidates

func (*SessionDB) CommitChatPick

func (d *SessionDB) CommitChatPick(ctx context.Context, epoch int64, key, digest, sessionID string, params, result *jsonutil.Object) (any, error)

Bumps the mount revision and stores the result with that revision as the receipt in one fenced write

func (*SessionDB) CommitLocalSession

func (d *SessionDB) CommitLocalSession(ctx context.Context, epoch int64, staged LocalCreateReceipt) (*jsonutil.Object, error)

Reserves the row, route and immutable policy of a local session together before publication

func (*SessionDB) CommitRefreshedPolicy

func (d *SessionDB) CommitRefreshedPolicy(ctx context.Context, epoch int64, sessionID string, old, new any, generation int64) (any, error)

Replaces exactly the old policy of an idle session at its generation and returns the next generation

func (*SessionDB) CompleteHandoff

func (d *SessionDB) CompleteHandoff(ctx context.Context, sessionID string) error

Marks the session's handoff completed and clears its error

func (*SessionDB) ConversationRevision

func (d *SessionDB) ConversationRevision(ctx context.Context, sessionID string, includeAncestors bool) (TranscriptRevision, error)

Revision of the active transcript, changing whenever a row lands, leaves or is rewritten

func (*SessionDB) CountEmptySessions

func (d *SessionDB) CountEmptySessions(ctx context.Context) (int, error)

Count of empty ended unarchived sessions

func (*SessionDB) CountMessagesAll

func (d *SessionDB) CountMessagesAll(ctx context.Context, sessionID string) (int, error)

Message rows of a session across every generation

func (*SessionDB) CountOpenPruneMatches

func (d *SessionDB) CountOpenPruneMatches(ctx context.Context, olderThanDays *float64, source string, f PruneFilters) (int, error)

Count of open sessions a matching prune or archive skips, zero when the selection includes open rows

func (*SessionDB) CountPruneMatches

func (d *SessionDB) CountPruneMatches(ctx context.Context, olderThanDays *float64, source string, pinnedOnly bool, f PruneFilters) (int, error)

Count of prune matches, pinnedOnly counting the rows that carry the pin itself

func (*SessionDB) CountSessionsWithStoredPrompt

func (d *SessionDB) CountSessionsWithStoredPrompt(ctx context.Context) (int, error)

Sessions whose next turn would replay a stored prompt, the ones a refresh rebuilds

func (*SessionDB) CreateSession

func (d *SessionDB) CreateSession(n NewSession) error

Creates or upserts a session record

func (*SessionDB) CronRunIdentity

func (d *SessionDB) CronRunIdentity(ctx context.Context, sessionID string) (*jsonutil.Object, error)

Cron job and execution ids of a cron run session, nil for any other session

func (*SessionDB) DeactivateMessage

func (d *SessionDB) DeactivateMessage(ctx context.Context, sessionID string, rowID int64) (int64, error)

Deactivates one known row idempotently, returning the affected row count

func (*SessionDB) DeactivateMessagesByDisplayKind

func (d *SessionDB) DeactivateMessagesByDisplayKind(ctx context.Context, sessionID, displayKind string) (int64, error)

Deactivates every live row of one display kind, returning the affected row count

func (*SessionDB) DeclaredScopeIdentity

func (d *SessionDB) DeclaredScopeIdentity(ctx context.Context, sessionID string) (bool, string, error)

Fork child flag and trimmed source of one session from a single read, false and empty when missing

func (*SessionDB) DeleteEmptySessions

func (d *SessionDB) DeleteEmptySessions(ctx context.Context, sessionsDir string) (int, error)

Deletes every empty ended unarchived session in one transaction, orphaning children and sweeping transcript files

func (*SessionDB) DeleteGatewayRoutingRows

func (d *SessionDB) DeleteGatewayRoutingRows(ctx context.Context, rows [][2]string) (int64, error)

Deletes the routing rows named by scope and session key, returning how many went

func (*SessionDB) DeleteMovedSession

func (d *SessionDB) DeleteMovedSession(ctx context.Context, sessionID string) (bool, error)

Removes a session this store no longer owns after the target confirmed it, children left behind detached

func (*SessionDB) DeleteSession

func (d *SessionDB) DeleteSession(ctx context.Context, sessionID string, o DeleteSessionOptions) (bool, error)

Deletes a session with its lineage and delegate children inside drift fences, orphaning branch children

func (*SessionDB) DeleteSessionIfEmpty

func (d *SessionDB) DeleteSessionIfEmpty(ctx context.Context, sessionID, sessionsDir string) (bool, error)

Deletes an untitled session with no messages and no children unless a live write guard protects it

func (*SessionDB) DeleteSessions

func (d *SessionDB) DeleteSessions(ctx context.Context, sessionIDs []string, o DeleteSessionsOptions) (int, error)

Deletes the sessions with delete_session semantics in one transaction, returning how many requested rows went

func (*SessionDB) DeleteTelegramTopicBinding

func (d *SessionDB) DeleteTelegramTopicBinding(ctx context.Context, chatID, threadID, profileName string) (int, error)

Deletes one chat thread binding and disables topic mode when it was the chat's last, returning rows deleted

func (*SessionDB) DisableTelegramTopicMode

func (d *SessionDB) DisableTelegramTopicMode(ctx context.Context, chatID, profileName string, clearBindings bool) error

Turns topic mode off for one chat and drops its bindings when asked, absent tables a silent no op

func (*SessionDB) DiscardUnadmittedSession

func (d *SessionDB) DiscardUnadmittedSession(ctx context.Context, sessionID string) (bool, error)

Removes a just created row nobody was admitted against without the retirement fence, else the fenced delete

func (*SessionDB) DisplayMessageCount

func (d *SessionDB) DisplayMessageCount(ctx context.Context, sessionID string) (int64, error)

Rows a display read of the segment paints, one per display order group

func (*SessionDB) DistinctSessionCwds

func (d *SessionDB) DistinctSessionCwds(ctx context.Context, includeArchived bool) ([]*jsonutil.Object, error)

Distinct non empty session cwds with usage counts and last activity for repo discovery

func (*SessionDB) EnableTelegramTopicMode

func (d *SessionDB) EnableTelegramTopicMode(ctx context.Context, m TelegramTopicMode) error

Migrates the topic tables and upserts the enabled topic mode row of one private chat and user

func (*SessionDB) EndAndBump

func (d *SessionDB) EndAndBump(ctx context.Context, conn SQLiteConn, query string, params []any, sessionID, reason string) (int64, error)

Runs an end stamp update and bumps the conversation generation, the writer entry of wrappers outside the package

func (*SessionDB) EndIdleLocalSession

func (d *SessionDB) EndIdleLocalSession(ctx context.Context, epoch int64, sessionID, targetID, reason string) (int64, error)

Stamps ended_at on the physical target only while the logical session's FIFO and workers are idle

func (*SessionDB) EndSession

func (d *SessionDB) EndSession(sessionID, endReason string) error

Marks a session ended keeping the first end reason, advancing the generation only when this call ended it

func (*SessionDB) EnsureSession

func (d *SessionDB) EnsureSession(n NewSession) error

Ensures a session row exists, an empty source meaning unknown

func (*SessionDB) ExecuteWrite

func (d *SessionDB) ExecuteWrite(ctx context.Context, fn func(conn SQLiteConn) error) error

Runs fn inside the retried write transaction with the default patience

func (*SessionDB) ExpiringRetirements

func (d *SessionDB) ExpiringRetirements(ctx context.Context, sessionIDs []string) (map[string]bool, error)

Ids among the given sessions whose own retired marker is a sweep marker that ages out

func (*SessionDB) ExportAll

func (d *SessionDB) ExportAll(ctx context.Context, source string, includeCompacted, includeInactive bool) ([]*jsonutil.Object, error)

Every session with its messages, one batched read per 900 sessions outside the display projection

func (*SessionDB) ExportSession

func (d *SessionDB) ExportSession(ctx context.Context, sessionID string, includeCompacted, includeInactive bool) (*jsonutil.Object, error)

One session with every message as a dict, compacted turns and archived rows on request, nil when unknown

func (*SessionDB) ExportSessionForMove

func (d *SessionDB) ExportSessionForMove(ctx context.Context, sessionID string) (*SessionMovePayload, error)

Move payload of a session, nil when absent, refused for a row the gateway ledger references

func (*SessionDB) ExportSessionLineage

func (d *SessionDB) ExportSessionLineage(ctx context.Context, sessionID string, includeCompacted, includeInactive bool) (*jsonutil.Object, error)

A compression lineage exported as one logical session dict with its segments, nil when unknown

func (SessionDB) FTSCJKRebuildStatus

func (s SessionDB) FTSCJKRebuildStatus(ctx context.Context) (*jsonutil.Object, error)

CJK index backfill progress or nil when none is pending

func (SessionDB) FTSCJKRebuildStep

func (s SessionDB) FTSCJKRebuildStep(ctx context.Context, progress *backfillProgress) (bool, error)

Backfills one chunk of the CJK index, true while work remains

func (SessionDB) FTSOptimizeAvailable

func (s SessionDB) FTSOptimizeAvailable(ctx context.Context) (bool, error)

Reports whether optimize storage has work, false without FTS5 or on a read only handle

func (SessionDB) FTSRebuildStatus

func (s SessionDB) FTSRebuildStatus(ctx context.Context) (*jsonutil.Object, error)

Deferred base rebuild progress or nil when none is pending, read through the pooled reader

func (SessionDB) FTSRebuildStep

func (s SessionDB) FTSRebuildStep(ctx context.Context, progress *backfillProgress) (bool, error)

Backfills one chunk of the deferred base rebuild into every servable index, true while work remains

func (*SessionDB) FailHandoff

func (d *SessionDB) FailHandoff(ctx context.Context, sessionID, reason string, onlyStates []string) (bool, error)

Marks the handoff failed with the reason, a compare and swap on the state when only states are given

func (*SessionDB) FinalizeOrphanedCompressionSessions

func (d *SessionDB) FinalizeOrphanedCompressionSessions(ctx context.Context) (int64, error)

Marks week old message bearing continuations of compression parents that never ran an API call as orphaned

func (*SessionDB) FindCrossedProfileSessions

func (d *SessionDB) FindCrossedProfileSessions(ctx context.Context, owner string) (*CrossedProfileSessions, error)

Keyed session rows whose identity disagrees with itself or with the owner of this store

func (*SessionDB) FindForeignImport

func (d *SessionDB) FindForeignImport(ctx context.Context, origin *jsonutil.Object) (string, error)

Session id of an earlier import of the foreign snapshot, empty when none

func (*SessionDB) FindLatestGatewaySessionForPeer

func (d *SessionDB) FindLatestGatewaySessionForPeer(ctx context.Context, q GatewayPeerQuery) (*jsonutil.Object, error)

Latest recoverable gateway row for the peer by exact key, then by the profile fenced full peer tuple

func (*SessionDB) FindLiveCompressionChild

func (d *SessionDB) FindLiveCompressionChild(ctx context.Context, parentSessionID string) (*jsonutil.Object, error)

Unique live direct continuation of a compression ended parent, nil when none or several

func (*SessionDB) FindOrphanedGatewaySessions

func (d *SessionDB) FindOrphanedGatewaySessions(ctx context.Context, maxGapS *float64) ([]*jsonutil.Object, error)

Message bearing rows that lost their routing identity, adoptable only when exactly one keyed predecessor is named

func (*SessionDB) FindPRURLMessages

func (d *SessionDB) FindPRURLMessages(ctx context.Context, sessionIDs []string) ([]map[string]any, error)

Tool results containing a pull request path, oldest first

func (*SessionDB) FindProfileLessTelegramTopicRows

func (d *SessionDB) FindProfileLessTelegramTopicRows(ctx context.Context) ([]*jsonutil.Object, error)

Telegram topic bindings labelled default whose session key names a named profile

func (*SessionDB) FindSessionAdmission

func (d *SessionDB) FindSessionAdmission(ctx context.Context, principalID, sessionID, requestID string) (*jsonutil.Object, error)

Admission at its exact durable identity, the unique principal, target and request key

func (*SessionDB) FindSessionByOrigin

func (d *SessionDB) FindSessionByOrigin(ctx context.Context, platform, chatID string, threadID, userID *string) (string, error)

Most recent live session id of a platform chat, empty when none or when several participants make it ambiguous

func (*SessionDB) FirstGeneration

func (d *SessionDB) FirstGeneration(ctx context.Context, derive func(int) string, pinned, spent GenerationProbe) (int, string, error)

First derived generation a new request may use, skipping retired ids unless pinned and live ids spent

func (*SessionDB) FlushForRead

func (d *SessionDB) FlushForRead(ctx context.Context) bool

Read side token barrier that never waits on a goroutine running an event loop

func (*SessionDB) FlushTokenCounts

func (d *SessionDB) FlushTokenCounts(timeoutS float64) bool

Blocks until every queued token delta is applied, false on timeout

func (*SessionDB) FlushTokenCountsChecked

func (d *SessionDB) FlushTokenCountsChecked(timeoutS float64) (bool, error)

Token count drain answering the raise a worker store can make

func (SessionDB) ForeignStateDBHolders

func (c SessionDB) ForeignStateDBHolders() ([]Holder, error)

Foreign processes holding this store for callers outside this package

func (*SessionDB) FreelistRatio

func (d *SessionDB) FreelistRatio(ctx context.Context) (float64, bool)

Reclaimable page fraction gating VACUUM, false when the pragmas cannot be read

func (*SessionDB) GatewayRoutingEntryForSession

func (d *SessionDB) GatewayRoutingEntryForSession(ctx context.Context, sessionID string) (*jsonutil.Object, error)

Routing entry in any scope whose current owner is the session, nil when none names it

func (*SessionDB) GetActiveMessageIDs

func (d *SessionDB) GetActiveMessageIDs(ctx context.Context, sessionID string) ([]int64, error)

Ordered physical active ids of a session for rewind compare and set checks

func (*SessionDB) GetActiveMessageWatermark

func (d *SessionDB) GetActiveMessageWatermark(ctx context.Context, sessionID string) (int64, error)

Highest active row id, zero when none, captured when compression starts

func (*SessionDB) GetAncestorDisplayPrefix

func (d *SessionDB) GetAncestorDisplayPrefix(ctx context.Context, sessionID string) ([]map[string]any, error)

Display messages the ancestors contribute ahead of the tip, row ids stripped

func (SessionDB) GetAnchoredView

func (s SessionDB) GetAnchoredView(ctx context.Context, sessionID string, aroundMessageID int64, o AnchoredViewOptions) (*jsonutil.Object, error)

Anchored message window plus the first and last non empty messages outside it, empty when the anchor is foreign

func (*SessionDB) GetCompressionChain

func (d *SessionDB) GetCompressionChain(ctx context.Context, sessionID string) ([]string, error)

Compression continuation chain of a session, root first through the tip

func (*SessionDB) GetCompressionFailureCooldown

func (d *SessionDB) GetCompressionFailureCooldown(sessionID string) (*jsonutil.Object, error)

Unexpired compression failure cooldown with its remaining seconds, nil when none is live

func (*SessionDB) GetCompressionFailureCooldownRow

func (d *SessionDB) GetCompressionFailureCooldownRow(sessionID string) (CompressionCooldownRow, error)

Exact stored cooldown columns so a cancelled compression can roll an expired or absent row back

func (*SessionDB) GetCompressionLineage

func (d *SessionDB) GetCompressionLineage(ctx context.Context, sessionID string) ([]string, error)

Compression ancestors through the tip in chronological order, later tips only when the session itself was compacted

func (*SessionDB) GetCompressionLockHolder

func (d *SessionDB) GetCompressionLockHolder(sessionID string) (*string, error)

Current unexpired compression lock holder, nil when none

func (*SessionDB) GetCompressionTip

func (d *SessionDB) GetCompressionTip(ctx context.Context, sessionID string) (string, error)

Live tip of a compression chain, the input id when no continuation exists

func (*SessionDB) GetConversationRoot

func (d *SessionDB) GetConversationRoot(sessionID string) (string, error)

Lineage root of a session id, the id itself when it has no recorded chain

func (*SessionDB) GetHandoffState

func (d *SessionDB) GetHandoffState(ctx context.Context, sessionID string) *jsonutil.Object

State, platform and error of the session's handoff record, nil when it has none or the read fails

func (*SessionDB) GetLatestTodoResult

func (d *SessionDB) GetLatestTodoResult(ctx context.Context, sessionID string, maxChars *int) (string, bool, error)

Newest visible, paired and valid Todo result in the resume display scope, false when none

func (*SessionDB) GetMessageReactions

func (d *SessionDB) GetMessageReactions(ctx context.Context, sessionID string, rowID int64) ([]any, error)

Reaction list persisted on one visible message row, never nil

func (*SessionDB) GetMessageRole

func (d *SessionDB) GetMessageRole(ctx context.Context, sessionID string, rowID int64) (string, bool, error)

Role of the active message at the row id in the session, false when absent

func (*SessionDB) GetMessages

func (d *SessionDB) GetMessages(ctx context.Context, sessionID string, o GetMessagesOptions) ([]*jsonutil.Object, error)

Message dicts of a session page under the requested visibility, deduped for display reads

func (*SessionDB) GetMessagesAround

func (d *SessionDB) GetMessagesAround(ctx context.Context, sessionID string, aroundMessageID int64, window int) (*jsonutil.Object, error)

Messages around one message id within window

func (*SessionDB) GetMessagesAsConversation

func (d *SessionDB) GetMessagesAsConversation(ctx context.Context, sessionID string, o ConversationOptions) ([]map[string]any, error)

Provider shaped conversation of a session, optionally merged across its lineage and repaired

func (*SessionDB) GetMeta

func (d *SessionDB) GetMeta(ctx context.Context, key string) (string, bool, error)

Value of a state_meta key, false when absent or NULL

func (SessionDB) GetNextTitleInLineage

func (t SessionDB) GetNextTitleInLineage(ctx context.Context, baseTitle string) (string, error)

Next title in a lineage read through the IOERR retrying reader

func (*SessionDB) GetRecentSessionModelRoute

func (d *SessionDB) GetRecentSessionModelRoute(ctx context.Context, sessionID string) (*jsonutil.Object, error)

Newest main loop model route of a session as one per call tuple, nil when none was recorded

func (*SessionDB) GetResumeConversations

func (d *SessionDB) GetResumeConversations(ctx context.Context, sessionID string) ([]map[string]any, []map[string]any, error)

Model history of the tip and display history of the whole lineage for a resume

func (*SessionDB) GetResumeMessageCount

func (d *SessionDB) GetResumeMessageCount(ctx context.Context, sessionID string, tipOnly bool) (int64, error)

Messages a resume of the session would reload

func (*SessionDB) GetSession

func (d *SessionDB) GetSession(ctx context.Context, sessionID string) (*jsonutil.Object, error)

Session row by id with resolved prompt columns after the queued token deltas land, nil when absent

func (*SessionDB) GetSessionAdmission

func (d *SessionDB) GetSessionAdmission(ctx context.Context, admissionID string) (*jsonutil.Object, error)

Admission by id, its retired tombstone when the live row is gone, nil when neither exists

func (SessionDB) GetSessionByTitle

func (t SessionDB) GetSessionByTitle(ctx context.Context, title string) (*jsonutil.Object, error)

Session dict of the exact title holder with its resolved system prompt, nil when none holds it

func (*SessionDB) GetSessionDeleteTargets

func (d *SessionDB) GetSessionDeleteTargets(ctx context.Context, sessionID string) ([]string, error)

Rows a delete of the session would remove, the session then its lineage then its delegate children

func (*SessionDB) GetSessionListRow

func (d *SessionDB) GetSessionListRow(ctx context.Context, sessionID string) (*jsonutil.Object, error)

Picker columns of one session without the prompt join or the token flush, nil when absent

func (*SessionDB) GetSessionMessagesAround

func (d *SessionDB) GetSessionMessagesAround(ctx context.Context, sessionID string, rowID int64, limit int) (*jsonutil.Object, error)

Display page of at most limit rows from an exact human prompt, nil when the row is no such prompt

func (*SessionDB) GetSessionModelConfigValue

func (d *SessionDB) GetSessionModelConfigValue(ctx context.Context, sessionID, key string, def any) (any, error)

One key of a session model_config through the tolerant parse, def when the session or key is absent

func (*SessionDB) GetSessionRichRow

func (d *SessionDB) GetSessionRichRow(ctx context.Context, sessionID string, compactRows bool) (*jsonutil.Object, error)

One session with the list enriched columns, nil when missing

func (*SessionDB) GetSessionTimeline

func (d *SessionDB) GetSessionTimeline(ctx context.Context, sessionID string, limit int, afterRowID int64) (*jsonutil.Object, error)

Chronological human prompts after a cursor, the cursor being the first physical row id of a logical turn

func (SessionDB) GetSessionTitle

func (t SessionDB) GetSessionTitle(ctx context.Context, sessionID string) (string, bool, error)

Title of a session, false when the session is missing or untitled

func (SessionDB) GetSessionTitleSource

func (t SessionDB) GetSessionTitleSource(ctx context.Context, sessionID string) (string, bool, error)

Provenance of a session title, false when the session is missing or untitled

func (*SessionDB) GetTelegramTopicBinding

func (d *SessionDB) GetTelegramTopicBinding(ctx context.Context, chatID, threadID, profileName string) (*jsonutil.Object, error)

Session binding row of one chat topic thread, nil when unbound

func (*SessionDB) GetTelegramTopicBindingBySession

func (d *SessionDB) GetTelegramTopicBindingBySession(ctx context.Context, sessionID string) (*jsonutil.Object, error)

Binding row that holds one session, nil when the session is unbound

func (*SessionDB) GuardedIDs

func (d *SessionDB) GuardedIDs(ctx context.Context, ids []string) (map[string]bool, error)

Ids of the given sessions under a live turn lease or compression lock, read on a reader connection

func (*SessionDB) HandoffHead

func (d *SessionDB) HandoffHead(ctx context.Context, sessionID string) (string, string, error)

Local owner and the row a handoff of the session moves, the receipt target's compression tip for a local conversation

func (*SessionDB) HasArchivedMessages

func (d *SessionDB) HasArchivedMessages(ctx context.Context, sessionID string) (bool, error)

Whether the session has any soft archived rows

func (*SessionDB) HasGatewayInputOwner

func (d *SessionDB) HasGatewayInputOwner(ctx context.Context, sessionID, owner string) (bool, error)

Whether an accepted user input row carries the gateway input owner marker

func (*SessionDB) HasMutationReceipt

func (d *SessionDB) HasMutationReceipt(ctx context.Context, principalID, sessionID, requestID string) (bool, error)

True when the principal's request already committed a mutation receipt against the session

func (*SessionDB) HasPendingHandoffs

func (d *SessionDB) HasPendingHandoffs(ctx context.Context) (bool, error)

True when any session waits in the pending handoff state

func (*SessionDB) HasPlatformMessageID

func (d *SessionDB) HasPlatformMessageID(ctx context.Context, sessionID, platformMessageID string) (bool, error)

Whether the platform message id was already persisted in the session

func (SessionDB) HasWriterConn

func (c SessionDB) HasWriterConn() bool

Whether the handle still holds its writer connection

func (*SessionDB) ImportForeignHistory

func (d *SessionDB) ImportForeignHistory(ctx context.Context, origin *jsonutil.Object, messages []any, title string, cwd, profile any) (*jsonutil.Object, error)

Adopts or mints a foreign snapshot in one transaction with its provenance, a duplicate click returning the first

func (*SessionDB) ImportLegacySessionAdmissions

func (d *SessionDB) ImportLegacySessionAdmissions(ctx context.Context, epoch int64, sourcePath, principalID string, writersDrained bool) (int64, error)

Imports a frozen legacy admissions snapshot once, the source file left as rollback evidence

func (*SessionDB) ImportMovedSession

func (d *SessionDB) ImportMovedSession(ctx context.Context, payload *SessionMovePayload, profileName string) (string, error)

Inserts a moved session into this store as profile's own, present when the id already exists else imported

func (*SessionDB) ImportSessions

func (d *SessionDB) ImportSessions(ctx context.Context, sessions []any) (*jsonutil.Object, error)

Imports exported sessions, skipping existing ids, refusing deleted ids by name and detaching foreign parents

func (*SessionDB) IncrementHygieneFailureStreak

func (d *SessionDB) IncrementHygieneFailureStreak(ctx context.Context, sessionKey string) (int, error)

Atomically bumps the hygiene failure streak of one chat and returns the new count

func (*SessionDB) InsertGatewayRoutingRowsIfAbsent

func (d *SessionDB) InsertGatewayRoutingRowsIfAbsent(ctx context.Context, rows []GatewayRoutingRow) (int64, error)

Adopts routing rows another store held for this one, an existing key keeping the row the gateway loads

func (*SessionDB) InsertSessionRowInTransaction

func (d *SessionDB) InsertSessionRowInTransaction(ctx context.Context, conn SQLiteConn, n NewSession) error

Keep existing constructor upsert on the caller's connection, refusing to recreate a retired session

func (*SessionDB) IsCompressionChildRow

func (d *SessionDB) IsCompressionChildRow(ctx context.Context, child *jsonutil.Object) (bool, error)

Whether a child row is a genuine compression continuation, for callers outside this package

func (*SessionDB) IsExplicitForkChild

func (d *SessionDB) IsExplicitForkChild(ctx context.Context, sessionID string) (bool, error)

Read only fork classification of a stored session, a missing row is no fork

func (*SessionDB) IsKanbanOwnedSession

func (d *SessionDB) IsKanbanOwnedSession(ctx context.Context, sessionID string) (bool, error)

Whether the session or any segment of its resume lineage belongs to the Kanban dispatcher

func (*SessionDB) IsReadOnly

func (d *SessionDB) IsReadOnly() bool

IsReadOnly reports whether the handle was opened read only

func (*SessionDB) IsTelegramSessionLinkedToTopic

func (d *SessionDB) IsTelegramSessionLinkedToTopic(ctx context.Context, sessionID string) (bool, error)

Whether the session is bound to any topic, false when the tables are absent

func (*SessionDB) IsTelegramTopicModeEnabled

func (d *SessionDB) IsTelegramTopicModeEnabled(ctx context.Context, chatID, userID, profileName string) (bool, error)

Whether topic mode is on for this chat and user under the profile namespace

func (*SessionDB) KeyProfilesForChat

func (d *SessionDB) KeyProfilesForChat(ctx context.Context, platform, chatID string) (map[string]bool, error)

Profiles whose keyed sessions hold the platform chat in this store

func (*SessionDB) LatestConversationBoundary

func (d *SessionDB) LatestConversationBoundary(ctx context.Context, sessionKey, source string) (int64, bool, error)

Conversation boundaries the peer has crossed, false when it never reset

func (*SessionDB) LatestConversationRole

func (d *SessionDB) LatestConversationRole(ctx context.Context, sessionID string) (string, error)

Role of the newest active conversation row skipping session_meta and system bookkeeping, empty when none

func (*SessionDB) LatestMessageRowID

func (d *SessionDB) LatestMessageRowID(ctx context.Context, sessionID, role string, offset int, requireText bool) (int64, bool, error)

Row id of the newest active role message offset steps back, false when none or the role is not user or assistant

func (*SessionDB) ListBackendHeartbeats

func (d *SessionDB) ListBackendHeartbeats(ctx context.Context) ([]*jsonutil.Object, error)

Snapshot of every backend heartbeat row, freshest first

func (*SessionDB) ListCronJobRuns

func (d *SessionDB) ListCronJobRuns(ctx context.Context, jobID string, limit int) ([]*jsonutil.Object, error)

Run sessions of one cron job newest first in the rich row shape, stamped with the job and execution ids

func (*SessionDB) ListCronJobRunsFrom

func (d *SessionDB) ListCronJobRunsFrom(ctx context.Context, jobID string, limit, offset int) ([]*jsonutil.Object, error)

Run sessions of one cron job from an offset, newest first in the rich row shape

func (*SessionDB) ListGatewayRoutingRows

func (d *SessionDB) ListGatewayRoutingRows(ctx context.Context) ([]*jsonutil.Object, error)

Every gateway routing row ordered by scope and key

func (*SessionDB) ListGatewaySessions

func (d *SessionDB) ListGatewaySessions(ctx context.Context, platform string, activeOnly bool) ([]*jsonutil.Object, error)

Newest row per routing key, filtered by source platform and open rows unless every row is asked for

func (*SessionDB) ListMetaPrefix

func (d *SessionDB) ListMetaPrefix(ctx context.Context, prefix string) ([]MetaEntry, error)

Key and value of every state_meta row whose key starts with the literal prefix

func (*SessionDB) ListNeverActiveKeyedSessions

func (d *SessionDB) ListNeverActiveKeyedSessions(ctx context.Context, olderThanDays float64) ([]*jsonutil.Object, error)

Keyed open rows older than the cutoff with no message, token, call, activity, title or keep intent

func (*SessionDB) ListPendingHandoffs

func (d *SessionDB) ListPendingHandoffs(ctx context.Context) []*jsonutil.Object

Every session pending handoff, oldest first, empty when the read fails

func (*SessionDB) ListPruneCandidates

func (d *SessionDB) ListPruneCandidates(ctx context.Context, olderThanDays *float64, source string, wholeLineages bool, f PruneFilters) ([]*jsonutil.Object, error)

Dry run of the sessions a matching prune or archive would touch, least recently active first

func (*SessionDB) ListRecentSessionsBounded

func (d *SessionDB) ListRecentSessionsBounded(ctx context.Context, o RecentSessionsBoundedOptions) ([]*jsonutil.Object, error)

Recent conversations resolved across compression lineage under a row ceiling and a cooperative deadline

func (SessionDB) ListRecentUserMessages

func (s SessionDB) ListRecentUserMessages(ctx context.Context, sessionID string, limit int, includeInactive bool) ([]*jsonutil.Object, error)

Most recent real user turns newest first as id, timestamp and an 80 character whitespace collapsed preview

func (*SessionDB) ListSessionAdmissions

func (d *SessionDB) ListSessionAdmissions(ctx context.Context, sessionID string, pendingOnly bool) ([]*jsonutil.Object, error)

Admissions of a session in FIFO order, only queued, started and unknown ones when pending only

func (*SessionDB) ListSessionsRich

func (d *SessionDB) ListSessionsRich(ctx context.Context, o ListSessionsRichOptions) ([]*jsonutil.Object, error)

Sessions with preview and last_active in one query, chain tip ordered when asked, pins back filled and tips projected

func (*SessionDB) ListSkillScaffoldedSessions

func (d *SessionDB) ListSkillScaffoldedSessions(ctx context.Context, limit int) ([]*jsonutil.Object, error)

Titled sessions whose first user turn was a skill invocation or an auto load scaffold, newest first

func (*SessionDB) ListTelegramTopicBindingsForChat

func (d *SessionDB) ListTelegramTopicBindingsForChat(ctx context.Context, chatID, profileName string) ([]*jsonutil.Object, error)

Every binding of one chat newest first, empty when the table is absent

func (*SessionDB) ListUnlinkedTelegramSessionsForUser

func (d *SessionDB) ListUnlinkedTelegramSessionsForUser(ctx context.Context, userID, profileName string, limit int) ([]*jsonutil.Object, error)

Rich rows of the user's telegram sessions bound to no topic, profile scoped once the bindings table exists

func (*SessionDB) LoadGatewayRoutingEntries

func (d *SessionDB) LoadGatewayRoutingEntries(ctx context.Context, scope string) (map[string]string, error)

Routing entries of one scope keyed by session key

func (*SessionDB) LocalReceipt

func (d *SessionDB) LocalReceipt(ctx context.Context, sessionID string) (*jsonutil.Object, error)

Stored creation receipt of a local session, storage_unavailable when it is missing or not a JSON object

func (*SessionDB) LocalSnapshot

func (d *SessionDB) LocalSnapshot(ctx context.Context, conn SQLiteConn, sessionID string) (*jsonutil.Object, error)

Receipt, physical target and target revision a prepared mutation is revalidated against

func (*SessionDB) LogicalSizeBytes

func (d *SessionDB) LogicalSizeBytes(ctx context.Context) (int64, bool)

Page count times page size, the main file size once the WAL is checkpointed in

func (*SessionDB) MaybeAutoArchive

func (d *SessionDB) MaybeAutoArchive(ctx context.Context, idleDays, minIntervalHours float64, excludePinned bool) AutoArchiveResult

Idempotent idle archive gated by the last_auto_archive meta stamp, never failing

func (*SessionDB) MaybeAutoPruneAndVacuum

func (d *SessionDB) MaybeAutoPruneAndVacuum(ctx context.Context, o AutoPruneOptions) AutoPruneResult

Prunes inactive sessions, closes stale open state owned rows and vacuums when due, never failing startup

func (*SessionDB) MessageCount

func (d *SessionDB) MessageCount(ctx context.Context, sessionID string) (int64, error)

Message count of one session, every session when the id is empty

func (*SessionDB) MutateRuntimeSession

func (d *SessionDB) MutateRuntimeSession(ctx context.Context, in RuntimeMutation) (*jsonutil.Object, error)

Commits a closed metadata edit and its retry receipt in one transaction, firing the delete event after

func (*SessionDB) MutateWorkerExecution

func (d *SessionDB) MutateWorkerExecution(ctx context.Context, in WorkerReceipt) (*jsonutil.Object, error)

One closed durable worker mutation and its receipt through the built in operation table

func (SessionDB) OptimizeFTS

func (s SessionDB) OptimizeFTS(ctx context.Context) (int, error)

Merges each present FTS5 index into one segment, a failing index logged, refused on a quarantined handle

func (SessionDB) OptimizeFTSStorage

func (s SessionDB) OptimizeFTSStorage(ctx context.Context, progressCB func(*jsonutil.Object), vacuum bool) (*jsonutil.Object, error)

Repairs an older FTS layout into the v23 shape to completion, reporting ok, reason, vacuumed and vacuum_skipped

func (*SessionDB) OwnProfileName

func (d *SessionDB) OwnProfileName() string

Profile name the rows this store writes carry, empty for the launch profile

func (*SessionDB) PatchSessionModelConfig

func (d *SessionDB) PatchSessionModelConfig(ctx context.Context, sessionID string, patch map[string]any) error

Merges the patch into model_config atomically, nil removing a key, a no op for an empty patch or missing row

func (SessionDB) Path

func (c SessionDB) Path() string

Path of the database file, empty for a handle with no backing store

func (*SessionDB) PlanUserTurnRewind

func (d *SessionDB) PlanUserTurnRewind(ctx context.Context, sessionID string, userOrdinal int, o RewindUserTurnOptions) (*RewindPlan, error)

Plans the rewind to just before a user turn, every read and check made and nothing written

func (*SessionDB) PolicyPicks

func (d *SessionDB) PolicyPicks(ctx context.Context, sessionID string) ([]string, error)

Sorted policy edits a session.mutate committed for the session, the durable record of the user's picks

func (*SessionDB) PrepareChatPick

func (d *SessionDB) PrepareChatPick(ctx context.Context, epoch int64, key, digest, sessionID string, params *jsonutil.Object) (*jsonutil.Object, error)

Stored receipt of an exact retry under the receipt key, else the fenced mount row under the row key

func (*SessionDB) PromoteToSessionReset

func (d *SessionDB) PromoteToSessionReset(ctx context.Context, sessionID, reason string) bool

Durably marks a reset boundary on a live row or a recoverably ended one, false when nothing was written

func (*SessionDB) PromptRefreshEpoch

func (d *SessionDB) PromptRefreshEpoch(ctx context.Context, sessionID string) (int, error)

Newest refresh epoch that applies to the session, zero when never requested

func (*SessionDB) PruneEmptyGhostSessions

func (d *SessionDB) PruneEmptyGhostSessions(ctx context.Context, sessionsDir string) (int, error)

Removes empty ended TUI ghost sessions older than a day with their transcript files

func (*SessionDB) PruneNeverActiveKeyedSessions

func (d *SessionDB) PruneNeverActiveKeyedSessions(ctx context.Context, o NeverActivePruneOptions) (int, int, int, error)

Deletes never active keyed rows outside live guards and the routing entries naming them

func (*SessionDB) PruneSessions

func (d *SessionDB) PruneSessions(ctx context.Context, o PruneSessionsOptions) (int, error)

Deletes ended sessions matching the filters with whole lineages, orphaning children and reclaiming expired tombstones

func (*SessionDB) PruneStaleHeartbeats

func (d *SessionDB) PruneStaleHeartbeats(ctx context.Context, maxAgeSeconds float64) ([]string, error)

Drops heartbeat rows older than the staleness window and returns the removed backend ids

func (*SessionDB) PublishCompressionChild

func (d *SessionDB) PublishCompressionChild(ctx context.Context, p CompressionChildPublish) error

Atomically closes a parent and publishes its durable compression child with the handoff and concurrent tail

func (*SessionDB) PublishSessionGitMetadata

func (d *SessionDB) PublishSessionGitMetadata(ctx context.Context, sessionID, cwd string, generation int64, gitBranch, gitRepoRoot string) (bool, error)

Publishes async git enrichment only while the cwd claim and its generation are still current

func (*SessionDB) PurgeProfileState

func (d *SessionDB) PurgeProfileState(profile string) (map[string]int, error)

Deletes exact profile identity from this state database, abandoning pending deliveries, returning per store counts

func (*SessionDB) PurgeStaleToolCallMarkers

func (d *SessionDB) PurgeStaleToolCallMarkers(ctx context.Context, dryRun, backup bool) (*jsonutil.Object, error)

Clears bare tool call marker content left by older sessions, with an optional VACUUM INTO snapshot first

func (*SessionDB) QueueTokenCounts

func (d *SessionDB) QueueTokenCounts(sessionID string, delta TokenCountDelta) error

Enqueues a token delta for the background writer, applying it inline once close stopped the writer

func (*SessionDB) ReadAll

func (d *SessionDB) ReadAll(ctx context.Context, query string, args ...any) ([]*jsonutil.Object, error)

Every row of one read only statement, the reader entry of wrappers outside the package

func (*SessionDB) ReadCtx

func (d *SessionDB) ReadCtx(ctx context.Context, fn func(conn SQLiteConn) error) error

Runs fn on a read connection of the store, the read ctx

func (SessionDB) RebuildFTS

func (s SessionDB) RebuildFTS(ctx context.Context) (int, error)

Rebuilds each present FTS5 index from messages under the cross process admission, zero when deferred

func (*SessionDB) ReclaimStaleRunningHandoffs

func (d *SessionDB) ReclaimStaleRunningHandoffs(ctx context.Context, reason string) []string

Fails every handoff stuck running from a dead gateway and returns their ids, logging a failed reclaim

func (*SessionDB) RecordAuxiliaryUsage

func (d *SessionDB) RecordAuxiliaryUsage(ctx context.Context, sessionID, task string, usage AuxiliaryUsage) error

Records an auxiliary call's usage per model, provider and task without touching the session totals

func (*SessionDB) RecordCompressionFailureCooldown

func (d *SessionDB) RecordCompressionFailureCooldown(sessionID string, cooldownUntil float64, errValue *string)

Persists the cooldown keeping any longer live deadline, the error always taking the latest diagnostic

func (*SessionDB) RecordCompressionFailureCooldownChecked

func (d *SessionDB) RecordCompressionFailureCooldownChecked(sessionID string, cooldownUntil float64, errValue *string) error

Cooldown record answering the raise a worker store can make

func (*SessionDB) RecordGatewaySessionPeer

func (d *SessionDB) RecordGatewaySessionPeer(ctx context.Context, sessionID string, p GatewayPeer) error

Persists the routing peer on the row or its compression lineage, inserting a missing row with full identity

func (*SessionDB) RecoverSessionInputs

func (d *SessionDB) RecoverSessionInputs(ctx context.Context, epoch int64) (int64, error)

Marks started work of earlier epochs unknown and never replays it, returning how many claims became unknown

func (*SessionDB) RefreshCompressionLock

func (d *SessionDB) RefreshCompressionLock(sessionID, holder string, ttlSeconds float64) bool

Extends the compression lock while holder still owns its row, even past the expiry

func (*SessionDB) RefreshCompressionLockChecked

func (d *SessionDB) RefreshCompressionLockChecked(sessionID, holder string, ttlSeconds float64) (bool, error)

Compression lock renewal answering the raise a worker store can make

func (*SessionDB) RefreshSessionTurnLease

func (d *SessionDB) RefreshSessionTurnLease(sessionID, holder string, ttlSeconds float64, patienceS *float64) (bool, error)

Extends the turn lease holder owns, false when it no longer owns it

func (*SessionDB) RegisterBackendHeartbeat

func (d *SessionDB) RegisterBackendHeartbeat(ctx context.Context, h BackendHeartbeat) error

Upserts the liveness row of one backend, the heartbeat defaulting to now and an empty id writing nothing

func (*SessionDB) RegisterWorkerExecution

func (d *SessionDB) RegisterWorkerExecution(ctx context.Context, in WorkerRegistration) (*jsonutil.Object, error)

Registers a worker for the session generation once, replaying an identical registration and refusing a busy lineage

func (*SessionDB) RehomeQueuedInputs

func (d *SessionDB) RehomeQueuedInputs(ctx context.Context, epoch int64, oldSessionID, newSessionID, principalPrefix string) ([]string, error)

Moves the old owner's queued prefix admissions onto the new session keeping ids and seq, returning them in FIFO order

func (*SessionDB) RekeyLegacyMainSessions

func (d *SessionDB) RekeyLegacyMainSessions(ctx context.Context, ids []string, profile string) (int64, error)

Rewrites legacy agent main keys and labels onto a profile for rows a standalone gateway wrote

func (*SessionDB) RekeyProfileState

func (d *SessionDB) RekeyProfileState(oldName, newName string) (map[string]int, error)

Atomically rewrites exact profile identity in this state database, returning per store counts

func (*SessionDB) RelabelSessionsToKeyProfile

func (d *SessionDB) RelabelSessionsToKeyProfile(ctx context.Context, ids []string) (int64, error)

Sets profile_name to the profile of each row's own key, the target re-derived inside the transaction

func (*SessionDB) RelabelTelegramTopicRows

func (d *SessionDB) RelabelTelegramTopicRows(ctx context.Context, rows []*jsonutil.Object) (*jsonutil.Object, error)

Stamps the key's profile onto default labelled topic bindings and lone mode rows, duplicates removed

func (*SessionDB) ReleaseCompressionLock

func (d *SessionDB) ReleaseCompressionLock(sessionID, holder string)

Releases the compression lock when holder owns it, idempotent once gone

func (*SessionDB) ReleaseCompressionLockChecked

func (d *SessionDB) ReleaseCompressionLockChecked(sessionID, holder string) error

Compression lock release answering the raise a worker store can make

func (*SessionDB) ReleaseHandedOffReceipts

func (d *SessionDB) ReleaseHandedOffReceipts(ctx context.Context, epoch int64, messaging func(source any) bool) ([]MovedReceipt, error)

Releases every local receipt whose current target a messaging lane holds, returning the released ones

func (*SessionDB) ReleaseSessionTurnLease

func (d *SessionDB) ReleaseSessionTurnLease(sessionID, holder string) error

Releases the turn lease holder owns on the conversation

func (*SessionDB) ReopenIfExplicitlyClosed

func (d *SessionDB) ReopenIfExplicitlyClosed(ctx context.Context, sessionID, provenance string, patienceS *float64) (*string, error)

Clears a stale explicit close stamp from a session a host proved still routed, returning the cleared reason

func (*SessionDB) ReopenOrphanedCompressionSession

func (d *SessionDB) ReopenOrphanedCompressionSession(ctx context.Context, sessionID string) (bool, error)

Reopens a compression parent only when no continuation was published and no live lease owns it

func (*SessionDB) ReopenSession

func (d *SessionDB) ReopenSession(ctx context.Context, sessionID string) error

Clears a session's end so it resumes, freezing markerless legacy reset children and dropping a sweep archive

func (*SessionDB) ReplaceGatewayRoutingEntries

func (d *SessionDB) ReplaceGatewayRoutingEntries(ctx context.Context, entries map[string]string, scope string) (map[string]bool, error)

Atomically replaces the routing index of one scope, returning the keys skipped as retired routes

func (*SessionDB) ReplaceMessages

func (d *SessionDB) ReplaceMessages(ctx context.Context, sessionID string, messages []map[string]any, opts ReplaceOptions) error

Atomically replaces a session's messages, deleting or soft archiving the dropped live rows

func (*SessionDB) ReplaceMessagesInTransaction

func (d *SessionDB) ReplaceMessagesInTransaction(ctx context.Context, conn SQLiteConn, sessionID string, messages []map[string]any, opts ReplaceOptions, expectedActiveIDs []int64) error

Replacement inside the caller transaction, refusing when the active ids moved off expectedActiveIDs

func (*SessionDB) RequestHandoff

func (d *SessionDB) RequestHandoff(ctx context.Context, sessionID, platform string) (bool, error)

Marks the session pending handoff to the platform, false while another handoff is in flight

func (*SessionDB) RequestPromptRefresh

func (d *SessionDB) RequestPromptRefresh(ctx context.Context, sessionID *string) (int, error)

Records a refresh request for every session or one session, returning the new epoch of the shared counter

func (*SessionDB) RequireIdle

func (d *SessionDB) RequireIdle(ctx context.Context, conn SQLiteConn, sessionIDs []string) error

Refuses any queued, started or unknown admission, any live worker and any live transcript lease

func (*SessionDB) RequireTargetAdvanceable

func (d *SessionDB) RequireTargetAdvanceable(ctx context.Context, conn SQLiteConn, sessionIDs []string) error

Fence for writes that publish a new physical target, refusing executing work and live transcript leases

func (*SessionDB) ResetHygieneFailureStreak

func (d *SessionDB) ResetHygieneFailureStreak(ctx context.Context, sessionKey string) error

Clears the persisted hygiene failure streak of one chat

func (*SessionDB) ResetLocalTarget

func (d *SessionDB) ResetLocalTarget(ctx context.Context, epoch int64, parentSessionID string, entry *jsonutil.Object) error

Publishes a reset child of a local session's live target and advances its receipt and route to it

func (*SessionDB) ResolveActiveRowID

func (d *SessionDB) ResolveActiveRowID(ctx context.Context, sessionID string, rowID int64) (int64, bool, error)

Active row still carrying a row's message, itself while active or its unique compaction clone

func (*SessionDB) ResolveResumeSessionID

func (d *SessionDB) ResolveResumeSessionID(sessionID string) (string, error)

Deepest descendant with messages along the newest plain continuation children, the input when a lookup fails

func (SessionDB) ResolveSessionByTitle

func (t SessionDB) ResolveSessionByTitle(ctx context.Context, title string) (string, bool, error)

Session id a title names, preferring the latest numbered continuation except for the canonical Bot Chat

func (*SessionDB) ResolveTitleConflictOnConn

func (d *SessionDB) ResolveTitleConflictOnConn(ctx context.Context, conn SQLiteConn, sessionID, title string) (string, bool, error)

Resolves a title collision inside an open write, the ValueError of a title another session holds

func (*SessionDB) ResolveUnknownSessionInput

func (d *SessionDB) ResolveUnknownSessionInput(ctx context.Context, epoch int64, admissionID string, generation int64,
	terminalWrite func(ctx context.Context, conn SQLiteConn, row *jsonutil.Object) error, captured *CapturedResult) (*jsonutil.Object, error)

Operator acknowledgement of an unknown turn, resolving it without requeue and committing a captured result of this epoch

func (*SessionDB) RestoreCompressionFailureCooldownRow

func (d *SessionDB) RestoreCompressionFailureCooldownRow(sessionID string, snapshot CompressionCooldownRow) error

Restores and verifies a cooldown snapshot, tolerating only a session row that vanished mid attempt

func (*SessionDB) RetagKanbanWorkerSessions

func (d *SessionDB) RetagKanbanWorkerSessions(ctx context.Context, workspacesRoot string) (int64, error)

Retags legacy kanban worker rows from cli to kanban by cwd under the workspaces root, once per root

func (*SessionDB) RetargetLocalAutomation

func (d *SessionDB) RetargetLocalAutomation(ctx context.Context, epoch int64, sessionID, principalID string, oldTargets []string, newTarget string) ([]string, error)

Points a local owner's queued automation rows naming a pre reset transcript at the new target, returning them in FIFO order

func (*SessionDB) RetireGatewayRoutes

func (d *SessionDB) RetireGatewayRoutes(ctx context.Context, sessionIDs []string, namespace string, expiring []string) error

Publishes routing fences for sessions retired in the namespace's profile and drops its routes naming them

func (*SessionDB) RetireUndrainedQueueRows

func (d *SessionDB) RetireUndrainedQueueRows(ctx context.Context, sessionID string) (int64, error)

Retires busy queue accept rows a restart left undrained, keeping them as inactive history

func (*SessionDB) RetiredSession

func (d *SessionDB) RetiredSession(ctx context.Context, sessionID string) (bool, error)

True when the session id was retired in this store, read through a pooled reader

func (SessionDB) RetryDeferredFTSRecovery

func (s SessionDB) RetryDeferredFTSRecovery(ctx context.Context) (bool, error)

Retries a deferred stale FTS rebuild from a periodic tick with doubling backoff and non blocking admission

func (*SessionDB) RetryTerminalAdmission

func (d *SessionDB) RetryTerminalAdmission(ctx context.Context, in SessionInput) (*jsonutil.Object, error)

Exact retry of an admission on a retired target, nil for a live one, refused for a retired miss or conflict

func (*SessionDB) RevertSteerInput

func (d *SessionDB) RevertSteerInput(ctx context.Context, epoch int64, admissionID string, generation int64) (bool, error)

Queues an undelivered transfer again in its original place, false when settlement already decided it

func (*SessionDB) RewindInTransaction

func (d *SessionDB) RewindInTransaction(ctx context.Context, conn SQLiteConn, sessionID string, targetMessageID int64, o RewindOptions) (*jsonutil.Object, []int64, any, *int64, error)

Transaction scoped rewind to the target row for a retry rewrite committed in the re-send admission

func (*SessionDB) RewindToMessage

func (d *SessionDB) RewindToMessage(ctx context.Context, sessionID string, targetMessageID int64, o RewindOptions) (*jsonutil.Object, error)

Soft deletes every active message from the target user row on and reports the rewound count, target and new head

func (*SessionDB) RewindUserTurn

func (d *SessionDB) RewindUserTurn(ctx context.Context, sessionID string, userOrdinal int, o RewindUserTurnOptions) (*RewindOutcome, error)

Soft deletes from a user turn onward, validated against the warm history, a composite carrier keeping its handoff

func (*SessionDB) RewritePrunedRows

func (d *SessionDB) RewritePrunedRows(ctx context.Context, sessionID string, changes []PruneChange, o PruneRewriteOptions) (int, error)

Rewrites each pruned row in place behind an archived twin, returning the rows rewritten

func (*SessionDB) RewrittenHeldRowIDs

func (d *SessionDB) RewrittenHeldRowIDs(ctx context.Context, sessionID string, held []map[string]any) ([]int64, error)

Ids among held dicts whose active row no longer holds the payload the dict holds

func (*SessionDB) RouteRetired

func (d *SessionDB) RouteRetired(ctx context.Context, sessionKey, entryJSON string) (bool, error)

True when a routing save or the legacy sessions json import must skip this entry

func (*SessionDB) SaveGatewayRoutingEntry

func (d *SessionDB) SaveGatewayRoutingEntry(ctx context.Context, sessionKey, entryJSON, scope string) error

Upserts one routing entry in the scope unless its route is retired

func (SessionDB) SearchMessages

func (s SessionDB) SearchMessages(ctx context.Context, query string, o SearchMessagesOptions) ([]*jsonutil.Object, error)

Searches messages through the routed indexes, logging the path of any search slower than search_slow_ms

func (*SessionDB) SearchSessions

func (d *SessionDB) SearchSessions(ctx context.Context, o SearchSessionsOptions) ([]*jsonutil.Object, error)

Sessions most recently active first with a computed last_active, scoped by source and workspace

func (*SessionDB) SearchSessionsByID

func (d *SessionDB) SearchSessionsByID(ctx context.Context, query string, o SearchSessionsByIDOptions) ([]*jsonutil.Object, error)

Surfaced sessions ranked exact, prefix then substring by id, an old compression root id resolving to its live tip

func (*SessionDB) SessionCount

func (d *SessionDB) SessionCount(ctx context.Context, o SessionCountOptions) (int, error)

Counts sessions under the list filters so a paired load more total matches the listing

func (*SessionDB) SessionCountBySource

func (d *SessionDB) SessionCountBySource(ctx context.Context, includeArchived, archivedOnly, excludeChildren bool) (*jsonutil.Object, error)

Session counts keyed by source in one grouped read, an empty source counted as cli

func (*SessionDB) SessionCountGE

func (d *SessionDB) SessionCountGE(ctx context.Context, n int) (bool, error)

Reports whether at least n sessions exist with archived rows included

func (*SessionDB) SessionLifecycleStatuses

func (d *SessionDB) SessionLifecycleStatuses(ctx context.Context, sessionIDs []string) (map[string]string, error)

Lifecycle status of each session from its last message row in one query, empty when it has none

func (*SessionDB) SessionModelConfig

func (d *SessionDB) SessionModelConfig(ctx context.Context, sessionID string) (map[string]any, error)

SessionModelConfig is a session's model_config with nested objects as plain maps, empty when the session or its config is missing

func (*SessionDB) SessionTurnLeaseExpiresAt

func (d *SessionDB) SessionTurnLeaseExpiresAt(sessionID, holder string) (*float64, error)

Expiry of the turn lease holder owns on the conversation, nil when it holds none

func (*SessionDB) SessionsWithModelConfigKey

func (d *SessionDB) SessionsWithModelConfigKey(ctx context.Context, key string) ([]string, error)

SessionsWithModelConfigKey lists the open sessions whose model_config holds a key

func (SessionDB) SetAutoTitle

func (t SessionDB) SetAutoTitle(ctx context.Context, sessionID, title, source string) (bool, error)

Sets a derived or llm title, false when a higher authority title holds the row

func (SessionDB) SetAutoTitleContext

func (t SessionDB) SetAutoTitleContext(ctx context.Context, sessionID, title, source string) (bool, error)

Provenance checked automatic title write of the titles port, reachable although the DB level setter shadows it

func (*SessionDB) SetExpiryFinalized

func (d *SessionDB) SetExpiryFinalized(ctx context.Context, sessionID string, finalized bool) error

Mirrors the SessionEntry expiry_finalized flag onto the row so it survives a lost sessions.json

func (*SessionDB) SetLatestMatchingMessageDisplayKind

func (d *SessionDB) SetLatestMatchingMessageDisplayKind(ctx context.Context, sessionID, role, content, displayKind string, displayMetadata any) (bool, error)

Stamps display kind and metadata on the newest active row matching role and content, false when none matched

func (*SessionDB) SetLatestUserAPIContent

func (d *SessionDB) SetLatestUserAPIContent(ctx context.Context, sessionID string, content any, apiContent string) (int64, error)

Backfills the api_content sidecar onto the newest active user row when its content still matches

func (*SessionDB) SetMessageAPIContent

func (d *SessionDB) SetMessageAPIContent(ctx context.Context, sessionID string, rowID int64, content any, apiContent string) (int64, error)

Backfills the api_content sidecar onto one known active user row whose content still matches

func (*SessionDB) SetMessageReaction

func (d *SessionDB) SetMessageReaction(ctx context.Context, sessionID string, rowID int64, emoji *string, author string) ([]any, bool, error)

Sets or clears an author reaction with tapback semantics, false for a row outside the visible lineage

func (*SessionDB) SetMeta

func (d *SessionDB) SetMeta(ctx context.Context, key, value string) error

Upserts a state_meta key in its own write transaction

func (*SessionDB) SetSessionArchived

func (d *SessionDB) SetSessionArchived(ctx context.Context, sessionID string, archived, notify bool) (bool, error)

Deliberately archives or unarchives a lineage, firing the delete hook on a real archive flip when notify holds

func (*SessionDB) SetSessionHidden

func (d *SessionDB) SetSessionHidden(ctx context.Context, sessionID string, hidden bool) (bool, error)

Hides or unhides a whole compression lineage from the default listing, leaving it resumable

func (*SessionDB) SetSessionModel

func (d *SessionDB) SetSessionModel(ctx context.Context, sessionID, model, provider, baseURL, apiMode string) error

SetSessionModel sets the model after a mid session switch and drops the browser lock, a provider writing the whole route in both shapes

func (*SessionDB) SetSessionPinned

func (d *SessionDB) SetSessionPinned(ctx context.Context, sessionID string, pinned bool) (bool, error)

Pins or unpins a whole compression lineage, a pin also unhiding it unless it is the canonical Bot Chat

func (*SessionDB) SetSessionRead

func (d *SessionDB) SetSessionRead(ctx context.Context, sessionID string, read bool) (bool, error)

Marks a whole compression lineage read at now or unread through a zero watermark

func (SessionDB) SetSessionTitle

func (t SessionDB) SetSessionTitle(ctx context.Context, sessionID, title string) (bool, error)

Sets a user provenance title, empty clearing it, ValueError on conflict or validation failure

func (SessionDB) SetSessionTitleSource

func (t SessionDB) SetSessionTitleSource(ctx context.Context, sessionID, source string) (bool, error)

Overwrites the provenance of a titled session without touching its text

func (*SessionDB) SetSessionYolo

func (d *SessionDB) SetSessionYolo(ctx context.Context, sessionID string, enabled bool) error

Persists the per session YOLO flag so it survives a resume, a no op without a session id or row

func (*SessionDB) SetTraceCallback

func (d *SessionDB) SetTraceCallback(fn func(sql string)) error

Installs fn as the statement trace of the writer and of every read connection handed out, nil removing it

func (*SessionDB) SetUserMessageContent

func (d *SessionDB) SetUserMessageContent(ctx context.Context, sessionID string, rowID int64, content any, displayMetadata any) (int64, error)

Rewrites the content of one active user row, replacing display metadata and clearing api_content when given

func (*SessionDB) SetWriteRetrySleep

func (d *SessionDB) SetWriteRetrySleep(fn func(deadline, patienceS float64) bool)

Installs the sleep every write of this store runs between lock retries, nil restoring the jittered sleep

func (*SessionDB) SettleSessionInput

func (d *SessionDB) SettleSessionInput(ctx context.Context, in SettleInput) (*jsonutil.Object, error)

Settles a started claim at its own epoch and generation, retiring its workers and storing its result

func (*SessionDB) SeverCrossedParents

func (d *SessionDB) SeverCrossedParents(ctx context.Context, ids []string) (int64, error)

Detaches children from a parent keyed under another profile while the crossing still holds

func (*SessionDB) SharedRegistryOwned

func (d *SessionDB) SharedRegistryOwned() bool

True while the process wide registry owns this handle

func (SessionDB) SleepBeforeWriteRetryJitter

func (c SessionDB) SleepBeforeWriteRetryJitter(deadline, patienceS float64) bool

Jittered write retry sleep that ignores any installed override

func (*SessionDB) StampLegacyCompressionChains

func (d *SessionDB) StampLegacyCompressionChains(ctx context.Context) (int64, error)

Stamps unset ancestors of chains compressed before write time stamping, returning the rows stamped

func (*SessionDB) SteerSessionInput

func (d *SessionDB) SteerSessionInput(ctx context.Context, epoch int64, admissionID string, generation int64) (*jsonutil.Object, bool, error)

Hands a queued admission to the running claim of the generation, true when this call committed the transfer

func (*SessionDB) SweepOrphanedSessions

func (d *SessionDB) SweepOrphanedSessions(ctx context.Context, o SweepOrphanedOptions) ([]string, error)

Ends idle open rows of the sources no live backend could own, sparing excluded and guarded rows

func (*SessionDB) TakeUnseenReactions

func (d *SessionDB) TakeUnseenReactions(ctx context.Context, sessionID, author string) ([]map[string]any, error)

Author reactions not yet surfaced, marked seen in the same write so each is announced once

func (*SessionDB) TerminalWorkerReceipt

func (d *SessionDB) TerminalWorkerReceipt(ctx context.Context, executionID, sessionID string, generation, sequence int64, adoptionSecret string, payloadDigest any) (any, error)

Retired producer evidence for one exact worker receipt, possession never reactivating the worker

func (*SessionDB) TouchSessionActivity

func (d *SessionDB) TouchSessionActivity(sessionID string, at *float64, description string, provenance ActivityProvenance) error

Stamps durable mid turn activity without ever moving the activity clock backwards

func (*SessionDB) TryAcquireCompressionLock

func (d *SessionDB) TryAcquireCompressionLock(sessionID, holder string, ttlSeconds float64) bool

Takes the compression lock, reclaiming expired or dead pid holders, false when a live holder owns it

func (*SessionDB) TryAcquireCompressionLockChecked

func (d *SessionDB) TryAcquireCompressionLockChecked(sessionID, holder string, ttlSeconds float64) (bool, error)

Compression lock acquire answering the raise a worker store can make, the canonical store never raising

func (*SessionDB) TryAcquireSessionTurnLease

func (d *SessionDB) TryAcquireSessionTurnLease(sessionID, holder string, ttlSeconds float64, patienceS *float64) (bool, error)

Claims the conversation turn lease once after sweeping long expired rows

func (*SessionDB) UnarchiveRecoverableSession

func (d *SessionDB) UnarchiveRecoverableSession(ctx context.Context, sessionID string) (bool, error)

Un-archives a session ended by a recoverable accident, true only when the lineage was un-archived

func (*SessionDB) UpdateSessionBillingRoute

func (d *SessionDB) UpdateSessionBillingRoute(ctx context.Context, sessionID, provider, baseURL string, billingMode *string) error

Sets the billing route unconditionally after the queued token deltas land

func (*SessionDB) UpdateSessionCwdClaim

func (d *SessionDB) UpdateSessionCwdClaim(ctx context.Context, sessionID, cwd, gitBranch, gitRepoRoot string, replaceGitMeta bool) (*int64, error)

Persists the cwd and claims a new git metadata generation, nil when the session is missing

func (*SessionDB) UpdateSessionMeta

func (d *SessionDB) UpdateSessionMeta(ctx context.Context, sessionID, modelConfigJSON string, model *string) error

Replaces model_config and, when given, the model after draining queued token deltas

func (*SessionDB) UpdateSessionModelConfig

func (d *SessionDB) UpdateSessionModelConfig(ctx context.Context, sessionID string, fn func(cfg map[string]any) bool) error

UpdateSessionModelConfig rewrites a session's model_config through fn in one write, fn answering false leaving it untouched and a missing row a no op

func (*SessionDB) UpdateSessionRuntimeLock

func (d *SessionDB) UpdateSessionRuntimeLock(ctx context.Context, sessionID string, lock RuntimeLock) error

Persists a Browser or API client runtime lock into model_config, lineage markers surviving

func (*SessionDB) UpdateSessionToolNames

func (d *SessionDB) UpdateSessionToolNames(sessionID string, pin any) error

Persists the JSON tools pin in the content addressed prompt table, the column holding its hash, nil clearing it

func (*SessionDB) UpdateSystemPrompt

func (d *SessionDB) UpdateSystemPrompt(ctx context.Context, sessionID string, systemPrompt *string) error

Stores the assembled system prompt snapshot through the content addressed prompt table, nil clearing it

func (*SessionDB) UpdateTokenCounts

func (d *SessionDB) UpdateTokenCounts(sessionID string, delta TokenCountDelta) error

Updates totals and route attribution after ensuring the session row exists with the caller's real source

func (*SessionDB) UsageTotals

func (d *SessionDB) UsageTotals(ctx context.Context, minMessageCount int, includeArchived bool) (tokens int64, costUSD float64, err error)

Tokens and spend of the store's root sessions in one scan, the billed figure preferred over the estimate

func (*SessionDB) Vacuum

func (d *SessionDB) Vacuum(ctx context.Context) (int, error)

Merges FTS segments then rewrites the file and truncates the WAL, refusing a quarantined handle first

func (*SessionDB) ValidateImportPayload

func (d *SessionDB) ValidateImportPayload(sessions []any) ([]*jsonutil.Object, []any, error)

Normalized import sessions and the problems that refuse them

func (*SessionDB) ValidateLegacyRow

func (d *SessionDB) ValidateLegacyRow(row *jsonutil.Object, subject any) error

Refuses as not_found every row but unrouted old local history of this profile

func (*SessionDB) ValidatePrepared

func (d *SessionDB) ValidatePrepared(ctx context.Context, conn SQLiteConn, sessionID string, prepared *jsonutil.Object) (*jsonutil.Object, error)

Current snapshot when it still equals the prepared one, revision_conflict when anything moved

func (*SessionDB) WorkerClaimOrigin

func (d *SessionDB) WorkerClaimOrigin(ctx context.Context, params *jsonutil.Object) (any, error)

Original parent a producer claim was bound to before physical rotation

func (*SessionDB) WorkerRetryTarget

func (d *SessionDB) WorkerRetryTarget(ctx context.Context, params *jsonutil.Object) (any, error)

Session the transport verifies a persist against, an old target accepted only for an exact publication replay

type SessionExportTooLargeError

type SessionExportTooLargeError struct {
	SessionID           string
	MessageCount, Limit int
}

A ValueError refusing an in memory JSON export past the export cap

func (*SessionExportTooLargeError) Error

func (*SessionExportTooLargeError) ErrorKind

func (e *SessionExportTooLargeError) ErrorKind() string

type SessionGoneEvent

type SessionGoneEvent struct {
	SessionIDs []string
	Reason     string
}

The on_session_delete event a committed runtime mutation owes its plugins

type SessionInput

type SessionInput struct {
	Epoch       int64
	PrincipalID string
	SessionID   string
	RequestID   string
	Payload     *jsonutil.Object
	Intent      string
	// Raises to refuse a new write, never seeing exact or terminal replays
	AuthorizeWrite func(ctx context.Context, conn SQLiteConn) error
	// Runs on the exact live replay inside the same transaction
	ReplayGuard func(ctx context.Context, conn SQLiteConn) error
}

One input to admit, the intent defaulting to queue and the guards running inside the owning write

type SessionLedgeredError

type SessionLedgeredError struct{ SessionID string }

A session with gateway admission or worker history, never movable between stores

func (*SessionLedgeredError) Error

func (e *SessionLedgeredError) Error() string

func (*SessionLedgeredError) ErrorKind

func (e *SessionLedgeredError) ErrorKind() string

type SessionLister

type SessionLister interface {
	ListSessionsRich(ctx context.Context, o ListSessionsRichOptions) ([]*jsonutil.Object, error)
}

Store surface an interactive session listing reads its rows from

type SessionListingQuery

type SessionListingQuery struct {
	Source                string
	SessionKey            string
	CurrentSessionID      string
	IncludeCurrentSession bool
	IncludeAllSources     bool
	IncludeUnnamed        bool
	SearchQuery           string
	Limit                 int
	ExcludeSources        []string
}

Arguments of an interactive session listing, a zero Limit meaning ten rows

type SessionMovePayload

type SessionMovePayload struct {
	Session      *jsonutil.Object
	SystemPrompt any
	ToolPin      any
	Messages     []*jsonutil.Object
	Usage        []*jsonutil.Object
}

Everything a target store needs to hold a session as its own, every message generation included

type SessionResumeTooLargeError

type SessionResumeTooLargeError struct {
	MessageCount, Limit int
	Scope               string
}

A ValueError refusing to reload a transcript longer than the resume cap

func (*SessionResumeTooLargeError) Error

func (*SessionResumeTooLargeError) ErrorKind

func (e *SessionResumeTooLargeError) ErrorKind() string

type SessionTurnLeaseLostError

type SessionTurnLeaseLostError struct{ Msg string }

Fences a transcript write whose turn lease holder lost the lease

func (*SessionTurnLeaseLostError) Error

func (e *SessionTurnLeaseLostError) Error() string

type SettleInput

type SettleInput struct {
	Epoch       int64
	AdmissionID string
	Generation  int64
	Outcome     string
	Result      *jsonutil.Object
	// Steer transfers bound to this claim, true when the text reached the claim's agent
	Transfers     map[string]bool
	TerminalWrite func(ctx context.Context, conn SQLiteConn, row *jsonutil.Object) error
}

Settlement of a started claim, the terminal write running in the same transaction

type StateDBCorruptError

type StateDBCorruptError struct {
	Msg   string
	Cause error
}

Quarantines a handle that observed structural corruption, a sqlite3.DatabaseError subclass

func (*StateDBCorruptError) Error

func (e *StateDBCorruptError) Error() string

func (*StateDBCorruptError) Unwrap

func (e *StateDBCorruptError) Unwrap() error

Cause the quarantine was raised from, carrying its SQLite result code

type StateDBDirError

type StateDBDirError struct {
	Dir string
	Err error
}

Reports a folder for the store that could not be created, the cause wrapped

func (*StateDBDirError) Error

func (e *StateDBDirError) Error() string

func (*StateDBDirError) Unwrap

func (e *StateDBDirError) Unwrap() error

type StateDBNewerSchemaError

type StateDBNewerSchemaError struct {
	Path   string
	Stored int64
}

Refuses a store whose schema version a newer icebath wrote, before anything rewrites it

func (*StateDBNewerSchemaError) Error

func (e *StateDBNewerSchemaError) Error() string

type StateDBReplacedError

type StateDBReplacedError struct{ Msg string }

Reports that the database path no longer names the file this handle opened

func (*StateDBReplacedError) Error

func (e *StateDBReplacedError) Error() string

type StorageFailure

type StorageFailure struct {
	Cause  string
	Code   string
	Gloss  string
	Action string
}

Plain language description of a persistence failure shared by every surface

func DescribeStorageCause

func DescribeStorageCause(ctx context.Context, cause string) StorageFailure

Description of a cause bucket a caller already classified, as a turn result carries it

func DescribeStorageFailure

func DescribeStorageFailure(ctx context.Context, excOrStr any) StorageFailure

Describes a persistence failure with its cause bucket, stable code, gloss and profile pinned action

type StoreUnavailableError

type StoreUnavailableError struct {
	Path  string
	Cause error
	// contains filtered or unexported fields
}

Session store that would not open, its text naming the store, the cause and what the user does

func NewStoreUnavailableError

func NewStoreUnavailableError(ctx context.Context, path string, cause error) *StoreUnavailableError

Open failure of the store at path described with the storage failure gloss, details and remedy

func (*StoreUnavailableError) Error

func (e *StoreUnavailableError) Error() string

func (*StoreUnavailableError) Unwrap

func (e *StoreUnavailableError) Unwrap() error

type SweepOrphanedOptions

type SweepOrphanedOptions struct {
	MaxIdleSeconds                 float64
	Sources                        []string
	ExcludeIDs                     []string
	ExcludePinned                  bool
	HeartbeatStalenessSeconds      *float64
	HeartbeatOwnershipGraceSeconds *float64
	RespectGatewayHeartbeats       bool
}

Orphan sweep scope, nil heartbeat windows meaning the defaults derived from the idle window

func NewSweepOrphanedOptions

func NewSweepOrphanedOptions(maxIdleSeconds float64) SweepOrphanedOptions

Sweep over tui, legacy client history and subagent rows honouring gateway heartbeats

type TableHistory

type TableHistory struct {
	Base   []string
	Events []SchemaEvent
}

Declared order a table first shipped with and every later edit in replay order

type TelegramTopicBinding

type TelegramTopicBinding struct {
	ChatID, ThreadID, UserID, SessionKey, SessionID string
	ManagedMode, ProfileName                        string
}

type TelegramTopicMode

type TelegramTopicMode struct {
	ChatID, UserID, ProfileName string
	HasTopicsEnabled            *bool
	AllowsUsersToCreateTopics   *bool
}

type TitleInUseError

type TitleInUseError struct {
	Title     string
	SessionID string
}

Error of a title another session holds

func (*TitleInUseError) Error

func (e *TitleInUseError) Error() string

type TokenCountDelta

type TokenCountDelta struct {
	InputTokens      int64
	OutputTokens     int64
	CacheReadTokens  int64
	CacheWriteTokens int64
	ReasoningTokens  int64
	Model            *string
	EstimatedCostUSD *float64
	ActualCostUSD    *float64
	CostStatus       *string
	CostSource       *string
	PricingVersion   *string
	BillingProvider  *string
	BillingBaseURL   *string
	BillingMode      *string
	APICallCount     int
	Absolute         bool
	Source           *string
	Task             string
}

One update_token_counts call, nil pointers are the Python None keywords

type ToolCall

type ToolCall struct {
	ID       string           `json:"id"`
	Type     string           `json:"type,omitempty"`
	Function ToolCallFunction `json:"function"`
	// Dict keys the struct has no field for, kept for lossless dict round trips
	Extra map[string]any `json:"-"`
	// Dict key order of the source when it differs from the order the agent builds tool calls in
	Keys []string `json:"-"`
}

func ToolCallFromDict

func ToolCallFromDict(d map[string]any) ToolCall

Tool call struct from a dict entry, unfit keys kept in Extra

type ToolCallFunction

type ToolCallFunction struct {
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
	// Dict keys the struct has no field for, kept for lossless dict round trips
	Extra map[string]any `json:"-"`
	// Dict key order of the source when it differs from name, arguments, thought_signature
	Keys []string `json:"-"`
}

Function part of a tool call

type ToolCallOwner

type ToolCallOwner struct {
	Named map[string]bool
	Index map[string]string
}

Memo of one assistant dict named variants and uid index across a flush

type TopicAlreadyLinkedError

type TopicAlreadyLinkedError struct{}

Binding refused because the session already belongs to another Telegram topic, a ValueError to class readers

func (*TopicAlreadyLinkedError) Error

func (*TopicAlreadyLinkedError) ErrorKind

func (*TopicAlreadyLinkedError) ErrorKind() string

type TrackedConn

type TrackedConn struct {
	SQLiteConn
	// contains filtered or unexported fields
}

Connection that releases its live registry entry exactly once, only after its descriptor is closed

func ConnectTracked

func ConnectTracked(path string, opts ...TrackedOption) (*TrackedConn, error)

Opens a connection and registers it for the lifetime of its descriptor, open and registration under one lock

func ConnectTrackedDB

func ConnectTrackedDB(path string, opts ...TrackedOption) (*TrackedConn, error)

Opens a connection tracked for its descriptor life through the patchable session store connector

func (*TrackedConn) Close

func (c *TrackedConn) Close() error

Closes the connection and untracks its path together under the lifecycle lock, keeping the entry when close fails

type TrackedOption

type TrackedOption func(*trackedOptions)

Option of ConnectTracked

func WithConnectFn

func WithConnectFn(fn SQLiteOpener) TrackedOption

Opens through fn instead of ConnectSQLite

func WithTimeout

func WithTimeout(seconds float64) TrackedOption

Busy timeout in seconds handed to the opener, five when unset

func WithTrackingPath

func WithTrackingPath(path string) TrackedOption

Tracks the connection under this filesystem path instead of the one SQLite reports

func WithURI

func WithURI() TrackedOption

Parses a database name starting with file as an SQLite URI

type TranscriptRevision

type TranscriptRevision struct {
	SessionIDs             []string
	Count, MaxID, Revision int64
}

Revision tuple of a transcript, its lineage ids, active count, newest id and summed revisions

type TurnLeaseTry

type TurnLeaseTry func(sessionID, holder string, ttlSeconds float64, patienceS *float64) (bool, error)

One turn lease acquire attempt with its write patience, the try_acquire_session_turn_lease of a store

type TurnLeaseWait

type TurnLeaseWait struct {
	TTLSeconds                float64
	WaitSeconds               float64
	PollIntervalSeconds       float64
	WaitNoticeIntervalSeconds float64
	AcquirePatienceS          float64
	OnWait                    func(waited float64) error
	ShouldAbort               func() (bool, error)
	OnContended               func() error
}

Waiting policy of a blocking turn lease acquire, callbacks returning errors that are logged and ignored

func NewTurnLeaseWait

func NewTurnLeaseWait() TurnLeaseWait

Waiting policy with the acquire_session_turn_lease defaults

type Tx

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

Statements of one write transaction on the writer connection

func (*Tx) Exec

func (t *Tx) Exec(query string, args ...any) (sql.Result, error)

Runs a statement in the transaction

func (*Tx) Query

func (t *Tx) Query(query string, args ...any) (*sql.Rows, error)

Runs a query in the transaction

func (*Tx) QueryRow

func (t *Tx) QueryRow(query string, args ...any) *sql.Row

Runs a single row query in the transaction

type UntrackableConnectionError

type UntrackableConnectionError struct {
	Path    string
	Factory string
	Cause   error
}

Reports a connection to a probe-able database that cannot carry its tracking entry, refused rather than returned untracked

func (*UntrackableConnectionError) Error

func (*UntrackableConnectionError) Unwrap

func (e *UntrackableConnectionError) Unwrap() error

type VersionTuple

type VersionTuple [3]*big.Int

Python or SQLite version as three unbounded integers, the shape _version_tuple returns

func NewVersionTuple

func NewVersionTuple(parts ...int64) VersionTuple

Version tuple of plain integers, missing parts zero and extra parts dropped

func (VersionTuple) Cmp

func (v VersionTuple) Cmp(o VersionTuple) int

Lexicographic comparison of two version tuples

type WALUnsupportedError

type WALUnsupportedError struct {
	Msg   string
	Cause error
}

Raised under require WAL when the filesystem cannot provide WAL or the on disk mode cannot be verified

func (*WALUnsupportedError) As

func (e *WALUnsupportedError) As(target any) bool

Lets the error match sqlite3.OperationalError so database init handlers still catch it

func (*WALUnsupportedError) Error

func (e *WALUnsupportedError) Error() string

type WorkerHandler

type WorkerHandler func(d *SessionDB, ctx context.Context, conn SQLiteConn, sessionID string, payload *jsonutil.Object) (*jsonutil.Object, error)

Handler of one worker receipt operation, run on the receipt transaction connection without committing

type WorkerReceipt

type WorkerReceipt struct {
	Epoch       int64
	ExecutionID string
	SessionID   string
	Generation  int64
	Sequence    int64
	Operation   string
	Payload     any
}

Keyword arguments of one worker receipt

type WorkerRegistration

type WorkerRegistration struct {
	Epoch          int64
	ExecutionID    string
	SessionID      string
	Generation     int64
	Kind           string
	AdoptionSecret string
	RequireIdle    bool
}

Keyword arguments of register_worker_execution

Source Files

Jump to

Keyboard shortcuts

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