knowledge

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: Apache-2.0 Imports: 23 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 knowledge is retrieval over a workspace's own documents: the folder you drop things into, chunked, embedded, and searched on demand.

It is the counterpart to internal/memory, and the two are deliberately not the same shape. Memory is what the assistant chose to remember — small, curated, and folded into EVERY prompt as a catalog. Knowledge is what YOU put there — arbitrarily large, never in the prompt, reached only when a tool goes looking. One is identity, the other is a library.

That difference decides where each lives. Memory sits outside the file tools' mount, because it is control plane: text that reaches every future prompt must not be writable through a generic file tool. Knowledge sits INSIDE the mount, at mnt/knowledge/, because documents are data — the same argument ADR-10 makes about a self-written skill granting no authority. What comes back from a search is untrusted content and is treated as such: redacted on the way in, and marked as foreign in the prompt.

The index does NOT live in the mount. It is host state — vectors, hashes, offsets — and the model has no business rewriting it.

Index

Constants

View Source
const DefaultInterval = time.Minute

DefaultInterval is how often a running daemon reconciles the corpus with the index.

A minute rather than a second because of what a reconcile now costs: an unchanged corpus is a directory walk, no file is opened, and nothing is written. Dropping a document in the folder and waiting up to a minute for it to be findable is the right trade against waking the machine sixty times as often to learn nothing.

Variables

This section is empty.

Functions

This section is empty.

Types

type Chunk

type Chunk struct {
	// Path is workspace-relative and forward-slashed — the same string a file tool would take.
	Path string `json:"path"`
	// Heading is the breadcrumb of Markdown headings above the passage ("Setup > Database"), empty
	// for text before any heading. It is shown in a result so a reader can place the quote, and it is
	// embedded with the text so a passage saying "set it to 30" is not orphaned from what "it" is.
	Heading string `json:"heading"`
	// Offset is the byte offset of Text within the file, so a result can point at a place rather than
	// at a document.
	Offset int `json:"offset"`
	// Text is the passage itself, as it appears in the file.
	Text string `json:"text"`
}

Chunk is one indexed passage: where it came from, and what it says.

type Embedder

type Embedder interface {
	// Embed returns one vector per input, in order. An error means none of them were produced.
	Embed(ctx context.Context, texts []string) ([][]float32, error)
	// Model names the embedding model, so an index can refuse vectors it cannot compare.
	Model() string
	// Dims is the length every returned vector has.
	Dims() int
}

Embedder turns text into vectors. It is a port: the consumer defines it, and the adapter lives beside it in internal/knowledge/embed.

Batched on purpose. Indexing a folder is thousands of chunks, and one request per chunk would spend the whole run on round trips; every provider worth using accepts a list.

A vector's meaning is relative to the model that produced it, so an index records which model and how many dimensions it was built with. Comparing across models is not a degraded answer, it is a meaningless one — see Index.stale.

type FileEntry

type FileEntry struct {
	// SHA256 of the file's bytes. The whole basis of incremental indexing: an unchanged hash means
	// the chunks and vectors below are still exactly what this file produces, so re-embedding it
	// would spend the operator's money to arrive at what is already on disk.
	SHA256 string `json:"sha256"`
	Size   int    `json:"size"`
	// ModTime is the file's timestamp when it was last read, in Unix nanoseconds. Only ever a HINT:
	// size and timestamp both matching means the file is not read at all, which is what makes a
	// periodic reconcile cost a directory walk instead of hashing the whole corpus. The hash stays
	// the truth, and a file whose timestamp moved is re-read and re-hashed before anything is
	// re-embedded — so a touched-but-unchanged file costs a read, never a provider call.
	ModTime int64         `json:"modTime"`
	Chunks  []StoredChunk `json:"chunks"`
}

FileEntry is one document as it was when last indexed.

type Index

type Index struct {
	Version int    `json:"version"`
	Model   string `json:"model"`
	Dims    int    `json:"dims"`
	// Files is keyed by the mount-relative, forward-slashed path.
	Files map[string]*FileEntry `json:"files"`
}

Index is everything known about a workspace's documents: which files were seen, what they hashed to, and the passages and vectors they produced.

It lives OUTSIDE the mount, beside grants.json. The corpus is data the model may read and write; the index is host state — hashes, offsets, vectors — and a model that could edit it could point a search result at text that is not in the file.

Model and Dims are recorded because a vector only means something relative to the model that produced it. Two different lengths cannot be compared at all, which fails loudly. Two different models at the SAME length is the dangerous case: the arithmetic still works and returns confident nonsense. Both are refused by Compatible.

func (*Index) Chunks

func (ix *Index) Chunks() []StoredChunk

Chunks returns every stored passage, in a stable order: by path, then by position in the file. Deterministic because search ranks on scores that tie, and a result list that reshuffles between two identical queries reads as instability that is not there.

func (*Index) Compatible

func (ix *Index) Compatible(model string, dims int) bool

Compatible reports whether this index can answer questions embedded by that model at that length.

Both halves matter and only one of them is obvious. A length mismatch makes comparison arithmetically impossible. A model mismatch at the same length does not — it produces a number, and the number is meaningless, which is the failure that would never be noticed.

func (*Index) Stats

func (ix *Index) Stats() (files, chunks int)

Stats is what a status command reports.

type MarkdownReader

type MarkdownReader struct{}

MarkdownReader splits Markdown and plain text at ATX headings.

Hand-written rather than a CommonMark parser, and that is a scope decision rather than a preference: what chunking needs from Markdown is where the subject changes, which ATX headings answer, and a parser would add a dependency for the ninety percent of syntax that does not affect a boundary. When fenced blocks containing "#" become a real problem, this is the thing that gets replaced — behind the port, without the rest of the package noticing.

func (MarkdownReader) Handles

func (MarkdownReader) Handles(ext string) bool

Handles takes Markdown and plain text. Anything else needs its own reader.

func (MarkdownReader) Sections

func (MarkdownReader) Sections(data []byte) ([]Section, error)

Sections splits the document at headings. It never fails: text is text.

type Options

type Options struct {
	// Dir is the corpus folder, mnt/knowledge in a workspace.
	Dir string
	// IndexPath is where the index is written, outside the mount.
	IndexPath string
	// Embedder is required — see New.
	Embedder Embedder
	// Scanner redacts vault values out of search results. Nil when no vault is unlocked.
	Scanner *secret.Scanner
	// Log is optional.
	Log *slog.Logger
}

Options is what a Store needs. A struct rather than five parameters, and it is the seam where the two paths differ: Dir is inside the mount because documents are data, IndexPath is outside it because the index is host state.

type Reader

type Reader interface {
	// Handles reports whether this reader takes that file extension, lowercased and with its dot.
	Handles(ext string) bool
	// Sections extracts the document. A reader for a binary format is what turns bytes into text.
	Sections(data []byte) ([]Section, error)
}

Reader turns one document format into sections. It is a port: the package chunks and embeds, and knows nothing about how a byte slice became text.

Deliberately narrow. Extracting from a PDF or an Office file needs a dependency that has no business inside a package the whole workspace links, so it belongs behind this interface in a package of its own — the same reason the embedding client is its own package.

type Report

type Report struct {
	Indexed   int      // files embedded this run
	Unchanged int      // files whose hash matched, so their vectors were reused
	Removed   int      // files gone from disk, dropped from the index
	Chunks    int      // passages in the index afterwards
	Skipped   []string // files no reader handles, named rather than silently ignored
}

Report is what one indexing run did.

type Result

type Result struct {
	Chunk
	// Score is the fused rank score. Comparable within one result list and meaningless outside it —
	// it is a sum of reciprocal ranks, not a similarity, and deliberately not presented as one.
	Score float64
	// Semantic and Lexical are the 1-based ranks this passage held in each ranker, or 0 when it did
	// not make that ranker's shortlist. Carried so a bad result can be diagnosed as "the vectors
	// liked it and the words did not" rather than guessed at.
	Semantic int
	Lexical  int
	// Similarity is the cosine between the query and this passage, always computed. UNLIKE Score it
	// means something on its own, which is why it is the number handed to the model: retrieval can
	// only rank what it has, so the judgement of whether the best match is actually an answer needs
	// the context of the question — and that is not in this package.
	//
	// It is not a probability. Its range is model-dependent: for many embedders unrelated text sits
	// well above zero, so the useful reading is comparative, not absolute.
	Similarity float32
}

Result is one passage the search found.

type Section

type Section struct {
	// Heading is the breadcrumb above the body ("Setup > Database"), empty where the format has no
	// such notion or the span sits above the first one.
	Heading string
	// Body is the text under it.
	Body string
	// Offset is where Body starts in the file, so a result can point at a place.
	Offset int
}

Section is a titled span of a document, as a Reader found it.

This is the seam between "what this file format looks like" and "how a passage is sized". A Markdown reader cuts at headings, a PDF reader would cut at pages or outline entries, a real CommonMark parser would cut at the same headings but understand fenced blocks and tables — and none of that changes how the sections are then packed into passages.

type Store

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

Store is one workspace's document index: the folder, the index beside it, and the embedder that connects them.

func New

func New(o Options) (*Store, error)

New opens the store. It reads neither the folder nor the index — Index and Search do.

A nil embedder is refused: without one there is nothing this type can do, and a Store that silently answers nothing is worse than a missing one. Whether the feature exists at all is the caller's decision, the same shape as the whoami tool and a speaker model.

func (*Store) Dir

func (s *Store) Dir() string

Dir is the corpus folder, for a caller that has to create or report it.

func (*Store) Index

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

Index brings the index in line with the folder.

It holds the store's lock for the whole run, including the provider calls, so a Search during one waits. That is deliberate rather than overlooked: a reconcile that found nothing to do holds it for a directory walk, which is the case that happens every minute, and the case that holds it for minutes is the FIRST index of a corpus — when there is nothing to search yet anyway. Building a replacement index outside the lock and swapping it in would remove the wait and add a second copy of the corpus in memory plus the reasoning about which one a concurrent write belongs to; not worth it until somebody actually waits.

Incremental by content hash: a file whose bytes are unchanged keeps the chunks and vectors it already has, because re-embedding it would spend the operator's money to arrive at what is already on disk. A file that is gone is dropped; a file no reader handles is SKIPPED AND NAMED — silently ignoring it is how somebody drops a PDF in the folder and never learns it is not searchable.

func (*Store) IndexPath

func (s *Store) IndexPath() string

IndexPath is where the index is written, so an error message can name it.

func (*Store) Paths

func (s *Store) Paths() ([]string, error)

Paths lists the indexed documents, sorted.

func (*Store) Search

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

Search finds the passages that best answer a query.

Hybrid, and the two halves fail differently on purpose. Vectors find a passage that means the same thing in other words, and miss an exact identifier they never saw during training — a serial number, an internal codename, a flag. Words find exactly that, and miss every paraphrase. Running one of them alone means accepting its blind spot as a property of the product.

The two are fused by reciprocal rank rather than by adding scores, because their scores share no scale. What survives is agreement: a passage both rankers put near the top beats one that either loved alone.

func (*Store) SetReaders

func (s *Store) SetReaders(rs ...Reader)

SetReaders replaces the set of document readers. The Markdown reader is the default; a consumer that has an extractor for another format installs it here, before the first Index.

Not a With* option: those configure at construction and this mutates afterwards, and calling the two the same thing is how somebody expects one and gets the other.

func (*Store) Stats

func (s *Store) Stats() (files, chunks int, err error)

Stats reports what the index holds, without indexing.

func (*Store) Tools

func (s *Store) Tools() ([]agentkit.Tool, error)

Tools is the tool set this store exposes: one search, ungated.

Ungated on the same argument that leaves memory_read and skill_read ungated: it is context, never authority. It reads files already inside the workspace mount and produces text — it changes nothing, and reaches nothing file_read could not already reach.

One thing IS worth stating rather than glossing: answering embeds the query, which sends it to the configured embedding provider. That is not a target the model chose — it is host configuration, the same standing as the endpoint that already sees every message of the conversation — so it is not a per-call decision to put in front of a human. The decision is made once, by configuring an embedder at all, and the documentation says what it means.

func (*Store) Watch

func (s *Store) Watch(ctx context.Context, every time.Duration)

Watch reconciles the corpus with the index until ctx is done.

A ticker rather than filesystem notifications, and that is a decision rather than a shortcut. Watching would mean a third-party dependency in a tree that keeps its list deliberately short, recursive watch management for every subdirectory that appears, and platform behaviour that silently drops events under load — after which a periodic reconcile is needed anyway as the backstop. This is only the backstop, without the part that would still need it.

It runs once immediately, so a daemon starting up does not wait an interval before noticing what changed while it was down. Every run is logged: a reconcile that quietly costs money is exactly what an operator should be able to see.

type StoredChunk

type StoredChunk struct {
	Chunk
	// Vector is base64 of little-endian float32. Not a JSON array of numbers: at 768 dimensions that
	// is roughly 10 KB of decimal text per chunk against 4 KB here, and a corpus of a few thousand
	// chunks turns the difference into tens of megabytes that have to be parsed on every load.
	Vector string `json:"vector"`
}

StoredChunk is a passage and its vector.

Directories

Path Synopsis
Package embed is the remote half of knowledge retrieval: an OpenAI-compatible /v1/embeddings client, and the only place in the tree that sends document text to a third party.
Package embed is the remote half of knowledge retrieval: an OpenAI-compatible /v1/embeddings client, and the only place in the tree that sends document text to a third party.

Jump to

Keyboard shortcuts

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