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 ¶
- Variables
- func SchemaVersion() int
- type CacheCall
- type CacheRow
- type CacheTotals
- type CompressPlan
- type EventRow
- type FileInfo
- type FileProject
- type ImportTarget
- type NewBlock
- type NewMessage
- type ProjectDump
- type ProjectInfo
- type PurgeOpts
- type Report
- type RestoreItem
- type RestoreReport
- type Row
- type SearchHit
- type Session
- type SessionRow
- type Store
- func (s *Store) AddIntent(ctx context.Context, sid string, originSeq int64, text string) (int64, error)
- func (s *Store) AppendEvent(ctx context.Context, sid, typ string, payload any) error
- func (s *Store) AppendMessage(ctx context.Context, sid string, m NewMessage) (kernel.Message, error)
- func (s *Store) AppendMessageWithIntent(ctx context.Context, sid string, m NewMessage) (kernel.Message, error)
- func (s *Store) ApplyCompress(ctx context.Context, sid string, p CompressPlan) error
- func (s *Store) ApplyDecompress(ctx context.Context, sid string, p kernel.DecompressPlan) error
- func (s *Store) CacheTotals(ctx context.Context, sid string) (CacheTotals, error)
- func (s *Store) CheckInvariants(ctx context.Context, sid string) error
- func (s *Store) ClearForcedNudge(ctx context.Context, sid string) error
- func (s *Store) Close() error
- func (s *Store) CloseIntent(ctx context.Context, sid string, id int64, status string, closedSeq int64) error
- func (s *Store) CreateSession(ctx context.Context, sess Session) error
- func (s *Store) EnsureProject(ctx context.Context, id, root, storage string, now int64) error
- func (s *Store) Epoch(ctx context.Context) (int64, error)
- func (s *Store) ExportProject(ctx context.Context, id string) (ProjectDump, error)
- func (s *Store) ForcedNudge(ctx context.Context, sid string) (bool, error)
- func (s *Store) GetProject(ctx context.Context, id string) (ProjectInfo, error)
- func (s *Store) GetSession(ctx context.Context, sid string) (SessionRow, error)
- func (s *Store) GetTrigger(ctx context.Context, sid string) (kernel.TriggerState, error)
- func (s *Store) ImportProject(ctx context.Context, d ProjectDump, dst ImportTarget) (map[string]int64, error)
- func (s *Store) ListCacheLedger(ctx context.Context, sid string, limit int) ([]CacheRow, error)
- func (s *Store) ListEvents(ctx context.Context, sid string, limit int) ([]EventRow, error)
- func (s *Store) ListProjects(ctx context.Context) ([]ProjectInfo, error)
- func (s *Store) ListSessionIDs(ctx context.Context, projectID string) ([]string, error)
- func (s *Store) MoveProject(ctx context.Context, id, newRoot string) error
- func (s *Store) ProjectIDByRoot(ctx context.Context, root string) (string, error)
- func (s *Store) PurgeAll(ctx context.Context, o PurgeOpts) (Report, error)
- func (s *Store) PurgeOlderThan(ctx context.Context, projectID string, cutoff time.Time, o PurgeOpts) (Report, error)
- func (s *Store) PurgeProject(ctx context.Context, id string) (map[string]int64, error)
- func (s *Store) PurgeProjectReport(ctx context.Context, id string, o PurgeOpts) (Report, error)
- func (s *Store) PurgeSession(ctx context.Context, sid string, o PurgeOpts) (Report, error)
- func (s *Store) RecordCache(ctx context.Context, sid string, c CacheCall) error
- func (s *Store) RequestNudge(ctx context.Context, sid string, payload any) error
- func (s *Store) RestoreDumps(ctx context.Context, items []RestoreItem, replace, dryRun bool) (RestoreReport, error)
- func (s *Store) ScopeSessionIDs(ctx context.Context, projectID string, olderThan time.Time) ([]string, error)
- func (s *Store) Seal(ctx context.Context) error
- func (s *Store) Search(ctx context.Context, sid, query string, limit int) ([]SearchHit, error)
- func (s *Store) SearchProject(ctx context.Context, projectID, query string, limit int) ([]SearchHit, error)
- func (s *Store) SessionWindow(ctx context.Context, sid string) (model string, limit int, err error)
- func (s *Store) SetContextLimit(ctx context.Context, sid string, limit int) error
- func (s *Store) SetTrigger(ctx context.Context, sid string, t kernel.TriggerState) error
- func (s *Store) Snapshot(ctx context.Context, sid string) (kernel.Snapshot, error)
- func (s *Store) Vacuum(ctx context.Context) error
- func (s *Store) VacuumInto(ctx context.Context, path string) error
- type TableRows
Constants ¶
This section is empty.
Variables ¶
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.
var ErrEmptyQuery = errors.New("search: query has no searchable terms")
ErrEmptyQuery reports a query with no word characters: nothing to match.
var ErrProjectNotFound = errors.New("store: project not found")
ErrProjectNotFound reports a project ID with no row in projects.
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.
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 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 ¶
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 ¶
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 ¶
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 ¶
RestoreReport counts the rows a restore removed and wrote. Conflicts lists every reason the restore was refused, when it was.
type Row ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
CacheTotals returns the sums of the session's cache_ledger rows.
func (*Store) CheckInvariants ¶
CheckInvariants runs I1, I2, I3, I6, I7 for a session against the committed state.
func (*Store) ClearForcedNudge ¶
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) 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 ¶
CreateSession inserts a session and its zeroed trigger_state row in one tx.
func (*Store) EnsureProject ¶
EnsureProject inserts the project or refreshes its root and last_seen_at.
func (*Store) Epoch ¶
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 ¶
ExportProject reads every row of a project in one read transaction. It returns ErrProjectNotFound when the project does not exist.
func (*Store) ForcedNudge ¶
ForcedNudge reports whether a forced nudge is waiting for the next Plan.
func (*Store) GetProject ¶
GetProject returns one project, or ErrProjectNotFound.
func (*Store) GetSession ¶
GetSession reads the row of session sid. sql.ErrNoRows (wrapped) means no such session.
func (*Store) GetTrigger ¶
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 ¶
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 ¶
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 ¶
ListSessionIDs returns the session ids of a project without loading their rows, for read-only health checks.
func (*Store) MoveProject ¶
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 ¶
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 ¶
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 ¶
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 ¶
PurgeProjectReport is PurgeProject with a Report and the dry-run option.
func (*Store) PurgeSession ¶
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 ¶
RecordCache appends one cache_ledger row (spec §9.4).
func (*Store) RequestNudge ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
SetTrigger overwrites the trigger_state row of a session.
func (*Store) Snapshot ¶
Snapshot loads the full ledger, blocks, intents and trigger state of a session.