db

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2026 License: AGPL-3.0-or-later Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ContainsAction

func ContainsAction(actions string, action string) bool

func SplitActions

func SplitActions(actions string) []string

Types

type APIKey

type APIKey struct {
	ID        int64      `json:"id"`
	UserID    int64      `json:"user_id"`
	Name      string     `json:"name"`
	KeyHash   string     `json:"-"`
	KeyPrefix string     `json:"key_prefix"` // first 8 chars for identification
	RoleID    int64      `json:"role_id"`
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
	CreatedAt time.Time  `json:"created_at"`
}

type AgentBriefing

type AgentBriefing struct {
	// Identity is the L0 identity stack (org → team → individual).
	// Populated by the server before returning the briefing; left as-is by BuildBriefing.
	// Rendered as the first section of the briefing so the agent sees outer-to-inner
	// identity constraints before any decision history.
	Identity        any              `json:"identity,omitempty"`
	RecentDocs      []RecentDoc      `json:"recent_docs"`
	RecentTraces    []Trace          `json:"recent_traces"`
	PendingOutcomes []Trace          `json:"pending_outcomes"`
	KnowledgeGaps   []KnowledgeGap   `json:"knowledge_gaps,omitempty"`
	StaleAlerts     []StaleReference `json:"stale_alerts,omitempty"`
	Alerts          []string         `json:"alerts,omitempty"`
}

type AuditEntry

type AuditEntry struct {
	ID           int64     `json:"id"`
	UserID       int64     `json:"user_id"`
	Action       string    `json:"action"` // "read", "write", "delete", "permission_check"
	ResourcePath string    `json:"resource_path"`
	Timestamp    time.Time `json:"timestamp"`
	Details      string    `json:"details,omitempty"`
}

type BillingInfo

type BillingInfo struct {
	ID                   int64     `json:"id"`
	VaultID              int64     `json:"vault_id"`
	StripeCustomerID     string    `json:"stripe_customer_id"`
	StripeSubscriptionID string    `json:"stripe_subscription_id"`
	Plan                 string    `json:"plan"`
	MaxUsers             int       `json:"max_users"`
	StorageLimitMB       int64     `json:"storage_limit_mb"`
	StorageUsedMB        int64     `json:"storage_used_mb"`
	Status               string    `json:"status"`
	CreatedAt            time.Time `json:"created_at"`
	UpdatedAt            time.Time `json:"updated_at"`
}

type DB

type DB struct {

	// OnKeyCreated is called after a new API key is successfully inserted.
	// The callback receives the key prefix (e.g. "vk_a1b2c3d4"). In cloud
	// mode, the tenant pool sets this to index the key in the control plane
	// so Bearer-token routing works without a /t/<slug> URL prefix.
	OnKeyCreated func(prefix string)
	// contains filtered or unexported fields
}

func Open

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

func (*DB) AddGroupMember

func (db *DB) AddGroupMember(groupID, userID int64) error

func (*DB) AddPermission

func (db *DB) AddPermission(roleID int64, resourceType, resourcePattern, actions, effect string) (*Permission, error)

func (*DB) AddStorageLimit

func (db *DB) AddStorageLimit(vaultID int64, additionalMB int64) error

func (*DB) AddTraceEdge

func (db *DB) AddTraceEdge(sourcePath, targetTraceID, edgeType, section, relevance string) error

AddTraceEdge creates a link between a source document and a decision trace.

func (*DB) AddTracePolicy

func (db *DB) AddTracePolicy(traceID, policyRef, policyText string) error

AddTracePolicy records a policy applied in a decision.

func (*DB) AddTraceTag

func (db *DB) AddTraceTag(traceID, tag string) error

AddTraceTag adds a tag to a trace.

func (*DB) AssignGroupRole

func (db *DB) AssignGroupRole(groupID, roleID int64) error

func (*DB) AssignRole

func (db *DB) AssignRole(userID, roleID int64) error

func (*DB) AuthenticateAPIKey

func (db *DB) AuthenticateAPIKey(key string) (*APIKey, error)

func (*DB) BuildBriefing

func (db *DB) BuildBriefing(actorRole string, taskContext string) (*AgentBriefing, error)

BuildBriefing generates a context packet for an agent role.

func (*DB) CheckStaleReferences

func (db *DB) CheckStaleReferences(traceID string) ([]StaleReference, error)

CheckStaleReferences checks if any documents referenced by a trace have been revised since the trace was created.

func (*DB) CleanExpiredTokens

func (db *DB) CleanExpiredTokens() error

CleanExpiredTokens removes tokens that have expired.

func (*DB) Close

func (db *DB) Close() error

func (*DB) CountUsers

func (db *DB) CountUsers(vaultID int64) (int, error)

CountUsers returns the number of users with roles assigned for a vault.

func (*DB) CreateAPIKey

func (db *DB) CreateAPIKey(userID int64, name string, roleID int64, expiresAt *time.Time) (string, *APIKey, error)

func (*DB) CreateBilling

func (db *DB) CreateBilling(vaultID int64, stripeCustomerID, plan string, maxUsers int, storageLimitMB int64) (*BillingInfo, error)

func (*DB) CreateGroup

func (db *DB) CreateGroup(vaultID int64, name, description string) (*Group, error)

func (*DB) CreateRole

func (db *DB) CreateRole(vaultID int64, name, description string) (*Role, error)

func (*DB) CreateToken

func (db *DB) CreateToken(tokenType, email string, ttl time.Duration, vaultID, roleID, groupID, inviterID *int64) (string, error)

CreateToken generates a secure random token and stores it.

func (*DB) CreateTrace

func (db *DB) CreateTrace(t *Trace) error

CreateTrace inserts a new decision trace.

func (*DB) CreateUser

func (db *DB) CreateUser(email, displayName, password string) (*User, error)

func (*DB) CreateVault

func (db *DB) CreateVault(name, path string) (*Vault, error)

func (*DB) DeleteGroup

func (db *DB) DeleteGroup(groupID int64) error

func (*DB) DeleteTrace

func (db *DB) DeleteTrace(traceID string) error

DeleteTrace removes a trace and its edges/tags/policies.

func (*DB) FindContradictions

func (db *DB) FindContradictions(decisionType, decision string, tags []string) ([]Trace, error)

FindContradictions looks for existing traces of the same type with a different decision.

func (*DB) FindPrecedent

func (db *DB) FindPrecedent(decisionType string, tags []string, context string, limit int) ([]TraceWithEdges, error)

FindPrecedent searches for similar past decisions using type, tags, and text matching.

func (*DB) GetAllPermissionsForUser

func (db *DB) GetAllPermissionsForUser(userID int64) ([]Permission, error)

GetPermissionsForUser now includes permissions from group-role assignments. This REPLACES the original method — it unions direct role permissions with group-role permissions.

func (*DB) GetAuditLog

func (db *DB) GetAuditLog(limit int) ([]AuditEntry, error)

func (*DB) GetBilling

func (db *DB) GetBilling(vaultID int64) (*BillingInfo, error)

func (*DB) GetBillingByCustomer

func (db *DB) GetBillingByCustomer(stripeCustomerID string) (*BillingInfo, error)

func (*DB) GetCurrentRevision

func (db *DB) GetCurrentRevision(filePath string) (*DocRevision, error)

GetCurrentRevision returns the latest revision for a document.

func (*DB) GetFolderContext

func (db *DB) GetFolderContext(folderPath string) (string, error)

GetFolderContext returns the context annotation for a folder path.

func (*DB) GetGroup

func (db *DB) GetGroup(vaultID int64, name string) (*Group, error)

func (*DB) GetGroupMembers

func (db *DB) GetGroupMembers(groupID int64) ([]User, error)

func (*DB) GetGroupRoles

func (db *DB) GetGroupRoles(groupID int64) ([]Role, error)

func (*DB) GetKnowledgeGaps

func (db *DB) GetKnowledgeGaps(minOccurrences int, days int) ([]KnowledgeGap, error)

GetKnowledgeGaps returns queries that returned zero results, aggregated by frequency.

func (*DB) GetPermissionsForRole

func (db *DB) GetPermissionsForRole(roleID int64) ([]Permission, error)

func (*DB) GetPermissionsForUser

func (db *DB) GetPermissionsForUser(userID int64) ([]Permission, error)

func (*DB) GetRecentKnowledgeNotes

func (db *DB) GetRecentKnowledgeNotes(limit int) ([]KnowledgeNote, error)

func (*DB) GetRevisionHistory

func (db *DB) GetRevisionHistory(filePath string) ([]DocRevision, error)

GetRevisionHistory returns all revisions for a document.

func (*DB) GetRole

func (db *DB) GetRole(vaultID int64, name string) (*Role, error)

func (*DB) GetRoleByID

func (db *DB) GetRoleByID(roleID int64) (*Role, error)

func (*DB) GetTrace

func (db *DB) GetTrace(traceID string) (*Trace, error)

GetTrace returns a trace by its trace_id.

func (*DB) GetTraceEdges

func (db *DB) GetTraceEdges(traceID string) ([]TraceEdge, error)

GetTraceEdges returns all edges for a trace.

func (*DB) GetTracePolicies

func (db *DB) GetTracePolicies(traceID string) ([]TracePolicy, error)

GetTracePolicies returns policies applied in a trace.

func (*DB) GetTraceTags

func (db *DB) GetTraceTags(traceID string) ([]string, error)

GetTraceTags returns tags for a trace.

func (*DB) GetTracesReferencingDocument

func (db *DB) GetTracesReferencingDocument(docPath string) ([]Trace, error)

GetTracesReferencingDocument returns all traces that used a document as input.

func (*DB) GetUser

func (db *DB) GetUser(email string) (*User, error)

func (*DB) GetUserByID

func (db *DB) GetUserByID(id int64) (*User, error)

func (*DB) GetUserGroups

func (db *DB) GetUserGroups(userID int64) ([]Group, error)

func (*DB) GetUserRoles

func (db *DB) GetUserRoles(userID int64) ([]Role, error)

func (*DB) GetVault

func (db *DB) GetVault(name string) (*Vault, error)

func (*DB) IndexDocument

func (db *DB) IndexDocument(filePath, title, tags, content string) error

IndexDocument adds or updates a document in the FTS5 index.

func (*DB) IndexTraceFTS

func (db *DB) IndexTraceFTS(traceID, traceType, summary, reasoning, decision string) error

IndexTrace adds or updates a decision trace in the traces FTS5 index.

func (*DB) ListAPIKeys

func (db *DB) ListAPIKeys(userID int64) ([]APIKey, error)

func (*DB) ListFolderContexts

func (db *DB) ListFolderContexts() (map[string]string, error)

ListFolderContexts returns all folder context annotations.

func (*DB) ListGroups

func (db *DB) ListGroups(vaultID int64) ([]Group, error)

func (*DB) ListRoles

func (db *DB) ListRoles(vaultID int64) ([]Role, error)

func (*DB) ListTraces

func (db *DB) ListTraces(limit int) ([]Trace, error)

ListTraces returns recent traces, optionally filtered.

func (*DB) ListUsers

func (db *DB) ListUsers() ([]User, error)

func (*DB) ListVaults

func (db *DB) ListVaults() ([]Vault, error)

func (*DB) LogAudit

func (db *DB) LogAudit(userID int64, action, resourcePath, details string) error

func (*DB) LogSearch

func (db *DB) LogSearch(query string, resultCount int, actorID string) error

LogSearch records a search query and its result count.

func (*DB) Login

func (db *DB) Login(email, password string) (string, *User, error)

Login verifies email/password and returns or creates a session API key. The key is tied to the user's first assigned role, or returns an error if the user has no roles.

func (*DB) RecordKnowledgeNote

func (db *DB) RecordKnowledgeNote(filePath, source, sourceDetail, category string) error

func (*DB) RecordRevision

func (db *DB) RecordRevision(filePath, rev, content, changedBy, changeSummary string) error

RecordRevision stores a new revision for a document.

func (*DB) RemoveDocument

func (db *DB) RemoveDocument(filePath string) error

RemoveDocument removes a document from the FTS5 index.

func (*DB) RemoveGroupMember

func (db *DB) RemoveGroupMember(groupID, userID int64) error

func (*DB) RevokeGroupRole

func (db *DB) RevokeGroupRole(groupID, roleID int64) error

func (*DB) RevokeRole

func (db *DB) RevokeRole(userID, roleID int64) error

func (*DB) SearchFTS

func (db *DB) SearchFTS(query string, limit int) ([]SearchResult, error)

SearchFTS performs a BM25-ranked full-text search across the vault.

func (*DB) SearchTraces

func (db *DB) SearchTraces(opts TraceSearchOpts) ([]Trace, error)

SearchTraces searches traces by type, tags, actor, status, and/or free text.

func (*DB) SearchTracesFTS

func (db *DB) SearchTracesFTS(query string, limit int) ([]Trace, error)

SearchTracesFTS performs BM25-ranked search across decision traces.

func (*DB) SetFolderContext

func (db *DB) SetFolderContext(folderPath, context string) error

SetFolderContext sets the context annotation for a folder.

func (*DB) UpdateBillingStatus

func (db *DB) UpdateBillingStatus(vaultID int64, status string) error

func (*DB) UpdateBillingSubscription

func (db *DB) UpdateBillingSubscription(vaultID int64, subscriptionID, plan string, maxUsers int, storageLimitMB int64) error

func (*DB) UpdateDisplayName

func (db *DB) UpdateDisplayName(userID int64, name string) error

func (*DB) UpdateStorageUsed

func (db *DB) UpdateStorageUsed(vaultID int64, usedMB int64) error

func (*DB) UpdateTraceOutcome

func (db *DB) UpdateTraceOutcome(traceID, status, notes string) error

UpdateTraceOutcome records the outcome of a past decision.

func (*DB) UseToken

func (db *DB) UseToken(token string) error

UseToken marks a token as used.

func (*DB) ValidateToken

func (db *DB) ValidateToken(token, tokenType string) (*Token, error)

ValidateToken checks if a token is valid (exists, not used, not expired).

type DocRevision

type DocRevision struct {
	ID            int64     `json:"id"`
	FilePath      string    `json:"file_path"`
	Rev           string    `json:"rev"`
	ContentHash   string    `json:"content_hash"`
	ChangedBy     string    `json:"changed_by"`
	ChangeSummary string    `json:"change_summary"`
	CreatedAt     time.Time `json:"created_at"`
}

type Group

type Group struct {
	ID          int64  `json:"id"`
	VaultID     int64  `json:"vault_id"`
	Name        string `json:"name"`
	Description string `json:"description"`
}

type KnowledgeGap

type KnowledgeGap struct {
	Query        string `json:"query"`
	SearchCount  int    `json:"search_count"`
	Actors       string `json:"actors"`
	LastSearched string `json:"last_searched"`
}

type KnowledgeNote

type KnowledgeNote struct {
	ID           int64  `json:"id"`
	FilePath     string `json:"file_path"`
	Source       string `json:"source"`
	SourceDetail string `json:"source_detail"`
	Category     string `json:"category"`
	CreatedAt    string `json:"created_at"`
	UpdatedAt    string `json:"updated_at"`
}

type Permission

type Permission struct {
	ID              int64  `json:"id"`
	RoleID          int64  `json:"role_id"`
	ResourceType    string `json:"resource_type"`    // "folder", "file", "tag"
	ResourcePattern string `json:"resource_pattern"` // "/engineering/**", "#sales", etc.
	Actions         string `json:"actions"`          // comma-separated: "read,write,delete"
	Effect          string `json:"effect"`           // "allow" or "deny"
}

type RecentDoc

type RecentDoc struct {
	Path       string `json:"path"`
	Rev        string `json:"rev,omitempty"`
	ModifiedAt string `json:"modified_at,omitempty"`
}

type Role

type Role struct {
	ID          int64  `json:"id"`
	VaultID     int64  `json:"vault_id"`
	Name        string `json:"name"`
	Description string `json:"description"`
}

type SearchResult

type SearchResult struct {
	FilePath string  `json:"file_path"`
	Title    string  `json:"title"`
	Tags     string  `json:"tags"`
	Snippet  string  `json:"snippet"`
	Rank     float64 `json:"rank"`
	Context  string  `json:"folder_context,omitempty"`
}

SearchResult represents a search hit with relevance scoring.

type StaleReference

type StaleReference struct {
	FilePath      string    `json:"file_path"`
	EdgeType      string    `json:"edge_type"`
	TraceDate     time.Time `json:"trace_date"`
	NewRev        string    `json:"new_rev"`
	RevDate       time.Time `json:"rev_date"`
	ChangeSummary string    `json:"change_summary"`
}

type SyncState

type SyncState struct {
	FilePath     string    `json:"file_path"`
	ContentHash  string    `json:"content_hash"`
	LastModified time.Time `json:"last_modified"`
	LastSyncedBy int64     `json:"last_synced_by"`
}

type Token

type Token struct {
	ID        int64      `json:"id"`
	Token     string     `json:"token"`
	Type      string     `json:"type"` // "verify", "invite", "reset"
	Email     string     `json:"email"`
	VaultID   *int64     `json:"vault_id,omitempty"`
	RoleID    *int64     `json:"role_id,omitempty"`
	GroupID   *int64     `json:"group_id,omitempty"`
	InviterID *int64     `json:"inviter_id,omitempty"`
	ExpiresAt time.Time  `json:"expires_at"`
	UsedAt    *time.Time `json:"used_at,omitempty"`
	CreatedAt time.Time  `json:"created_at"`
}

type Trace

type Trace struct {
	ID                int64      `json:"id"`
	TraceID           string     `json:"trace_id"`
	FilePath          string     `json:"file_path"`
	Type              string     `json:"type"`
	Status            string     `json:"status"`
	ActorID           string     `json:"actor_id"`
	ActorRole         string     `json:"actor_role"`
	Decision          string     `json:"decision"`
	Summary           string     `json:"summary"`
	Reasoning         string     `json:"reasoning"`
	Deviation         bool       `json:"deviation"`
	DeviationReason   string     `json:"deviation_reason,omitempty"`
	OutcomeStatus     string     `json:"outcome_status"`
	OutcomeNotes      string     `json:"outcome_notes,omitempty"`
	OutcomeRecordedAt *time.Time `json:"outcome_recorded_at,omitempty"`
	CreatedAt         time.Time  `json:"created_at"`
}

type TraceEdge

type TraceEdge struct {
	ID            int64  `json:"id"`
	SourcePath    string `json:"source_path"`
	TargetTraceID string `json:"target_trace_id"`
	EdgeType      string `json:"edge_type"`
	Section       string `json:"section,omitempty"`
	Relevance     string `json:"relevance,omitempty"`
}

type TracePolicy

type TracePolicy struct {
	ID         int64  `json:"id"`
	TraceID    string `json:"trace_id"`
	PolicyRef  string `json:"policy_ref"`
	PolicyText string `json:"policy_text"`
}

type TraceSearchOpts

type TraceSearchOpts struct {
	Type          string
	Tags          []string
	ActorID       string
	ActorRole     string
	Status        string
	OutcomeStatus string
	Decision      string
	Deviation     bool
	Query         string // free text search
	Limit         int
}

type TraceWithEdges

type TraceWithEdges struct {
	Trace    Trace         `json:"trace"`
	Edges    []TraceEdge   `json:"edges"`
	Policies []TracePolicy `json:"policies"`
	Tags     []string      `json:"tags"`
}

type User

type User struct {
	ID          int64     `json:"id"`
	Email       string    `json:"email"`
	DisplayName string    `json:"display_name"`
	AuthMethod  string    `json:"auth_method"` // "local", "oidc"
	Password    string    `json:"-"`           // bcrypt hash, only for local auth
	CreatedAt   time.Time `json:"created_at"`
}

type UserRole

type UserRole struct {
	UserID int64 `json:"user_id"`
	RoleID int64 `json:"role_id"`
}

type Vault

type Vault struct {
	ID        int64     `json:"id"`
	Name      string    `json:"name"`
	Path      string    `json:"path"` // filesystem path
	CreatedAt time.Time `json:"created_at"`
}

Jump to

Keyboard shortcuts

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