Help us shape the future of Go! Take the 2026 Go Developer Survey

store

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: Apache-2.0 Imports: 41 Imported by: 0

Documentation

Overview

Package store will persist AgentSQL metadata and audit records.

Package store persists AgentSQL metadata and immutable audit records.

Index

Constants

View Source
const (
	RedactionActivationFirst      = "first_activated"
	RedactionActivationSwitched   = "switched"
	RedactionActivationRolledBack = "rolled_back"
)
View Source
const APIKeyPrefix = "asql_"

APIKeyPrefix identifies AgentSQL plaintext API keys.

View Source
const DefaultTenantID = "tenant_default"
View Source
const (
	// DemoSeedSessionPrefix is reserved exclusively for Live Demo seed data.
	// Only the demo-seed command may call SeedHistoricalAudits, and only after
	// verifying config.Demo.Enabled=true. Production paths must never use it.
	DemoSeedSessionPrefix = "demo-seed:v1:"
)
View Source
const MaxTaskReadGrantDuration = 24 * time.Hour
View Source
const MaxTaskReadGrantUses int64 = 10

Variables

View Source
var (
	// ErrAdminRefreshTokenInvalid is returned for an unknown, expired, or
	// otherwise unusable refresh token.
	ErrAdminRefreshTokenInvalid = errors.New("invalid admin refresh token")
	// ErrAdminRefreshTokenReplay identifies reuse of a rotated or revoked
	// refresh token. The repository revokes the whole refresh family before
	// returning this error.
	ErrAdminRefreshTokenReplay = errors.New("admin refresh token replay detected")
)
View Source
var (
	// ErrInvalidPage indicates that a page number is less than one.
	ErrInvalidPage = errors.New("page must be at least 1")
	// ErrInvalidPageSize indicates that a page size is outside the safe range.
	ErrInvalidPageSize = errors.New("page_size must be between 1 and 1000")
	// ErrAuditEventAlreadyDelivered identifies an idempotent outbox replay.
	ErrAuditEventAlreadyDelivered = errors.New("audit event was already delivered")
)
View Source
var (
	ErrB5CASConflict       = errors.New("b5 store compare-and-swap conflict")
	ErrB5ReceiptConflict   = errors.New("b5 result receipt immutable conflict")
	ErrB5InvalidTransition = errors.New("b5 store invalid state transition")
)
View Source
var (
	// ErrChainCoverageIncomplete indicates that not every audit row is fully linked to the state head.
	ErrChainCoverageIncomplete = errors.New("audit chain coverage is incomplete")
	// ErrChainModeDowngrade indicates that database state disagrees with the trusted manifest.
	ErrChainModeDowngrade = errors.New("audit chain mode or key version disagrees with trusted manifest: mode_downgrade")
)
View Source
var (
	// ErrBuildLeaseActive indicates that another owner holds an unexpired build lease.
	ErrBuildLeaseActive = errors.New("audit chain build lease is active")
	// ErrStaleBuildFencing indicates that a build owner or epoch no longer owns the build.
	ErrStaleBuildFencing = errors.New("stale audit chain build fencing token")
	// ErrChainAlreadyActive indicates that an active chain cannot be rebuilt in place.
	ErrChainAlreadyActive = errors.New("audit chain is already active")
	// ErrBuildNotInProgress indicates that the chain is not currently being built.
	ErrBuildNotInProgress = errors.New("audit chain build is not in progress")
	// ErrInvalidBuildMode indicates that a requested chain mode is unsupported.
	ErrInvalidBuildMode = errors.New("invalid audit chain build mode")
)
View Source
var (
	// ErrSecretMissing indicates that AGENTSQL_SECRET is unset or empty.
	ErrSecretMissing = errors.New("AGENTSQL_SECRET is required")
	// ErrSecretLength indicates that AGENTSQL_SECRET is not a 32-byte AES key.
	ErrSecretLength = errors.New("AGENTSQL_SECRET must be exactly 32 bytes")
	// ErrInvalidCiphertext indicates that an encrypted password cannot be authenticated.
	ErrInvalidCiphertext = errors.New("invalid datasource password ciphertext")
	// ErrCipherUnavailable indicates that a password cipher was not initialized.
	ErrCipherUnavailable = errors.New("datasource password cipher is not initialized")
)
View Source
var (
	// ErrDemoSeedUnsafeDatabase means the audit target contains non-demo data.
	ErrDemoSeedUnsafeDatabase = errors.New("demo historical seed refused: audit store contains non-demo data")
	// ErrDemoSeedConflict means immutable seed data differs or only part of a
	// requested audit batch already exists.
	ErrDemoSeedConflict = errors.New("demo historical seed conflicts with persisted data")
)
View Source
var (
	ErrFenceLost       = errors.New("control-plane fence lost")
	ErrProtocolBlocked = errors.New("runtime protocol is not permitted")
	ErrActivationGate  = errors.New("protocol-3 activation gate is not ready")
)
View Source
var (
	ErrOutboxEventAlreadyExists     = errors.New("management audit outbox event already exists")
	ErrUnsafeManagementAuditDetails = errors.New("management audit details contain prohibited secret material")
)
View Source
var (
	// ErrStreamEventsPurged indicates that at least one event required for a
	// contiguous replay is no longer available.
	ErrStreamEventsPurged = errors.New("stream events purged and no longer available")
	// ErrMCPStreamNotFound indicates that the requested stream was never opened
	// or that its expired cursor has already been reclaimed.
	ErrMCPStreamNotFound = errors.New("MCP stream not found")
)
View Source
var (
	ErrInvalidRedactionKeyID          = errors.New("redaction key version ID must be canonical decimal text in range 1..9999")
	ErrInvalidKeyCommitment           = errors.New("redaction key commitment must be 64 lowercase hexadecimal characters")
	ErrRedactionKeyCommitmentConflict = errors.New("redaction key commitment conflicts with the registered value")
	ErrRedactionKeyTransition         = errors.New("redaction key state transition is not allowed")
	ErrRedactionKeyIntegrity          = errors.New("redaction key registry integrity violation")
)
View Source
var (
	// ErrNotFound indicates that a requested store entity does not exist.
	ErrNotFound = errors.New("store entity not found")
	// ErrInvalidStorePath indicates that the SQLite path is empty.
	ErrInvalidStorePath = errors.New("SQLite path is required")
	// ErrInvalidPostgresDSN indicates that the PostgreSQL DSN is empty.
	ErrInvalidPostgresDSN = errors.New("PostgreSQL DSN is required")
	// ErrInvalidMetadataDriver indicates an unsupported metadata-store driver.
	ErrInvalidMetadataDriver = errors.New("unsupported metadata store driver")
	// ErrInvalidAuditDriver indicates an unsupported independent audit driver.
	ErrInvalidAuditDriver = errors.New("unsupported audit store driver")
	// ErrNilContext indicates that a store operation received no context.
	ErrNilContext = errors.New("context is required")
)
View Source
var (
	ErrTaskReadGrantRequestInvalid  = errors.New("invalid task read grant request")
	ErrTaskReadGrantRequestConflict = errors.New("task read grant request conflict")
)
View Source
var ErrAgentNotFound = errors.New("agent not found")

ErrAgentNotFound indicates that an Agent lookup returned no record.

View Source
var ErrApprovalNotExecutable = errors.New("approval is not executable")
View Source
var ErrApprovalNotPending = errors.New("approval is no longer pending")
View Source
var ErrApprovalReplayConflict = errors.New("approval replay conflicts with persisted record")

ErrApprovalReplayConflict indicates that a separated-store saga found an approval with the same ID but different immutable pending-request fields.

View Source
var ErrInvalidDiscoveryDraft = errors.New("invalid discovery draft")
View Source
var ErrMaskRuleConflict = errors.New("mask rule normalized scope and column conflict")
View Source
var ErrRevisionMismatch = errors.New("store revision mismatch")
View Source
var ErrTaskReadGrantInvalid = errors.New("invalid task read grant")

ErrTaskReadGrantInvalid is returned when a temporary grant violates its bounded, tenant-scoped storage contract.

View Source
var ErrTenantRequired = errors.New("tenant ID is required")

Functions

func AuditMigrationVersions

func AuditMigrationVersions(ctx context.Context, database *sql.DB, dialect Dialect) (int, int, error)

AuditMigrationVersions returns current and code-latest audit versions.

func ExitCodeForVerification

func ExitCodeForVerification(outcome ChainVerificationOutcome, verifyErr error) int

ExitCodeForVerification maps a verification observation to the stable CLI process contract without making the verifier itself depend on a CLI.

func GenerateAPIKey

func GenerateAPIKey() (plaintext string, hash string, err error)

GenerateAPIKey creates a random API key and its SHA-256 hexadecimal digest. Callers must return the plaintext once and persist only the digest.

func HashAPIKey

func HashAPIKey(plaintext string) string

HashAPIKey returns the lowercase hexadecimal SHA-256 digest of plaintext.

func IsInvalidDiscoveryDraft

func IsInvalidDiscoveryDraft(err error) bool

IsInvalidDiscoveryDraft reports a structurally invalid discovery draft.

func IsMaskRuleConflict

func IsMaskRuleConflict(err error) bool

IsMaskRuleConflict reports whether a repository write collided with the database-enforced normalized (datasource, schema, table, column) key.

func LatestCombinedSQLiteMigrationVersion

func LatestCombinedSQLiteMigrationVersion() (int, error)

LatestCombinedSQLiteMigrationVersion returns the schema version required of a source database accepted by the SQLite-to-PostgreSQL搬迁器. The source is deliberately limited to the combined SQLite migration stream.

func MetadataMigrationVersions

func MetadataMigrationVersions(ctx context.Context, database *sql.DB, dialect Dialect, auditSeparate bool) (int, int, error)

MetadataMigrationVersions returns current and code-latest metadata versions.

func Migrate

func Migrate(ctx context.Context, database *sql.DB, dialect Dialect) error

Migrate applies each embedded migration exactly once in version order.

func MigrateAudit

func MigrateAudit(ctx context.Context, database *sql.DB, dialect Dialect) error

MigrateAudit applies the independent audit-only migration stream.

func MigrateMetadata

func MigrateMetadata(ctx context.Context, database *sql.DB, dialect Dialect, auditSeparate bool) error

MigrateMetadata applies the metadata migration stream for the requested layout. The combined stream remains byte-for-byte unchanged when audit data shares the metadata database.

func RollbackMetadataMigration

func RollbackMetadataMigration(ctx context.Context, database *sql.DB, dialect Dialect, auditSeparate bool, version int) error

RollbackMetadataMigration applies the checked-in down migration for the current metadata version. Repeating the same version is a no-op; skipping a newer applied version is rejected.

func VerifyAuditSchema

func VerifyAuditSchema(ctx context.Context, database *sql.DB, dialect Dialect) error

VerifyAuditSchema checks the deployed independent audit schema without DDL.

func VerifyFencing

func VerifyFencing(state ChainState, owner string, epoch int) error

VerifyFencing verifies that state belongs to the supplied in-progress build.

func VerifyMetadataSchema

func VerifyMetadataSchema(ctx context.Context, database *sql.DB, dialect Dialect, auditSeparate bool) error

VerifyMetadataSchema checks the deployed metadata schema without executing DDL. It is the fail-closed startup path used when auto_migrate is disabled.

func WithTenant added in v0.5.0

func WithTenant(ctx context.Context, tenantID string) (context.Context, error)

WithTenant binds an authenticated tenant to repository calls.

Types

type AdminRefreshSession added in v0.5.0

type AdminRefreshSession struct {
	FamilyID  string
	TokenHash string
	TenantID  string
	UserID    string
	Username  string
	CreatedAt time.Time
	ExpiresAt time.Time
}

AdminRefreshSession is the server-side identity bound to a refresh family. TokenHash is a SHA-256 digest encoded as lowercase hexadecimal; plaintext refresh tokens never cross into the store package.

type AdminSessionRepository added in v0.5.0

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

AdminSessionRepository persists administrator access-token revocations and rotating refresh-token families in the metadata database.

func (*AdminSessionRepository) CreateRefreshSession added in v0.5.0

func (repository *AdminSessionRepository) CreateRefreshSession(ctx context.Context, session AdminRefreshSession) error

CreateRefreshSession creates one refresh family and its initial token. It also lazily removes records whose own expiry can no longer affect security.

func (*AdminSessionRepository) RevokeAccessAndRefreshFamily added in v0.5.0

func (repository *AdminSessionRepository) RevokeAccessAndRefreshFamily(ctx context.Context, jti, familyID string, accessExpires, now time.Time) error

RevokeAccessAndRefreshFamily atomically records an access jti revocation and revokes its associated refresh family. Legacy access tokens without a family still receive a durable jti revocation.

func (*AdminSessionRepository) RevokeAccessJTI added in v1.1.0

func (repository *AdminSessionRepository) RevokeAccessJTI(ctx context.Context, jti string, expiresAt, now time.Time) error

RevokeAccessJTI revokes one short-lived delegated token without ending the parent console session or other delegations in its refresh family.

func (*AdminSessionRepository) RevokeRefreshFamily added in v0.5.0

func (repository *AdminSessionRepository) RevokeRefreshFamily(ctx context.Context, familyID string, now time.Time) error

RevokeRefreshFamily is used when identity revalidation fails after an otherwise successful rotation. No replacement token is returned to the caller unless this fail-closed cleanup succeeds.

func (*AdminSessionRepository) RotateRefreshToken added in v0.5.0

func (repository *AdminSessionRepository) RotateRefreshToken(ctx context.Context, oldHash, newHash string, now time.Time) (AdminRefreshSession, error)

RotateRefreshToken consumes oldHash and inserts newHash atomically. Reuse of a consumed token revokes every token in the family before returning.

func (*AdminSessionRepository) ValidateAccessToken added in v0.5.0

func (repository *AdminSessionRepository) ValidateAccessToken(ctx context.Context, jti, familyID string, now time.Time) (bool, error)

ValidateAccessToken checks both its jti revocation record and, for tokens issued with refresh support, the persisted refresh-family state.

type AgentRankingItem

type AgentRankingItem struct {
	AgentID      string `json:"agent_id"`
	Name         string `json:"name"`
	BlockedCount int64  `json:"blocked_count"`
}

type AgentRepository

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

AgentRepository provides CRUD operations for agents.

func (*AgentRepository) Create

func (repository *AgentRepository) Create(ctx context.Context, agent model.Agent) (model.Agent, error)

Create inserts an agent and returns the stored record.

func (*AgentRepository) Delete

func (repository *AgentRepository) Delete(ctx context.Context, id string) error

Delete removes an agent by ID.

func (*AgentRepository) Get

func (repository *AgentRepository) Get(ctx context.Context, id string) (model.Agent, error)

Get returns an agent by ID.

func (*AgentRepository) GetByAPIKeyHash

func (repository *AgentRepository) GetByAPIKeyHash(
	ctx context.Context,
	hash string,
) (model.Agent, error)

GetByAPIKeyHash returns an Agent by an exact SHA-256 API key digest.

func (*AgentRepository) List

func (repository *AgentRepository) List(ctx context.Context) ([]model.Agent, error)

List returns all agents ordered by creation time and ID.

func (*AgentRepository) Update

func (repository *AgentRepository) Update(ctx context.Context, agent model.Agent) (model.Agent, error)

Update replaces mutable agent fields and returns the stored record.

type ApprovalPage

type ApprovalPage struct {
	Total    int64
	Page     int
	PageSize int
	List     []model.Approval
}

type ApprovalRepository

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

ApprovalRepository provides CRUD operations for approval records.

func (*ApprovalRepository) ClaimApproved added in v0.6.0

func (repository *ApprovalRepository) ClaimApproved(
	ctx context.Context, id, agentID string, now time.Time,
) (claimed model.Approval, err error)

ClaimApproved consumes a sealed approval exactly once. A claimed request stays claimed across process restarts and is never made executable again.

func (*ApprovalRepository) ClaimApprovedForRequester added in v1.1.0

func (repository *ApprovalRepository) ClaimApprovedForRequester(
	ctx context.Context, id, agentID, requesterUserID string, now time.Time,
) (model.Approval, error)

ClaimApprovedForRequester atomically checks the delegated human owner. A mismatch leaves the approval untouched and therefore cannot consume it.

func (*ApprovalRepository) CompleteClaim added in v0.6.0

func (repository *ApprovalRepository) CompleteClaim(
	ctx context.Context, id, agentID, status string, auditID *int64, outcomeCode *string, now time.Time,
) (model.Approval, error)

CompleteClaim records the final outcome after one claimed execution. A failed persistence attempt leaves claimed as a manual-review state.

func (*ApprovalRepository) Create

func (repository *ApprovalRepository) Create(ctx context.Context, approval model.Approval) (model.Approval, error)

Create inserts an approval and returns the stored record.

func (*ApprovalRepository) CreatePendingWithAudit

func (repository *ApprovalRepository) CreatePendingWithAudit(
	ctx context.Context,
	approval model.Approval,
	auditLog model.AuditLog,
) (created model.Approval, recorded model.AuditLog, err error)

CreatePendingWithAudit atomically inserts both records when metadata and audit share a database. With separate databases it writes the immutable audit record first, then inserts the linked approval in a metadata transaction; a metadata failure therefore leaves a valid orphan audit.

func (*ApprovalRepository) DecidePending

func (repository *ApprovalRepository) DecidePending(
	ctx context.Context,
	id string,
	status string,
	approver string,
	reason *string,
	decidedAt time.Time,
) (updated model.Approval, err error)

DecidePending atomically transitions one pending approval and returns the committed record. A missing approval and a completed approval are distinct.

func (*ApprovalRepository) Delete

func (repository *ApprovalRepository) Delete(ctx context.Context, id string) error

Delete removes an approval by ID.

func (*ApprovalRepository) Get

func (repository *ApprovalRepository) Get(ctx context.Context, id string) (model.Approval, error)

Get returns an approval by ID.

func (*ApprovalRepository) ListPage

func (repository *ApprovalRepository) ListPage(
	ctx context.Context,
	status string,
	page int,
	pageSize int,
) (ApprovalPage, error)

ListPage returns approvals ordered newest first, optionally filtered by status.

func (*ApprovalRepository) Update

func (repository *ApprovalRepository) Update(ctx context.Context, approval model.Approval) (model.Approval, error)

Update replaces mutable approval fields and returns the stored record.

type AuditLogReader added in v0.5.0

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

AuditLogReader provides read-only audit queries for operational tools that already own a database connection.

func NewAuditLogReader added in v0.5.0

func NewAuditLogReader(database *sql.DB, dialect Dialect) *AuditLogReader

NewAuditLogReader binds read-only audit queries to an existing connection.

func (*AuditLogReader) FilteredPage added in v0.5.0

func (reader *AuditLogReader) FilteredPage(
	ctx context.Context,
	filter model.AuditFilter,
	page int,
	pageSize int,
) (AuditPage, error)

FilteredPage returns matching audit logs ordered newest first.

type AuditLogRepository

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

AuditLogRepository provides append and paginated read operations only.

func (*AuditLogRepository) AppendBatch

func (repository *AuditLogRepository) AppendBatch(ctx context.Context, logs []model.AuditLog) ([]model.AuditLog, error)

AppendBatch appends logs in input order. When chaining is enabled, the complete batch and the single head update are committed atomically.

func (*AuditLogRepository) FilteredPage

func (repository *AuditLogRepository) FilteredPage(
	ctx context.Context,
	filter model.AuditFilter,
	page int,
	pageSize int,
) (AuditPage, error)

FilteredPage returns matching audit logs ordered newest first.

func (*AuditLogRepository) FindByEventUUIDs

func (repository *AuditLogRepository) FindByEventUUIDs(
	ctx context.Context,
	uuids []string,
) ([]model.AuditLog, error)

FindByEventUUIDs returns persisted rows for the supplied event UUIDs. Rows include every business column used by canonical audit-chain encoding.

func (*AuditLogRepository) Insert

func (repository *AuditLogRepository) Insert(ctx context.Context, auditLog model.AuditLog) (model.AuditLog, error)

Insert appends an audit log and returns the record with generated ID and timestamp.

func (*AuditLogRepository) Page

func (repository *AuditLogRepository) Page(ctx context.Context, page, pageSize int) (AuditPage, error)

Page returns audit logs ordered newest first.

type AuditOptions

type AuditOptions struct {
	Separate     bool
	Driver       Dialect
	PostgresDSN  string
	MaxOpenConns int
	MaxIdleConns int
	AutoMigrate  bool
}

AuditOptions configures the optional independent audit connection.

type AuditPage

type AuditPage = model.AuditPage

AuditPage preserves the store API while the shared shape lives in model.

type AuditStoreView

type AuditStoreView interface {
	MigrationVersions(context.Context) (current, latest int, err error)
	AuditLogs() *AuditLogRepository
	Close() error
}

AuditStoreView is the audit-only surface used by management audit delivery.

func OpenAuditOnly

func OpenAuditOnly(ctx context.Context, options AuditOptions) (AuditStoreView, error)

OpenAuditOnly opens and prepares an independent PostgreSQL audit target.

type B5DMLGrant

type B5DMLGrant struct {
	GrantID, PolicyID, PrincipalID, DatasourceID               string
	PolicyRevision                                             int64
	Effect                                                     b5.GrantEffect
	Element                                                    b5.GrantElement
	Action                                                     b5.DMLAction
	DatabaseOID, RelationOID                                   uint32
	RelationKind, SchemaName, RelationName, CatalogFingerprint string
	WriteTargetKind                                            *string
	ColumnAttnum                                               *int
	ColumnName                                                 *string
	ColumnTypeOID                                              *uint32
	ColumnTypeModifier                                         *int
	ColumnCollationOID                                         *uint32
	ReferenceKind                                              *string
	ProofSchemaID                                              string
	ProofSchemaVersion                                         uint16
	ProofDigest                                                []byte
	CreatedAt, UpdatedAt                                       time.Time
	Revision                                                   int64
}

type B5DMLGrantRepository

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

func (*B5DMLGrantRepository) Create

func (*B5DMLGrantRepository) DeleteIfRevision

func (r *B5DMLGrantRepository) DeleteIfRevision(ctx context.Context, id string, revision int64) error

func (*B5DMLGrantRepository) Get

func (*B5DMLGrantRepository) List

func (r *B5DMLGrantRepository) List(ctx context.Context, principal, datasource string, action b5.DMLAction, limit int) ([]B5DMLGrant, error)

func (*B5DMLGrantRepository) UpdateIfRevision

func (r *B5DMLGrantRepository) UpdateIfRevision(ctx context.Context, v B5DMLGrant, expected int64) (B5DMLGrant, error)

type B5DMLGrantStore

type B5DMLGrantStore interface {
	Create(context.Context, B5DMLGrant) (B5DMLGrant, error)
	Get(context.Context, string) (B5DMLGrant, error)
	List(context.Context, string, string, b5.DMLAction, int) ([]B5DMLGrant, error)
	UpdateIfRevision(context.Context, B5DMLGrant, int64) (B5DMLGrant, error)
	DeleteIfRevision(context.Context, string, int64) error
}

type B5ReceiptAdvance

type B5ReceiptAdvance struct {
	AppendConfirmation *b5.AppendConfirmation
	Reconciliation     *b5.Reconciliation
	DeliveryStatus     *b5.DeliveryStatus
}

type B5ReceiptKey

type B5ReceiptKey struct {
	SessionID, RequestID string
	EventUUID            []byte
	AttemptGeneration    uint64
}

type B5ResultReceipt

type B5ResultReceipt struct {
	Key                                         B5ReceiptKey
	SchemaID                                    string
	SchemaVersion                               uint16
	BusinessEventDigest, WALAppendReceiptDigest []byte
	ReportedDurability                          b5.AuditDurability
	AppendConfirmation                          b5.AppendConfirmation
	Reconciliation                              b5.Reconciliation
	DeliveryStatus                              b5.DeliveryStatus
	CreatedAt, UpdatedAt                        time.Time
	Revision                                    int64
}

type B5ResultReceiptRepository

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

func (*B5ResultReceiptRepository) Advance

func (*B5ResultReceiptRepository) Get

func (*B5ResultReceiptRepository) ListByEventUUID

func (r *B5ResultReceiptRepository) ListByEventUUID(ctx context.Context, eventUUID []byte) ([]B5ResultReceipt, error)

ListByEventUUID joins the durable response plane to a verified WAL record. More than one row is possible because a request can be retried with a new attempt generation; callers must preserve every immutable historical value.

func (*B5ResultReceiptRepository) PutWriteOnce

type B5Session

type B5Session struct {
	SessionID, AgentID, TenantID, PrincipalID, OwnerInstanceID string
	OwnerEpoch                                                 uint64
	ContinuationSchemaID                                       string
	ContinuationSchemaVersion                                  uint16
	ContinuationKeyCiphertext                                  string
	ContinuationHMACDigest                                     []byte
	StickyRoute                                                string
	Status                                                     b5.SessionStatus
	IdleExpiresAt, AbsoluteExpiresAt, CreatedAt, UpdatedAt     time.Time
	Revision                                                   int64
}

type B5SessionFilter

type B5SessionFilter struct {
	Status, Owner, Query string
}

type B5SessionPage

type B5SessionPage struct {
	Total          int64
	List           []B5Session
	Page, PageSize int
}

type B5SessionRepository

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

func (*B5SessionRepository) CASOwner

func (r *B5SessionRepository) CASOwner(ctx context.Context, id string, expectedRevision int64, expectedOwner string, expectedEpoch uint64, newOwner, stickyRoute, keyCiphertext string, keyDigest []byte) (B5Session, error)

CASOwner is the S3 directory fencing primitive. Owner epoch advances by exactly one and the continuation key is re-sealed with AAD containing that new epoch in the same durable compare-and-swap.

func (*B5SessionRepository) CASStatus

func (r *B5SessionRepository) CASStatus(ctx context.Context, id string, expectedRevision int64, from, to b5.SessionStatus, idleExpiry time.Time) (B5Session, error)

func (*B5SessionRepository) Create

func (r *B5SessionRepository) Create(ctx context.Context, value B5Session) (B5Session, error)

func (*B5SessionRepository) Get

func (*B5SessionRepository) ListExpired

func (r *B5SessionRepository) ListExpired(ctx context.Context, now time.Time, limit int) ([]B5Session, error)

func (*B5SessionRepository) ListPage

func (r *B5SessionRepository) ListPage(ctx context.Context, filter B5SessionFilter, page, pageSize int) (B5SessionPage, error)

ListPage exposes only non-secret directory metadata. Continuation key ciphertext and HMAC material never cross the repository boundary here.

type B5SessionStore

B5 repository contracts are deliberately metadata-only and never grant access to a business executor.

type B5Transaction

type B5Transaction struct {
	TransactionID, SessionID, DatasourceID string
	Status                                 b5.TransactionStatus
	Phase                                  b5.TransactionPhase
	PlanDigest                             []byte
	ApprovalID                             *string
	OwnerEpoch                             uint64
	IdleDeadline, WallDeadline             time.Time
	StatementDeadline                      *time.Time
	BackendPID                             *int
	BackendSecretDigest                    []byte
	BackendStartedAt                       *time.Time
	ConnectionGeneration, LeaseGeneration  uint64
	StatementCount                         int
	TransactionSeq                         uint64
	PreviousTxEventDigest                  []byte
	CreatedAt, UpdatedAt                   time.Time
	Revision                               int64
}

type B5TransactionFilter

type B5TransactionFilter struct {
	Status, Phase, DatasourceID, Query string
}

type B5TransactionPage

type B5TransactionPage struct {
	Total          int64
	List           []B5Transaction
	Page, PageSize int
}

type B5TransactionProgress

type B5TransactionProgress struct {
	IdleDeadline         *time.Time
	StatementDeadline    **time.Time
	BackendPID           **int
	BackendSecretDigest  *[]byte
	BackendStartedAt     **time.Time
	ConnectionGeneration *uint64
	LeaseGeneration      *uint64
	StatementCount       *int
	TransactionSeq       *uint64
	PreviousEventDigest  *[]byte
}

B5TransactionProgress is the bounded mutable part of a live transaction. Pointers distinguish "leave unchanged" from a typed zero value. Callers must still own the transaction's current revision, status and phase; this prevents a late statement result from extending a deadline or advancing a sequence after a terminal/watchdog CAS has won.

type B5TransactionRepository

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

func (*B5TransactionRepository) CASProgress

CASProgress persists deadline, backend and ordered-statement progress without changing the lifecycle phase. It is intentionally one SQL update: recovery must never observe a new statement count with an old deadline (or vice versa), and stale operation owners must lose the revision CAS.

func (*B5TransactionRepository) CASState

func (r *B5TransactionRepository) CASState(ctx context.Context, id string, revision int64, fromStatus b5.TransactionStatus, fromPhase b5.TransactionPhase, toStatus b5.TransactionStatus, toPhase b5.TransactionPhase) (B5Transaction, error)

func (*B5TransactionRepository) Create

func (*B5TransactionRepository) Get

func (*B5TransactionRepository) ListExpired

func (r *B5TransactionRepository) ListExpired(ctx context.Context, now time.Time, limit int) ([]B5Transaction, error)

func (*B5TransactionRepository) ListPage

func (r *B5TransactionRepository) ListPage(ctx context.Context, filter B5TransactionFilter, page, pageSize int) (B5TransactionPage, error)

type B5TxEvent

type B5TxEvent struct {
	TransactionID                                      string
	TransactionSeq                                     uint64
	EventUUID                                          []byte
	EventType, EventSchemaID                           string
	EventSchemaVersion                                 uint16
	PreviousTxEventDigest, EventDigest, CanonicalEvent []byte
	TerminalEvidenceText, DispositionProofText         *string
	AuditLogID                                         *int64
	CreatedAt                                          time.Time
}

type B5TxEventRepository

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

func (*B5TxEventRepository) Append

func (*B5TxEventRepository) Get

func (r *B5TxEventRepository) Get(ctx context.Context, transactionID string, sequence uint64) (B5TxEvent, error)

func (*B5TxEventRepository) GetByUUID

func (r *B5TxEventRepository) GetByUUID(ctx context.Context, eventUUID []byte) (B5TxEvent, error)

func (*B5TxEventRepository) List

func (r *B5TxEventRepository) List(ctx context.Context, limit int) ([]B5TxEvent, error)

func (*B5TxEventRepository) ListByTransaction

func (r *B5TxEventRepository) ListByTransaction(ctx context.Context, transactionID string, limit int) ([]B5TxEvent, error)

type B5TxEventStore

type B5TxEventStore interface {
	Append(context.Context, B5TxEvent) error
	Get(context.Context, string, uint64) (B5TxEvent, error)
	GetByUUID(context.Context, []byte) (B5TxEvent, error)
	List(context.Context, int) ([]B5TxEvent, error)
}

type BackfillConfig

type BackfillConfig struct {
	BatchSize           int
	Lease               time.Duration
	RenewBeforeFraction float64
}

BackfillConfig controls bounded backfill transactions and build-lease renewal.

type BackfillResult

type BackfillResult struct {
	Linked             int64
	RemainingUnchained int64
	HeadSeq            int64
	Complete           bool
}

BackfillResult describes the frontier reached by one complete Run call.

type BackfillService

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

BackfillService links historical audit rows while a chain remains BUILDING.

func NewBackfillService

func NewBackfillService(
	db *sql.DB,
	dialect Dialect,
	chainID string,
	keys ChainKeyProvider,
	cfg BackfillConfig,
) *BackfillService

NewBackfillService constructs a backfill service for one audit-chain domain.

func (*BackfillService) Activate

func (service *BackfillService) Activate(
	ctx context.Context,
	owner string,
	epoch int,
	manifest ChainManifest,
) error

Activate validates a stable BUILDING snapshot, then installs the database contract and performs the fenced ACTIVE CAS in one short transaction.

func (*BackfillService) Run

func (service *BackfillService) Run(ctx context.Context, owner string, epoch int) (BackfillResult, error)

Run verifies the existing prefix, then links every currently unchained row in bounded transactions. It deliberately leaves the chain in BUILDING.

func (*BackfillService) Status

func (service *BackfillService) Status(ctx context.Context) (ChainState, error)

Status returns the persisted state for this backfill service's chain.

func (*BackfillService) VerifyPrefix

func (service *BackfillService) VerifyPrefix(ctx context.Context, owner string, epoch int) (headSeq int64, reason string, err error)

VerifyPrefix verifies the currently linked BUILDING prefix from genesis to the state head. A structural or cryptographic break is returned as a stable reason string rather than as an operational error.

type BattleReport

type BattleReport struct {
	BlockedCount int64 `json:"blocked_count"`
	EstRowsSaved int64 `json:"est_rows_saved"`
}

type BuildLease

type BuildLease struct {
	ChainID    string
	InstanceID string
	Epoch      int
	Owner      string
	LeaseUntil time.Time
}

BuildLease is the fencing token and lease held by one build owner.

type BuildRequest

type BuildRequest struct {
	Mode  string
	Owner string
	Lease time.Duration
}

BuildRequest describes a request to begin or take over an audit-chain build.

type ChainAccess

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

ChainAccess is a domain-bound view of the database resources needed to observe and verify an audit chain. It deliberately exposes repositories and verifier construction rather than a general-purpose database handle.

func (*ChainAccess) State

func (access *ChainAccess) State() *ChainStateRepository

State returns the read-only state repository for this chain database.

func (*ChainAccess) Verifier

func (access *ChainAccess) Verifier(manifest ChainManifest) *ChainVerifier

Verifier constructs the existing verifier against this chain database.

type ChainBuildRepository

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

ChainBuildRepository owns the write-only lifecycle operations for chain builds. ChainStateRepository intentionally remains read-only.

func (*ChainBuildRepository) BeginBuild

func (repository *ChainBuildRepository) BeginBuild(
	ctx context.Context,
	chainID string,
	req BuildRequest,
) (BuildLease, error)

BeginBuild starts a new chain instance or takes over an expired build lease.

func (*ChainBuildRepository) RenewLease

func (repository *ChainBuildRepository) RenewLease(
	ctx context.Context,
	chainID, owner string,
	epoch int,
	lease time.Duration,
) (BuildLease, error)

RenewLease extends the lease held by the matching owner and epoch.

func (*ChainBuildRepository) ResetBuild

func (repository *ChainBuildRepository) ResetBuild(
	ctx context.Context,
	chainID, owner string,
	epoch int,
) error

ResetBuild abandons a fenced build and removes all derived chain data so a later BeginBuild creates a new chain instance from the beginning.

type ChainKeyProvider

type ChainKeyProvider interface {
	ChainKeyForVersion(ctx context.Context, version int) ([]byte, error)
}

ChainKeyProvider returns trusted HMAC key material for a frozen chain key version. It must never silently substitute a keyless mode for a missing key.

type ChainManifest

type ChainManifest interface {
	ChainKeyProvider
	ExpectedMode(ctx context.Context) (string, error)
	CurrentKeyVersion(ctx context.Context) (int, error)
}

ChainManifest is the trusted, database-external authority for chain mode and keys. Keyless mode is explicit and uses key version zero.

type ChainManifestProvider

type ChainManifestProvider interface {
	ChainManifestForDomain(ctx context.Context, domain string) (ChainManifest, error)
}

ChainManifestProvider resolves trusted, database-external chain authority.

func NewKeylessChainManifestProvider

func NewKeylessChainManifestProvider() ChainManifestProvider

NewKeylessChainManifestProvider returns the explicit version-zero manifest used by installations that have not configured an HMAC chain key.

type ChainProvisioner

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

ChainProvisioner runs the complete DISABLED/BUILDING to ACTIVE lifecycle.

func NewChainProvisioner

func NewChainProvisioner(
	db *sql.DB,
	dialect Dialect,
	chainID string,
	manifest ChainManifest,
	cfg BackfillConfig,
) *ChainProvisioner

NewChainProvisioner constructs an end-to-end chain provisioner.

func (*ChainProvisioner) Provision

func (provisioner *ChainProvisioner) Provision(ctx context.Context, owner string) error

Provision resumes or starts a build, completes its backfill, and atomically installs the database contract while switching the chain to ACTIVE.

func (*ChainProvisioner) Status

func (provisioner *ChainProvisioner) Status(ctx context.Context) (ChainState, error)

Status returns the persisted state for this provisioner's chain.

type ChainState

type ChainState struct {
	ChainID          string
	ChainInstanceID  *string
	Status           string
	Mode             *string
	HeadSeq          int64
	HeadID           *int64
	HeadHash         *string
	GenesisAt        *time.Time
	ProtectedSinceID *int64
	BuildOwner       *string
	BuildLeaseUntil  *time.Time
	BuildEpoch       int
	LastBuiltID      *int64
	LastBuiltSeq     *int64
	LastBuiltHash    *string
	UpdatedAt        time.Time
}

ChainState is the persisted runtime state for one audit-chain domain.

type ChainStateRepository

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

ChainStateRepository provides read-only access to audit-chain state.

func (*ChainStateRepository) Get

func (repository *ChainStateRepository) Get(ctx context.Context, chainID string) (ChainState, error)

Get returns the state for one audit-chain domain.

func (*ChainStateRepository) GetVerification

func (repository *ChainStateRepository) GetVerification(ctx context.Context, chainID string) (ChainVerification, error)

GetVerification returns the last verification observation for one chain.

type ChainVerification

type ChainVerification struct {
	ChainID             string
	ObservedInstanceID  *string
	ObservedHeadHash    *string
	Result              *string
	LastVerifiedHeadSeq *int64
	LastVerifiedAt      *time.Time
	BreakSeq            *int64
	BreakID             *int64
	BreakReason         *string
}

ChainVerification is the last verification observation for one chain.

type ChainVerificationOutcome

type ChainVerificationOutcome struct {
	ChainID            string
	Status             string
	ObservedInstanceID string
	Valid              bool
	Result             string
	HeadSeq            int64
	TotalRows          int64
	Unchained          int64
	BreakSeq           int64
	BreakID            int64
	BreakReason        string
	VerifiedAt         time.Time
	// contains filtered or unexported fields
}

ChainVerificationOutcome is one consistent-snapshot observation of an audit chain. BreakSeq and BreakID are zero when the result is not tied to a particular stored row.

type ChainVerifier

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

ChainVerifier validates any persisted chain state without acquiring a build lease or a chain_state write lock.

func NewChainVerifier

func NewChainVerifier(db *sql.DB, dialect Dialect, chainID string, manifest ChainManifest) *ChainVerifier

NewChainVerifier constructs an independent, read-only chain verifier.

func (*ChainVerifier) Verify

func (verifier *ChainVerifier) Verify(ctx context.Context) (outcome ChainVerificationOutcome, resultErr error)

Verify checks the complete linked chain and its coverage in one stable, read-only database snapshot.

func (*ChainVerifier) VerifyAndPersist

func (verifier *ChainVerifier) VerifyAndPersist(ctx context.Context) (ChainVerificationOutcome, error)

VerifyAndPersist verifies first, then conditionally persists all nine verification columns in a separate write transaction. A newer persisted observation or a changed F4 state tuple makes the write a harmless no-op.

type ColumnAuthorizationState

type ColumnAuthorizationState struct {
	Policies       []model.Policy
	MaskRules      []model.MaskRule
	RevisionDigest string
}

ColumnAuthorizationState is read entirely through the original control snapshot transaction. It contains no database handle and can be passed to the S4 execution coordinator without permitting a second metadata read.

type ControlFence

type ControlFence struct {
	FenceKey          string
	MinReaderProtocol int
	MaxWriterProtocol int
	FenceEpoch        int64
	State             string
	Revision          int64
}

type ControlSnapshot

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

ControlSnapshot holds the reader fence and policy snapshot transaction. Business resources may only be acquired after this object exists.

func (*ControlSnapshot) Close

func (snapshot *ControlSnapshot) Close() error

func (*ControlSnapshot) ColumnAuthorizationState

func (snapshot *ControlSnapshot) ColumnAuthorizationState(ctx context.Context, agentID, datasourceID string) (ColumnAuthorizationState, error)

func (*ControlSnapshot) FinalCheck

func (snapshot *ControlSnapshot) FinalCheck(ctx context.Context, now time.Time) error

FinalCheck runs in the original snapshot immediately before sealing.

type DashboardKPI

type DashboardKPI struct {
	TotalRequests      int64    `json:"total_requests"`
	Blocked            int64    `json:"blocked"`
	PendingApprovals   int64    `json:"pending_approvals"`
	ActiveAgents       int64    `json:"active_agents"`
	DatasourcesTotal   int64    `json:"datasources_total"`
	TotalRequestsDelta *float64 `json:"total_requests_change_pct"`
	BlockedDelta       *float64 `json:"blocked_change_pct"`
}

type DashboardRepository

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

DashboardRepository executes read-only dashboard aggregates.

func NewDashboardRepository

func NewDashboardRepository(
	metaDB, auditDB *sql.DB,
	metaDriver, auditDriver Dialect,
) *DashboardRepository

NewDashboardRepository returns a dashboard repository that reads metadata and immutable audit aggregates from their respective targets.

func (*DashboardRepository) Summary

func (repository *DashboardRepository) Summary(ctx context.Context, days int) (DashboardSummary, error)

Summary returns one read-only dashboard snapshot for the trailing days.

type DashboardSummary

type DashboardSummary struct {
	KPI                  DashboardKPI       `json:"kpi"`
	Trend14D             []TrendDay         `json:"trend_14d"`
	DecisionDistribution []DecisionCount    `json:"decision_distribution"`
	RiskTop              []RiskTopEntry     `json:"risk_top"`
	AgentRanking         []AgentRankingItem `json:"agent_ranking"`
	BattleReport         BattleReport       `json:"battle_report"`
}

type DatasourceRepository

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

DatasourceRepository provides encrypted CRUD operations for datasources.

func (*DatasourceRepository) Create

func (repository *DatasourceRepository) Create(
	ctx context.Context,
	datasource model.Datasource,
	plaintextPassword string,
) (model.Datasource, error)

Create encrypts plaintextPassword, inserts a datasource, and returns it.

func (*DatasourceRepository) DecryptPassword

func (repository *DatasourceRepository) DecryptPassword(passwordEncrypted string) (string, error)

DecryptPassword authenticates and decrypts a stored datasource password.

func (*DatasourceRepository) Delete

func (repository *DatasourceRepository) Delete(ctx context.Context, id string) error

Delete removes a datasource by ID.

func (*DatasourceRepository) Get

func (repository *DatasourceRepository) Get(ctx context.Context, id string) (model.Datasource, error)

Get returns a datasource by ID with its encrypted password.

func (*DatasourceRepository) List

func (repository *DatasourceRepository) List(ctx context.Context) ([]model.Datasource, error)

List returns every datasource ordered by ID. PasswordEnc is returned only for trusted internal use and must never be exposed by an external API.

func (*DatasourceRepository) Update

func (repository *DatasourceRepository) Update(
	ctx context.Context,
	datasource model.Datasource,
	plaintextPassword string,
) (model.Datasource, error)

Update encrypts plaintextPassword, replaces mutable fields, and returns the datasource.

type DecisionCount

type DecisionCount struct {
	Decision string `json:"decision"`
	Count    int64  `json:"count"`
}

type Dialect

type Dialect string

Dialect identifies the SQL dialect used by the metadata store.

const (
	// DialectSQLite selects the SQLite metadata-store dialect.
	DialectSQLite Dialect = "sqlite"
	// DialectPostgres selects the PostgreSQL metadata-store dialect.
	DialectPostgres Dialect = "postgres"
)

func ParseDialect

func ParseDialect(value string) (Dialect, error)

ParseDialect normalizes and validates a metadata-store dialect name.

type DiscoveryApplyOutcome

type DiscoveryApplyOutcome struct {
	Created         []model.MaskRule
	Existing        []model.MaskRule
	CoveredByGlobal []model.MaskRule
	Conflicts       []model.MaskRule
}

DiscoveryApplyOutcome contains only persisted rules grouped by the fixed idempotency semantics. Conflicts cause the whole metadata mutation to be skipped.

type DiscoveryDraft

type DiscoveryDraft struct {
	ID                string
	SchemaName        string
	TableName         string
	ColumnName        string
	SensitiveType     string
	Algo              string
	RangeBucketWidth  *int64
	RangeBucketOffset *int64
	RangeGranularity  string
}

DiscoveryDraft is one canonical datasource-scoped disabled mask-rule request. ID must be unique and ColumnName must already be normalized.

type FenceRepository

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

func (*FenceRepository) ActivateProtocol3

func (repository *FenceRepository) ActivateProtocol3(ctx context.Context, activation Protocol3Activation) (RuntimeInstance, error)

ActivateProtocol3 atomically establishes the protocol-3 fence and the first live runtime lease. It never weakens the protocol-2 defaults unless every supplied and durable readiness fact is true.

func (*FenceRepository) BeginRead

func (repository *FenceRepository) BeginRead(ctx context.Context, protocol int, instanceID string, now time.Time) (*ControlSnapshot, error)

func (*FenceRepository) DrainRuntime

func (repository *FenceRepository) DrainRuntime(ctx context.Context, instanceID string) error

DrainRuntime prevents new snapshots from using this instance. It is a best-effort shutdown operation; lease expiry remains the authoritative fail-closed boundary if the control plane is unavailable.

func (*FenceRepository) Heartbeat

func (repository *FenceRepository) Heartbeat(ctx context.Context, instance RuntimeInstance, now time.Time, lease time.Duration) (RuntimeInstance, error)

Heartbeat inserts a new runtime or renews a still-authorized live runtime. An expired or revoked identity cannot resurrect itself.

func (*FenceRepository) PrepareProtocol3Activation

func (repository *FenceRepository) PrepareProtocol3Activation(ctx context.Context) (Protocol3MetadataReadiness, error)

PrepareProtocol3Activation performs phase one of activation in one strong, read-only snapshot. The returned ETag is single-use in the sense that any intervening fence or readiness change makes phase two fail closed.

func (*FenceRepository) Protocol3Readiness

func (repository *FenceRepository) Protocol3Readiness(ctx context.Context) (Protocol3MetadataReadiness, error)

Protocol3Readiness reports the durable enrollment/catalog portion of the activation gate without mutating the fence.

type HumanAuthRepository added in v0.5.0

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

func (*HumanAuthRepository) AdvanceMFACounter added in v0.5.0

func (repository *HumanAuthRepository) AdvanceMFACounter(ctx context.Context, tenantID, userID string, counter int64) error

func (*HumanAuthRepository) ConsumeLoginChallenge added in v0.5.0

func (repository *HumanAuthRepository) ConsumeLoginChallenge(ctx context.Context, hash string, now time.Time) (LoginChallenge, error)

func (*HumanAuthRepository) ConsumeOIDCRequest added in v0.5.0

func (repository *HumanAuthRepository) ConsumeOIDCRequest(ctx context.Context, stateHash string, now time.Time) (OIDCAuthRequest, error)

func (*HumanAuthRepository) ConsumeRecoveryCode added in v0.5.0

func (repository *HumanAuthRepository) ConsumeRecoveryCode(ctx context.Context, tenantID, userID, codeHash string, now time.Time) error

func (*HumanAuthRepository) CreateExternalIdentity added in v0.5.0

func (repository *HumanAuthRepository) CreateExternalIdentity(ctx context.Context, user model.User, provider, subject string) (model.User, error)

func (*HumanAuthRepository) CreateLoginChallenge added in v0.5.0

func (repository *HumanAuthRepository) CreateLoginChallenge(ctx context.Context, value LoginChallenge) error

func (*HumanAuthRepository) CreateOIDCRequest added in v0.5.0

func (repository *HumanAuthRepository) CreateOIDCRequest(ctx context.Context, value OIDCAuthRequest) error

func (*HumanAuthRepository) DisableMFA added in v0.5.0

func (repository *HumanAuthRepository) DisableMFA(ctx context.Context, tenantID, userID string) error

func (*HumanAuthRepository) EnableMFA added in v0.5.0

func (repository *HumanAuthRepository) EnableMFA(ctx context.Context, tenantID, userID string, counter int64) error

func (*HumanAuthRepository) MFA added in v0.5.0

func (repository *HumanAuthRepository) MFA(ctx context.Context, tenantID, userID string) (MFARecord, error)

func (*HumanAuthRepository) ProviderForUser added in v0.5.0

func (repository *HumanAuthRepository) ProviderForUser(ctx context.Context, tenantID, userID string) (string, error)

func (*HumanAuthRepository) PutPendingMFA added in v0.5.0

func (repository *HumanAuthRepository) PutPendingMFA(ctx context.Context, record MFARecord, recoveryHashes []string) error

func (*HumanAuthRepository) UserByExternalSubject added in v0.5.0

func (repository *HumanAuthRepository) UserByExternalSubject(ctx context.Context, tenantID, provider, subject string) (model.User, error)

type KeylessChainManifest

type KeylessChainManifest struct{}

KeylessChainManifest is the explicit version-zero, no-key chain authority.

func (KeylessChainManifest) ChainKeyForVersion

func (KeylessChainManifest) ChainKeyForVersion(context.Context, int) ([]byte, error)

func (KeylessChainManifest) CurrentKeyVersion

func (KeylessChainManifest) CurrentKeyVersion(context.Context) (int, error)

func (KeylessChainManifest) ExpectedMode

func (KeylessChainManifest) ExpectedMode(context.Context) (string, error)

type LoginAttemptRepository added in v1.4.0

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

LoginAttemptRepository atomically accounts for password and LDAP attempts across gateways sharing one PostgreSQL metadata database. Keys are HMACs supplied by the caller; no tenant or account name is persisted here.

func (*LoginAttemptRepository) Allow added in v1.4.0

func (repository *LoginAttemptRepository) Allow(ctx context.Context, key [sha256.Size]byte) (allowed bool, err error)

Allow consumes one attempt in a 60-second window measured by PostgreSQL's clock. A database failure returns an error, which callers must fail closed.

type LoginChallenge added in v0.5.0

type LoginChallenge struct {
	Hash      string
	TenantID  string
	UserID    string
	Username  string
	ExpiresAt time.Time
}

type MCPStreamEventRepository added in v0.5.0

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

MCPStreamEventRepository persists resumable MCP SSE stream events in the metadata database. The cursor row survives event purges so event indexes do not restart and replay can fail closed when a requested prefix is gone.

func (*MCPStreamEventRepository) AppendStreamEvent added in v0.5.0

func (repository *MCPStreamEventRepository) AppendStreamEvent(
	ctx context.Context,
	sessionID string,
	streamID string,
	data []byte,
	maxBytes int,
	ttl time.Duration,
) error

AppendStreamEvent atomically allocates the next stream index, appends the event, and enforces TTL and aggregate byte bounds.

func (*MCPStreamEventRepository) DeleteSessionStreams added in v0.5.0

func (repository *MCPStreamEventRepository) DeleteSessionStreams(ctx context.Context, sessionID string) error

DeleteSessionStreams removes all cursors and events for a closed session.

func (*MCPStreamEventRepository) OpenStream added in v0.5.0

func (repository *MCPStreamEventRepository) OpenStream(ctx context.Context, sessionID, streamID string) error

OpenStream idempotently creates the durable cursor for a logical SSE stream.

func (*MCPStreamEventRepository) PurgeExpiredStreamEvents added in v0.5.0

func (repository *MCPStreamEventRepository) PurgeExpiredStreamEvents(ctx context.Context, maxBytes int, ttl time.Duration) error

PurgeExpiredStreamEvents enforces TTL and aggregate byte limits. It is intentionally synchronous and caller-triggered; no cleanup goroutine exists.

func (*MCPStreamEventRepository) StreamEventsAfter added in v0.5.0

func (repository *MCPStreamEventRepository) StreamEventsAfter(
	ctx context.Context,
	sessionID string,
	streamID string,
	afterIndex int,
) (firstIndex int, events [][]byte, err error)

StreamEventsAfter returns a complete, ordered replay strictly after afterIndex. It returns ErrStreamEventsPurged without any events if the retained sequence has a gap.

type MFARecord added in v0.5.0

type MFARecord struct {
	TenantID         string
	UserID           string
	SecretCiphertext string
	Status           string
	LastCounter      int64
}

type ManagementAuditOutboxRepository

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

ManagementAuditOutboxRepository persists and leases management audit deliveries.

func (*ManagementAuditOutboxRepository) Append

Append writes an event in the caller's metadata transaction.

func (*ManagementAuditOutboxRepository) ClaimBatch

func (repository *ManagementAuditOutboxRepository) ClaimBatch(ctx context.Context, workerID string, batchLimit int, lease time.Duration) (events []model.ManagementAuditOutbox, err error)

ClaimBatch leases the earliest currently eligible events.

func (*ManagementAuditOutboxRepository) Delivered

func (repository *ManagementAuditOutboxRepository) Delivered(ctx context.Context, eventUUID string) (bool, error)

Delivered reports whether one outbox event has been durably acknowledged.

func (*ManagementAuditOutboxRepository) MarkDelivered

func (repository *ManagementAuditOutboxRepository) MarkDelivered(ctx context.Context, eventUUID string) (err error)

MarkDelivered marks one event delivered.

func (*ManagementAuditOutboxRepository) MarkFailed

func (repository *ManagementAuditOutboxRepository) MarkFailed(ctx context.Context, eventUUID, lastErr string, backoff time.Duration) error

MarkFailed releases a claim and schedules its next delivery attempt.

func (*ManagementAuditOutboxRepository) PendingStats

func (repository *ManagementAuditOutboxRepository) PendingStats(ctx context.Context) (count int, oldestAge time.Duration, err error)

PendingStats returns pending count and age of the oldest event.

func (*ManagementAuditOutboxRepository) TenantPendingStats added in v0.9.0

func (repository *ManagementAuditOutboxRepository) TenantPendingStats(ctx context.Context) (count, retrying int, oldestAge time.Duration, err error)

TenantPendingStats reports only the caller's undelivered management events. It deliberately excludes event contents, errors and other tenants' counts.

type ManagementAuditWrite

type ManagementAuditWrite struct {
	Audit  *model.AuditLog
	Outbox *model.ManagementAuditOutbox
}

ManagementAuditWrite selects exactly one atomic audit destination. Combined stores use Audit; separated stores use Outbox.

type MaskRuleRepository

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

MaskRuleRepository provides CRUD operations for mask rules.

func (*MaskRuleRepository) ApplyDiscoveryDraftsWithAudit

func (repository *MaskRuleRepository) ApplyDiscoveryDraftsWithAudit(
	ctx context.Context,
	datasourceID string,
	drafts []DiscoveryDraft,
	buildAudit func(DiscoveryApplyOutcome) (model.AuditLog, error),
) (outcome DiscoveryApplyOutcome, recorded model.AuditLog, err error)

ApplyDiscoveryDraftsWithAudit uses one metadata transaction for the rules and their audit obligation. Shared stores write audit_logs directly; separate stores enqueue a management audit outbox event for eventual relay. The process-wide mutex makes same-process retries deterministic; the unique index remains the final cross-process barrier.

func (*MaskRuleRepository) Create

func (repository *MaskRuleRepository) Create(ctx context.Context, rule model.MaskRule) (model.MaskRule, error)

Create inserts a mask rule and returns the stored record.

func (*MaskRuleRepository) Delete

func (repository *MaskRuleRepository) Delete(ctx context.Context, id string) error

Delete removes a mask rule by ID.

func (*MaskRuleRepository) Get

func (repository *MaskRuleRepository) Get(ctx context.Context, id string) (model.MaskRule, error)

Get returns a mask rule by ID.

func (*MaskRuleRepository) List

func (repository *MaskRuleRepository) List(ctx context.Context) ([]model.MaskRule, error)

List returns all mask rules ordered by table and column.

func (*MaskRuleRepository) ListByDatasource

func (repository *MaskRuleRepository) ListByDatasource(
	ctx context.Context,
	datasourceID string,
) ([]model.MaskRule, error)

ListByDatasource returns datasource-specific and global mask rules, including disabled drafts, in stable table and column order.

func (*MaskRuleRepository) ListEnabledByDatasource

func (repository *MaskRuleRepository) ListEnabledByDatasource(
	ctx context.Context,
	datasourceID string,
) ([]model.MaskRule, error)

ListEnabledByDatasource is the runtime-only view used to compile redactors.

func (*MaskRuleRepository) Update

func (repository *MaskRuleRepository) Update(ctx context.Context, rule model.MaskRule) (model.MaskRule, error)

Update replaces mutable mask-rule fields and returns the stored record.

type MetadataOptions

type MetadataOptions struct {
	Driver          Dialect
	SQLitePath      string
	PostgresDSN     string
	MaxOpenConns    int
	MaxIdleConns    int
	ConnMaxLifetime time.Duration
	AutoMigrate     bool
	Audit           AuditOptions
}

MetadataOptions configures the metadata connection and its audit target.

type MetadataRegistryView

type MetadataRegistryView interface {
	MigrationVersions(context.Context) (current, latest int, err error)
	RedactionKeys() *RedactionKeyRepository
	Outbox() *ManagementAuditOutboxRepository
	Close() error
}

MetadataRegistryView is the metadata-only surface used by registry and relay tooling.

func OpenMetadataOnly

func OpenMetadataOnly(ctx context.Context, options MetadataOptions, secret []byte) (MetadataRegistryView, error)

OpenMetadataOnly opens and prepares only the metadata target. Audit settings select the combined or separated migration stream but are never connected.

type NotificationRepository

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

NotificationRepository stores the complete notification configuration in the metadata database. Confidential webhook values are encrypted at rest.

func (*NotificationRepository) Get

func (repository *NotificationRepository) Get(ctx context.Context) (notify.Config, error)

Get returns the persisted configuration. An unconfigured store has the safe default: notifications disabled and no channels.

func (*NotificationRepository) Replace

func (repository *NotificationRepository) Replace(ctx context.Context, config notify.Config) (resultErr error)

Replace atomically replaces the complete notification configuration.

type OIDCAuthRequest added in v0.5.0

type OIDCAuthRequest struct {
	StateHash    string
	Nonce        string
	PKCEVerifier string
	ReturnTo     string
	ExpiresAt    time.Time
}

type PasswordCipher

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

PasswordCipher encrypts datasource passwords with AES-256-GCM.

func NewPasswordCipher

func NewPasswordCipher(secret []byte) (*PasswordCipher, error)

NewPasswordCipher constructs the repository cipher from an explicit secret.

func NewPasswordCipherFromEnv

func NewPasswordCipherFromEnv() (*PasswordCipher, error)

NewPasswordCipherFromEnv constructs a password cipher from AGENTSQL_SECRET.

func (*PasswordCipher) Decrypt

func (passwordCipher *PasswordCipher) Decrypt(encoded string) (string, error)

Decrypt authenticates and decrypts a datasource password.

func (*PasswordCipher) Encrypt

func (passwordCipher *PasswordCipher) Encrypt(plaintext string) (string, error)

Encrypt encrypts a plaintext datasource password with a fresh random nonce.

type PolicyRepository

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

PolicyRepository owns policy parents, bindings, formal permissions, and legacy staging rows. Mutations use one control-plane transaction.

func (*PolicyRepository) Create

func (repository *PolicyRepository) Create(ctx context.Context, policy model.Policy) (model.Policy, error)

func (*PolicyRepository) Delete

func (repository *PolicyRepository) Delete(ctx context.Context, id string) error

func (*PolicyRepository) DeleteIfRevision

func (repository *PolicyRepository) DeleteIfRevision(ctx context.Context, id string, expected int64) error

func (*PolicyRepository) FinalizeColumnBindingTwoPhase

func (repository *PolicyRepository) FinalizeColumnBindingTwoPhase(
	ctx context.Context,
	policyID string,
	expectedRevision int64,
	discover func(context.Context) error,
	revalidate func(context.Context) (RevalidatedColumnBinding, error),
) (saved model.Policy, returnedErr error)

FinalizeColumnBindingTwoPhase enforces discovery-without-control followed by control-exclusive -> business revalidation -> metadata CAS. The revalidate callback is the only place a business lock may be acquired.

func (*PolicyRepository) Get

func (repository *PolicyRepository) Get(ctx context.Context, id string) (model.Policy, error)

func (*PolicyRepository) List

func (repository *PolicyRepository) List(ctx context.Context) ([]model.Policy, error)

func (*PolicyRepository) ListByAgent

func (repository *PolicyRepository) ListByAgent(ctx context.Context, agentID string) ([]model.Policy, error)

func (*PolicyRepository) ListByAgentAndDatasource

func (repository *PolicyRepository) ListByAgentAndDatasource(ctx context.Context, agentID, datasourceID string) ([]model.Policy, error)

func (*PolicyRepository) Update

func (repository *PolicyRepository) Update(ctx context.Context, policy model.Policy) (model.Policy, error)

func (*PolicyRepository) UpdateIfRevision

func (repository *PolicyRepository) UpdateIfRevision(ctx context.Context, policy model.Policy, expected int64) (model.Policy, error)

type Protocol3Activation

type Protocol3Activation struct {
	InstanceID       string
	ArtifactDigest   string
	ExpectedETag     string
	BinderReady      bool
	CatalogReady     bool
	ReservationReady bool
	Now              time.Time
	Lease            time.Duration
}

Protocol3Activation carries attestations that were produced without a control transaction. ActivateProtocol3 rechecks every metadata fact while holding the exclusive fence and atomically establishes the fence/runtime.

type Protocol3MetadataReadiness

type Protocol3MetadataReadiness struct {
	StagingRows         int64
	WildcardPolicies    int64
	IncompleteBindings  int64
	UnhealthyBindings   int64
	OrphanedPermissions int64
	// ETag binds the phase-one metadata snapshot and control fence. Activation
	// must present it again while holding the exclusive fence.
	ETag string
}

Protocol3MetadataReadiness is the metadata half of the B2 activation gate. Business-database binder attestation is deliberately performed before this transaction so activation never creates a business -> control lock edge.

func (Protocol3MetadataReadiness) Ready

func (readiness Protocol3MetadataReadiness) Ready() bool

type RBACRepository added in v0.5.0

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

RBACRepository persists tenant-scoped control-plane identities and grants. Every user and role lookup requires a non-empty tenant ID and includes it in the SQL predicate; callers cannot accidentally fall back to a global query.

func (*RBACRepository) CreateRole added in v0.5.0

func (repository *RBACRepository) CreateRole(ctx context.Context, role model.Role) (model.Role, error)

func (*RBACRepository) CreateTenant added in v0.5.0

func (repository *RBACRepository) CreateTenant(ctx context.Context, tenant model.Tenant) (model.Tenant, error)

func (*RBACRepository) CreateUser added in v0.5.0

func (repository *RBACRepository) CreateUser(ctx context.Context, user model.User) (model.User, error)

func (*RBACRepository) DeleteRole added in v0.5.0

func (repository *RBACRepository) DeleteRole(ctx context.Context, tenantID, id string) error

func (*RBACRepository) DeleteTenant added in v0.5.0

func (repository *RBACRepository) DeleteTenant(ctx context.Context, id string) error

func (*RBACRepository) DeleteUser added in v0.5.0

func (repository *RBACRepository) DeleteUser(ctx context.Context, tenantID, id string) error

func (*RBACRepository) GetRole added in v0.5.0

func (repository *RBACRepository) GetRole(ctx context.Context, tenantID, id string) (model.Role, error)

func (*RBACRepository) GetTenant added in v0.5.0

func (repository *RBACRepository) GetTenant(ctx context.Context, id string) (model.Tenant, error)

func (*RBACRepository) GetUser added in v0.5.0

func (repository *RBACRepository) GetUser(ctx context.Context, tenantID, id string) (model.User, error)

func (*RBACRepository) GetUserByUsername added in v0.5.0

func (repository *RBACRepository) GetUserByUsername(ctx context.Context, tenantID, username string) (model.User, error)

func (*RBACRepository) ListPermissions added in v0.5.0

func (repository *RBACRepository) ListPermissions(ctx context.Context) ([]model.Permission, error)

func (*RBACRepository) ListRoles added in v0.5.0

func (repository *RBACRepository) ListRoles(ctx context.Context, tenantID string) ([]model.Role, error)

func (*RBACRepository) ListTenants added in v0.5.0

func (repository *RBACRepository) ListTenants(ctx context.Context) ([]model.Tenant, error)

func (*RBACRepository) ListUsers added in v0.5.0

func (repository *RBACRepository) ListUsers(ctx context.Context, tenantID string) ([]model.User, error)

func (*RBACRepository) SetRoleParents added in v0.5.0

func (repository *RBACRepository) SetRoleParents(ctx context.Context, tenantID, roleID string, parents []string) error

func (*RBACRepository) SetRolePermissions added in v0.5.0

func (repository *RBACRepository) SetRolePermissions(ctx context.Context, tenantID, roleID string, permissions []string) error

func (*RBACRepository) SetUserRoles added in v0.5.0

func (repository *RBACRepository) SetUserRoles(ctx context.Context, tenantID, userID string, roleIDs []string) error

func (*RBACRepository) UpdateRole added in v0.5.0

func (repository *RBACRepository) UpdateRole(ctx context.Context, role model.Role) (model.Role, error)

func (*RBACRepository) UpdateTenant added in v0.5.0

func (repository *RBACRepository) UpdateTenant(ctx context.Context, tenant model.Tenant) (model.Tenant, error)

func (*RBACRepository) UpdateUser added in v0.5.0

func (repository *RBACRepository) UpdateUser(ctx context.Context, user model.User) (model.User, error)

func (*RBACRepository) UserRoleIDs added in v0.5.0

func (repository *RBACRepository) UserRoleIDs(ctx context.Context, tenantID, userID string) ([]string, error)

type RedactionKeyRegistration

type RedactionKeyRegistration struct {
	ID, Commitment, Label, ConfigRevision string
}

RedactionKeyRegistration is safe registry metadata; it never contains key material.

type RedactionKeyRepository

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

RedactionKeyRepository persists key-version metadata without key material.

func (*RedactionKeyRepository) Get

Get returns one registered key version.

func (*RedactionKeyRepository) List

List returns registered versions in numeric ID order.

func (*RedactionKeyRepository) MarkActiveCAS

func (repository *RedactionKeyRepository) MarkActiveCAS(ctx context.Context, id string) (before, after model.RedactionKeyVersion, outcome string, err error)

MarkActiveCAS atomically performs the first activation or switches active versions.

func (*RedactionKeyRepository) MarkActiveCASWithAudit

func (repository *RedactionKeyRepository) MarkActiveCASWithAudit(ctx context.Context, id string, write func(before, after model.RedactionKeyVersion, outcome string) (ManagementAuditWrite, error)) (before, after model.RedactionKeyVersion, outcome string, err error)

MarkActiveCASWithAudit atomically changes registry state and persists its audit.

func (*RedactionKeyRepository) MarkRetired

func (repository *RedactionKeyRepository) MarkRetired(ctx context.Context, id string) error

MarkRetired retires a standby or legacy version. Active versions must be switched first.

func (*RedactionKeyRepository) MarkRetiredWithAudit

func (repository *RedactionKeyRepository) MarkRetiredWithAudit(ctx context.Context, id string, write func(before, after model.RedactionKeyVersion) (ManagementAuditWrite, error)) (before, after model.RedactionKeyVersion, err error)

MarkRetiredWithAudit atomically retires a version and persists its audit.

func (*RedactionKeyRepository) RegisterStandby

func (repository *RedactionKeyRepository) RegisterStandby(ctx context.Context, id, commitment, label, configRevision string, tx *sql.Tx) error

RegisterStandby inserts a standby version or reconciles its non-state metadata.

func (*RedactionKeyRepository) RegisterStandbysWithAudit

func (repository *RedactionKeyRepository) RegisterStandbysWithAudit(ctx context.Context, registrations []RedactionKeyRegistration, write ManagementAuditWrite) error

RegisterStandbysWithAudit atomically registers all supplied versions and persists the management audit in the same metadata transaction.

type RevalidatedColumnBinding

type RevalidatedColumnBinding struct {
	Binding     model.RelationPolicyBinding
	Permissions []model.PolicyColumnPermission
	// Release keeps the business metadata lock alive through the control-plane
	// CAS and commit. It is invoked on both success and failure after revalidate.
	Release func() error
}

RevalidatedColumnBinding is produced from original legacy/star input while the caller holds its business schema lock. Discovery results are never accepted as this value.

type RiskTopEntry

type RiskTopEntry struct {
	RuleID string `json:"rule_id"`
	Count  int64  `json:"count"`
}

type RuleRepository

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

RuleRepository provides CRUD operations for persisted rule definitions.

func (*RuleRepository) Create

func (repository *RuleRepository) Create(ctx context.Context, rule model.Rule) (model.Rule, error)

Create inserts a rule and returns the stored record.

func (*RuleRepository) Delete

func (repository *RuleRepository) Delete(ctx context.Context, id string) error

Delete removes a rule by ID.

func (*RuleRepository) Get

func (repository *RuleRepository) Get(ctx context.Context, id string) (model.Rule, error)

Get returns a rule by ID.

func (*RuleRepository) List

func (repository *RuleRepository) List(ctx context.Context, dbType string) ([]model.Rule, error)

List returns rules for one database type, or all rules when dbType is empty.

func (*RuleRepository) Update

func (repository *RuleRepository) Update(ctx context.Context, rule model.Rule) (model.Rule, error)

Update replaces mutable rule fields and returns the stored record.

type RuntimeInstance

type RuntimeInstance struct {
	InstanceID      string
	ProtocolVersion int
	ArtifactDigest  string
	Status          string
	LastHeartbeatAt time.Time
	LeaseExpiresAt  time.Time
	Revision        int64
}

type SQLiteToPostgresApprovalSummary

type SQLiteToPostgresApprovalSummary struct {
	SourceNonNullAuditIDs int64
	TargetNonNullAuditIDs int64
	SourceOrphans         int64
	TargetOrphans         int64
}

type SQLiteToPostgresOptions

type SQLiteToPostgresOptions struct {
	SourcePath string
	MetadataDB *sql.DB
	AuditDB    *sql.DB
	Separate   bool
	VerifyHash bool
}

SQLiteToPostgresOptions describes a one-shot migration. PostgreSQL connections are supplied by the caller so DSNs never enter this package's errors or output.

type SQLiteToPostgresSequenceSummary

type SQLiteToPostgresSequenceSummary struct {
	LastValue    int64
	IsCalled     bool
	ExpectedNext int64
}

type SQLiteToPostgresSummary

type SQLiteToPostgresSummary struct {
	Tables       []SQLiteToPostgresTableSummary
	Sequence     SQLiteToPostgresSequenceSummary
	Approvals    SQLiteToPostgresApprovalSummary
	Verification string
	VerifyHash   bool
}

func MigrateSQLiteToPostgres

func MigrateSQLiteToPostgres(ctx context.Context, options SQLiteToPostgresOptions) (summary SQLiteToPostgresSummary, resultErr error)

MigrateSQLiteToPostgres copies a latest combined SQLite snapshot into one combined PostgreSQL store or a separated metadata/audit pair.

type SQLiteToPostgresTableSummary

type SQLiteToPostgresTableSummary struct {
	Table                  string
	SourceRows, TargetRows int64
	SHA256                 string
	MinID, MaxID           *int64
}

type Store

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

Store owns the metadata and audit connections plus metadata-side encryption.

func Open

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

Open connects to SQLite, validates the encryption secret, and applies all embedded migrations before returning.

func OpenMetadata

func OpenMetadata(ctx context.Context, options MetadataOptions, secret []byte) (*Store, error)

OpenMetadata opens, verifies, and optionally migrates both configured stores.

func OpenWithSecret

func OpenWithSecret(ctx context.Context, path string, secret []byte) (*Store, error)

OpenWithSecret opens the metadata store with an explicitly injected encryption key. It avoids process-global environment mutation in bootstrap.

func (*Store) AdminSessions added in v0.5.0

func (store *Store) AdminSessions() *AdminSessionRepository

AdminSessions returns the persistent administrator-token session repository.

func (*Store) Agents

func (store *Store) Agents() *AgentRepository

Agents returns the agent repository.

func (*Store) Approvals

func (store *Store) Approvals() *ApprovalRepository

Approvals uses metadata for approval rows and the configured audit target for the audit-first saga when those targets are separate.

func (*Store) AuditLogs

func (store *Store) AuditLogs() *AuditLogRepository

AuditLogs returns the append-only repository bound to the audit target.

func (*Store) B5DMLGrants

func (store *Store) B5DMLGrants() *B5DMLGrantRepository

func (*Store) B5ResultReceipts

func (store *Store) B5ResultReceipts() *B5ResultReceiptRepository

func (*Store) B5Sessions

func (store *Store) B5Sessions() *B5SessionRepository

B5Sessions exposes the feature-off B5 session persistence surface. No production handler calls this repository until a later activation slice.

func (*Store) B5Transactions

func (store *Store) B5Transactions() *B5TransactionRepository

func (*Store) B5TxEvents

func (store *Store) B5TxEvents() *B5TxEventRepository

func (*Store) Chain

func (store *Store) Chain(domain string) (*ChainAccess, error)

Chain returns the database view for one audit-chain domain. Combined stores use the metadata management chain. In the separated layout, the independent audit database's traffic chain covers both traffic and management records; callers should select that domain for audit verification.

func (*Store) Close

func (store *Store) Close() error

Close releases the independent audit connection first, then metadata. Pointer identity is the only criterion used to avoid double-closing a shared pool.

func (*Store) Dashboard

func (store *Store) Dashboard() *DashboardRepository

Dashboard returns aggregates composed from the metadata and audit targets.

func (*Store) Datasources

func (store *Store) Datasources() *DatasourceRepository

Datasources returns the datasource repository.

func (*Store) Fence

func (store *Store) Fence() *FenceRepository

Fence returns the reader/writer fence and runtime lease repository.

func (*Store) HumanAuth added in v0.5.0

func (store *Store) HumanAuth() *HumanAuthRepository

HumanAuth returns the repository for MFA and external human identities.

func (*Store) MCPStreamEvents added in v0.5.0

func (store *Store) MCPStreamEvents() *MCPStreamEventRepository

MCPStreamEvents returns the persistent Streamable HTTP event repository.

func (*Store) ManagementAuditLogs

func (store *Store) ManagementAuditLogs() *AuditLogRepository

ManagementAuditLogs returns the chain-aware management audit sink. In the separated layout, management and traffic records share the audit database's traffic chain; the metadata database contains only the delivery outbox.

func (*Store) MaskRules

func (store *Store) MaskRules() *MaskRuleRepository

MaskRules returns the mask-rule repository.

func (*Store) Notifications

func (store *Store) Notifications() *NotificationRepository

Notifications returns the notification configuration repository.

func (*Store) Outbox

func (store *Store) Outbox() *ManagementAuditOutboxRepository

Outbox returns the metadata-side management audit outbox.

func (*Store) Ping

func (store *Store) Ping(ctx context.Context) error

Ping verifies both targets. A shared connection is pinged exactly once.

func (*Store) Policies

func (store *Store) Policies() *PolicyRepository

Policies returns the policy repository.

func (*Store) RBAC added in v0.5.0

func (store *Store) RBAC() *RBACRepository

RBAC returns the tenant-scoped identity and authorization repository.

func (*Store) RedactionKeys

func (store *Store) RedactionKeys() *RedactionKeyRepository

RedactionKeys returns the metadata-side redaction key registry.

func (*Store) Rules

func (store *Store) Rules() *RuleRepository

Rules returns the rule repository.

func (*Store) SeedHistoricalAudits

func (store *Store) SeedHistoricalAudits(
	ctx context.Context,
	audits []model.AuditLog,
	approvals []model.Approval,
) (recorded []model.AuditLog, persistedApprovals []model.Approval, err error)

SeedHistoricalAudits is exclusively for Live Demo seed data. The caller must be the demo-seed command and must first verify config.Demo.Enabled=true; production code must never call this historical-write entry point.

Approvals correspond, in order, to the approve-decision audits in audits. Their AuditID fields must be nil; this method fills the database-allocated audit identities and returns the persisted audit and approval records.

func (*Store) SharedLoginAttempts added in v1.4.0

func (store *Store) SharedLoginAttempts() *LoginAttemptRepository

SharedLoginAttempts uses the metadata database so every gateway sees the same password and LDAP attempt budget. SQLite deployments remain single-node.

func (*Store) TaskReadGrantRequests added in v0.8.0

func (store *Store) TaskReadGrantRequests() *TaskReadGrantRequestRepository

TaskReadGrantRequests manages tenant-scoped approval before key issuance.

func (*Store) TaskReadGrants added in v0.7.0

func (store *Store) TaskReadGrants() *TaskReadGrantRepository

TaskReadGrants returns tenant-scoped, exact-query temporary authorization.

type TaskReadGrantRepository added in v0.7.0

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

func (*TaskReadGrantRepository) Consume added in v0.9.0

func (repository *TaskReadGrantRepository) Consume(
	ctx context.Context, id, tenantID, agentID, datasourceID, sqlSHA256 string, now time.Time,
) error

Consume claims one bounded result before the gateway returns it. The conditional UPDATE is the cross-instance fence: concurrent requests may execute, but no more than max_uses can return a result. A consumed slot is deliberately not refunded after a later transport failure.

func (*TaskReadGrantRepository) Create added in v0.7.0

Create stores only hashes. The INSERT's tenant predicates are the final boundary even if an API caller provides a foreign Agent or datasource ID.

func (*TaskReadGrantRepository) Get added in v0.7.0

func (*TaskReadGrantRepository) List added in v0.7.0

func (repository *TaskReadGrantRepository) List(ctx context.Context) ([]model.TaskReadGrant, error)

func (*TaskReadGrantRepository) Revoke added in v0.7.0

func (repository *TaskReadGrantRepository) Revoke(ctx context.Context, id string) (model.TaskReadGrant, error)

Revoke is idempotent and visible to subsequent reads immediately after the update commits. It never reactivates an expired or already revoked grant.

func (*TaskReadGrantRepository) Validate added in v0.7.0

func (repository *TaskReadGrantRepository) Validate(
	ctx context.Context, id, tenantID, agentID, datasourceID, sqlSHA256 string, now time.Time,
) (model.TaskReadGrant, error)

Validate performs a fresh storage read for every execution gate. The tenant and Agent IDs come from authentication, never from SQL parameters or headers.

type TaskReadGrantRequestRepository added in v0.8.0

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

TaskReadGrantRequestRepository keeps approval and one-time issuance in the metadata database. The request stores encrypted SQL and no usable API key.

func (*TaskReadGrantRequestRepository) Create added in v0.8.0

func (*TaskReadGrantRequestRepository) Get added in v0.8.0

func (*TaskReadGrantRequestRepository) Issue added in v0.8.0

func (repository *TaskReadGrantRequestRepository) Issue(ctx context.Context, id, requesterID, grantID, keyHash string) (model.TaskReadGrantRequest, error)

Issue atomically marks one approved request and inserts its only grant. A repeated or concurrent call cannot create another usable key.

func (*TaskReadGrantRequestRepository) List added in v0.8.0

func (repository *TaskReadGrantRequestRepository) List(ctx context.Context, requesterID string, reviewer bool) ([]model.TaskReadGrantRequest, error)

func (*TaskReadGrantRequestRepository) Review added in v0.8.0

func (repository *TaskReadGrantRequestRepository) Review(ctx context.Context, id, reviewerID string, approve bool) (model.TaskReadGrantRequest, error)

type TrendDay

type TrendDay struct {
	Date    string `json:"date"`
	Total   int64  `json:"total"`
	Deny    int64  `json:"deny"`
	Warn    int64  `json:"warn"`
	Approve int64  `json:"approve"`
	Allow   int64  `json:"allow"`
}

Jump to

Keyboard shortcuts

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