memory

package
v0.194.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0, MIT Imports: 33 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 memory provides the SQLite-backed persistence layer for yaah. It manages three concerns over a single database file:

  • Sessions: conversation sessions and their messages (session_repo.go, message_repo.go)
  • Long-term memory: searchable notes with FTS5 full-text indexing (memory_crud.go, memory_search.go, memory_vector.go, memory_lifecycle.go, repository.go)
  • Todo persistence: saving/loading the in-memory todo store (todo.go)

The DB type is the single entry point for all database operations.

Index

Constants

View Source
const (
	ScopeGlobal  = "global"
	ScopeSession = "session"

	// ScopeAll is a read-path-only widening: it asks a search to span every
	// tier. It is deliberately not a persistable tier — NormalizeScope
	// rejects it — so no row can be written with scope = "all" and become
	// invisible to a scope = ? filter.
	ScopeAll = "all"
)

Memory scopes are the explicit tiers of docs/compaction-as-sleep.md §8 P3 (directions 4/5): ScopeSession marks an atom distilled from the running conversation — the consolidator's "deep sleep" product — and ScopeGlobal marks one meant to outlive any single session. An empty scope means ScopeGlobal.

View Source
const DefaultEmbeddingTimeout = 30 * time.Second

DefaultEmbeddingTimeout is the HTTP request timeout used when Client is nil.

View Source
const DefaultSessionPageSize = 50

DefaultSessionPageSize caps ListSessionsPage when the caller passes no limit (the ACP spec: agents SHOULD enforce a sensible page size).

Exported so higher layers that need to reason about a page (the session registry's List clamp) derive it from here instead of restating 50.

View Source
const StaleAge = 30 * 24 * time.Hour

StaleAge is the single staleness floor shared by the hygiene sweep and the stats view: a compaction atom younger than this had its whole lifetime to be recalled. Keeping it in one place prevents the sweep and its stats view from drifting apart.

Variables

View Source
var ErrInvalidCursor = errors.New("invalid cursor")

ErrInvalidCursor is returned for malformed pagination cursors. Callers (ACP session/list) surface it as invalid params.

View Source
var ErrMemoryNotFound = errors.New("memory not found")

ErrMemoryNotFound is the sentinel wrapped (with the offending ID) by DeleteMemory and UpdateMemory when no row matches, so consumers can separate a missing ID from a genuine database failure with errors.Is instead of substring-matching a message (#330 review follow-up).

View Source
var ErrSavedPermissionNotFound = errors.New("saved permission not found")

ErrSavedPermissionNotFound is the sentinel wrapped (with the offending triple) by DeleteSavedPermission when the row does not exist, so a caller can separate a stale delete from a genuine database failure with errors.Is.

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

ErrSessionNotFound is returned when a session id does not exist in the store (delete/resume of a stale or unknown id).

View Source
var ErrWorkflowRunNotFound = errors.New("memory: workflow run not found")

ErrWorkflowRunNotFound reports that no run state is stored under that id.

Functions

func CosineSimilarity added in v0.52.1

func CosineSimilarity(a, b []float32) float32

CosineSimilarity returns the cosine similarity between a and b. Returns 0 if the lengths differ or if either vector has zero magnitude.

func DefaultPath

func DefaultPath() string

DefaultPath returns the default database path (~/.yaah/state.db).

func DeriveSessionTitle added in v0.95.0

func DeriveSessionTitle(content string) string

DeriveSessionTitle condenses a user message into a picker label: whitespace collapsed, synthetic traffic rejected, hard-capped at maxSessionTitleRunes with an ellipsis. Empty return = no title yet. Shared with the agent loop's persist hook, which mirrors TouchSession's one-shot rule to notify clients of the title transition.

func EncodeEmbedding added in v0.52.1

func EncodeEmbedding(e Embedding) []byte

EncodeEmbedding serializes an Embedding to a little-endian float32 byte slice for SQLite BLOB storage.

func IsEmbedFailure added in v0.106.1

func IsEmbedFailure(err error) bool

IsEmbedFailure reports whether err came from the query-embedding step of a vector search (as opposed to the store/scan step). Callers that need the reason for a degraded semantic path use this: SearchMemoryVectorScopedDiag returns it, while SearchMemoryVectorScoped deliberately degrades it to (nil, nil).

func NewEntryID added in v0.55.2

func NewEntryID() string

NewEntryID returns a fresh memory entry ID. IDs were previously mem-<UnixNano>, which collides when two entries are created within the clock's nanosecond resolution — coarse clocks make that a primary-key collision for back-to-back inserts, not a theoretical one. The random form matches newTurnID's shape: 128 bits of crypto/rand, hex-encoded, with a time-based fallback only if the system entropy source is unavailable.

func NormalizeScope added in v0.98.0

func NormalizeScope(scope string) (string, error)

NormalizeScope maps the empty scope to ScopeGlobal and lowercases the known tiers. An unknown value is an error: persisting an unfilterable tier would make the row invisible to every scope = ? query, so it must fail loudly instead of being written verbatim.

func NormalizeScopeFilter added in v0.103.0

func NormalizeScopeFilter(scope string) (string, error)

NormalizeScopeFilter validates the tier filter of a read path. Unlike NormalizeScope it accepts ScopeAll, because widening a query cannot make a row unreachable the way writing an unknown tier can.

It deliberately does not treat the empty string as "every tier". The store used to read "" as "no predicate" while the tool layer read the same "" as "global only", so one input meant opposite things a hundred lines apart. Every read now has to name its tier.

func TraceOwnerParentsReadOnly added in v0.123.0

func TraceOwnerParentsReadOnly(path string, ownerIDs []string) (map[string]string, error)

TraceOwnerParentsReadOnly resolves trace owners without opening the mutable database path: reports must not create or migrate state.db. A missing database is an empty mapping, not an error.

Types

type DB

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

DB is the yaah persistent database.

func Open

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

Open opens (or creates) the yaah database at the given path.

func OpenDefault

func OpenDefault() (*DB, error)

OpenDefault opens the database at the default path.

func (*DB) AddMemory

func (d *DB) AddMemory(e Entry) error

AddMemory inserts a new memory entry. The caller should separately call EmbedMemoryAsync to produce the embedding vector.

func (*DB) AddMemoryDedup added in v0.2.0

func (d *DB) AddMemoryDedup(e Entry) (string, error)

AddMemoryDedup adds a memory entry, skipping if text is identical to an existing entry. Returns the ID of the duplicate if found, or empty string if the entry was added. The lookup and insert run in a single write transaction (the DSN sets _txlock=immediate) so concurrent dedup calls cannot both observe "no match" and insert duplicate rows.

func (*DB) AddMemorySuperseding added in v0.103.0

func (d *DB) AddMemorySuperseding(e Entry, supersedesID string) (string, bool, error)

AddMemorySuperseding writes e and marks supersedesID as superseded by the atom that ends up representing it, in one transaction. It returns the atom's id and whether that atom already existed (an identical live atom is reused rather than duplicated, exactly as AddMemoryDedup does).

func (*DB) AddMessage

func (d *DB) AddMessage(m Message) error

AddMessage inserts a message into a session. When an embedder is configured and the role is "user" or "assistant", the content is embedded in a background goroutine so the caller is not blocked.

func (*DB) ClaimSessionWatchFire added in v0.141.0

func (d *DB) ClaimSessionWatchFire(sessionID, id, owner string, armedAt, firedAt, leaseUntil int64, evidence string) (bool, error)

ClaimSessionWatchFire transitions an armed watch owned by owner to fired. armedAt scopes the claim to that watch generation, so a same-id replacement is never marked. It reports false when another process owns the row, the row is no longer armed, or the generation changed, so a process that lost the last-resume race cannot deliver a wake the current owner is responsible for.

func (*DB) ClaimSessionWatches added in v0.141.0

func (d *DB) ClaimSessionWatches(sessionID, owner string, leaseUntil int64) ([]SessionWatch, error)

ClaimSessionWatches makes owner the owner of every armed watch for the session and returns the claimed set. Last resume wins: a newer process takes over and the older process's eventual fires are rejected by ClaimSessionWatchFire. Fired rows are deliberately not claimed: a live owner may still be delivering them, and a resume re-delivers them only after the previous lease expires. The UPDATE and SELECT share a transaction so the returned set is the one this owner claimed.

func (*DB) Close

func (d *DB) Close() error

Close drains in-flight background embedding writes (bounded by embedDrainTimeout) and then closes the database connection. Draining first keeps a short-lived process from racing its own embeds against the pool shutdown.

func (*DB) CountMemories added in v0.103.0

func (d *DB) CountMemories(scope string) (int, error)

CountMemories reports how many entries live in the named tier: ScopeGlobal, ScopeSession, or ScopeAll. It exists so a caller can say "there are memories here, just not in the tier you searched" instead of reporting a bare miss.

func (*DB) CountMessages added in v0.121.0

func (d *DB) CountMessages() (int, error)

CountMessages reports how many messages the store holds across every session. It exists so a caller can tell "there are past transcripts to recall" from "there are session rows but nothing in them": a session is created at wiring time before any turn runs, so a run that produced no messages leaves a row that recalls nothing, and memory_search_sessions skips message-less sessions rather than listing them.

func (*DB) CreateSession

func (d *DB) CreateSession(s Session) error

CreateSession inserts a new session. The system_prompt column is capped so an unbounded prompt cannot bloat the database (review A6/S7). Persona records the resolved orchestrator persona the session was created with (yaah-21uk.9): resume reads the name back and re-resolves it against that day's registry instead of re-reading agents.default.agent. A session's activity timestamp starts at its start: pickers show freshly created sessions with their creation time instead of an epoch-zero updatedAt.

func (*DB) DeleteMemory added in v0.2.0

func (d *DB) DeleteMemory(id string) error

DeleteMemory removes a memory entry by ID. A delete matching no rows is an error, not a success: tool callers pass back whatever ID the tools surfaced, and a silent no-op delete let truncated IDs report "deleted" while the row — and its duplicates — accumulated (#328).

func (*DB) DeleteMessagesFrom added in v0.55.1

func (d *DB) DeleteMessagesFrom(sessionID string, fromIdx int) error

DeleteMessagesFrom removes persisted message rows for a session at idx >= fromIdx. Used when the in-memory conversation is replaced wholesale (compaction rebase) or rewound (turn restore), so stale rows cannot conflict with re-persisted messages or resurrect on resume (review finding B7). FTS5 rows follow via the messages table's delete triggers; the messages_vec rows are removed here in the same transaction so a reused rowid cannot resurface a stale vector.

func (*DB) DeleteSavedPermission added in v0.167.0

func (d *DB) DeleteSavedPermission(projectID, action, resource string) error

DeleteSavedPermission removes one row; deleting an unknown row wraps ErrSavedPermissionNotFound, never a silent no-op.

func (*DB) DeleteSession added in v0.94.0

func (d *DB) DeleteSession(id string) error

DeleteSession removes a session and its dependent rows atomically. messages has a foreign key to sessions(id) but foreign_keys enforcement is not guaranteed (modernc.org/sqlite defaults it off), so children are deleted explicitly — inside one transaction, so a mid-way failure never leaves an emptied session row still on the pages. todos is not session-keyed and memory entries are global; trace_owners rows pointing at the session are stale after deletion and are removed too.

func (*DB) DeleteSessionWatch added in v0.140.0

func (d *DB) DeleteSessionWatch(sessionID, id string) error

DeleteSessionWatch removes one watch row. An unknown id is a no-op.

func (*DB) DeleteSessionWatches added in v0.140.0

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

DeleteSessionWatches removes every watch row for a session. It is the cleanup path for a session whose watches can no longer be honoured (the session was deleted or its workspace is gone), never the resume path.

func (*DB) DeleteWorkflowCheckpoint added in v0.186.0

func (d *DB) DeleteWorkflowCheckpoint(runID string) error

DeleteWorkflowCheckpoint removes one run's state. It is the cleanup path for a run a caller is done with — never the resume path, which must read the record to know what not to re-do.

func (*DB) EmbedMemoryAsync added in v0.52.1

func (d *DB) EmbedMemoryAsync(id, text string) <-chan struct{}

EmbedMemoryAsync embeds the text in a background goroutine and stores the result. Returns a channel that closes when the embed completes — or immediately, with nothing written, when no embedder is configured or the store is closing (a skipped embed is recovered by the reconcile pass). Callers that need to wait for the embedding (e.g. the memory_add tool) can read from the channel.

func (*DB) Embedder added in v0.52.1

func (d *DB) Embedder() Embedder

Embedder returns the configured embedding model, or nil. Safe for concurrent use.

func (*DB) EndSession added in v0.2.0

func (d *DB) EndSession(id string, endedAt int64, tokensIn int, tokensOut int, tokensCached, subTokensIn, subTokensOut int) error

EndSession sets the ended_at timestamp and final token counts for a session, including the cache-hit and sub-agent attribution columns.

Idempotent-safe by construction, because every exit of a session funnels its close through here and more than one caller can reach it (a signal funnel racing the driver's deferred close, a retried teardown):

  • ended_at only ever moves FORWARD, so a second close can neither reopen a row (ended_at back to 0) nor pin it to a stale clock. Forward-only is what a resumed session needs: its row still carries the previous process's ended_at, and the next close must advance it.
  • the usage columns take the maximum of the stored and offered values, mirroring UpdateSessionUsage's monotonic flush. A close carrying a stale or zeroed snapshot therefore cannot shrink what the row already reports.

A close for an id with no row returns ErrSessionNotFound instead of succeeding on zero rows: the write is the only evidence the session ended, and a row left at ended_at = 0 is exactly the failure this guards against.

func (*DB) EnsureVectorIndex added in v0.147.0

func (d *DB) EnsureVectorIndex(ctx context.Context) (recreated bool, err error)

EnsureVectorIndex creates (or recreates) the vec0 index tables (memory_vec and messages_vec) at the width the configured embedder produces, and stamps that width. It is the startup reconciliation point: a model swap changes the width, so stale tables are dropped and recreated for the follow-up re-embed pass to repopulate.

Idempotent and safe to call repeatedly. Returns recreated=true when any table was (re)created and needs repopulation. A nil embedder is a no-op; a probe failure (embedder unreachable) is returned so callers can degrade gracefully and retry via the write/reconcile paths.

func (*DB) GetCompactionCooldown added in v0.27.0

func (d *DB) GetCompactionCooldown(sessionID string) (cooldownUntil int64, ineffective int, err error)

GetCompactionCooldown returns the compaction cooldown state for a session.

func (*DB) GetMemory added in v0.2.0

func (d *DB) GetMemory(id string) (Entry, error)

GetMemory retrieves a single memory entry by ID.

func (*DB) GetMessages

func (d *DB) GetMessages(sessionID string) ([]Message, error)

GetMessages returns all messages for a session.

func (*DB) GetSession added in v0.36.0

func (d *DB) GetSession(id string) (Session, error)

GetSession retrieves a single session by ID.

func (*DB) GetSkillProvenance added in v0.97.0

func (d *DB) GetSkillProvenance(name string) (SkillProvenance, error)

GetSkillProvenance returns a skill's provenance record. An unknown name yields the zero record (not an error).

func (*DB) GetSkillUsage added in v0.97.0

func (d *DB) GetSkillUsage(name string) (SkillUsage, error)

GetSkillUsage returns a skill's usage record. An unknown name yields the zero record (not an error): callers summarising a skills tree must not have to special-case a skill nobody has touched yet.

func (*DB) Journey added in v0.100.0

func (d *DB) Journey(limit int) ([]JourneyEvent, error)

Journey returns the most recent memory and skill events merged into one newest-first timeline, truncated to limit (limit <= 0 means 50). It is a render: two bounded reads, no writes.

func (*DB) ListMemory

func (d *DB) ListMemory(limit int) ([]Entry, error)

ListMemory returns the most recent memory entries.

func (*DB) ListMemoryScoped added in v0.98.0

func (d *DB) ListMemoryScoped(limit int, scope string) ([]Entry, error)

ListMemoryScoped returns the most recent memory entries, restricted to the named tier (ScopeGlobal, ScopeSession, or ScopeAll).

func (*DB) ListSessionWatches added in v0.140.0

func (d *DB) ListSessionWatches(sessionID string) ([]SessionWatch, error)

ListSessionWatches returns every persisted watch for a session, oldest first. The caller owns the slice.

func (*DB) ListSessions

func (d *DB) ListSessions(limit int) ([]Session, error)

ListSessions returns recent sessions.

func (*DB) ListSessionsPage added in v0.94.0

func (d *DB) ListSessionsPage(filter SessionListFilter) ([]SessionSummary, string, error)

ListSessionsPage returns one page of session summaries, newest first, ordered by (started_at DESC, id DESC) for a stable keyset pagination. The second return value is the opaque cursor for the next page, empty on the last page. An unparsable filter.Cursor returns ErrInvalidCursor so callers can map it to an invalid-params error rather than something that looks like an internal failure.

func (*DB) ListSkillLedger added in v0.97.0

func (d *DB) ListSkillLedger(name string) ([]SkillLedgerEntry, error)

ListSkillLedger returns a skill's ledger rows oldest-first. name == "" returns the whole ledger. An unknown name yields no rows and no error.

func (*DB) ListWorkflowRuns added in v0.186.0

func (d *DB) ListWorkflowRuns(limit int) ([]WorkflowRunRow, error)

ListWorkflowRuns returns the most recently updated runs, newest first. It is the listing a `yaah workflow runs` surface would print, and the way a caller finds the id it wants to resume.

func (*DB) LoadTodos added in v0.4.0

func (d *DB) LoadTodos() ([]todo.Item, error)

LoadTodos retrieves the persisted todo list.

func (*DB) LoadWorkflowCheckpoint added in v0.186.0

func (d *DB) LoadWorkflowCheckpoint(runID string) (WorkflowCheckpoint, error)

LoadWorkflowCheckpoint reads one run's projection back. A run id with no row returns an error wrapping ErrWorkflowRunNotFound.

func (*DB) MaxMessageIdx added in v0.127.1

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

MaxMessageIdx returns the highest persisted message index for a session, or -1 when the session has no rows. It is the recovery anchor for a persister whose cursor fell behind the store (an interrupted or overlapping run): appending at max+1 keeps the transcript contiguous instead of retrying an occupied position forever.

func (*DB) PromoteMemory added in v0.103.0

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

PromoteMemory moves an atom from the session tier into the global one and returns the tier it came from. Promotion is one-way on purpose: a global fact is a claim about the world, and a demoted atom would only be re-promoted (and re-contested) on the next recall. Promoting an atom that is already global is a no-op rather than an error, so a retry after a partial failure is safe.

func (*DB) PruneSession added in v0.99.0

func (d *DB) PruneSession(sessionID string) (int64, error)

PruneSession deletes the session-scoped atoms distilled by one conversation, returning the number of rows removed. It is for explicit session DELETION, not close: sessions are resumable, so close deliberately leaves a session's working context intact (the age-based PruneStaleCompaction reclaims dead atoms later). An empty sessionID is a no-op rather than a blanket delete.

Two guards keep recall intact:

  • Only scope = 'session' rows are candidates. Global atoms — the ones meant to outlive the conversation — are never this method's business, whatever session wrote them.
  • Never-accessed is a precondition. An atom with access_count > 0 or accessed_at > 0 earned its keep by being recalled, so it survives its session; that is the whole difference between working context and a dead atom.

func (*DB) PruneStaleCompaction added in v0.99.0

func (d *DB) PruneStaleCompaction(olderThan time.Time) (int64, error)

PruneStaleCompaction deletes compaction atoms created before olderThan that were never accessed, returning the number of rows removed. It is the single sweep that closes the deep-sleep loop: the consolidator's output that no later recall ever touched. It covers both scopes because a never-accessed atom is dead weight whether the session that wrote it is still around or not — and age alone is safe precisely because access is the proof that an atom mattered.

Every characteristic of a row must hold before it is deleted, and each one rules out a distinct mistake:

  • the compactionSourceTag element in tags — an atom written by a human, a turn, or the CLI carries no such tag and is never swept.
  • created_at < olderThan — the atom had its whole lifetime to be useful, including any session resume within that window.
  • neither accessed_at nor access_count is set — access is proof the atom earned its keep; a used one is kept indefinitely.

A zero olderThan therefore deletes nothing (its Unix seconds are far in the past), which is the safe default for a caller that forgot to set it.

func (*DB) ReconcileEmbeddings added in v0.52.1

func (d *DB) ReconcileEmbeddings(ctx context.Context) (int, error)

ReconcileEmbeddings finds memory rows with NULL embedding, embeds their text using the configured embedder, and stores the results. It returns the number of rows updated. An error from any single embed does not stop the reconciliation; each failure is surfaced via the rate-limited warning log and the OTel embed-failure counter.

func (*DB) ReconcileMemoryDigests added in v0.54.0

func (d *DB) ReconcileMemoryDigests() (int, error)

ReconcileMemoryDigests backfills the digest column for rows where it is NULL (e.g. entries added before the digest migration). Returns the number of rows updated.

func (*DB) ReconcileMessageEmbeddings added in v0.148.0

func (d *DB) ReconcileMessageEmbeddings(ctx context.Context) (int, error)

ReconcileMessageEmbeddings backfills embeddings for user/assistant message rows with a NULL embedding, then heals rows left at a stale width after a model swap. Returns the number of rows updated. An error from any single embed does not stop the reconciliation.

func (*DB) RecordSkillLedger added in v0.97.0

func (d *DB) RecordSkillLedger(name, action, beforeHash, afterHash, delta string) error

RecordSkillLedger appends one mutation to a skill's ledger. The ledger is append-only — there is no update or delete path — so an autonomous consolidation that patches a skill stays auditable and reversible.

func (*DB) RecordSkillProvenance added in v0.97.0

func (d *DB) RecordSkillProvenance(name, createdBy, source string) error

RecordSkillProvenance stamps who created a skill and from what source. Idempotent per name: the first record wins, so re-creating an archived skill never rewrites the original author's provenance.

func (*DB) RecordSkillUsage added in v0.97.0

func (d *DB) RecordSkillUsage(name string, used bool) error

RecordSkillUsage bumps a skill's counters. used=true counts a real use (the skill's instructions were applied) and stamps last_used_at; used=false counts a view — listed or inspected — which never touches last_used_at, so "used" stays meaningful. The upsert makes the first call for a name create the row.

func (*DB) RecordTraceOwner added in v0.55.0

func (d *DB) RecordTraceOwner(ownerID, parentSession, role string) error

RecordTraceOwner persists the mapping from a Shepherd trace owner ID (the session ID for main agents, a synthetic `sub-{role}-{parent}-{ts}` ID for sub-agents) to the parent session that spawned it. This makes Shepherd facts joinable to `sessions` rows even when the owner differs from the session ID. Idempotent per owner.

func (*DB) ReembedStaleEmbeddings added in v0.137.0

func (d *DB) ReembedStaleEmbeddings(ctx context.Context) (int, error)

ReembedStaleEmbeddings rewrites memory rows whose stored vector has a different dimensionality than the configured embedder produces (yaah-shq). Swapping the model (say 384-dim all-MiniLM for 768-dim nomic) leaves every earlier row uncomparable to the new query vectors — it survives on keyword fallback until this runs. It also re-mirrors rows whose BLOB is the correct width but whose vec0 row is missing (a crash between the BLOB update and the mirror would otherwise leave them invisible to the index-preferred search). Returns the number of rows healed; a nil embedder is a no-op. An embed failure is surfaced like any other and does not stop the sweep.

func (*DB) ReembedStaleMessageEmbeddings added in v0.148.0

func (d *DB) ReembedStaleMessageEmbeddings(ctx context.Context) (int, error)

ReembedStaleMessageEmbeddings heals the messages_vec index from the BLOB column: it re-embeds rows whose stored width differs from the embedder (the message-side counterpart to ReembedStaleEmbeddings), and re-mirrors rows whose BLOB is the correct width but whose vec0 row is missing (a crash between the BLOB update and the mirror would otherwise leave them invisible to the index-preferred search). Returns the number of rows healed; a nil embedder is a no-op. An embed failure is surfaced like any other and does not stop the sweep.

func (*DB) ReleaseSessionWatchLease added in v0.141.0

func (d *DB) ReleaseSessionWatchLease(sessionID, id, owner string) (bool, error)

ReleaseSessionWatchLease clears the lease on a fired row still owned by owner. A row that was already delivered and deleted, or re-armed by a newer owner, is untouched.

func (*DB) SaveSavedPermission added in v0.167.0

func (d *DB) SaveSavedPermission(p SavedPermission) error

SaveSavedPermission records one allow decision. Rows are unique per (project, action, resource): re-saving a decision the user has already made is a no-op, not a second row.

func (*DB) SaveSessionWatch added in v0.140.0

func (d *DB) SaveSessionWatch(sessionID string, w SessionWatch) error

SaveSessionWatch inserts or replaces one watch row.

func (*DB) SaveTodos added in v0.4.0

func (d *DB) SaveTodos(items []todo.Item) error

SaveTodos persists the todo list as a JSON blob.

func (*DB) SaveWorkflowCheckpoint added in v0.186.0

func (d *DB) SaveWorkflowCheckpoint(cp WorkflowCheckpoint) error

SaveWorkflowCheckpoint writes one run's projection in a single transaction. Every statement is an upsert, so re-saving the same projection is a no-op: the scheduler re-writes the whole snapshot on every event, and a store that only tolerated deltas would have to trust a diff it cannot verify.

func (*DB) SavedPermissions added in v0.167.0

func (d *DB) SavedPermissions(projectID string) ([]SavedPermission, error)

SavedPermissions returns the project's saved allows as ruleset rows. Each row is one Effect Allow rule keyed on the tool name; a session's saved answers therefore participate in the ordinary last-match-wins ruleset fold, where the configured ruleset (evaluated after them) can still narrow or deny.

func (*DB) SearchMemory

func (d *DB) SearchMemory(query string, limit int, tag ...string) ([]Entry, error)

SearchMemory searches memory entries using FTS5 and bumps access counters for returned results. An optional tag can be passed to filter by tag.

func (*DB) SearchMemoryScoped added in v0.98.0

func (d *DB) SearchMemoryScoped(query string, limit int, tagFilter, scope string) ([]Entry, error)

SearchMemoryScoped is SearchMemory with an explicit scope (tier) filter. scope must name a tier: ScopeGlobal, ScopeSession, or ScopeAll. Each returned entry carries its own Scope.

func (*DB) SearchMemoryVector added in v0.52.1

func (d *DB) SearchMemoryVector(ctx context.Context, query string, limit int) ([]VectorResult, error)

SearchMemoryVector embeds the query, scans all rows with non-null embedding, and returns the top-K sorted by cosine similarity (descending). Rows whose stored vector has a different dimensionality than the embedder's output are scored by keyword fallback and ranked after the vector hits (yaah-shq). Falls back to an empty result when no embedder is configured or the embedding call fails; a failed embedding call is surfaced via the rate-limited warning log and the OTel embed-failure counter.

func (*DB) SearchMemoryVectorReport added in v0.148.1

func (d *DB) SearchMemoryVectorReport(ctx context.Context, query string, limit int) (VectorSearchReport, error)

SearchMemoryVectorReport is SearchMemoryVector with the dimension-mismatch diagnostics attached (yaah-shq).

func (*DB) SearchMemoryVectorScoped added in v0.98.0

func (d *DB) SearchMemoryVectorScoped(ctx context.Context, query string, limit int, scope string) ([]VectorResult, error)

SearchMemoryVectorScoped is SearchMemoryVector with an explicit scope (tier) filter. scope must name a tier: ScopeGlobal, ScopeSession, or ScopeAll.

An embed failure degrades to (nil, nil): semantic recall is best-effort and the caller keeps its keyword path. Use SearchMemoryVectorScopedDiag when the reason for the degradation must be reported.

func (*DB) SearchMemoryVectorScopedDiag added in v0.106.1

func (d *DB) SearchMemoryVectorScopedDiag(ctx context.Context, query string, limit int, scope string) ([]VectorResult, error)

SearchMemoryVectorScopedDiag is SearchMemoryVectorScoped with the reason for a degraded vector search preserved. A non-nil error means the vector path produced nothing: either the query could not be embedded (an embed failure, already recorded for the log and OTel counter; classify it with IsEmbedFailure) or the store query failed. A nil embedder is not an error — it reports (nil, nil) — so a caller that must name that state checks Embedder() first.

func (*DB) SearchMemoryVectorScopedReport added in v0.148.1

func (d *DB) SearchMemoryVectorScopedReport(ctx context.Context, query string, limit int, scope string) (VectorSearchReport, error)

SearchMemoryVectorScopedReport is the search the front-ends call: the ranked page together with the count of rows the vector path could not compare (yaah-shq). An embedding-model swap leaves earlier rows at the old width: the vec0 index is recreated at the new width (so it holds none of them) and a cosine score against the new query vector is meaningless. Those rows are keyword-scored into the page and counted in the report — the omission is never silent, and nothing is re-embedded here (no embedder round-trip beyond the query itself).

A nil embedder reports the zero report; an embed failure returns an *embedError after recording it, exactly like the Diag form.

func (*DB) SearchMessages added in v0.2.0

func (d *DB) SearchMessages(query string, limit int) ([]Message, error)

SearchMessages searches past session messages using FTS5.

func (*DB) SearchMessagesVector added in v0.52.1

func (d *DB) SearchMessagesVector(ctx context.Context, query string, limit int) ([]MessageVectorResult, error)

SearchMessagesVector embeds the query and returns the top-K semantically matched messages, degrading an embed failure to an empty result so the caller keeps its keyword path. Use SearchMessagesVectorDiag when the reason for the degradation must be reported.

func (*DB) SearchMessagesVectorDiag added in v0.148.0

func (d *DB) SearchMessagesVectorDiag(ctx context.Context, query string, limit int) ([]MessageVectorResult, error)

SearchMessagesVectorDiag is SearchMessagesVector with the reason for a degraded semantic path preserved: a non-nil error means the vector path produced nothing, either because the query could not be embedded (an embed failure, already recorded for the log and OTel counter; classify it with IsEmbedFailure) or the store query failed. A nil embedder is not an error — it reports (nil, nil) — so a caller that must name that state checks Embedder() first.

func (*DB) SessionMode added in v0.129.0

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

SessionMode reads the session's persisted mode. The empty string is build: a row created before the column existed (or by a caller that never switched) reads as build, never as an unknown regime. An unknown id returns the underlying sql.ErrNoRows so a caller can tell "no mode stored" from "no such session".

func (*DB) SessionModel added in v0.158.0

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

SessionModel reads the session's persisted model pick (parity W4). Written as the "provider/model" wire form by SetSessionModel; the empty string is "nothing stored" — a row created before the first model switch (or a legacy row holding a bare model name, which carries no provider and reads as no pick at the resolution sites). An unknown id returns the underlying sql.ErrNoRows so a caller can tell "no pick stored" from "no such session".

func (*DB) SessionPersona added in v0.153.0

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

SessionPersona reads the session's persisted orchestrator persona name (yaah-21uk.9): the name CreateSession stored at creation, which a resume re-resolves against that day's registry instead of re-reading agents.default.agent — the persona is selection state, so a config default change never rewrites an existing session. The empty string is "nothing stored": a row created before the column existed (the column's DEFAULT) reads as build at the resolution sites, the zero-change migration. An unknown id returns the underlying sql.ErrNoRows so a caller can tell "no persona stored" from "no such session".

func (*DB) SetCompactionCooldown added in v0.27.0

func (d *DB) SetCompactionCooldown(sessionID string, cooldownUntil int64, ineffective int) error

SetCompactionCooldown persists the compaction cooldown state for a session.

func (*DB) SetEmbedder added in v0.52.1

func (d *DB) SetEmbedder(e Embedder)

SetEmbedder configures the embedding model used for semantic search. When nil, vector search is disabled. Safe for concurrent use.

func (*DB) SetSessionMode added in v0.129.0

func (d *DB) SetSessionMode(id, mode string) error

SetSessionMode records the ACP session mode ("build" or "plan"; the empty string is build) so the selection outlives the process: resume reads it back and the session starts in the mode it was left in instead of silently widening to build. Written on the switch rather than at close, because a crash, a harness timeout or a kill never reaches the close path.

updated_at is deliberately untouched: it means "timestamp of the last persisted message", and a mode switch is selection state, not activity — a resume picker must not reorder sessions because someone changed a mode.

func (*DB) SetSessionModel added in v0.158.0

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

SetSessionModel records the session's model pick as the "provider/model" wire form (parity W4): a mid-session switch rewrites the column a resume restores, so the session comes back routed where it was switched to. Written on the switch rather than at close, mirroring SetSessionPersona — a crash, a harness timeout or a kill never reaches the close path.

updated_at is deliberately untouched: model selection state, not activity (same rule as SetSessionPersona).

func (*DB) SetSessionPersona added in v0.153.0

func (d *DB) SetSessionPersona(id, persona string) error

SetSessionPersona records the session's orchestrator persona name (yaah-21uk.12): a mid-session switch rewrites the column a resume re-resolves, so the session comes back as the persona it was switched to rather than the one it was created with. Written on the switch rather than at close, mirroring SetSessionMode — a crash, a harness timeout or a kill never reaches the close path.

updated_at is deliberately untouched: persona selection state, not activity (same rule as SetSessionMode).

func (*DB) SetSessionPersonaState added in v0.171.1

func (d *DB) SetSessionPersonaState(id, persona, systemPrompt, provider, model string) error

SetSessionPersonaState atomically records a persona switch's three side effects — the persona column, the rebuilt system prompt (when it changed), and the resolved routing pick (when routable) — in one transaction so a crash between the writes cannot leave the row half-switched (yaah-21uk.17). An empty systemPrompt or pick leaves the corresponding column untouched, matching the conditional writes the caller made before.

func (*DB) SetSessionSystemPrompt added in v0.153.0

func (d *DB) SetSessionSystemPrompt(id, prompt string) error

SetSessionSystemPrompt replaces the persisted system prompt: a persona switch rebinds the persona body into the prompt, and resume reads this column byte-for-byte, so the row must carry the switched prompt or the resume would run the old persona body under the new persona name. The create-time truncation cap applies, same as CreateSession.

updated_at is deliberately untouched (selection state, not activity).

func (*DB) Stats added in v0.100.0

func (d *DB) Stats() (MemoryStats, error)

Stats returns the aggregate memory view. Every query is a single cheap aggregation; nothing is written.

func (*DB) SupersedeMemory added in v0.103.0

func (d *DB) SupersedeMemory(oldID, newID string) error

SupersedeMemory marks oldID as superseded by newID. The row is kept for audit but excluded from every recall path, so a contradicted fact stops surfacing instead of being silently retained beside its correction.

func (*DB) SupersededBy added in v0.103.0

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

SupersededBy reports which atom superseded id, or "" when id is still live.

func (*DB) TouchSession added in v0.94.0

func (d *DB) TouchSession(sessionID string, updatedAt int64, titleCandidate string) error

TouchSession records message activity: updated_at moves to the message timestamp and, while the title is still empty, the candidate becomes the title. Both are best-effort bookkeeping for pickers, not turn data.

func (*DB) TraceOwnerParent added in v0.55.0

func (d *DB) TraceOwnerParent(ownerID string) (string, error)

TraceOwnerParent returns the parent session recorded for a trace owner, or "" when the owner is unknown. Main-agent owners map to themselves.

func (*DB) TraceOwnersForSession added in v0.132.6

func (d *DB) TraceOwnersForSession(sessionID string) ([]string, error)

TraceOwnersForSession returns every trace owner id recorded for a parent session. The mapping is the only record of the sub-* synthetic owner ids, so the kernel-first session delete reads it before the cascade removes the rows (docs/retention-gc.md §5) — collect first, evict second, cascade last.

func (*DB) UpdateMemory added in v0.2.0

func (d *DB) UpdateMemory(id string, text string) error

UpdateMemory updates the text of an existing memory entry.

func (*DB) UpdateSessionSummary added in v0.36.0

func (d *DB) UpdateSessionSummary(id string, summary string) error

UpdateSessionSummary persists the most recent compaction summary for a session, capped like system_prompt (review A6/S7).

func (*DB) UpdateSessionUsage added in v0.78.0

func (d *DB) UpdateSessionUsage(id string, tokensIn int, tokensOut int, tokensCached, subTokensIn, subTokensOut int) error

UpdateSessionUsage flushes the running usage counters without ending the session. Called incrementally (per LLM call) so a session killed mid-run — a harness timeout, a crash — still reports what it spent. ended_at is untouched: the session is still open.

func (*DB) UpdateSessionWorkspace added in v0.61.0

func (d *DB) UpdateSessionWorkspace(id, backend, omittedTools string) error

UpdateSessionWorkspace records the workspace substrate a session ran under and the host-only tools isolated mode omitted (decision D4 of the isolated-workspace plan). Called after the tool registry is final, so the omitted list reflects what this session actually skipped. The columns describe the session's most recent run; a resumed session that changed mode overwrites them.

type DebouncedWriter added in v0.27.0

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

func NewDebouncedWriter added in v0.27.0

func NewDebouncedWriter(db *DB) *DebouncedWriter

func (*DebouncedWriter) Flush added in v0.27.0

func (w *DebouncedWriter) Flush() error

func (*DebouncedWriter) Update added in v0.27.0

func (w *DebouncedWriter) Update(ctx context.Context, m Message) error

type Embedder added in v0.52.1

type Embedder interface {
	Embed(ctx context.Context, text string) (Embedding, error)
}

Embedder produces an embedding for a single input string.

type Embedding added in v0.52.1

type Embedding []float32

Embedding is a float32 vector produced by an embedding model.

func DecodeEmbedding added in v0.52.1

func DecodeEmbedding(b []byte) Embedding

DecodeEmbedding deserializes a BLOB back into an Embedding.

func EmbedQuery added in v0.146.0

func EmbedQuery(ctx context.Context, e Embedder, text string) (Embedding, error)

EmbedQuery embeds search/query text with the embedder's query-side treatment when it has one, falling back to Embed otherwise. Callers outside this package (e.g. skill search) use it to embed a query without reaching for Embed, which carries the document-side prefix.

type Entry

type Entry struct {
	ID          string `json:"id"`
	Text        string `json:"text"`
	Tags        string `json:"tags"` // JSON array
	Source      string `json:"source"`
	Scope       string `json:"scope"`
	SessionID   string `json:"session_id,omitempty"`
	CreatedAt   int64  `json:"created_at"`
	AccessedAt  int64  `json:"accessed_at,omitempty"`
	AccessCount int    `json:"access_count"`
}

Entry represents a long-term memory note. Scope is its tier (ScopeSession or ScopeGlobal); it is always populated on read. SessionID links a session-scoped atom to the conversation that distilled it and is empty on global atoms and on every row written before schema v5 — the garbage collector in hygiene.go needs a non-empty value before it touches a row.

type GGUFEmbedder added in v0.137.0

type GGUFEmbedder struct {
	// LibPath is the prebuilt llama.cpp shared library the yzma loader
	// needs (e.g. libllama.so). Empty lets the loader pick its default.
	LibPath string
	// ModelPath is the GGUF model file. Required.
	ModelPath string
	// QueryPrefix and DocumentPrefix are the asymmetric prefixes for
	// nomic-style models ("search_query: "/"search_document: "). Leave
	// empty for symmetric models.
	QueryPrefix    string
	DocumentPrefix string
	// contains filtered or unexported fields
}

GGUFEmbedder embeds text in-process from a local GGUF model using yzma's prebuilt llama.cpp bindings (purego FFI — CGO_ENABLED=0 stays intact). It exists so semantic memory works with no LM Studio or Ollama running (yaah-m3pk), reusing the same GGUF weights those tools download.

llama.cpp contexts are not safe for concurrent use, so every embed call serializes on mu across the whole tokenize → decode → pool sequence. The model and context are created lazily on first use: construction stays cheap and a missing library or model surfaces as an error (and via the yaah-ka6 startup probe) instead of a panic.

func NewGGUFEmbedder added in v0.137.0

func NewGGUFEmbedder(libPath, modelPath, queryPrefix, documentPrefix string) *GGUFEmbedder

NewGGUFEmbedder returns a GGUF-backed embedder. Model loading is deferred to the first Embed call; probe it via the yaah-ka6 startup check.

func (*GGUFEmbedder) DecodeWindow added in v0.137.1

func (g *GGUFEmbedder) DecodeWindow() int

DecodeWindow reports the decode window the embedder actually uses — tokens per decode after the train-context clamp — or 0 before the model is loaded. Diagnostic surface for the clamp (yaah-x58j).

func (*GGUFEmbedder) Dims added in v0.137.0

func (g *GGUFEmbedder) Dims() int

Dims reports the model's embedding width (0 until the model is loaded).

func (*GGUFEmbedder) Embed added in v0.137.0

func (g *GGUFEmbedder) Embed(ctx context.Context, text string) (Embedding, error)

Embed embeds document text, applying the document prefix.

func (*GGUFEmbedder) EmbedQuery added in v0.137.0

func (g *GGUFEmbedder) EmbedQuery(ctx context.Context, text string) (Embedding, error)

EmbedQuery embeds search-query text, applying the query prefix. It satisfies QueryEmbedder so search and storage can be treated asymmetrically (nomic-style models score meaningfully higher with prefixed query/document sides).

func (*GGUFEmbedder) TrainContext added in v0.137.1

func (g *GGUFEmbedder) TrainContext() int

TrainContext reports the model's own n_ctx_train (the clamp's source), or 0 when the model is not yet loaded — which is also what a model that reports no n_ctx_train returns, so "unloaded" and "no train context reported" are not distinguishable through this accessor. Once loaded, a 0 train context leaves the clamped window at the reserved default (before any load, DecodeWindow is 0 too — nothing is clamped or resolved yet).

type HTTPEmbedder added in v0.52.1

type HTTPEmbedder struct {
	// BaseURL is the embeddings endpoint base, e.g. "http://127.0.0.1:7334".
	BaseURL string
	// APIKey, when non-empty, is sent as a Bearer token. Local servers
	// such as llama-server do not need it.
	APIKey string
	// Model is the model name sent to the embeddings endpoint.
	// Defaults to "local" (works for llama-server). Set to an ollama model
	// name (e.g. "nomic-embed-text:latest") for ollama.
	Model string
	// Client is the HTTP client used. When nil, a default client with a
	// 30-second timeout is used.
	Client *http.Client
	// QueryPrefix and DocumentPrefix are optional asymmetric prefixes
	// applied to search-query and document text respectively (nomic-style
	// "search_query: " / "search_document: "). Empty means no prefix
	// (symmetric models), matching the previous behavior.
	QueryPrefix    string
	DocumentPrefix string
}

HTTPEmbedder calls an OpenAI-compatible /v1/embeddings endpoint. It works with llama-server, Ollama, and provider APIs. Zero values are usable (http.DefaultClient, timeout defaults).

func NewEmbedder added in v0.52.1

func NewEmbedder(baseURL, apiKey, model string, client *http.Client) *HTTPEmbedder

NewEmbedder creates an HTTPEmbedder for the given base URL, API key, model name, and HTTP client. When apiKey is empty, no Authorization header is sent (local servers). When model is empty, defaults to "local". When client is nil, a default client with a 30-second timeout is used.

func (*HTTPEmbedder) Embed added in v0.52.1

func (e *HTTPEmbedder) Embed(ctx context.Context, text string) (Embedding, error)

Embed embeds document text, applying DocumentPrefix when set. It calls POST /v1/embeddings and returns the float32 embedding vector from the first data element.

func (*HTTPEmbedder) EmbedQuery added in v0.146.0

func (e *HTTPEmbedder) EmbedQuery(ctx context.Context, text string) (Embedding, error)

EmbedQuery embeds search-query text, applying QueryPrefix when set. It satisfies QueryEmbedder, so search paths prefer it over Embed for nomic-style asymmetric prefixes.

type JourneyEvent added in v0.100.0

type JourneyEvent struct {
	Kind      string // "memory" or "skill"
	ID        string // memory id, or skill name
	Detail    string // truncated memory text, or the skill action
	CreatedAt int64  // Unix seconds
}

JourneyEvent is one node of the rendered learning graph: either a memory atom or a skill mutation, both normalized to a common kind/timestamp so a viewer can draw one timeline.

type MemoryRepository added in v0.36.0

type MemoryRepository interface {
	AddMemory(e Entry) error
	AddMemoryDedup(e Entry) (string, error)
	SearchMemory(query string, limit int, tag ...string) ([]Entry, error)
	GetMemory(id string) (Entry, error)
	// DeleteMemory removes an entry; a delete matching no rows returns
	// an error wrapping ErrMemoryNotFound (never a silent no-op).
	DeleteMemory(id string) error
	// UpdateMemory updates an entry's text; an ID matching no rows
	// returns an error wrapping ErrMemoryNotFound.
	UpdateMemory(id string, text string) error
	ListMemory(limit int) ([]Entry, error)
}

MemoryRepository manages long-term memory entries.

type MemoryStats added in v0.100.0

type MemoryStats struct {
	Total              int   // all memory atoms
	Global             int   // scope = global
	Session            int   // scope = session
	NeverAccessed      int   // atoms no recall ever touched
	StaleCandidates    int   // compaction atoms older than the floor, never accessed
	SkillsTracked      int   // skills with a provenance row
	SkillLedgerEntries int   // append-only skill mutation rows
	OldestCreatedAt    int64 // Unix seconds; 0 when the store is empty
	NewestCreatedAt    int64 // Unix seconds; 0 when the store is empty
}

MemoryStats is the aggregate view shown by `yaah memory stats`.

type Message

type Message struct {
	ID                 string `json:"id"`
	SessionID          string `json:"session_id"`
	Idx                int    `json:"idx"`
	Role               string `json:"role"`
	Content            string `json:"content"`
	ReasoningContent   string `json:"reasoning_content,omitempty"`
	ReasoningSignature string `json:"reasoning_signature,omitempty"`
	ToolName           string `json:"tool_name,omitempty"`
	ToolCallID         string `json:"tool_call_id,omitempty"`
	ToolCalls          string `json:"tool_calls,omitempty"`
	Timestamp          int64  `json:"ts"`
	TraceID            string `json:"trace_id,omitempty"`
	TurnID             string `json:"turn_id,omitempty"`
}

Message represents a single message in a session.

type MessageRepository added in v0.36.0

type MessageRepository interface {
	AddMessage(m Message) error
	GetMessages(sessionID string) ([]Message, error)
	SearchMessages(query string, limit int) ([]Message, error)
}

MessageRepository manages the message history within sessions.

type MessageVectorResult added in v0.148.0

type MessageVectorResult struct {
	ID        string
	SessionID string
	Role      string
	Content   string
	Timestamp int64
	Score     float32
}

MessageVectorResult is a session message matched by semantic search. It carries the originating session, role, and timestamp so a recall can point at the conversation it came from — the pre-vec0 path returned only the content, which left the session implicit.

type QueryEmbedder added in v0.137.0

type QueryEmbedder interface {
	Embedder
	EmbedQuery(ctx context.Context, text string) (Embedding, error)
}

QueryEmbedder is an optional interface for embedders that treat query text differently from document text (e.g. nomic-style search_query:/ search_document: prefixes). Callers embedding a search query should use EmbedQuery, which falls back to Embed for plain embedders.

type SavedPermission added in v0.167.0

type SavedPermission struct {
	// ProjectID is the canonical workspace root the decision was made in.
	ProjectID string
	// Action is the tool name the ask carried.
	Action string
	// Resource is the ask's resource derivation (glob, permissions
	// vocabulary); matching is on the derived resource, not on a pattern.
	Resource string
	// CreatedAt is when the user granted it.
	CreatedAt int64
}

SavedPermission is one durable "always" answer from an approval prompt: the user allowed this (tool, resource) shape once and chose always.

It is project-scoped — ProjectID is the canonical workspace root, so an allow saved in one repository never widens a call in another — and consults as a Rule with Effect Allow, meaning the regular last-match-wins ruleset fold applies when the config ruleset names the same (tool, resource) pair: the configured ruleset wins on overlap.

type Session

type Session struct {
	ID        string `json:"id"`
	StartedAt int64  `json:"started_at"`
	EndedAt   int64  `json:"ended_at,omitempty"`
	CWD       string `json:"cwd"`
	Model     string `json:"model"`
	TokensIn  int    `json:"tokens_in"`
	TokensOut int    `json:"tokens_out"`
	// TokensCached is the sum of prompt tokens the provider served
	// from its context cache (deepseek automatic prefix cache). A
	// session killed mid-run still reports its spend because usage
	// flushes incrementally (UpdateSessionUsage), not only at EndSession.
	TokensCached int `json:"tokens_cached,omitempty"`
	// SubTokensIn/SubTokensOut attribute the sub-agent share of the
	// session total (blocking dispatches via the loop fold, background
	// dispatches via the jobs manager). The totals include sub-agent
	// spend; orchestrator spend = total - sub.
	SubTokensIn      int    `json:"sub_tokens_in,omitempty"`
	SubTokensOut     int    `json:"sub_tokens_out,omitempty"`
	SystemPrompt     string `json:"system_prompt,omitempty"`
	CompactedSummary string `json:"compacted_summary,omitempty"`
	// WorkspaceBackend records the workspace substrate the session ran
	// under ("local" or "containerd"), and WorkspaceOmittedTools the
	// host-only tool names isolated mode left out (comma-separated).
	// Decision D4 of the isolated-workspace plan: a run's available tool
	// set differs by mode, so "the model didn't use background_process"
	// and "the model couldn't" must stay distinguishable in the record.
	WorkspaceBackend      string `json:"workspace_backend,omitempty"`
	WorkspaceOmittedTools string `json:"workspace_omitted_tools,omitempty"`
	// Title is a short human-readable label derived from the first user
	// message (session pickers, `yaah sessions`, ACP session/list).
	Title string `json:"title,omitempty"`
	// UpdatedAt is the ts of the last persisted message; 0 on a session
	// with no messages yet (list queries COALESCE it to started_at).
	UpdatedAt int64 `json:"updated_at,omitempty"`
	// Persona is the resolved orchestrator persona the session was
	// created with (yaah-21uk.9): the built-in "build"/"plan" name, or
	// a role-file persona's file stem, persisted at creation so a
	// resume restores the session's own budget
	// (resolveOrchestratorBudget) and tool-belt selection even after
	// agents.default.agent — or the role files themselves — change. The
	// empty string is a row from before the column existed and reads as
	// build at the read sites: pre-persona sessions all ran the plain
	// build orchestrator, so build is all there is to restore.
	Persona string `json:"persona,omitempty"`
}

Session represents a conversation session.

type SessionListFilter added in v0.94.0

type SessionListFilter struct {
	// CWD, when non-empty, matches sessions started in exactly this
	// directory (the ACP session/list cwd parameter, an absolute path).
	CWD string
	// Cursor is the opaque pagination cursor from a previous page;
	// empty for the first page.
	Cursor string
	// Limit caps the page size; <= 0 uses DefaultSessionPageSize.
	Limit int
}

SessionListFilter narrows a ListSessionsPage query.

type SessionRepository added in v0.36.0

type SessionRepository interface {
	CreateSession(s Session) error
	GetSession(id string) (Session, error)
	ListSessions(limit int) ([]Session, error)
	EndSession(id string, endedAt int64, tokensIn int, tokensOut int, tokensCached, subTokensIn, subTokensOut int) error
	UpdateSessionUsage(id string, tokensIn int, tokensOut int, tokensCached, subTokensIn, subTokensOut int) error
	UpdateSessionSummary(id string, summary string) error
	GetCompactionCooldown(sessionID string) (cooldownUntil int64, ineffective int, err error)
	SetCompactionCooldown(sessionID string, cooldownUntil int64, ineffective int) error
	// Session mode persists the build/plan selection across processes so
	// a resumed session is not silently widened back to build.
	SetSessionMode(id, mode string) error
	SessionMode(id string) (string, error)
	// Persona and system-prompt selection state a mid-session persona
	// switch persists on the switch (yaah-21uk.12), so a resume restores
	// both the persona name and the prompt bytes the session ran with.
	SetSessionPersona(id, persona string) error
	SetSessionSystemPrompt(id, prompt string) error
	// Model pick (parity W4): a mid-session model switch persists on the
	// switch as the "provider/model" wire form, so a resume re-routes the
	// session the same way.
	SetSessionModel(id, provider, model string) error
	// Session-lifecycle surface for pickers and multi-session hosts
	// (ACP session/list, resume, delete; `yaah sessions`).
	DeleteSession(id string) error
	ListSessionsPage(filter SessionListFilter) ([]SessionSummary, string, error)
	TouchSession(sessionID string, updatedAt int64, titleCandidate string) error
}

SessionRepository manages conversation sessions.

type SessionSummary added in v0.94.0

type SessionSummary struct {
	ID           string `json:"id"`
	CWD          string `json:"cwd,omitempty"`
	Title        string `json:"title,omitempty"`
	Model        string `json:"model,omitempty"`
	StartedAt    int64  `json:"started_at"`
	UpdatedAt    int64  `json:"updated_at"`
	EndedAt      int64  `json:"ended_at,omitempty"`
	MessageCount int    `json:"message_count"`
}

SessionSummary is the projection ListSessionsPage returns per row: the fields a session picker (ACP session/list, `yaah sessions`, a future TUI/REPL resume picker) needs without touching message bodies.

type SessionWatch added in v0.140.0

type SessionWatch struct {
	ID         string
	On         string
	Until      string
	State      string
	Evidence   string
	ArmedAt    int64
	ExpiresAt  int64
	FiredAt    int64
	IntervalMs int64
	Owner      string
	LeaseUntil int64
}

SessionWatch is the persisted form of one armed watch (internal/wake). It lives in session_watches, keyed by (session_id, id), so each session owns its own armed set and a resume can rebuild it without seeing another session's watches.

type SkillLedgerEntry added in v0.97.0

type SkillLedgerEntry struct {
	ID         int64
	Name       string
	Action     string
	BeforeHash string
	AfterHash  string
	Delta      string
	CreatedAt  string // RFC 3339
}

SkillLedgerEntry is one append-only record of a skill mutation. BeforeHash/AfterHash are content digests, so a ledger row shows what changed without storing the bodies; Delta carries a serialized patch when a caller supplies one, and is empty otherwise.

type SkillProvenance added in v0.97.0

type SkillProvenance struct {
	Name      string
	CreatedBy string
	Source    string // e.g. "skill:create"; empty when unknown
	CreatedAt string // RFC 3339
}

SkillProvenance records who created a skill and from what source.

type SkillUsage added in v0.97.0

type SkillUsage struct {
	Name            string
	UseCount        int
	ViewCount       int
	ReuseAfterPatch int
	LastUsedAt      string // RFC 3339; empty when never used
	CreatedAt       string // RFC 3339
}

SkillUsage is the usage record for one skill: use_count counts loads that were applied to the task, view_count counts inspections that did not become uses. ReuseAfterPatch is reserved for a future idempotency check (a patched skill must be re-used before it is patched again); it is currently always zero because nothing writes it.

type TodoRepository added in v0.36.0

type TodoRepository interface {
	todo.Persister
}

TodoRepository manages persistent todo items.

type VectorResult added in v0.52.1

type VectorResult struct {
	Entry
	Score float32
	// Keyword marks a keyword-fallback hit: the row's stored embedding cannot be
	// compared with the current model's query vector, so it is ranked by word
	// overlap rather than dropped from the page.
	Keyword bool
}

VectorResult is a memory entry with its similarity score. A hit whose stored embedding could not be compared with the query vector — a previous embedding model wrote it at a different width — is marked Keyword and carries a keyword-overlap score instead of a cosine one (yaah-shq).

type VectorSearchReport added in v0.148.1

type VectorSearchReport struct {
	// Hits is the result page: vector-scored rows first (descending cosine
	// similarity), then the keyword-scored rows the vector path could not
	// compare.
	Hits []VectorResult
	// DimMismatch counts the in-scope, live rows whose stored embedding width
	// differs from the current model's query vector. Each one is keyword-scored;
	// none is re-embedded here.
	DimMismatch int
	// DimMismatchByDim maps a stored embedding width to its row count, so a
	// store holding rows from several past models reports every width.
	DimMismatchByDim map[int]int
}

VectorSearchReport is one vector search: the ranked page plus the counts that let a caller tell a degraded recall from a true miss (yaah-shq). A row left at a previous embedding model's width is incomparable to the current query vector, so it is counted here (and keyword-scored) instead of vanishing without a signal.

func (VectorSearchReport) HasDimMismatch added in v0.148.1

func (r VectorSearchReport) HasDimMismatch() bool

HasDimMismatch reports whether any in-scope row was left at a previous embedding model's width. A caller that shows results uses it to name the omission rather than presenting keyword fallback as semantic recall.

type WorkflowAttemptRow added in v0.186.0

type WorkflowAttemptRow struct {
	DispatchID string
	NodePath   string
	Number     int
	Status     string
	StartedAt  int64
	FinishedAt int64
	Payload    string
}

WorkflowAttemptRow is one dispatched attempt. DispatchID is "<node path>#<number>", so the primary key is also the identity a trace joins the dispatch envelope on.

type WorkflowCheckpoint added in v0.186.0

type WorkflowCheckpoint struct {
	Run         WorkflowRunRow
	Nodes       []WorkflowNodeRow
	Instances   []WorkflowInstanceRow
	Attempts    []WorkflowAttemptRow
	Settlements []WorkflowSettlementRow
	// Events are appended, never rewritten: each row is one sequence number.
	Events []WorkflowEventRow
	// Trace are the run's typed trace records, appended from the same events the
	// Events rows render (yaah-0u0v.17).
	Trace []WorkflowTraceRow
}

WorkflowCheckpoint is one run's whole durable projection.

type WorkflowEventRow added in v0.186.0

type WorkflowEventRow struct {
	Seq  int
	Line string
}

WorkflowEventRow is one line of the run's canonical event log. The log is a projection of the run, kept beside the state it describes so a resumed run's report and the trace bead (yaah-0u0v.17) read one sequence.

type WorkflowInstanceRow added in v0.186.0

type WorkflowInstanceRow struct {
	Path     string
	Owner    string
	BodyPath string
	Item     int
	Name     string
	Ordinal  int
	Payload  string
}

WorkflowInstanceRow is one body instance's identity: which container minted it, which body template it was copied from, and what its own scope bound.

type WorkflowNodeRow added in v0.186.0

type WorkflowNodeRow struct {
	Path    string
	Kind    string
	State   string
	Ordinal int
	Payload string
}

WorkflowNodeRow is one node's state. Ordinal preserves the scheduler's canonical result order — a top-level node followed by the instances its containers minted — because a resume must rebuild that order, not a map's.

type WorkflowRunRow added in v0.186.0

type WorkflowRunRow struct {
	RunID    string
	SpecHash string
	SpecPath string
	// GraphName is the document's metadata.name.
	GraphName string
	Status    string
	Reason    string
	// Dispatches and PeakInFlight are the run's tallies, so a resumed run keeps
	// spending the same budget.
	Dispatches   int
	PeakInFlight int
	// StartedAt and FinishedAt are unix nanoseconds; zero means unset.
	StartedAt  int64
	FinishedAt int64
	// Params and Ledger are JSON: the bound workflow parameters and the
	// proposal ledger (open/claims/settled).
	Params   string
	Ledger   string
	Warnings string
	// Seq is the last event sequence number the run wrote.
	Seq       int
	UpdatedAt int64
}

WorkflowRunRow is one run's own row: its identity, its document, and its disposition.

type WorkflowSettlementRow added in v0.186.0

type WorkflowSettlementRow struct {
	NodePath   string
	ProposalID string
	Producer   string
	Action     string
	Status     string
	RecordedAt int64
	Payload    string
}

WorkflowSettlementRow is one settlement disposition a settle node recorded. Status is the proposal runtime's own verdict — settled, conflict, or error — verbatim.

type WorkflowTraceRow added in v0.187.0

type WorkflowTraceRow struct {
	Seq      int
	EventSeq int
	Kind     string
	NodePath string
	Attempt  int
	Status   string
	Payload  string
}

WorkflowTraceRow is one typed trace record (yaah-0u0v.17). Seq is the record's own sequence number within the run, EventSeq the event log line it projects, and Kind, NodePath, Attempt and Status are columns because a trace reader filters on them ("every dispatch of this node", "every settle record") without decoding the payload.

Jump to

Keyboard shortcuts

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