store

package
v0.8.18 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2026 License: MIT Imports: 32 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

Index

Constants

View Source
const (
	AuditIdentityMaxCount = 100_000
	AuditFeedMaxCount     = 10_001
)
View Source
const (
	FeedHealthOK      = "ok"
	FeedHealthError   = "error"
	FeedHealthBlocked = "blocked"
	FeedHealthDead    = "dead"
)
View Source
const (
	RetrievalSegmentTarget    = 5_000
	RetrievalSegmentHardLimit = 10_000
)
View Source
const (
	MaxRetrievalProjectionChunks      = 50_000
	MaxRetrievalProjectionOccurrences = 200_000
	MaxRetrievalProjectionStagedBytes = 128 << 20
)
View Source
const (
	ReviewEventKindItemImported         = "item_imported"
	ReviewEventKindItemUpdated          = "item_updated"
	ReviewEventKindSourceCreated        = "source_created"
	ReviewEventKindSourceExtracted      = "source_extracted"
	ReviewEventKindSourceSummarized     = "source_summarized"
	ReviewEventKindItemSummarized       = "item_summarized"
	ReviewEventKindXMediaTranscribed    = "x_media_transcribed"
	ReviewEventKindXPhotoOCRed          = "x_photo_ocred"
	ReviewEventKindSourceFailed         = "source_failed"
	ReviewEventKindItemEnrichmentFailed = "item_enrichment_failed"
	ReviewEventKindBlocked              = "blocked"
)
View Source
const (
	ReviewActionabilityReview     = "review"
	ReviewActionabilityBackground = "background"
	ReviewActionabilityBlocked    = "blocked"
	ReviewActionabilityFailure    = "failure"
)
View Source
const (
	ReviewEventViewEvents   = "events"
	ReviewEventViewEntities = "entities"
)
View Source
const InteractivePoolSize = 4

InteractivePoolSize is the shared pool size for live web and MCP consumers.

View Source
const LinkCaptureAdmissionBusyTimeout = 2 * time.Second

LinkCaptureAdmissionBusyTimeout is the effective lock-wait budget for the deferred link admission connection. The modernc SQLite driver may report a context error only after its busy handler has waited, so callers should use this value when they need a bounded admission request.

View Source
const (
	MaxLinkCaptureAttempts = 8
)
View Source
const MaxRetrievalNativeCandidates = 190

MaxRetrievalNativeCandidates keeps the five-column request CTE below the conservative SQLite 999-bind-variable floor (190 * 5 + two root facts).

View Source
const (
	// PipelineKindAll identifies the aggregate row returned before grouped
	// pipeline rows. Consumers must not present it as an ordinary kind.
	PipelineKindAll = "ALL"
)

Variables

View Source
var (
	ErrRetrievalPurgeEpochChanged        = errors.New("retrieval purge epoch changed")
	ErrRetrievalEmbeddingProfileNotFound = errors.New("retrieval embedding profile not found")
)
View Source
var (
	ErrRetrievalUnavailable              = errors.New("retrieval storage is unavailable")
	ErrRetrievalEmbeddingNoLongerCorrupt = errors.New("retrieval embedding is no longer corrupt")
)
View Source
var ErrDatabaseIncompatible = errors.New("database is incompatible")

ErrDatabaseIncompatible marks an observed dbrain schema or migration identity incompatibility. Ordinary open, descriptor, I/O, and availability failures deliberately do not wrap this sentinel.

View Source
var ErrItemNotFound = errors.New("item not found")
View Source
var ErrMastodonSyncStateChanged = errors.New("mastodon sync state changed during write")
View Source
var ErrRetrievalGenerationActivationStale = errors.New("retrieval generation activation expectations changed")
View Source
var ErrRetrievalGenerationMembershipUnproven = errors.New("retrieval generation membership provenance is unavailable")
View Source
var ErrSemanticRefreshRunStale = errors.New("semantic refresh run changed")

Functions

func EncodeReviewCursor added in v0.2.22

func EncodeReviewCursor(cursor ReviewCursor) (string, error)

func GenerateMCPBearerToken added in v0.2.5

func GenerateMCPBearerToken() (string, error)

func HashMCPBearerToken added in v0.2.5

func HashMCPBearerToken(token string) string

func MarkRetrievalParentDirtyTx added in v0.8.0

func MarkRetrievalParentDirtyTx(ctx context.Context, tx *sql.Tx, kind, sourceKey string) (int64, error)

MarkRetrievalParentDirtyTx allocates a durable work revision in the caller's transaction. Active segmented generations remain usable while projection and embedding work moves changed vectors through the exact L0 tail. Authoritative item, source, and enrichment writes are covered independently by database triggers; callers should use this named seam only when they need the allocated revision without performing such a write.

func NormalizeGitHubUsername added in v0.2.5

func NormalizeGitHubUsername(username string) string

NormalizeGitHubUsername returns the case-insensitive GitHub login key used for auth lookups.

func NormalizeReviewEventTypes added in v0.2.22

func NormalizeReviewEventTypes(values []string) ([]string, error)

func NormalizeReviewEventView added in v0.2.22

func NormalizeReviewEventView(value string) (string, error)

func ValidateRestorableDatabase added in v0.6.0

func ValidateRestorableDatabase(ctx context.Context, path string) error

ValidateRestorableDatabase verifies that path is a compatible dbrain store without creating, migrating, or otherwise modifying it.

Types

type ActivityStats

type ActivityStats struct {
	Now                       time.Time `json:"now"`
	Window                    string    `json:"window"`
	LatestItemUpdatedAt       time.Time `json:"latest_item_updated_at"`
	LatestSourceUpdatedAt     time.Time `json:"latest_source_updated_at"`
	LatestSourceSummaryAt     time.Time `json:"latest_source_summary_at"`
	ItemsUpdatedInWindow      int       `json:"items_updated_in_window"`
	SourcesUpdatedInWindow    int       `json:"sources_updated_in_window"`
	SourcesSummarizedInWindow int       `json:"sources_summarized_in_window"`
}

type ApplyRetrievalProjectionInput added in v0.8.0

type ApplyRetrievalProjectionInput struct {
	ParentKind         string
	ParentSourceKey    string
	DirtyRevision      int64
	ExpectedPurgeEpoch int64
	Projection         retrievalchunk.Projection
	Status             RetrievalProjectionStatus
	Reason             string
}

type AuditArchivedMediaRecord added in v0.7.0

type AuditArchivedMediaRecord struct {
	Key             string
	SizeBytes       int64
	ArchivedAt      time.Time
	ArchivedAtValid bool
}

type AuditLocalIdentifierRow added in v0.7.0

type AuditLocalIdentifierRow struct {
	RowID     int64
	SourceKey string
}

AuditLocalIdentifierRow is app-only diagnostic evidence. It is intentionally excluded from the portable audit report schema.

type AuditMediaLocalEvidence added in v0.7.0

type AuditMediaLocalEvidence struct {
	EligibleLocalCount   int
	UncoveredPrunedCount int
	OrphanCount          int
}

type AuditPipelinePartitions added in v0.7.0

type AuditPipelinePartitions struct {
	Hydration     []PipelineStageRow
	Extraction    []PipelineStageRow
	Summary       []PipelineStageRow
	Transcription []PipelineStageRow
	OCR           []PipelineStageRow
	MediaArchive  []PipelineStageRow
}

type AuditProvenanceEvidence added in v0.7.0

type AuditProvenanceEvidence struct {
	CheckID                 string
	SuccessfulCount         int
	CompleteCount           int
	LegacyMissingCount      int
	PostCutoverMissingCount int
	CutoverAt               time.Time
	CutoverKnown            bool
	MissingByField          map[string]int
}

type AuditReadSnapshot added in v0.7.0

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

func (*AuditReadSnapshot) ArchivedMediaRecords added in v0.7.0

func (s *AuditReadSnapshot) ArchivedMediaRecords(ctx context.Context) ([]AuditArchivedMediaRecord, error)

func (*AuditReadSnapshot) Close added in v0.7.0

func (s *AuditReadSnapshot) Close() error

func (*AuditReadSnapshot) CountLocalIdentityMatches added in v0.7.0

func (s *AuditReadSnapshot) CountLocalIdentityMatches(ctx context.Context, source AuditSource, hashes []string) (int, error)

CountLocalIdentityMatches counts unique requested hashes represented by the query-only snapshot. Validation happens before selecting the fixed query, and local rows are streamed and hashed in Go; no 100,000-placeholder SQL is built.

func (*AuditReadSnapshot) ListEnabledFeedsForAudit added in v0.7.0

func (s *AuditReadSnapshot) ListEnabledFeedsForAudit(ctx context.Context) ([]Feed, error)

ListEnabledFeedsForAudit returns the minimal configured-feed projection needed by the upstream parity adapter. The fixed cap includes one sentinel row so the adapter can distinguish a complete 10,000-feed inventory from an over-budget one without opening another database connection.

func (*AuditReadSnapshot) LocalIdentifierRows added in v0.7.0

func (s *AuditReadSnapshot) LocalIdentifierRows(ctx context.Context, checkID string, limit int) ([]AuditLocalIdentifierRow, error)

LocalIdentifierRows returns identifiers only for a closed set of fixed, read-only audit queries. Callers cannot supply SQL or cleanup paths.

func (*AuditReadSnapshot) MediaLocalEvidence added in v0.7.0

func (s *AuditReadSnapshot) MediaLocalEvidence(ctx context.Context) (AuditMediaLocalEvidence, error)

func (*AuditReadSnapshot) PipelinePartitions added in v0.7.0

func (s *AuditReadSnapshot) PipelinePartitions(ctx context.Context) (AuditPipelinePartitions, error)

func (*AuditReadSnapshot) Provenance added in v0.7.0

func (*AuditReadSnapshot) SemanticRuntimeReadinessSnapshotAt added in v0.8.8

func (s *AuditReadSnapshot) SemanticRuntimeReadinessSnapshotAt(ctx context.Context, profile embedding.Profile, exactMaxChunks int, now time.Time) (semanticreadiness.Snapshot, error)

SemanticRuntimeReadinessSnapshotAt reads the same bounded admission facts from the query-only transaction already owned by the audit. It does not create a nested transaction or widen the snapshot beyond semantic runtime counters and the active-generation catalog proof.

type AuditSource added in v0.7.0

type AuditSource string

AuditSource is a store-owned closed enum. Its values are the fixed local source_type populations used for parity matching; callers cannot provide a table, column, or predicate.

const (
	AuditSourceAppleNotes        AuditSource = "apple_note"
	AuditSourceSafariTabs        AuditSource = "safari_tab"
	AuditSourceXBookmarks        AuditSource = "x_bookmark"
	AuditSourceGitHubStars       AuditSource = "github_star"
	AuditSourceYouTubeLiked      AuditSource = "youtube_liked"
	AuditSourceYouTubeWatchLater AuditSource = "youtube_watch_later"
	AuditSourceFeeds             AuditSource = "feed_entry"
)

type AuthUser added in v0.2.5

type AuthUser struct {
	ID                       int64
	Provider                 string
	GitHubID                 string
	GitHubUsername           string
	GitHubUsernameNormalized string
	Email                    string
	Name                     string
	AvatarURL                string
	ApprovedAt               string
	LastLoginAt              string
	CreatedAt                string
	UpdatedAt                string
}

type AuthoritativeWriteWaitEvent added in v0.8.17

type AuthoritativeWriteWaitEvent struct {
	Metadata string
	Wait     time.Duration
	Outcome  string
}

AuthoritativeWriteWaitEvent reports the time spent waiting for the shared semantic maintenance lease before an authoritative write transaction.

type AuthoritativeWriteWaitObserver added in v0.8.17

type AuthoritativeWriteWaitObserver func(AuthoritativeWriteWaitEvent)

type BacklogStats

type BacklogStats struct {
	XHydrationPending             int           `json:"x_hydration_pending"`
	LinkDiscoveryPending          int           `json:"link_discovery_pending"`
	SourceExtractionPending       int           `json:"source_extraction_pending"`
	SourceSummaryPending          int           `json:"source_summary_pending"`
	SourceExtractionPendingByType []CountBucket `json:"source_extraction_pending_by_type"`
	SourceSummaryPendingByType    []CountBucket `json:"source_summary_pending_by_type"`
	Drained                       bool          `json:"drained"`
}

type ChunkReplaceResult added in v0.8.0

type ChunkReplaceResult struct {
	Created int `json:"created"`
	Reused  int `json:"reused"`
	Updated int `json:"updated"`
	Deleted int `json:"deleted"`
}

type CompleteRetrievalIndexGenerationInput added in v0.8.0

type CompleteRetrievalIndexGenerationInput struct {
	Generation                                                           RetrievalIndexGenerationRow
	Segments                                                             []RetrievalIndexSegmentRow
	Members                                                              []RetrievalIndexSegmentMember
	SnapshotRevision, ExpectedPurgeEpoch, ExpectedActiveSnapshotRevision int64
	ExpectedActiveGenerationID                                           string
	ActivationMode                                                       RetrievalGenerationActivationMode
}

type CountBucket

type CountBucket struct {
	Key   string `json:"key"`
	Count int    `json:"count"`
}

type DatabaseIntegrity added in v0.7.0

type DatabaseIntegrity struct {
	QuickCheckChecked        bool   `json:"quick_check_checked"`
	QuickCheck               string `json:"quick_check,omitempty"`
	QuickViolationCount      int    `json:"quick_violation_count"`
	ForeignKeyViolationCount int    `json:"foreign_key_violation_count"`
	SchemaCompatibility      string `json:"schema_compatibility"`
	MigrationCompatibility   string `json:"migration_compatibility"`
	UserVersion              int    `json:"user_version"`
	SupportedVersion         int    `json:"supported_version"`
	AppliedMigrationCount    int    `json:"applied_migration_count"`
	MissingTableCount        int    `json:"missing_table_count"`
	MissingColumnCount       int    `json:"missing_column_count"`
	// contains filtered or unexported fields
}

func InspectDatabaseReadOnly added in v0.7.0

func InspectDatabaseReadOnly(ctx context.Context, path string, includeIntegrity bool) (DatabaseIntegrity, error)

type DeleteItemsResult

type DeleteItemsResult struct {
	Count     int      `json:"count"`
	NotePaths []string `json:"note_paths"`
	SourceIDs []int64  `json:"source_ids"`
}

type DeleteSourcesResult

type DeleteSourcesResult struct {
	Count     int      `json:"count"`
	NotePaths []string `json:"note_paths"`
}

type Feed added in v0.1.6

type Feed struct {
	ID                   int64
	FeedKey              string
	URL                  string
	NormalizedURL        string
	ResolvedURL          string
	SiteURL              string
	Title                string
	Description          string
	Language             string
	Enabled              bool
	HealthStatus         string
	PollIntervalSeconds  int
	NextFetchAfter       time.Time
	FetchETag            string
	FetchLastModified    string
	FetchBodyHash        string
	LastCheckedAt        time.Time
	LastFetchedAt        time.Time
	LastChangedAt        time.Time
	LastSuccessAt        time.Time
	FailureKind          string
	FirstFailedAt        time.Time
	LastFailedAt         time.Time
	LastHTTPStatus       int
	LastError            string
	ErrorCount           int
	LatestNormalizedJSON string
	UserTags             string
	CreatedAt            time.Time
	UpdatedAt            time.Time
}

type FeedEntry added in v0.1.6

type FeedEntry struct {
	FeedID          int64
	EntryKey        string
	IdentityKey     string
	GUID            string
	GUIDIsPermalink bool
	Link            string
	NormalizedLink  string
	Title           string
	Author          string
	PublishedAt     string
	EntryUpdatedAt  string
	SummaryHTML     string
	SummaryText     string
	ContentHTML     string
	ContentMarkdown string
	ContentText     string
	EnclosuresJSON  string
	ExtensionsJSON  string
	RawJSON         string
	ContentHash     string
	Item            model.Item
	SourceCandidate *model.SourceCandidate
	ObservedAt      time.Time
}

type FeedEntryApplyResult added in v0.1.6

type FeedEntryApplyResult struct {
	FeedEntryID      int64
	ItemID           int64
	SourceID         int64
	Created          bool
	Updated          bool
	Unchanged        bool
	Version          int
	SourceLinked     bool
	SourceCreated    bool
	IdentityConflict bool
}

type FeedFailureState added in v0.1.6

type FeedFailureState struct {
	FeedID         int64
	HealthStatus   string
	FailureKind    string
	LastHTTPStatus int
	Error          string
	FailedAt       time.Time
	NextFetchAfter time.Time
}

type FeedFetchRecord added in v0.1.6

type FeedFetchRecord struct {
	FeedID            int64
	ObservedAt        time.Time
	RequestURL        string
	FinalURL          string
	HTTPStatus        int
	HeadersJSON       string
	ContentEncoding   string
	DecodedBodyHash   string
	WireResponseBytes []byte
	DecodedSizeBytes  int64
	ParseStatus       string
	ParseError        string
}

type FeedFetchState added in v0.1.6

type FeedFetchState struct {
	FeedID               int64
	ResolvedURL          string
	Title                string
	SiteURL              string
	Description          string
	Language             string
	FetchETag            string
	FetchLastModified    string
	FetchBodyHash        string
	LatestNormalizedJSON string
	CheckedAt            time.Time
	FetchedAt            time.Time
	Changed              bool
	NextFetchAfter       time.Time
}

type FeedUpsert added in v0.1.6

type FeedUpsert struct {
	FeedKey             string
	URL                 string
	NormalizedURL       string
	ResolvedURL         string
	Title               string
	SiteURL             string
	Description         string
	Language            string
	PollIntervalSeconds int
	Enabled             bool
	UserTags            string
}

type FeedUpsertResult added in v0.1.6

type FeedUpsertResult struct {
	FeedID  int64
	Created bool
}

type GitHubAuthProfile added in v0.2.5

type GitHubAuthProfile struct {
	GitHubID       string
	GitHubUsername string
	Email          string
	Name           string
	AvatarURL      string
}

type LinkCapture added in v0.8.17

type LinkCapture struct {
	ID             int64
	Candidate      model.SourceCandidate
	EnqueuedAt     time.Time
	UpdatedAt      time.Time
	LastAttemptAt  time.Time
	NextAttemptAt  time.Time
	ProcessedAt    time.Time
	DeadLetteredAt time.Time
	AttemptCount   int
	LastError      string
}

LinkCapture is the durable, pre-authoritative intake record for a deferred link save. It is intentionally separate from sources: source mutations still cross the authoritative semantic maintenance lease when the worker drains it.

type LinkCaptureEnqueueResult added in v0.8.17

type LinkCaptureEnqueueResult struct {
	Capture  LinkCapture
	Created  bool
	Reopened bool
}

type MCPBearerToken added in v0.2.5

type MCPBearerToken struct {
	ID               int64  `json:"id"`
	Name             string `json:"name"`
	TokenFingerprint string `json:"token_fingerprint"`
	RevokedAt        string `json:"revoked_at,omitempty"`
	CreatedAt        string `json:"created_at"`
	UpdatedAt        string `json:"updated_at"`
}

type MCPBearerTokenCreateResult added in v0.2.5

type MCPBearerTokenCreateResult struct {
	Token  string         `json:"token"`
	Record MCPBearerToken `json:"record"`
}

type MastodonSyncState added in v0.8.12

type MastodonSyncState struct {
	AccountKey          string
	CanonicalOrigin     string
	VerifiedAccountID   string
	Handle              string
	BackfillNextURL     string
	BackfillComplete    bool
	BackfillIncremental bool
	BackfillPageURL     string
	BackfillPageDigest  string
	BackfillPageOffset  int
	LastPageURL         string
	LastPageDigest      string
	CapabilitiesJSON    string
	LastSuccessAt       time.Time
	LastErrorAt         time.Time
	LastError           string
}

type MigrationEvent

type MigrationEvent struct {
	Phase         MigrationPhase
	Version       int
	LatestVersion int
	Name          string
	Err           error
}

MigrationEvent describes one schema migration lifecycle event.

type MigrationPhase

type MigrationPhase string

MigrationPhase identifies the lifecycle state for a migration event.

const (
	// MigrationStarted is emitted before a missing migration starts running.
	MigrationStarted MigrationPhase = "started"
	// MigrationApplied is emitted after a missing migration has been applied and recorded.
	MigrationApplied MigrationPhase = "applied"
	// MigrationFailed is emitted when a missing migration or its metadata write fails.
	MigrationFailed MigrationPhase = "failed"
)

type MigrationReporter

type MigrationReporter func(MigrationEvent)

MigrationReporter receives migration lifecycle events during writable startup.

type OKFExportOptions added in v0.2.17

type OKFExportOptions struct {
	IncludeItems   bool
	IncludeSources bool
	SourceTypes    []string
	Limit          int
}

OKFExportOptions controls a read-only snapshot used by the OKF projection.

type OKFExportSnapshot added in v0.2.17

type OKFExportSnapshot struct {
	Items           []model.Item                     `json:"items"`
	Sources         []model.SourceDocument           `json:"sources"`
	ItemSources     map[int64][]model.ItemSourceRef  `json:"item_sources"`
	SourceBacklinks map[int64][]model.SourceBacklink `json:"source_backlinks"`
	ItemMedia       map[int64][]model.ItemMediaRef   `json:"item_media"`
	ItemChildren    map[int64][]model.SourceBacklink `json:"item_children"`
}

OKFExportSnapshot is a consistent SQLite view used by the OKF exporter.

type OpenOptions

type OpenOptions struct {
	MigrationReporter          MigrationReporter
	SemanticCacheDir           string
	MaxOpenConns               int
	MaxIdleConns               int
	AuthoritativeWriteObserver AuthoritativeWriteWaitObserver
}

OpenOptions configures writable store startup behavior.

type PipelineStageRow

type PipelineStageRow struct {
	Kind               string    `json:"kind"`
	Total              int       `json:"total"`
	Current            int       `json:"current"`
	Pending            int       `json:"pending"`
	Blocked            int       `json:"blocked"`
	Terminal           int       `json:"terminal"`
	Failed             int       `json:"failed"`
	Unknown            int       `json:"unknown"`
	PartitionValid     bool      `json:"partition_valid"`
	PercentCurrent     float64   `json:"percent_current"`
	OldestPendingAt    time.Time `json:"-"`
	OldestPendingKnown bool      `json:"-"`
}

type PipelineStats

type PipelineStats struct {
	SummaryPromptVersion string             `json:"summary_prompt_version"`
	SummaryTool          string             `json:"summary_tool"`
	SummaryToolVersion   string             `json:"summary_tool_version"`
	Hydration            []PipelineStageRow `json:"hydration"`
	Extraction           []PipelineStageRow `json:"extraction"`
	Summary              []PipelineStageRow `json:"summary"`
	Transcription        []PipelineStageRow `json:"transcription"`
	OCR                  []PipelineStageRow `json:"ocr"`
	MediaArchive         []PipelineStageRow `json:"media_archive"`
}

type PoolStats added in v0.8.17

type PoolStats struct {
	MaxOpenConnections int
	OpenConnections    int
	InUse              int
	Idle               int
	WaitCount          int64
	WaitDuration       time.Duration
}

PoolStats is a point-in-time snapshot of the store's database/sql pool. WaitCount and WaitDuration are cumulative since the pool was opened; the connection counts describe the pool at the time of the snapshot.

type PrunedMediaRepairCandidates added in v0.7.1

type PrunedMediaRepairCandidates struct {
	OCRItemIDs        []int64
	TranscriptItemIDs []int64
}

type PublicChatShare added in v0.2.6

type PublicChatShare struct {
	Slug             string
	OwnerProvider    string
	OwnerSubject     string
	OwnerUsername    string
	ContentHash      string
	Title            string
	Summary          string
	Categories       []string
	SanitizedContent string
	OriginalURLs     []string
	MetadataJSON     string
	CreatedAt        time.Time
	UpdatedAt        time.Time
}

type PublicChatShareInput added in v0.2.6

type PublicChatShareInput struct {
	OwnerProvider    string
	OwnerSubject     string
	OwnerUsername    string
	Title            string
	Summary          string
	Categories       []string
	SanitizedContent string
	OriginalURLs     []string
	MetadataJSON     string
}

type PutRetrievalEmbeddingBatchInput added in v0.8.0

type PutRetrievalEmbeddingBatchInput struct {
	Profile            embedding.Profile
	Rows               []RetrievalEmbeddingRow
	ExpectedPurgeEpoch int64
}

type RebuildFTSStats

type RebuildFTSStats struct {
	Rebuilt int
	Skipped int
	Errors  int
}

type ResetSourceEnrichmentOptions

type ResetSourceEnrichmentOptions struct {
	Domains            []string
	SourceIDs          []int64
	SourceTypes        []string
	ExtractStatuses    []string
	SummaryStatuses    []string
	FailureKinds       []string
	MinFailures        int
	RehydrateXArticles bool
	DryRun             bool
}

type ResetSourceEnrichmentStats

type ResetSourceEnrichmentStats struct {
	Matched       int  `json:"matched"`
	Reset         int  `json:"reset"`
	XItemsMatched int  `json:"x_items_matched,omitempty"`
	XItemsReset   int  `json:"x_items_reset,omitempty"`
	DryRun        bool `json:"dry_run"`
}

type RetrievalActiveRootReadRequest added in v0.8.0

type RetrievalActiveRootReadRequest struct {
	ProfileID, ExpectedActiveGenerationID              string
	ExpectedPurgeEpoch, ExpectedActiveSnapshotRevision int64
}

RetrievalActiveRootReadRequest pins a read to the active root facts observed before opening a derived native root.

type RetrievalActiveSegmentCompactionSegment added in v0.8.0

type RetrievalActiveSegmentCompactionSegment struct {
	RetrievalIndexSegmentRow
	CreatedOrder              int64
	LiveCount, TombstoneCount int
}

RetrievalActiveSegmentCompactionSegment combines an immutable segment catalog entry with its current authoritative membership state. CreatedOrder is one-based and stable for a given root: segment creation timestamp first, then content-addressed segment hash.

type RetrievalActiveSegmentCompactionSnapshot added in v0.8.0

type RetrievalActiveSegmentCompactionSnapshot struct {
	Profile  RetrievalEmbeddingProfileRow
	Segments []RetrievalActiveSegmentCompactionSegment
}

RetrievalActiveSegmentCompactionSnapshot is the immutable active-root input for compaction planning. It contains no vector payloads and makes no change to SQLite or cache state.

type RetrievalActiveSegmentMember added in v0.8.0

type RetrievalActiveSegmentMember struct {
	SegmentHash string
	Ordinal     uint64
	Embedding   RetrievalEmbeddingRow
}

RetrievalActiveSegmentMember is one current, live immutable membership and its authoritative embedding. Source ordinal is retained so callers can reproduce deterministic input order while assigning new segment ordinals.

type RetrievalActiveSegmentMemberStreamRequest added in v0.8.0

type RetrievalActiveSegmentMemberStreamRequest struct {
	ProfileID, ExpectedActiveGenerationID              string
	ExpectedPurgeEpoch, ExpectedActiveSnapshotRevision int64
	SegmentHashes                                      []string
}

RetrievalActiveSegmentMemberStreamRequest identifies the one or two active segments selected by a compaction plan, together with the root CAS facts observed while planning. The stream rechecks all of these facts before it reads vector bytes.

type RetrievalActiveSegmentMemberVisitor added in v0.8.0

type RetrievalActiveSegmentMemberVisitor func(RetrievalActiveSegmentMember) error

RetrievalActiveSegmentMemberVisitor consumes one stream row synchronously. It must not call this Store or mutate SQLite while the stream is active.

type RetrievalChunkEvidenceRow added in v0.8.0

type RetrievalChunkEvidenceRow struct {
	ChunkID         string
	ParentKind      string
	ParentSourceKey string
	EvidenceRole    string
	Ordinal         int
	StartChar       int
	EndChar         int
	Heading         string
	ChunkTextHash   string
	Text            string
	Title           string
	URL             string
	NotePath        string
	Summary         string
	Author          string
	SourceType      string
	PublishedAt     string
	ExtractedAt     string
	SummarizedAt    string
	UserTags        string
}

RetrievalChunkEvidenceRow hydrates a chunk with its current parent evidence. Parents whose rendered note has been purged are deliberately absent.

type RetrievalChunkProfileMismatchError added in v0.8.0

type RetrievalChunkProfileMismatchError struct {
	ProjectionVersion string
	ChunkerVersion    string
	Count             int
}

func (*RetrievalChunkProfileMismatchError) Error added in v0.8.0

type RetrievalChunkRow added in v0.8.0

type RetrievalChunkRow struct {
	ChunkID           string
	ParentKind        string
	ParentSourceKey   string
	EvidenceRole      string
	SectionOrdinal    int
	Ordinal           int
	StartChar         int
	EndChar           int
	Heading           string
	ProjectionVersion string
	ChunkerVersion    string
	InputContentHash  string
	ChunkTextHash     string
	Text              string
	// AttemptCount is populated by embedding candidate selectors. Ordinary
	// chunk reads leave it zero.
	AttemptCount int
}

type RetrievalDanglingGenerationRecovery added in v0.8.6

type RetrievalDanglingGenerationRecovery struct {
	ProfileID, GenerationID, DescriptorSHA256, BackendVersion string
	SnapshotRevision, PurgeEpoch                              int64
	Dimensions, IndexedChunkCount                             int
}

RetrievalDanglingGenerationRecovery describes a profile root that is still the authoritative profile pointer but was incorrectly marked stale and inactive by the pre-v29 projection dirty triggers.

type RetrievalEmbeddingCorruptionError added in v0.8.0

type RetrievalEmbeddingCorruptionError struct {
	ChunkID   string
	ProfileID string
	Reason    string
}

func (*RetrievalEmbeddingCorruptionError) Error added in v0.8.0

type RetrievalEmbeddingProfileRow added in v0.8.0

type RetrievalEmbeddingProfileRow struct {
	ProfileID, ActiveGenerationID                          string
	LatestRevision, PurgeEpoch, ActiveSnapshotRevision     int64
	ActiveIndexedCount, L0ReadyCount, ActiveTombstoneCount int
}

type RetrievalEmbeddingRow added in v0.8.0

type RetrievalEmbeddingRow struct {
	ChunkID           string
	ProfileID         string
	Provider          string
	Model             string
	Dimensions        int
	Representation    string
	Normalization     string
	VectorBytes       []byte
	VectorHash        string
	ChunkTextHash     string
	Revision          int64
	Status            RetrievalEmbeddingStatus
	AttemptCount      int
	LastError         string
	NextAttemptAt     time.Time
	EmbeddedAt        time.Time
	ParentKind        string
	ParentSourceKey   string
	EvidenceRole      string
	SourceType        string
	SectionOrdinal    int
	Text              string
	ProjectionVersion string
	ChunkerVersion    string
}

type RetrievalEmbeddingStatus added in v0.8.0

type RetrievalEmbeddingStatus string
const (
	RetrievalEmbeddingPending RetrievalEmbeddingStatus = "pending"
	RetrievalEmbeddingReady   RetrievalEmbeddingStatus = "ready"
	RetrievalEmbeddingBlocked RetrievalEmbeddingStatus = "blocked"
	RetrievalEmbeddingError   RetrievalEmbeddingStatus = "error"
)

type RetrievalEmbeddingVerificationState added in v0.8.0

type RetrievalEmbeddingVerificationState struct {
	ProfileID, ActiveGenerationID                                         string
	Profile                                                               embedding.Profile
	LatestRevision, PurgeEpoch, GlobalPurgeEpoch, ActiveSnapshotRevision  int64
	ActiveIndexedCount, L0ReadyCount, ActiveTombstoneCount                int
	GenerationBackend, GenerationBackendVersion, GenerationDistanceMetric string
	GenerationStatus                                                      RetrievalGenerationStatus
	GenerationDimensions, GenerationIndexedChunkCount                     int
	GenerationActive                                                      bool
}

type RetrievalFlushWindow added in v0.8.0

type RetrievalFlushWindow struct {
	Profile          RetrievalEmbeddingProfileRow
	Rows             []RetrievalEmbeddingRow
	SnapshotRevision int64
}

type RetrievalGenerationActivationMode added in v0.8.0

type RetrievalGenerationActivationMode string
const (
	RetrievalGenerationAdvanceSnapshot RetrievalGenerationActivationMode = "advance_snapshot"
	RetrievalGenerationRewriteSnapshot RetrievalGenerationActivationMode = "rewrite_snapshot"
)

type RetrievalGenerationStatus added in v0.8.0

type RetrievalGenerationStatus string
const (
	RetrievalGenerationBuilding  RetrievalGenerationStatus = "building"
	RetrievalGenerationCompleted RetrievalGenerationStatus = "completed"
	RetrievalGenerationStale     RetrievalGenerationStatus = "stale"
	RetrievalGenerationError     RetrievalGenerationStatus = "error"
)

type RetrievalIndexGenerationRow added in v0.8.0

type RetrievalIndexGenerationRow struct {
	GenerationID       string
	ProfileID          string
	Backend            string
	BackendVersion     string
	Dimensions         int
	DistanceMetric     string
	IndexedChunkCount  int
	SourceManifestHash string
	BuildStatus        RetrievalGenerationStatus
	BuildError         string
	RelativeCachePath  string
	BuildStartedAt     time.Time
	BuildCompletedAt   time.Time
	ActivatedAt        time.Time
	Active             bool
}

type RetrievalIndexSegmentMember added in v0.8.0

type RetrievalIndexSegmentMember struct {
	SegmentHash, ChunkID, VectorHash string
	Ordinal                          uint64
	Revision                         int64
}

type RetrievalIndexSegmentRow added in v0.8.0

type RetrievalIndexSegmentRow struct {
	SegmentHash, ProfileID, Backend, BackendVersion, DistanceMetric, RelativeCachePath string
	Dimensions, IndexedChunkCount                                                      int
	MembershipHash, PayloadHash, ManifestHash                                          string
}

type RetrievalNativeCandidate added in v0.8.0

type RetrievalNativeCandidate struct {
	SegmentHash, ChunkID, VectorHash string
	Revision                         int64
}

RetrievalNativeCandidate is an immutable ANN-manifest member selected by a native index. It is not evidence until ReadRetrievalNativeCandidates proves that it still belongs to the active SQLite root and current ready embedding.

type RetrievalNativeCandidateRequest added in v0.8.0

type RetrievalNativeCandidateRequest struct {
	ProfileID, ExpectedActiveGenerationID              string
	ExpectedPurgeEpoch, ExpectedActiveSnapshotRevision int64
	Candidates                                         []RetrievalNativeCandidate
}

RetrievalNativeCandidateRequest binds approximate candidates to the active root facts observed while opening the native root. The read fails closed when those facts changed; stale members are simply omitted from its result.

type RetrievalNativeReadSession added in v0.8.0

type RetrievalNativeReadSession interface {
	ReadRetrievalNativeCandidates(context.Context, RetrievalNativeCandidateRequest) ([]RetrievalEmbeddingRow, error)
	ReadRetrievalExactL0(context.Context, RetrievalActiveRootReadRequest, int) ([]RetrievalEmbeddingRow, error)
	Close() error
}

RetrievalNativeReadSession keeps every authority read for one native search on a single SQLite snapshot. It is deliberately query-only: the native index remains derived data and SQLite remains the authority for both active root validation and exact L0 rows.

type RetrievalParentWork added in v0.8.0

type RetrievalParentWork struct {
	Parent        retrievalchunk.Parent
	DirtyRevision int64
}

type RetrievalProjectionCheckpoint added in v0.8.0

type RetrievalProjectionCheckpoint struct {
	WorkID             string `json:"work_id"`
	DirtyRevision      int64  `json:"dirty_revision"`
	ExpectedPurgeEpoch int64  `json:"expected_purge_epoch"`
	ParentKind         string `json:"parent_kind"`
	ParentSourceKey    string `json:"parent_source_key"`
	ProjectionHash     string `json:"projection_hash"`
	SectionKey         string `json:"section_key"`
	NextBoundary       int    `json:"next_boundary"`
	StagedChunks       int    `json:"staged_chunks"`
	StagedOccurrences  int    `json:"staged_occurrences"`
	StagedBytes        int64  `json:"staged_bytes"`
	PreparedPlan       string `json:"-"`
}

type RetrievalProjectionStageRow added in v0.8.0

type RetrievalProjectionStageRow struct {
	Chunk      retrievalchunk.Chunk
	Occurrence retrievalchunk.Occurrence
}

type RetrievalProjectionStaleWorkError added in v0.8.0

type RetrievalProjectionStaleWorkError struct {
	ParentKind       string
	ParentSourceKey  string
	SelectedRevision int64
	CurrentRevision  int64
	Reason           string
}

RetrievalProjectionStaleWorkError reports a projection result that no longer matches the durable parent work item. Callers may discard it; the current dirty state is deliberately left untouched.

func (*RetrievalProjectionStaleWorkError) Error added in v0.8.0

type RetrievalProjectionStatus added in v0.8.0

type RetrievalProjectionStatus string
const (
	RetrievalProjectionPending RetrievalProjectionStatus = "pending"
	RetrievalProjectionCurrent RetrievalProjectionStatus = "current"
	RetrievalProjectionEmpty   RetrievalProjectionStatus = "empty"
	RetrievalProjectionBlocked RetrievalProjectionStatus = "blocked"
	RetrievalProjectionError   RetrievalProjectionStatus = "error"
)

type RetrievalProjectionTooLargeError added in v0.8.0

type RetrievalProjectionTooLargeError struct {
	ChunkCount      int
	OccurrenceCount int
	ByteCount       int64
	Limit           int
}

func (*RetrievalProjectionTooLargeError) Error added in v0.8.0

type RetrievalSemanticGCArtifact added in v0.8.11

type RetrievalSemanticGCArtifact struct {
	ID                string    `json:"id"`
	ProfileID         string    `json:"profile_id"`
	RelativeCachePath string    `json:"relative_cache_path"`
	CreatedAt         time.Time `json:"created_at"`
	UpdatedAt         time.Time `json:"updated_at"`
}

type RetrievalSemanticGCOptions added in v0.8.11

type RetrievalSemanticGCOptions struct {
	Now             time.Time
	GracePeriod     time.Duration
	RetainPublished int
}

type RetrievalSemanticGCPlan added in v0.8.11

type RetrievalSemanticGCPlan struct {
	CatalogProfiles     []string                      `json:"catalog_profiles"`
	RetainedGenerations []RetrievalSemanticGCArtifact `json:"retained_generations"`
	PrunableGenerations []RetrievalSemanticGCArtifact `json:"prunable_generations"`
	RetainedSegments    []RetrievalSemanticGCArtifact `json:"retained_segments"`
	PrunableSegments    []RetrievalSemanticGCArtifact `json:"prunable_segments"`
	PrunableMemberRows  int64                         `json:"prunable_member_rows"`
}

type RetrievalStatus added in v0.8.0

type RetrievalStatus struct {
	Available           bool   `json:"available"`
	ProfileID           string `json:"profile_id"`
	ChunkCount          int    `json:"chunk_count"`
	ReadyEmbeddings     int    `json:"ready_embeddings"`
	PendingEmbeddings   int    `json:"pending_embeddings"`
	BlockedEmbeddings   int    `json:"blocked_embeddings"`
	FailedEmbeddings    int    `json:"failed_embeddings"`
	EmbeddingCandidates int    `json:"embedding_candidates"`
	ActiveGenerationID  string `json:"active_generation_id"`
	StaleGenerations    int    `json:"stale_generations"`
}

type RetrievalVectorRow added in v0.8.0

type RetrievalVectorRow struct {
	ChunkID, ProfileID            string
	Provider, Model               string
	Dimensions                    int
	Representation, Normalization string
	VectorBytes                   []byte
	VectorHash, ChunkTextHash     string
	CurrentChunkTextHash          string
	ProjectionVersion             string
	ChunkerVersion                string
	Revision                      int64
}

type ReviewCursor added in v0.2.22

type ReviewCursor struct {
	EventAt    time.Time `json:"event_at"`
	EventKind  string    `json:"event_kind"`
	EntityKind string    `json:"entity_kind"`
	EntityID   int64     `json:"entity_id"`
	EventStage string    `json:"event_stage"`
}

func DecodeReviewCursor added in v0.2.22

func DecodeReviewCursor(token string) (ReviewCursor, error)

func ParseReviewSince added in v0.2.22

func ParseReviewSince(value string, now time.Time) (ReviewCursor, error)

type ReviewEntityEvent added in v0.2.22

type ReviewEntityEvent struct {
	EventID       string    `json:"event_id"`
	EventKind     string    `json:"event_kind"`
	EventAt       time.Time `json:"event_at"`
	EventStage    string    `json:"event_stage"`
	Status        string    `json:"status"`
	Actionability string    `json:"actionability"`
	Importance    int       `json:"importance"`
	Message       string    `json:"message,omitempty"`
	Reasons       []string  `json:"reasons"`
}

type ReviewEntityGroup added in v0.2.22

type ReviewEntityGroup struct {
	EntityKind       string              `json:"entity_kind"`
	EntityID         int64               `json:"entity_id"`
	EntityKey        string              `json:"entity_key"`
	SourceType       string              `json:"source_type"`
	Title            string              `json:"title"`
	URL              string              `json:"url"`
	NotePath         string              `json:"note_path"`
	FirstEventAt     time.Time           `json:"first_event_at"`
	LatestEventAt    time.Time           `json:"latest_event_at"`
	EventCount       int                 `json:"event_count"`
	EventKinds       []string            `json:"event_kinds"`
	Summary          string              `json:"summary"`
	SummaryEventID   string              `json:"summary_event_id"`
	SummaryEventKind string              `json:"summary_event_kind"`
	Tags             []string            `json:"tags"`
	Status           string              `json:"status"`
	Message          string              `json:"message,omitempty"`
	Actionability    string              `json:"actionability"`
	Importance       int                 `json:"importance"`
	Reasons          []string            `json:"reasons"`
	Events           []ReviewEntityEvent `json:"events"`
}

type ReviewEvent added in v0.2.22

type ReviewEvent struct {
	EventID       string    `json:"event_id"`
	EventKind     string    `json:"event_kind"`
	EventAt       time.Time `json:"event_at"`
	EntityKind    string    `json:"entity_kind"`
	EntityID      int64     `json:"entity_id"`
	EntityKey     string    `json:"entity_key"`
	EventStage    string    `json:"event_stage"`
	SourceType    string    `json:"source_type"`
	Title         string    `json:"title"`
	URL           string    `json:"url"`
	NotePath      string    `json:"note_path"`
	Summary       string    `json:"summary"`
	Tags          []string  `json:"tags"`
	Status        string    `json:"status"`
	Message       string    `json:"message,omitempty"`
	Actionability string    `json:"actionability"`
	Importance    int       `json:"importance"`
	Reasons       []string  `json:"reasons"`
}

type ReviewEventFilter added in v0.2.22

type ReviewEventFilter struct {
	Cursor ReviewCursor
	Limit  int
	Types  []string
	View   string
}

type ReviewEventPage added in v0.2.22

type ReviewEventPage struct {
	View          string              `json:"view"`
	Cursor        ReviewCursor        `json:"cursor"`
	NextCursor    string              `json:"next_cursor"`
	HighWatermark time.Time           `json:"high_watermark"`
	Events        []ReviewEvent       `json:"events"`
	Entities      []ReviewEntityGroup `json:"entities"`
	Truncated     bool                `json:"truncated"`
	Counts        []CountBucket       `json:"counts"`
}

type SemanticRefreshCounters added in v0.8.0

type SemanticRefreshCounters struct {
	ProjectedParents int64 `json:"projected_parents"`
	EmbeddedChunks   int64 `json:"embedded_chunks"`
	FlushedVectors   int64 `json:"flushed_vectors"`
	CompactedVectors int64 `json:"compacted_vectors"`
	VerifiedVectors  int64 `json:"verified_vectors"`
	SuccessorRuns    int64 `json:"successor_runs"`
}

type SemanticRefreshRun added in v0.8.0

type SemanticRefreshRun struct {
	RunID, ProfileID, Checkpoint, CurrentGenerationID  string
	ErrorCode, ErrorText, ReadinessState               string
	PurgeEpoch, ProjectionWatermark, EmbeddingRevision int64
	Version                                            int64
	Stage                                              SemanticRefreshStage
	State                                              SemanticRefreshRunState
	Counters                                           SemanticRefreshCounters
	CreatedAt, UpdatedAt, LastProgressAt               time.Time
}

type SemanticRefreshRunState added in v0.8.0

type SemanticRefreshRunState string
const (
	SemanticRefreshRunRunning    SemanticRefreshRunState = "running"
	SemanticRefreshRunFailed     SemanticRefreshRunState = "failed"
	SemanticRefreshRunCancelled  SemanticRefreshRunState = "cancelled"
	SemanticRefreshRunCompleted  SemanticRefreshRunState = "completed"
	SemanticRefreshRunSuperseded SemanticRefreshRunState = "superseded"
)

type SemanticRefreshRunUpdate added in v0.8.0

type SemanticRefreshRunUpdate struct {
	RunID, Checkpoint, CurrentGenerationID string
	ErrorCode, ErrorText, ReadinessState   string
	ExpectedVersion, EmbeddingRevision     int64
	Stage                                  SemanticRefreshStage
	State                                  SemanticRefreshRunState
	Counters                               SemanticRefreshCounters
	Now                                    time.Time
}

type SemanticRefreshStage added in v0.8.0

type SemanticRefreshStage string
const (
	SemanticRefreshProjection SemanticRefreshStage = "projection"
	SemanticRefreshEmbedding  SemanticRefreshStage = "embedding"
	SemanticRefreshFlush      SemanticRefreshStage = "flush"
	SemanticRefreshCompaction SemanticRefreshStage = "compaction"
	SemanticRefreshVerify     SemanticRefreshStage = "verify"
	SemanticRefreshReadiness  SemanticRefreshStage = "readiness"
)

type SourceActivityEvent

type SourceActivityEvent struct {
	SourceID     int64     `json:"source_id"`
	SourceKey    string    `json:"source_key"`
	SourceType   string    `json:"source_type"`
	Domain       string    `json:"domain"`
	FailureKind  string    `json:"failure_kind,omitempty"`
	CanonicalURL string    `json:"canonical_url"`
	Title        string    `json:"title"`
	NotePath     string    `json:"note_path"`
	EventKind    string    `json:"event_kind"`
	Status       string    `json:"status"`
	Message      string    `json:"message,omitempty"`
	EventAt      time.Time `json:"event_at"`
}

type SourceActivityFeed

type SourceActivityFeed struct {
	Window             string                     `json:"window"`
	RecentSuccesses    []SourceActivityEvent      `json:"recent_successes"`
	RecentFailures     []SourceActivityEvent      `json:"recent_failures"`
	FailureHotspots    []SourceFailureHotspot     `json:"failure_hotspots"`
	FailureKinds       []CountBucket              `json:"failure_kinds"`
	FailureStatuses    []CountBucket              `json:"failure_statuses"`
	FailureDomains     []CountBucket              `json:"failure_domains"`
	FailureTable       []SourceActivityEvent      `json:"failure_table"`
	FailureTableTotal  int                        `json:"failure_table_total"`
	FailureTableOffset int                        `json:"failure_table_offset"`
	FailureTableLimit  int                        `json:"failure_table_limit"`
	FailureTableSort   string                     `json:"failure_table_sort"`
	TrendBucket        string                     `json:"trend_bucket"`
	Trend              []SourceActivityTrendPoint `json:"trend"`
}

type SourceActivityFilter

type SourceActivityFilter struct {
	Limit         int
	FailureOffset int
	FailureSort   string
	SourceType    string
	Domain        string
	Status        string
	FailureKind   string
	Message       string
	Window        time.Duration
}

type SourceActivityTrendPoint

type SourceActivityTrendPoint struct {
	BucketStart  time.Time `json:"bucket_start"`
	Label        string    `json:"label"`
	SuccessCount int       `json:"success_count"`
	FailureCount int       `json:"failure_count"`
}

type SourceCountFilter

type SourceCountFilter struct {
	SourceType    string
	ExtractTool   string
	SummaryStatus string
	ExtractStatus string
}

type SourceFailureHotspot

type SourceFailureHotspot struct {
	Domain        string    `json:"domain"`
	SourceType    string    `json:"source_type"`
	Status        string    `json:"status"`
	FailureKind   string    `json:"failure_kind,omitempty"`
	Count         int       `json:"count"`
	LatestEventAt time.Time `json:"latest_event_at"`
}

type StageRetrievalProjectionInput added in v0.8.0

type StageRetrievalProjectionInput struct {
	WorkID             string
	DirtyRevision      int64
	ExpectedPurgeEpoch int64
	ParentKind         string
	ParentSourceKey    string
	ProjectionHash     string
	Cursor             retrievalchunk.Cursor
	Rows               []RetrievalProjectionStageRow
	PreparedPlan       []byte
	// PreparedPlanDigest is computed once by the prepared command session.
	// Supplying it lets later durable batches validate immutable plan identity
	// without reading or hashing the full plan BLOB again.
	PreparedPlanDigest string
}

type StartSemanticRefreshRunInput added in v0.8.0

type StartSemanticRefreshRunInput struct {
	RunID, ProfileID                string
	PurgeEpoch, ProjectionWatermark int64
	InitialCounters                 SemanticRefreshCounters
	Now                             time.Time
}

type Store

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

func Open

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

func OpenReadOnly

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

OpenReadOnly opens an existing store for read-only consumers such as MCP. It intentionally skips schema creation/migrations so startup cannot block behind a long-running writer before the MCP initialize response is sent.

func OpenReadOnlyContext added in v0.7.0

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

OpenReadOnlyContext opens an existing query-only store and bounds all bootstrap probes with the caller's context.

func OpenReadOnlyContextWithOptions added in v0.8.17

func OpenReadOnlyContextWithOptions(ctx context.Context, path string, opts OpenOptions) (*Store, error)

OpenReadOnlyContextWithOptions opens an existing query-only store and bounds all bootstrap probes with the caller's context.

func OpenReadOnlyWithOptions added in v0.8.17

func OpenReadOnlyWithOptions(path string, opts OpenOptions) (*Store, error)

OpenReadOnlyWithOptions opens an existing query-only store with configurable connection-pool sizing. It intentionally skips schema migrations.

func OpenWithOptions

func OpenWithOptions(path string, opts OpenOptions) (*Store, error)

func OpenWithSemanticCache added in v0.8.0

func OpenWithSemanticCache(path string, cacheDir string) (*Store, error)

func OpenWithSemanticCacheOptions added in v0.8.0

func OpenWithSemanticCacheOptions(path string, cacheDir string, opts OpenOptions) (*Store, error)

func (*Store) AcquireSemanticRefreshStage added in v0.8.0

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

func (*Store) ActivateRetrievalIndexGeneration added in v0.8.0

func (s *Store) ActivateRetrievalIndexGeneration(ctx context.Context, generationID string) error

func (*Store) ActiveMCPBearerTokenCount added in v0.2.5

func (s *Store) ActiveMCPBearerTokenCount(ctx context.Context) (int, error)

func (*Store) Activity

func (s *Store) Activity(ctx context.Context, now time.Time, window time.Duration) (ActivityStats, error)

func (*Store) ApplyFeedEntry added in v0.1.6

func (s *Store) ApplyFeedEntry(ctx context.Context, entry FeedEntry) (FeedEntryApplyResult, error)

func (*Store) ApplyRetrievalProjection added in v0.8.0

func (s *Store) ApplyRetrievalProjection(ctx context.Context, input ApplyRetrievalProjectionInput) (ChunkReplaceResult, error)

func (*Store) ApproveGitHubAuthUser added in v0.2.5

func (s *Store) ApproveGitHubAuthUser(ctx context.Context, username string) (AuthUser, bool, error)

func (*Store) Backlog

func (s *Store) Backlog(ctx context.Context, promptVersion string, toolName string, toolVersion string) (BacklogStats, error)

func (*Store) BeginAuditReadSnapshot added in v0.7.0

func (s *Store) BeginAuditReadSnapshot(ctx context.Context) (*AuditReadSnapshot, error)

func (*Store) BeginRetrievalNativeReadSnapshot added in v0.8.0

func (s *Store) BeginRetrievalNativeReadSnapshot(ctx context.Context) (RetrievalNativeReadSession, error)

BeginRetrievalNativeReadSnapshot pins one query-only SQLite read snapshot for a native semantic search. All methods still CAS-check the active root; the pinned view prevents a successful search from mixing L0 and validated candidates from different database snapshots.

func (*Store) BlockCorruptRetrievalEmbedding added in v0.8.0

func (s *Store) BlockCorruptRetrievalEmbedding(ctx context.Context, corruption *RetrievalEmbeddingCorruptionError) error

BlockCorruptRetrievalEmbedding explicitly revalidates and transitions the row identified by a ListReadyEmbeddings diagnostic. Keeping it separate makes read-only consumers non-mutating. Revalidation inside the write transaction prevents a stale diagnostic from blocking a row repaired in the meantime.

func (*Store) BlockRetrievalProjectionTooLarge added in v0.8.0

func (s *Store) BlockRetrievalProjectionTooLarge(
	ctx context.Context,
	parent retrievalchunk.Parent,
	dirtyRevision int64,
	projectionHash string,
	expectedPurgeEpoch int64,
) error

func (*Store) Close

func (s *Store) Close() error

func (*Store) CompleteRetrievalIndexGeneration added in v0.8.0

func (s *Store) CompleteRetrievalIndexGeneration(ctx context.Context, input CompleteRetrievalIndexGenerationInput) error

CompleteRetrievalIndexGeneration records an already-published root and only activates it after every newly-built member still matches SQLite evidence.

func (*Store) CountChunksNeedingEmbeddingAt added in v0.8.0

func (s *Store) CountChunksNeedingEmbeddingAt(ctx context.Context, profileID string, now time.Time) (int, error)

func (*Store) CountChunksNeedingEmbeddingForProfileAt added in v0.8.0

func (s *Store) CountChunksNeedingEmbeddingForProfileAt(ctx context.Context, profile embedding.Profile, now time.Time) (int, error)

func (*Store) CountDirtyRetrievalParents added in v0.8.9

func (s *Store) CountDirtyRetrievalParents(ctx context.Context, watermark int64) (int, error)

func (*Store) CountExactUserTag

func (s *Store) CountExactUserTag(ctx context.Context, tag string, sourceTypes []string) (int, error)

func (*Store) CountItemTextMatches

func (s *Store) CountItemTextMatches(ctx context.Context, query string, sourceTypes []string) (int, error)

func (*Store) CountItems

func (s *Store) CountItems(ctx context.Context, sourceType string, groupBy string) ([]CountBucket, error)

func (*Store) CountRetrievalVectors added in v0.8.9

func (s *Store) CountRetrievalVectors(ctx context.Context, profileID string) (int, error)

func (*Store) CountRetrievalVectorsAfter added in v0.8.9

func (s *Store) CountRetrievalVectorsAfter(ctx context.Context, profileID, afterChunkID string) (int, error)

func (*Store) CountSourceTextMatches

func (s *Store) CountSourceTextMatches(ctx context.Context, query string, sourceTypes []string) (int, error)

func (*Store) CountSources

func (s *Store) CountSources(ctx context.Context, filter SourceCountFilter, groupBy string) ([]CountBucket, error)

func (*Store) CreateMCPBearerToken added in v0.2.5

func (s *Store) CreateMCPBearerToken(ctx context.Context, name string) (MCPBearerTokenCreateResult, error)

func (*Store) DeleteItemsBySourceType

func (s *Store) DeleteItemsBySourceType(ctx context.Context, sourceType string) (DeleteItemsResult, error)

func (*Store) DeleteOrphanSources

func (s *Store) DeleteOrphanSources(ctx context.Context, sourceType string) (DeleteSourcesResult, error)

func (*Store) DeletePublicChatShareByOwner added in v0.8.2

func (s *Store) DeletePublicChatShareByOwner(ctx context.Context, slug string, ownerProvider string, ownerSubject string) error

func (*Store) EnableFeed added in v0.1.6

func (s *Store) EnableFeed(ctx context.Context, ref string, enabled bool) error

func (*Store) EnqueueLinkCapture added in v0.8.17

func (s *Store) EnqueueLinkCapture(ctx context.Context, candidate model.SourceCandidate, now time.Time) (LinkCaptureEnqueueResult, error)

func (*Store) GetFeed added in v0.1.6

func (s *Store) GetFeed(ctx context.Context, ref string) (Feed, error)

func (*Store) GetGitHubAuthUserByID added in v0.2.5

func (s *Store) GetGitHubAuthUserByID(ctx context.Context, githubID string) (AuthUser, bool, error)

func (*Store) GetGitHubAuthUserByUsername added in v0.2.5

func (s *Store) GetGitHubAuthUserByUsername(ctx context.Context, username string) (AuthUser, bool, error)

func (*Store) GetItem

func (s *Store) GetItem(ctx context.Context, lookup string) (model.Item, error)

func (*Store) GetItemByID

func (s *Store) GetItemByID(ctx context.Context, id int64) (model.Item, error)

func (*Store) GetItemEnrichment

func (s *Store) GetItemEnrichment(ctx context.Context, itemID int64, role string) (model.ItemEnrichment, error)

func (*Store) GetLinkCapture added in v0.8.17

func (s *Store) GetLinkCapture(ctx context.Context, id int64) (LinkCapture, error)

func (*Store) GetMCPBearerTokenByID added in v0.2.5

func (s *Store) GetMCPBearerTokenByID(ctx context.Context, id int64) (MCPBearerToken, bool, error)

func (*Store) GetMCPBearerTokenByRawToken added in v0.2.5

func (s *Store) GetMCPBearerTokenByRawToken(ctx context.Context, token string) (MCPBearerToken, bool, error)

func (*Store) GetMastodonSyncState added in v0.8.12

func (s *Store) GetMastodonSyncState(ctx context.Context, accountKey, origin string) (*MastodonSyncState, error)

func (*Store) GetMastodonSyncStateByVerifiedAccount added in v0.8.12

func (s *Store) GetMastodonSyncStateByVerifiedAccount(ctx context.Context, origin, verifiedAccountID string) (*MastodonSyncState, error)

func (*Store) GetMediaAsset

func (s *Store) GetMediaAsset(ctx context.Context, assetID int64) (model.MediaAsset, error)

func (*Store) GetPreferredLocalSourceExtract

func (s *Store) GetPreferredLocalSourceExtract(ctx context.Context, sourceID int64) (model.ExtractResult, bool, error)

func (*Store) GetPublicChatShareBySlug added in v0.2.6

func (s *Store) GetPublicChatShareBySlug(ctx context.Context, slug string) (PublicChatShare, bool, error)

func (*Store) GetRetrievalChunk added in v0.8.0

func (s *Store) GetRetrievalChunk(ctx context.Context, chunkID string) (RetrievalChunkRow, error)

func (*Store) GetSource

func (s *Store) GetSource(ctx context.Context, lookup string) (model.SourceDocument, error)

func (*Store) GetSourceByID

func (s *Store) GetSourceByID(ctx context.Context, sourceID int64) (model.SourceDocument, error)

func (*Store) GetSourceEvidence

func (s *Store) GetSourceEvidence(ctx context.Context, lookup string) (model.SourceDocument, error)

func (*Store) GetSourceExtractedText

func (s *Store) GetSourceExtractedText(ctx context.Context, lookup string) (string, error)

func (*Store) GetSourceExtractedTextPrefix added in v0.2.12

func (s *Store) GetSourceExtractedTextPrefix(ctx context.Context, lookup string, maxChars int) (string, error)

func (*Store) GetSourcesByIDs

func (s *Store) GetSourcesByIDs(ctx context.Context, sourceIDs []int64) ([]model.SourceDocument, error)

func (*Store) HasFTS

func (s *Store) HasFTS() bool

func (*Store) HydrateRetrievalChunks added in v0.8.0

func (s *Store) HydrateRetrievalChunks(ctx context.Context, chunkIDs []string) ([]RetrievalChunkEvidenceRow, error)

func (*Store) InvalidateItemOCR

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

func (*Store) InvalidateItemSummary

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

func (*Store) LatestSemanticRefreshRun added in v0.8.0

func (s *Store) LatestSemanticRefreshRun(ctx context.Context, profileID string) (*SemanticRefreshRun, error)

func (*Store) LinkCaptureAdmissionPoolStats added in v0.8.17

func (s *Store) LinkCaptureAdmissionPoolStats() PoolStats

LinkCaptureAdmissionPoolStats returns the dedicated deferred-link admission pool snapshot. It returns the main pool for in-memory stores and a zero-value snapshot when the file-backed admission pool has not been initialized.

func (*Store) ListAllEntityItems

func (s *Store) ListAllEntityItems(ctx context.Context, limit int) ([]model.Item, error)

func (*Store) ListAllEntitySources

func (s *Store) ListAllEntitySources(ctx context.Context, limit int) ([]model.SourceDocument, error)

func (*Store) ListAllItems

func (s *Store) ListAllItems(ctx context.Context, limit int) ([]model.Item, error)

func (*Store) ListAllSources

func (s *Store) ListAllSources(ctx context.Context, limit int) ([]model.SourceDocument, error)

func (*Store) ListBacklinksForSource

func (s *Store) ListBacklinksForSource(ctx context.Context, sourceID int64) ([]model.SourceBacklink, error)

func (*Store) ListCategorizedItems

func (s *Store) ListCategorizedItems(ctx context.Context) ([]model.Item, error)

ListCategorizedItems returns all items that have a non-empty user_tags field.

func (*Store) ListCategorizedSources

func (s *Store) ListCategorizedSources(ctx context.Context) ([]model.SourceDocument, error)

ListCategorizedSources returns all sources that have a non-empty user_tags field.

func (*Store) ListCategorizedSourcesWithoutEvidence

func (s *Store) ListCategorizedSourcesWithoutEvidence(ctx context.Context) ([]model.SourceDocument, error)

ListCategorizedSourcesWithoutEvidence returns tagged sources that lack extracted or summarized evidence.

func (*Store) ListChunksNeedingEmbedding added in v0.8.0

func (s *Store) ListChunksNeedingEmbedding(ctx context.Context, profileID, afterChunkID string, limit int) ([]RetrievalChunkRow, error)

func (*Store) ListChunksNeedingEmbeddingAt added in v0.8.0

func (s *Store) ListChunksNeedingEmbeddingAt(ctx context.Context, profileID, afterChunkID string, limit int, now time.Time) ([]RetrievalChunkRow, error)

func (*Store) ListChunksNeedingEmbeddingForProfileAt added in v0.8.0

func (s *Store) ListChunksNeedingEmbeddingForProfileAt(ctx context.Context, profile embedding.Profile, afterChunkID string, limit int, now time.Time) ([]RetrievalChunkRow, error)

func (*Store) ListDeadLetteredLinkCaptures added in v0.8.17

func (s *Store) ListDeadLetteredLinkCaptures(ctx context.Context, limit int) ([]LinkCapture, error)

ListDeadLetteredLinkCaptures returns captures whose bounded intake retry window ended without creating a source. The failure fields are deliberately exposed as queue state: LastError is a normalized failure kind, not a raw diagnostic message.

func (*Store) ListDirtyRetrievalParents added in v0.8.0

func (s *Store) ListDirtyRetrievalParents(ctx context.Context, watermark int64, limit int) ([]RetrievalParentWork, error)

func (*Store) ListFeeds added in v0.1.6

func (s *Store) ListFeeds(ctx context.Context, includeDisabled bool) ([]Feed, error)

func (*Store) ListFeedsDue added in v0.1.6

func (s *Store) ListFeedsDue(ctx context.Context, now time.Time, limit int, includeBlocked bool) ([]Feed, error)

func (*Store) ListGitHubAuthUsers added in v0.2.5

func (s *Store) ListGitHubAuthUsers(ctx context.Context) ([]AuthUser, error)
func (s *Store) ListItemChildLinks(ctx context.Context, parentItemID int64, linkKind string) ([]int64, error)

func (*Store) ListItemMediaRefs

func (s *Store) ListItemMediaRefs(ctx context.Context, itemID int64) ([]model.ItemMediaRef, error)

func (*Store) ListItemMediaRefsForSourceKeys added in v0.2.10

func (s *Store) ListItemMediaRefsForSourceKeys(ctx context.Context, sourceKeys []string) (map[string][]model.ItemMediaRef, error)

func (*Store) ListItemSourceKeysByMediaLocalPath

func (s *Store) ListItemSourceKeysByMediaLocalPath(ctx context.Context, localPath string) ([]string, error)

func (*Store) ListItemsForCategorize

func (s *Store) ListItemsForCategorize(ctx context.Context, limit int, force bool) ([]model.Item, error)

ListItemsForCategorize returns items ordered newest-first. When force is false only items with an empty user_tags field are returned.

func (*Store) ListItemsForLinkDiscovery

func (s *Store) ListItemsForLinkDiscovery(ctx context.Context, limit int, force bool) ([]model.Item, error)

func (*Store) ListItemsForXHydration

func (s *Store) ListItemsForXHydration(ctx context.Context, limit int, force bool) ([]model.Item, error)

func (*Store) ListItemsForXMediaSummary

func (s *Store) ListItemsForXMediaSummary(ctx context.Context, limit int, force bool) ([]model.Item, error)

func (*Store) ListItemsForXMediaTranscription

func (s *Store) ListItemsForXMediaTranscription(ctx context.Context, limit int, force bool) ([]model.Item, error)

func (*Store) ListItemsForXPhotoOCR

func (s *Store) ListItemsForXPhotoOCR(ctx context.Context, limit int, force bool) ([]model.Item, error)

func (*Store) ListItemsForXPhotoOCRAudit

func (s *Store) ListItemsForXPhotoOCRAudit(ctx context.Context, limit int, includePruned bool) ([]model.Item, error)

func (*Store) ListItemsForXQuoteHydration

func (s *Store) ListItemsForXQuoteHydration(ctx context.Context, limit int, force bool) ([]model.Item, error)

func (*Store) ListLinkedItemsBySourceType added in v0.1.7

func (s *Store) ListLinkedItemsBySourceType(ctx context.Context, sourceID int64, sourceType string, limit int) ([]model.Item, error)

func (*Store) ListMCPBearerTokens added in v0.2.5

func (s *Store) ListMCPBearerTokens(ctx context.Context, includeRevoked bool) ([]MCPBearerToken, error)

func (*Store) ListMastodonMediaRefsForDownload added in v0.8.12

func (s *Store) ListMastodonMediaRefsForDownload(ctx context.Context, limit int, force bool) ([]model.ItemMediaRef, error)

ListMastodonMediaRefsForDownload returns retryable media linked from Mastodon records. Keeping the source filter in SQL prevents a Mastodon run from accidentally retrying unrelated X or Bluesky media.

func (*Store) ListMediaAssetOwnerItems added in v0.8.13

func (s *Store) ListMediaAssetOwnerItems(ctx context.Context, assetID int64) ([]model.Item, error)

ListMediaAssetOwnerItems returns every item linked to an asset in a stable source-aware order. The result intentionally does not load each item's media/enrichment mirror; callers that need those details can load the specific owner after choosing it.

func (*Store) ListMediaAssetsByLocalPath

func (s *Store) ListMediaAssetsByLocalPath(ctx context.Context, localPath string) ([]model.MediaAsset, error)

func (*Store) ListMediaAssetsForArchive

func (s *Store) ListMediaAssetsForArchive(ctx context.Context, limit int, force bool) ([]model.MediaAsset, error)

func (*Store) ListMediaAssetsForDownload

func (s *Store) ListMediaAssetsForDownload(ctx context.Context, limit int, force bool) ([]model.MediaAsset, error)

func (*Store) ListMediaAssetsForPrune

func (s *Store) ListMediaAssetsForPrune(ctx context.Context, limit int) ([]model.MediaAsset, error)

func (*Store) ListPendingLinkCaptures added in v0.8.17

func (s *Store) ListPendingLinkCaptures(ctx context.Context, now time.Time, limit int) ([]LinkCapture, error)

func (*Store) ListPrunedMediaRepairCandidates added in v0.7.1

func (s *Store) ListPrunedMediaRepairCandidates(ctx context.Context, includeOCR, includeTranscripts bool, limit int) (PrunedMediaRepairCandidates, error)

func (*Store) ListPublicChatSharesByOwner added in v0.2.6

func (s *Store) ListPublicChatSharesByOwner(ctx context.Context, ownerProvider string, ownerSubject string, limit int) ([]PublicChatShare, error)

func (*Store) ListReadyEmbeddings added in v0.8.0

func (s *Store) ListReadyEmbeddings(ctx context.Context, profileID string, limit int) ([]RetrievalEmbeddingRow, error)

func (*Store) ListRetrievalParents added in v0.8.0

func (s *Store) ListRetrievalParents(ctx context.Context, afterSourceKey string, limit int) ([]retrievalchunk.Parent, error)

ListRetrievalParents pages distinct source keys and returns every item/source parent for each selected key. limit is therefore a key-page size; a page can contain more parent rows when both tables contain the same source key.

func (*Store) ListRetrievalVectors added in v0.8.0

func (s *Store) ListRetrievalVectors(ctx context.Context, profileID string, page VectorPage) ([]RetrievalVectorRow, error)

func (*Store) ListReviewEvents added in v0.2.22

func (s *Store) ListReviewEvents(ctx context.Context, filter ReviewEventFilter) (ReviewEventPage, error)

func (*Store) ListSourceDocumentsForItem added in v0.2.25

func (s *Store) ListSourceDocumentsForItem(ctx context.Context, itemID int64) ([]model.SourceDocument, error)

func (*Store) ListSourcesForCategorize

func (s *Store) ListSourcesForCategorize(ctx context.Context, limit int, force bool) ([]model.SourceDocument, error)

ListSourcesForCategorize returns sources with extracted or summarized evidence ordered newest-first. When force is false only evidence-bearing sources with an empty user_tags field are returned.

func (*Store) ListSourcesForEnrichment

func (s *Store) ListSourcesForEnrichment(ctx context.Context, limit int, force bool, summarize bool, promptVersion string, toolName string, toolVersion string) ([]model.SourceDocument, error)

func (*Store) ListSourcesForItem

func (s *Store) ListSourcesForItem(ctx context.Context, itemID int64) ([]model.ItemSourceRef, error)

func (*Store) LoadOKFExportSnapshot added in v0.2.17

func (s *Store) LoadOKFExportSnapshot(ctx context.Context, opts OKFExportOptions) (OKFExportSnapshot, error)

func (*Store) LoadRetrievalProjectionStaging added in v0.8.0

func (s *Store) LoadRetrievalProjectionStaging(ctx context.Context, parent retrievalchunk.Parent, dirtyRevision int64) (RetrievalProjectionCheckpoint, bool, error)

func (*Store) MarkItemLinkDiscovery

func (s *Store) MarkItemLinkDiscovery(ctx context.Context, itemID int64, at time.Time) error

func (*Store) MarkLinkCaptureAttempt added in v0.8.17

func (s *Store) MarkLinkCaptureAttempt(ctx context.Context, id int64, now time.Time) error

func (*Store) MarkLinkCaptureFailed added in v0.8.17

func (s *Store) MarkLinkCaptureFailed(ctx context.Context, id int64, now, nextAttempt time.Time, kind string) error

func (*Store) MarkLinkCaptureProcessed added in v0.8.17

func (s *Store) MarkLinkCaptureProcessed(ctx context.Context, id int64, now time.Time) error

func (*Store) MarkMediaLocalPrunedByPath

func (s *Store) MarkMediaLocalPrunedByPath(ctx context.Context, localPath string, prunedAt time.Time) (int64, error)

func (*Store) MergeItemMediaCandidates added in v0.8.12

func (s *Store) MergeItemMediaCandidates(ctx context.Context, itemID int64, candidates []model.MediaCandidate) (bool, error)

MergeItemMediaCandidates adds validated candidates to the current item links without treating an incomplete source projection as authoritative. Existing links are retained when a server includes an unsupported or malformed attachment alongside valid media.

func (*Store) NextRetrievalFlushWindow added in v0.8.0

func (s *Store) NextRetrievalFlushWindow(ctx context.Context, profileID string, limit int) (RetrievalFlushWindow, error)

NextRetrievalFlushWindow returns a contiguous revision prefix of the exact L0 tail. Revision order is essential: advancing past an older unindexed row would make it disappear from both the root and the exact tail.

func (*Store) Pipeline

func (s *Store) Pipeline(ctx context.Context, promptVersion string, toolName string, toolVersion string) (PipelineStats, error)

func (*Store) PlanRetrievalSemanticGC added in v0.8.11

func (s *Store) PlanRetrievalSemanticGC(ctx context.Context, opts RetrievalSemanticGCOptions) (RetrievalSemanticGCPlan, error)

func (*Store) PoolStats added in v0.8.17

func (s *Store) PoolStats() PoolStats

PoolStats returns the live database/sql pool counters used by operational request logging. A zero-value snapshot is returned for an unavailable store.

func (*Store) ProjectionWorkRevision added in v0.8.0

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

func (*Store) PromoteRetrievalProjectionStaging added in v0.8.0

func (s *Store) PromoteRetrievalProjectionStaging(ctx context.Context, checkpoint RetrievalProjectionCheckpoint) (ChunkReplaceResult, error)

func (*Store) PruneRetrievalSemanticCatalog added in v0.8.11

func (s *Store) PruneRetrievalSemanticCatalog(ctx context.Context, opts RetrievalSemanticGCOptions) (RetrievalSemanticGCPlan, error)

func (*Store) PurgeItemIndexedContent

func (s *Store) PurgeItemIndexedContent(ctx context.Context, sourceKey string, rawJSON string) (bool, error)

func (*Store) PutRetrievalEmbedding added in v0.8.0

func (s *Store) PutRetrievalEmbedding(ctx context.Context, row RetrievalEmbeddingRow) error

func (*Store) PutRetrievalEmbeddingBatch added in v0.8.0

func (s *Store) PutRetrievalEmbeddingBatch(ctx context.Context, input PutRetrievalEmbeddingBatchInput) (int64, error)

func (*Store) PutRetrievalIndexGeneration added in v0.8.0

func (s *Store) PutRetrievalIndexGeneration(ctx context.Context, row RetrievalIndexGenerationRow) error

func (*Store) ReactivateRetrievalDanglingGeneration added in v0.8.6

func (s *Store) ReactivateRetrievalDanglingGeneration(
	ctx context.Context,
	expected RetrievalDanglingGenerationRecovery,
) error

ReactivateRetrievalDanglingGeneration restores a candidate only after the caller has independently verified the immutable native root. Every profile, generation, and catalog fact is re-proved in the same write transaction so a stale inspection cannot activate a changed root.

func (*Store) ReadRetrievalExactL0 added in v0.8.0

func (s *Store) ReadRetrievalExactL0(ctx context.Context, input RetrievalActiveRootReadRequest, limit int) ([]RetrievalEmbeddingRow, error)

ReadRetrievalExactL0 returns only current ready embeddings absent from the CAS-checked active root. It bounds the exact delta explicitly; callers must fail open rather than silently search a truncated L0 tail.

func (*Store) ReadRetrievalNativeCandidates added in v0.8.0

func (s *Store) ReadRetrievalNativeCandidates(ctx context.Context, input RetrievalNativeCandidateRequest) ([]RetrievalEmbeddingRow, error)

ReadRetrievalNativeCandidates validates a bounded native candidate set in a single read-only transaction. It preserves request order for the current members that remain, so a later exact reranker can use deterministic tie-breaking without trusting native result ordering.

func (*Store) RebuildFTS

func (s *Store) RebuildFTS(ctx context.Context) (RebuildFTSStats, error)

func (*Store) RecordFeedFetch added in v0.1.6

func (s *Store) RecordFeedFetch(ctx context.Context, rec FeedFetchRecord) error

func (*Store) RecordMastodonSyncErrorIfCurrent added in v0.8.12

func (s *Store) RecordMastodonSyncErrorIfCurrent(ctx context.Context, accountKey, origin, verifiedAccountID string, at time.Time, message string, expected *MastodonSyncState) error

RecordMastodonSyncErrorIfCurrent updates only diagnostics. It never copies stale pagination from the failed run back over a newer state.

func (*Store) RemoveGitHubAuthUser added in v0.2.5

func (s *Store) RemoveGitHubAuthUser(ctx context.Context, username string) (AuthUser, bool, error)

func (*Store) RepairRetrievalRuntimeReadinessCounters added in v0.8.0

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

RepairRetrievalRuntimeReadinessCounters rebuilds the migration-21 projection and embedding-profile aggregates from authoritative rows. Trigger replacement, both backfills, and supporting indexes commit atomically in one cancellable write transaction.

func (s *Store) ReplaceItemChildLinks(ctx context.Context, parentItemID int64, linkKind string, childItemIDs []int64) (bool, error)

func (*Store) ReplaceRetrievalChunks added in v0.8.0

func (s *Store) ReplaceRetrievalChunks(ctx context.Context, parentKind, parentSourceKey string, chunks []retrievalchunk.Chunk) (ChunkReplaceResult, error)

func (*Store) ResetMastodonSyncState added in v0.8.12

func (s *Store) ResetMastodonSyncState(ctx context.Context, accountKey, origin string) error

func (*Store) ResetMastodonSyncStateForVerifiedAccount added in v0.8.12

func (s *Store) ResetMastodonSyncStateForVerifiedAccount(ctx context.Context, accountKey, origin, verifiedAccountID string) error

ResetMastodonSyncStateForVerifiedAccount clears pagination only when the snapshot loaded by this call is still current. The full-state compare-and- set prevents a concurrent account or pagination replacement from being erased by --force or stale-cursor recovery.

func (*Store) ResetMastodonSyncStateForVerifiedAccountIfCurrent added in v0.8.12

func (s *Store) ResetMastodonSyncStateForVerifiedAccountIfCurrent(ctx context.Context, expected *MastodonSyncState) (*MastodonSyncState, error)

ResetMastodonSyncStateForVerifiedAccountIfCurrent clears pagination using a full-state CAS and returns the exact cleared snapshot. Callers must retain that returned value as their expected state; reloading after the reset can accidentally adopt a competing run's progress.

func (*Store) ResetSourceEnrichment

func (s *Store) ResetSourceEnrichment(ctx context.Context, opts ResetSourceEnrichmentOptions) (ResetSourceEnrichmentStats, error)

func (*Store) RetrievalActiveSegmentCompactionSnapshot added in v0.8.0

func (s *Store) RetrievalActiveSegmentCompactionSnapshot(ctx context.Context, profileID string) (RetrievalActiveSegmentCompactionSnapshot, error)

RetrievalActiveSegmentCompactionSnapshot reads one active root in a single read-only transaction. A member is live only when its exact stored identity still joins a ready embedding and current parent projection; every other catalogued member is a tombstone. It fails closed on active-root or catalog corruption, leaving planning and root replacement to later layers.

func (*Store) RetrievalAvailable added in v0.8.0

func (s *Store) RetrievalAvailable(ctx context.Context) (bool, error)

func (*Store) RetrievalDanglingGenerationRecovery added in v0.8.6

func (s *Store) RetrievalDanglingGenerationRecovery(
	ctx context.Context,
	profileID string,
) (*RetrievalDanglingGenerationRecovery, error)

RetrievalDanglingGenerationRecovery returns a recovery candidate only for the narrow legacy corruption shape: a non-empty profile pointer to the same profile's stale, inactive, fully catalogued segmented generation. Active completed roots and profiles without a root need no recovery.

func (*Store) RetrievalDatabaseID added in v0.8.0

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

func (*Store) RetrievalEmbeddingProfile added in v0.8.0

func (s *Store) RetrievalEmbeddingProfile(ctx context.Context, profileID string) (RetrievalEmbeddingProfileRow, error)

func (*Store) RetrievalEmbeddingVerificationState added in v0.8.0

func (s *Store) RetrievalEmbeddingVerificationState(ctx context.Context, profileID string) (RetrievalEmbeddingVerificationState, error)

func (*Store) RetrievalIndexGenerationSegments added in v0.8.0

func (s *Store) RetrievalIndexGenerationSegments(ctx context.Context, generationID string) ([]RetrievalIndexSegmentRow, error)

func (*Store) RetrievalPurgeEpoch added in v0.8.0

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

func (*Store) RetrievalStatus added in v0.8.0

func (s *Store) RetrievalStatus(ctx context.Context, profileID string) (RetrievalStatus, error)

func (*Store) RetrievalStatusAt added in v0.8.0

func (s *Store) RetrievalStatusAt(ctx context.Context, profileID string, now time.Time) (RetrievalStatus, error)

func (*Store) RevokeMCPBearerToken added in v0.2.5

func (s *Store) RevokeMCPBearerToken(ctx context.Context, ref string) (MCPBearerToken, bool, error)

func (*Store) SaveItemMediaCandidates added in v0.8.12

func (s *Store) SaveItemMediaCandidates(ctx context.Context, itemID int64, candidates []model.MediaCandidate) (bool, error)

SaveItemMediaCandidates replaces the media references for an item through the same transaction path used by X hydration. A valid empty candidate list clears stale links; callers with an invalid or incomplete decoder result should not call this method.

func (*Store) SaveItemOCR

func (s *Store) SaveItemOCR(ctx context.Context, itemID int64, result model.OCRResult, inputHash string) (bool, error)

func (*Store) SaveItemSummary

func (s *Store) SaveItemSummary(ctx context.Context, itemID int64, summary model.SummaryResult, inputHash string) (bool, error)

func (*Store) SaveItemUserTags

func (s *Store) SaveItemUserTags(ctx context.Context, itemID int64, tags string) error

func (*Store) SaveMediaArchive

func (s *Store) SaveMediaArchive(ctx context.Context, assetID int64, result model.MediaArchiveResult) (bool, error)

func (*Store) SaveMediaDownload

func (s *Store) SaveMediaDownload(ctx context.Context, assetID int64, result model.MediaDownloadResult) (bool, error)

func (*Store) SavePublicChatShare added in v0.2.6

func (s *Store) SavePublicChatShare(ctx context.Context, input PublicChatShareInput) (PublicChatShare, error)

func (*Store) SaveSourceExtraction

func (s *Store) SaveSourceExtraction(ctx context.Context, sourceID int64, result model.ExtractResult, contentHash string) (bool, error)

func (*Store) SaveSourceSummary

func (s *Store) SaveSourceSummary(ctx context.Context, sourceID int64, result model.SummaryResult) (bool, error)

func (*Store) SaveSourceUserTags

func (s *Store) SaveSourceUserTags(ctx context.Context, sourceID int64, tags string) error

func (*Store) SaveXHydration

func (s *Store) SaveXHydration(ctx context.Context, itemID int64, hydration model.XHydration) (bool, error)

func (*Store) SaveXMediaTranscription added in v0.5.0

func (s *Store) SaveXMediaTranscription(ctx context.Context, itemID int64, state XMediaTranscriptionState) error

func (*Store) SaveXMediaTranscriptionState

func (s *Store) SaveXMediaTranscriptionState(ctx context.Context, itemID int64, status string, errorText string, at time.Time) error

func (*Store) Search

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

func (*Store) SearchExactUserTag

func (s *Store) SearchExactUserTag(ctx context.Context, tag string, limit int) ([]model.SearchResult, error)

func (*Store) SearchSources

func (s *Store) SearchSources(ctx context.Context, query string, limit int) ([]model.SearchResult, error)

func (*Store) SearchUserTags

func (s *Store) SearchUserTags(ctx context.Context, tagQuery string, limit int) ([]model.SearchResult, error)

func (*Store) SemanticReadinessSnapshotAt added in v0.8.0

func (s *Store) SemanticReadinessSnapshotAt(ctx context.Context, profile embedding.Profile, exactMaxChunks int, now time.Time) (semanticreadiness.Snapshot, error)

SemanticReadinessSnapshotAt reads every readiness fact and every dirty parent used by exact v3 planning through one immutable SQLite read transaction. No status/runtime caller may compose readiness from independent autocommit reads.

func (*Store) SemanticRuntimeReadinessSnapshotAt added in v0.8.0

func (s *Store) SemanticRuntimeReadinessSnapshotAt(ctx context.Context, profile embedding.Profile, exactMaxChunks int, now time.Time) (semanticreadiness.Snapshot, error)

SemanticRuntimeReadinessSnapshotAt acquires admission facts without the maintenance/status path's repeated full-corpus joins. Projection facts are ledger aggregates, embedding state comes from transactionally maintained profile counters, and exact row validation is entered only when both the current chunk set and the whole profile fit the immutable exact-search cap. Every read and bounded validation belongs to one read transaction.

func (*Store) SourceActivityFeed

func (s *Store) SourceActivityFeed(ctx context.Context, limit int) (SourceActivityFeed, error)

func (*Store) SourceActivityFeedFiltered

func (s *Store) SourceActivityFeedFiltered(ctx context.Context, filter SourceActivityFilter) (SourceActivityFeed, error)

func (*Store) SourceHasLinkedItemType added in v0.1.7

func (s *Store) SourceHasLinkedItemType(ctx context.Context, sourceID int64, sourceType string) (bool, error)

func (*Store) StageRetrievalProjectionBatch added in v0.8.0

func (s *Store) StageRetrievalProjectionBatch(ctx context.Context, input StageRetrievalProjectionInput) (RetrievalProjectionCheckpoint, error)

func (*Store) StartOrResumeSemanticRefreshRun added in v0.8.0

func (s *Store) StartOrResumeSemanticRefreshRun(ctx context.Context, in StartSemanticRefreshRunInput) (SemanticRefreshRun, bool, error)

func (*Store) StreamRetrievalActiveSegmentMembers added in v0.8.0

func (s *Store) StreamRetrievalActiveSegmentMembers(ctx context.Context, input RetrievalActiveSegmentMemberStreamRequest, visit RetrievalActiveSegmentMemberVisitor) (int, error)

StreamRetrievalActiveSegmentMembers visits current live embeddings from one or two selected segments in one read-only SQLite transaction. It retains no vector collection; stale immutable memberships are omitted. Callers must still use activation CAS after building derived payloads, because the root or embedding state can change after this read transaction closes.

func (*Store) TouchSemanticRefreshRunProgress added in v0.8.0

func (s *Store) TouchSemanticRefreshRunProgress(ctx context.Context, runID string, at time.Time) error

func (*Store) UpdateFeedFailure added in v0.1.6

func (s *Store) UpdateFeedFailure(ctx context.Context, state FeedFailureState) error

func (*Store) UpdateFeedFetchState added in v0.1.6

func (s *Store) UpdateFeedFetchState(ctx context.Context, state FeedFetchState) error

func (*Store) UpdateGitHubAuthUserFromOAuth added in v0.2.5

func (s *Store) UpdateGitHubAuthUserFromOAuth(ctx context.Context, userID int64, profile GitHubAuthProfile) (AuthUser, error)

func (*Store) UpdateSemanticRefreshRun added in v0.8.0

func (s *Store) UpdateSemanticRefreshRun(ctx context.Context, in SemanticRefreshRunUpdate) (SemanticRefreshRun, error)

func (*Store) UpsertFeed added in v0.1.6

func (s *Store) UpsertFeed(ctx context.Context, input FeedUpsert) (FeedUpsertResult, error)

func (*Store) UpsertItem

func (s *Store) UpsertItem(ctx context.Context, item model.Item) (model.UpsertResult, error)

func (*Store) UpsertMastodonSyncState added in v0.8.12

func (s *Store) UpsertMastodonSyncState(ctx context.Context, state MastodonSyncState) error

func (*Store) UpsertMastodonSyncStateIfCurrent added in v0.8.12

func (s *Store) UpsertMastodonSyncStateIfCurrent(ctx context.Context, state MastodonSyncState, expected *MastodonSyncState) error

UpsertMastodonSyncStateIfCurrent writes a checkpoint only if the complete state observed by the caller is still current. Identity alone is not enough: a competing run may have changed pagination while retaining the same account.

func (*Store) UpsertSource

func (s *Store) UpsertSource(ctx context.Context, candidate model.SourceCandidate) (model.SourceUpsertResult, error)
func (s *Store) UpsertSourceLink(ctx context.Context, itemID int64, candidate model.SourceCandidate) (model.SourceLinkUpsertResult, error)

func (*Store) VacuumRetrievalDatabase added in v0.8.11

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

func (*Store) ValidateMCPBearerToken added in v0.2.5

func (s *Store) ValidateMCPBearerToken(ctx context.Context, token string) (bool, error)

func (*Store) XMediaTranscriptionInputHash added in v0.7.0

func (s *Store) XMediaTranscriptionInputHash(ctx context.Context, itemID int64, settings []XMediaTranscriptionInputSettings) (string, error)

type VectorPage added in v0.8.0

type VectorPage struct {
	AfterChunkID string
	Limit        int
}

type XMediaTranscriptionInputSettings added in v0.7.0

type XMediaTranscriptionInputSettings struct {
	Backend    string `json:"backend"`
	Model      string `json:"model"`
	Language   string `json:"language"`
	VADEnabled bool   `json:"vad_enabled"`
}

type XMediaTranscriptionState added in v0.5.0

type XMediaTranscriptionState struct {
	Status, Error, RawJSON, Model, Tool, ToolVersion, InputHash string
	InputSettings                                               []XMediaTranscriptionInputSettings
	CompletedAt                                                 time.Time
}

Source Files

Jump to

Keyboard shortcuts

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