store

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 22 Imported by: 0 modules, 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

Overview

Package store persists the accordion ledger in SQLite (spec §5, §10). It knows nothing about trigger policy or validation rules: those live in kernel. Its job is to apply a plan atomically and keep the schema invariants (see invariants.go) true inside every write transaction.

Index

Constants

This section is empty.

Variables

View Source
var ErrContentMismatch = errors.New("store: content does not match its hash")

ErrContentMismatch reports a contents row whose stored bytes do not match its key: the raw data, decoded as AppendMessage stores it, must hash to hash and have exactly size_bytes bytes. A backup or dump that breaks this is refused before any row is written.

View Source
var ErrEmptyQuery = errors.New("search: query has no searchable terms")

ErrEmptyQuery reports a query with no word characters: nothing to match.

View Source
var ErrProjectNotFound = errors.New("store: project not found")

ErrProjectNotFound reports a project ID with no row in projects.

View Source
var ErrRestoreConflict = errors.New("store: restore conflicts with existing data")

ErrRestoreConflict reports that a restore would duplicate or overwrite data already in the destination. RestoreDumps writes nothing when it returns it.

View Source
var ErrSessionNotFound = errors.New("store: session not found")

ErrSessionNotFound reports a session ID with no row in sessions.

Functions

func SchemaVersion

func SchemaVersion() int

SchemaVersion is the newest schema this build reads and writes.

Types

type CacheCall

type CacheCall struct {
	InputTokens   int
	CachedTokens  int
	EstTokens     int
	AfterCompress bool
}

CacheCall is one row of cache_ledger (spec §9.4).

type CacheRow

type CacheRow struct {
	CallSeq int64
	At      int64
	CacheCall
}

CacheRow is one stored cache_ledger row: the upstream sample of one call.

type CacheTotals

type CacheTotals struct {
	Calls         int64
	InputTokens   int64
	CachedTokens  int64
	AfterCompress int64 // calls that were the first after a fold
}

CacheTotals sums the cache ledger of a session (spec §9.4): the measured cache cost of the upstream calls.

type CompressPlan

type CompressPlan struct {
	NewBlocks    []NewBlock
	Deactivate   []string          // active blocks consumed by NewBlocks
	ParentOf     map[string]string // consumed block -> new parent block
	CloseIntents []int64           // open intents completed by NewBlocks (§11.3)
	TokensAfter  int               // low-water mark after the fold
	Now          int64
}

CompressPlan is the already-validated output of kernel validation (spec §10.1).

type EventRow

type EventRow struct {
	Seq     int64
	At      int64
	Type    string
	Payload json.RawMessage
}

EventRow is one row of the events log (spec §5.2). Payload is the stored JSON.

type FileInfo

type FileInfo struct {
	SchemaVersion int
	Projects      []FileProject
	Sessions      []string
}

FileInfo describes a database file that passed InspectFile.

func InspectFile

func InspectFile(ctx context.Context, path string) (FileInfo, error)

InspectFile validates a database file without migrating or otherwise changing it. It checks the SQLite magic, refuses a schema newer than this build, requires the acd-ctx tables, runs PRAGMA integrity_check, and runs the invariants (I1-I3, I6, I7) for every session. The file is opened on a plain handle; callers pass a scratch copy, never the user's file.

type FileProject

type FileProject struct {
	ID       string
	RootPath string
	Storage  string
}

FileProject is one row of projects in a database file.

type ImportTarget

type ImportTarget struct {
	ProjectID string // ID the sessions belong to at the destination
	RootPath  string
	Storage   string // "global" | "local"
}

ImportTarget says how an imported project is registered in the destination.

type NewBlock

type NewBlock struct {
	ID        string
	Tier      int
	Topic     string
	Summary   string
	StartSeq  int64
	EndSeq    int64
	SrcTokens int
	SumTokens int
	Sources   []string // consumed blocks (T2/T3 only)
}

NewBlock is one block produced by a compress call.

type NewMessage

type NewMessage struct {
	Role       kernel.Role
	Kind       kernel.Kind
	ToolName   string
	ToolCallID string
	Text       string
	Tokens     int
}

NewMessage is a ledger entry before it receives seq and ref.

type ProjectDump

type ProjectDump struct {
	ProjectID string
	Tables    []TableRows
}

ProjectDump is every row that belongs to one project, grouped by table in foreign-key order (see dumpTables).

func (ProjectDump) SessionIDs

func (d ProjectDump) SessionIDs() []string

SessionIDs lists the sessions in the dump.

type ProjectInfo

type ProjectInfo struct {
	ID         string
	RootPath   string
	Storage    string // "global" | "local"
	CreatedAt  int64
	LastSeenAt int64
	Sessions   int64
	// Bytes is the raw size of the distinct contents the project's messages
	// reference. Contents are shared across projects, so the sum over all
	// projects can exceed the database size.
	Bytes int64
}

ProjectInfo is one row of projects with its aggregates (spec §18.7).

type PurgeOpts

type PurgeOpts struct {
	DryRun bool
}

PurgeOpts selects a dry run. A dry run returns the Report of the purge that would happen and changes nothing.

type Report

type Report struct {
	Projects   int64
	Sessions   int64
	Messages   int64
	Blocks     int64
	Events     int64
	Contents   int64
	BytesFreed int64
}

Report counts what a purge removed, or would remove in a dry run. Contents are shared by content hash, so only contents that no remaining message refers to are counted. BytesFreed is the raw size of those contents.

type RestoreItem

type RestoreItem struct {
	Dump   ProjectDump
	Target ImportTarget
}

RestoreItem is one project of a restore: its rows and the identity they take in the destination.

type RestoreReport

type RestoreReport struct {
	Purged    map[string]int64
	Written   map[string]int64
	Conflicts []string
}

RestoreReport counts the rows a restore removed and wrote. Conflicts lists every reason the restore was refused, when it was.

type Row

type Row map[string]any

Row is one table row of a dump, keyed by column name. Values are the driver's own types (int64, string, []byte, nil), so BLOBs such as zstd contents are copied byte for byte.

type SearchHit

type SearchHit struct {
	SessionID string
	Kind      string // "message" or "block"
	Key       string // message ref (m00042) or block id (b17)
	Snippet   string // the matching body with the hits in [brackets]
	Score     float64
}

SearchHit is one matching message or block.

type Session

type Session struct {
	ID           string
	ProjectID    string
	Model        string
	ContextLimit int
	Mode         string // proxy | plugin | library
	Integration  string
}

Session describes a row of sessions (spec §5.2).

type SessionRow

type SessionRow struct {
	ID           string
	ProjectID    string
	Model        string
	ContextLimit int
	Mode         string
	Integration  string
}

SessionRow is the stored description of one session (spec §5.2).

type Store

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

Store is a single-writer handle over one SQLite database.

func Open

func Open(path string) (*Store, error)

Open opens (or creates) the database at path, applies pragmas and migrates. Use "file::memory:?mode=memory&cache=shared" style DSNs for tests.

func (*Store) AddIntent

func (s *Store) AddIntent(ctx context.Context, sid string, originSeq int64, text string) (int64, error)

AddIntent appends an open intent originating at originSeq and returns its id.

func (*Store) AppendEvent

func (s *Store) AppendEvent(ctx context.Context, sid, typ string, payload any) error

AppendEvent writes one row to the append-only events log.

func (*Store) AppendMessage

func (s *Store) AppendMessage(ctx context.Context, sid string, m NewMessage) (kernel.Message, error)

AppendMessage stores the content (deduplicated by sha256) and appends the message at the next seq. Returns the ledger view with seq and ref filled.

func (*Store) AppendMessageWithIntent

func (s *Store) AppendMessageWithIntent(ctx context.Context, sid string, m NewMessage) (kernel.Message, error)

AppendMessageWithIntent is AppendMessage that also opens an intent (spec §11.3) when m is a user text message with a non-empty kernel.IntentText (harness text such as a <system-reminder> alone opens none). The message and its intent commit together, so a crash cannot leave a user turn without its intent.

func (*Store) ApplyCompress

func (s *Store) ApplyCompress(ctx context.Context, sid string, p CompressPlan) error

ApplyCompress writes a validated plan in one transaction (spec §10.3). Nothing is deleted: messages stay, only blocks.active changes. Invariants are checked before commit; a violation rolls everything back.

func (*Store) ApplyDecompress

func (s *Store) ApplyDecompress(ctx context.Context, sid string, p kernel.DecompressPlan) error

ApplyDecompress writes a decompress plan in one transaction (spec §13.1, mode "context"). The target block becomes inactive with no parent, and each direct source becomes active again with parent_block cleared. Nothing is deleted. Every row update must match exactly one row, so a plan built from a stale snapshot fails instead of corrupting the block set. Invariants are checked before commit.

func (*Store) CacheTotals

func (s *Store) CacheTotals(ctx context.Context, sid string) (CacheTotals, error)

CacheTotals returns the sums of the session's cache_ledger rows.

func (*Store) CheckInvariants

func (s *Store) CheckInvariants(ctx context.Context, sid string) error

CheckInvariants runs I1, I2, I3, I6, I7 for a session against the committed state.

func (*Store) ClearForcedNudge

func (s *Store) ClearForcedNudge(ctx context.Context, sid string) error

ClearForcedNudge drops the forced flag of a session. NudgePending is left as it is: the nudge it caused is still unanswered until a compress.

func (*Store) Close

func (s *Store) Close() error

Close releases the database and codecs.

func (*Store) CloseIntent

func (s *Store) CloseIntent(ctx context.Context, sid string, id int64, status string, closedSeq int64) error

CloseIntent moves an open intent to done or superseded.

func (*Store) CreateSession

func (s *Store) CreateSession(ctx context.Context, sess Session) error

CreateSession inserts a session and its zeroed trigger_state row in one tx.

func (*Store) EnsureProject

func (s *Store) EnsureProject(ctx context.Context, id, root, storage string, now int64) error

EnsureProject inserts the project or refreshes its root and last_seen_at.

func (*Store) Epoch

func (s *Store) Epoch(ctx context.Context) (int64, error)

Epoch returns the store epoch. Every purge increments it in its own transaction. A process that caches session state compares it on each request and drops that state when it has changed.

func (*Store) ExportProject

func (s *Store) ExportProject(ctx context.Context, id string) (ProjectDump, error)

ExportProject reads every row of a project in one read transaction. It returns ErrProjectNotFound when the project does not exist.

func (*Store) ForcedNudge

func (s *Store) ForcedNudge(ctx context.Context, sid string) (bool, error)

ForcedNudge reports whether a forced nudge is waiting for the next Plan.

func (*Store) GetProject

func (s *Store) GetProject(ctx context.Context, id string) (ProjectInfo, error)

GetProject returns one project, or ErrProjectNotFound.

func (*Store) GetSession

func (s *Store) GetSession(ctx context.Context, sid string) (SessionRow, error)

GetSession reads the row of session sid. sql.ErrNoRows (wrapped) means no such session.

func (*Store) GetTrigger

func (s *Store) GetTrigger(ctx context.Context, sid string) (kernel.TriggerState, error)

GetTrigger reads the single trigger_state row of a session.

func (*Store) ImportProject

func (s *Store) ImportProject(ctx context.Context, d ProjectDump, dst ImportTarget) (map[string]int64, error)

ImportProject copies a dump into s in one transaction. Session IDs and message refs are kept, so the copy is identical apart from the project ID and the storage mode. Every imported session must pass checkInvariants before commit; any failure rolls the whole copy back. A session ID already present at the destination is an error. It returns the rows written per table.

func (*Store) ListCacheLedger

func (s *Store) ListCacheLedger(ctx context.Context, sid string, limit int) ([]CacheRow, error)

ListCacheLedger returns the last limit rows of the session's cache ledger in call order, oldest first. A limit <= 0 returns every row. The proxy replays the rows to rebuild the token calibration after a restart (spec §15).

func (*Store) ListEvents

func (s *Store) ListEvents(ctx context.Context, sid string, limit int) ([]EventRow, error)

ListEvents returns the last limit events of a session in event order, oldest first. A limit <= 0 returns every event.

func (*Store) ListProjects

func (s *Store) ListProjects(ctx context.Context) ([]ProjectInfo, error)

ListProjects returns every project, most recently seen first.

func (*Store) ListSessionIDs

func (s *Store) ListSessionIDs(ctx context.Context, projectID string) ([]string, error)

ListSessionIDs returns the session ids of a project without loading their rows, for read-only health checks.

func (*Store) MoveProject

func (s *Store) MoveProject(ctx context.Context, id, newRoot string) error

MoveProject points an existing project at a new root path. Its ID does not change (spec §18.2). It fails with ErrProjectNotFound for an unknown ID and with a unique-index error when another project already owns newRoot.

func (*Store) ProjectIDByRoot

func (s *Store) ProjectIDByRoot(ctx context.Context, root string) (string, error)

ProjectIDByRoot returns the ID of the project registered at root, or ErrProjectNotFound. After MoveProject the ID no longer equals the hash of the root, so callers look it up here before deriving one.

func (*Store) PurgeAll

func (s *Store) PurgeAll(ctx context.Context, o PurgeOpts) (Report, error)

PurgeAll removes every project with all of its derived data, then every content row that no message refers to. The database is left empty of conversations, and the schema and the store epoch remain.

func (*Store) PurgeOlderThan

func (s *Store) PurgeOlderThan(ctx context.Context, projectID string, cutoff time.Time, o PurgeOpts) (Report, error)

PurgeOlderThan removes whole sessions whose last activity is before cutoff. projectID "" covers every project. A session is never removed partly, so the sessions that remain keep their ledgers (invariants I1 to I7). Projects are kept, even when they lose all their sessions.

func (*Store) PurgeProject

func (s *Store) PurgeProject(ctx context.Context, id string) (map[string]int64, error)

PurgeProject deletes all data of one project in a single transaction and returns the number of rows removed per table. Contents are content-addressed and shared, so a content row goes only when no message refers to it any more.

func (*Store) PurgeProjectReport

func (s *Store) PurgeProjectReport(ctx context.Context, id string, o PurgeOpts) (Report, error)

PurgeProjectReport is PurgeProject with a Report and the dry-run option.

func (*Store) PurgeSession

func (s *Store) PurgeSession(ctx context.Context, sid string, o PurgeOpts) (Report, error)

PurgeSession removes one session completely: its messages, blocks and lineage, intents, trigger state, events, cache ledger and search rows, and the contents that only it referred to. The project stays. It returns ErrSessionNotFound for an unknown ID.

func (*Store) RecordCache

func (s *Store) RecordCache(ctx context.Context, sid string, c CacheCall) error

RecordCache appends one cache_ledger row (spec §9.4).

func (*Store) RequestNudge

func (s *Store) RequestNudge(ctx context.Context, sid string, payload any) error

RequestNudge marks a session for forced compaction (spec §19.4 compact). It raises nudge_pending and nudge_forced together and logs a "compact" event with payload, in one transaction. The next Plan of the session nudges, and the flag is cleared by that Plan.

func (*Store) RestoreDumps

func (s *Store) RestoreDumps(ctx context.Context, items []RestoreItem, replace, dryRun bool) (RestoreReport, error)

RestoreDumps applies items in one transaction, so either every project lands or none does. Merge (replace=false) refuses when a project ID, a session ID or a root path already belongs to another project. Replace first purges each target project ID that exists, using the purge core of purge.go, and then imports. dryRun runs the whole plan and rolls back, so the report shows what would happen. Every imported session must pass the invariants before commit.

func (*Store) ScopeSessionIDs

func (s *Store) ScopeSessionIDs(ctx context.Context, projectID string, olderThan time.Time) ([]string, error)

ScopeSessionIDs lists the sessions that PurgeOlderThan with the same arguments would remove, in ID order. projectID "" covers every project, and a zero olderThan applies no age filter.

func (*Store) Seal

func (s *Store) Seal(ctx context.Context) error

Seal folds the write-ahead log into the main file and switches the database back to rollback-journal mode, so the file alone holds all of its data. It is meant for scratch copies that are about to be moved.

func (*Store) Search

func (s *Store) Search(ctx context.Context, sid, query string, limit int) ([]SearchHit, error)

Search runs a full-text query over the messages and block summaries of one session. Hits are ordered by bm25 relevance, best first.

func (*Store) SearchProject

func (s *Store) SearchProject(ctx context.Context, projectID, query string, limit int) ([]SearchHit, error)

SearchProject is Search over every session of a project.

func (*Store) SessionWindow

func (s *Store) SessionWindow(ctx context.Context, sid string) (model string, limit int, err error)

SessionWindow returns the model a session was created with and the context window stored for it. sql.ErrNoRows (wrapped) means no such session.

func (*Store) SetContextLimit

func (s *Store) SetContextLimit(ctx context.Context, sid string, limit int) error

SetContextLimit replaces the stored context window of session sid. It writes only that column, so the ledger, blocks and trigger state are left as they are.

func (*Store) SetTrigger

func (s *Store) SetTrigger(ctx context.Context, sid string, t kernel.TriggerState) error

SetTrigger overwrites the trigger_state row of a session.

func (*Store) Snapshot

func (s *Store) Snapshot(ctx context.Context, sid string) (kernel.Snapshot, error)

Snapshot loads the full ledger, blocks, intents and trigger state of a session.

func (*Store) Vacuum

func (s *Store) Vacuum(ctx context.Context) error

Vacuum folds the write-ahead log into the main file, rebuilds the database file to return free pages to the OS, and merges the full-text index. It is not part of a purge: call it after one.

func (*Store) VacuumInto

func (s *Store) VacuumInto(ctx context.Context, path string) error

VacuumInto writes a consistent copy of the database to path. It runs inside a read transaction, so a writer on another handle can keep committing while the copy is made. path must not exist.

type TableRows

type TableRows struct {
	Table string
	Rows  []Row
}

TableRows holds the rows of one table in a dump.

Jump to

Keyboard shortcuts

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