service

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package service is the memory service's domain logic: OKF bundles in and out, concepts with their chunks and edges, search with its full-text fallback, agent tokens, and the audit trail behind every write.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNoBundle  = errors.New("capsa: bundle not found")
	ErrForbidden = errors.New("capsa: token may not access this bundle")
	// ErrInvalidConcept marks a file that is not an OKF concept (no `type`).
	ErrInvalidConcept = errors.New("capsa: not a concept")
	ErrInvalidScope   = errors.New("capsa: unknown scope")
	ErrInvalidPath    = errors.New("capsa: invalid concept path")
	// ErrExists marks a bundle slug that is taken.
	ErrExists = errors.New("capsa: bundle already exists")
	// ErrNoEmbeddings is returned by IndexPending when no provider is configured.
	ErrNoEmbeddings = errors.New("capsa: no embedding provider configured")
)

Errors the API and MCP layers map to responses.

View Source
var ErrInvalidQuery = errors.New("capsa: query is empty")

ErrInvalidQuery marks an empty search.

Functions

func NormalizePath

func NormalizePath(p string) string

NormalizePath strips the ".md" suffix and slashes around a concept path.

func Terms

func Terms(text string) []string

Terms splits a text into the words the full-text search and the key boost use: lowercase runs of letters and digits of at least two characters.

func ValidatePath

func ValidatePath(p string) error

ValidatePath reports whether p can be a concept id: a relative path inside the bundle, with no reserved filename and no dot-path.

Types

type BundleInfo

type BundleInfo struct {
	ID          string          `json:"id"`
	Slug        string          `json:"slug"`
	Title       string          `json:"title"`
	Description string          `json:"description"`
	OKFVersion  string          `json:"okf_version"`
	Concepts    int64           `json:"concepts"`
	Pending     int             `json:"pending_chunks"`
	Settings    json.RawMessage `json:"settings"`
}

BundleInfo is a bundle with its concept count.

type ConceptView

type ConceptView struct {
	Bundle       string           `json:"bundle"`
	Path         string           `json:"path"`
	Type         string           `json:"type"`
	Title        string           `json:"title"`
	Description  string           `json:"description"`
	Tags         []string         `json:"tags,omitempty"`
	Status       string           `json:"status"`
	TrustTier    string           `json:"trust_tier"`
	Stale        bool             `json:"stale"`
	StaleAfter   *time.Time       `json:"stale_after,omitempty"`
	SupersededBy string           `json:"superseded_by,omitempty"`
	Version      int              `json:"version"`
	Content      string           `json:"content"`
	Neighbors    []store.Neighbor `json:"neighbors,omitempty"`
}

ConceptView is a concept as the API and MCP return it.

type Config

type Config struct {
	// MaxLimit caps how many results one search may return (0 = 50).
	MaxLimit int
	// DefaultLimit is what a search without a limit returns (0 = 8).
	DefaultLimit int
	// Reranker scores the best vector hits with a cross-encoder before the
	// answer is cut to the limit (nil: the vector order stands).
	Reranker rerank.Provider
	// RerankCandidates is how many of the best hits the reranker sees (0 = 20).
	RerankCandidates int
	// RerankMinScore drops reranked hits below this relevance (0: keep all).
	RerankMinScore float32
}

Config tunes a Service.

func (Config) RerankerName

func (c Config) RerankerName() string

RerankerName is the reranker's name for the answer, "" when there is none.

type Hit

type Hit struct {
	Bundle      string  `json:"bundle"`
	Path        string  `json:"path"`
	Type        string  `json:"type"`
	Title       string  `json:"title"`
	Description string  `json:"description,omitempty"`
	Status      string  `json:"status"`
	TrustTier   string  `json:"trust_tier"`
	Stale       bool    `json:"stale"`
	Heading     string  `json:"heading,omitempty"`
	Text        string  `json:"text"`
	Score       float32 `json:"score"`
	Version     int     `json:"version"`
}

Hit is one result.

type ImportStats

type ImportStats struct {
	Concepts  int `json:"concepts"`
	Created   int `json:"created"`
	Updated   int `json:"updated"`
	Unchanged int `json:"unchanged"`
	Removed   int `json:"removed"`
	Edges     int `json:"edges"`
	Pending   int `json:"pending_chunks"`
}

ImportStats is what an import did.

type Query

type Query struct {
	Text string
	// Bundle is a slug; "" searches every bundle the token may read.
	Bundle string
	Type   string
	Tags   []string
	// IncludeNotCurrent also returns deprecated concepts.
	IncludeNotCurrent bool
	// Limit is 0 for DefaultLimit.
	Limit int
}

Query is one search.

type Result

type Result struct {
	Mode          string `json:"mode"`
	Hits          []Hit  `json:"hits"`
	LowConfidence bool   `json:"low_confidence"`
	// Fallback says why the full-text index answered or the reranker was
	// skipped.
	Fallback string `json:"fallback_reason,omitempty"`
	Reranker string `json:"reranker,omitempty"`
}

Result is a search's answer. Mode is "vector", "fts" when the embedding provider was unavailable and the full-text index answered instead, with "+rerank" appended when a reranker ordered the candidates. The scores of the modes are not comparable.

type Service

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

Service wires the repository, the embedding provider and the audit log.

func New

func New(repo *store.Repo, provider embed.Provider, logger *slog.Logger, cfg Config) *Service

New creates the service. provider may be nil: the service then searches through the full-text index only.

func (*Service) Authenticate

func (s *Service) Authenticate(ctx context.Context, plaintext string) (*store.Token, error)

Authenticate resolves a bearer token; an unknown token is store.ErrNotFound and a revoked one ErrForbidden.

func (*Service) CheckContent

func (s *Service) CheckContent(ctx context.Context) (store.ContentCounts, error)

CheckContent is the startup self-check, for the commands that rewrite: a key that does not open the stored content, or sealed content with no key, must stop them before anything is written.

func (*Service) ContentCounts

func (s *Service) ContentCounts(ctx context.Context) (store.ContentCounts, error)

ContentCounts reports how many stored content values are sealed and how many are plaintext: what a rewrite would touch.

func (*Service) CreateBundle

func (s *Service) CreateBundle(ctx context.Context, actor, slug, title, description string) (*store.Bundle, error)

CreateBundle makes an empty bundle.

func (*Service) CreateToken

func (s *Service) CreateToken(ctx context.Context, actor, name string, scopes, bundles []string) (string, *store.Token, error)

CreateToken issues a bearer token and returns its plaintext once.

func (*Service) DeleteBundle

func (s *Service) DeleteBundle(ctx context.Context, actor, slug string) error

DeleteBundle removes a bundle with everything in it.

func (*Service) DeprecateConcept

func (s *Service) DeprecateConcept(ctx context.Context, tok *store.Token, slug, conceptPath, supersededBy string) (*ConceptView, error)

DeprecateConcept marks a concept deprecated in its own frontmatter, with an optional replacement, and stores that as a new version.

func (*Service) ExportBundle

func (s *Service) ExportBundle(ctx context.Context, slug, dir string) (int, error)

ExportBundle writes the concepts of the bundle as OKF files under dir, each exactly as stored, plus a generated root index.md. Reserved files (index.md, log.md) are not stored, so the export regenerates index.md and writes no log.md. Returns the number of concepts written.

func (*Service) GetConcept

func (s *Service) GetConcept(ctx context.Context, tok *store.Token, slug, conceptPath string) (*ConceptView, error)

GetConcept returns a concept.

func (*Service) HasEmbeddings

func (s *Service) HasEmbeddings() bool

HasEmbeddings reports whether vector search is available.

func (*Service) ImportBundle

func (s *Service) ImportBundle(ctx context.Context, actor, dir, slug string, prune, wrap bool) (*ImportStats, error)

ImportBundle stores the OKF bundle under dir as slug. Unchanged concepts (same content hash) are left alone, so a re-import is cheap. prune removes the concepts of the bundle that the directory no longer holds; wrap turns the directory's plain markdown files (no `type`) into concepts. Chunks are stored without embeddings; IndexPending (the worker, or the CLI's import) embeds them.

func (*Service) IndexPending

func (s *Service) IndexPending(ctx context.Context, batch int) (int, error)

IndexPending embeds up to batch chunks that still have no embedding — the worker's and the CLI's way to finish what a write or an import left pending. Returns how many chunks it embedded.

func (*Service) ListBundles

func (s *Service) ListBundles(ctx context.Context) ([]BundleInfo, error)

ListBundles returns every bundle.

func (*Service) ListConcepts

func (s *Service) ListConcepts(ctx context.Context, tok *store.Token, slug, prefix string, includeNotCurrent bool) ([]store.ConceptSummary, error)

ListConcepts lists the concepts of a bundle under a prefix.

func (*Service) ListEpisodes

func (s *Service) ListEpisodes(ctx context.Context, tok *store.Token, slug string, limit int) ([]store.Episode, error)

ListEpisodes returns the newest episodes of a bundle.

func (*Service) ListTokens

func (s *Service) ListTokens(ctx context.Context) ([]store.Token, error)

ListTokens returns every token.

func (*Service) PutConcept

func (s *Service) PutConcept(ctx context.Context, tok *store.Token, slug, conceptPath, content string) (*ConceptView, bool, error)

PutConcept stores a concept from its whole file content: a new concept, or a new version of an existing one. Unchanged content is a no-op. The concept is chunked and embedded at once when the provider answers; when it does not, the chunks wait for the worker.

func (*Service) RecentAudit

func (s *Service) RecentAudit(ctx context.Context, limit int) ([]store.AuditEntry, error)

RecentAudit returns the newest audit rows.

func (*Service) RecentQueries

func (s *Service) RecentQueries(ctx context.Context, limit int) ([]store.QueryLogEntry, error)

RecentQueries returns the newest logged searches (the admin log view).

func (*Service) Remember

func (s *Service) Remember(ctx context.Context, tok *store.Token, slug, text string) (int64, error)

Remember stores a raw memory of an agent; a later phase consolidates episodes into concepts.

func (*Service) RevokeToken

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

RevokeToken revokes a token.

func (*Service) RevokeTokenByName

func (s *Service) RevokeTokenByName(ctx context.Context, actor, name string) error

RevokeTokenByName revokes the token with that name.

func (*Service) RewriteContent

func (s *Service) RewriteContent(ctx context.Context, seal bool) (int, error)

RewriteContent seals (seal) or opens every stored content value in place; returns how many values changed.

func (*Service) Search

func (s *Service) Search(ctx context.Context, tok *store.Token, q *Query) (*Result, error)

Search ranks the chunks of the allowed bundles against the query. Every call is logged: the query log is what the experiment is measured by.

func (*Service) Stats

func (s *Service) Stats(ctx context.Context) (*Stats, error)

Stats returns the aggregates.

type Stats

type Stats struct {
	Bundles []BundleInfo       `json:"bundles"`
	Queries []store.QueryStats `json:"queries"`
	Tokens  int                `json:"tokens"`
}

Stats is the experiment's dashboard: bundles and their indexing state, the query log aggregates, and the token count.

Jump to

Keyboard shortcuts

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