postgres

package
v2.3.4 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Overview

Package postgres contains the server-mode repositories.

Package postgres contains the server-mode repositories. Every operation is transaction scoped and binds the authenticated tenant through the SECURITY DEFINER function installed by the server migration.

Index

Constants

View Source
const (
	OutboxStatusPending    = "pending"
	OutboxStatusLeased     = "leased"
	OutboxStatusComplete   = "complete"
	OutboxStatusDeadLetter = "dead_letter"
)

Variables

View Source
var (
	ErrInvalidRelation  = errors.New("postgres graph: invalid relation type")
	ErrInvalidTimeRange = errors.New("postgres graph: invalid valid-time range")
	ErrInvalidEdge      = errors.New("postgres graph: invalid edge")
)
View Source
var (
	ErrTenantContextRequired   = errors.New("postgres store: tenant context is required")
	ErrPrincipalRequired       = errors.New("postgres store: principal is required")
	ErrGrantDigestRequired     = errors.New("postgres store: grant digest is required")
	ErrGrantVersionRequired    = errors.New("postgres store: grant version is required")
	ErrAuthorizedStoreRequired = errors.New("postgres store: authorized store is required")
)
View Source
var ErrCodeIndexUnavailable = errors.New("code_index_unavailable")

ErrCodeIndexUnavailable reports that the scoped corpus has not completed a successful reindex. Legacy project-only rows are never used as fallback.

View Source
var ErrInvalidUser = errors.New("postgres users: invalid user")

Functions

This section is empty.

Types

type AuditSink

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

AuditSink persists authorization decisions without recording request content, token material, or other secrets. Each event is bound to the same verified principal as the server store and is tenant-isolated by PostgreSQL RLS.

func NewAuditSink

func NewAuditSink(pool *pgxpool.Pool, principalSubject, grantDigest string, grantVersion int64) (*AuditSink, error)

func (*AuditSink) Record

func (a *AuditSink) Record(ctx context.Context, e authz.AuditEvent) error

type AuthorizedStore

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

AuthorizedStore is the only server-facing storage capability. The raw Store remains package-private in composition; transports receive repository ports and cannot select a tenant or bypass the authorization binding.

func NewAuthorizedStore

func NewAuthorizedStore(pool *pgxpool.Pool, ac authz.AuthorizedContext) (*AuthorizedStore, error)

NewAuthorizedStore is the server-safe constructor. The tenant and grants are taken from a prior authorization decision; callers cannot supply a client-owned tenant independently of the verified principal.

func (*AuthorizedStore) AuthorizeAdminManage added in v2.3.0

func (s *AuthorizedStore) AuthorizeAdminManage(ctx context.Context) error

AuthorizeAdminManage exposes a narrow, audited capability gate for server administration endpoints without leaking repositories or policy internals.

func (*AuthorizedStore) BulkSaveObservations

func (s *AuthorizedStore) BulkSaveObservations(ctx context.Context, observations []*domain.Observation) error

func (*AuthorizedStore) CreateGraphEdge

func (s *AuthorizedStore) CreateGraphEdge(ctx context.Context, e *domain.Edge) error

func (*AuthorizedStore) CreateSession

func (s *AuthorizedStore) CreateSession(ctx context.Context, session *domain.Session) error

CreateSession creates a session in the authorized workspace context.

func (*AuthorizedStore) CreateUser

func (*AuthorizedStore) DeleteGraphEdge

func (s *AuthorizedStore) DeleteGraphEdge(ctx context.Context, id int64) error

func (*AuthorizedStore) DeleteObservation

func (s *AuthorizedStore) DeleteObservation(ctx context.Context, id int64) error

func (*AuthorizedStore) DeleteProjectArtifact

func (s *AuthorizedStore) DeleteProjectArtifact(ctx context.Context, id string, reason string) error

DeleteProjectArtifact soft deletes an artifact.

func (*AuthorizedStore) ExecuteHandoff

ExecuteHandoff performs the compound preauthorization — observation write ahead of the transaction, plus the optional relation INSIDE it — and then delegates to the RLS-bound executor. tenant/workspace/scope authority comes only from the verified principal; partial permission, an unavailable authorization dependency, or a cross-tenant target fails closed with zero effects (REM-AUTH-001, RD5).

func (*AuthorizedStore) GetAgentCodeGraphSnapshot added in v2.3.0

func (s *AuthorizedStore) GetAgentCodeGraphSnapshot(ctx context.Context, project, query string, maxHops, maxNodes, maxEdges int) (*code.CodeGraph, error)

GetAgentCodeGraphSnapshot is the bounded AST acquisition counterpart. It reads only seed symbols and a limited relation frontier from the trusted project-bound code index; GetGraph's 100k-symbol materialization is avoided.

func (*AuthorizedStore) GetAgentGraphSnapshot added in v2.3.0

func (s *AuthorizedStore) GetAgentGraphSnapshot(ctx context.Context, projectPublicID, projectLabel string, seedPublicIDs []string, maxHops, maxNodes, maxEdges int) (*domain.GraphSubgraph, error)

GetAgentGraphSnapshot applies every budget before acquisition. Each hop is a separate canonically ordered bounded query over already-authorized frontier nodes, so neither corpus materialization nor unbounded recursive fan-out can occur before truncation.

func (*AuthorizedStore) GetAgentObservationByID added in v2.3.0

func (s *AuthorizedStore) GetAgentObservationByID(ctx context.Context, projectPublicID, projectLabel string, id int64) (*domain.Observation, error)

GetAgentObservationByID hydrates a vector candidate only when the candidate still belongs to the exact public project UUID selected and authorized for the request. The label is checked solely as canonical display metadata.

func (*AuthorizedStore) GetCodeGraph added in v2.3.0

func (s *AuthorizedStore) GetCodeGraph(ctx context.Context, project string) (*code.CodeGraph, error)

func (*AuthorizedStore) GetGraphEdge

func (s *AuthorizedStore) GetGraphEdge(ctx context.Context, id int64) (*domain.Edge, error)

func (*AuthorizedStore) GetGraphEdgeByPublicID

func (s *AuthorizedStore) GetGraphEdgeByPublicID(ctx context.Context, publicID string) (*domain.Edge, error)

func (*AuthorizedStore) GetGraphSubgraph

func (s *AuthorizedStore) GetGraphSubgraph(ctx context.Context, rootPublicID string, depth, maxNodes int) (*domain.GraphSubgraph, error)

GetGraphSubgraph projects authorized aggregates into a bounded heterogeneous graph without duplicating users, sessions, projects, or entities into a generic source-of-truth table.

func (*AuthorizedStore) GetImportanceScore

func (s *AuthorizedStore) GetImportanceScore(ctx context.Context, id int64) (*domain.ImportanceScore, error)

func (*AuthorizedStore) GetObservationByID

func (s *AuthorizedStore) GetObservationByID(ctx context.Context, id int64) (*domain.Observation, error)

func (*AuthorizedStore) GetObservationByPublicID

func (s *AuthorizedStore) GetObservationByPublicID(ctx context.Context, publicID string) (*domain.Observation, error)

func (*AuthorizedStore) GetProjectContext

func (s *AuthorizedStore) GetProjectContext(ctx context.Context, project string) (*domain.ProjectContext, error)

GetProjectContext resolves the corporate and project rules into a consolidated System Prompt along with the list of available skills.

func (*AuthorizedStore) GetProjectDuplicates

func (s *AuthorizedStore) GetProjectDuplicates(ctx context.Context) ([]domain.ProjectDuplicateGroup, error)

GetProjectDuplicates scans projects and returns groups with casing or near-duplicate discrepancies.

func (*AuthorizedStore) GetProjectSkill

func (s *AuthorizedStore) GetProjectSkill(ctx context.Context, project, key string) (*domain.ProjectSkill, error)

GetProjectSkill gets a specific skill by key.

func (*AuthorizedStore) GetRAGStats added in v2.3.0

func (s *AuthorizedStore) GetRAGStats(ctx context.Context, project string) (*domain.RAGStats, error)

func (*AuthorizedStore) GetRelatedObservations

func (s *AuthorizedStore) GetRelatedObservations(ctx context.Context, id int64, depth int) ([]*domain.Observation, error)

func (*AuthorizedStore) GetServerStats

func (s *AuthorizedStore) GetServerStats(ctx context.Context) (*domain.ServerStats, error)

GetServerStats returns counters scoped by the configured tenant and workspace.

func (*AuthorizedStore) GetUserProfile

func (s *AuthorizedStore) GetUserProfile(ctx context.Context, id string) (*identity.UserRecord, error)

func (*AuthorizedStore) IssueToken

func (*AuthorizedStore) ListAgentProjects added in v2.3.0

func (s *AuthorizedStore) ListAgentProjects(ctx context.Context) (map[string]string, error)

ListAgentProjects resolves public IDs and labels inside the principal-bound tenant/workspace transaction. It returns only projects granted for search and with at least one corpus the same principal may read.

func (*AuthorizedStore) ListAuditEvents

func (s *AuthorizedStore) ListAuditEvents(ctx context.Context, limit int) ([]*domain.AuditEntry, error)

ListAuditEvents returns recent administrative audit entries for the workspace tenant.

func (*AuthorizedStore) ListCodeSymbols added in v2.3.0

func (s *AuthorizedStore) ListCodeSymbols(ctx context.Context, filter code.SymbolFilter) ([]code.Symbol, error)

func (*AuthorizedStore) ListObservations

func (s *AuthorizedStore) ListObservations(ctx context.Context, f domain.ObservationFilter) ([]*domain.Observation, error)

func (*AuthorizedStore) ListProjectArtifacts

func (s *AuthorizedStore) ListProjectArtifacts(ctx context.Context, project string, kind string) ([]*domain.ProjectArtifactItem, error)

ListProjectArtifacts lists all artifacts (rules & skills) for a project and workspace default.

func (*AuthorizedStore) ListProjectSkills

func (s *AuthorizedStore) ListProjectSkills(ctx context.Context, project string) ([]*domain.ProjectSkill, error)

ListProjectSkills returns the list of active skills for a project and workspace default.

func (*AuthorizedStore) ListProjects

func (s *AuthorizedStore) ListProjects(ctx context.Context) ([]string, error)

ListProjects returns project keys visible to the configured principal.

func (*AuthorizedStore) ListSessions

func (s *AuthorizedStore) ListSessions(ctx context.Context, project string) ([]*domain.Session, error)

ListSessions returns sessions visible in the authorized workspace.

func (*AuthorizedStore) ListTokens

func (s *AuthorizedStore) ListTokens(ctx context.Context) ([]identity.TokenRecord, error)

func (*AuthorizedStore) ListUsers

func (s *AuthorizedStore) ListUsers(ctx context.Context) ([]identity.UserRecord, error)

func (*AuthorizedStore) MergeProject

func (s *AuthorizedStore) MergeProject(ctx context.Context, sourceProject, targetProject string) (*domain.ProjectMergeResult, error)

MergeProject consolidates observations, sessions, prompts, and importance scores from sourceProject into targetProject.

func (*AuthorizedStore) PullSync

func (s *AuthorizedStore) PullSync(ctx context.Context, cursor int64, limit int) (*domain.SyncPage, error)

func (*AuthorizedStore) PushSync

func (s *AuthorizedStore) PushSync(ctx context.Context, batch *domain.SyncBatch) (*domain.SyncResult, error)

func (*AuthorizedStore) RecordImportanceAccess

func (s *AuthorizedStore) RecordImportanceAccess(ctx context.Context, id int64) error

RecordImportanceAccess records a read against an authorized observation. The resource is resolved before authorization so an id from another tenant cannot be used as an oracle or mutate its score metadata.

func (*AuthorizedStore) RevokeToken

func (s *AuthorizedStore) RevokeToken(ctx context.Context, id string) error

func (*AuthorizedStore) RotateToken

func (s *AuthorizedStore) RotateToken(ctx context.Context, id string) (identity.IssuedToken, error)

func (*AuthorizedStore) SaveCodeGraph added in v2.3.0

func (s *AuthorizedStore) SaveCodeGraph(ctx context.Context, graph *code.CodeGraph) error

func (*AuthorizedStore) SaveObservation

func (s *AuthorizedStore) SaveObservation(ctx context.Context, o *domain.Observation) error

func (*AuthorizedStore) SaveObservationWithEffect

func (s *AuthorizedStore) SaveObservationWithEffect(ctx context.Context, o *domain.Observation) (domain.SaveEffect, error)

SaveObservationWithEffect authorizes the write exactly like SaveObservation and persists through the transactional effect primitive, so the durable created/updated classification is decided inside the transaction (RD2, REM-SAVE-001). No repository escapes the boundary.

func (*AuthorizedStore) SaveProjectArtifact

SaveProjectArtifact saves (creates or updates revision) for a project rule or skill.

func (*AuthorizedStore) SearchAgentObservations added in v2.3.0

func (s *AuthorizedStore) SearchAgentObservations(ctx context.Context, projectPublicID, projectLabel, query string, opts domain.SearchOptions) ([]*domain.SearchResult, error)

SearchAgentObservations separates authority identity from corpus labeling. Grants and authorization use the immutable projects.public_id; only after resolving and matching that ID inside the bound tenant/workspace transaction is its internal projects.id used to filter observations.project_id. The label remains display metadata and can never select the corpus.

func (*AuthorizedStore) SearchObservations

func (s *AuthorizedStore) SearchObservations(ctx context.Context, query string, opts domain.SearchOptions) ([]*domain.SearchResult, error)

func (*AuthorizedStore) SetImportanceScore

func (s *AuthorizedStore) SetImportanceScore(ctx context.Context, id int64, score float64) error

SetImportanceScore sets a lifecycle score only after resolving and enforcing the actual observation resource.

func (*AuthorizedStore) SetUserActive

func (s *AuthorizedStore) SetUserActive(ctx context.Context, id string, active bool) error

func (*AuthorizedStore) UpdateImportanceScore

func (s *AuthorizedStore) UpdateImportanceScore(ctx context.Context, id int64, increment float64) error

func (*AuthorizedStore) UpdateObservation

func (s *AuthorizedStore) UpdateObservation(ctx context.Context, o *domain.Observation) error

func (*AuthorizedStore) VerifyToken

func (s *AuthorizedStore) VerifyToken(ctx context.Context, secret, scope string) (identity.Principal, error)

type EntityRepository

type EntityRepository struct{ *Store }

func (*EntityRepository) DeleteByObservation

func (r *EntityRepository) DeleteByObservation(ctx context.Context, id int64) error

func (*EntityRepository) FindByEntity

func (r *EntityRepository) FindByEntity(ctx context.Context, typ, val string) (out []*domain.EntityLink, err error)

func (*EntityRepository) GetByObservation

func (r *EntityRepository) GetByObservation(ctx context.Context, id int64) (out []*domain.EntityLink, err error)
func (r *EntityRepository) SaveLinks(ctx context.Context, links []*domain.EntityLink) error

type GraphRepository

type GraphRepository struct{ *Store }

func (*GraphRepository) CountAllEdges

func (r *GraphRepository) CountAllEdges(ctx context.Context) (n int, err error)

func (*GraphRepository) CountEdgesByObservation

func (r *GraphRepository) CountEdgesByObservation(ctx context.Context, id int64) (n int, err error)

func (*GraphRepository) CreateEdge

func (r *GraphRepository) CreateEdge(ctx context.Context, e *domain.Edge) error

func (*GraphRepository) DeleteEdge

func (r *GraphRepository) DeleteEdge(ctx context.Context, id int64) error

func (*GraphRepository) GetContradictions

func (r *GraphRepository) GetContradictions(ctx context.Context, from, to time.Time) ([]*domain.Edge, error)

func (*GraphRepository) GetEdge

func (r *GraphRepository) GetEdge(ctx context.Context, id int64) (*domain.Edge, error)

func (*GraphRepository) GetEdgeByPublicID

func (r *GraphRepository) GetEdgeByPublicID(ctx context.Context, publicID string) (*domain.Edge, error)

func (*GraphRepository) GetEdgesForObservation

func (r *GraphRepository) GetEdgesForObservation(ctx context.Context, id int64) (out []*domain.Edge, err error)

func (*GraphRepository) GetEvolutionChain

func (r *GraphRepository) GetEvolutionChain(ctx context.Context, a, b int64) ([]*domain.Edge, error)

func (*GraphRepository) GetRelated

func (r *GraphRepository) GetRelated(ctx context.Context, id int64, depth int) (out []*domain.Observation, err error)

func (*GraphRepository) UpdateEdge

func (r *GraphRepository) UpdateEdge(ctx context.Context, e *domain.Edge) error

type MultiTenantTokenPrincipalVerifier added in v2.3.0

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

MultiTenantTokenPrincipalVerifier is the SaaS data-plane verifier. It authenticates a bearer through one migration-owned SECURITY DEFINER routine that derives the candidate tenant from the stored, non-secret token prefix and verifies the tenant-bound HMAC before returning a principal. Requests never provide or select a tenant identifier.

func NewMultiTenantTokenPrincipalVerifier added in v2.3.0

func NewMultiTenantTokenPrincipalVerifier(pool *pgxpool.Pool) (*MultiTenantTokenPrincipalVerifier, error)

func (*MultiTenantTokenPrincipalVerifier) VerifyToken added in v2.3.0

func (v *MultiTenantTokenPrincipalVerifier) VerifyToken(ctx context.Context, secret, requiredScope string) (identity.Principal, error)

type ObservationRepository

type ObservationRepository struct{ *Store }

func (*ObservationRepository) CountAll

func (r *ObservationRepository) CountAll(ctx context.Context) (n int, err error)

func (*ObservationRepository) CountByRoot

func (r *ObservationRepository) CountByRoot(ctx context.Context, id int64) (n int, err error)

func (*ObservationRepository) CountEdgesAsObs

func (r *ObservationRepository) CountEdgesAsObs(ctx context.Context, id int64) (n int, err error)

func (*ObservationRepository) Delete

func (r *ObservationRepository) Delete(ctx context.Context, id int64) error

func (*ObservationRepository) GetByID

func (*ObservationRepository) GetByPublicID

func (r *ObservationRepository) GetByPublicID(ctx context.Context, publicID string) (*domain.Observation, error)

func (*ObservationRepository) GetBySource

func (r *ObservationRepository) GetBySource(ctx context.Context, source string, limit int) ([]*domain.Observation, error)

func (*ObservationRepository) GetByTopicKey

func (r *ObservationRepository) GetByTopicKey(ctx context.Context, project, key string) (*domain.Observation, error)

func (*ObservationRepository) GetByType

func (r *ObservationRepository) GetByType(ctx context.Context, typ string, limit int) ([]*domain.Observation, error)

func (*ObservationRepository) List

func (*ObservationRepository) ListArchivable

func (r *ObservationRepository) ListArchivable(ctx context.Context, cutoff time.Time, minScore float64, limit int) ([]*domain.Observation, error)

ListArchivable returns old, low-importance observations for lifecycle jobs. Importance is currently represented by the supplied score threshold; the server schema keeps lifecycle filtering tenant-scoped inside the transaction.

func (*ObservationRepository) Save

Save keeps the legacy contract and delegates to SaveWithEffect, preserving signature, topic upsert, and unconditional duplicate inserts (REM-SAVE-001, RD2).

func (*ObservationRepository) SaveBulk

func (r *ObservationRepository) SaveBulk(ctx context.Context, observations []*domain.Observation) error

SaveBulk persists an already-authorized batch in one transaction. Authorization belongs to the facade; this repository method only provides atomic persistence.

func (*ObservationRepository) SaveWithEffect

SaveWithEffect persists the observation and reports the durable write status decided inside the same transaction. REM-SAVE-001 compatibility: the interactive path preserves the exact legacy Save observable — topic upsert plus unconditional insert — and never performs dedup replay; manual duplicates always produce a second durable row. Dedup classification is a handoff-only concern (saveWithEffectInTx).

func (*ObservationRepository) Update

type OutboxIntent

type OutboxIntent struct {
	ID            int64
	ObservationID int64
	Intent        string
	Status        string
	Attempts      int
	AvailableAt   time.Time
	LeaseOwner    string
	LeasedUntil   *time.Time
	Error         string
	CompletedAt   *time.Time
	AffectedRows  int
}

type OutboxStore

type OutboxStore struct{ *Store }

func (*OutboxStore) DeadLetter

func (r *OutboxStore) DeadLetter(ctx context.Context, id int64, cause error) error

func (*OutboxStore) EnqueueInTx

func (r *OutboxStore) EnqueueInTx(ctx context.Context, id int64, intent, model string) error

func (*OutboxStore) Lease

func (r *OutboxStore) Lease(ctx context.Context, limit int) (out []OutboxIntent, err error)

func (*OutboxStore) MarkComplete

func (r *OutboxStore) MarkComplete(ctx context.Context, id int64) error

func (*OutboxStore) MarkFailed

func (r *OutboxStore) MarkFailed(ctx context.Context, id int64, cause error, next time.Time) error

func (*OutboxStore) PendingCount

func (r *OutboxStore) PendingCount(ctx context.Context) (n int, err error)

func (*OutboxStore) RecoverPending

func (r *OutboxStore) RecoverPending(ctx context.Context) error

func (*OutboxStore) WithinTx

func (r *OutboxStore) WithinTx(ctx context.Context, h any, fn func(context.Context) error) error

type PostgresCodeStore added in v2.3.0

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

PostgresCodeStore runs only inside an authorized, project-bound transaction. Schema ownership remains exclusively in forward migrations.

func (*PostgresCodeStore) CountSymbols added in v2.3.0

func (s *PostgresCodeStore) CountSymbols(ctx context.Context, filter code.SymbolFilter) (int, error)

func (*PostgresCodeStore) DeleteRelationsByFile added in v2.3.0

func (s *PostgresCodeStore) DeleteRelationsByFile(ctx context.Context, project, filePath string) error

func (*PostgresCodeStore) DeleteRelationsByProject added in v2.3.0

func (s *PostgresCodeStore) DeleteRelationsByProject(ctx context.Context, project string) error

func (*PostgresCodeStore) DeleteSymbolsByFile added in v2.3.0

func (s *PostgresCodeStore) DeleteSymbolsByFile(ctx context.Context, project, filePath string) error

func (*PostgresCodeStore) DeleteSymbolsByProject added in v2.3.0

func (s *PostgresCodeStore) DeleteSymbolsByProject(ctx context.Context, project string) error

func (*PostgresCodeStore) GetGraph added in v2.3.0

func (s *PostgresCodeStore) GetGraph(ctx context.Context, project string) (*code.CodeGraph, error)

func (*PostgresCodeStore) GetSymbolByID added in v2.3.0

func (s *PostgresCodeStore) GetSymbolByID(ctx context.Context, id string) (*code.Symbol, error)

func (*PostgresCodeStore) ListRelationsBySymbol added in v2.3.0

func (s *PostgresCodeStore) ListRelationsBySymbol(ctx context.Context, symbolID string) ([]code.Relation, error)

func (*PostgresCodeStore) ListSymbols added in v2.3.0

func (s *PostgresCodeStore) ListSymbols(ctx context.Context, filter code.SymbolFilter) ([]code.Symbol, error)

func (*PostgresCodeStore) SaveRelations added in v2.3.0

func (s *PostgresCodeStore) SaveRelations(ctx context.Context, relations []code.Relation) error

func (*PostgresCodeStore) SaveSymbols added in v2.3.0

func (s *PostgresCodeStore) SaveSymbols(ctx context.Context, symbols []code.Symbol) error

type PostgresReindexSource added in v2.3.0

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

PostgresReindexSource is a read-only view of one project corpus. Its internal project key is resolved once from a granted public UUID inside the principal-bound transaction and is never accepted from CLI input.

func NewPostgresReindexSource added in v2.3.0

func NewPostgresReindexSource(ctx context.Context, store *AuthorizedStore, projectPublicID string) (*PostgresReindexSource, error)

func (*PostgresReindexSource) CanonicalProjectLabel added in v2.3.0

func (s *PostgresReindexSource) CanonicalProjectLabel() string

func (*PostgresReindexSource) DescribeCorpus added in v2.3.0

func (*PostgresReindexSource) GetEmbedding added in v2.3.0

func (s *PostgresReindexSource) GetEmbedding(ctx context.Context, scope external.ReindexScope, observationID int64) ([]float32, string, error)

func (*PostgresReindexSource) List added in v2.3.0

func (*PostgresReindexSource) ReindexScope added in v2.3.0

func (s *PostgresReindexSource) ReindexScope() external.ReindexScope

func (*PostgresReindexSource) Scope added in v2.3.0

func (s *PostgresReindexSource) Scope(ctx context.Context, observationID int64) (external.ReindexScope, error)

type PromptRepository

type PromptRepository struct{ *Store }

func (*PromptRepository) List

func (r *PromptRepository) List(ctx context.Context, project string, limit int) (out []*domain.Prompt, err error)

func (*PromptRepository) Save

type SearchRepository

type SearchRepository struct{ *Store }

func (*SearchRepository) Search

func (r *SearchRepository) Search(ctx context.Context, query string, opts domain.SearchOptions) (out []*domain.SearchResult, err error)

type SessionRepository

type SessionRepository struct{ *Store }

func (*SessionRepository) Create

func (r *SessionRepository) Create(ctx context.Context, s *domain.Session) error

func (*SessionRepository) End

func (r *SessionRepository) End(ctx context.Context, id, summary string) error

func (*SessionRepository) GetByID

func (r *SessionRepository) GetByID(ctx context.Context, id string) (*domain.Session, error)

func (*SessionRepository) List

func (r *SessionRepository) List(ctx context.Context, project string) (out []*domain.Session, err error)

type Store

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

Store is a tenant-scoped PostgreSQL repository bundle.

func NewStore

func NewStore(pool *pgxpool.Pool, tenant *domain.TenantContext, principal domain.Principal) (*Store, error)

func (*Store) Backend

func (s *Store) Backend() string

func (*Store) BeginTx

func (s *Store) BeginTx(ctx context.Context) (domain.Tx, error)

func (*Store) ExecuteHandoff

func (s *Store) ExecuteHandoff(ctx context.Context, scope domain.HandoffScope, key string, canonical domain.CanonicalHandoff, hash [32]byte) (domain.ObservationWriteResult, error)

ExecuteHandoff implements domain.HandoffExecutor for the PostgreSQL namespace. Claim/read, observation materialization, optional relation, and receipt finalize all share one authorized transaction: any failure rolls every effect back, and a retry with the same key replays the receipt. Relation targets are not revalidated here; use executeHandoff with an in-transaction authorizer (the AuthorizedStore path) for that.

func (*Store) GetAllScores

func (r *Store) GetAllScores(ctx context.Context) ([]*domain.ImportanceScore, error)

func (*Store) GetIncomingEdgeCount

func (r *Store) GetIncomingEdgeCount(ctx context.Context, obsID int64) (int, error)

func (*Store) GetObservation

func (r *Store) GetObservation(ctx context.Context, obsID int64) (*domain.Observation, error)

func (*Store) GetScore

func (r *Store) GetScore(ctx context.Context, obsID int64) (*domain.ImportanceScore, error)

GetScore retrieves the tenant-scoped score for an observation.

func (*Store) GetTop

func (r *Store) GetTop(ctx context.Context, project string, limit int) ([]*domain.ImportanceScore, error)

GetTop retrieves tenant-scoped scores for a project.

func (*Store) GetTopByScore

func (r *Store) GetTopByScore(ctx context.Context, project string, limit int) ([]*domain.ImportanceScore, error)

func (*Store) Health

func (s *Store) Health(ctx context.Context) domain.Health

func (*Store) RecordAccess

func (r *Store) RecordAccess(ctx context.Context, obsID int64) error

func (*Store) SetScore

func (r *Store) SetScore(ctx context.Context, obsID int64, score float64) error

func (*Store) UpdateScore

func (r *Store) UpdateScore(ctx context.Context, obsID int64, increment float64) error

UpdateScore adjusts a score and clamps it to the domain range.

func (*Store) WithinTx

func (s *Store) WithinTx(ctx context.Context, handle any, fn func(context.Context) error) error

type SystemService

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

SystemService is the only capability granted to background lifecycle work. It intentionally exposes no repository and derives its identity from the already verified server principal; clients cannot construct or supply it.

func NewSystemService

func NewSystemService(store *AuthorizedStore) (*SystemService, error)

func (*SystemService) Delete

func (s *SystemService) Delete(ctx context.Context, id int64) error

func (*SystemService) ListArchivable

func (s *SystemService) ListArchivable(ctx context.Context, cutoff time.Time, minScore float64, limit int) ([]*domain.Observation, error)

type TokenPrincipalVerifier

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

TokenPrincipalVerifier is the narrow, verification-only PostgreSQL capability for the pre-composition window: authentication runs before any principal exists, and NewStore requires a verified principal, so a middleware verifier cannot hold a repository. The verifier pins ONE fixed tenant whose UUID keys the credential digest HMAC; the mediated routine derives the actual tenant from the credential itself, so a token issued under any other tenant never matches. It holds no principal, no grant digest, and no mutation surface — VerifyToken is its only method — and it never logs or persists the presented secret or the returned provenance.

func NewTokenPrincipalVerifier

func NewTokenPrincipalVerifier(pool *pgxpool.Pool, tenantID string) (*TokenPrincipalVerifier, error)

NewTokenPrincipalVerifier builds the fixed-tenant verifier over an application-role pool. The tenant comes from configuration, never from a request; pool and tenant id are validated fail-closed before any credential is accepted. uuid.Parse accepts uppercase, raw, URN, and braced spellings, but migration 106 derives credential digests from the canonical uuid::text form, so the parsed UUID is canonicalized before it is stored: every accepted spelling keys the same tenant digest HMAC.

func (*TokenPrincipalVerifier) VerifyToken

func (v *TokenPrincipalVerifier) VerifyToken(ctx context.Context, secret, requiredScope string) (identity.Principal, error)

VerifyToken authenticates a presented secret with the same single cortex_verify_token_principal call the repository uses, inside its own principal-free transaction: nothing is bound before authentication succeeds. Errors keep the stable redacted taxonomy (ErrInvalidToken/ErrTokenRevoked/ErrTokenExpired/ErrInsufficientScope) and the returned Principal.GrantDigest is verify-minted provenance only.

type TokenRepository

type TokenRepository struct{ *Store }

TokenRepository persists API credentials in PostgreSQL. Plaintext secrets are returned only by Issue and are never stored. Every token lifecycle mutation (issue, rotate, revoke) and verification execute exclusively through the migration-owned SECURITY DEFINER routines installed by the unshipped 106 server migration; the application role holds no direct api_tokens write and cannot select token_digest.

func (*TokenRepository) Issue

func (*TokenRepository) List

func (r *TokenRepository) List(ctx context.Context) (out []identity.TokenRecord, err error)

List returns metadata only. Secret and digest material are never exposed. It reads the non-sensitive api_tokens columns regranted by 106; the digest column is not part of the application role's column grant.

func (*TokenRepository) Revoke

func (r *TokenRepository) Revoke(ctx context.Context, id string) error

func (*TokenRepository) Rotate

func (*TokenRepository) Verify

func (r *TokenRepository) Verify(ctx context.Context, secret, requiredScope string) (identity.Principal, error)

Verify authenticates a presented secret through cortex_verify_token_principal. The routine locks the matched token, enforces revocation, expiry, subject liveness and the required scope, aggregates durable grants, folds last_used_at into the same transaction, and mints the one-time binding provenance consumed by cortex_bind_principal. The returned Principal.GrantDigest is that verify-minted provenance only — it is bearer-equivalent, must stay in memory, and is never a configured or recomputable grant digest.

type UserRepository

type UserRepository struct{ *Store }

UserRepository persists application users. Identity provisioning, grant reads, and activation state changes execute exclusively through the migration-owned SECURITY DEFINER routines installed by the unshipped 106 server migration; the application role holds no direct DML on actor_subjects or principal_grants and cannot read grant digests or versions.

func (*UserRepository) Create

func (*UserRepository) GetByPublicID

func (r *UserRepository) GetByPublicID(ctx context.Context, id string) (*identity.UserRecord, error)

func (*UserRepository) List

func (*UserRepository) SetActive

func (r *UserRepository) SetActive(ctx context.Context, id string, active bool) error

Jump to

Keyboard shortcuts

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