Documentation
¶
Overview ¶
Package store implements the persistent memory engine for Engram.
It uses SQLite with FTS5 full-text search to store and retrieve observations from AI coding sessions. This is the core of Engram — everything else (HTTP server, MCP server, CLI, plugins) talks to this.
Index ¶
- Constants
- Variables
- func ClassifyTool(toolName string) string
- func ExtractLearnings(text string) []string
- func NormalizeProject(project string) (normalized string, warning string)
- func Now() string
- func SuggestTopicKey(typ, title, content string) string
- type AddObservationParams
- type AddPromptParams
- type Candidate
- type CandidateOptions
- type CloudUpgradeLegacyMutationFinding
- type CloudUpgradeLegacyMutationReport
- type CloudUpgradeRepairReport
- type CloudUpgradeSnapshot
- type CloudUpgradeState
- type Config
- type DeferredRow
- type DiagnosticSessionEvidence
- type EnrolledProject
- type ExportData
- type ImportResult
- type JudgeBySemanticParams
- type JudgeRelationParams
- type ListDeferredOptions
- type ListRelationsOptions
- type MergeResult
- type MigrateResult
- type Observation
- type ObservationRelations
- type ObservationSnippet
- type PassiveCaptureParams
- type PassiveCaptureResult
- type PendingSyncMutationProjectCount
- type ProjectNameCount
- type ProjectStats
- type Prompt
- type PruneResult
- type Relation
- type RelationListItem
- type RelationStats
- type ReplayDeferredResult
- type SQLiteLockSnapshot
- type SaveRelationParams
- type ScanOptions
- type ScanResult
- type SearchOptions
- type SearchResult
- type SemanticRunner
- type SemanticVerdict
- type Session
- type SessionProjectReclassification
- type SessionProjectReclassificationCounts
- type SessionProjectReclassificationResult
- type SessionSummary
- type Stats
- type Store
- func (s *Store) AckSyncMutationSeqs(targetKey string, seqs []int64) error
- func (s *Store) AckSyncMutations(targetKey string, lastAckedSeq int64) error
- func (s *Store) AcquireSyncLease(targetKey, owner string, ttl time.Duration, now time.Time) (bool, error)
- func (s *Store) AddObservation(p AddObservationParams) (int64, error)
- func (s *Store) AddPrompt(p AddPromptParams) (int64, error)
- func (s *Store) AllObservations(project, scope string, limit int) ([]Observation, error)
- func (s *Store) AllSessions(project string, limit int) ([]SessionSummary, error)
- func (s *Store) ApplyPulledChunk(targetKey, chunkID string, mutations []SyncMutation) error
- func (s *Store) ApplyPulledMutation(targetKey string, mutation SyncMutation) error
- func (s *Store) ApplySessionProjectReclassification(actions []SessionProjectReclassification) (SessionProjectReclassificationResult, error)
- func (s *Store) BackupSQLite() (string, error)
- func (s *Store) CanRollbackCloudUpgrade(project string) (bool, error)
- func (s *Store) ClearCloudUpgradeState(project string) error
- func (s *Store) Close() error
- func (s *Store) CountDeferredAndDead() (deferred, dead int, err error)
- func (s *Store) CountObservationsForProject(name string) (int, error)
- func (s *Store) CountPendingNonEnrolledSyncMutations(targetKey string) ([]PendingSyncMutationProjectCount, error)
- func (s *Store) CountRelationSyncMutations() (int, error)
- func (s *Store) CountRelations(opts ListRelationsOptions) (int, error)
- func (s *Store) CreateSession(id, project, directory string) error
- func (s *Store) DeleteObservation(id int64, hardDelete bool) error
- func (s *Store) DeletePrompt(id int64) error
- func (s *Store) DeleteSession(id string) error
- func (s *Store) DiagnoseCloudUpgradeLegacyMutations(project string) (CloudUpgradeLegacyMutationReport, error)
- func (s *Store) EndSession(id string, summary string) error
- func (s *Store) EnrollProject(project string) error
- func (s *Store) EstimateSessionProjectReclassification(actions []SessionProjectReclassification) (SessionProjectReclassificationCounts, error)
- func (s *Store) Export() (*ExportData, error)
- func (s *Store) ExportProject(project string) (*ExportData, error)
- func (s *Store) FindCandidates(savedID int64, opts CandidateOptions) ([]Candidate, error)
- func (s *Store) FormatContext(project, scope string) (string, error)
- func (s *Store) GetCloudUpgradeState(project string) (*CloudUpgradeState, error)
- func (s *Store) GetDeferred(syncID string) (DeferredRow, error)
- func (s *Store) GetObservation(id int64) (*Observation, error)
- func (s *Store) GetObservationBySyncID(syncID string) (*Observation, error)
- func (s *Store) GetRelation(syncID string) (*Relation, error)
- func (s *Store) GetRelationByIntID(id int64) (*RelationListItem, error)
- func (s *Store) GetRelationStats(project string) (RelationStats, error)
- func (s *Store) GetRelationsForObservations(syncIDs []string) (map[string]ObservationRelations, error)
- func (s *Store) GetSession(id string) (*Session, error)
- func (s *Store) GetSyncState(targetKey string) (*SyncState, error)
- func (s *Store) GetSyncedChunks() (map[string]bool, error)
- func (s *Store) GetSyncedChunksForTarget(targetKey string) (map[string]bool, error)
- func (s *Store) HasPendingSyncMutationsForProject(project string) (bool, error)
- func (s *Store) Import(data *ExportData) (*ImportResult, error)
- func (s *Store) IsProjectEnrolled(project string) (bool, error)
- func (s *Store) JudgeBySemantic(p JudgeBySemanticParams) (string, error)
- func (s *Store) JudgeRelation(p JudgeRelationParams) (*Relation, error)
- func (s *Store) ListDeferred(opts ListDeferredOptions) ([]DeferredRow, error)
- func (s *Store) ListDiagnosticSessions(project string) ([]DiagnosticSessionEvidence, error)
- func (s *Store) ListEnrolledProjects() ([]EnrolledProject, error)
- func (s *Store) ListObservationSyncPayloads() ([]any, error)
- func (s *Store) ListPendingProjectMutations(project string) ([]SyncMutation, error)
- func (s *Store) ListPendingSyncMutations(targetKey string, limit int) ([]SyncMutation, error)
- func (s *Store) ListPendingSyncMutationsAfterSeq(targetKey string, afterSeq int64, limit int) ([]SyncMutation, error)
- func (s *Store) ListProjectNames() ([]string, error)
- func (s *Store) ListProjectsWithStats() ([]ProjectStats, error)
- func (s *Store) ListRelations(opts ListRelationsOptions) ([]RelationListItem, error)
- func (s *Store) MarkSyncAuthRequired(targetKey, message string) error
- func (s *Store) MarkSyncBlocked(targetKey, reasonCode, message string) error
- func (s *Store) MarkSyncFailure(targetKey, message string, backoffUntil time.Time) error
- func (s *Store) MarkSyncHealthy(targetKey string) error
- func (s *Store) MarkSyncPaused(targetKey, message string) error
- func (s *Store) MarkSyncPending(targetKey string) error
- func (s *Store) MaxObservationLength() int
- func (s *Store) MergeProjects(sources []string, canonical string) (*MergeResult, error)
- func (s *Store) MigrateProject(oldName, newName string) (*MigrateResult, error)
- func (s *Store) PassiveCapture(p PassiveCaptureParams) (*PassiveCaptureResult, error)
- func (s *Store) ProjectExists(name string) (bool, error)
- func (s *Store) PruneProject(project string) (*PruneResult, error)
- func (s *Store) ReadSQLiteLockSnapshot(ctx context.Context) (SQLiteLockSnapshot, error)
- func (s *Store) RecentObservations(project, scope string, limit int) ([]Observation, error)
- func (s *Store) RecentPrompts(project string, limit int) ([]Prompt, error)
- func (s *Store) RecentSessions(project string, limit int) ([]SessionSummary, error)
- func (s *Store) RecordSyncedChunk(chunkID string) error
- func (s *Store) RecordSyncedChunkForTarget(targetKey, chunkID string) error
- func (s *Store) ReleaseSyncLease(targetKey, owner string) error
- func (s *Store) RepairCloudUpgrade(project string, apply bool) (CloudUpgradeRepairReport, error)
- func (s *Store) ReplayDeferred() (result ReplayDeferredResult, err error)
- func (s *Store) RollbackCloudUpgrade(project string) (CloudUpgradeState, error)
- func (s *Store) SaveCloudUpgradeState(state CloudUpgradeState) error
- func (s *Store) SaveRelation(p SaveRelationParams) (*Relation, error)
- func (s *Store) ScanProject(opts ScanOptions) (ScanResult, error)
- func (s *Store) Search(query string, opts SearchOptions) ([]SearchResult, error)
- func (s *Store) SearchPrompts(query string, project string, limit int) ([]Prompt, error)
- func (s *Store) SessionObservations(sessionID string, limit int) ([]Observation, error)
- func (s *Store) SkipAckNonEnrolledMutations(targetKey string) (int64, error)
- func (s *Store) Stats() (*Stats, error)
- func (s *Store) Timeline(observationID int64, before, after int) (*TimelineResult, error)
- func (s *Store) UnenrollProject(project string) error
- func (s *Store) UpdateObservation(id int64, p UpdateObservationParams) (*Observation, error)
- type SyncMutation
- type SyncMutationPayloadValidation
- type SyncState
- type TimelineEntry
- type TimelineResult
- type UpdateObservationParams
Constants ¶
const ( RelationPending = "pending" RelationRelated = "related" RelationCompatible = "compatible" RelationScoped = "scoped" RelationConflictsWith = "conflicts_with" RelationSupersedes = "supersedes" RelationNotConflict = "not_conflict" )
Valid relation type values. Type compatibility is NOT enforced in Phase 1; the agent does that judgment.
const ( JudgmentStatusPending = "pending" JudgmentStatusJudged = "judged" JudgmentStatusOrphaned = "orphaned" JudgmentStatusIgnored = "ignored" )
Valid judgment_status values.
const ( DefaultSyncTargetKey = "cloud" LocalChunkTargetKey = "local" SyncLifecycleIdle = "idle" SyncLifecyclePending = "pending" SyncLifecycleRunning = "running" SyncLifecycleHealthy = "healthy" SyncLifecycleDegraded = "degraded" SyncEntitySession = "session" SyncEntityObservation = "observation" SyncEntityPrompt = "prompt" SyncEntityRelation = "relation" SyncOpUpsert = "upsert" SyncOpDelete = "delete" SyncSourceLocal = "local" SyncSourceRemote = "remote" )
const ( UpgradeStagePlanned = "planned" UpgradeStageDoctorReady = "doctor_ready" UpgradeStageDoctorBlocked = "doctor_blocked" UpgradeStageRepairApplied = "repair_applied" UpgradeStageBootstrapEnrolled = "bootstrap_enrolled" UpgradeStageBootstrapPushed = "bootstrap_pushed" UpgradeStageBootstrapVerified = "bootstrap_verified" UpgradeStageRolledBack = "rolled_back" UpgradeRepairClassNone = "none" UpgradeRepairClassReady = "ready" UpgradeRepairClassRepairable = "repairable" UpgradeRepairClassBlocked = "blocked" UpgradeRepairClassPolicy = "policy" )
const ( UpgradeReasonRepairableLegacyMutationPayload = "upgrade_repairable_legacy_mutation_payload" UpgradeReasonBlockedLegacyMutationManual = "upgrade_blocked_legacy_mutation_manual" )
Variables ¶
var ( ErrSessionNotFound = errors.New("session not found") ErrSessionHasObservations = errors.New("session still has observations") ErrSessionDeleteBlocked = errors.New("session deletion is blocked while cloud sync enrollment is active") ErrObservationNotFound = errors.New("observation not found") ErrPromptNotFound = errors.New("prompt not found") )
Sentinel errors returned by delete operations so callers can use errors.Is.
var ( // ErrRelationFKMissing is returned by applyRelationUpsertTx when one or // both observations referenced by the relation payload do not exist locally // yet. The caller must write the mutation to sync_apply_deferred and ACK // the sequence so the cursor does not stall. ErrRelationFKMissing = errors.New("relation FK precondition not met: referenced observation missing") // ErrCrossProjectRelation is returned by JudgeRelation when the source and // target observations belong to different projects. The write is rejected // entirely; no memory_relations row is created and no sync mutation is // enqueued. ErrCrossProjectRelation = errors.New("relation rejected: source and target observations are in different projects") // ErrApplyDead is returned when a deferred relation payload cannot be // decoded or fails a hard validation. The row is written to // sync_apply_deferred with apply_status='dead' and is never retried // automatically; Phase 3 adds a republish CLI. ErrApplyDead = errors.New("relation apply permanently failed: payload invalid or undecodable") )
Sentinel errors for relation sync apply path (Phase 2).
var ErrSemanticPromptBuilderRequired = errors.New("semantic scan requires a non-nil BuildPrompt function")
ErrSemanticPromptBuilderRequired is returned by ScanProject when ScanOptions.Semantic is true but ScanOptions.BuildPrompt is nil.
var ErrSemanticRunnerRequired = errors.New("semantic scan requires a non-nil Runner")
ErrSemanticRunnerRequired is returned by ScanProject when ScanOptions.Semantic is true but ScanOptions.Runner is nil.
Functions ¶
func ClassifyTool ¶
ClassifyTool returns the observation type for a given tool name.
func ExtractLearnings ¶
ExtractLearnings parses structured learning items from text. It looks for sections like "## Key Learnings:" or "## Aprendizajes Clave:" and extracts numbered (1. text) or bullet (- text) items. Returns learnings from the LAST matching section (most recent output).
func NormalizeProject ¶ added in v1.11.0
NormalizeProject applies canonical project name normalization: lowercase + trim whitespace + collapse consecutive hyphens/underscores. Returns the normalized name and a warning message if the name was changed (empty string if no change was needed). Exported so MCP and CLI handlers can surface the warning to users.
func SuggestTopicKey ¶
SuggestTopicKey generates a stable topic key suggestion from type/title/content. It infers a topic family (e.g. architecture/*, bug/*) and then appends a normalized segment from title/content for stable cross-session keys.
Types ¶
type AddObservationParams ¶
type AddObservationParams struct {
SessionID string `json:"session_id"`
Type string `json:"type"`
Title string `json:"title"`
Content string `json:"content"`
ToolName string `json:"tool_name,omitempty"`
Project string `json:"project,omitempty"`
Scope string `json:"scope,omitempty"`
TopicKey string `json:"topic_key,omitempty"`
}
type AddPromptParams ¶
type Candidate ¶ added in v1.14.0
type Candidate struct {
// ID is the integer primary key of the candidate observation.
ID int64
// SyncID is the TEXT sync_id of the candidate observation.
SyncID string
// Title is the candidate's title.
Title string
// Type is the candidate's observation type.
Type string
// TopicKey is the candidate's topic_key (may be nil).
TopicKey *string
// Score is the FTS5 BM25 rank (negative; closer to 0 = better match).
Score float64
// JudgmentID is the sync_id of the pending memory_relations row created
// for this (source, candidate) pair.
JudgmentID string
}
Candidate represents a potential conflict candidate surfaced by FindCandidates.
type CandidateOptions ¶ added in v1.14.0
type CandidateOptions struct {
// Project filters candidates to the same project as the saved observation.
Project string
// Scope filters candidates to the same scope as the saved observation.
Scope string
// Type is reserved for Phase 2 type-compatibility filtering; NOT enforced Phase 1.
Type string
// Limit caps the number of candidates returned. Default 3 when nil or <=0.
Limit int
// BM25Floor is the minimum BM25 score (negative; closer to 0 = better match).
// Candidates below the floor are excluded. Default -2.0 when nil.
//
// Use a pointer so that an explicit 0.0 (very strict — nothing passes) is
// distinguishable from the zero value (which previously collided with the
// default sentinel). nil means "use the default (-2.0)".
BM25Floor *float64
// SkipInsert controls whether FindCandidates inserts pending relation rows.
// When true, candidates are returned but NO rows are written to memory_relations.
// Default false preserves the existing behavior (rows are inserted).
SkipInsert bool
}
CandidateOptions controls the FindCandidates query.
type CloudUpgradeLegacyMutationFinding ¶ added in v1.13.0
type CloudUpgradeLegacyMutationFinding struct {
Seq int64 `json:"seq"`
Entity string `json:"entity"`
Op string `json:"op"`
ReasonCode string `json:"reason_code"`
Message string `json:"message"`
Repairable bool `json:"repairable"`
RepairHint string `json:"repair_hint,omitempty"`
EntityKey string `json:"entity_key,omitempty"`
TargetKey string `json:"target_key,omitempty"`
Project string `json:"project,omitempty"`
}
type CloudUpgradeLegacyMutationReport ¶ added in v1.13.0
type CloudUpgradeLegacyMutationReport struct {
Project string `json:"project"`
RepairableCount int `json:"repairable_count"`
BlockedCount int `json:"blocked_count"`
Findings []CloudUpgradeLegacyMutationFinding `json:"findings,omitempty"`
}
type CloudUpgradeRepairReport ¶ added in v1.13.0
type CloudUpgradeSnapshot ¶ added in v1.13.0
type CloudUpgradeState ¶ added in v1.13.0
type CloudUpgradeState struct {
Project string `json:"project"`
Stage string `json:"stage"`
RepairClass string `json:"repair_class"`
Snapshot CloudUpgradeSnapshot `json:"snapshot"`
LastErrorCode string `json:"last_error_code,omitempty"`
LastErrorMessage string `json:"last_error_message,omitempty"`
FindingsJSON string `json:"findings_json,omitempty"`
AppliedActions string `json:"applied_actions,omitempty"`
UpdatedAt string `json:"updated_at"`
}
type Config ¶
type Config struct {
DataDir string
MaxObservationLength int
MaxContextResults int
MaxSearchResults int
DedupeWindow time.Duration
}
func DefaultConfig ¶
func FallbackConfig ¶ added in v1.9.3
FallbackConfig returns a Config with the given DataDir and default values. Use this when DefaultConfig fails and you have resolved the home directory through alternative means.
type DeferredRow ¶ added in v1.15.0
type DeferredRow struct {
SyncID string `json:"sync_id"`
Entity string `json:"entity"`
Payload map[string]any `json:"payload,omitempty"`
PayloadRaw string `json:"payload_raw"`
PayloadValid bool `json:"payload_valid"`
ApplyStatus string `json:"apply_status"`
RetryCount int `json:"retry_count"`
LastError *string `json:"last_error,omitempty"`
LastAttemptedAt *string `json:"last_attempted_at,omitempty"`
FirstSeenAt string `json:"first_seen_at"`
}
DeferredRow represents a row in sync_apply_deferred with the payload decoded.
type DiagnosticSessionEvidence ¶ added in v1.15.0
type DiagnosticSessionEvidence struct {
ID string `json:"id"`
Project string `json:"project"`
Directory string `json:"directory"`
Name string `json:"name"`
}
DiagnosticSessionEvidence is the read-only session projection used by operational diagnostics. It intentionally avoids observation/prompt payloads.
type EnrolledProject ¶ added in v1.8.0
type EnrolledProject struct {
Project string `json:"project"`
EnrolledAt string `json:"enrolled_at"`
}
EnrolledProject represents a project enrolled for cloud sync.
type ExportData ¶
type ExportData struct {
Version string `json:"version"`
ExportedAt string `json:"exported_at"`
Sessions []Session `json:"sessions"`
Observations []Observation `json:"observations"`
Prompts []Prompt `json:"prompts"`
}
ExportData is the full serializable dump of the engram database.
type ImportResult ¶
type JudgeBySemanticParams ¶ added in v1.15.0
type JudgeBySemanticParams struct {
// SourceID is the TEXT sync_id of the source observation (required).
SourceID string
// TargetID is the TEXT sync_id of the target observation (required).
TargetID string
// Relation is the verdict verb (required); must be in validRelationVerbs.
// Passing "not_conflict" is a no-op: no row is inserted and no error is returned.
Relation string
// Confidence is the LLM's self-reported confidence score [0.0, 1.0].
Confidence float64
// Reasoning is the LLM's short explanation.
Reasoning string
// Model is the LLM model identifier. Stored as marked_by_model.
Model string
}
JudgeBySemanticParams holds the inputs for JudgeBySemantic.
type JudgeRelationParams ¶ added in v1.14.0
type JudgeRelationParams struct {
// JudgmentID is the sync_id of the relation row to update (required).
JudgmentID string
// Relation is the verdict verb (required); must be one of validRelationVerbs.
Relation string
// Reason is an optional free-text explanation.
Reason *string
// Evidence is optional free-form JSON or text evidence.
Evidence *string
// Confidence is optional 0..1 confidence score.
Confidence *float64
// MarkedByActor is the actor identifier (e.g. "agent:claude-sonnet-4-6" or "user").
MarkedByActor string
// MarkedByKind is the actor kind ("agent", "human", "system").
MarkedByKind string
// MarkedByModel is the model ID (may be empty for human actors).
MarkedByModel string
// SessionID is the session in which the judgment was made (optional).
SessionID string
}
JudgeRelationParams holds the inputs for JudgeRelation.
type ListDeferredOptions ¶ added in v1.15.0
type ListDeferredOptions struct {
// Status filters by apply_status. Empty means no status filter.
Status string
// Limit caps the number of rows returned. 0 or negative means no limit.
Limit int
// Offset is the pagination offset.
Offset int
}
ListDeferredOptions controls ListDeferred queries.
type ListRelationsOptions ¶ added in v1.15.0
type ListRelationsOptions struct {
// Project filters by the project of the source OR target observation (via JOIN).
// Empty means no project filter (return all).
Project string
// Status filters by judgment_status. Empty means no status filter.
Status string
// SinceTime filters to rows created_at >= SinceTime. Zero value means no filter.
SinceTime time.Time
// Limit caps the number of rows returned. 0 or negative means no limit.
Limit int
// Offset is the pagination offset.
Offset int
}
ListRelationsOptions controls ListRelations and CountRelations queries.
type MergeResult ¶ added in v1.11.0
type MergeResult struct {
Canonical string `json:"canonical"`
SourcesMerged []string `json:"sources_merged"`
ObservationsUpdated int64 `json:"observations_updated"`
SessionsUpdated int64 `json:"sessions_updated"`
PromptsUpdated int64 `json:"prompts_updated"`
}
MergeResult summarizes the result of merging multiple project name variants into a single canonical project name.
type MigrateResult ¶ added in v1.10.0
type Observation ¶
type Observation struct {
ID int64 `json:"id"`
SyncID string `json:"sync_id"`
SessionID string `json:"session_id"`
Type string `json:"type"`
Title string `json:"title"`
Content string `json:"content"`
ToolName *string `json:"tool_name,omitempty"`
Project *string `json:"project,omitempty"`
Scope string `json:"scope"`
TopicKey *string `json:"topic_key,omitempty"`
RevisionCount int `json:"revision_count"`
DuplicateCount int `json:"duplicate_count"`
LastSeenAt *string `json:"last_seen_at,omitempty"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
DeletedAt *string `json:"deleted_at,omitempty"`
}
type ObservationRelations ¶ added in v1.14.0
type ObservationRelations struct {
// AsSource holds relations where this observation is source_id.
AsSource []Relation
// AsTarget holds relations where this observation is target_id.
AsTarget []Relation
}
ObservationRelations groups relations for a single observation, split by role.
type ObservationSnippet ¶ added in v1.15.0
ObservationSnippet carries the fields needed by BuildPrompt to construct an LLM comparison prompt without importing internal/llm from this package.
type PassiveCaptureParams ¶
type PassiveCaptureParams struct {
SessionID string `json:"session_id"`
Content string `json:"content"`
Project string `json:"project,omitempty"`
Source string `json:"source,omitempty"` // e.g. "subagent-stop", "session-end"
}
PassiveCaptureParams holds the input for passive memory capture.
type PassiveCaptureResult ¶
type PassiveCaptureResult struct {
Extracted int `json:"extracted"` // Total learnings found in text
Saved int `json:"saved"` // New observations created
Duplicates int `json:"duplicates"` // Skipped because already existed
}
PassiveCaptureResult holds the output of passive memory capture.
type PendingSyncMutationProjectCount ¶ added in v1.14.9
type ProjectNameCount ¶ added in v1.11.0
ProjectNameCount holds a project name and how many observations it has.
type ProjectStats ¶ added in v1.11.0
type ProjectStats struct {
Name string `json:"name"`
ObservationCount int `json:"observation_count"`
SessionCount int `json:"session_count"`
PromptCount int `json:"prompt_count"`
Directories []string `json:"directories"` // unique directories from sessions
}
ProjectStats holds aggregate statistics for a single project.
type PruneResult ¶ added in v1.11.0
type PruneResult struct {
Project string `json:"project"`
SessionsDeleted int64 `json:"sessions_deleted"`
PromptsDeleted int64 `json:"prompts_deleted"`
}
PruneResult holds the outcome of pruning a single project.
type Relation ¶ added in v1.14.0
type Relation struct {
ID int64 `json:"id"`
SyncID string `json:"sync_id"`
SourceID string `json:"source_id"`
TargetID string `json:"target_id"`
Relation string `json:"relation"`
Reason *string `json:"reason,omitempty"`
Evidence *string `json:"evidence,omitempty"`
Confidence *float64 `json:"confidence,omitempty"`
JudgmentStatus string `json:"judgment_status"`
MarkedByActor *string `json:"marked_by_actor,omitempty"`
MarkedByKind *string `json:"marked_by_kind,omitempty"`
MarkedByModel *string `json:"marked_by_model,omitempty"`
SessionID *string `json:"session_id,omitempty"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
// Annotation fields — populated by GetRelationsForObservations via LEFT JOIN.
// Excluded from JSON output (used only for in-process annotation building).
// REQ-005, REQ-012 | Design §7, §8.
SourceIntID int64 `json:"-"` // integer primary key of source observation
SourceTitle string `json:"-"` // title of source observation; empty if missing/deleted
SourceMissing bool `json:"-"` // true if source is soft-deleted or not found
TargetIntID int64 `json:"-"` // integer primary key of target observation
TargetTitle string `json:"-"` // title of target observation; empty if missing/deleted
TargetMissing bool `json:"-"` // true if target is soft-deleted or not found
}
Relation represents a row in memory_relations.
type RelationListItem ¶ added in v1.15.0
type RelationListItem struct {
ID int64 `json:"id"`
SyncID string `json:"sync_id"`
Relation string `json:"relation"`
JudgmentStatus string `json:"judgment_status"`
SourceID string `json:"source_id"`
SourceTitle string `json:"source_title"`
TargetID string `json:"target_id"`
TargetTitle string `json:"target_title"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
RelationListItem represents a single row in a ListRelations result, enriched with observation titles via JOIN (no full Relation struct).
type RelationStats ¶ added in v1.15.0
type RelationStats struct {
Project string `json:"project"`
ByRelation map[string]int `json:"by_relation"`
ByJudgmentStatus map[string]int `json:"by_judgment_status"`
DeferredCount int `json:"deferred"`
DeadCount int `json:"dead"`
}
RelationStats holds aggregate counts of relations for a project.
type ReplayDeferredResult ¶ added in v1.15.0
ReplayDeferredResult holds counts returned by ReplayDeferred.
type SQLiteLockSnapshot ¶ added in v1.15.0
type SQLiteLockSnapshot struct {
JournalMode string `json:"journal_mode"`
BusyTimeoutMS int `json:"busy_timeout_ms"`
CheckpointBusy int `json:"checkpoint_busy"`
CheckpointLog int `json:"checkpoint_log"`
CheckpointedFrames int `json:"checkpointed_frames"`
}
SQLiteLockSnapshot captures conservative SQLite lock/contention indicators. wal_checkpoint(PASSIVE) is an observational probe for this diagnostic surface; callers must not interpret it as a repair action.
type SaveRelationParams ¶ added in v1.14.0
type SaveRelationParams struct {
// SyncID is the unique identifier for this relation row (format: rel-<16hex>).
SyncID string
// SourceID is the TEXT sync_id of the source observation.
SourceID string
// TargetID is the TEXT sync_id of the target observation.
TargetID string
}
SaveRelationParams holds the inputs for SaveRelation.
type ScanOptions ¶ added in v1.15.0
type ScanOptions struct {
// Project is required — scopes the observation walk.
Project string
// Since filters observations to created_at >= Since. Zero value means no filter.
Since time.Time
// Apply controls whether new relation rows are inserted.
// When false (dry-run, default), candidates are reported but not written.
Apply bool
// MaxInsert caps the number of new relation rows inserted in a single Apply run.
// Default 100 when 0 or negative.
MaxInsert int
// Semantic controls whether the worker pool LLM-judge step runs.
// When false (default), ScanProject behaves exactly as Phase 3.
Semantic bool
// Concurrency is the worker pool size for semantic calls. Default 5 if 0.
Concurrency int
// TimeoutPerCall is the per-pair context timeout for runner.Compare.
// Default 60s if zero.
TimeoutPerCall time.Duration
// MaxSemantic caps the number of LLM calls in a single semantic scan. Default 100 if 0.
MaxSemantic int
// Runner is the SemanticRunner used for LLM comparison. Required when Semantic=true.
Runner SemanticRunner
// BuildPrompt constructs the LLM prompt for a given (a, b) pair.
// Required when Semantic=true.
BuildPrompt func(a, b ObservationSnippet) string
}
ScanOptions controls a ScanProject call.
type ScanResult ¶ added in v1.15.0
type ScanResult struct {
Project string `json:"project"`
Inspected int `json:"inspected"`
CandidatesFound int `json:"candidates_found"`
AlreadyRelated int `json:"already_related"`
RelationsInserted int `json:"inserted"`
Capped bool `json:"capped"`
DryRun bool `json:"dry_run"`
// Semantic counters — populated only when ScanOptions.Semantic is true.
// Zero-value is safe for existing JSON consumers.
SemanticJudged int `json:"semantic_judged"`
SemanticSkipped int `json:"semantic_skipped"`
SemanticErrors int `json:"semantic_errors"`
}
ScanResult holds the output of a ScanProject call.
type SearchOptions ¶
type SearchResult ¶
type SearchResult struct {
Observation
Rank float64 `json:"rank"`
}
type SemanticRunner ¶ added in v1.15.0
type SemanticRunner interface {
Compare(ctx context.Context, prompt string) (SemanticVerdict, error)
}
SemanticRunner is a duck-typed interface satisfied by *llm.ClaudeRunner and *llm.OpenCodeRunner without requiring this package to import internal/llm. Any value whose Compare method matches this signature satisfies the interface.
type SemanticVerdict ¶ added in v1.15.0
type SemanticVerdict struct {
// Relation is one of: conflicts_with, supersedes, scoped, related, compatible, not_conflict.
Relation string
// Confidence is a 0.0–1.0 score from the runner.
Confidence float64
// Reasoning is a short human-readable explanation (≤200 chars).
Reasoning string
// Model is the model identifier reported by the CLI (e.g. "claude-haiku-4-5").
Model string
// DurationMS is wall-clock time for the CLI invocation in milliseconds.
DurationMS int64
}
SemanticVerdict is the result of a semantic comparison between two observations. It mirrors llm.Verdict but lives in this package to avoid a store→llm import cycle.
type SessionProjectReclassification ¶ added in v1.15.0
type SessionProjectReclassificationCounts ¶ added in v1.15.0
type SessionProjectReclassificationResult ¶ added in v1.15.0
type SessionProjectReclassificationResult struct {
Counts SessionProjectReclassificationCounts
BackupPath string
}
type SessionSummary ¶
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
func (*Store) AckSyncMutationSeqs ¶ added in v1.8.0
AckSyncMutationSeqs acknowledges specific mutation sequence numbers without requiring them to be contiguous.
func (*Store) AckSyncMutations ¶ added in v1.8.0
func (*Store) AcquireSyncLease ¶ added in v1.8.0
func (*Store) AddObservation ¶
func (s *Store) AddObservation(p AddObservationParams) (int64, error)
func (*Store) AllObservations ¶
func (s *Store) AllObservations(project, scope string, limit int) ([]Observation, error)
AllObservations returns recent observations ordered by most recent first (for TUI browsing).
func (*Store) AllSessions ¶
func (s *Store) AllSessions(project string, limit int) ([]SessionSummary, error)
AllSessions returns recent sessions ordered by most recent first (for TUI browsing).
func (*Store) ApplyPulledChunk ¶ added in v1.13.0
func (s *Store) ApplyPulledChunk(targetKey, chunkID string, mutations []SyncMutation) error
ApplyPulledChunk atomically applies all mutations contained in a pulled chunk and records the chunk as synced in the same transaction. This guarantees retry safety: a failed chunk import leaves no partial semantic mutations.
func (*Store) ApplyPulledMutation ¶ added in v1.8.0
func (s *Store) ApplyPulledMutation(targetKey string, mutation SyncMutation) error
func (*Store) ApplySessionProjectReclassification ¶ added in v1.15.0
func (s *Store) ApplySessionProjectReclassification(actions []SessionProjectReclassification) (SessionProjectReclassificationResult, error)
func (*Store) BackupSQLite ¶ added in v1.15.0
func (*Store) CanRollbackCloudUpgrade ¶ added in v1.13.0
func (*Store) ClearCloudUpgradeState ¶ added in v1.13.0
func (*Store) CountDeferredAndDead ¶ added in v1.15.0
CountDeferredAndDead returns the count of rows in sync_apply_deferred grouped by apply_status. Only 'deferred' and 'dead' statuses are counted; 'applied' rows (if any) are not included.
func (*Store) CountObservationsForProject ¶ added in v1.11.0
CountObservationsForProject returns the number of non-deleted observations for the given project name. Used by handleSave for the similar-project warning instead of the heavier ListProjectsWithStats.
func (*Store) CountPendingNonEnrolledSyncMutations ¶ added in v1.14.9
func (s *Store) CountPendingNonEnrolledSyncMutations(targetKey string) ([]PendingSyncMutationProjectCount, error)
func (*Store) CountRelationSyncMutations ¶ added in v1.14.0
CountRelationSyncMutations returns the number of sync_mutations rows whose entity is NOT 'session', 'observation', or 'prompt' — i.e., any entity that would indicate memory_relations data leaking into sync. Used by integration tests to assert that relation operations never enqueue sync mutations (REQ-009).
In Phase 1, only 'session', 'observation', and 'prompt' are valid entities. Any other entity (e.g. 'relation', 'memory_relation') would be a regression.
func (*Store) CountRelations ¶ added in v1.15.0
func (s *Store) CountRelations(opts ListRelationsOptions) (int, error)
CountRelations returns the total number of relation rows matching opts. Uses the same WHERE conditions as ListRelations.
func (*Store) CreateSession ¶
func (*Store) DeleteObservation ¶
func (*Store) DeletePrompt ¶ added in v1.12.0
DeletePrompt hard-deletes a single prompt by ID and records a sync tombstone. It returns ErrPromptNotFound if no prompt with that ID exists.
func (*Store) DeleteSession ¶ added in v1.12.0
DeleteSession hard-deletes a session and its prompts. It returns ErrSessionHasObservations if the session has any observations (including soft-deleted ones) to prevent orphaned rows. It returns ErrSessionNotFound if no session with that ID exists.
When the session belongs to an enrolled project, this operation also enqueues a session/delete mutation so cloud replicas can remove the session.
func (*Store) DiagnoseCloudUpgradeLegacyMutations ¶ added in v1.13.0
func (s *Store) DiagnoseCloudUpgradeLegacyMutations(project string) (CloudUpgradeLegacyMutationReport, error)
func (*Store) EnrollProject ¶ added in v1.8.0
EnrollProject registers a project for cloud sync. Idempotent — re-enrolling an already-enrolled project is a no-op.
func (*Store) EstimateSessionProjectReclassification ¶ added in v1.15.0
func (s *Store) EstimateSessionProjectReclassification(actions []SessionProjectReclassification) (SessionProjectReclassificationCounts, error)
func (*Store) Export ¶
func (s *Store) Export() (*ExportData, error)
func (*Store) ExportProject ¶ added in v1.13.0
func (s *Store) ExportProject(project string) (*ExportData, error)
ExportProject returns an export restricted to records relevant to a single normalized project. This avoids full-database exports when only one project needs to sync.
func (*Store) FindCandidates ¶ added in v1.14.0
func (s *Store) FindCandidates(savedID int64, opts CandidateOptions) ([]Candidate, error)
FindCandidates runs a post-transaction FTS5 candidate query for the given savedID and returns at most opts.Limit candidates above the BM25 floor.
For each candidate, a pending memory_relations row is inserted and the row's sync_id is exposed as Candidate.JudgmentID.
Errors from this method are expected to be logged and swallowed by callers — detection failure must never fail the originating save.
func (*Store) GetCloudUpgradeState ¶ added in v1.13.0
func (s *Store) GetCloudUpgradeState(project string) (*CloudUpgradeState, error)
func (*Store) GetDeferred ¶ added in v1.15.0
func (s *Store) GetDeferred(syncID string) (DeferredRow, error)
GetDeferred returns a single row from sync_apply_deferred by sync_id. Returns an error wrapping "not found" when no row exists (matches FindCandidates style).
func (*Store) GetObservation ¶
func (s *Store) GetObservation(id int64) (*Observation, error)
func (*Store) GetObservationBySyncID ¶ added in v1.8.0
func (s *Store) GetObservationBySyncID(syncID string) (*Observation, error)
func (*Store) GetRelation ¶ added in v1.14.0
GetRelation retrieves a single relation row by its sync_id.
func (*Store) GetRelationByIntID ¶ added in v1.15.0
func (s *Store) GetRelationByIntID(id int64) (*RelationListItem, error)
GetRelationByIntID retrieves a single relation enriched with source/target observation titles by its integer primary key. Returns a *RelationListItem (same shape as ListRelations rows) so HTTP handlers share one response type. Returns an error wrapping "not found" when the id does not exist.
func (*Store) GetRelationStats ¶ added in v1.15.0
func (s *Store) GetRelationStats(project string) (RelationStats, error)
GetRelationStats returns aggregate counts for a project's relations plus the deferred and dead queue totals. Two queries are executed: one GROUP BY and one delegated to CountDeferredAndDead.
func (*Store) GetRelationsForObservations ¶ added in v1.14.0
func (s *Store) GetRelationsForObservations(syncIDs []string) (map[string]ObservationRelations, error)
GetRelationsForObservations returns a map of observation sync_id → ObservationRelations for all observations in syncIDs. Relations with judgment_status='orphaned' are excluded.
A single SQL query with IN/OR and LEFT JOINs avoids N+1 queries. The returned Relation values are enriched with source/target integer IDs and titles via LEFT JOIN, used by the MCP annotation builder (REQ-005, REQ-012). Missing or soft-deleted observations set the corresponding *Missing flag to true.
func (*Store) GetSyncState ¶ added in v1.8.0
func (*Store) GetSyncedChunks ¶
GetSyncedChunks returns local-target chunk IDs for backwards compatibility.
func (*Store) GetSyncedChunksForTarget ¶ added in v1.13.0
GetSyncedChunksForTarget returns chunk IDs tracked for a specific sync target.
func (*Store) HasPendingSyncMutationsForProject ¶ added in v1.13.0
func (*Store) Import ¶
func (s *Store) Import(data *ExportData) (*ImportResult, error)
func (*Store) IsProjectEnrolled ¶ added in v1.8.0
IsProjectEnrolled returns true if the given project is enrolled for cloud sync.
func (*Store) JudgeBySemantic ¶ added in v1.15.0
func (s *Store) JudgeBySemantic(p JudgeBySemanticParams) (string, error)
JudgeBySemantic persists a semantic verdict produced by an AgentRunner into the memory_relations table with system provenance (marked_by_kind="system", marked_by_actor="engram", marked_by_model=params.Model).
When params.Relation is "not_conflict" the call is a no-op: no row is inserted and an empty sync_id is returned without error.
Idempotency: if a row already exists for (source_id, target_id) in either direction, the existing row is updated (UPSERT). The returned sync_id is always the canonical row's sync_id.
Returns ErrCrossProjectRelation when source and target belong to different projects. Returns a validation error when required fields are missing or Confidence is out of [0.0, 1.0].
func (*Store) JudgeRelation ¶ added in v1.14.0
func (s *Store) JudgeRelation(p JudgeRelationParams) (*Relation, error)
JudgeRelation records a verdict on an existing pending relation row.
Re-judge policy: OVERWRITE the existing row (design decision). The updated row is returned on success.
Phase 2: wraps the UPDATE in a transaction to atomically enqueue a sync mutation when the source observation's project is enrolled for cloud sync. Returns ErrCrossProjectRelation if source and target belong to different projects.
Returns an error if the judgment_id is unknown or the relation verb is invalid.
func (*Store) ListDeferred ¶ added in v1.15.0
func (s *Store) ListDeferred(opts ListDeferredOptions) ([]DeferredRow, error)
ListDeferred returns rows from sync_apply_deferred with optional status filter and pagination. The payload field is decoded to map[string]any; on malformed JSON, PayloadValid is false and PayloadRaw is preserved.
func (*Store) ListDiagnosticSessions ¶ added in v1.15.0
func (s *Store) ListDiagnosticSessions(project string) ([]DiagnosticSessionEvidence, error)
ListDiagnosticSessions returns session evidence scoped by project when provided. The query is read-only and ordered for deterministic diagnostics.
func (*Store) ListEnrolledProjects ¶ added in v1.8.0
func (s *Store) ListEnrolledProjects() ([]EnrolledProject, error)
ListEnrolledProjects returns all projects currently enrolled for cloud sync, ordered alphabetically by project name.
func (*Store) ListObservationSyncPayloads ¶ added in v1.14.0
ListObservationSyncPayloads returns the decoded payloads of all sync_mutations rows whose entity = 'observation'. Used by integration tests to assert that new observation columns (review_after, expires_at, embedding*) are NOT present in the sync wire format in Phase 1 (REQ-009).
func (*Store) ListPendingProjectMutations ¶ added in v1.15.0
func (s *Store) ListPendingProjectMutations(project string) ([]SyncMutation, error)
ListPendingProjectMutations returns pending cloud mutations for one project, or all projects when project is empty, without enrollment filtering. Doctor needs to diagnose blocked metadata even when a project is not enrolled.
func (*Store) ListPendingSyncMutations ¶ added in v1.8.0
func (s *Store) ListPendingSyncMutations(targetKey string, limit int) ([]SyncMutation, error)
func (*Store) ListPendingSyncMutationsAfterSeq ¶ added in v1.13.0
func (*Store) ListProjectNames ¶ added in v1.11.0
ListProjectNames returns all distinct project names from observations, ordered alphabetically. Used for fuzzy matching and consolidation.
func (*Store) ListProjectsWithStats ¶ added in v1.11.0
func (s *Store) ListProjectsWithStats() ([]ProjectStats, error)
ListProjectsWithStats returns all projects with aggregated counts. Ordered by observation count descending.
func (*Store) ListRelations ¶ added in v1.15.0
func (s *Store) ListRelations(opts ListRelationsOptions) ([]RelationListItem, error)
ListRelations returns a paginated list of relation rows filtered by the given options. Project filtering is done via LEFT JOIN to observations (no schema change). Uses idx_memrel_status_created for efficient status+date ordering.
func (*Store) MarkSyncAuthRequired ¶ added in v1.13.0
func (*Store) MarkSyncBlocked ¶ added in v1.13.0
func (*Store) MarkSyncFailure ¶ added in v1.8.0
func (*Store) MarkSyncHealthy ¶ added in v1.8.0
func (*Store) MarkSyncPaused ¶ added in v1.13.0
func (*Store) MarkSyncPending ¶ added in v1.13.0
func (*Store) MaxObservationLength ¶ added in v1.8.1
MaxObservationLength returns the configured maximum content length for observations.
func (*Store) MergeProjects ¶ added in v1.11.0
func (s *Store) MergeProjects(sources []string, canonical string) (*MergeResult, error)
MergeProjects migrates all records from each source project name into the canonical name. Sources that equal the canonical (after normalization) or have no records are silently skipped — the operation is idempotent. All updates are performed inside a single transaction for atomicity.
func (*Store) MigrateProject ¶ added in v1.10.0
func (s *Store) MigrateProject(oldName, newName string) (*MigrateResult, error)
func (*Store) PassiveCapture ¶
func (s *Store) PassiveCapture(p PassiveCaptureParams) (*PassiveCaptureResult, error)
PassiveCapture extracts learnings from text and saves them as observations. It deduplicates against existing observations using content hash matching.
func (*Store) ProjectExists ¶ added in v1.13.0
ProjectExists returns true if the named project has at least one record in any of observations, sessions, prompts, or enrollment tables. Uses a single UNION ALL LIMIT 1 query for efficiency (REQ-315). The sync_enrolled_projects branch ensures a project enrolled via EnrollProject() without any other data is still recognized (JC1).
func (*Store) PruneProject ¶ added in v1.11.0
func (s *Store) PruneProject(project string) (*PruneResult, error)
PruneProject removes all sessions and prompts for a project that has zero (non-deleted) observations. Returns an error if the project still has observations — the caller must verify first.
func (*Store) ReadSQLiteLockSnapshot ¶ added in v1.15.0
func (s *Store) ReadSQLiteLockSnapshot(ctx context.Context) (SQLiteLockSnapshot, error)
ReadSQLiteLockSnapshot returns SQLite lock-related PRAGMA values without starting an application write transaction.
func (*Store) RecentObservations ¶
func (s *Store) RecentObservations(project, scope string, limit int) ([]Observation, error)
func (*Store) RecentPrompts ¶
func (*Store) RecentSessions ¶
func (s *Store) RecentSessions(project string, limit int) ([]SessionSummary, error)
func (*Store) RecordSyncedChunk ¶
RecordSyncedChunk marks a local-target chunk as imported/exported.
func (*Store) RecordSyncedChunkForTarget ¶ added in v1.13.0
RecordSyncedChunkForTarget marks a chunk as imported/exported for a target.
func (*Store) ReleaseSyncLease ¶ added in v1.8.0
func (*Store) RepairCloudUpgrade ¶ added in v1.13.0
func (s *Store) RepairCloudUpgrade(project string, apply bool) (CloudUpgradeRepairReport, error)
func (*Store) ReplayDeferred ¶ added in v1.15.0
func (s *Store) ReplayDeferred() (result ReplayDeferredResult, err error)
ReplayDeferred retries all rows in sync_apply_deferred with apply_status='deferred' (up to 50 per call, ordered by first_seen_at). For each row:
- Calls applyPulledMutationTx inside a transaction.
- On success: the apply itself deletes the deferred row (applyRelationUpsertTx already includes DELETE FROM sync_apply_deferred on success path).
- On ErrRelationFKMissing: increments retry_count; if retry_count reaches 5, marks apply_status='dead'. Otherwise updates last_error + last_attempted_at.
- On ErrApplyDead or other decode errors: marks apply_status='dead'.
Dead rows are never retried. Idempotent: calling twice in one cycle does not double-retry because successful rows are deleted and failed rows update retry_count in place.
Returns counts (retried, succeeded, failed, dead) for caller logging.
func (*Store) RollbackCloudUpgrade ¶ added in v1.13.0
func (s *Store) RollbackCloudUpgrade(project string) (CloudUpgradeState, error)
func (*Store) SaveCloudUpgradeState ¶ added in v1.13.0
func (s *Store) SaveCloudUpgradeState(state CloudUpgradeState) error
func (*Store) SaveRelation ¶ added in v1.14.0
func (s *Store) SaveRelation(p SaveRelationParams) (*Relation, error)
SaveRelation inserts a new pending relation row. The SyncID field must be unique (enforced by the UNIQUE constraint on memory_relations.sync_id).
func (*Store) ScanProject ¶ added in v1.15.0
func (s *Store) ScanProject(opts ScanOptions) (ScanResult, error)
ScanProject walks all observations in the given project (filtered by Since) and for each observation calls FindCandidates with SkipInsert=true. If Apply is true and below MaxInsert cap, each new candidate pair is inserted as a pending relation (after a pre-check to skip already-related pairs).
Phase 4 extension: when ScanOptions.Semantic is true, after the FTS5 candidate collection a bounded worker pool calls Runner.Compare on each pair and persists non-"not_conflict" verdicts via JudgeBySemantic. Semantic=false (zero value) preserves Phase 3 behaviour exactly.
Returns a ScanResult with counts of inspected observations, candidates found, already-related pairs skipped, relations inserted, and whether the cap was hit.
func (*Store) Search ¶
func (s *Store) Search(query string, opts SearchOptions) ([]SearchResult, error)
func (*Store) SearchPrompts ¶
func (*Store) SessionObservations ¶
func (s *Store) SessionObservations(sessionID string, limit int) ([]Observation, error)
SessionObservations returns all observations for a specific session.
func (*Store) SkipAckNonEnrolledMutations ¶ added in v1.8.0
SkipAckNonEnrolledMutations acks (marks as skipped) all pending mutations that belong to non-enrolled projects, preventing journal bloat. Empty-project mutations are never skipped — they always sync regardless of enrollment.
func (*Store) Timeline ¶
func (s *Store) Timeline(observationID int64, before, after int) (*TimelineResult, error)
func (*Store) UnenrollProject ¶ added in v1.8.0
UnenrollProject removes a project from cloud sync enrollment. Idempotent — unenrolling a non-enrolled project is a no-op.
func (*Store) UpdateObservation ¶
func (s *Store) UpdateObservation(id int64, p UpdateObservationParams) (*Observation, error)
type SyncMutation ¶ added in v1.8.0
type SyncMutation struct {
Seq int64 `json:"seq"`
TargetKey string `json:"target_key"`
Entity string `json:"entity"`
EntityKey string `json:"entity_key"`
Op string `json:"op"`
Payload string `json:"payload"`
Source string `json:"source"`
Project string `json:"project"`
OccurredAt string `json:"occurred_at"`
AckedAt *string `json:"acked_at,omitempty"`
}
type SyncMutationPayloadValidation ¶ added in v1.15.0
type SyncMutationPayloadValidation struct {
Entity string `json:"entity"`
Op string `json:"op"`
EntityKey string `json:"entity_key,omitempty"`
MissingFields []string `json:"missing_fields,omitempty"`
ReasonCode string `json:"reason_code,omitempty"`
Message string `json:"message,omitempty"`
}
SyncMutationPayloadValidation describes deterministic required-field issues in a pending sync mutation payload.
func ValidateSyncMutationPayload ¶ added in v1.15.0
func ValidateSyncMutationPayload(entity, op, payload, entityKey string) SyncMutationPayloadValidation
ValidateSyncMutationPayload performs pure required-field validation for sync payloads. It is intentionally conservative: malformed/empty/unsupported payloads are reported as manual blocks, while complete payloads return an empty validation.
type SyncState ¶ added in v1.8.0
type SyncState struct {
TargetKey string `json:"target_key"`
Lifecycle string `json:"lifecycle"`
LastEnqueuedSeq int64 `json:"last_enqueued_seq"`
LastAckedSeq int64 `json:"last_acked_seq"`
LastPulledSeq int64 `json:"last_pulled_seq"`
ConsecutiveFailures int `json:"consecutive_failures"`
BackoffUntil *string `json:"backoff_until,omitempty"`
LeaseOwner *string `json:"lease_owner,omitempty"`
LeaseUntil *string `json:"lease_until,omitempty"`
ReasonCode *string `json:"reason_code,omitempty"`
ReasonMessage *string `json:"reason_message,omitempty"`
LastError *string `json:"last_error,omitempty"`
UpdatedAt string `json:"updated_at"`
}
type TimelineEntry ¶
type TimelineEntry struct {
ID int64 `json:"id"`
SessionID string `json:"session_id"`
Type string `json:"type"`
Title string `json:"title"`
Content string `json:"content"`
ToolName *string `json:"tool_name,omitempty"`
Project *string `json:"project,omitempty"`
Scope string `json:"scope"`
TopicKey *string `json:"topic_key,omitempty"`
RevisionCount int `json:"revision_count"`
DuplicateCount int `json:"duplicate_count"`
LastSeenAt *string `json:"last_seen_at,omitempty"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
DeletedAt *string `json:"deleted_at,omitempty"`
IsFocus bool `json:"is_focus"` // true for the anchor observation
}
type TimelineResult ¶
type TimelineResult struct {
Focus Observation `json:"focus"` // The anchor observation
Before []TimelineEntry `json:"before"` // Observations before the focus (chronological)
After []TimelineEntry `json:"after"` // Observations after the focus (chronological)
SessionInfo *Session `json:"session_info"` // Session that contains the focus observation
TotalInRange int `json:"total_in_range"`
}