Documentation
¶
Index ¶
- Constants
- Variables
- func AddRecordTags(raw []byte, concepts []string) ([]byte, error)
- func AllowedTransitions(from string, hasSupersededBy bool) []string
- func CanTransition(from, to string, hasSupersededBy bool) bool
- func CandidateTerms(text string) []string
- func CheckDOIRetraction(doi, apiURL string) (retracted bool, note string, err error)
- func CheckpointAndCopy(srcPath, dstPath string) error
- func Chunk(text string, max int) []string
- func ChunkHash(text string) string
- func CleanName(kind, name string) (string, error)
- func DefaultPath(root string) string
- func DetectIdentityIssues(aPath, bPath string) ([]IdentityCollision, []ContentDivergence, error)
- func ExportJSONL(kb *KnowledgeBase, w io.Writer, projectName string) error
- func FactKey(fact string) string
- func FindWorkspace(dir string) (root, marker string, ok bool)
- func FmtHelp(src string, appName string, version string, releaseDate string, ...) string
- func IsFrontmatterScalarField(name string) bool
- func IsValidKind(kind string) bool
- func LevenshteinDistance(a, b string) int
- func NewUUID() (string, error)
- func NormalizeForMerge(scratchPath, originalPath string) error
- func ParseKnowledgeItem(item string) (character, fact string, ok bool)
- func ReconcileCollisions(bPath string, collisions []IdentityCollision) error
- func RecordIDPrefix(kind string) string
- func RecordLabel(id string) string
- func RegisterEmbedder(e Embedder)
- func RenderRecordFile(rf *RecordFile) ([]byte, error)
- func StripCodeSpans(text string) string
- func StripCommonSuffix(s string) string
- func TagDocumentText(text string, names []string) (string, []string)
- func Today() string
- func ValidConceptKind(kind string) bool
- func VectorsPath(dbPath string) string
- func WikilinkTarget(inner string) string
- type AmbiguousRefError
- type Checker
- type CitedRef
- type Concept
- type ConceptCandidate
- type ConceptDetailItem
- type ConceptDetailResult
- type ConceptInUseError
- type ConceptMatch
- type ConceptSpan
- type ConceptSuggestions
- type ConceptUsage
- type ContentDivergence
- type CorpusRow
- type DBComparison
- type Document
- type DocumentIngestOptions
- type DocumentIngestResult
- type DocumentReviewItem
- type DocumentSection
- type DocumentUsage
- type EmbedOptions
- type EmbedProgress
- type EmbedResult
- type EmbedStatus
- type Embedder
- type FrontmatterAccept
- type FrontmatterFieldReport
- type FrontmatterKeywordReport
- type FrontmatterResult
- type FrontmatterSignal
- type FusedRow
- type FuzzyConceptMatch
- type FuzzyTagInsertion
- type GitProvenance
- type HitProvenance
- type IdentityCollision
- type ImportTableSummary
- type InUseError
- type KBSearchResult
- type KnowledgeBase
- func (kb *KnowledgeBase) AddConcept(name, description string) (int64, error)
- func (kb *KnowledgeBase) AddConceptWithIdentifier(name, description, identifierType, identifierValue string) (int64, error)
- func (kb *KnowledgeBase) AddDocument(d Document) (int64, error)
- func (kb *KnowledgeBase) AddDocumentSection(s DocumentSection) (int64, error)
- func (kb *KnowledgeBase) AddObservation(projectID int64, kind, body string) (int64, error)
- func (kb *KnowledgeBase) AddObservationDraft(projectID int64, kind, body, by string, confidence *float64) (int64, error)
- func (kb *KnowledgeBase) AddObservationRelation(fromID, toID int64, relationship string) error
- func (kb *KnowledgeBase) AddObservationWithSource(projectID int64, kind, body, sourceDOI string) (int64, error)
- func (kb *KnowledgeBase) AddProject(name, description string) (int64, error)
- func (kb *KnowledgeBase) AddProjectWithStatus(name, description, status string) (int64, error)
- func (kb *KnowledgeBase) AddRecord(r Record) (int64, error)
- func (kb *KnowledgeBase) AddRecordRelation(fromID, toID int64, relationship string) error
- func (kb *KnowledgeBase) AddSource(s Source) (int64, error)
- func (kb *KnowledgeBase) ApplyFrontmatter(path string, raw []byte, prov Provenance, accept FrontmatterAccept, ...) ([]byte, FrontmatterResult, error)
- func (kb *KnowledgeBase) CheckRetractions(checker func(doi string) (retracted bool, note string, err error), ...) (checked, updated int, err error)
- func (kb *KnowledgeBase) ClearDocumentSectionConcepts(sectionID int64) error
- func (kb *KnowledgeBase) ClearRecordConcepts(recordID int64) error
- func (kb *KnowledgeBase) ClearRecordRelationsFrom(fromID int64) error
- func (kb *KnowledgeBase) Close() error
- func (kb *KnowledgeBase) CompareToJSONL(r io.Reader) (DBComparison, error)
- func (kb *KnowledgeBase) ConceptDetail(name string, limit int) (ConceptDetailResult, error)
- func (kb *KnowledgeBase) ConceptUsage(name string) (ConceptUsage, error)
- func (kb *KnowledgeBase) Concepts() ([]Concept, error)
- func (kb *KnowledgeBase) ConceptsOfKind(kind string) ([]Concept, error)
- func (kb *KnowledgeBase) DeleteConcept(name string, force bool) (ConceptUsage, error)
- func (kb *KnowledgeBase) DeleteDocument(id int64, force bool) (DocumentUsage, error)
- func (kb *KnowledgeBase) DeleteObservation(id int64, force bool) (ObservationUsage, error)
- func (kb *KnowledgeBase) DeleteProject(name string, force bool) (ProjectUsage, error)
- func (kb *KnowledgeBase) DeleteRecord(id int64) (RecordUsage, error)
- func (kb *KnowledgeBase) DistinctRecordValues(field string) ([]string, error)
- func (kb *KnowledgeBase) DocumentByID(id int64) (*Document, error)
- func (kb *KnowledgeBase) DocumentByPath(path string) (*Document, error)
- func (kb *KnowledgeBase) DocumentReviewQueue(projectID int64, status string) ([]DocumentReviewItem, error)
- func (kb *KnowledgeBase) DocumentSectionConcepts(sectionID int64) ([]Concept, error)
- func (kb *KnowledgeBase) DocumentSections(documentID int64) ([]DocumentSection, error)
- func (kb *KnowledgeBase) DocumentSources(documentID int64) ([]SourceLink, error)
- func (kb *KnowledgeBase) DocumentUsage(id int64) (DocumentUsage, error)
- func (kb *KnowledgeBase) Documents(projectID int64) ([]Document, error)
- func (kb *KnowledgeBase) DraftDocumentSummary(sectionID int64, body, generatedBy string, confidence *float64) error
- func (kb *KnowledgeBase) EligibleTagConcepts(text string, candidates []string) ([]string, error)
- func (kb *KnowledgeBase) EmbedCorpus(scope SearchScope) ([]CorpusRow, error)
- func (kb *KnowledgeBase) EmbedIndex(ctx context.Context, v *Vectors, e Embedder, opts EmbedOptions) (EmbedResult, error)
- func (kb *KnowledgeBase) EmbedStatus(v *Vectors, chunkRunes int) (EmbedStatus, error)
- func (kb *KnowledgeBase) FindOrCreateSource(title, identifierType, identifierValue string) (int64, error)
- func (kb *KnowledgeBase) FormatMarkdown(projectID int64) (string, error)
- func (kb *KnowledgeBase) FuzzyMatchConceptNames(text string) ([]FuzzyConceptMatch, error)
- func (kb *KnowledgeBase) HasConcept(name string) (bool, error)
- func (kb *KnowledgeBase) HitsFor(keys []RowKey) ([]KBSearchResult, error)
- func (kb *KnowledgeBase) IngestDocument(projectID int64, path string, opts DocumentIngestOptions) (DocumentIngestResult, error)
- func (kb *KnowledgeBase) LexicalRanking(term string, scope SearchScope) ([]RowKey, error)
- func (kb *KnowledgeBase) LexicalRankingWide(term string, scope SearchScope) (typed, widened []RowKey, err error)
- func (kb *KnowledgeBase) LinkDocumentSectionConcept(sectionID, conceptID int64) error
- func (kb *KnowledgeBase) LinkDocumentSource(documentID, sourceID int64, relationship, version, hash string) error
- func (kb *KnowledgeBase) LinkObservationConcept(observationID, conceptID int64) error
- func (kb *KnowledgeBase) LinkObservationSource(observationID, sourceID int64, relationship string) error
- func (kb *KnowledgeBase) LinkObservationSourceAt(observationID, sourceID int64, relationship, version, hash string) error
- func (kb *KnowledgeBase) LinkProjectConcept(projectID, conceptID int64) error
- func (kb *KnowledgeBase) LinkRecordConcept(recordID, conceptID int64) error
- func (kb *KnowledgeBase) LinkRecordSource(recordID, sourceID int64, relationship, version, hash string) error
- func (kb *KnowledgeBase) ListRecords(f RecordFilter) ([]Record, error)
- func (kb *KnowledgeBase) ListSources() ([]Source, error)
- func (kb *KnowledgeBase) MarkDocumentSectionStale(id int64) error
- func (kb *KnowledgeBase) MatchConceptNameCounts(text string) (map[string]int, error)
- func (kb *KnowledgeBase) MatchConceptNames(text string) ([]string, error)
- func (kb *KnowledgeBase) ObservationByID(id int64) (*Observation, error)
- func (kb *KnowledgeBase) ObservationConcepts(observationID int64) ([]Concept, error)
- func (kb *KnowledgeBase) ObservationRelationsFor(id int64) ([]RelatedObservation, error)
- func (kb *KnowledgeBase) ObservationReviewQueue(projectID int64) ([]Observation, error)
- func (kb *KnowledgeBase) ObservationSourceLinks(observationID int64) ([]SourceLink, error)
- func (kb *KnowledgeBase) ObservationSources(observationID int64) ([]Source, error)
- func (kb *KnowledgeBase) ObservationUsage(id int64) (ObservationUsage, error)
- func (kb *KnowledgeBase) Observations(projectID int64) ([]Observation, error)
- func (kb *KnowledgeBase) ObservationsByStatus(projectID int64, status string) ([]Observation, error)
- func (kb *KnowledgeBase) Path() string
- func (kb *KnowledgeBase) ProjectByName(name string) (*Project, error)
- func (kb *KnowledgeBase) ProjectConcepts(projectID int64) ([]Concept, error)
- func (kb *KnowledgeBase) ProjectForDir(root, dir string) (string, error)
- func (kb *KnowledgeBase) ProjectUsage(name string) (ProjectUsage, error)
- func (kb *KnowledgeBase) Projects() ([]Project, error)
- func (kb *KnowledgeBase) PromoteDocumentSummary(sectionID int64) error
- func (kb *KnowledgeBase) PromoteObservation(id int64) error
- func (kb *KnowledgeBase) ProposeFrontmatter(path string, raw []byte, prov Provenance) (FrontmatterResult, error)
- func (kb *KnowledgeBase) RecallByConceptNames(names []string, limit int) ([]ConceptMatch, error)
- func (kb *KnowledgeBase) RecallByNames(names []string, limit int, project string) (TextRecall, error)
- func (kb *KnowledgeBase) RecallByText(text string, limit int, project string) (TextRecall, error)
- func (kb *KnowledgeBase) RecordByID(id int64) (*Record, error)
- func (kb *KnowledgeBase) RecordByIdentity(workspace string, projectID int64, scope, recordID string) (*Record, error)
- func (kb *KnowledgeBase) RecordConcepts(recordID int64) ([]Concept, error)
- func (kb *KnowledgeBase) RecordFuzzyReport(rf *RecordFile, explicit []string) ([]RecordFuzzyFinding, error)
- func (kb *KnowledgeBase) RecordSources(recordID int64) ([]SourceLink, error)
- func (kb *KnowledgeBase) RecordUsage(id int64) (RecordUsage, error)
- func (kb *KnowledgeBase) RecordsByProject(projectID int64) ([]Record, error)
- func (kb *KnowledgeBase) RecordsByRecordID(recordID string) ([]Record, error)
- func (kb *KnowledgeBase) RecordsUnderPath(prefix string) ([]Record, error)
- func (kb *KnowledgeBase) RelationsFor(id int64) ([]RelatedRecord, error)
- func (kb *KnowledgeBase) RemoveRecordRelation(fromID, toID int64, relationship string) (bool, error)
- func (kb *KnowledgeBase) RemoveSource(id int64) error
- func (kb *KnowledgeBase) RenameConcept(old, new string) error
- func (kb *KnowledgeBase) RenameProject(old, new string) error
- func (kb *KnowledgeBase) RenameProjectRow(old, new string) error
- func (kb *KnowledgeBase) ResolveConceptName(name string) (int64, error)
- func (kb *KnowledgeBase) ResolveRef(ref Ref, workspace string) (*Record, error)
- func (kb *KnowledgeBase) RetractSource(id int64, note string) error
- func (kb *KnowledgeBase) Search(term string) ([]KBSearchResult, error)
- func (kb *KnowledgeBase) SearchScoped(term string, scope SearchScope) (*ScopedSearchResult, error)
- func (kb *KnowledgeBase) SemanticSearch(v *Vectors, e Embedder, query string, opts SemanticOptions) (*SemanticResult, error)
- func (kb *KnowledgeBase) SetConceptKind(name, kind string) error
- func (kb *KnowledgeBase) SetProjectDescription(name, description string) error
- func (kb *KnowledgeBase) SetProjectStatus(name, status string) error
- func (kb *KnowledgeBase) ShowSource(id int64) (*Source, error)
- func (kb *KnowledgeBase) SourceCitations(id int64) (SourceCitations, error)
- func (kb *KnowledgeBase) SourceObservationCount(id int64) (int, error)
- func (kb *KnowledgeBase) Stats() (Stats, error)
- func (kb *KnowledgeBase) StoryCheck(projectID int64) ([]StoryFinding, error)
- func (kb *KnowledgeBase) StoryEvents(projectID int64) ([]StoryEvent, error)
- func (kb *KnowledgeBase) StoryTimeline(projectID int64, narrative bool) ([]TimelineEntry, error)
- func (kb *KnowledgeBase) SuggestConcepts(project string, limit int) (ConceptSuggestions, error)
- func (kb *KnowledgeBase) Summary() (string, error)
- func (kb *KnowledgeBase) SyncDocumentSources(documentID int64, refs []CitedRef) (int, []string, error)
- func (kb *KnowledgeBase) SyncRecordSources(recordID int64, refs []CitedRef) (int, []string, error)
- func (kb *KnowledgeBase) UnlinkDocumentSource(documentID, sourceID int64) error
- func (kb *KnowledgeBase) UnlinkObservationConcept(observationID int64, concept string) error
- func (kb *KnowledgeBase) UnlinkObservationSource(observationID, sourceID int64) error
- func (kb *KnowledgeBase) UnlinkProjectConcept(project, concept string) error
- func (kb *KnowledgeBase) UnlinkRecordSource(recordID, sourceID int64) error
- func (kb *KnowledgeBase) UpdateDocumentDescription(id int64, description string) error
- func (kb *KnowledgeBase) UpdateDocumentMetadata(id int64, title, author, publishedDate, checksum string) error
- func (kb *KnowledgeBase) UpdateDocumentSectionBody(id int64, body string, sourceSize, tagDensity int, stale bool) error
- func (kb *KnowledgeBase) UpdateDocumentSectionTagDensity(id int64, tagDensity int) error
- func (kb *KnowledgeBase) UpdateRecordPath(id int64, path string) error
- func (kb *KnowledgeBase) UpdateRecordStatus(id int64, status string) error
- func (kb *KnowledgeBase) WhoKnows(projectID int64, character, scene string) (WhoKnowsResult, error)
- func (kb *KnowledgeBase) WhoLearns(projectID int64, fact string) ([]Learner, error)
- func (kb *KnowledgeBase) Workspace() string
- type KnownFact
- type Learner
- type MaterialRef
- type MergeScratch
- type MergeTableSummary
- type NearExistingMatch
- type Observation
- type ObservationUsage
- type ParsedDocument
- type Project
- type ProjectStats
- type ProjectUsage
- type Provenance
- type Record
- type RecordFile
- type RecordFilter
- type RecordFuzzyFinding
- type RecordUsage
- type Ref
- type RelatedObservation
- type RelatedRecord
- type RetractionCheckError
- type RowDifference
- type RowKey
- type ScopedSearchResult
- type SearchScope
- type SemanticHit
- type SemanticOptions
- type SemanticResult
- type Source
- type SourceCitations
- type SourceLink
- type SourceRef
- type StatCount
- type Stats
- type StoredChunk
- type StoryEvent
- type StoryFinding
- type StoryMeta
- type StoryTime
- type TableDiff
- type TextRecall
- type TextRecallHit
- type TimelineEntry
- type UsageCount
- type Vectors
- func (v *Vectors) Building() (bool, error)
- func (v *Vectors) CheckModel(e Embedder) error
- func (v *Vectors) ChunkCount() (int, error)
- func (v *Vectors) Close() error
- func (v *Vectors) DeleteRow(sourceType string, sourceID int64) error
- func (v *Vectors) IndexedRows() ([]RowKey, error)
- func (v *Vectors) Lock() (*VectorsLock, error)
- func (v *Vectors) Meta() VectorsMeta
- func (v *Vectors) Path() string
- func (v *Vectors) PutRow(sourceType string, sourceID int64, chunks []StoredChunk) error
- func (v *Vectors) RowChunks(sourceType string, sourceID int64) ([]StoredChunk, error)
- type VectorsLock
- type VectorsMeta
- type WhoKnowsResult
Constants ¶
const ( // Version number of release Version = "0.0.32" // ReleaseDate, the date version.go was generated ReleaseDate = "2026-11-20" // ReleaseHash, the Git hash when version.go was generated ReleaseHash = "cdbcbcf" LicenseText = `` /* 770-byte string literal not displayed */ )
const ( MarkerDB = "knowledge.db" MarkerJSONL = "knowledge.jsonl" )
* MarkerDB and MarkerJSONL name the two files whose presence under agents/
- marks a directory as a workspace root. The database is the working copy;
- the JSONL file is the tracked export a fresh clone has before its database
- is rebuilt from it (the database is gitignored).
const CeilingEnv = "KB_CEILING_DIRECTORIES"
* CeilingEnv names the environment variable listing directories FindWorkspace
- must not examine, nor anything above them (the PathListSeparator separates
- entries; blank entries are ignored), as git's GIT_CEILING_DIRECTORIES does.
- It keeps a scratch directory, or a test, from walking up into a real
- workspace.
const DefaultChunkRunes = 400
* DefaultChunkRunes is the longest chunk, in characters, that Chunk is asked
- for when semantic search embeds a row: about 128 tokens. It is a starting
- value, to be tuned against the labelled query set (semantic-search-plan.md T9).
const DefaultFusionK = 60
* DefaultFusionK is the constant in reciprocal-rank fusion, 1/(k + rank). The
- usual value is 60. It is a starting point, to be checked against the labelled
- query set (semantic-search-plan.md T9).
const DefaultMinScore = 0.35
* DefaultMinScore is the cosine similarity a chunk must reach to be returned
- when SemanticOptions.MinScore is zero. Without a cutoff nearest-neighbour
- search never finds nothing. It was set from the labelled query set
- (semantic-search-plan.md T9) for all-MiniLM-L6-v2: recall at 10 is unchanged
- from 0.20 to 0.35 and falls at 0.40, and 0.35 halves the rows returned
- compared with 0.30. Another model needs its own measurement.
const DefaultRetractionWatchURL = "https://api.retractionwatch.com/api/v1/retractiondata/"
DefaultRetractionWatchURL is the base URL for the Retraction Watch API.
const LockStaleAfter = 5 * time.Minute
* LockStaleAfter is how long a claim on the vector index may go without a
- heartbeat before another run may take it over: a run that crashed or was
- killed does not block the index for ever. A live run refreshes its claim after
- every batch, which takes seconds.
const NoCutoff = -1
* NoCutoff, as SemanticOptions.MinScore, returns every indexed row however far
- from the query it is: cosine similarity is never below -1.
const VectorsSchemaVersion = 1
* VectorsSchemaVersion is the version of the sidecar's tables. A file written
- by a newer version is refused rather than misread.
Variables ¶
var ( // cancelled is adopted, then abandoned: distinct from rejected (never // adopted) and superseded (replaced by a later decision). The reason goes in // the record's body, by convention. See TODO.md, raised 2026-09-21. RecordStatuses = []string{"proposed", "accepted", "superseded", "rejected", "cancelled"} RecordKinds = []string{"decision", "correction", "refinement", "design", "plan"} RecordTriggers = []string{ "design", "plan-review", "implementation", "live-test", "release-review", "request", "external", } )
RecordStatuses, RecordKinds and RecordTriggers are the vocabularies from DECISION_RECORD_FORMAT.md. They are documented and reported against, not enforced: a value outside them parses and is carried, with a warning. Rejecting one would turn a typo in a file several harnesses write into a failed run rather than a fixable row.
var ConceptKinds = []string{"character", "place", "theme", "other"}
* ConceptKinds is the closed vocabulary of concept kinds (DR-0078): what a
- concept names. "other" is the default, and the value of every concept made
- before kinds existed. *
- Example:
- fmt.Println(strings.Join(knowledge.ConceptKinds, ", ")) // character, place, theme, other
var EmbeddedKinds = []string{"records", "observations", "concepts", "documents"}
* EmbeddedKinds are the search kinds semantic search embeds, in the order
- SearchKinds lists them: observations, decision records, documents (each
- document's title, description and headings entry, and its reviewed summaries)
- and concepts. Projects and sources are short and lexical search
- serves them (workspace DR-0088, semantic-search-design.md section 6). *
- Example:
- for _, k := range knowledge.EmbeddedKinds { fmt.Println(k) }
var ErrAmbiguousScene error = ambiguousScene{}
* ErrAmbiguousScene marks a scene name that matches more than one event: a label
- shared by two events, or a scene number used in two files (DR-0083 item 5). It
- is also an ErrInvalid, so errors.Is matches either: a command line that names
- such a scene is a usage error (exit 2). *
- Example:
- _, err := kb.WhoKnows(pid, "Anna", "twin")
- if errors.Is(err, knowledge.ErrAmbiguousScene) { // name the scene by its number instead }
var ErrConflict = errors.New("conflict")
* ErrConflict marks an error the library raises because the current state of
- the knowledge base forbids an operation that was otherwise well formed: a
- rename onto a name that is already taken, a project that still owns records, a
- document section that is not in the state a promotion needs. Match it with
- errors.Is; the message is unchanged. kb exits 1 for it (workspace DR-0003 class
- "negative": the command ran correctly and the answer is no). An item that is
- still referenced has its own marker, ErrInUse. *
- Example:
- if err := kb.RenameConcept("old", "new"); errors.Is(err, knowledge.ErrConflict) {
- // "new" already exists
- }
var ErrInUse = errors.New("in use")
* ErrInUse marks an error the library raises because an operation is refused
- while the item is still referenced: a source still linked to an observation.
- Match it with errors.Is; the message is unchanged. It is a refusal the current
- state forces, so kb exits 1 for it (workspace DR-0003 class "negative"). A
- concept still linked has its own typed error, *ConceptInUseError. *
- Example:
- if err := kb.RemoveSource(1); errors.Is(err, knowledge.ErrInUse) {
- // unlink it first
- }
var ErrInvalid = errors.New("invalid")
* ErrInvalid marks an error the library raises because a value it was given is
- not acceptable: a name that is blank, an observation kind or project status
- outside its vocabulary, a malformed source date, url or DOI, a record or
- frontmatter block that does not parse. Match it with errors.Is; the message is
- unchanged. Whether it is a mistake in a command line or in a file's content is
- the caller's to say: kb exits 2 for the first and 65 for the second (workspace
- DR-0003, knowledge DR-0047). *
- Example:
- if _, err := kb.AddObservation(id, "bogus", "text"); errors.Is(err, knowledge.ErrInvalid) {
- // the kind is not one of ValidObservationKinds
- }
var ErrLocked = errors.New("vector index locked")
* ErrLocked marks an error raised because another run holds the vector index:
- two kb embed runs would write the same file. Trying again later may work, so
- kb exits 75 for it (workspace DR-0003 class "temp_fail"). Match it with
- errors.Is. *
- Example:
- if _, err := v.Lock(); errors.Is(err, knowledge.ErrLocked) {
- // another kb embed is running; try again later
- }
var ErrModelMismatch = errors.New("vector index built by another model")
* ErrModelMismatch marks an error raised because the vector index was built by
- a different model (name, dimensions or fingerprint) than the embedder in use.
- Mixing the two would rank nonsense, so it is refused; the remedy is to rebuild
- the index. kb exits 65 for it (class "data"). Match it with errors.Is. *
- Example:
- if err := v.CheckModel(e); errors.Is(err, knowledge.ErrModelMismatch) {
- // tell the user to run kb embed -rebuild
- }
var ErrNoIndex = errors.New("no vector index")
* ErrNoIndex marks an error raised because the vector index has not been built:
- there is no sidecar file beside the database. kb exits 66 for it (workspace
- DR-0003 class "no_input") and the message points to kb embed. Match it with
- errors.Is. *
- Example:
- if _, err := knowledge.OpenVectors(dbPath); errors.Is(err, knowledge.ErrNoIndex) {
- // tell the user to run kb embed
- }
var ErrNoMembers = errors.New("no members")
* ErrNoMembers marks a search whose scope and kind cannot have any rows by the
- shape of the knowledge base: observations always belong to a project, so the
- workspace tier has none, and a project has no projects inside it. It is not an
- empty result and not a bad argument: the question was well formed and the
- answer is no (knowledge DR-0074). kb exits 1 for it, with the message as the
- reason. Match it with errors.Is. *
- Example:
- _, err := kb.SearchScoped("cache", knowledge.SearchScope{Workspace: true, Kinds: []string{"observations"}})
- if errors.Is(err, knowledge.ErrNoMembers) {
- // say why, exit 1
- }
var ErrNotFound = errors.New("not found")
* ErrNotFound marks an error the library raises because a name it was asked
- about is not in the knowledge base: a project or concept to rename, delete or
- export. Match it with errors.Is; the message is unchanged. It is not used for
- a lookup that returns (nil, nil), which is not an error. *
- Example:
- if err := kb.RenameConcept("old", "new"); errors.Is(err, knowledge.ErrNotFound) {
- // there is no concept "old"
- }
var SearchKinds = []string{"records", "observations", "concepts", "documents", "sources", "projects"}
* SearchKinds is the closed vocabulary of kinds a scoped search accepts, in
- the order a menu and completion list them (knowledge DR-0073). One list serves
- the parser, completion and the help text, so they cannot disagree. "sources"
- joined it with DR-0080, which indexed sources and amended DR-0013. *
- Example:
- for _, k := range knowledge.SearchKinds { fmt.Println(k) }
var ValidObservationKinds = []string{"note", "finding", "decision", "question", "hypothesis"}
ValidObservationKinds lists the accepted values for Observation.Kind.
Functions ¶
func AddRecordTags ¶ added in v0.0.15
* AddRecordTags adds concepts to the frontmatter `tags:` of a record file's
- raw bytes, changing nothing else: not the other frontmatter lines, not the
- body, not the line endings. It is not RenderRecordFile, which normalises the
- whole file. *
- It edits three shapes of tags and refuses the rest rather than guessing:
- a one-line flow list (`tags: []`, `tags: [a, b]`), a block list
- (`tags:` then `- item` lines), and an absent field (a `tags:` line is
- added before the closing fence). A name already present, compared without
- regard to case, is not added again, so the call is idempotent. *
- Parameters:
- raw ([]byte) — the whole record file.
- concepts ([]string) — names to add. *
- Returns:
- []byte — the edited file; the input itself, unchanged, when there was nothing to add.
- error — ErrInvalid for a file without frontmatter or a tags form it will not edit. *
- Example:
- next, err := knowledge.AddRecordTags(raw, []string{"toast"})
func AllowedTransitions ¶ added in v0.0.18
* AllowedTransitions returns the statuses a record may move to from the given
- status, in RecordStatuses order. The table is DR-0060 as confirmed for D0: the
- single source the direct form, the review prompt and the TUI all read. *
- Parameters:
- from (string) — the record's current status
- hasSupersededBy (bool) — whether the record already carries superseded_by *
- Returns:
- []string — the permitted target statuses; empty for a terminal or unknown status *
- Example:
- AllowedTransitions("proposed", false) // [accepted rejected]
func CanTransition ¶ added in v0.0.18
- CanTransition reports whether a record may move from one status to another. *
- Parameters:
- from (string) — the current status
- to (string) — the requested status
- hasSupersededBy (bool) — whether the record already carries superseded_by *
- Returns:
- bool — true when the move is in the table; a same-status request is false *
- Example:
- CanTransition("rejected", "accepted", false) // false
func CandidateTerms ¶ added in v0.0.12
* CandidateTerms returns the lowercased single-word candidate terms in text,
- in order of appearance with repeats kept. Fenced code blocks and inline code
- spans are stripped first (StripCodeSpans), then English stopwords and bare
- record references (dr-0013, adr-0004) are dropped. Filtering out terms that
- are already known concepts is left to the caller. This is the one
- definition of "a candidate word" that concept suggestion and the
- frontmatter keyword scorer share. *
- Parameters:
- text (string) — free text, e.g. a document section body. *
- Returns:
- []string — the surviving terms, each at least three characters long. *
- Example:
- knowledge.CandidateTerms("The chunking and `code` again") // ["chunking", "again"]
func CheckDOIRetraction ¶
* CheckDOIRetraction queries the Retraction Watch API for the given DOI and
- reports whether the work has been retracted. *
- Parameters:
- doi (string) — DOI to query, e.g. "10.1234/example".
- apiURL (string) — base URL of the Retraction Watch API; use
- DefaultRetractionWatchURL for production. *
- Returns:
- retracted (bool) — true when the DOI appears in the retraction database.
- note (string) — human-readable note with reason and date; empty when
- not retracted.
- error — on network failure, non-200 response, or bad JSON. *
- Example:
- retracted, note, err := CheckDOIRetraction("10.1234/paper", DefaultRetractionWatchURL)
- if retracted { fmt.Println("retracted:", note) }
func CheckpointAndCopy ¶ added in v0.0.15
* CheckpointAndCopy checkpoints srcPath's WAL, so every committed page is in
- the main file, and copies it, plus any -wal and -shm sidecars still present,
- to dstPath. The checkpoint is the one thing it does to the source: it moves
- committed pages into the main file and changes no row. *
- Parameters:
- srcPath (string) — the database to copy.
- dstPath (string) — where the copy goes; overwritten if present. *
- Returns:
- error — if the source cannot be opened, checkpointed or copied. *
- Example:
- err := knowledge.CheckpointAndCopy("agents/knowledge.db", "/tmp/scratch/a.db")
func Chunk ¶ added in v0.0.29
* Chunk splits text into pieces of at most max characters for embedding. It
- breaks at paragraph boundaries where it can, then at word boundaries, and cuts
- a single word only when that word is longer than max. Short paragraphs are
- packed together. Text with no words gives no chunks. The result is the same
- for the same input. *
- Parameters:
- text (string) — the text to split
- max (int) — the most characters in a chunk; zero or less means DefaultChunkRunes *
- Returns:
- []string — the chunks, in order, each non-empty and trimmed *
- Example:
- for _, c := range knowledge.Chunk(body, knowledge.DefaultChunkRunes) {
- fmt.Println(len(c))
- }
func ChunkHash ¶ added in v0.0.29
* ChunkHash returns the content hash stored with a chunk: the hex SHA-256 of its
- text. Equal text gives an equal hash, which is how an unchanged chunk is
- recognised and skipped. *
- Parameters:
- text (string) — the chunk text *
- Returns:
- string — the hash *
- Example:
- h := knowledge.ChunkHash("a chunk")
func CleanName ¶ added in v0.0.13
* CleanName makes a project or concept name one tidy line: it trims the ends,
- collapses every interior run of whitespace (a newline, a tab, a non-breaking
- space, two spaces) to a single space, and refuses a name that is empty
- afterwards or holds any other control character. *
- A blank name is never meaningful: it sorts first in every list, cannot be
- typed back to select it, and used to be storable by `kb project add ”`.
- Trimming matches what ingest already does to wikilink and tag text, so a
- padded name resolves to the row it plainly means instead of forking a
- duplicate. Collapsing does the same for a hard-wrapped [[wikilink]]: the
- wrapped spelling and the one-line spelling are the same concept, and neither
- can put a newline into a project list row or a directory name. A control
- character such as ESC or NUL is never part of a real name and would reach the
- terminal as typed, so it is refused (DR-0046, reversing DR-0042 item 1's
- "interior whitespace is left alone"). *
- Parameters:
- kind (string) — "project" or "concept"; only used in the error message.
- name (string) — the name as supplied. *
- Returns:
- string — the cleaned name.
- error — if the cleaned name is empty or holds a control character. *
- Example:
- name, err := CleanName("concept", "deterministic\noutput") // "deterministic output", nil
func DefaultPath ¶
* DefaultPath returns the conventional knowledge.db location under root
- (root + "agents/knowledge.db"), for callers with no path override of
- their own. *
- Parameters:
- root (string) — the project or workspace root directory. *
- Returns:
- string — root joined with "agents/knowledge.db". *
- Example:
- dbPath := DefaultPath("/home/user/myproject")
- kb, err := Open(dbPath)
func DetectIdentityIssues ¶ added in v0.0.15
func DetectIdentityIssues(aPath, bPath string) ([]IdentityCollision, []ContentDivergence, error)
* DetectIdentityIssues is the read-only detection half of a merge: the
- entities both databases hold under different uuids, and the records both
- hold with different text. It changes nothing; correction is
- ReconcileCollisions and MergeKnowledgeBases. Both paths must already carry
- the current schema (see PrepareMergeScratch). *
- Parameters:
- aPath (string) — the first database (a scratch copy).
- bPath (string) — the second database (a scratch copy). *
- Returns:
- []IdentityCollision — CollisionReport's result.
- []ContentDivergence — DivergenceReport's result.
- error — on database failure. *
- Example:
- collisions, divergences, err := knowledge.DetectIdentityIssues(s.A, s.B)
func ExportJSONL ¶ added in v0.0.3
func ExportJSONL(kb *KnowledgeBase, w io.Writer, projectName string) error
* ExportJSONL writes the knowledge base (or, when projectName is
- non-empty, just the reachable subset of one project) as a stream of
- newline-delimited JSON records to w -- one project/concept/source/
- observation/link per line, in dependency order (parents before
- children), each self-describing via a "type" field. See
- jsonl-export-design.md for the full format and the reachability rule
- used when projectName is set. Import with ImportJSONL. *
- Parameters:
- kb (*KnowledgeBase) — the knowledge base to export.
- w (io.Writer) — destination for the JSON-L stream.
- projectName (string) — "" exports every project; a specific
- name exports only that project and
- everything reachable from it. *
- Returns:
- error — if projectName is set but no such project exists, or on
- database/encoding failure. *
- Example:
- f, _ := os.Create("export.jsonl")
- defer f.Close()
- err := ExportJSONL(kb, f, "") // whole database
func FactKey ¶ added in v0.0.25
* FactKey folds a fact's text to its identity (DR-0083 item 2): lower case, with
- runs of white space collapsed to one space. No stemming. *
- Parameters:
- fact (string) — the fact as written. *
- Returns:
- string — the key two spellings of one fact share. *
- Example:
- knowledge.FactKey("The Letter is forged") // "the letter is forged"
func FindWorkspace ¶ added in v0.0.17
* FindWorkspace walks up from dir to the nearest ancestor (dir itself
- included) whose agents/ directory holds a regular file named knowledge.db
- or knowledge.jsonl, the way git finds .git. Where one directory holds both,
- the database is reported. An agents/ directory without either file, or a
- marker that is a directory, does not make a workspace. A directory listed in
- CeilingEnv ends the walk before it is examined, so a workspace at or above a
- ceiling is never found. *
- Parameters:
- dir (string) — where to start; a relative path is made absolute first. *
- Returns:
- root (string) — the workspace root, or "" when none was found.
- marker (string) — MarkerDB or MarkerJSONL, or "" when none was found.
- ok (bool) — whether a workspace was found. *
- Example:
- root, marker, ok := FindWorkspace("/home/me/Laboratory/harvey/cmd")
- // root == "/home/me/Laboratory", marker == MarkerDB, ok == true
func FmtHelp ¶
func FmtHelp(src string, appName string, version string, releaseDate string, releaseHash string) string
FmtHelp lets you process a text block with simple curly brace markup.
func IsFrontmatterScalarField ¶ added in v0.0.12
* IsFrontmatterScalarField reports whether name is one of the four scalar
- fields ApplyFrontmatter can accept or set: title, author, dateCreated,
- dateModified. keywords is list-valued and handled through
- FrontmatterAccept.Keywords instead. *
- Parameters:
- name (string) — a frontmatter field name. *
- Returns:
- bool — true for a recognized scalar field. *
- Example:
- knowledge.IsFrontmatterScalarField("title") // true
func IsValidKind ¶
- IsValidKind reports whether kind is one of ValidObservationKinds. *
- Parameters:
- kind (string) — the observation kind to check. *
- Returns:
- bool — true if kind is a recognized observation kind. *
- Example:
- if !knowledge.IsValidKind(kind) {
- kind = "note"
- }
func LevenshteinDistance ¶ added in v0.0.11
* LevenshteinDistance is the classic edit distance between a and b,
- computed over runes (not bytes) since concept names and document prose
- aren't guaranteed ASCII. Two-row iterative DP. Exported so cmd/kb's
- fuzzy clustering (`kb concept suggest`, v0.0.11 item 5) can share this
- exact implementation with FuzzyMatchConceptNames (`kb document
- fuzzy-tag`), rather than a second copy of the same algorithm — design
- decision 1 of fuzzy-concept-clustering-design.md. *
- Parameters:
- a (string) — first string.
- b (string) — second string. *
- Returns:
- int — the edit distance between a and b. *
- Example:
- d := knowledge.LevenshteinDistance("chunking", "chunkings")
- fmt.Println(d) // 1
func NewUUID ¶ added in v0.0.4
* NewUUID returns a fresh UUID v7, the identity every record and row in this
- schema carries so that `merge` can reconcile writes made on different
- machines. *
- Returns:
- string — the UUID in its canonical hyphenated form.
- error — if the system entropy source fails. *
- Example:
- id, err := NewUUID() // "01a03b46-e5e0-7461-a74c-ac096492f96d"
func NormalizeForMerge ¶ added in v0.0.5
* NormalizeForMerge brings a merge scratch copy up to the current schema
- before it is ATTACHed, so that a database predating a table can still be
- merged instead of failing the query that names it. Merge copies its inputs
- with a plain file copy rather than through Open, so nothing has ever
- migrated them; `records` is the first table for which that matters, since a
- database written before decision records existed has no such table and
- SELECT ... FROM b.records against it is an error, not an empty result. *
- The workspace name is derived from originalPath, never from scratchPath.
- A record's workspace is the base name of its database's root (DR-0011), and
- the scratch copy is the one place where the file is deliberately not where
- it came from — deriving from the copy would backfill a temp directory's name
- over every record that predates the workspace column. See DR-0014. *
- Parameters:
- scratchPath (string) — path to the throwaway copy to migrate in place.
- originalPath (string) — path the copy was taken from; supplies the
- workspace name and is not opened or modified. *
- Returns:
- error — if the copy cannot be opened or migrated. *
- Example:
- _ = checkpointAndCopy(aPath, scratchA)
- if err := knowledge.NormalizeForMerge(scratchA, aPath); err != nil {
- return err
- }
func ParseKnowledgeItem ¶ added in v0.0.25
* ParseKnowledgeItem splits one learns or knows item, "Character: fact", at its
- first colon (DR-0083 item 1). The fact may itself contain colons. *
- Parameters:
- item (string) — the item as written, e.g. "Anna: the letter is forged". *
- Returns:
- string — the character, trimmed.
- string — the fact, trimmed, as written.
- bool — false when there is no colon or either side is empty. *
- Example:
- who, fact, ok := knowledge.ParseKnowledgeItem("Anna: the letter is forged")
- // who == "Anna", fact == "the letter is forged", ok
func ReconcileCollisions ¶
func ReconcileCollisions(bPath string, collisions []IdentityCollision) error
* ReconcileCollisions rewrites, in bPath, the uuid of every row named in
- collisions to match its counterpart's uuid (UUIDA) — "a" wins. This must
- be called (and MergeKnowledgeBases must be given the now-rewritten bPath)
- before merging past a CollisionReport hit: without it, MergeKnowledgeBases
- resolves a name collision by keeping whichever row it inserts first and
- silently dropping the other via the uuid/name UNIQUE constraints — which
- also orphans and drops every child row (observations, links) that pointed
- at the dropped row through its uuid. Reconciling first means both sides'
- child rows correctly attach to the single surviving merged parent instead. *
- Parameters:
- bPath (string) — path to the knowledge.db whose colliding rows will be rewritten.
- collisions ([]IdentityCollision) — the result of CollisionReport(aPath, bPath). *
- Returns:
- error — on database failure. *
- Example:
- collisions, _ := CollisionReport(aPath, bPath)
- if len(collisions) > 0 {
- _ = ReconcileCollisions(bPath, collisions)
- }
- summary, _ := MergeKnowledgeBases(aPath, bPath, mergedPath)
func RecordIDPrefix ¶ added in v0.0.32
* RecordIDPrefix is the id prefix of a record kind: "DS" for a design, "PL"
- for a plan, and "" for the decision kinds, whose ids are bare digits stored
- as "0096" and printed "DR-0096" (DR-0096). *
- Parameters:
- kind (string) — the record kind. *
- Returns:
- string — "DS", "PL" or "". *
- Example:
- knowledge.RecordIDPrefix("design") // "DS"
func RecordLabel ¶ added in v0.0.32
* RecordLabel is a record id as kb prints it: "DR-0096" for a decision's
- digits, and the id itself for a design ("DS-0001") or a plan ("PL-0001"),
- whose stored id carries its prefix (DR-0096). *
- Parameters:
- id (string) — the record id as stored. *
- Returns:
- string — the label. *
- Example:
- knowledge.RecordLabel("0096") // "DR-0096"
- knowledge.RecordLabel("DS-0001") // "DS-0001"
func RegisterEmbedder ¶ added in v0.0.29
func RegisterEmbedder(e Embedder)
* RegisterEmbedder makes e the embedder semantic search uses, replacing any
- earlier one. Pass nil to remove it. It is meant to be called once from the
- main of a program that links an implementation. *
- Parameters:
- e (Embedder) — the embedder to use, or nil for none *
- Example:
- knowledge.RegisterEmbedder(myEmbedder)
func RenderRecordFile ¶ added in v0.0.4
func RenderRecordFile(rf *RecordFile) ([]byte, error)
* RenderRecordFile writes a record back out in canonical form: the
- frontmatter in the documented key order with the documented quoting, then
- the body verbatim. *
- Rendering is a fixed point — parsing the output and rendering again produces
- identical bytes — which is what lets ingest and `kb record` share one
- writer without a file's original formatting leaking downstream. *
- Parameters:
- rf (*RecordFile) — the record to render. *
- Returns:
- []byte — the complete file contents.
- error — if the frontmatter cannot be marshalled. *
- Example:
- out, err := RenderRecordFile(rf)
- err = os.WriteFile(rf.Record.Path, out, 0o644)
func StripCodeSpans ¶ added in v0.0.12
* StripCodeSpans removes fenced code blocks and inline code spans from
- text, replacing each with a single space so word boundaries on either side
- survive a removed span. It is the one definition of "code" shared by
- density-linking at ingest and by `kb document tag`'s eligibility check
- (DR-0027, DR-0029), exported so cmd/kb does not carry a second copy. *
- Parameters:
- text (string) — Markdown text. *
- Returns:
- string — text with every code block and code span replaced by a space. *
- Example:
- knowledge.StripCodeSpans("use `rename` twice") // "use twice"
func StripCommonSuffix ¶ added in v0.0.11
* StripCommonSuffix lowercases s and strips exactly one trailing suffix
- from a fixed list (`ing`/`es`/`ed`/`s`, longest match first) --
- deliberately crude, not a real stemmer: a single strip, never iterative,
- and returns s unchanged if none of the fixed suffixes match. Exported
- for the same reason as LevenshteinDistance: shared verbatim between
- `kb document fuzzy-tag` and `kb concept suggest`'s fuzzy clustering. *
- Parameters:
- s (string) — the word to normalize. *
- Returns:
- string — s with its longest matching suffix stripped, or unchanged. *
- Example:
- knowledge.StripCommonSuffix("chunkings") // "chunking"
func TagDocumentText ¶ added in v0.0.12
* TagDocumentText applies insertWikilink for every name in names against
- text, returning the fully-updated text and the subset of names actually
- inserted. Names are applied longest-first (ties broken alphabetically,
- for determinism), so a longer phrase is wrapped as one unit before a
- shorter name it contains gets a chance to fragment it -- e.g. "chunking
- strategy" wraps whole rather than "chunking" wrapping first and leaving
- "strategy" dangling outside the brackets. *
- Parameters:
- text (string) — the document's raw content to tag.
- names ([]string) — candidate concept names to look for. *
- Returns:
- string — text with every safely-found candidate wrapped in [[ ]].
- []string — the names actually inserted, in application order; nil if
- none matched. *
- Example:
- out, inserted := TagDocumentText(body, []string{"chunking", "workspace"})
func Today ¶ added in v0.0.4
func Today() string
* Today returns the current date as YYYY-MM-DD, the form the record format
- requires. It is a string rather than a time.Time because a bare date in YAML
- resolves to a timestamp, and the format quotes it to prevent exactly that. *
- Returns:
- string — today's date, e.g. "2026-08-25". *
- Example:
- date := Today() // "2026-08-25"
func ValidConceptKind ¶ added in v0.0.24
- ValidConceptKind reports whether kind is one of ConceptKinds. *
- Parameters:
- kind (string) — a candidate concept kind. *
- Returns:
- bool — true when kind is in the vocabulary; the empty string is not. *
- Example:
- knowledge.ValidConceptKind("place") // true
func VectorsPath ¶ added in v0.0.29
* VectorsPath returns where the sidecar for a database lives: beside it, named
- for it, so --db and KB_DB move both together. agents/knowledge.db gives
- agents/knowledge.vectors.db. *
- Parameters:
- dbPath (string) — the knowledge database's path *
- Returns:
- string — the sidecar's path *
- Example:
- p := knowledge.VectorsPath("agents/knowledge.db") // agents/knowledge.vectors.db
func WikilinkTarget ¶ added in v0.0.24
* WikilinkTarget returns the concept a wikilink points at, given the text
- between its brackets. A link may carry a display alias after the first
- "|" -- [[the-long-fire/Anna|Anna]] links the concept before the bar and
- displays the text after it (DR-0078). A link with no bar is returned
- trimmed and otherwise unchanged. Callers still pass the result through
- CleanName. *
- Parameters:
- inner (string) — the text between [[ and ]], as captured by the
- wikilink pattern. *
- Returns:
- string — the target concept name, without the alias; empty when the
- link has only an alias. *
- Example:
- knowledge.WikilinkTarget("the-long-fire/Anna|Anna") // "the-long-fire/Anna"
Types ¶
type AmbiguousRefError ¶ added in v0.0.17
* AmbiguousRefError reports a bare record id that more than one tier holds. It
- carries the qualified candidates so a caller can offer them. It matches
- ErrInvalid under errors.Is, since an ambiguous reference is a value that
- cannot be acted on as given. *
- Fields:
- Ref (Ref) — the bare reference that was asked for.
- Candidates ([]Ref) — each tier's qualified reference, project tiers by
- name and the workspace tier as "workspace". *
- Example:
- var amb *knowledge.AmbiguousRefError
- if errors.As(err, &amb) {
- fmt.Println(amb.Candidates) // [clasm/DR-0001 cold/DR-0001 workspace/DR-0001]
- }
func (*AmbiguousRefError) Error ¶ added in v0.0.17
func (e *AmbiguousRefError) Error() string
Error names the candidates in full, so the message is enough to retry with.
func (*AmbiguousRefError) Is ¶ added in v0.0.17
func (e *AmbiguousRefError) Is(target error) bool
Is lets errors.Is(err, ErrInvalid) match.
type Checker ¶ added in v0.0.29
type Checker interface {
Available() error
}
* Checker is an optional interface for an Embedder that can say, without
- loading anything, whether it is able to run: its model files are installed.
- kb asks before it starts embedding so a missing model is one clear error
- (exit 66, pointing to kb model fetch), not a failure part way through a run. *
- Methods:
- Available() error — nil when the embedder can run; otherwise an error that
- wraps fs.ErrNotExist when the model is not installed *
- Example:
- if c, ok := e.(knowledge.Checker); ok {
- if err := c.Available(); err != nil { return err }
- }
type CitedRef ¶ added in v0.0.25
* CitedRef is one entry of a `sources:` front matter list, understood
- (DR-0081 item 4): a bare DOI, an absolute URL, or the id of a source already
- in the knowledge base. *
- Fields:
- Kind (string) — "doi", "url" or "id".
- Value (string) — the DOI or URL as written, or the source id in decimal. *
- Example:
- refs, warnings := knowledge.ParseSourceRefs([]string{"10.1234/sparql", "source:3"})
- // refs[0].Kind == "doi", refs[1] == CitedRef{"id", "3"}
func ParseSourceRefs ¶ added in v0.0.25
* ParseSourceRefs reads the entries of a `sources:` list. Blank entries are
- skipped silently. An entry that is not a bare DOI, an absolute URL or
- `source:ID` (a positive integer) is reported and skipped, the rest are kept:
- it is data read from a file, never a reason to fail an ingest. *
- A pasted `doi:` or doi.org prefix is refused, not rewritten, for the reason
- `kb source add` gives: a mistyped DOI would otherwise be checked for
- retraction, found nowhere, and read as "not retracted". *
- Parameters:
- raw ([]string) — the entries as written. *
- Returns:
- []CitedRef — the entries understood, in order, duplicates removed.
- []string — a message for each entry that was not. *
- Example:
- refs, warnings := knowledge.ParseSourceRefs([]string{"10.1234/x", "doi:10.1/y"})
- // len(refs) == 1; warnings names "doi:10.1/y" and says to write the bare DOI
type Concept ¶
type Concept struct {
ID int64
Name string
Description string
IdentifierType string
IdentifierValue string
// Kind is what the concept names: one of ConceptKinds. "other" is the
// default and the value for every concept that predates kinds (DR-0078).
Kind string
}
* Concept represents a named idea or term that can be linked to projects and
- observations. A concept may also represent a scholarly entity — a paper,
- person, institution, or funder — in which case IdentifierType is one of
- the IdentifierType values (e.g. "doi", "orcid", "ror", "fundref") and
- IdentifierValue is that identifier's normalized (extended) form. Both
- fields are "" for concepts that are plain ideas/terms, not entities. *
- Example:
- concepts, err := kb.Concepts()
- for _, c := range concepts {
- fmt.Println(c.Name, "-", c.Description)
- if c.IdentifierType != "" {
- fmt.Printf(" %s: %s\n", c.IdentifierType, c.IdentifierValue)
- }
- }
type ConceptCandidate ¶ added in v0.0.12
type ConceptCandidate struct {
Term string `json:"term"`
Occurrences int `json:"occurrences"`
Items int `json:"items"`
Score float64 `json:"score"`
Variants []string `json:"variants,omitempty"`
}
* ConceptCandidate is one suggested new concept: a term ranked by corpus-wide
- distinctiveness (TF-IDF shaped), not raw frequency. It is also the entry
- shape of `kb concept suggest --json`, so its tags are a compatibility
- contract. *
- Fields:
- Term (string) — the candidate's canonical spelling: the
- highest-occurrence member of its spelling cluster.
- Occurrences (int) — mentions across the corpus, summed over variants.
- Items (int) — how many distinct items (record bodies, document
- sections) mention it, unioned over variants.
- Score (float64) — Occurrences times the inverse item frequency.
- Variants ([]string) — spelling variants merged into this candidate;
- empty (and omitted from JSON) for a singleton. *
- Example:
- // {Term: "rename", Occurrences: 41, Items: 8, Score: 70.8, Variants: ["renamed", "renaming"]}
type ConceptDetailItem ¶ added in v0.0.15
type ConceptDetailItem struct {
ID int64
Project string
Title string
Body string
CreatedAt time.Time
}
* ConceptDetailItem is one thing linked to a concept, as ConceptDetail lists
- it: enough to recognise the item and judge the link, not the whole row. *
- Fields:
- ID (int64) — internal database id (a document section's id for a section).
- Project (string) — owning project's name; for a project item its own name;
- "" for a workspace-tier record.
- Title (string) — a record's or document's title; "" for an observation or project.
- Body (string) — an observation's text, a project's description, a record's or
- section's text (a section's only when its summary is reviewed).
- CreatedAt (time.Time) — the time the list is ordered by: created, or ingested for a record. *
- Example:
- d, _ := kb.ConceptDetail("toast", 10)
- for _, o := range d.Observations { fmt.Println(o.ID, o.Body) }
type ConceptDetailResult ¶ added in v0.0.15
type ConceptDetailResult struct {
Concept Concept
Usage ConceptUsage
Projects []ConceptDetailItem
Observations []ConceptDetailItem
Records []ConceptDetailItem
DocumentSections []ConceptDetailItem
Spans []ConceptSpan
}
- ConceptDetailResult is everything ConceptDetail knows about one concept. *
- Fields:
- Concept (Concept) — the concept row: description and identifier.
- Usage (ConceptUsage) — the full link counts, whatever the limit.
- Projects ([]ConceptDetailItem) — up to limit projects, newest first.
- Observations ([]ConceptDetailItem) — up to limit observations, newest first.
- Records ([]ConceptDetailItem) — up to limit records, newest first.
- DocumentSections ([]ConceptDetailItem) — up to limit document sections, newest first.
- Spans ([]ConceptSpan) — every project the concept reaches, by name; empty
- when limit is zero. *
- Example:
- d, _ := kb.ConceptDetail("toast", 10)
- fmt.Println(d.Usage.Total(), len(d.Records), len(d.Spans))
type ConceptInUseError ¶ added in v0.0.12
type ConceptInUseError struct {
Usage ConceptUsage
}
* ConceptInUseError is what DeleteConcept returns, without changing anything,
- when the concept still has links and force was not given. Test for it with
- errors.As to report the counts. *
- Fields:
- Usage (ConceptUsage) — the links that would have been removed. *
- Example:
- var inUse *knowledge.ConceptInUseError
- if errors.As(err, &inUse) { fmt.Println(inUse.Usage.Records) }
func (*ConceptInUseError) Error ¶ added in v0.0.12
func (e *ConceptInUseError) Error() string
Error describes the links that block the delete. It says "force" rather than a command-line flag, since this is library code; cmd/kb rewrites it.
type ConceptMatch ¶ added in v0.0.6
type ConceptMatch struct {
SourceType string
ID int64
ProjectID int64
Title string
Body string
SummaryStatus string
MatchCount int
CreatedAt time.Time
// HitProvenance is filled by RecallByText and RecallByNames (DR-0080); the
// older RecallByConceptNames leaves it empty.
HitProvenance
}
* ConceptMatch is one entity (an observation, a record, or a document
- gist/section) linked to one or more concepts a RecallByConceptNames
- caller asked about. *
- Fields:
- SourceType (string) — "observation", "record", "document_gist", or
- "document_section" -- the same vocabulary
- kb_fts.source_type uses.
- ID (int64) — internal database id of the entity (for a
- document match, the document_sections row).
- ProjectID (int64) — owning project id (0 for a workspace-tier record).
- Title (string) — "" for an observation; the record's or
- document's title otherwise.
- Body (string) — the entity's text -- for a document match,
- only when SummaryStatus == "reviewed" (see
- narrative-documents-design.md decision 8):
- an unreviewed summary is findable by tag,
- but never surfaced as trustworthy content.
- SummaryStatus (string) — "" for observation/record matches;
- "unsummarized"/"drafted"/"reviewed" for a
- document match, explaining why Body may be
- empty rather than leaving the caller to guess.
- MatchCount (int) — how many of the queried concepts this entity is linked to.
- CreatedAt (time.Time) — Observation.CreatedAt, Record.IngestedAt, or
- the document section's CreatedAt.
type ConceptSpan ¶ added in v0.0.23
type ConceptSpan struct {
Project string
Tagged bool
Observations int
Records int
DocumentSections int
}
- ConceptSpan is one project a concept reaches, with how it reaches it. *
- Fields:
- Project (string) — the project's name.
- Tagged (bool) — the concept is linked to the project itself.
- Observations (int) — the project's observations that link it.
- Records (int) — the project's records that link it.
- DocumentSections (int) — sections of the project's documents that link it. *
- Example:
- d, _ := kb.ConceptDetail("toast", 10)
- for _, s := range d.Spans { fmt.Println(s.Project, s.Tagged, s.Observations) }
type ConceptSuggestions ¶ added in v0.0.12
type ConceptSuggestions struct {
Candidates []ConceptCandidate `json:"candidates"`
NearExisting []NearExistingMatch `json:"near_existing"`
}
* ConceptSuggestions is what SuggestConcepts returns, and the JSON shape of
- `kb concept suggest --json` (a bare array before v0.0.11). *
- Fields:
- Candidates ([]ConceptCandidate) — suggested new concepts, best first;
- nil when none.
- NearExisting ([]NearExistingMatch) — terms excluded from candidacy because
- they are a close spelling of an
- existing concept (fuzzy-tag's job). *
- Example:
- s, _ := kb.SuggestConcepts("harvey", 20)
- for _, c := range s.Candidates { fmt.Println(c.Term, c.Score) }
type ConceptUsage ¶ added in v0.0.12
type ConceptUsage struct {
Name string
Projects int
Observations int
Records int
DocumentSections int
}
* ConceptUsage counts what links to one concept, so a caller can decide
- whether deleting it would strip real data. A concept is linked from
- projects and observations (which have no ingest step, so nothing recreates
- those links), and from records and document sections (which re-link on their
- next ingest if their files still name the concept). *
- Fields:
- Name (string) — the concept's name.
- Projects (int) — projects it is attached to.
- Observations (int) — observations it is attached to.
- Records (int) — decision records that link to it.
- DocumentSections (int) — document sections that link to it. *
- Example:
- u, _ := kb.ConceptUsage("C++")
- fmt.Println(u.Total())
func (ConceptUsage) Total ¶ added in v0.0.12
func (u ConceptUsage) Total() int
- Total returns how many links the concept has, across every kind. *
- Returns:
- int — the sum of Projects, Observations, Records and DocumentSections. *
- Example:
- if u.Total() == 0 { fmt.Println("unused") }
type ContentDivergence ¶ added in v0.0.5
type ContentDivergence struct {
Table string // always "records" today; only records carry a checksum
Label string // "DR-0007"
ChecksumA string
ChecksumB string
}
* ContentDivergence is one record the two databases agree is the same record
- — same workspace, project, scope and id — but whose text differs, detected
- by comparing the checksums ingest stores over the file's bytes. *
- This is reported apart from an IdentityCollision and does not stop a merge.
- A decision record's text is its artifact in a way a project's description is
- not, so the operator needs to know which record's prose was dropped in order
- to reconcile the two Markdown files; but the merge's conflict rule is
- unchanged, and the row already present still wins. See DR-0013. *
- Example:
- divergences, _ := DivergenceReport("a.db", "b.db")
- for _, d := range divergences {
- fmt.Printf("%s differs: %s vs %s\n", d.Label, d.ChecksumA, d.ChecksumB)
- }
func DivergenceReport ¶ added in v0.0.5
func DivergenceReport(aPath, bPath string) ([]ContentDivergence, error)
* DivergenceReport opens aPath and bPath read-only and reports every record
- the two agree on the identity of but disagree on the content of. Identity is
- matched exactly as CollisionReport matches it, so the two reports describe
- the same pairs of rows from different angles: a divergence may or may not
- also be a collision, and either can occur alone. *
- Parameters:
- aPath (string) — path to the first knowledge.db.
- bPath (string) — path to the second knowledge.db. *
- Returns:
- []ContentDivergence — one entry per diverging record; empty if none.
- error — on database failure. *
- Example:
- divergences, err := DivergenceReport("/machine-a/knowledge.db", "/machine-b/knowledge.db")
type CorpusRow ¶ added in v0.0.29
- CorpusRow is one row of the knowledge base as semantic search sees it. *
- Fields:
- SourceType (string) — kb_fts source_type: observation, record, concept document or document_summary
- SourceID (int64) — the row's id in its own table
- Text (string) — the text lexical search indexes for the row, which is the text embedded *
- Example:
- rows, _ := kb.EmbedCorpus(knowledge.SearchScope{})
- fmt.Println(rows[0].SourceType, rows[0].SourceID)
type DBComparison ¶ added in v0.0.15
type DBComparison struct {
Tables []TableDiff
Collisions []IdentityCollision
}
* DBComparison is the result of comparing a live database with a JSONL dump.
- In every TableDiff the first side ("A") is the database and the second
- ("B") is the dump: OnlyA is "in this database, not in the JSONL", OnlyB is
- "in the JSONL, not in this database". *
- Fields:
- Tables ([]TableDiff) — per-table result, clean tables included.
- Collisions ([]IdentityCollision) — entities held under different uuids on the two sides. *
- Example:
- c, _ := kb.CompareToJSONL(f)
- fmt.Println(c.Recommendation())
func (DBComparison) InSync ¶ added in v0.0.15
func (c DBComparison) InSync() bool
InSync reports whether the database and the dump hold the same content.
func (DBComparison) Recommendation ¶ added in v0.0.15
func (c DBComparison) Recommendation() string
* Recommendation names the action that would bring the two together:
- "in-sync" when nothing differs; "import" when the dump only adds rows to
- the database; "export" when the database only adds rows to the dump;
- "diverged" when both have rows the other lacks, or any row on both sides
- differs, or an entity carries two uuids (import, then export). *
- Because there are no tombstones, rows only in the dump may be rows deleted
- here on purpose, and an "import" recommendation brings them back. *
- Returns:
- string — one of "in-sync", "import", "export", "diverged". *
- Example:
- switch c.Recommendation() { case "import": ... }
type Document ¶ added in v0.0.6
type Document struct {
ID int64
ProjectID int64
Title string
Format string
Path string
Author string
PublishedDate string
Description string // the front-matter description, verbatim; "" when the file has none
Checksum string
IngestedAt time.Time
UUID string
OriginHost string
}
* Document is a narrative or article ingested at the graduated-abstraction
- levels described in narrative-documents-design.md: a documents row plus a
- DocumentSection per gist/section.
type DocumentIngestOptions ¶ added in v0.0.12
- DocumentIngestOptions tunes one IngestDocument call. *
- Fields:
- Title (string) — overrides the title parsed from frontmatter, a
- Fountain title page, or a first H1. Empty accepts
- the parsed title, falling back to the file's base name.
- Format (string) — overrides extension-based format detection
- ("markdown", "fountain", "text"). Empty detects.
- DryRun (bool) — report what would happen and write nothing. *
- Example:
- opts := knowledge.DocumentIngestOptions{Title: "Field Notes", DryRun: true}
type DocumentIngestResult ¶ added in v0.0.12
type DocumentIngestResult struct {
Path string `json:"path"`
DryRun bool `json:"dry_run"`
Action string `json:"action"`
SectionsAdded int `json:"sections_added"`
SectionsUpdated int `json:"sections_updated"`
SectionsStale int `json:"sections_stale"`
RemovedHeadings []string `json:"removed_headings,omitempty"`
Warning string `json:"warning,omitempty"`
// EventsWritten is how many story events the file yields (DR-0079), and
// StoryWarnings what was not understood in its story metadata.
EventsWritten int `json:"events_written,omitempty"`
StoryWarnings []string `json:"story_warnings,omitempty"`
// SourcesLinked is how many sources the file's `sources:` key cites, and
// SourceWarnings the entries that were not understood or not found
// (DR-0081 item 4).
SourcesLinked int `json:"sources_linked,omitempty"`
SourceWarnings []string `json:"source_warnings,omitempty"`
// TagWarnings the wikilinks and keywords CleanName refused (a control
// character): they are not tags, and the document is ingested without them.
TagWarnings []string `json:"tag_warnings,omitempty"`
}
* DocumentIngestResult is what IngestDocument reports, and is also the
- JSON shape `kb document ingest --json` prints, so its tags are a
- compatibility contract. RemovedHeadings lists old sections whose heading
- no longer matches anything in the re-ingested content: reported, never
- deleted (narrative-documents-design.md decision 10). *
- Fields:
- Path (string) — the path as it was passed to IngestDocument.
- DryRun (bool) — true when nothing was written.
- Action (string) — "added", "updated", or "skipped" (checksum unchanged).
- SectionsAdded (int) — sections newly inserted (all of them, for "added").
- SectionsUpdated (int) — matched sections whose body changed.
- SectionsStale (int) — updated sections whose existing summary is now flagged stale.
- RemovedHeadings ([]string) — old headings with no match in the new content.
- Warning (string) — a non-fatal parser warning, or empty. *
- Example:
- res, _ := kb.IngestDocument(pid, "notes.md", knowledge.DocumentIngestOptions{})
- fmt.Println(res.Action, res.SectionsAdded)
type DocumentReviewItem ¶ added in v0.0.6
type DocumentReviewItem struct {
DocumentSection
DocumentTitle string
}
* DocumentReviewItem is one row of the review queue (kb document review
- list): a document_sections row plus the document context needed to
- display it.
type DocumentSection ¶ added in v0.0.6
type DocumentSection struct {
ID int64
DocumentID int64
Level string
Seq int
Heading string
Body string
SummaryBody string
SummaryStatus string
SummaryStale bool
SourceSize int
TagDensity int
Confidence *float64
GeneratedBy string
CreatedAt time.Time
UUID string
OriginHost string
// SceneID, Story and StoryWarnings are read from the manuscript at parse
// time and are not stored: story_events is derived from them at ingest
// (DR-0075). SceneID is the scene number written in a Fountain heading,
// "" when there is none; Story is that scene's story metadata.
SceneID string
Story StoryMeta
StoryWarnings []string
}
* DocumentSection is one row of a document's decomposition: either the
- document-level gist (Level == "gist", Body always empty) or one
- structural unit (Level == "section", Body populated at ingest). Summary*
- and Confidence describe the deferred, reviewable layer described in
- narrative-documents-design.md decision 7; SummaryStale is set when Body
- changes under an existing summary on re-ingest (decision 10).
type DocumentUsage ¶ added in v0.0.14
type DocumentUsage struct {
ID int64
Path string
Sections int
ReviewedSections int
ConceptLinks int
}
- DocumentUsage counts what a document holds. *
- Fields:
- ID (int64) — the document's id.
- Path (string) — the path it was ingested from.
- Sections (int) — sections, the gist row included.
- ReviewedSections (int) — sections whose summary a human has reviewed.
- ConceptLinks (int) — section-to-concept links. *
- Example:
- u, _ := kb.DocumentUsage(1)
- fmt.Println(u.ReviewedSections)
type EmbedOptions ¶ added in v0.0.29
type EmbedOptions struct {
BatchSize int
ChunkRunes int
Progress func(EmbedProgress)
}
- EmbedOptions tunes EmbedIndex. *
- Fields:
- BatchSize (int) — texts per Embed call; zero means 16
- ChunkRunes (int) — the longest chunk, in characters; zero means DefaultChunkRunes
- Progress (func(EmbedProgress)) — called after each committed batch; may be nil *
- Example:
- opts := knowledge.EmbedOptions{BatchSize: 8, Progress: func(p knowledge.EmbedProgress) {
- fmt.Printf("%d of %d rows\n", p.Done, p.Total)
- }}
type EmbedProgress ¶ added in v0.0.29
type EmbedProgress struct {
Done, Total, ChunksEmbedded int
}
- EmbedProgress is reported after each batch EmbedIndex commits. *
- Fields:
- Done (int) — rows embedded so far in this run
- Total (int) — rows this run has to embed
- ChunksEmbedded (int) — chunks sent to the embedder so far in this run
type EmbedResult ¶ added in v0.0.29
type EmbedResult struct {
RowsEmbedded, RowsSkipped, RowsRemoved, ChunksEmbedded int
}
- EmbedResult says what EmbedIndex did, also when it stopped early. *
- Fields:
- RowsEmbedded (int) — rows whose chunks were written
- RowsSkipped (int) — rows already up to date
- RowsRemoved (int) — rows whose chunks were dropped because the row is gone or has no text
- ChunksEmbedded (int) — chunks sent to the embedder; a chunk whose text did not change is not
type EmbedStatus ¶ added in v0.0.29
type EmbedStatus struct {
Rows, RowsUpToDate, RowsToEmbed, RowsToRemove, ChunksStored, ChunksToEmbed int
RowsByType map[string]int
}
- EmbedStatus says how far the vector sidecar is from the corpus. *
- Fields:
- Rows (int) — rows in the corpus
- RowsByType (map[string]int) — corpus rows by kb_fts source_type
- RowsUpToDate (int) — rows whose chunks are all stored
- RowsToEmbed (int) — rows new or changed since they were embedded
- RowsToRemove (int) — indexed rows that are gone or have no text
- ChunksStored (int) — chunks in the sidecar
- ChunksToEmbed (int) — chunks a run would send to the embedder
type Embedder ¶ added in v0.0.29
type Embedder interface {
Model() string
Dimensions() int
Fingerprint() string
Embed(texts []string) ([][]float32, error)
}
* Embedder turns text into vectors. An implementation is registered with
- RegisterEmbedder by the program that links it; the plain kb registers none. *
- Methods:
- Model() string — the model's name, recorded beside the vectors it made
- Dimensions() int — the length of each vector Embed returns
- Fingerprint() string — identifies the exact model files, so vectors made
- by a different build of the same name are not mixed
- Embed(texts []string) ([][]float32, error) — one vector per text, in
- order; an error means no vector in the batch can be trusted *
- Example:
- type fake struct{}
- func (fake) Model() string { return "fake" }
- func (fake) Dimensions() int { return 2 }
- func (fake) Fingerprint() string { return "v1" }
- func (fake) Embed(t []string) ([][]float32, error) {
- out := make([][]float32, len(t))
- for i := range t { out[i] = []float32{1, 0} }
- return out, nil
- }
- knowledge.RegisterEmbedder(fake{})
func RegisteredEmbedder ¶ added in v0.0.29
- RegisteredEmbedder returns the embedder registered with RegisterEmbedder. *
- Returns:
- Embedder — the registered embedder, or nil
- bool — true when one is registered *
- Example:
- if e, ok := knowledge.RegisteredEmbedder(); ok {
- fmt.Println(e.Model())
- }
type FrontmatterAccept ¶ added in v0.0.12
- FrontmatterAccept says what ApplyFrontmatter should write. *
- Fields:
- Fields ([]string) — scalar fields whose proposal to accept
- (see IsFrontmatterScalarField). title, author
- and dateCreated are absent-only; dateModified
- is always refreshed.
- Keywords ([]string) — keyword names to add. Each must be a known
- concept or one of the report's proposed new
- candidates; a new candidate's concept is
- created (except on a dry run).
- Set (map[string]string) — explicit values that bypass signal detection
- and the absent-only rule, including an
- explicit empty value. *
- Example:
- acc := knowledge.FrontmatterAccept{Fields: []string{"title"}, Set: map[string]string{"author": "Jane"}}
type FrontmatterFieldReport ¶ added in v0.0.12
type FrontmatterFieldReport struct {
Field string `json:"field"`
Current string `json:"current,omitempty"`
Proposed string `json:"proposed,omitempty"`
Signals []FrontmatterSignal `json:"signals,omitempty"`
Accepted bool `json:"accepted"`
}
* FrontmatterFieldReport is one scalar field's outcome in a
- FrontmatterResult, and the per-field JSON shape of `kb document
- frontmatter --json`, so its tags are a compatibility contract. *
- Fields:
- Field (string) — title, author, dateCreated or dateModified.
- Current (string) — the existing value; for an absent-only
- field, its presence means nothing is proposed.
- Proposed (string) — the proposed value, or the value that was
- just set by an explicit Set.
- Signals ([]FrontmatterSignal) — author only: every signal that fired.
- Accepted (bool) — whether this call selected the field. *
- Example:
- // {Field: "title", Proposed: "A Real Title", Accepted: true}
type FrontmatterKeywordReport ¶ added in v0.0.12
type FrontmatterKeywordReport struct {
Current []string `json:"current"`
Known []string `json:"known_proposals"`
New []ConceptCandidate `json:"new_candidate_proposals"`
Accepted []string `json:"accepted"`
}
- FrontmatterKeywordReport is the keywords outcome in a FrontmatterResult. *
- Fields:
- Current ([]string) — the keywords already in the file.
- Known ([]string) — known concepts mentioned in the text and not
- yet listed; order is not specified.
- New ([]ConceptCandidate) — terms distinctive to this document, scored
- against the rest of its project or corpus.
- Accepted ([]string) — the names this call accepted. *
- Example:
- // {Current: [], Known: ["chunking"], New: [{Term: "gronkulator", ...}], Accepted: []}
type FrontmatterResult ¶ added in v0.0.12
type FrontmatterResult struct {
Path string `json:"path"`
DryRun bool `json:"dry_run"`
Fields []FrontmatterFieldReport `json:"fields"`
Keywords FrontmatterKeywordReport `json:"keywords"`
Written bool `json:"written"`
}
* FrontmatterResult is one file's whole report, and the JSON shape of `kb
- document frontmatter --json`. *
- Fields:
- Path (string) — the path as passed in.
- DryRun (bool) — true when the call was a preview.
- Fields ([]FrontmatterFieldReport) — title, author, dateCreated, dateModified.
- Keywords (FrontmatterKeywordReport) — the keyword proposals and acceptances.
- Written (bool) — true when ApplyFrontmatter's returned
- bytes differ from its input and are
- meant to be written (never on a dry run). *
- Example:
- res, _ := kb.ProposeFrontmatter("a.md", raw, nil)
type FrontmatterSignal ¶ added in v0.0.12
* FrontmatterSignal is one candidate value with its provenance label, for
- the author field's multi-signal report (design decision 4: show every
- signal when they disagree, not just the winner). It has no JSON tags, so
- its keys are Source and Value, as `kb document frontmatter --json` has
- always printed them. *
- Fields:
- Source (string) — where the value came from: byline, git, or git config.
- Value (string) — the candidate author. *
- Example:
- // {Source: "byline", Value: "Jane Doe"}
type FusedRow ¶ added in v0.0.29
type FusedRow struct {
SourceType string
SourceID int64
Score float64
LexicalRank int
SemanticRank int
}
- FusedRow is one row of a hybrid search with where each ranking put it. *
- Fields:
- SourceType (string) — kb_fts source_type of the row
- SourceID (int64) — the row's id
- Score (float64) — the sum of 1/(k + rank) over the rankings that found the row
- LexicalRank (int) — its place in the lexical ranking from 1, or 0 if that ranking did not find it
- SemanticRank (int) — its place in the semantic ranking from 1, or 0 if that ranking did not find it *
- Example:
- for _, r := range knowledge.FuseRankings(lexical, semantic, 0) {
- fmt.Println(r.SourceType, r.SourceID, r.InBoth())
- }
func FuseRankings ¶ added in v0.0.29
* FuseRankings merges the lexical and the semantic ranking of one query into
- one, by reciprocal-rank fusion: a row's score is the sum of 1/(k + rank) over
- the rankings that found it. A row found by both rankings comes before any row
- found by one (the design, semantic-search-design.md section 4: plain fusion
- would let a first place in one ranking outscore a fiftieth place in both);
- within each group the higher score comes first, and a tie goes to the better
- lexical rank, then the better semantic rank, then type and id, so the order is
- the same every time. A row listed twice counts once, at its best place. *
- Parameters:
- lexical ([]RowKey) — the rows lexical search found, best first
- semantic ([]RowKey) — the rows semantic search found, best first
- k (int) — the fusion constant; zero or less means DefaultFusionK *
- Returns:
- []FusedRow — every row either ranking found, best first *
- Example:
- fused := knowledge.FuseRankings(lexicalKeys, semanticKeys, knowledge.DefaultFusionK)
type FuzzyConceptMatch ¶ added in v0.0.11
* FuzzyConceptMatch is one spelling-level near-miss FuzzyMatchConceptNames
- found in a piece of text: a typo, plural, or simple tense variant of a
- known concept's name, not an exact match (MatchConceptNames already finds
- those). *
- Fields:
- Concept (string) — canonical concept name, Concepts()'s own casing.
- Text (string) — the actual text found, original casing preserved.
- Start (int) — byte offset into the input text where Text begins.
- End (int) — byte offset where Text ends (half-open range).
- Distance (int) — Levenshtein distance recorded for this match (raw,
- or the stemmed fallback distance when raw
- overshot the candidate-generation ceiling). *
- Example:
- matches, _ := kb.FuzzyMatchConceptNames("the chunkings here")
- fmt.Println(matches[0].Concept, matches[0].Distance) // "chunking" 1
func FuzzyEligible ¶ added in v0.0.12
func FuzzyEligible(matches []FuzzyConceptMatch, explicit []string, text string) []FuzzyConceptMatch
* FuzzyEligible applies design decision 5's real threshold to matches
- already produced by FuzzyMatchConceptNames: with no explicit concepts
- given, keep a match only if its concept is at least
- minFuzzyConceptLength letters long, its Distance is within fuzzyThreshold
- for the concept's length, and a distance-2 match shares at least
- minFuzzyDistanceTwoPrefix leading letters with its concept (DR-0036); with
- explicit concepts given, keep only matches whose
- Concept is named there (any distance up to FuzzyMatchConceptNames's own
- ceiling qualifies -- the --concept bypass, decision 2), dropping every
- other concept's matches entirely. Either way, drop any match whose
- [Start, End) overlaps a frontmatter block, first H1, code span, existing
- wikilink, or footnote-definition line in text. *
- Takes text (not just matches) because the exclusion spans are computed
- from the raw text. *
- Parameters:
- matches ([]FuzzyConceptMatch) — from FuzzyMatchConceptNames(text).
- explicit ([]string) — concept names to force, or nil for the
- length-based threshold.
- text (string) — the same text the matches came from. *
- Returns:
- []FuzzyConceptMatch — the matches that survive, in their original order. *
- Example:
- ms, _ := kb.FuzzyMatchConceptNames(text)
- eligible := knowledge.FuzzyEligible(ms, nil, text)
type FuzzyTagInsertion ¶ added in v0.0.12
type FuzzyTagInsertion struct {
Section string `json:"section"`
Text string `json:"text"`
Concept string `json:"concept"`
Distance int `json:"distance"`
Footnote int `json:"footnote"`
}
* FuzzyTagInsertion is one footnote inserted by FuzzyTagDocumentText, and is
- also the per-entry JSON shape `kb document fuzzy-tag --json` prints, so its
- tags are a compatibility contract. *
- Fields:
- Section (string) — heading text of the section the near-miss sits in,
- or "" for lead text before any heading.
- Text (string) — the near-miss as written in the document.
- Concept (string) — the canonical concept the footnote links to.
- Distance (int) — the Levenshtein distance that qualified the match.
- Footnote (int) — the footnote label number assigned. *
- Example:
- // {Section: "Background", Text: "chunkings", Concept: "chunking", Distance: 1, Footnote: 1}
func FuzzyTagDocumentText ¶ added in v0.0.12
func FuzzyTagDocumentText(text string, matches []FuzzyConceptMatch) (string, []FuzzyTagInsertion)
* FuzzyTagDocumentText inserts a footnote marker after each near-miss in
- matches, and a footnote definition carrying the canonical [Concept]
- before the next section heading (or at end of file). It never bracket-wraps
- the near-miss itself: doing so would let ResolveConceptName mint a
- duplicate concept from the misspelled or inflected spelling. It is text in,
- text out: no file or database access, and the caller owns the write. *
- matches must be the eligible matches (see FuzzyEligible) computed against
- this same text: their Start/End offsets index into the original text. A
- match whose concept is already wikilinked anywhere in the text is skipped,
- so the function is idempotent on its own output. *
- Parameters:
- text (string) — the document's raw content.
- matches ([]FuzzyConceptMatch) — eligible matches for that text. *
- Returns:
- string — the text with footnotes inserted.
- []FuzzyTagInsertion — one entry per footnote inserted, in match order;
- nil when nothing was inserted. *
- Example:
- ms, _ := kb.FuzzyMatchConceptNames(text)
- out, ins := knowledge.FuzzyTagDocumentText(text, knowledge.FuzzyEligible(ms, nil, text))
type GitProvenance ¶ added in v0.0.12
type GitProvenance struct{}
* GitProvenance is the default Provenance: it runs the git command line
- from the file's own directory, and reports "no history" (ok=false) for any
- git failure, whether that is not a repository, no commits yet, or git not
- being installed. FileTime is the file's modification time; a true birth time is
- not exposed portably by the standard library. *
- Example:
- author, date, ok := knowledge.GitProvenance{}.FirstCommit("notes/a.md")
func (GitProvenance) ConfigUserName ¶ added in v0.0.12
func (GitProvenance) ConfigUserName(dir string) (string, bool)
* ConfigUserName implements Provenance using `git config user.name` run in
- dir, so a repository-local override is honored. *
- Parameters:
- dir (string) — the directory whose git configuration to query. *
- Returns:
- string — the configured name.
- bool — false when none is set. *
- Example:
- name, ok := knowledge.GitProvenance{}.ConfigUserName(".")
func (GitProvenance) FileTime ¶ added in v0.0.12
func (GitProvenance) FileTime(path string) (time.Time, error)
- FileTime implements Provenance with the file's modification time. *
- Parameters:
- path (string) — the file to stat. *
- Returns:
- time.Time — the modification time.
- error — when the file cannot be stat'ed. *
- Example:
- t, err := knowledge.GitProvenance{}.FileTime("a.md")
func (GitProvenance) FirstCommit ¶ added in v0.0.12
func (GitProvenance) FirstCommit(path string) (string, string, bool)
- FirstCommit implements Provenance using `git log --follow --reverse`. *
- Parameters:
- path (string) — the file to look up. *
- Returns:
- string — the oldest commit's author name.
- string — that commit's author date, RFC 3339.
- bool — false when git reports no history for path. *
- Example:
- author, date, ok := knowledge.GitProvenance{}.FirstCommit("a.md")
func (GitProvenance) LastCommit ¶ added in v0.0.12
func (GitProvenance) LastCommit(path string) (string, bool)
- LastCommit implements Provenance using `git log -1`. *
- Parameters:
- path (string) — the file to look up. *
- Returns:
- string — the newest commit's author date, RFC 3339.
- bool — false when git reports no history for path. *
- Example:
- date, ok := knowledge.GitProvenance{}.LastCommit("a.md")
type HitProvenance ¶ added in v0.0.25
type HitProvenance struct {
Sources []SourceRef
Material *MaterialRef
Retracted bool
}
* HitProvenance is what supports a hit (DR-0080): the works its row cites, the
- file its row came from, and a flag that any cited work is retracted.
- KBSearchResult and the recall hit embed it. *
- Fields:
- Sources ([]SourceRef) — the cited works; empty, never nil, when none.
- Material (*MaterialRef) — the file, for a document or record; nil for
- every other kind.
- Retracted (bool) — true when any entry of Sources is retracted. *
- Example:
- if hit.Retracted { fmt.Println("rests on a retracted source") }
type IdentityCollision ¶ added in v0.0.5
type IdentityCollision struct {
Table string // "projects", "concepts" or "records"
Label string // the colliding name, or "DR-0007" for a record
UUIDA string
UUIDB string
}
* IdentityCollision is one entity that exists independently in both source
- databases under two different uuids — almost certainly the same real-world
- thing, created on two machines before either knew about the other, and now
- indistinguishable except by what identifies it. *
- What identifies it differs by table. For projects and concepts it is the
- name, which a UNIQUE constraint already enforces. For records it is the
- identity DR-0011 defines: workspace, project, scope and record id. *
- Example:
- collisions, _ := CollisionReport("a.db", "b.db")
- for _, c := range collisions {
- fmt.Printf("%s %q: %s vs %s\n", c.Table, c.Label, c.UUIDA, c.UUIDB)
- }
func CollisionReport ¶
func CollisionReport(aPath, bPath string) ([]IdentityCollision, error)
* CollisionReport opens aPath and bPath read-only and reports every entity
- that exists in both under different uuids. Callers should review (and
- resolve, via ReconcileCollisions) any collisions before calling
- MergeKnowledgeBases — an unresolved collision is settled "first insert wins"
- by MergeKnowledgeBases's INSERT OR IGNORE, which drops the losing row and
- orphans every child row that pointed at it. *
- Both databases must already carry the current schema; see NormalizeForMerge. *
- Parameters:
- aPath (string) — path to the first knowledge.db.
- bPath (string) — path to the second knowledge.db. *
- Returns:
- []IdentityCollision — one entry per colliding entity; empty if none found.
- error — on database failure. *
- Example:
- collisions, err := CollisionReport("/machine-a/knowledge.db", "/machine-b/knowledge.db")
type ImportTableSummary ¶ added in v0.0.3
type ImportTableSummary struct {
Table string
Read int
Imported int
Skipped int
Warnings []string `json:",omitempty"`
}
* ImportTableSummary reports, per JSON-L record type, how many lines were
- read, how many resulted in a new row, and how many were skipped —
- because a matching row already existed locally, or (for join records)
- because one of the referenced uuids couldn't be resolved.
func ImportJSONL ¶ added in v0.0.3
func ImportJSONL(kb *KnowledgeBase, r io.Reader) ([]ImportTableSummary, error)
* ImportJSONL reads a stream written by ExportJSONL (or hand-built in the
- same format) and applies it to kb, an already-open, live knowledge base.
- The whole stream is buffered and grouped by record type before anything
- is written, then applied in dependency order (projects/concepts/sources,
- then observations, then the three join types) regardless of the order
- lines appeared in r — see jsonl-export-design.md for the full identity
- and conflict-resolution rules (name-keyed for projects/concepts,
- identifier-keyed for sources, uuid-keyed for observations and joins).
- Unresolvable references and unrecognized "type" values are skipped, not
- fatal; only malformed JSON aborts the import. *
- Parameters:
- kb (*KnowledgeBase) — the live knowledge base to import into.
- r (io.Reader) — a JSON-L stream, as produced by ExportJSONL. *
- Returns:
- []ImportTableSummary — one entry per record type seen (including any
- unrecognized type, reported with Imported=0).
- error — on malformed JSON (with the offending line
- number) or database failure. *
- Example:
- f, _ := os.Open("export.jsonl")
- defer f.Close()
- summary, err := ImportJSONL(kb, f)
type InUseError ¶ added in v0.0.14
type InUseError struct {
Entity string
Name string
Counts []UsageCount
}
* InUseError is what a delete returns, without changing anything, when the target
- still has something depending on it and the delete was not forced (or, for a
- project that owns content, whatever force says). It matches ErrInUse under
- errors.Is, so a caller that only needs "refused" tests that, and errors.As reaches
- the counts. ConceptInUseError is the older, concept-only form. *
- Fields:
- Entity (string) — "project", "observation", "document" or "record".
- Name (string) — the target's name or id, as a caller gave it.
- Counts ([]UsageCount) — what depends on it; only entries with N > 0 are shown. *
- Example:
- var inUse *knowledge.InUseError
- if errors.As(err, &inUse) { fmt.Println(inUse.Counts) }
func (*InUseError) Error ¶ added in v0.0.14
func (e *InUseError) Error() string
func (*InUseError) Is ¶ added in v0.0.14
func (e *InUseError) Is(target error) bool
type KBSearchResult ¶
type KBSearchResult struct {
Kind string
Label string
Snippet string
SourceType string
SourceID int64 // the row's id in its own table, as the index stores it; 0 when unknown
ProjectID int64 // the owning project's id; 0 for a concept or a workspace-tier record
Ref string // a record's qualified reference ("harvey/DR-0004", "workspace/DR-0003"); "" for other kinds
Status string // a record's status; "" for other kinds
Passage string // the part of an observation, record or document summary that matched, the matched words between « and »; "" when only the label matched
Section string // for a record, the bold label ("Decision") of the part that matched, or "title"; "" otherwise
// HitProvenance is what supports the hit: the works its row cites, the file
// it came from and whether any cited work is retracted (DR-0080).
HitProvenance
}
- KBSearchResult holds one row returned by Search. *
- Fields:
- Kind (string) — observation kind ("note", "finding", etc.), a record's
- own kind ("decision", "correction"), or "project" / "concept".
- Label (string) — project name for observations; "DR-NNNN" for records;
- entity name for projects and concepts.
- Snippet (string) — observation body; title for records; description for
- projects and concepts.
- SourceType (string) — which table the hit came from: "observation",
- "project", "concept", "record" or "document_summary".
- Kind alone cannot say, since a record's kind is its
- own vocabulary.
- SourceID (int64) — the row's id in its own table; 0 when unknown.
- ProjectID (int64) — the owning project's id; 0 for a concept or a workspace-tier record.
- Ref (string) — a record's qualified reference, "harvey/DR-0004" or
- "workspace/DR-0003"; "" for every other kind.
- Status (string) — a record's status; "" for every other kind.
- Passage (string) — the passage that matched, with the matched words
- between « and »; "" for a concept or project, or when
- only the label matched.
- Section (string) — for a record, the bold label of the part the match is
- in ("Decision"), or "title" when the title matched
- and the body did not; "" otherwise. *
- Example:
- results, _ := kb.Search("WAL mode")
- for _, r := range results {
- fmt.Printf("[%s] %s — %s\n", r.Kind, r.Label, r.Snippet)
- }
type KnowledgeBase ¶
type KnowledgeBase struct {
// contains filtered or unexported fields
}
* KnowledgeBase is a SQLite3-backed store for projects, observations, and
- concepts. The database file is created automatically on first use at
- whatever path Open is given. *
- Example:
- kb, err := Open(DefaultPath(root))
- if err != nil {
- log.Fatal(err)
- }
- defer kb.Close()
func Open ¶
func Open(dbPath string) (*KnowledgeBase, error)
* Open opens (or creates) the SQLite knowledge base at dbPath. The schema
- is applied on every open so that tables are created on first use without
- manual migration. *
- Parameters:
- dbPath (string) — full path to the knowledge.db file. *
- Returns:
- *KnowledgeBase — ready-to-use knowledge base handle.
- error — if the database file cannot be opened or the schema
- cannot be applied. *
- Example:
- kb, err := Open(DefaultPath("/home/user/myproject"))
- if err != nil {
- log.Fatal(err)
- }
- defer kb.Close()
func (*KnowledgeBase) AddConcept ¶
func (kb *KnowledgeBase) AddConcept(name, description string) (int64, error)
* AddConcept inserts a new concept or, if a concept with the same name exists,
- updates it and returns its existing ID. It is equivalent to calling
- AddConceptWithIdentifier with identifierType = identifierValue = "", which
- leaves any identifier already recorded for an existing concept untouched. *
- Since names are unique, this doubles as the correction path for a concept's
- description — there is no SetConceptDescription, unlike SetProjectDescription
- on projects. An empty description preserves the stored one; see
- AddConceptWithIdentifier. *
- Parameters:
- name (string) — unique concept name.
- description (string) — human-readable explanation of the concept; "" preserves
- the stored description on an existing concept. *
- Returns:
- int64 — ID of the inserted or existing concept.
- error — if name is blank, or on database failure. *
- Example:
- id, err := kb.AddConcept("WAL mode", "SQLite write-ahead logging for concurrency")
func (*KnowledgeBase) AddConceptWithIdentifier ¶
func (kb *KnowledgeBase) AddConceptWithIdentifier(name, description, identifierType, identifierValue string) (int64, error)
* AddConceptWithIdentifier inserts a new concept, or updates an existing
- concept with the same name, optionally recording a scholarly identifier
- (e.g. a paper's DOI, a person's ORCID, an institution's ROR) that the
- concept represents. *
- On an update, an empty description, identifierType or identifierValue
- preserves the stored value rather than clearing it. That matters most for
- the description: calling this with a name alone is a legitimate way to
- assert a concept exists, and clearing its description on the way would be
- silent data loss. Pass a non-empty description to correct one. *
- Parameters:
- name (string) — unique concept name.
- description (string) — human-readable explanation of the concept, or "" to
- preserve the stored one.
- identifierType (string) — one of the IdentifierType values (e.g. "doi", "orcid"), or "".
- identifierValue (string) — normalized (extended) identifier value, or "". *
- Returns:
- int64 — ID of the inserted or existing concept.
- error — if name is blank, or on database failure. *
- Example:
- id, err := kb.AddConceptWithIdentifier("Jane Doe", "paper author",
- string(IdentifierORCID), "0000-0003-0900-6903")
func (*KnowledgeBase) AddDocument ¶ added in v0.0.6
func (kb *KnowledgeBase) AddDocument(d Document) (int64, error)
- AddDocument inserts a new document row. *
- Parameters:
- d (Document) — fields to store; ID/UUID/OriginHost/IngestedAt are set
- by this call and any given value is ignored. *
- Returns:
- int64 — ID of the new document.
- error — on database failure. *
- Example:
- id, err := kb.AddDocument(Document{ProjectID: pid, Title: "A Story",
- Format: "markdown", Path: "stories/a-story.md"})
func (*KnowledgeBase) AddDocumentSection ¶ added in v0.0.6
func (kb *KnowledgeBase) AddDocumentSection(s DocumentSection) (int64, error)
- AddDocumentSection inserts a new document_sections row. *
- Parameters:
- s (DocumentSection) — fields to store; ID/UUID/OriginHost/CreatedAt are
- set by this call and any given value is ignored. *
- Returns:
- int64 — ID of the new section.
- error — on database failure. *
- Example:
- id, err := kb.AddDocumentSection(DocumentSection{DocumentID: docID,
- Level: "section", Seq: 0, Heading: "Chapter One", Body: "..."})
func (*KnowledgeBase) AddObservation ¶
func (kb *KnowledgeBase) AddObservation(projectID int64, kind, body string) (int64, error)
* AddObservation inserts a new observation for a project and returns its ID.
- It is equivalent to calling AddObservationWithSource with sourceDOI = "". *
- Parameters:
- projectID (int64) — ID of the owning project.
- kind (string) — one of: note, finding, decision, question, hypothesis.
- body (string) — the observation text. *
- Returns:
- int64 — ID of the new observation.
- error — if kind is invalid, body is blank, or the insert fails. *
- Example:
- id, err := kb.AddObservation(1, "finding", "WAL mode doubles write throughput")
func (*KnowledgeBase) AddObservationDraft ¶ added in v0.0.30
func (kb *KnowledgeBase) AddObservationDraft(projectID int64, kind, body, by string, confidence *float64) (int64, error)
* AddObservationDraft records an observation written by a model. It is
- stored with status "drafted", is not written to kb_fts, and stays out of
- search and recall until a person promotes it with PromoteObservation
- (DR-0090). The library has no terminal rule; the command line does. *
- Parameters:
- projectID (int64) — ID of the owning project.
- kind (string) — one of: note, finding, decision, question, hypothesis.
- body (string) — the observation text.
- by (string) — who drafted it, e.g. "harvey qwen2.5:3b"; one non-blank line.
- confidence (*float64) — the drafter's estimate in 0 to 1, or nil. *
- Returns:
- int64 — ID of the new drafted observation.
- error — ErrInvalid for a bad kind, blank body, bad by or confidence outside 0 to 1. *
- Example:
- c := 0.7
- id, err := kb.AddObservationDraft(1, "finding", "WAL helps", "harvey qwen2.5:3b", &c)
func (*KnowledgeBase) AddObservationRelation ¶ added in v0.0.8
func (kb *KnowledgeBase) AddObservationRelation(fromID, toID int64, relationship string) error
* AddObservationRelation stores one directed edge between two observations.
- Adding the same edge twice is a no-op. Mirrors AddRecordRelation exactly,
- one level down — see DR-0023: an observation is corrected by superseding
- it with a new one, never by mutating its body, so the old row stays
- exactly as originally recorded and the correction is just this edge plus
- the new row's own timestamp. *
- Parameters:
- fromID (int64) — the newer, correcting observation's primary key.
- toID (int64) — the older, corrected observation's primary key.
- relationship (string) — "supersedes"; the only relationship observations
- carry today. *
- Returns:
- error — when either observation is missing, or on database failure. *
- Example:
- err := kb.AddObservationRelation(newerID, olderID, "supersedes")
func (*KnowledgeBase) AddObservationWithSource ¶
func (kb *KnowledgeBase) AddObservationWithSource(projectID int64, kind, body, sourceDOI string) (int64, error)
* AddObservationWithSource inserts a new observation for a project,
- recording the normalized DOI of the paper it was extracted from, and
- returns its ID. *
- Parameters:
- projectID (int64) — ID of the owning project.
- kind (string) — one of: note, finding, decision, question, hypothesis.
- body (string) — the observation text.
- sourceDOI (string) — normalized DOI of the source paper, or "" if none. *
- Returns:
- int64 — ID of the new observation.
- error — if kind is invalid, body is blank, or the insert fails. *
- Example:
- id, err := kb.AddObservationWithSource(1, "finding",
- "This paper found X", "https://doi.org/10.1234/abcd.5678")
func (*KnowledgeBase) AddProject ¶
func (kb *KnowledgeBase) AddProject(name, description string) (int64, error)
* AddProject inserts a new project row and returns its auto-assigned ID. If a
- project with the same name already exists, its ID is returned instead. *
- Parameters:
- name (string) — unique project name.
- description (string) — short human-readable description. *
- Returns:
- int64 — ID of the inserted or existing project.
- error — if name is blank, or on database failure. *
- Example:
- id, err := kb.AddProject("harvey", "Terminal coding agent backed by Ollama")
func (*KnowledgeBase) AddProjectWithStatus ¶ added in v0.0.2
func (kb *KnowledgeBase) AddProjectWithStatus(name, description, status string) (int64, error)
* AddProjectWithStatus is like AddProject but sets an explicit status
- instead of the "active" default. status must be one of concept, active,
- paused, or concluded. *
- Parameters:
- name (string) — unique project name.
- description (string) — short human-readable description.
- status (string) — one of concept, active, paused, concluded. *
- Returns:
- int64 — ID of the inserted or existing project. If the project already
- existed, its status is left unchanged (same no-op convention
- as AddProject).
- error — on database failure, if status is not one of the allowed values, or if name is blank. *
- Example:
- id, err := kb.AddProjectWithStatus("harvey", "Terminal coding agent", "concept")
func (*KnowledgeBase) AddRecord ¶ added in v0.0.4
func (kb *KnowledgeBase) AddRecord(r Record) (int64, error)
* AddRecord inserts a decision record, or updates the existing row with the
- same identity. A record's identity is (project_id, scope, record_id), which
- is what makes re-ingesting a whole tree idempotent rather than duplicating
- it. *
- UUID and OriginHost are filled in when empty and preserved when the caller
- supplies them, since a record file carries its own uuid: regenerating one on
- every ingest would break cross-machine merge. *
- Parameters:
- r (Record) — the record to store; the ID field is ignored. *
- Returns:
- int64 — the ID of the inserted or updated row.
- error — on database failure. *
- Example:
- id, err := kb.AddRecord(Record{
- RecordID: "0160", ProjectID: pid, Scope: "project",
- Path: "decisions/0160-iam-instance-profile.md",
- Title: "Associate/Replace IAM instance profile",
- Date: "2026-08-18", Status: "accepted", Kind: "decision",
- })
func (*KnowledgeBase) AddRecordRelation ¶ added in v0.0.4
func (kb *KnowledgeBase) AddRecordRelation(fromID, toID int64, relationship string) error
* AddRecordRelation stores one directed edge between two records. Adding the
- same edge twice is a no-op. *
- Only the stated direction is stored: superseded_by is the inverse of
- supersedes and is computed by RelationsFor on read. Storing a supersession
- deliberately does not change either record's status, because superseded_by
- does not imply status: superseded — a later record can invalidate one
- decision inside a multi-decision episode while the rest stand. Use
- UpdateRecordStatus when the whole record really is superseded. *
- Parameters:
- fromID (int64) — the citing record's primary key.
- toID (int64) — the cited record's primary key.
- relationship (string) — "supersedes" or "relates_to". *
- Returns:
- error — when either record is missing, or on database failure. *
- Example:
- err := kb.AddRecordRelation(newerID, olderID, "supersedes")
func (*KnowledgeBase) AddSource ¶
func (kb *KnowledgeBase) AddSource(s Source) (int64, error)
* AddSource inserts a new source row and returns its auto-assigned ID.
- When identifier_type and identifier_value are both non-empty, an existing
- row with the same (type, value) pair is returned instead of creating a
- duplicate. *
- The title is trimmed and must not be blank. published_date, when set, must be
- YYYY, YYYY-MM or YYYY-MM-DD. A "url" identifier must be an absolute URL and a
- "doi" identifier a bare 10.NNNN/suffix DOI; other identifier types are not
- checked. Nothing is rewritten beyond trimming whitespace. The JSONL importer
- does not call AddSource and is not held to these checks. *
- Parameters:
- s (Source) — source metadata; ID field is ignored. *
- Returns:
- int64 — the ID of the inserted or existing row.
- error — for a blank title or a malformed date, url or doi (nothing is
- inserted), or on database failure. *
- Example:
- id, err := kb.AddSource(Source{Title: "SPARQL 1.1", IdentifierType: "doi", IdentifierValue: "10.1234/sparql"})
func (*KnowledgeBase) ApplyFrontmatter ¶ added in v0.0.12
func (kb *KnowledgeBase) ApplyFrontmatter(path string, raw []byte, prov Provenance, accept FrontmatterAccept, dryRun bool) ([]byte, FrontmatterResult, error)
* ApplyFrontmatter proposes, then applies exactly what accept selects, and
- returns the file's new bytes for the caller to write. The document body is
- never modified: only the frontmatter block is spliced, via a YAML node edit
- that leaves every other key, value and comment in it alone. *
- Every accepted keyword is validated before any concept is created or any
- byte is produced, so one bad name aborts the whole call. On a real run a
- new-candidate keyword's concept is created in the database before this
- returns, which is why the caller should write the bytes it gets back; on a
- dry run the database is never touched and the input bytes come back. *
- Parameters:
- path (string) — as for ProposeFrontmatter.
- raw ([]byte) — the file's current bytes; never modified.
- prov (Provenance) — nil means GitProvenance.
- accept (FrontmatterAccept) — what to write.
- dryRun (bool) — preview only: report, but change nothing. *
- Returns:
- []byte — the new file contents when result.Written is true,
- otherwise raw unchanged; nil on error.
- FrontmatterResult — the report, with Accepted marks set.
- error — for an unknown field, a rejected keyword, unparseable
- frontmatter, or a database failure. *
- Example:
- next, res, err := kb.ApplyFrontmatter("a.md", raw, nil, knowledge.FrontmatterAccept{Fields: []string{"title"}}, false)
- if err == nil && res.Written { os.WriteFile("a.md", next, 0o644) }
func (*KnowledgeBase) CheckRetractions ¶
func (kb *KnowledgeBase) CheckRetractions( checker func(doi string) (retracted bool, note string, err error), out io.Writer, ) (checked, updated int, err error)
* CheckRetractions queries checker for every non-retracted source with
- identifier_type = "doi" and marks any hits as retracted. It sets
- last_checked_at for every source the checker answered for, and only those: a
- source whose lookup failed has not been checked. Every source is tried even
- after a failure. Progress is written to out. *
- Parameters:
- checker (func(doi string) (bool, string, error)) — returns (retracted,
- note, err) for a given DOI. Use CheckDOIRetraction for production.
- out (io.Writer) — destination for per-source status lines. *
- Returns:
- checked (int) — number of DOI sources the checker gave an answer for.
- updated (int) — number of sources newly marked as retracted.
- error — a *RetractionCheckError when some sources could not be
- checked (the rest still were, and the counts are valid),
- or another error on database failure. *
- Example:
- checked, updated, err := kb.CheckRetractions(
- func(doi string) (bool, string, error) {
- return CheckDOIRetraction(doi, DefaultRetractionWatchURL)
- }, os.Stdout)
func (*KnowledgeBase) ClearDocumentSectionConcepts ¶ added in v0.0.7
func (kb *KnowledgeBase) ClearDocumentSectionConcepts(sectionID int64) error
* ClearDocumentSectionConcepts deletes every concept link a section carries,
- without deleting the concepts themselves. Verbatim shape of
- ClearRecordConcepts (knowledge.go): re-ingest calls this before re-tagging
- a section's current wikilinks and keywords, so a tag dropped from the
- source text is actually dropped from the database rather than only ever
- accumulating. *
- Parameters:
- sectionID (int64) — ID of the document_sections row. *
- Returns:
- error — on database failure. *
- Example:
- err := kb.ClearDocumentSectionConcepts(sectionID)
func (*KnowledgeBase) ClearRecordConcepts ¶ added in v0.0.7
func (kb *KnowledgeBase) ClearRecordConcepts(recordID int64) error
* ClearRecordConcepts deletes every concept link a record carries, without
- deleting the concepts themselves — another record or observation may still
- reference one. Ingest calls this before re-linking a record's current
- wikilinks and tags on every run, so a tag dropped from a file is actually
- dropped from the database: without it, record_concepts only ever grew,
- exactly as record_relations did before ClearRecordRelationsFrom. *
- Parameters:
- recordID (int64) — internal database id of the record (Record.ID, not RecordID). *
- Returns:
- error — on database failure. *
- Example:
- err := kb.ClearRecordConcepts(recordID)
func (*KnowledgeBase) ClearRecordRelationsFrom ¶ added in v0.0.7
func (kb *KnowledgeBase) ClearRecordRelationsFrom(fromID int64) error
* ClearRecordRelationsFrom deletes every relation a record declares as its
- own — both supersedes and relates_to — without touching edges other
- records declare toward it. Ingest calls this before re-inserting a
- record's current set on every run, so a relation dropped from a file's
- frontmatter is actually dropped from the database: without it,
- record_relations only ever grew, since re-ingest inserted what a file
- declared but never deleted what it no longer declared. *
- Scoped to fromID so the other side's own declarations survive: deleting by
- either endpoint would also erase a relates_to edge the other record still
- asserts. *
- Parameters:
- fromID (int64) — the citing record's primary key. *
- Returns:
- error — on database failure. *
- Example:
- err := kb.ClearRecordRelationsFrom(recordID)
func (*KnowledgeBase) Close ¶
func (kb *KnowledgeBase) Close() error
* Close releases the database connection. It should be deferred immediately
- after a successful Open call. *
- Returns:
- error — from the underlying sql.DB.Close call. *
- Example:
- kb, _ := Open(dbPath)
- defer kb.Close()
func (*KnowledgeBase) CompareToJSONL ¶ added in v0.0.15
func (kb *KnowledgeBase) CompareToJSONL(r io.Reader) (DBComparison, error)
* CompareToJSONL compares this database with a JSONL dump by full content,
- never by file time, and changes neither. The database is copied with
- VACUUM INTO, the dump is imported into a second scratch database, and the
- two go through the same identity rules merge uses (DiffDatabases,
- CollisionReport), so this cannot disagree with `kb merge` or `kb import`
- about what "the same row" means. The library does no file I/O for the dump:
- the caller passes a reader (DR-0035). *
- Parameters:
- r (io.Reader) — a JSONL stream as written by ExportJSONL. *
- Returns:
- DBComparison — the per-table differences and a recommendation.
- error — ErrInvalid for a malformed dump, or a database failure. *
- Example:
- f, _ := os.Open("agents/knowledge.jsonl")
- defer f.Close()
- c, err := kb.CompareToJSONL(f)
func (*KnowledgeBase) ConceptDetail ¶ added in v0.0.15
func (kb *KnowledgeBase) ConceptDetail(name string, limit int) (ConceptDetailResult, error)
* ConceptDetail reports one concept's description, link counts and up to
- limit linked items of each kind, newest first, without changing anything.
- The name must match exactly, including case, as DeleteConcept requires, so
- "show" and "delete" agree on what a name means. A miss is ErrNotFound; when
- a concept differing only in case exists, the error text offers it. *
- Parameters:
- name (string) — the concept's name.
- limit (int) — most items per kind; zero returns counts only, negative is treated as zero. *
- Returns:
- ConceptDetailResult — the concept, its counts and its items.
- error — ErrNotFound for an unknown name, or a database failure. *
- Example:
- d, err := kb.ConceptDetail("toast", 10)
func (*KnowledgeBase) ConceptUsage ¶ added in v0.0.12
func (kb *KnowledgeBase) ConceptUsage(name string) (ConceptUsage, error)
* ConceptUsage reports what links to the named concept, without changing
- anything. The name must match exactly, including case. *
- Parameters:
- name (string) — the concept's name. *
- Returns:
- ConceptUsage — the link counts.
- error — if no concept has that name, or on database failure. *
- Example:
- u, err := kb.ConceptUsage("...")
func (*KnowledgeBase) Concepts ¶
func (kb *KnowledgeBase) Concepts() ([]Concept, error)
- Concepts returns all concepts ordered by name. *
- Returns:
- []Concept — all concept rows; empty (not nil) if none exist.
- error — on database failure. *
- Example:
- concepts, err := kb.Concepts()
- for _, c := range concepts {
- fmt.Println(c.Name)
- }
func (*KnowledgeBase) ConceptsOfKind ¶ added in v0.0.24
func (kb *KnowledgeBase) ConceptsOfKind(kind string) ([]Concept, error)
- ConceptsOfKind returns the concepts of one kind, ordered by name. *
- Parameters:
- kind (string) — one of ConceptKinds. *
- Returns:
- []Concept — the matching concepts; empty (not nil) if none.
- error — ErrInvalid for a kind outside the vocabulary, or a database failure. *
- Example:
- characters, err := kb.ConceptsOfKind("character")
func (*KnowledgeBase) DeleteConcept ¶ added in v0.0.12
func (kb *KnowledgeBase) DeleteConcept(name string, force bool) (ConceptUsage, error)
* DeleteConcept removes the named concept: its row, every link to it, and its
- full-text entry, in one transaction for the rows. The projects, observations,
- records and document sections it was linked to are left alone; only the
- links go. Without force, a concept that still has links is refused with a
- *ConceptInUseError and nothing changes, so a mistyped name cannot silently
- strip tags from real data. *
- Two things this does not do, and a caller should tell the user. It does not
- touch files: a record or document that still contains [[Name]], or lists the
- name in tags or keywords, recreates the concept when that file is next ingested
- after it changes (an unchanged file is skipped) or when the database is rebuilt
- from the files.
- And it does not propagate: a database that still holds the concept brings it
- back on the next merge or import into this one. *
- Parameters:
- name (string) — the concept's name, matched exactly including case.
- force (bool) — unlink the concept from everything and delete it anyway. *
- Returns:
- ConceptUsage — the links that existed, which were removed when force was
- given or there were none.
- error — *ConceptInUseError when linked and !force, an error if no
- concept has that name, or on database failure. *
- Example:
- u, err := kb.DeleteConcept("...", true)
func (*KnowledgeBase) DeleteDocument ¶ added in v0.0.14
func (kb *KnowledgeBase) DeleteDocument(id int64, force bool) (DocumentUsage, error)
* DeleteDocument removes a document, its sections and their concept links, and the
- search entries of any promoted summaries. A document with a section whose summary is
- reviewed is refused unless force is true: a reviewed summary is human-gated data and
- deleting it loses it. Ingesting the file again recreates the document, without the
- reviewed summaries. *
- Parameters:
- id (int64) — the document's id.
- force (bool) — delete even though a reviewed summary is lost. *
- Returns:
- DocumentUsage — what the document held.
- error — ErrNotFound if there is no such document; an *InUseError (matching
- ErrInUse), with nothing changed, if a reviewed summary blocks it. *
- Example:
- u, err := kb.DeleteDocument(1, false)
func (*KnowledgeBase) DeleteObservation ¶ added in v0.0.14
func (kb *KnowledgeBase) DeleteObservation(id int64, force bool) (ObservationUsage, error)
* DeleteObservation removes an observation. One with concept links, source links or
- supersession relations (either direction) is refused unless force is true, which
- removes those links and relations and the observation; the concepts, sources and the
- other observations stay. *
- Parameters:
- id (int64) — the observation's id.
- force (bool) — remove links and relations too. *
- Returns:
- ObservationUsage — what depended on it.
- error — ErrNotFound if there is no such observation; an *InUseError
- (matching ErrInUse), with nothing changed, if it is linked and
- force is false. *
- Example:
- u, err := kb.DeleteObservation(7, true)
func (*KnowledgeBase) DeleteProject ¶ added in v0.0.14
func (kb *KnowledgeBase) DeleteProject(name string, force bool) (ProjectUsage, error)
* DeleteProject removes a project. A project that owns any observation, record or
- document is always refused, with force or without: one call must never destroy
- work, so the content has to be deleted or moved first. A project with only concept
- links is refused unless force is true, which removes those links and the project;
- the concepts themselves stay. It exists to remove a stray empty project. *
- Parameters:
- name (string) — the project's name, matched exactly.
- force (bool) — remove concept links too. *
- Returns:
- ProjectUsage — what depended on it (removed, or, on refusal, what blocked it).
- error — ErrNotFound if there is no such project; an *InUseError (matching
- ErrInUse), with nothing changed, if it is not deletable. *
- Example:
- u, err := kb.DeleteProject("stray", false)
func (*KnowledgeBase) DeleteRecord ¶ added in v0.0.14
func (kb *KnowledgeBase) DeleteRecord(id int64) (RecordUsage, error)
* DeleteRecord removes a record's row, its relations in both directions, its concept
- links and its search entry. It is for a row whose file has gone: the library does no
- file I/O, so it cannot check that, and the caller must (kb's record delete does). A
- row deleted while its file still exists comes back the next time the file changes and
- is ingested. The relations of other records that pointed at this one go with it. *
- Parameters:
- id (int64) — the record row's id. *
- Returns:
- RecordUsage — what the row was linked to.
- error — ErrNotFound if there is no such record, or on database failure. *
- Example:
- u, err := kb.DeleteRecord(12)
func (*KnowledgeBase) DistinctRecordValues ¶ added in v0.0.13
func (kb *KnowledgeBase) DistinctRecordValues(field string) ([]string, error)
* DistinctRecordValues returns the values a record field actually takes in
- this database, sorted, without duplicates and without the empty string.
- It exists so a caller can tell a filter value nothing carries (a typo) from
- a real one that happens to match no record, which matters because the
- status, kind and trigger vocabularies are documented rather than enforced:
- a record may carry a value outside them. *
- Parameters:
- field (string) — one of "status", "kind", "trigger" or "initiative". *
- Returns:
- []string — the distinct non-empty values; nil when no record has one.
- error — for any other field name, or on database failure. *
- Example:
- statuses, err := kb.DistinctRecordValues("status") // [accepted proposed]
func (*KnowledgeBase) DocumentByID ¶ added in v0.0.6
func (kb *KnowledgeBase) DocumentByID(id int64) (*Document, error)
* DocumentByID returns the document with the given internal id, or nil if
- none exists. *
- Parameters:
- id (int64) — the document's internal id. *
- Returns:
- *Document — the matching document, or nil when not found.
- error — on database failure. *
- Example:
- d, err := kb.DocumentByID(42)
func (*KnowledgeBase) DocumentByPath ¶ added in v0.0.6
func (kb *KnowledgeBase) DocumentByPath(path string) (*Document, error)
- DocumentByPath returns the document stored at path, or nil if none exists. *
- Parameters:
- path (string) — the document's stored path. *
- Returns:
- *Document — the matching document, or nil when not found.
- error — on database failure. *
- Example:
- d, err := kb.DocumentByPath("stories/a-story.md")
func (*KnowledgeBase) DocumentReviewQueue ¶ added in v0.0.6
func (kb *KnowledgeBase) DocumentReviewQueue(projectID int64, status string) ([]DocumentReviewItem, error)
* DocumentReviewQueue returns document_sections rows needing attention
- (design decision 7), optionally scoped to one project and one status.
- With status == "", the default is the actual triage queue --
- "unsummarized" and "drafted" rows, not "reviewed" ones, which need no
- further attention. Passing an explicit status (including "reviewed")
- overrides that default, for auditing. *
- Parameters:
- projectID (int64) — scope to one project, or 0 for every project.
- status (string) — an exact status to filter to, or "" for the
- unsummarized+drafted default. *
- Returns:
- []DocumentReviewItem — matching sections, gist first then by seq within
- each document; nil when none.
- error — on database failure. *
- Example:
- items, err := kb.DocumentReviewQueue(0, "")
func (*KnowledgeBase) DocumentSectionConcepts ¶ added in v0.0.6
func (kb *KnowledgeBase) DocumentSectionConcepts(sectionID int64) ([]Concept, error)
* DocumentSectionConcepts returns all concepts linked to the given document
- section id, ordered by concept id. Mirrors RecordConcepts (knowledge.go). *
- Parameters:
- sectionID (int64) — the document_sections row's internal id. *
- Returns:
- []Concept — linked concepts; nil when none.
- error — on database failure. *
- Example:
- concepts, err := kb.DocumentSectionConcepts(sectionID)
func (*KnowledgeBase) DocumentSections ¶ added in v0.0.6
func (kb *KnowledgeBase) DocumentSections(documentID int64) ([]DocumentSection, error)
* DocumentSections returns every section of a document, gist first, then
- by Seq. *
- Parameters:
- documentID (int64) — the document's internal id. *
- Returns:
- []DocumentSection — the document's sections; nil when none.
- error — on database failure. *
- Example:
- sections, err := kb.DocumentSections(docID)
func (*KnowledgeBase) DocumentSources ¶ added in v0.0.25
func (kb *KnowledgeBase) DocumentSources(documentID int64) ([]SourceLink, error)
- DocumentSources lists the sources a document cites, ordered by source id. *
- Parameters:
- documentID (int64) — document primary key. *
- Returns:
- []SourceLink — empty (not nil) when none.
- error — on database failure. *
- Example:
- links, err := kb.DocumentSources(7)
func (*KnowledgeBase) DocumentUsage ¶ added in v0.0.14
func (kb *KnowledgeBase) DocumentUsage(id int64) (DocumentUsage, error)
- DocumentUsage reports what the document holds, without changing anything. *
- Parameters:
- id (int64) — the document's id. *
- Returns:
- DocumentUsage — the counts.
- error — ErrNotFound if there is no such document, or on database failure. *
- Example:
- u, err := kb.DocumentUsage(1)
func (*KnowledgeBase) Documents ¶ added in v0.0.6
func (kb *KnowledgeBase) Documents(projectID int64) ([]Document, error)
* Documents lists documents, optionally scoped to one project, ordered by
- id (i.e. ingestion order). Mirrors DocumentReviewQueue's projectID
- convention: 0 means every project. *
- Parameters:
- projectID (int64) — scope to one project, or 0 for every project. *
- Returns:
- []Document — matching documents; nil when none.
- error — on database failure. *
- Example:
- docs, err := kb.Documents(0)
func (*KnowledgeBase) DraftDocumentSummary ¶ added in v0.0.6
func (kb *KnowledgeBase) DraftDocumentSummary(sectionID int64, body, generatedBy string, confidence *float64) error
* DraftDocumentSummary writes a gist or section summary (design decision
- 7): sets summary_body, summary_status to "drafted", generatedBy (a caller
- identity -- "human" or a model name; knowledge never calls a model
- itself), and confidence. A fresh draft clears summary_stale, since it is
- by definition not stale against itself. Range-validating confidence is
- the caller's job (the CLI does it); this is a trusted data-layer write. *
- Parameters:
- sectionID (int64) — the document_sections row to draft.
- body (string) — the summary text.
- generatedBy (string) — who/what produced it.
- confidence (*float64) — self-reported confidence, or nil. *
- Returns:
- error — on database failure. *
- Example:
- c := 0.8
- err := kb.DraftDocumentSummary(sectionID, "...", "human", &c)
func (*KnowledgeBase) EligibleTagConcepts ¶ added in v0.0.12
func (kb *KnowledgeBase) EligibleTagConcepts(text string, candidates []string) ([]string, error)
* EligibleTagConcepts returns the subset of candidates mentioned more than
- once in text, outside code spans -- the same >1-occurrence,
- code-span-excluded threshold DR-0027's density-linking already applies
- to decide a concept is genuinely relevant to a piece of text, reused
- here (via MatchConceptNameCounts) so a concept `kb document tag` would
- insert explicitly is exactly one density-linking would already have
- linked implicitly on the next ingest -- this tool just makes that link
- visible in the prose instead of leaving it inferred. *
- The result is sorted case-insensitively (then exactly), so it is stable from
- one call to the next. *
- Parameters:
- text (string) — the document's raw content.
- candidates ([]string) — concept names eligibility is restricted to. *
- Returns:
- []string — candidates mentioned more than once outside code spans; nil
- when none qualify.
- error — on database failure. *
- Example:
- names, err := kb.EligibleTagConcepts(body, []string{"chunking", "workspace"})
func (*KnowledgeBase) EmbedCorpus ¶ added in v0.0.29
func (kb *KnowledgeBase) EmbedCorpus(scope SearchScope) ([]CorpusRow, error)
* EmbedCorpus returns the rows semantic search embeds or ranks, narrowed by
- the same scope lexical search uses (SearchScoped), so the two cannot disagree
- about what a scope contains. The text is read from the full-text index, so
- there is one definition of a row's text: a drafted document summary is
- absent because lexical search does not trust it either, and a section's body
- is absent because lexical search does not index it. Limit is ignored. *
- Parameters:
- scope (SearchScope) — where to look; the zero value is every embedded row *
- Returns:
- []CorpusRow — the rows, in no particular order
- error — ErrInvalid for a kind that is not embedded (the message names the
- choices), an unknown kind, or Project with Workspace; ErrNotFound for an
- unknown project; ErrNoMembers when no requested kind can exist in the scope *
- Example:
- rows, err := kb.EmbedCorpus(knowledge.SearchScope{Project: "harvey", Kinds: []string{"records"}})
func (*KnowledgeBase) EmbedIndex ¶ added in v0.0.29
func (kb *KnowledgeBase) EmbedIndex(ctx context.Context, v *Vectors, e Embedder, opts EmbedOptions) (EmbedResult, error)
* EmbedIndex brings the vector sidecar in step with the corpus. A row is split
- into chunks and compared with what is stored: a chunk whose text is unchanged
- keeps its vector, a new or changed one is sent to the embedder, and a row that
- is gone, or has no text, loses its chunks. Embedding happens in batches and
- each finished row is committed, so an interrupted run, by error or by
- cancelling ctx, has lost at most the batch in flight and a rerun carries on.
- It holds the sidecar's lock for the whole run (ErrLocked when another run has
- it) and refreshes it after each batch, aborting if the lock was taken over.
- It never builds an index for a different model: that is ErrModelMismatch, and
- the remedy is ResetVectors. *
- Parameters:
- ctx (context.Context) — cancelled to stop between batches
- v (*Vectors) — the sidecar to update
- e (Embedder) — the model; it must be the one v was built with
- opts (EmbedOptions) — batch size, chunk size and progress reporting *
- Returns:
- EmbedResult — what was done, valid also when an error is returned
- error — ctx's error when cancelled; ErrModelMismatch; ErrLocked; the embedder's error;
- a database error *
- Example:
- res, err := kb.EmbedIndex(ctx, v, embedder, knowledge.EmbedOptions{})
- fmt.Printf("%d rows embedded, %d up to date\n", res.RowsEmbedded, res.RowsSkipped)
func (*KnowledgeBase) EmbedStatus ¶ added in v0.0.29
func (kb *KnowledgeBase) EmbedStatus(v *Vectors, chunkRunes int) (EmbedStatus, error)
* EmbedStatus reports what EmbedIndex would do, changing nothing and loading
- no model. *
- Parameters:
- v (*Vectors) — the sidecar to compare
- chunkRunes (int) — the longest chunk; zero means DefaultChunkRunes *
- Returns:
- EmbedStatus — the counts
- error — a database error *
- Example:
- st, err := kb.EmbedStatus(v, 0)
- fmt.Printf("%d of %d rows not indexed\n", st.RowsToEmbed, st.Rows)
func (*KnowledgeBase) FindOrCreateSource ¶
func (kb *KnowledgeBase) FindOrCreateSource(title, identifierType, identifierValue string) (int64, error)
* FindOrCreateSource upserts a source by identifier when one is provided, or
- inserts a new source with the given title when no identifier is known. *
- Parameters:
- title (string) — human-readable title or file path.
- identifierType (string) — "doi", "url", etc.; empty = no identifier.
- identifierValue (string) — the identifier value; empty = no identifier. *
- Returns:
- int64 — the ID of the found or created source.
- error — on database failure. *
- Example:
- id, err := kb.FindOrCreateSource("spec.md", "doi", "10.1234/example")
func (*KnowledgeBase) FormatMarkdown ¶
func (kb *KnowledgeBase) FormatMarkdown(projectID int64) (string, error)
* FormatMarkdown returns the knowledge base contents as Markdown, suitable for
- injecting into a conversation as context. When projectID > 0 only that project
- is included; when projectID == 0 all projects are included. Each project gets
- a ## heading, and observations are listed with their kind in bold. *
- Parameters:
- projectID (int64) — project to export; 0 = all projects. *
- Returns:
- string — Markdown-formatted knowledge base contents; "" if no data.
- error — on database failure. *
- Example:
- md, err := kb.FormatMarkdown(0) // all projects
- md, err := kb.FormatMarkdown(1) // project id=1 only
func (*KnowledgeBase) FuzzyMatchConceptNames ¶ added in v0.0.11
func (kb *KnowledgeBase) FuzzyMatchConceptNames(text string) ([]FuzzyConceptMatch, error)
* FuzzyMatchConceptNames returns spelling-level near-misses of known
- concept names in text -- typos, plurals, and simple tense variants that
- MatchConceptNames's exact whole-word matching would find nothing for.
- Scoped deliberately to spelling distance, not paraphrase: a concept
- already found as an exact match anywhere in text is skipped entirely
- (fuzzy matching is additive, never a duplicate of what exact matching
- already covers). *
- Parameters:
- text (string) — free text to search, e.g. a document's raw content. *
- Returns:
- []FuzzyConceptMatch — near-misses sorted by Start, then Concept; nil
- when none.
- error — on database failure. *
- Example:
- matches, err := kb.FuzzyMatchConceptNames("the chunkings here")
- // matches[0] == {Concept: "chunking", Text: "chunkings", Distance: 1, ...}
func (*KnowledgeBase) HasConcept ¶ added in v0.0.20
func (kb *KnowledgeBase) HasConcept(name string) (bool, error)
* HasConcept reports whether a concept with this name exists, matching
- case-insensitively as ResolveConceptName does, and creates nothing. It is what a
- plan needs to say which concepts an ingest would create. *
- Parameters:
- name (string) — the concept name as it appears in text. *
- Returns:
- bool — true when a concept of that name exists.
- error — on database failure, or when the name is blank. *
- Example:
- ok, err := kb.HasConcept("computer")
func (*KnowledgeBase) HitsFor ¶ added in v0.0.29
func (kb *KnowledgeBase) HitsFor(keys []RowKey) ([]KBSearchResult, error)
* HitsFor looks up the rows named by keys and returns them in the same order,
- with the fields a search result shows and their provenance (DR-0080), but no
- passage: there is no query to mark one, so the caller sets it, for a semantic
- hit from the matching chunk. A key with no row (deleted since) is left out. *
- Parameters:
- keys ([]RowKey) — the rows to look up *
- Returns:
- []KBSearchResult — one per key that still exists, in the order of keys
- error — a database error *
- Example:
- hits, err := kb.HitsFor([]knowledge.RowKey{{SourceType: "record", SourceID: 12}})
func (*KnowledgeBase) IngestDocument ¶ added in v0.0.12
func (kb *KnowledgeBase) IngestDocument(projectID int64, path string, opts DocumentIngestOptions) (DocumentIngestResult, error)
* IngestDocument parses the file at path and creates or reconciles its
- documents row and sections in project projectID. A path not yet stored is
- ingested fresh; a stored path with an unchanged checksum is skipped; a
- stored path with a changed checksum is reconciled by matching sections on
- heading text (an unchanged body is left alone, a changed body updates in
- place and flags its summary stale, an unmatched old heading is reported
- and never deleted, an unmatched new heading is inserted unsummarized).
- Every section and the gist are concept-tagged and density-scored as they
- are written. *
- The path is stored exactly as given, and DocumentByPath is an exact string
- match, so a second consumer must pass the same form (relative or absolute)
- every time or it will ingest the same file twice as two documents. *
- The caller is responsible for confirming projectID exists; unlike the
- CLI this does not look a project up by name. *
- Parameters:
- projectID (int64) — the owning project's id.
- path (string) — the file to ingest.
- opts (DocumentIngestOptions) — title/format overrides and dry-run. *
- Returns:
- DocumentIngestResult — what happened (zero value on error).
- error — on an unreadable file, an unsupported format
- (PDF), or a database failure. *
- Example:
- res, err := kb.IngestDocument(pid, "stories/a.md", knowledge.DocumentIngestOptions{})
- // res.Action == "added"
func (*KnowledgeBase) LexicalRanking ¶ added in v0.0.29
func (kb *KnowledgeBase) LexicalRanking(term string, scope SearchScope) ([]RowKey, error)
* LexicalRanking returns the rows a full-text search finds in an embedded kind,
- best first, as the lexical half of a hybrid search. It looks only in
- EmbeddedKinds, takes the term as typed (every word must appear in a row), and
- goes deeper than a results page so fusion has rows to work with. A term FTS5
- cannot parse is retried as one quoted phrase. *
- Parameters:
- term (string) — the search term, in FTS5 syntax
- scope (SearchScope) — where to look; Kinds must be among EmbeddedKinds *
- Returns:
- []RowKey — the matching rows, best first (bm25), at most hybridLexicalDepth
- error — ErrInvalid for a scope with a kind that is not embedded, or a database error *
- Example:
- keys, err := kb.LexicalRanking("exit codes", knowledge.SearchScope{})
func (*KnowledgeBase) LexicalRankingWide ¶ added in v0.0.31
func (kb *KnowledgeBase) LexicalRankingWide(term string, scope SearchScope) (typed, widened []RowKey, err error)
* LexicalRankingWide is LexicalRanking for a question typed as a sentence
- (knowledge DR-0094). It runs the typed term first. When that finds fewer than
- three rows and the term is plain words (no quote, no *, no parentheses, no
- column filter, no capitalised AND, OR, NOT or NEAR), it also runs an OR of the
- term's words of four letters or more, ranked by bm25. A term in FTS5 syntax is
- never rewritten. *
- Parameters:
- term (string) — the search term
- scope (SearchScope) — where to look; Kinds must be among EmbeddedKinds *
- Returns:
- typed ([]RowKey) — the rows the typed term found, best first
- widened ([]RowKey) — the rows of the any-word search, best first, which include the typed rows;
- nil when the typed term was left alone
- error — as LexicalRanking *
- Example:
- typed, widened, err := kb.LexicalRankingWide("when did the ferry schedule change", knowledge.SearchScope{})
func (*KnowledgeBase) LinkDocumentSectionConcept ¶ added in v0.0.6
func (kb *KnowledgeBase) LinkDocumentSectionConcept(sectionID, conceptID int64) error
* LinkDocumentSectionConcept associates a document section with a concept.
- Duplicate links are silently ignored. Verbatim shape of
- LinkRecordConcept (knowledge.go), for the same relationship one level
- down (design decision 5). *
- Parameters:
- sectionID (int64) — ID of the document_sections row.
- conceptID (int64) — ID of the concept. *
- Returns:
- error — on database failure. *
- Example:
- err := kb.LinkDocumentSectionConcept(sectionID, conceptID)
func (*KnowledgeBase) LinkDocumentSource ¶ added in v0.0.25
func (kb *KnowledgeBase) LinkDocumentSource(documentID, sourceID int64, relationship, version, hash string) error
* LinkDocumentSource records that a document cites a source (DR-0081 item 3).
- A second link of the same pair is ignored, the first write staying. *
- Parameters:
- documentID (int64) — document primary key.
- sourceID (int64) — source primary key.
- relationship (string) — label; "" means "cited".
- version (string) — version of the work read; "" when not recorded.
- hash (string) — its content hash; "" when not recorded. *
- Returns:
- error — ErrNotFound for a document or source that does not exist, or on database failure. *
- Example:
- err := kb.LinkDocumentSource(7, 1, "cited", "", "")
func (*KnowledgeBase) LinkObservationConcept ¶
func (kb *KnowledgeBase) LinkObservationConcept(observationID, conceptID int64) error
* LinkObservationConcept associates an observation with a concept. Duplicate
- links are silently ignored. *
- Parameters:
- observationID (int64) — ID of the observation.
- conceptID (int64) — ID of the concept. *
- Returns:
- error — ErrNotFound for an observation or concept that does not exist, or on database failure. *
- Example:
- err := kb.LinkObservationConcept(obsID, conceptID)
func (*KnowledgeBase) LinkObservationSource ¶
func (kb *KnowledgeBase) LinkObservationSource(observationID, sourceID int64, relationship string) error
* LinkObservationSource creates an observation_sources row linking an
- observation to a source. Duplicate links are silently ignored. *
- Parameters:
- observationID (int64) — observation primary key.
- sourceID (int64) — source primary key.
- relationship (string) — label, e.g. "cited" or "retrieved". *
- Returns:
- error — ErrNotFound for an observation or source that does not exist, or on database failure. *
- Example:
- err := kb.LinkObservationSource(42, 1, "retrieved")
func (*KnowledgeBase) LinkObservationSourceAt ¶ added in v0.0.25
func (kb *KnowledgeBase) LinkObservationSourceAt(observationID, sourceID int64, relationship, version, hash string) error
* LinkObservationSourceAt is LinkObservationSource with the version and content
- hash of the cited work at the time it was read (DR-0081 item 2). A second link
- of the same pair is ignored, the first write staying. *
- Parameters:
- observationID (int64) — observation primary key.
- sourceID (int64) — source primary key.
- relationship (string) — label; "" means "cited".
- version (string) — version of the work read; "" when not recorded.
- hash (string) — its content hash; "" when not recorded. *
- Returns:
- error — ErrNotFound for an observation or source that does not exist, or on database failure. *
- Example:
- err := kb.LinkObservationSourceAt(42, 1, "cited", "2nd ed", "sha256:ab12")
func (*KnowledgeBase) LinkProjectConcept ¶
func (kb *KnowledgeBase) LinkProjectConcept(projectID, conceptID int64) error
* LinkProjectConcept associates a project with a concept. Duplicate links are
- silently ignored. *
- Parameters:
- projectID (int64) — ID of the project.
- conceptID (int64) — ID of the concept. *
- Returns:
- error — ErrNotFound for a project or concept that does not exist, or on database failure. *
- Example:
- err := kb.LinkProjectConcept(projectID, conceptID)
func (*KnowledgeBase) LinkRecordConcept ¶ added in v0.0.6
func (kb *KnowledgeBase) LinkRecordConcept(recordID, conceptID int64) error
* LinkRecordConcept associates a record with a concept. Duplicate links are
- silently ignored. *
- Parameters:
- recordID (int64) — internal database id of the record (Record.ID, not RecordID).
- conceptID (int64) — ID of the concept. *
- Returns:
- error — on database failure. *
- Example:
- err := kb.LinkRecordConcept(recordID, conceptID)
func (*KnowledgeBase) LinkRecordSource ¶ added in v0.0.25
func (kb *KnowledgeBase) LinkRecordSource(recordID, sourceID int64, relationship, version, hash string) error
* LinkRecordSource records that a decision record cites a source (DR-0081
- item 3), as LinkDocumentSource does for a document. *
- Parameters:
- recordID (int64) — record primary key.
- sourceID (int64) — source primary key.
- relationship (string) — label; "" means "cited".
- version (string) — version of the work read; "" when not recorded.
- hash (string) — its content hash; "" when not recorded. *
- Returns:
- error — ErrNotFound for a record or source that does not exist, or on database failure. *
- Example:
- err := kb.LinkRecordSource(3, 1, "cited", "", "")
func (*KnowledgeBase) ListRecords ¶ added in v0.0.4
func (kb *KnowledgeBase) ListRecords(f RecordFilter) ([]Record, error)
* ListRecords returns the records matching a filter, oldest first, sorted by
- date and then record_id — never by record_id alone, since a correction can
- carry a lower id than the record it supersedes. *
- Parameters:
- f (RecordFilter) — the filter; zero-valued fields match anything. *
- Returns:
- []Record — matching records; empty when none match.
- error — on database failure. *
- Example:
- recs, err := kb.ListRecords(RecordFilter{Project: "clasm", Kind: "correction"})
- ws, err := kb.ListRecords(RecordFilter{Scope: "workspace"})
func (*KnowledgeBase) ListSources ¶
func (kb *KnowledgeBase) ListSources() ([]Source, error)
- ListSources returns all rows in the sources table, ordered by id. *
- Returns:
- []Source — all sources; empty slice when none exist.
- error — on database failure. *
- Example:
- sources, err := kb.ListSources()
func (*KnowledgeBase) MarkDocumentSectionStale ¶ added in v0.0.6
func (kb *KnowledgeBase) MarkDocumentSectionStale(id int64) error
* MarkDocumentSectionStale sets a section's summary_stale flag without
- touching its body or summary -- used on the gist row when any section of
- its document changes on re-ingest (design decision 10), since a
- whole-document gist describes the document as a whole. *
- Parameters:
- id (int64) — the section's internal id. *
- Returns:
- error — on database failure. *
- Example:
- err := kb.MarkDocumentSectionStale(gistSectionID)
func (*KnowledgeBase) MatchConceptNameCounts ¶ added in v0.0.10
func (kb *KnowledgeBase) MatchConceptNameCounts(text string) (map[string]int, error)
* MatchConceptNameCounts is MatchConceptNames with an occurrence count
- instead of a presence flag, for a caller that needs to threshold on
- frequency rather than just detect a mention — document ingest's
- density-based concept linking (TODO.md's MADR item) is the motivating
- caller: a single incidental mention is too weak a signal to auto-link,
- but several are not. *
- Parameters:
- text (string) — free text to search, e.g. a document section's body. *
- Returns:
- map[string]int — concept name to occurrence count; a concept with zero
- occurrences is absent from the map, not present at 0.
- error — on database failure. *
- Example:
- counts, err := kb.MatchConceptNameCounts(sectionBody)
- if counts["RAG"] > 1 { fmt.Println("link it") }
func (*KnowledgeBase) MatchConceptNames ¶ added in v0.0.6
func (kb *KnowledgeBase) MatchConceptNames(text string) ([]string, error)
* MatchConceptNames returns every known concept name that appears in text as
- a whole word, case-insensitively, including a name that begins or ends in
- punctuation such as C++ or .NET (see conceptNameMatches). Whole-word matching (not substring) is
- deliberate: a short concept name like "RAG" must not match inside an
- unrelated word like "storage". Concept names are otherwise free-form, so
- this compiles one small regex per concept per call rather than assuming
- any structure to exploit — call frequency here is "once per prompt," not a
- hot loop. *
- Parameters:
- text (string) — free text to search, e.g. a prompt. *
- Returns:
- []string — matched concept names, in Concepts()'s own order; nil when none.
- error — on database failure. *
- Example:
- names, err := kb.MatchConceptNames("how does chunking interact with RAG?")
func (*KnowledgeBase) ObservationByID ¶
func (kb *KnowledgeBase) ObservationByID(id int64) (*Observation, error)
- ObservationByID returns a single observation by its id. *
- Parameters:
- id (int64) — the observation's id. *
- Returns:
- *Observation — the matching observation.
- error — sql.ErrNoRows if no observation has that id, or on
- database failure. *
- Example:
- o, err := kb.ObservationByID(42)
- if err != nil {
- // not found or DB error
- }
func (*KnowledgeBase) ObservationConcepts ¶ added in v0.0.22
func (kb *KnowledgeBase) ObservationConcepts(observationID int64) ([]Concept, error)
* ObservationConcepts returns the concepts linked to one observation, in id
- order. An observation with no links, or one that does not exist, gives an
- empty list. *
- Parameters:
- observationID (int64) — the observation's id. *
- Returns:
- []Concept — the linked concepts.
- error — on database failure. *
- Example:
- cs, err := kb.ObservationConcepts(7)
func (*KnowledgeBase) ObservationRelationsFor ¶ added in v0.0.8
func (kb *KnowledgeBase) ObservationRelationsFor(id int64) ([]RelatedObservation, error)
* ObservationRelationsFor returns every relation touching an observation,
- described from that observation's point of view. Mirrors RelationsFor
- (records.go): an edge where it is the source is reported as stored; an
- edge where it is the target is inverted, so "supersedes" becomes
- "superseded_by". *
- Parameters:
- id (int64) — the observations table primary key. *
- Returns:
- []RelatedObservation — matching relations; empty when the observation has none.
- error — on database failure. *
- Example:
- rels, err := kb.ObservationRelationsFor(id)
- for _, rel := range rels {
- fmt.Printf("%s %d\n", rel.Relationship, rel.ObservationID)
- }
func (*KnowledgeBase) ObservationReviewQueue ¶ added in v0.0.30
func (kb *KnowledgeBase) ObservationReviewQueue(projectID int64) ([]Observation, error)
* ObservationReviewQueue returns the drafted observations awaiting review,
- oldest first. A draft that a newer observation supersedes is not queued: the
- newer one is what is left to review. *
- Parameters:
- projectID (int64) — scope to one project, or 0 for every project. *
- Returns:
- []Observation — drafted rows; nil when none.
- error — on database failure. *
- Example:
- queue, err := kb.ObservationReviewQueue(0)
func (*KnowledgeBase) ObservationSourceLinks ¶ added in v0.0.25
func (kb *KnowledgeBase) ObservationSourceLinks(observationID int64) ([]SourceLink, error)
* ObservationSourceLinks lists the sources an observation cites with the link's
- relationship, version and hash, ordered by source id. ObservationSources is
- the older call without the link columns. *
- Parameters:
- observationID (int64) — observation primary key. *
- Returns:
- []SourceLink — empty (not nil) when none.
- error — on database failure. *
- Example:
- links, err := kb.ObservationSourceLinks(42)
func (*KnowledgeBase) ObservationSources ¶
func (kb *KnowledgeBase) ObservationSources(observationID int64) ([]Source, error)
* ObservationSources returns all sources linked to the given observation id,
- including retraction state, ordered by source id. *
- Parameters:
- observationID (int64) — observation primary key. *
- Returns:
- []Source — linked sources; empty slice when none.
- error — on database failure. *
- Example:
- sources, err := kb.ObservationSources(42)
func (*KnowledgeBase) ObservationUsage ¶ added in v0.0.14
func (kb *KnowledgeBase) ObservationUsage(id int64) (ObservationUsage, error)
- ObservationUsage reports what depends on the observation, without changing anything. *
- Parameters:
- id (int64) — the observation's id. *
- Returns:
- ObservationUsage — the counts.
- error — ErrNotFound if there is no such observation, or on database failure. *
- Example:
- u, err := kb.ObservationUsage(7)
func (*KnowledgeBase) Observations ¶
func (kb *KnowledgeBase) Observations(projectID int64) ([]Observation, error)
- Observations returns all observations for a project, newest first. *
- Parameters:
- projectID (int64) — ID of the project to query. *
- Returns:
- []Observation — slice of matching rows; empty (not nil) if none exist.
- error — on database failure. *
- Example:
- obs, err := kb.Observations(1)
- for _, o := range obs {
- fmt.Printf("[%s] %s\n", o.Kind, o.Body)
- }
func (*KnowledgeBase) ObservationsByStatus ¶ added in v0.0.30
func (kb *KnowledgeBase) ObservationsByStatus(projectID int64, status string) ([]Observation, error)
* ObservationsByStatus returns a project's observations with the given
- status, newest first. Observations is this with "reviewed". A drafted
- observation that a newer one supersedes is not returned. *
- Parameters:
- projectID (int64) — ID of the project to query.
- status (string) — "reviewed", "drafted" or "all". *
- Returns:
- []Observation — matching rows; empty (not nil) if none.
- error — ErrInvalid for an unknown status, or on database failure. *
- Example:
- drafts, err := kb.ObservationsByStatus(1, "drafted")
func (*KnowledgeBase) Path ¶
func (kb *KnowledgeBase) Path() string
Path returns the absolute path of the open knowledge base file.
func (*KnowledgeBase) ProjectByName ¶
func (kb *KnowledgeBase) ProjectByName(name string) (*Project, error)
- ProjectByName returns the project with the given name, or nil if not found. *
- Parameters:
- name (string) — exact project name. *
- Returns:
- *Project — the matching project, or nil.
- error — on database failure. *
- Example:
- p, err := kb.ProjectByName("harvey")
func (*KnowledgeBase) ProjectConcepts ¶
func (kb *KnowledgeBase) ProjectConcepts(projectID int64) ([]Concept, error)
- ProjectConcepts returns all concepts linked to a project, ordered by name. *
- Parameters:
- projectID (int64) — ID of the project. *
- Returns:
- []Concept — linked concepts; empty (not nil) if none.
- error — on database failure. *
- Example:
- concepts, err := kb.ProjectConcepts(1)
func (*KnowledgeBase) ProjectForDir ¶ added in v0.0.17
func (kb *KnowledgeBase) ProjectForDir(root, dir string) (string, error)
* ProjectForDir names the project a directory belongs to (DR-0058): the
- directory sits under agents/projects/<name>/, or under a repository
- directory <name>/ at the workspace root where agents/projects/<name>/ also
- exists. The name must be a project the database knows; a directory for which
- no project row exists, a directory outside the root, and the root, agents/ and
- agents/decisions/ themselves all give "". Symbolic links are resolved first,
- so a link into a project counts as the project. *
- Parameters:
- root (string) — the workspace root.
- dir (string) — the directory to place, normally the working directory. *
- Returns:
- string — the project name, or "" when dir belongs to no known project.
- error — on database failure. *
- Example:
- name, err := kb.ProjectForDir("/home/me/Laboratory", "/home/me/Laboratory/harvey/cmd")
- // name == "harvey"
func (*KnowledgeBase) ProjectUsage ¶ added in v0.0.14
func (kb *KnowledgeBase) ProjectUsage(name string) (ProjectUsage, error)
- ProjectUsage reports what depends on the named project, without changing anything. *
- Parameters:
- name (string) — the project's name, matched exactly. *
- Returns:
- ProjectUsage — the counts.
- error — ErrNotFound if there is no such project, or on database failure. *
- Example:
- u, err := kb.ProjectUsage("stray")
func (*KnowledgeBase) Projects ¶
func (kb *KnowledgeBase) Projects() ([]Project, error)
- Projects returns all projects ordered by creation date. *
- Returns:
- []Project — slice of all project rows; empty (not nil) if none exist.
- error — on database failure. *
- Example:
- projects, err := kb.Projects()
- for _, p := range projects {
- fmt.Println(p.Name, p.Status)
- }
func (*KnowledgeBase) PromoteDocumentSummary ¶ added in v0.0.6
func (kb *KnowledgeBase) PromoteDocumentSummary(sectionID int64) error
* PromoteDocumentSummary promotes a drafted summary to reviewed (design
- decision 7) -- the only human action that makes a summary trusted. This
- is also the only point a summary is indexed into kb_fts (decision 8): a
- section's raw body is never indexed, only its reviewed summary, and only
- once it is reviewed. *
- Parameters:
- sectionID (int64) — the document_sections row to promote. *
- Returns:
- error — if the section does not exist, is not currently "drafted", or
- on database failure. *
- Example:
- err := kb.PromoteDocumentSummary(sectionID)
func (*KnowledgeBase) PromoteObservation ¶ added in v0.0.30
func (kb *KnowledgeBase) PromoteObservation(id int64) error
* PromoteObservation makes a drafted observation reviewed and indexes it, so
- search and recall find it. It has no terminal rule (DR-0070); the command
- `kb observation review promote` adds that. *
- Parameters:
- id (int64) — the observation to promote. *
- Returns:
- error — ErrNotFound for an unknown id, ErrConflict when it is not drafted. *
- Example:
- err := kb.PromoteObservation(12)
func (*KnowledgeBase) ProposeFrontmatter ¶ added in v0.0.12
func (kb *KnowledgeBase) ProposeFrontmatter(path string, raw []byte, prov Provenance) (FrontmatterResult, error)
* ProposeFrontmatter is the read-only half of `kb document frontmatter`: it
- reports what it would propose for a file's title, author, dateCreated,
- dateModified and keywords, deriving signals from the file's own prose and
- from prov. It writes nothing, to the file or the database. *
- Parameters:
- path (string) — the file's path, used for provenance lookups and to
- find the document's project in the knowledge base.
- raw ([]byte) — the file's current bytes; the caller reads them.
- prov (Provenance) — the source of authorship and dates; nil means GitProvenance. *
- Returns:
- FrontmatterResult — the report, with nothing accepted.
- error — on unparseable frontmatter or a database failure. *
- Example:
- raw, _ := os.ReadFile("a.md")
- res, err := kb.ProposeFrontmatter("a.md", raw, nil)
func (*KnowledgeBase) RecallByConceptNames ¶ added in v0.0.6
func (kb *KnowledgeBase) RecallByConceptNames(names []string, limit int) ([]ConceptMatch, error)
* RecallByConceptNames returns observations and records linked to any of the
- given concept names, merged into one list ranked by how many of the
- queried concepts each entity matches (descending), then by recency
- (descending), truncated to limit. *
- A name matching no concept is silently skipped rather than erroring — a
- prompt mentioning nothing tagged is a normal outcome, not a failure — and
- no concept is ever created as a side effect of calling this (unlike
- ResolveConceptName, used at ingest time). The query is not scoped to any
- one project: ProjectID is reported on every result so a caller can filter
- or weight afterward. *
- Parameters:
- names ([]string) — concept names to match against, as returned by
- MatchConceptNames or supplied directly.
- limit (int) — maximum results to return; non-positive means no cap. *
- Returns:
- []ConceptMatch — ranked matches; nil when none.
- error — on database failure. *
- Example:
- matches, err := kb.RecallByConceptNames([]string{"chunking", "RAG"}, 5)
func (*KnowledgeBase) RecallByNames ¶ added in v0.0.15
func (kb *KnowledgeBase) RecallByNames(names []string, limit int, project string) (TextRecall, error)
* RecallByNames is RecallByText without the matching step: the names are used
- directly, case-insensitively, and one that matches no concept is skipped.
- TextRecall.Matched holds the canonical spelling of those that exist. *
- Parameters:
- names ([]string) — concept names to recall by.
- limit (int) — maximum hits; non-positive means no cap.
- project (string) — restrict hits to this project by name; "" for all. *
- Returns:
- TextRecall — the concepts found and ranked hits.
- error — ErrNotFound for an unknown project, or a database failure. *
- Example:
- r, err := kb.RecallByNames([]string{"toast"}, 10, "")
func (*KnowledgeBase) RecallByText ¶ added in v0.0.15
func (kb *KnowledgeBase) RecallByText(text string, limit int, project string) (TextRecall, error)
* RecallByText finds the concepts named in text (MatchConceptNames), then
- returns the observations, records and document sections linked to them,
- with the concepts each one matched, so a caller can see why it came back. *
- This is the richer sibling of RecallByConceptNames, which covers the same
- observations, records and document sections and ranks the same way (matched
- concepts descending, then recency), and which is unchanged. RecallByText adds
- a project filter, the project name and the matched concepts on every hit,
- and the list of linked projects, so a caller can see why each hit came back. *
- Text that matches no concept is a normal outcome, not an error: the result
- is empty. Nothing is ever created. *
- Parameters:
- text (string) — free text, such as a prompt.
- limit (int) — maximum hits; non-positive means no cap.
- project (string) — restrict hits to this project by name; "" for all. An unknown
- name is ErrNotFound. Workspace-tier records are excluded when set. *
- Returns:
- TextRecall — matched concept names and ranked hits.
- error — ErrNotFound for an unknown project, or a database failure. *
- Example:
- r, err := kb.RecallByText("chunking and RAG", 5, "harvey")
func (*KnowledgeBase) RecordByID ¶ added in v0.0.4
func (kb *KnowledgeBase) RecordByID(id int64) (*Record, error)
- RecordByID returns the record with the given primary key. *
- Parameters:
- id (int64) — the records table primary key. *
- Returns:
- *Record — the record.
- error — sql.ErrNoRows when not found; other errors on database failure. *
- Example:
- r, err := kb.RecordByID(id)
- fmt.Println(r.Title)
func (*KnowledgeBase) RecordByIdentity ¶ added in v0.0.4
func (kb *KnowledgeBase) RecordByIdentity(workspace string, projectID int64, scope, recordID string) (*Record, error)
* RecordByIdentity returns the record with the given identity — the
- (workspace, project, scope, record_id) tuple the identity index is built
- over. This is how a reference in a record file is resolved to a row, since a
- file cites "0160" or "clasm:0160", never a primary key. *
- The workspace is explicit rather than taken from the database, because
- ingest's --root may name a workspace other than the one the database sits
- in. Pass kb.Workspace() for the database's own. *
- Parameters:
- workspace (string) — the workspace name, e.g. "WorkLab".
- projectID (int64) — the owning project; pass 0 for the workspace tier.
- scope (string) — "project" or "workspace".
- recordID (string) — zero-padded record number, e.g. "0160". *
- Returns:
- *Record — the record.
- error — sql.ErrNoRows when no such record exists. *
- Example:
- r, err := kb.RecordByIdentity(kb.Workspace(), projectID, "project", "0160")
- ws, err := kb.RecordByIdentity("WorkLab", 0, "workspace", "0001")
func (*KnowledgeBase) RecordConcepts ¶ added in v0.0.6
func (kb *KnowledgeBase) RecordConcepts(recordID int64) ([]Concept, error)
* RecordConcepts returns all concepts linked to the given record id, ordered
- by concept id. *
- Parameters:
- recordID (int64) — internal database id of the record (Record.ID, not RecordID). *
- Returns:
- []Concept — linked concepts; nil when none.
- error — on database failure. *
- Example:
- concepts, err := kb.RecordConcepts(recID)
func (*KnowledgeBase) RecordFuzzyReport ¶ added in v0.0.15
func (kb *KnowledgeBase) RecordFuzzyReport(rf *RecordFile, explicit []string) ([]RecordFuzzyFinding, error)
* RecordFuzzyReport finds, in a decision record's body, near-miss spellings
- of known concepts that the record does not already link. It writes nothing. *
- It reuses the document matcher and its eligibility rules (FuzzyEligible).
- The explicit-concept bypass is narrowed for records: FuzzyEligible would
- keep every token within FuzzyMatchConceptNames's ceiling of a named
- concept, which for a short concept is most short common words, so a named
- concept is widened only to tokens that contain its name (detoast,
- toasting) plus what the ordinary rules already admit. Two more things differ from documents
- (DR-0052 item 7). Only the body is searched, so frontmatter text such as
- `tags: [toast]` never matches. And a concept is skipped only when the
- record already links it, in `tags:` or as a [[wikilink]], not when its
- plain name appears in prose, since prose links nothing. *
- Parameters:
- rf (*RecordFile) — the parsed record.
- explicit ([]string) — concept names to force, bypassing the length and distance
- rules for exactly these; nil for the ordinary rules. *
- Returns:
- []RecordFuzzyFinding — one per unlinked concept with at least one eligible near-miss,
- ordered by first appearance; nil when none.
- error — on database failure. *
- Example:
- rf, _ := knowledge.ParseRecordFile("decisions/0013-x.md")
- findings, err := kb.RecordFuzzyReport(rf, nil)
func (*KnowledgeBase) RecordSources ¶ added in v0.0.25
func (kb *KnowledgeBase) RecordSources(recordID int64) ([]SourceLink, error)
- RecordSources lists the sources a decision record cites, ordered by source id. *
- Parameters:
- recordID (int64) — record primary key. *
- Returns:
- []SourceLink — empty (not nil) when none.
- error — on database failure. *
- Example:
- links, err := kb.RecordSources(3)
func (*KnowledgeBase) RecordUsage ¶ added in v0.0.14
func (kb *KnowledgeBase) RecordUsage(id int64) (RecordUsage, error)
- RecordUsage reports what a record row is linked to, without changing anything. *
- Parameters:
- id (int64) — the record row's id. *
- Returns:
- RecordUsage — the counts and the stored path.
- error — ErrNotFound if there is no such record, or on database failure. *
- Example:
- u, err := kb.RecordUsage(12)
func (*KnowledgeBase) RecordsByProject ¶ added in v0.0.4
func (kb *KnowledgeBase) RecordsByProject(projectID int64) ([]Record, error)
* RecordsByProject returns every record belonging to a project, oldest
- first, sorted by date and then record_id. *
- The sort matters. Ids are identity, not chronology: within a single date
- real logs are inconsistently ordered, so a correction can carry a lower id
- than the record it supersedes — clasm DR-0159 supersedes DR-0160. Sorting on
- record_id alone would put them in the wrong order. *
- Parameters:
- projectID (int64) — the owning project; pass 0 for workspace-tier records. *
- Returns:
- []Record — matching records; empty when none exist.
- error — on database failure. *
- Example:
- recs, err := kb.RecordsByProject(pid)
- workspace, err := kb.RecordsByProject(0)
func (*KnowledgeBase) RecordsByRecordID ¶ added in v0.0.4
func (kb *KnowledgeBase) RecordsByRecordID(recordID string) ([]Record, error)
* RecordsByRecordID returns every record carrying the given id, across all
- projects and both tiers. An id alone is not an identity — two projects may
- each have a DR-0001 — so callers resolving a bare id use this to detect the
- ambiguity rather than silently picking one. *
- Parameters:
- recordID (string) — zero-padded record number, e.g. "0001". *
- Returns:
- []Record — every match; empty when the id is unknown.
- error — on database failure. *
- Example:
- matches, err := kb.RecordsByRecordID("0001")
- if len(matches) > 1 { // ambiguous, ask the caller to qualify it }
func (*KnowledgeBase) RecordsUnderPath ¶ added in v0.0.4
func (kb *KnowledgeBase) RecordsUnderPath(prefix string) ([]Record, error)
* RecordsUnderPath returns every record whose stored path begins with
- prefix, oldest first. Ingest uses it to report records whose file has
- vanished from disk without deleting them. *
- Parameters:
- prefix (string) — a path prefix, relative to the workspace root. *
- Returns:
- []Record — matching records; empty when none match.
- error — on database failure. *
- Example:
- recs, err := kb.RecordsUnderPath("clasm/decisions")
func (*KnowledgeBase) RelationsFor ¶ added in v0.0.4
func (kb *KnowledgeBase) RelationsFor(id int64) ([]RelatedRecord, error)
* RelationsFor returns every relation touching a record, described from that
- record's point of view. Edges where it is the source are reported as stored;
- edges where it is the target are inverted, so "supersedes" becomes
- "superseded_by". A relates_to edge is symmetric and reads the same from
- either end. *
- Parameters:
- id (int64) — the records table primary key. *
- Returns:
- []RelatedRecord — matching relations; empty when the record has none.
- error — on database failure. *
- Example:
- rels, err := kb.RelationsFor(id)
- for _, rel := range rels {
- fmt.Printf("%s %d\n", rel.Relationship, rel.RecordID)
- }
func (*KnowledgeBase) RemoveRecordRelation ¶ added in v0.0.31
func (kb *KnowledgeBase) RemoveRecordRelation(fromID, toID int64, relationship string) (bool, error)
* RemoveRecordRelation deletes one relation a record declares, and reports
- whether there was one. A relates_to edge is symmetric, so it is removed whichever
- of the two records declared it. *
- Parameters:
- fromID (int64) — the record that declares the relation
- toID (int64) — the record it points at
- relationship (string) — "supersedes" or "relates_to" *
- Returns:
- bool — true when a row was deleted
- error — a database error *
- Example:
- removed, err := kb.RemoveRecordRelation(a.ID, b.ID, "relates_to")
func (*KnowledgeBase) RemoveSource ¶
func (kb *KnowledgeBase) RemoveSource(id int64) error
* RemoveSource deletes the source with the given id. Returns an error if the
- source is linked to any observations. *
- Parameters:
- id (int64) — source primary key. *
- Returns:
- error — ErrInUse if the source is linked, ErrNotFound if there is no such source. *
- Example:
- err := kb.RemoveSource(1) // fails if linked
func (*KnowledgeBase) RenameConcept ¶ added in v0.0.9
func (kb *KnowledgeBase) RenameConcept(old, new string) error
* RenameConcept changes a concept's name, refreshing its kb_fts row via
- refreshConceptFTS. Unlike RenameProject, nothing refuses this: every
- reference to a concept (record_concepts, observation_concepts,
- project_concepts, document_section_concepts) is a foreign key to
- concepts.id, never a name matched from an external file, so a concept has
- no corpus to desync — see DR-0024. *
- Parameters:
- old (string) — the concept's current name.
- new (string) — the replacement name. *
- Returns:
- error — if old does not exist, new is blank or already names another concept, or on
- database failure. *
- Example:
- err := kb.RenameConcept("wal-mdoe", "wal-mode")
func (*KnowledgeBase) RenameProject ¶ added in v0.0.9
func (kb *KnowledgeBase) RenameProject(old, new string) error
* RenameProject changes a project's name, refreshing its kb_fts row via the
- same refreshProjectFTS a description correction already uses. Refuses
- outright when the project owns any records: a decision record's project:
- frontmatter has to match projects.name, and kb ingest resolves that field
- by name on every run, so a rename with no corresponding rewrite of the
- corpus's files makes the next ingest mint a phantom project under the old
- name and duplicate every record under it — reproduced and recorded in
- DR-0024. Rewriting a corpus automatically is out of scope here; refusing
- is the safe default until that lands. *
- Parameters:
- old (string) — the project's current name.
- new (string) — the replacement name. *
- Returns:
- error — if old does not exist, new is blank or already names another project, the
- project owns any records, or on database failure. *
- Example:
- err := kb.RenameProject("caltechcampuspubs_static", "ep3StaticSite")
func (*KnowledgeBase) RenameProjectRow ¶ added in v0.0.10
func (kb *KnowledgeBase) RenameProjectRow(old, new string) error
* RenameProjectRow renames a project's row and refreshes its kb_fts entry,
- exactly like RenameProject, but skips the records-owning guard. It exists
- for a caller that has already rewritten every owned record's project:
- frontmatter on disk itself — cmd/kb's `kb project rename` orchestration,
- per DR-0026 — and must therefore run only after that corpus rewrite is
- confirmed complete, never on its own against a project with records whose
- files have not been touched: that is exactly the corruption RenameProject
- refuses to cause. *
- Parameters:
- old (string) — the project's current name.
- new (string) — the replacement name. *
- Returns:
- error — if old does not exist, new is blank or already names another project, or on
- database failure. *
- Example:
- err := kb.RenameProjectRow("caltechcampuspubs_static", "ep3StaticSite")
func (*KnowledgeBase) ResolveConceptName ¶ added in v0.0.6
func (kb *KnowledgeBase) ResolveConceptName(name string) (int64, error)
* ResolveConceptName finds an existing concept whose name matches name
- case-insensitively, or creates one with name exactly as given when none
- exists. Intended for concept names extracted from free text (inline
- [[wikilink]] tags, frontmatter Tags lists), where capitalization is often
- an artifact of sentence position rather than a deliberate distinction —
- unlike AddConcept/kb concept add, which stays exact-match since a human
- typing a concept name at the CLI is a deliberate act. The casing of
- whichever mention is resolved first becomes canonical for every later
- case-variant. *
- Parameters:
- name (string) — concept name as encountered in text. *
- Returns:
- int64 — ID of the matching or newly created concept.
- error — if name is blank, or on database failure. *
- Example:
- id, err := kb.ResolveConceptName("computer")
func (*KnowledgeBase) ResolveRef ¶ added in v0.0.17
func (kb *KnowledgeBase) ResolveRef(ref Ref, workspace string) (*Record, error)
* ResolveRef finds the record a reference names. A qualified reference's scope
- is, in order: "workspace" (any case), the workspace tier; an exact project
- name; the workspace's own directory name (any case), as an alias for the
- workspace tier. A project therefore wins over the alias, and cannot be
- shadowed by the directory it sits in. A bare id resolves only when exactly one
- tier holds it; otherwise the result is an *AmbiguousRefError. Only records of
- the named workspace are considered. *
- Parameters:
- ref (Ref) — the reference, from ParseRef.
- workspace (string) — the workspace's name as records are stamped with it,
- which is the base name of its root; "" means this
- database's own. *
- Returns:
- *Record — the record.
- error — matching ErrNotFound when the scope is unknown or the tier holds
- no such id, or *AmbiguousRefError (matching ErrInvalid) for an
- ambiguous bare id. *
- Example:
- ref, _ := knowledge.ParseRef("clasm/DR-0178")
- rec, err := kb.ResolveRef(ref, "")
func (*KnowledgeBase) RetractSource ¶
func (kb *KnowledgeBase) RetractSource(id int64, note string) error
* RetractSource sets retracted=1 and records a retraction note on the source
- with the given id. *
- Parameters:
- id (int64) — source primary key.
- note (string) — free-text retraction note. *
- Returns:
- error — ErrNotFound if there is no such source, or on database failure. *
- Example:
- err := kb.RetractSource(1, "Retracted 2026-07-01 by publisher")
func (*KnowledgeBase) Search ¶
func (kb *KnowledgeBase) Search(term string) ([]KBSearchResult, error)
* Search performs a full-text search across observations, projects, and concepts
- using the FTS5 index. Results are ranked by relevance (best match first).
- Returns an error wrapping ErrFTSUnavailable when the FTS index is not present. *
- The term uses standard FTS5 query syntax: multiple words are ANDed, phrases
- can be quoted ("WAL mode"), and prefix search is supported (docker*). A term
- that is not valid query syntax (a hyphenated name like map-reduce, a version
- like v0.0.11, an unbalanced quote) is searched as a literal phrase instead of
- failing. *
- Parameters:
- term (string) — FTS5 query term. *
- Returns:
- []KBSearchResult — ranked results; nil if none found.
- error — on query failure or when FTS is unavailable. *
- Example:
- results, err := kb.Search("docker")
- for _, r := range results {
- fmt.Printf("[%-10s] %s — %s\n", r.Kind, r.Label, r.Snippet)
- }
func (*KnowledgeBase) SearchScoped ¶ added in v0.0.22
func (kb *KnowledgeBase) SearchScoped(term string, scope SearchScope) (*ScopedSearchResult, error)
* SearchScoped performs the full-text search of Search, restricted to a scope
- and to kinds, with the restriction applied in the query so a limit never
- hides a match in scope behind a better-ranked one outside it. It returns the
- total and a count per kind before the limit. *
- With an empty scope it is the global search. A project scope covers that
- project's observations, records, documents' reviewed summaries and concepts
- (the union of those tagged on the project, on its observations and on its
- records); the workspace tier covers workspace-tier records, the summaries of
- documents with no project, and concepts linked to workspace-tier records.
- "projects" is valid at the global scope only, and observations have no
- workspace tier. *
- Parameters:
- term (string) — FTS5 query; a term that is not valid syntax is searched as a phrase, as Search does.
- scope (SearchScope) — where to look. *
- Returns:
- *ScopedSearchResult — the results, total and counts; never nil without an error.
- error — ErrInvalid for an unknown kind, a negative limit, or Project with Workspace;
- ErrNotFound for an unknown project; ErrNoMembers when every requested kind
- is impossible in the scope; a database failure otherwise. *
- Example:
- r, err := kb.SearchScoped("exit codes", knowledge.SearchScope{Project: "harvey", Kinds: []string{"records"}})
func (*KnowledgeBase) SemanticSearch ¶ added in v0.0.29
func (kb *KnowledgeBase) SemanticSearch(v *Vectors, e Embedder, query string, opts SemanticOptions) (*SemanticResult, error)
* SemanticSearch ranks the indexed rows by how close their best chunk is to
- the query, by cosine similarity, and returns those at or above the cutoff.
- Nothing close is an empty result, not an error. It only reads: rows with no
- chunks yet are counted in Unindexed and never indexed here. The index must
- have been built by the same model as e. *
- Parameters:
- v (*Vectors) — the open sidecar
- e (Embedder) — the model that embeds the query; it must be the one v was built with
- query (string) — plain text; no search syntax applies
- opts (SemanticOptions) — scope, cutoff and limit *
- Returns:
- *SemanticResult — the hits, the total before the limit, and the unindexed count
- error — ErrInvalid for a blank query, a cutoff outside -1 to 1 or a kind that
- is not embedded; ErrNotFound for an unknown project; ErrModelMismatch; the
- embedder's error; a database error *
- Example:
- r, err := kb.SemanticSearch(v, embedder, "why was the compiler licence chosen", knowledge.SemanticOptions{})
func (*KnowledgeBase) SetConceptKind ¶ added in v0.0.24
func (kb *KnowledgeBase) SetConceptKind(name, kind string) error
* SetConceptKind sets what an existing concept names, and advances its
- updated_at so merge and import carry the change (DR-0025). Adding the
- concept again, from prose or `kb concept add`, never resets its kind. *
- Parameters:
- name (string) — the concept's exact name.
- kind (string) — one of ConceptKinds. *
- Returns:
- error — ErrInvalid for a kind outside the vocabulary, ErrNotFound when
- no concept has that name, or a database failure. *
- Example:
- err := kb.SetConceptKind("the-long-fire/Anna", "character")
func (*KnowledgeBase) SetProjectDescription ¶ added in v0.0.5
func (kb *KnowledgeBase) SetProjectDescription(name, description string) error
* SetProjectDescription replaces an existing project's description and
- reindexes it for search. A description is grounding context — it is what
- ProjectByName reports and what Search returns as a snippet — so this is
- how a description that has gone stale gets corrected without hand-written
- SQL against the database. *
- An empty description is honoured rather than rejected: clearing one here is
- explicit, unlike on AddConcept, where an omitted description is far more
- likely to be an accident than an instruction. *
- updated_at is touched. Nothing reads it across machines yet — MergeKnowledgeBases
- and ImportJSONL both resolve a conflict in favour of the row already present,
- without consulting it — but recording it now is what makes a later
- last-writer-wins reconciliation possible at all. *
- Parameters:
- name (string) — the project's unique name.
- description (string) — the replacement description; "" clears it. *
- Returns:
- error — if the project does not exist, or on database failure. *
- Example:
- err := kb.SetProjectDescription("dev-process", "names DESIGN_REVIEW_PLAN_IMPLEMENT.md")
func (*KnowledgeBase) SetProjectStatus ¶ added in v0.0.2
func (kb *KnowledgeBase) SetProjectStatus(name, status string) error
* SetProjectStatus updates an existing project's status. status must be
- one of concept, active, paused, or concluded. *
- Parameters:
- name (string) — the project's unique name.
- status (string) — one of concept, active, paused, concluded. *
- Returns:
- error — if status is invalid, the project does not exist, or on
- database failure. *
- Example:
- err := kb.SetProjectStatus("harvey", "paused")
func (*KnowledgeBase) ShowSource ¶
func (kb *KnowledgeBase) ShowSource(id int64) (*Source, error)
* ShowSource returns the full source row for the given id, or an error if
- not found. *
- Parameters:
- id (int64) — source primary key. *
- Returns:
- *Source — the source row.
- error — sql.ErrNoRows when not found; other errors on db failure. *
- Example:
- s, err := kb.ShowSource(1)
func (*KnowledgeBase) SourceCitations ¶ added in v0.0.25
func (kb *KnowledgeBase) SourceCitations(id int64) (SourceCitations, error)
- SourceCitations reports what cites a source, without changing anything. *
- Parameters:
- id (int64) — source primary key. *
- Returns:
- SourceCitations — the counts per kind.
- error — on database failure. *
- Example:
- c, err := kb.SourceCitations(1)
func (*KnowledgeBase) SourceObservationCount ¶ added in v0.0.22
func (kb *KnowledgeBase) SourceObservationCount(id int64) (int, error)
* SourceObservationCount returns how many observations are linked to a source,
- which is what stops RemoveSource: a caller can say so before asking for a
- delete. *
- Parameters:
- id (int64) — source primary key. *
- Returns:
- int — the number of observation_sources rows for the source.
- error — on database failure. *
- Example:
- n, err := kb.SourceObservationCount(1)
func (*KnowledgeBase) Stats ¶ added in v0.0.23
func (kb *KnowledgeBase) Stats() (Stats, error)
- Stats reports the shape of the database without changing anything. *
- Returns:
- Stats — the counts, checks and per-project lines.
- error — a database failure. *
- Example:
- s, err := kb.Stats()
- if err == nil { fmt.Println(len(s.Projects), "projects") }
func (*KnowledgeBase) StoryCheck ¶ added in v0.0.24
func (kb *KnowledgeBase) StoryCheck(projectID int64) ([]StoryFinding, error)
* StoryCheck reports continuity problems in a project's story (DR-0075
- item 10, DR-0079), changing nothing: *
- - missing-file: a Fountain document whose file cannot be read, so its
- scene numbers could not be checked.
- - unnumbered-scene: a Fountain scene with no scene number, which therefore
- has no event.
- - scene-comment-no-id, scene-id-disagreement, scene-id-repeated,
- scene-comment-syntax, fountain-style-heading, front-matter-ignored: a
- Markdown file's scenes are not what they seem to say (DR-0082): a story
- comment on a heading with no id, a heading {#id} and a comment id that
- differ, a scene id used twice, an unknown key or a word with no "=" in a
- comment, a heading ending like a Fountain "#12A#" (which is text, not an
- id), and a front matter event or story_time the file's scene ids make
- moot.
- - duplicate-label: one label on several events.
- - unparseable-time, unresolved-time: a story_time that is not understood, or
- a relative one whose anchor is missing, ambiguous, undated or cyclic.
- - unknown-reference: a foreshadows, pays_off or precedes name that names no
- single event.
- - contradiction: a declared order (before:, after:, precedes) that the
- events' own dates contradict.
- - cycle: events whose declared order cannot be satisfied.
- - two-places: a character in two different places at the same day or
- ordinal; wider intervals overlap innocently and are not flagged.
- - foreshadow-order: within one document, a scene that foreshadows an
- earlier scene, or pays off a later one. Across documents the reading
- order is not known and nothing is said.
- - knowledge-before-learned: a scene says a character knows a fact, and every
- scene where that character learns it is provably later in story order. A
- knows with no learns anywhere is backstory and is not reported, nor is one
- whose learning is unordered against it (DR-0083).
- - unknown-fact: two different facts, each of at least 12 characters, that are
- one edit apart, which is probably one fact typed twice. Reported, never
- merged.
- - fact-number-differs: the same, where the one edit is a digit ("41 coins",
- "42 coins"): two figures that may be two facts or a continuity slip, not a
- typo. Reported, never merged.
- - late-source: a document cites a source with the relationship "evidence"
- whose published_date is after the end of one of the document's events. A
- source with no date, or an event with no calendar interval, gives nothing. *
- Parameters:
- projectID (int64) — the project. *
- Returns:
- []StoryFinding — ordered by kind, document and message; empty (not nil)
- when nothing is wrong.
- error — on database failure. *
- Example:
- fs, err := kb.StoryCheck(pid)
func (*KnowledgeBase) StoryEvents ¶ added in v0.0.24
func (kb *KnowledgeBase) StoryEvents(projectID int64) ([]StoryEvent, error)
* StoryEvents returns a project's story events in document and narrative
- order (DR-0079). *
- Parameters:
- projectID (int64) — the project, or 0 for every project. *
- Returns:
- []StoryEvent — the events; empty (not nil) if none.
- error — on database failure. *
- Example:
- evs, err := kb.StoryEvents(pid)
func (*KnowledgeBase) StoryTimeline ¶ added in v0.0.24
func (kb *KnowledgeBase) StoryTimeline(projectID int64, narrative bool) ([]TimelineEntry, error)
- StoryTimeline lists a project's story events (DR-0075 item 9). *
- In story order (narrative false) an event comes after every event provably
- before it, by non-overlapping intervals or by a before:/after: relation or a
- precedes list; ties go to narrative order. Where two neighbours' order is not
- established the later is marked Unordered. Events with no interval and no
- relation come last, marked Undated. In narrative order (narrative true) events
- are listed by document and position in it, which is the order a reader meets
- them, with the story time alongside. *
- Parameters:
- projectID (int64) — the project.
- narrative (bool) — list in reading order instead of story order. *
- Returns:
- []TimelineEntry — one per event; empty (not nil) if none.
- error — on database failure. *
- Example:
- es, err := kb.StoryTimeline(pid, false)
func (*KnowledgeBase) SuggestConcepts ¶ added in v0.0.12
func (kb *KnowledgeBase) SuggestConcepts(project string, limit int) (ConceptSuggestions, error)
* SuggestConcepts is a read-only scan of every record body and every
- document section body (gist rows are ignored), optionally scoped to one
- project, that returns candidate new concepts ranked by corpus-wide
- distinctiveness. It never writes anything: a suggestion becomes a real
- concept only when a human adds it (`kb concept add`), the same mechanical-
- signal-then-human-curates pattern density-linking and document summary
- review already use. Spelling variants of one term are merged before scoring,
- and a term that is a near-miss of an already-known concept is excluded from
- candidacy and reported in NearExisting instead. *
- Parameters:
- project (string) — a project name to scope the scan to, or "" for the
- whole knowledge base.
- limit (int) — cap on Candidates; zero or negative means no cap. *
- Returns:
- ConceptSuggestions — the candidates (best first) and the near-existing
- pairs. NearExisting is not capped by limit.
- error — for an unknown project, or on database failure. *
- Example:
- s, err := kb.SuggestConcepts("harvey", 20)
func (*KnowledgeBase) Summary ¶
func (kb *KnowledgeBase) Summary() (string, error)
* Summary returns a human-readable text summary of all projects and their
- recent observations, suitable for printing in the Harvey REPL. *
- Returns:
- string — formatted multi-line summary.
- error — on database failure. *
- Example:
- s, err := kb.Summary()
- fmt.Print(s)
func (*KnowledgeBase) SyncDocumentSources ¶ added in v0.0.25
func (kb *KnowledgeBase) SyncDocumentSources(documentID int64, refs []CitedRef) (int, []string, error)
* SyncDocumentSources makes a document's `cited` links match the sources its
- file lists (DR-0081 item 4): each entry is resolved to a source (an existing
- identifier or id is linked; an unknown DOI or URL is made a source titled by
- its identifier), links the file no longer lists are removed, and links with
- any other relationship are left alone. It is run on every ingest of a file
- with a `sources:` key, a skipped one included, as story events are. *
- Parameters:
- documentID (int64) — the document.
- refs ([]CitedRef) — the entries, from ParseSourceRefs. *
- Returns:
- int — how many sources the document now cites through its file.
- []string — a message for each entry that could not be resolved
- (a source:ID that names no source).
- error — on database failure. *
- Example:
- refs, _ := knowledge.ParseSourceRefs([]string{"10.1234/sparql"})
- n, warnings, err := kb.SyncDocumentSources(docID, refs)
func (*KnowledgeBase) SyncRecordSources ¶ added in v0.0.25
* SyncRecordSources is SyncDocumentSources for a decision record's `sources:`
- front matter. *
- Parameters:
- recordID (int64) — the record.
- refs ([]CitedRef) — the entries, from ParseSourceRefs. *
- Returns:
- int — how many sources the record now cites through its file.
- []string — a message for each entry that could not be resolved.
- error — on database failure. *
- Example:
- n, warnings, err := kb.SyncRecordSources(recID, refs)
func (*KnowledgeBase) UnlinkDocumentSource ¶ added in v0.0.25
func (kb *KnowledgeBase) UnlinkDocumentSource(documentID, sourceID int64) error
* UnlinkDocumentSource removes the link between a document and a source it
- cites. Removing a link that does not exist is ErrNotFound. *
- Parameters:
- documentID (int64) — the document's id.
- sourceID (int64) — the source's id. *
- Returns:
- error — ErrNotFound for a missing document, source or link; or on database failure. *
- Example:
- err := kb.UnlinkDocumentSource(7, 2)
func (*KnowledgeBase) UnlinkObservationConcept ¶ added in v0.0.14
func (kb *KnowledgeBase) UnlinkObservationConcept(observationID int64, concept string) error
* UnlinkObservationConcept removes the link between an observation and a concept. The
- concept name matches exactly. Removing a link that does not exist is ErrNotFound. *
- Parameters:
- observationID (int64) — the observation's id.
- concept (string) — the concept's name. *
- Returns:
- error — ErrNotFound for a missing observation, concept or link; or on database failure. *
- Example:
- err := kb.UnlinkObservationConcept(7, "RAG")
func (*KnowledgeBase) UnlinkObservationSource ¶ added in v0.0.14
func (kb *KnowledgeBase) UnlinkObservationSource(observationID, sourceID int64) error
* UnlinkObservationSource removes the link between an observation and a source.
- Removing a link that does not exist is ErrNotFound. *
- Parameters:
- observationID (int64) — the observation's id.
- sourceID (int64) — the source's id. *
- Returns:
- error — ErrNotFound for a missing observation, source or link; or on database failure. *
- Example:
- err := kb.UnlinkObservationSource(7, 2)
func (*KnowledgeBase) UnlinkProjectConcept ¶ added in v0.0.14
func (kb *KnowledgeBase) UnlinkProjectConcept(project, concept string) error
* UnlinkProjectConcept removes the link between a project and a concept. Both names
- match exactly, as for DeleteConcept: a destructive call must not guess. Removing a
- link that does not exist is ErrNotFound, not a success. *
- Parameters:
- project (string) — the project's name.
- concept (string) — the concept's name. *
- Returns:
- error — ErrNotFound for a missing project, concept or link; or on database failure. *
- Example:
- err := kb.UnlinkProjectConcept("harvey", "RAG")
func (*KnowledgeBase) UnlinkRecordSource ¶ added in v0.0.25
func (kb *KnowledgeBase) UnlinkRecordSource(recordID, sourceID int64) error
* UnlinkRecordSource removes the link between a decision record and a source it
- cites. Removing a link that does not exist is ErrNotFound. *
- Parameters:
- recordID (int64) — the record's id.
- sourceID (int64) — the source's id. *
- Returns:
- error — ErrNotFound for a missing record, source or link; or on database failure. *
- Example:
- err := kb.UnlinkRecordSource(3, 2)
func (*KnowledgeBase) UpdateDocumentDescription ¶ added in v0.0.32
func (kb *KnowledgeBase) UpdateDocumentDescription(id int64, description string) error
- UpdateDocumentDescription sets a document's stored front-matter description. *
- Parameters:
- id (int64) — the document's internal id.
- description (string) — the description, verbatim; "" when the file has none. *
- Returns:
- error — on database failure. *
- Example:
- err := kb.UpdateDocumentDescription(docID, "Fieldwork on quokka habitats")
func (*KnowledgeBase) UpdateDocumentMetadata ¶ added in v0.0.6
func (kb *KnowledgeBase) UpdateDocumentMetadata(id int64, title, author, publishedDate, checksum string) error
* UpdateDocumentMetadata updates a document's title/author/published_date/
- checksum in place, and refreshes ingested_at. Used when re-ingesting a
- changed file (design decision 10) -- the document row itself is always
- updated in place; only its sections need the careful match-by-heading
- treatment. *
- Parameters:
- id (int64) — the document's internal id.
- title, author, publishedDate, checksum (string) — the new values. *
- Returns:
- error — on database failure. *
- Example:
- err := kb.UpdateDocumentMetadata(docID, "New Title", "", "", newChecksum)
func (*KnowledgeBase) UpdateDocumentSectionBody ¶ added in v0.0.6
func (kb *KnowledgeBase) UpdateDocumentSectionBody(id int64, body string, sourceSize, tagDensity int, stale bool) error
* UpdateDocumentSectionBody updates a section's raw body and word-count
- signal on re-ingest, and sets its stale flag (design decision 10) --
- summary_body/summary_status/confidence are deliberately left untouched,
- since the whole point is that an existing summary is never silently
- discarded when its underlying text changes. *
- Parameters:
- id (int64) — the section's internal id.
- body (string) — the new raw body.
- sourceSize (int) — the new word count.
- stale (bool) — whether this change should mark the section stale
- (true whenever an existing drafted/reviewed
- summary is now describing different text). *
- Returns:
- error — on database failure. *
- Example:
- err := kb.UpdateDocumentSectionBody(secID, newBody, 42, true)
func (*KnowledgeBase) UpdateDocumentSectionTagDensity ¶ added in v0.0.6
func (kb *KnowledgeBase) UpdateDocumentSectionTagDensity(id int64, tagDensity int) error
* UpdateDocumentSectionTagDensity updates only a section's tag_density,
- without touching body, summary, or stale state. Used to refresh the gist
- row's density on re-ingest (design decision 6) -- the gist has no body of
- its own to update, only a density computed from the whole document's
- current text. *
- Parameters:
- id (int64) — the section's internal id.
- tagDensity (int) — the new density value. *
- Returns:
- error — on database failure. *
- Example:
- err := kb.UpdateDocumentSectionTagDensity(gistSectionID, 4)
func (*KnowledgeBase) UpdateRecordPath ¶ added in v0.0.7
func (kb *KnowledgeBase) UpdateRecordPath(id int64, path string) error
* UpdateRecordPath sets a record's stored path, leaving every other field
- alone. This is the write ingest makes when a checksum-matched record's file
- has moved: the body is unchanged so nothing else needs updating, but path
- itself does, or the database silently diverges from the files that are
- supposed to be authoritative. *
- Parameters:
- id (int64) — the records table primary key.
- path (string) — the new path, relative to the workspace root. *
- Returns:
- error — when no such record exists, or on database failure. *
- Example:
- err := kb.UpdateRecordPath(id, "agents/projects/clasm/decisions/0001-x.md")
func (*KnowledgeBase) UpdateRecordStatus ¶ added in v0.0.4
func (kb *KnowledgeBase) UpdateRecordStatus(id int64, status string) error
* UpdateRecordStatus sets a record's status, leaving every other field
- alone. It is the promotion path from proposed to accepted, and the
- demotion path to superseded. *
- Parameters:
- id (int64) — the records table primary key.
- status (string) — the new status value. *
- Returns:
- error — when no such record exists, or on database failure. *
- Example:
- err := kb.UpdateRecordStatus(id, "accepted")
func (*KnowledgeBase) WhoKnows ¶ added in v0.0.25
func (kb *KnowledgeBase) WhoKnows(projectID int64, character, scene string) (WhoKnowsResult, error)
* WhoKnows lists what a character learns, in story order, up to a scene
- (DR-0083 item 5). *
- A fact counts when the character has a learns row for it in a scene that is
- provably at or before the scene asked about (the scene itself counts). A fact
- learned in several scenes is listed once, at the earliest. A knows row is use,
- not learning, and is never listed. Facts learned only in scenes whose order
- against the scene is not established are returned in Unordered, not guessed.
- With scene "" every fact the character learns is returned. *
- Parameters:
- projectID (int64) — the project.
- character (string) — the character, matched without regard to case.
- scene (string) — a scene number or an event label; "" for no limit. *
- Returns:
- WhoKnowsResult — Facts and Unordered, both empty (not nil) when there are none.
- error — ErrNotFound when no scene row names the character, or the
- scene names no event; ErrAmbiguousScene (also ErrInvalid) when it names
- several; or a database failure. A character named only in knows rows is
- found, with nothing learned. *
- Example:
- r, err := kb.WhoKnows(pid, "Anna", "12A")
- for _, f := range r.Facts { fmt.Printf("%s (%s)\n", f.Fact, f.LearnedIn) }
func (*KnowledgeBase) WhoLearns ¶ added in v0.0.25
func (kb *KnowledgeBase) WhoLearns(projectID int64, fact string) ([]Learner, error)
- WhoLearns lists who learns a fact, and where, in story order (DR-0083 item 5). *
- The fact is matched by its folded key (see FactKey), so case and spacing do
- not matter. A character who learns it in several scenes is listed once, at
- the earliest. A fact that is only used (a knows row, backstory) has no
- learner. *
- Parameters:
- projectID (int64) — the project.
- fact (string) — the fact's text. *
- Returns:
- []Learner — one per character, in story order.
- error — ErrInvalid for a blank fact; ErrNotFound when no scene teaches
- it; or a database failure. *
- Example:
- ls, err := kb.WhoLearns(pid, "the letter is forged")
- for _, l := range ls { fmt.Println(l.Character, l.LearnedIn) }
func (*KnowledgeBase) Workspace ¶ added in v0.0.4
func (kb *KnowledgeBase) Workspace() string
* Workspace returns the name of the workspace this database belongs to: the
- base name of the workspace root, which is the parent of the directory
- holding the database. A database at ~/WorkLab/agents/knowledge.db reports
- "WorkLab". *
- It is derived from the path rather than configured or stored in a record
- file, so there is nothing to keep in sync and nothing to get wrong. *
- Returns:
- string — the workspace name. *
- Example:
- kb, _ := Open("/home/u/WorkLab/agents/knowledge.db")
- fmt.Println(kb.Workspace()) // "WorkLab"
type KnownFact ¶ added in v0.0.25
type KnownFact struct {
Fact string
FactKey string
LearnedIn string
SceneID string
Document string
EventID int64
}
- KnownFact is one fact a character learns, and where (DR-0083). *
- Fact is the text as written in the scene that teaches it, FactKey its folded
- identity (see FactKey), LearnedIn the name of that scene (its label, or its
- scene number), SceneID the scene number (empty for a prose scene file), and
- Document the file's path. EventID is the story event. *
- Example:
- r, _ := kb.WhoKnows(pid, "Anna", "")
- fmt.Println(r.Facts[0].Fact, "in", r.Facts[0].LearnedIn)
type Learner ¶ added in v0.0.25
type Learner struct {
Character string
Fact string
LearnedIn string
SceneID string
Document string
}
- Learner is one character who learns a fact, from WhoLearns. *
- Fact is the text as that character's scene writes it; LearnedIn, SceneID and
- Document are as in KnownFact. *
- Example:
- ls, _ := kb.WhoLearns(pid, "the letter is forged")
- fmt.Println(ls[0].Character, ls[0].LearnedIn)
type MaterialRef ¶ added in v0.0.25
* MaterialRef is the file a document or record came from (DR-0080): where it
- is, the checksum it had when it was read, and when. It is the other sense of
- "source" (the material read into the knowledge base), kept apart from the
- works a row cites. *
- Fields:
- Path (string) — the file path as ingested.
- Checksum (string) — the content checksum recorded at ingest.
- Format (string) — "markdown", "fountain" or "text" for a document;
- "markdown" for a record.
- IngestedAt (time.Time) — when it was last ingested. *
- Example:
- if hit.Material != nil { fmt.Println(hit.Material.Path, hit.Material.Checksum) }
type MergeScratch ¶ added in v0.0.15
type MergeScratch struct {
A, B string
// contains filtered or unexported fields
}
* MergeScratch is a pair of throwaway copies of two knowledge bases, brought
- up to the current schema, that detection and correction can work on without
- touching the originals. It is the read-only front half of a merge, shared by
- `kb merge` and `kb check-db` (DR-0053). *
- Fields:
- A (string) — path of the copy of the first database.
- B (string) — path of the copy of the second database. *
- Example:
- s, err := knowledge.PrepareMergeScratch("a.db", "b.db")
- if err != nil { return err }
- defer s.Close()
func PrepareMergeScratch ¶ added in v0.0.15
func PrepareMergeScratch(aPath, bPath string) (*MergeScratch, error)
* PrepareMergeScratch copies both databases into a fresh temporary directory
- and brings each copy up to the current schema (NormalizeForMerge), so a
- database predating a table can still be compared or merged. The originals
- are opened only to checkpoint and copy them, and their rows are never
- changed. The workspace name for each copy comes from the original path
- (DR-0014). *
- Parameters:
- aPath (string) — path to the first knowledge.db.
- bPath (string) — path to the second knowledge.db. *
- Returns:
- *MergeScratch — the copies; call Close to remove them.
- error — if either database cannot be copied or migrated; nothing is left behind. *
- Example:
- s, err := knowledge.PrepareMergeScratch("a.db", "b.db")
func (*MergeScratch) Close ¶ added in v0.0.15
func (s *MergeScratch) Close() error
- Close removes the scratch directory and everything in it. *
- Returns:
- error — if the directory cannot be removed. *
- Example:
- defer s.Close()
type MergeTableSummary ¶
* MergeTableSummary reports, per table, how many rows came from each
- source and how many rows the merged table ended up with (less than
- FromA+FromB when uuid or name collisions caused an intentional drop).
func MergeKnowledgeBases ¶
func MergeKnowledgeBases(aPath, bPath, mergedPath string) ([]MergeTableSummary, error)
* MergeKnowledgeBases creates a fresh knowledge base at mergedPath (which
- must not already exist) containing the set union of aPath and bPath,
- deduped by uuid (and, for projects/concepts, by the pre-existing name
- UNIQUE constraint, and for records by their four-column identity). aPath and
- bPath are opened read-only via ATTACH; neither is modified. *
- All sixteen tables that travel are carried: projects, concepts, sources,
- observations, records and documents, plus the eight join/child tables
- (record_relations, record_concepts, document_sections,
- document_section_concepts, observation_concepts, project_concepts,
- observation_sources, observation_relations). Every one appears in the
- returned summary, so a
- table that loses rows says so — records were once absent from both the
- merge and the summary, and a merge that dropped them reported success
- (DR-0013). *
- Both sources must already carry the current schema. This function names
- every table directly, so a database predating one of them fails the query
- rather than contributing nothing; callers copying a live database should run
- NormalizeForMerge on the copy first, as cmd/kb's merge verb does (DR-0014). *
- Parameters:
- aPath (string) — path to the first source knowledge.db.
- bPath (string) — path to the second source knowledge.db.
- mergedPath (string) — path for the new merged knowledge.db; must not exist. *
- Returns:
- []MergeTableSummary — one entry per table, with each side's count and the merged count.
- error — on database failure, or if mergedPath already exists. *
- Example:
- summary, err := MergeKnowledgeBases("/machine-a/knowledge.db", "/machine-b/knowledge.db", "/tmp/merged.db")
type NearExistingMatch ¶ added in v0.0.12
type NearExistingMatch struct {
Token string `json:"token"`
Concept string `json:"concept"`
Distance int `json:"distance"`
}
* NearExistingMatch is one candidate term SuggestConcepts excludes from
- candidacy because it is a fuzzy near-miss of an already-known concept:
- `kb document fuzzy-tag`'s job, not concept suggestion's. It is also the
- entry shape of `kb concept suggest --json`'s near_existing array, so its
- tags are a compatibility contract. The list is a mechanical pass and noisy:
- expect a human to discard some pairs. *
- Fields:
- Token (string) — the term found in the corpus.
- Concept (string) — the existing concept it is close to (lowercased).
- Distance (int) — the edit distance between them (raw or stemmed). *
- Example:
- // {Token: "collisions", Concept: "collision", Distance: 1}
type Observation ¶
type Observation struct {
ID int64
ProjectID int64
Kind string
Body string
SourceDOI string
CreatedAt time.Time
// Status is "reviewed" (trusted: searchable, recalled) or "drafted"
// (written by a model, invisible until a person promotes it; DR-0090).
Status string
// GeneratedBy names the drafter of a drafted observation; "" otherwise.
GeneratedBy string
// Confidence is the drafter's 0 to 1 estimate, or nil when none was given.
Confidence *float64
}
* Observation represents a single timestamped note, finding, decision,
- question, or hypothesis attached to a project. SourceDOI records the
- normalized DOI of the paper the observation was extracted from, if any;
- it is "" for observations not tied to a specific source document. *
- Example:
- obs, err := kb.Observations(projectID)
- for _, o := range obs {
- fmt.Printf("[%s] %s\n", o.Kind, o.Body)
- }
type ObservationUsage ¶ added in v0.0.14
type ObservationUsage struct {
ID int64
Concepts int
Sources int
RelationsFrom int
RelationsTo int
}
- ObservationUsage counts what depends on one observation. *
- Fields:
- ID (int64) — the observation's id.
- Concepts (int) — concept links.
- Sources (int) — source links.
- RelationsFrom (int) — relations where it is the newer side (it supersedes another).
- RelationsTo (int) — relations where it is the older side (another supersedes it). *
- Example:
- u, _ := kb.ObservationUsage(7)
- fmt.Println(u.Total())
func (ObservationUsage) Total ¶ added in v0.0.14
func (u ObservationUsage) Total() int
- Total returns how many links and relations the observation has. *
- Returns:
- int — the sum of all four counts. *
- Example:
- if u.Total() == 0 { fmt.Println("unlinked") }
type ParsedDocument ¶ added in v0.0.6
type ParsedDocument struct {
Format string
Title string
Author string
PublishedDate string
Keywords []string
GistSeed string
Sections []DocumentSection
Checksum string
Warning string
// Story is the document-level story metadata from front matter (a prose
// scene file is one scene). StoryWarnings collects what was not
// understood, from front matter and from every scene's boneyard.
Story StoryMeta
StoryWarnings []string
// Sources is the front matter's `sources:` list, as written, and
// SourcesPresent says the key was there at all (DR-0081 item 4): a file
// with the key manages the citations it makes; a file without it manages
// none.
Sources []string
SourcesPresent bool
}
* ParsedDocument is the result of reading and segmenting one document file,
- before anything is written to the database. Sections holds only
- `'section'`-level rows (design decision 1) -- the caller creates the
- `'gist'` row itself, seeded from GistSeed when a frontmatter description
- or Fountain title page provided one.
func ParseDocumentFile ¶ added in v0.0.6
func ParseDocumentFile(path, formatOverride string) (*ParsedDocument, error)
* ParseDocumentFile reads path, determines its format, and segments it per
- narrative-documents-design.md decisions 2-4: Markdown frontmatter and
- Fountain title pages are both recognized metadata sources (decision 3),
- PDF is rejected outright rather than silently mishandled (decision 2). *
- Parameters:
- path (string) — path to the document file.
- formatOverride (string) — "markdown"/"fountain"/"text"/"pdf", or "" to
- infer from the file extension. *
- Returns:
- *ParsedDocument — the parsed document, ready for the caller to reconcile
- against any existing row (see cmd/kb's document
- ingest, which owns that reconciliation the same way
- cmd/kb/ingest.go owns it for records).
- error — on a read failure, a malformed Fountain source, or a
- PDF document (not yet supported, no extraction path
- exists). *
- Example:
- pd, err := knowledge.ParseDocumentFile("stories/a-story.md", "")
type Project ¶
- Project represents a single project row in the knowledge base. *
- Example:
- projects, err := kb.Projects()
- for _, p := range projects {
- fmt.Printf("%d %s [%s]\n", p.ID, p.Name, p.Status)
- }
type ProjectStats ¶ added in v0.0.23
- ProjectStats is one project's line in a Stats report. *
- Fields:
- Name (string) — the project's name.
- Observations (int) — its observations.
- Records (int) — its decision records.
- Documents (int) — its documents.
- Concepts (int) — its concepts: the union of those tagged on the
- project, on its observations and on its records,
- each counted once (DR-0073). *
- Example:
- s, _ := kb.Stats()
- fmt.Println(s.Projects[0].Name, s.Projects[0].Concepts)
type ProjectUsage ¶ added in v0.0.14
- ProjectUsage counts what depends on one project. *
- Fields:
- Name (string) — the project's name.
- Observations (int) — observations it owns.
- Records (int) — decision records it owns.
- Documents (int) — documents it owns.
- Concepts (int) — concept links it has. *
- Example:
- u, _ := kb.ProjectUsage("harvey")
- fmt.Println(u.Owned())
func (ProjectUsage) Owned ¶ added in v0.0.14
func (u ProjectUsage) Owned() int
* Owned returns how many observations, records and documents the project owns:
- the content that DeleteProject never removes. *
- Returns:
- int — Observations + Records + Documents. *
- Example:
- if u.Owned() > 0 { fmt.Println("not empty") }
func (ProjectUsage) Total ¶ added in v0.0.14
func (u ProjectUsage) Total() int
- Total returns Owned plus the concept links. *
- Returns:
- int — everything that depends on the project. *
- Example:
- fmt.Println(u.Total())
type Provenance ¶ added in v0.0.12
type Provenance interface {
FirstCommit(path string) (author, date string, ok bool)
LastCommit(path string) (date string, ok bool)
ConfigUserName(dir string) (name string, ok bool)
FileTime(path string) (time.Time, error)
}
* Provenance is where ProposeFrontmatter and ApplyFrontmatter learn who
- wrote a file and when. GitProvenance is the default and shells out to git;
- a caller that wants no subprocess, or its own idea of authorship, supplies
- another implementation. *
- Methods:
- FirstCommit(path) — author and RFC 3339 date of the oldest commit
- touching path; ok=false when path has no history.
- LastCommit(path) — RFC 3339 date of the newest commit touching path;
- ok=false when path has no history.
- ConfigUserName(dir) — the configured user.name as seen from dir;
- ok=false when unset.
- FileTime(path) — a filesystem timestamp for path, the fallback when
- there is no history. *
- Example:
- var p knowledge.Provenance = knowledge.GitProvenance{}
type Record ¶ added in v0.0.4
type Record struct {
ID int64
RecordID string
ProjectID int64
Scope string
Path string
Title string
Date string
Status string
Kind string
Trigger string
Phase string
Initiative string
Session string
Body string
Checksum string
IngestedAt time.Time
UUID string
OriginHost string
Workspace string
}
* Record represents one decision record: a single file under a project's
- decisions/ directory, parsed into its frontmatter fields plus its body. *
- RecordID, Date and Phase are strings rather than numbers or times on
- purpose. A bare 0142 in YAML parses as the integer 142, losing the zero
- padding that makes ids sort and grep predictably, and a bare 2026-08-19
- resolves to a timestamp. The file format quotes all three, and so does this
- struct. *
- ProjectID is 0 for a workspace-tier record, which is stored as a NULL
- project_id. Scope distinguishes the two tiers explicitly: "project" or
- "workspace". *
- Fields:
- ID (int64) — primary key, assigned on insert.
- RecordID (string) — zero-padded record number, e.g. "0142".
- ProjectID (int64) — owning project; 0 for the workspace tier.
- Scope (string) — "project" or "workspace".
- Path (string) — file path relative to the workspace root.
- Title (string) — the record's title.
- Date (string) — YYYY-MM-DD, as written in the file.
- Status (string) — proposed | accepted | superseded | rejected | cancelled.
- Kind (string) — decision | correction | note, documented not enforced.
- Trigger (string) — what prompted the episode; may be empty.
- Phase (string) — release or phase label, e.g. "0.0.46".
- Initiative (string) — cross-project initiative name.
- Session (string) — originating session identifier.
- Body (string) — everything after the closing frontmatter fence.
- Checksum (string) — over the raw file bytes; makes ingest idempotent.
- IngestedAt (time.Time) — when the row was last written.
- UUID (string) — stable identity for cross-machine merge.
- OriginHost (string) — host that first wrote the record.
- Workspace (string) — the workspace the record belongs to, the base
- name of the workspace root. Part of the record's
- identity: two workspaces may each have a DR-0001. *
- Example:
- recs, err := kb.RecordsByProject(projectID)
- for _, r := range recs {
- fmt.Printf("DR-%s %s %s\n", r.RecordID, r.Date, r.Title)
- }
type RecordFile ¶ added in v0.0.4
type RecordFile struct {
Record Record
ProjectName string
Supersedes []string
SupersededBy []string
RelatesTo []string
Decisions []string
Tags []string
Warnings []string
// Sources is the `sources:` list as written and SourcesPresent says the
// key was there at all (DR-0081): a record with the key manages the
// citations it makes.
Sources []string
SourcesPresent bool
// contains filtered or unexported fields
}
* RecordFile is one parsed decision record: the database-bound fields in
- Record, plus the file-level fields that are not columns of the records
- table. *
- Supersedes, SupersededBy and RelatesTo hold raw frontmatter entries — bare
- ids, or `scope:id` for a cross-tier reference — and are resolved into
- record_relations at ingest, not here. Decisions and Tags have no column yet
- and are carried so that a round trip preserves them. *
- Fields:
- Record (Record) — the fields that map onto the records table.
- ProjectName (string) — frontmatter "project"; empty at the workspace tier.
- Supersedes ([]string) — ids this record replaces.
- SupersededBy ([]string) — ids that replace this one.
- RelatesTo ([]string) — non-superseding cross-references.
- Decisions ([]string) — one-line summaries for a multi-decision episode.
- Tags ([]string) — free-form tags.
- Warnings ([]string) — non-fatal problems found while parsing. *
- Example:
- rf, err := ParseRecordFile("decisions/0008-config-resolution.md")
- for _, w := range rf.Warnings {
- fmt.Fprintln(os.Stderr, w)
- }
func ParseRecord ¶ added in v0.0.4
func ParseRecord(data []byte, path string) (*RecordFile, error)
- ParseRecord parses a decision record from bytes already in memory. *
- The body is everything after the closing fence, kept verbatim: the format
- uses bold-lead sections rather than headings precisely so that conversion
- copies bodies byte for byte. *
- Parameters:
- data ([]byte) — the whole file, frontmatter and body.
- path (string) — the path to record on the parsed Record. *
- Returns:
- *RecordFile — the parsed record.
- error — on missing or malformed frontmatter, or a missing required
- field. *
- Example:
- rf, err := ParseRecord(data, "decisions/0008-config-resolution.md")
func ParseRecordFile ¶ added in v0.0.4
func ParseRecordFile(path string) (*RecordFile, error)
- ParseRecordFile reads and parses the decision record at path. *
- Parameters:
- path (string) — path to the record file. *
- Returns:
- *RecordFile — the parsed record, with Path set to path.
- error — on a read failure, missing frontmatter, or a missing
- required field. Vocabulary and quoting problems are
- reported in Warnings instead. *
- Example:
- rf, err := ParseRecordFile("decisions/0160-iam-instance-profile.md")
- fmt.Println(rf.Record.Title)
type RecordFilter ¶ added in v0.0.4
type RecordFilter struct {
Project string
Scope string
Status string
Kind string
Trigger string
Initiative string
Since string
}
* RecordFilter narrows a ListRecords query. A zero-valued field means "any";
- Scope selects a tier, since a project name cannot express the workspace
- tier, whose records have no project at all. *
- Fields:
- Project (string) — projects.name; "" matches any project.
- Scope (string) — "project" or "workspace"; "" matches both.
- Status (string) — exact status match.
- Kind (string) — exact kind match.
- Trigger (string) — exact trigger match.
- Initiative (string) — exact initiative match.
- Since (string) — YYYY-MM-DD; keeps records dated on or after it. *
- Example:
- recs, err := kb.ListRecords(RecordFilter{Project: "clasm", Kind: "correction"})
type RecordFuzzyFinding ¶ added in v0.0.15
type RecordFuzzyFinding struct {
Concept string `json:"concept"`
Variants []string `json:"variants"`
Count int `json:"count"`
ExactMentions int `json:"exact_mentions"`
}
* RecordFuzzyFinding is one concept a decision record mentions only by
- near-miss spellings, and so does not link to. *
- The JSON tags are the per-finding shape `kb record fuzzy-tag --json` prints. *
- Fields:
- Concept (string) — the canonical concept name.
- Variants ([]string) — the distinct near-miss spellings found, as written, in order
- of first appearance.
- Count (int) — how many near-miss occurrences there are in all.
- ExactMentions (int) — how many times the plain concept name appears in the body:
- prose that links nothing, reported so a reader can see the
- record already talks about the concept. *
- Example:
- rep, _ := kb.RecordFuzzyReport(rf, []string{"toast"})
- fmt.Println(rep[0].Concept, rep[0].Variants) // toast [detoast]
type RecordUsage ¶ added in v0.0.14
type RecordUsage struct {
ID int64
RecordID string
Path string
Concepts int
RelationsFrom int
RelationsTo int
}
- RecordUsage counts what a record row is linked to. *
- Fields:
- ID (int64) — the row's id.
- RecordID (string) — the record's id within its tier, for example "0040".
- Path (string) — the path stored for its file, relative to the workspace root.
- Concepts (int) — concept links.
- RelationsFrom (int) — relations where it is the source.
- RelationsTo (int) — relations where it is the target. *
- Example:
- u, _ := kb.RecordUsage(12)
- fmt.Println(u.Path)
type Ref ¶ added in v0.0.17
* Ref names a decision record: a scope and a record id. The scope is a project
- name or "workspace" (knowledge DR-0057); it is empty for a bare id, which
- resolves only where the id is unambiguous. *
- Fields:
- Scope (string) — a project name, "workspace", or "" for a bare id.
- ID (string) — the record id as stored, digits only and at least four
- wide ("0004"). *
- Example:
- ref, _ := knowledge.ParseRef("harvey/DR-0004")
- fmt.Println(ref.Scope, ref.ID) // harvey 0004
func ParseRef ¶ added in v0.0.17
* ParseRef reads a record reference: "SCOPE/DR-NNNN", "SCOPE/NNNN", "DR-NNNN"
- or "NNNN". The "DR-" prefix is case-insensitive, surrounding space is
- ignored, and an id shorter than four digits is padded with zeros, so
- "harvey/4" is harvey/DR-0004. It does not check that the scope exists; that
- is ResolveRef's job, since it needs the database. *
- Parameters:
- s (string) — the reference as typed. *
- Returns:
- Ref — the parsed reference.
- error — matching ErrInvalid when s is empty, has an empty scope or id, has
- more than one "/", or has an id that is not all digits. *
- Example:
- ref, err := knowledge.ParseRef("workspace/DR-0003")
- // ref == Ref{"workspace", "0003"}, err == nil
type RelatedObservation ¶ added in v0.0.8
RelatedObservation is one relation touching an observation, described from that observation's point of view — mirrors RelatedRecord (records.go).
type RelatedRecord ¶ added in v0.0.4
* RelatedRecord is one edge of the record graph, described from the point of
- view of the record that was asked about. Only one direction of a
- supersession is stored; RelationsFor synthesises the other, so a record that
- is the target of a "supersedes" edge reports it as "superseded_by". *
- Fields:
- RecordID (int64) — primary key of the record at the other end.
- Relationship (string) — supersedes | superseded_by | relates_to. *
- Example:
- rels, err := kb.RelationsFor(id)
- for _, rel := range rels {
- fmt.Printf("%s -> %d\n", rel.Relationship, rel.RecordID)
- }
type RetractionCheckError ¶ added in v0.0.14
* RetractionCheckError reports that CheckRetractions checked every source it
- could but some could not be checked: the lookup failed, or a retraction it
- found could not be recorded. A source that could not be checked is not "not
- retracted", so the caller must not read silence as reassurance. The counts
- CheckRetractions returned alongside it are valid. Unwrap reaches the first
- failure, so errors.Is and errors.As see its cause. *
- Fields:
- Checked (int) — sources that got an answer.
- Failed (int) — sources that could not be checked.
- First (error) — the first failure. *
- Example:
- var ce *knowledge.RetractionCheckError
- if errors.As(err, &ce) { fmt.Println(ce.Failed, "could not be checked") }
func (*RetractionCheckError) Error ¶ added in v0.0.14
func (e *RetractionCheckError) Error() string
func (*RetractionCheckError) Unwrap ¶ added in v0.0.14
func (e *RetractionCheckError) Unwrap() error
type RowDifference ¶ added in v0.0.15
- RowDifference is one row present on both sides whose compared columns differ. *
- Fields:
- Label (string) — a short human label for the row.
- A (string) — the compared columns on the first side, joined with " | ", cut to 80 runes.
- B (string) — the same on the second side. *
- Example:
- for _, d := range diff.Different { fmt.Println(d.Label, d.A, "vs", d.B) }
type RowKey ¶ added in v0.0.29
- RowKey names a row that has chunks in the sidecar. *
- Example:
- rows, _ := v.IndexedRows()
- fmt.Println(rows[0].SourceType, rows[0].SourceID)
type ScopedSearchResult ¶ added in v0.0.22
type ScopedSearchResult struct {
Results []KBSearchResult
Total int
Counts map[string]int
Spans map[int64][]string
SourceSpans map[int64][]string
}
- ScopedSearchResult is what SearchScoped returns. *
- Fields:
- Results ([]KBSearchResult) — the best matches, up to the limit, ranked.
- Total (int) — how many rows matched in scope, before the limit.
- Counts (map[string]int) — matches per kind, keyed by the SearchKinds name.
- Spans (map[int64][]string) — for each concept in Results, keyed by its id, the
- names of the projects whose context holds it, sorted.
- SourceSpans (map[int64][]string) — the same for each source in Results, keyed by its
- id: the projects whose observations, documents or records
- cite it. A source nothing cites has none. *
- Example:
- r, _ := kb.SearchScoped("cache", knowledge.SearchScope{})
- fmt.Printf("showing %d of %d\n", len(r.Results), r.Total)
type SearchScope ¶ added in v0.0.22
- SearchScope says where a scoped search looks (knowledge DR-0073, DR-0074). *
- Fields:
- Project (string) — a project name; "" for no project restriction.
- Workspace (bool) — the workspace tier only; cannot be combined with Project.
- Kinds ([]string) — members of SearchKinds; empty for every kind.
- Limit (int) — most results to return; 0 for the default, 50. *
- Example:
- sc := knowledge.SearchScope{Project: "harvey", Kinds: []string{"records"}}
type SemanticHit ¶ added in v0.0.29
type SemanticHit struct {
SourceType string
SourceID int64
Score float32
Chunk string
ChunkIndex int
}
- SemanticHit is one row found by SemanticSearch, with the chunk that matched. *
- Fields:
- SourceType (string) — kb_fts source_type of the row
- SourceID (int64) — the row's id
- Score (float32) — cosine similarity of the best chunk, at most 1
- Chunk (string) — the best chunk's text, for the passage line
- ChunkIndex (int) — the best chunk's position in the row *
- Example:
- fmt.Printf("%s:%d %.2f %s\n", h.SourceType, h.SourceID, h.Score, h.Chunk)
type SemanticOptions ¶ added in v0.0.29
type SemanticOptions struct {
Scope SearchScope
MinScore float32
Limit int
}
- SemanticOptions tunes SemanticSearch. *
- Fields:
- Scope (SearchScope) — which rows to rank, as for SearchScoped; only EmbeddedKinds can be asked for
- MinScore (float32) — the lowest cosine similarity returned; zero means DefaultMinScore, NoCutoff means all
- Limit (int) — the most rows returned; zero means 50 *
- Example:
- opts := knowledge.SemanticOptions{Scope: knowledge.SearchScope{Project: "harvey"}, MinScore: 0.4}
type SemanticResult ¶ added in v0.0.29
type SemanticResult struct {
Hits []SemanticHit
Total int
Unindexed int
}
- SemanticResult is what SemanticSearch returns. *
- Fields:
- Hits ([]SemanticHit) — up to Limit rows, best first
- Total (int) — how many rows reached the cutoff, before the limit
- Unindexed (int) — rows in scope with no chunks yet, which the search could not see *
- Example:
- r, _ := kb.SemanticSearch(v, e, "slow inference", knowledge.SemanticOptions{})
- fmt.Printf("showing %d of %d\n", len(r.Hits), r.Total)
type Source ¶
type Source struct {
ID int64
Title string
IdentifierType string
IdentifierValue string
Authors string
PublishedDate string
Publisher string
Rights string
Version string
Retracted bool
RetractionNote string
}
* Source is a row in the sources authority table. Each source represents a
- citable document or resource that may be linked to observations. *
- Fields:
- ID (int64) — auto-assigned primary key.
- Title (string) — human-readable title.
- IdentifierType (string) — "doi", "url", "isbn", "issn", "arxiv", "urn", or "".
- IdentifierValue (string) — the identifier string, e.g. "10.1234/example".
- Authors (string) — comma-separated author names.
- PublishedDate (string) — publication date, YYYY-MM-DD format.
- Publisher (string) — publisher name.
- Rights (string) — licence or rights statement.
- Version (string) — edition or version.
- Retracted (bool) — true when the source has been retracted.
- RetractionNote (string) — free-text note about the retraction. *
- Example:
- s := Source{Title: "SPARQL 1.1", IdentifierType: "doi", IdentifierValue: "10.1234/sparql"}
- id, err := kb.AddSource(s)
type SourceCitations ¶ added in v0.0.25
* SourceCitations counts what cites one source (DR-0081): it is what stops
- RemoveSource, so a caller can say so before asking for a delete. *
- Example:
- c, _ := kb.SourceCitations(1)
- fmt.Println(c.Total()) // 3
func (SourceCitations) String ¶ added in v0.0.25
func (c SourceCitations) String() string
* String describes the citations for a message: "2 observation(s), 1 document(s)",
- leaving out the kinds with none. *
- Returns:
- string — the description; "" when nothing cites the source. *
- Example:
- fmt.Println(SourceCitations{Documents: 1}) // "1 document(s)"
func (SourceCitations) Total ¶ added in v0.0.25
func (c SourceCitations) Total() int
- Total returns how many rows cite the source, of any kind. *
- Returns:
- int — Observations + Documents + Records. *
- Example:
- if c.Total() > 0 { fmt.Println("cited") }
type SourceLink ¶ added in v0.0.25
* SourceLink is one citation: a source, and how and at which version a
- observation, document or record cites it (DR-0081). *
- Fields:
- Source (Source) — the cited work, with its retraction state.
- Relationship (string) — "cited" unless the link says otherwise.
- SourceVersion (string) — the version of the work that was read; "" when not recorded.
- SourceHash (string) — its content hash at that time; "" when not recorded. *
- Example:
- links, _ := kb.DocumentSources(docID)
- for _, l := range links { fmt.Println(l.Source.Title, l.Relationship, l.SourceVersion) }
type SourceRef ¶ added in v0.0.25
type SourceRef struct {
ID int64
Title string
IdentifierType string
IdentifierValue string
PublishedDate string
Version string
Rights string
Retracted bool
RetractionNote string
Relationship string
SourceVersion string
SourceHash string
}
* SourceRef is one cited work as a search or recall hit reports it (DR-0080):
- enough to show what supports the hit and whether that support was retracted,
- without a second query. *
- Fields:
- ID, Title, IdentifierType, IdentifierValue, PublishedDate, Version, Rights,
- Retracted, RetractionNote — the source row.
- Relationship (string) — how the hit's row cites it ("cited" by default).
- SourceVersion (string) — the version of the work that was read, "" when not recorded.
- SourceHash (string) — its content hash at that time, "" when not recorded. *
- Example:
- for _, s := range hit.Sources { fmt.Println(s.Title, s.IdentifierValue, s.Retracted) }
type StatCount ¶ added in v0.0.23
- StatCount is one named number in a Stats report. *
- Fields:
- Name (string) — the table, join table or check the number is about.
- Count (int) — how many rows. *
- Example:
- s, _ := kb.Stats()
- for _, c := range s.Rows { fmt.Println(c.Name, c.Count) }
type Stats ¶ added in v0.0.23
type Stats struct {
Rows []StatCount
Links []StatCount
Checks []StatCount
Projects []ProjectStats
}
* Stats is the shape of a database: how many rows each table has, how many
- links each join table has, the facts a curator otherwise checks with SQL,
- and one line per project. Every list is in a fixed order. *
- Fields:
- Rows ([]StatCount) — rows per table.
- Links ([]StatCount) — rows per join table.
- Checks ([]StatCount) — things that are worth knowing and usually zero
- (an observation with no project) or are not
- an error (a concept nothing links to).
- Projects ([]ProjectStats) — per project, by name. *
- Example:
- s, err := kb.Stats()
type StoredChunk ¶ added in v0.0.29
type StoredChunk struct {
SourceType string
SourceID int64
Index int
Hash string
Text string
Vector []float32
}
- StoredChunk is one chunk of a row with its vector. *
- Fields:
- SourceType (string) — kb_fts source_type of the row (set when read back)
- SourceID (int64) — the row's id (set when read back)
- Index (int) — the chunk's position in the row, from 0
- Hash (string) — ChunkHash of Text, so an unchanged chunk is not re-embedded
- Text (string) — the chunk, kept for the passage line of a hit
- Vector ([]float32) — the embedding, of the sidecar's dimensions *
- Example:
- c := knowledge.StoredChunk{Index: 0, Hash: knowledge.ChunkHash(t), Text: t, Vector: vec}
type StoryEvent ¶ added in v0.0.24
type StoryEvent struct {
ID int64
ProjectID int64
DocumentID int64
SectionID int64
SceneID string
Label string
StoryTimeText string
Time StoryTime
AnchorEventID int64
State string
Note string
Place string
POV string
Status string
Characters []string
Foreshadows []string
PaysOff []string
Precedes []string
Seq int
}
* StoryEvent is one row of story_events: a scene, or a prose scene file, placed
- in story time (DR-0075, DR-0079). *
- State is one of "dated" (an absolute time), "resolved" (a relative time
- given an interval from its anchor), "edge" (an ordering relation to a found
- anchor, no interval), "unresolved" (a relation whose anchor is missing,
- ambiguous, undated or in a cycle; Note says which), or "none" (no usable
- story_time; Note says why when it was unparseable). *
- Example:
- evs, _ := kb.StoryEvents(projectID)
- for _, e := range evs { fmt.Println(e.Label, e.State, e.Time.Start) }
type StoryFinding ¶ added in v0.0.24
* StoryFinding is one thing StoryCheck noticed about a work (DR-0075 item 10).
- It is a report, never a repair: nothing in the knowledge base or the
- manuscript is changed because of it. *
- Kind is one of "missing-file", "unnumbered-scene", "scene-comment-no-id", "scene-id-disagreement", "scene-id-repeated", "scene-comment-syntax", "fountain-style-heading", "front-matter-ignored", "duplicate-label",
- "unresolved-time", "unparseable-time", "unknown-reference", "contradiction",
- "cycle", "two-places", "foreshadow-order", "knowledge-before-learned", "unknown-fact", "fact-number-differs" or "late-source". Document is the file path, and
- Message says what and where. *
- Example:
- fs, _ := kb.StoryCheck(pid)
- for _, f := range fs { fmt.Printf("%s: %s: %s\n", f.Kind, f.Document, f.Message) }
type StoryMeta ¶ added in v0.0.24
type StoryMeta struct {
Event string
StoryTime string
Place string
POV string
Status string
Characters []string
Foreshadows []string
PaysOff []string
Precedes []string
Learns []string
Knows []string
}
* StoryMeta is the story-structure metadata a manuscript carries for one
- scene: when it happens, where, whose point of view, how finished it is,
- who is in it, and its links to other scenes (DR-0075). It is read from a
- document's front matter, or, for a Fountain scene, from a one-line
- boneyard after the heading (DR-0078). Every field is optional. *
- Example:
- m := knowledge.StoryMeta{StoryTime: "1969-10-29", POV: "Anna"}
- fmt.Println(m.IsZero()) // false
func ParseStoryBoneyard ¶ added in v0.0.24
* ParseStoryBoneyard reads a Fountain boneyard element as story metadata
- (DR-0078). The boneyard itself is delimited by the fountain module; this
- reads only the key=value grammar inside it. *
- Parameters:
- content (string) — a boneyard element's Content, delimiters included. *
- Returns:
- StoryMeta — the metadata the boneyard sets.
- []string — a message for each pair that was not understood (an
- unknown key, or a word with no "="); the rest of the pairs are kept.
- bool — true when the boneyard is a story boneyard (its text starts
- "story:"); false for any other boneyard, which the caller leaves alone. *
- Example:
- m, warn, ok := knowledge.ParseStoryBoneyard("/* story: pov=Anna; characters=A, B *" + "/")
- // ok, m.POV == "Anna", m.Characters == []string{"A", "B"}, warn == nil
func ParseStoryComment ¶ added in v0.0.25
* ParseStoryComment reads a Markdown HTML comment as the story metadata of
- the scene above it (DR-0082): "<!-- story: id=12A; pov=Anna -->". It is
- the Markdown counterpart of ParseStoryBoneyard, with the same key=value
- grammar plus an id key, because a Markdown scene may take its id from the
- comment as well as from a heading attribute. *
- Parameters:
- content (string) — one HTML comment, delimiters included; it may span
- lines. *
- Returns:
- StoryMeta — the metadata the comment sets.
- string — the scene id the comment gives, "" when it has none.
- []string — a message for each pair that was not understood (an unknown
- key, or a word with no "="); the rest of the pairs are kept.
- bool — true when the comment is a story comment (its text starts
- "story:"); false for any other comment, which the caller leaves alone. *
- Example:
- m, id, warn, ok := knowledge.ParseStoryComment("<!-- story: id=12A; pov=Anna -->")
- // ok, id == "12A", m.POV == "Anna", warn == nil
type StoryTime ¶ added in v0.0.24
type StoryTime struct {
Precision string
Start string
End string
Relation string
Anchor string
Offset string
}
* StoryTime is a parsed story_time (DR-0079 item 2): when an event happens
- in the story, kept as an interval with a precision, or as an ordering
- relation to another event, or both once the relation has been resolved. *
- Start and End are ISO dates (2006-01-02) for the calendar precisions and
- decimal integers for "ordinal". Relation, Anchor and Offset describe a
- relative time ("after: e12 +3d"); Offset is "" for an ordering edge with no
- interval, otherwise a sign, a whole number and a unit, always written with
- its "+". *
- Example:
- t, _ := knowledge.ParseStoryTime("circa 1890")
- fmt.Println(t.Precision, t.Start, t.End) // circa 1890-01-01 1890-12-31
func ParseStoryTime ¶ added in v0.0.24
- ParseStoryTime reads a story_time value. *
- Parameters:
- s (string) — one of: 1969-10-29, 1969-10, 1969, circa 1890,
- ordinal: 12, after: LABEL [OFFSET], before: LABEL [OFFSET]. An
- offset is a whole number with a unit d, w, m or y, or a bare number
- against an ordinal anchor. *
- Returns:
- StoryTime — the parsed time; the zero value for an empty string.
- error — ErrInvalid for anything else, including an impossible
- date and a negative offset. *
- Example:
- t, err := knowledge.ParseStoryTime("after: e12 +3d")
- // t.Relation == "after", t.Anchor == "e12", t.Offset == "+3d"
func ResolveStoryTime ¶ added in v0.0.24
* ResolveStoryTime gives a relative event its interval from its anchor's:
- "after" adds the offset to the anchor's end, "before" subtracts it from the
- anchor's start (DR-0079). The result has day precision for dates and
- ordinal precision for ordinals. Month and year offsets use time.AddDate, so
- 31 January plus one month is 3 March. *
- Parameters:
- rel (StoryTime) — a relative time with a Relation and an Offset.
- anchor (StoryTime) — the anchor event's time, which must have an interval. *
- Returns:
- StoryTime — rel with Precision, Start and End filled in.
- error — ErrInvalid when there is no offset, the anchor has no interval,
- or the offset's unit does not fit the anchor (a day offset on an
- ordinal, or a bare number on dates). *
- Example:
- anchor, _ := knowledge.ParseStoryTime("1969-10-29")
- rel, _ := knowledge.ParseStoryTime("after: x +3d")
- got, _ := knowledge.ResolveStoryTime(rel, anchor) // 1969-11-01
func (StoryTime) HasInterval ¶ added in v0.0.24
* HasInterval reports whether the time places the event on the timeline by
- itself: a date, a year, a circa year, an ordinal or a resolved relation. *
- Returns:
- bool — true when Start and End are set. *
- Example:
- knowledge.StoryTime{Relation: "after", Anchor: "x"}.HasInterval() // false
type TableDiff ¶ added in v0.0.15
type TableDiff struct {
Table string
CountA int
CountB int
OnlyA []string
OnlyB []string
Different []RowDifference
}
- TableDiff is what differs in one table between two databases. *
- Fields:
- Table (string) — the table name.
- CountA (int) — rows on the first side.
- CountB (int) — rows on the second side.
- OnlyA ([]string) — labels of rows only on the first side.
- OnlyB ([]string) — labels of rows only on the second side.
- Different ([]RowDifference) — rows on both sides whose compared columns differ. *
- Example:
- fmt.Println(d.Table, len(d.OnlyA), len(d.OnlyB), len(d.Different))
func DiffDatabases ¶ added in v0.0.15
* DiffDatabases compares two knowledge bases table by table, over every table
- that travels, and reports rows only on one side and rows on both sides whose
- compared columns differ. It reads and changes nothing. It uses the same
- notion of "the same row" as merge: name for projects and concepts, uuid for
- observations, sources, documents and sections, the DR-0018 identity for
- records, and the pair of parent identities for links. *
- The compared columns are: projects description and status; concepts
- description and identifier; sources title, identifier and retraction;
- observations kind and body; records checksum; documents checksum; sections
- heading, body and summary. Links have identity only. *
- A row deleted on one side is indistinguishable from a row added on the
- other: there are no tombstones. *
- Both paths must carry the current schema (see PrepareMergeScratch). *
- Parameters:
- aPath (string) — the first database.
- bPath (string) — the second database. *
- Returns:
- []TableDiff — one per table, in a fixed order, clean tables included.
- error — on database failure. *
- Example:
- diffs, err := knowledge.DiffDatabases(s.A, s.B)
type TextRecall ¶ added in v0.0.15
type TextRecall struct {
Matched []string
Hits []TextRecallHit
Projects []string
}
- TextRecall is the result of RecallByText or RecallByNames. *
- Fields:
- Matched ([]string) — the concept names the recall used: those found in the text,
- or the canonical form of the names supplied. Empty when none.
- Hits ([]TextRecallHit) — items linked to them, ranked by matched concepts
- descending then recency, truncated to the limit.
- Projects ([]string) — names of projects linked to a matched concept, listed apart
- from Hits and not truncated by the limit. *
- Example:
- r, _ := kb.RecallByText("how does toast work", 10, "")
- fmt.Println(r.Matched, len(r.Hits))
type TextRecallHit ¶ added in v0.0.15
type TextRecallHit struct {
ConceptMatch
Project string
Concepts []string
}
* TextRecallHit is one item RecallByText or RecallByNames found: a
- ConceptMatch plus the two things a curator needs to judge it. *
- Fields:
- ConceptMatch — the item itself; SourceType is "observation", "record",
- "document_gist" or "document_section", and MatchCount is
- how many of the matched concepts it links to.
- Project (string) — the owning project's name; "" for a workspace-tier record.
- Concepts ([]string) — exactly the matched concepts this item links to, in the
- order of TextRecall.Matched. *
- Example:
- for _, h := range r.Hits { fmt.Println(h.SourceType, h.ID, h.Project, h.Concepts) }
type TimelineEntry ¶ added in v0.0.24
type TimelineEntry struct {
Event StoryEvent
DocumentPath string
Rank int
Unordered bool
Undated bool
InCycle bool
}
* TimelineEntry is one row of a story timeline (DR-0075 item 9): an event in
- the order it was asked for, with what is and is not known about that order. *
- Unordered is true when this entry's place after the one before it is not
- established: their intervals overlap, or they are different kinds of time, or
- nothing relates them. It is reported, never guessed (DR-0075 item 8). Undated
- is true, in story order, for an event with no interval and no relation to any
- other event, and, in narrative order, for an event with no interval of its own.
- InCycle is true for an event in, or ordered behind, a cycle of ordering
- relations; a cycle is reported by StoryCheck. *
- Example:
- es, _ := kb.StoryTimeline(pid, false)
- for _, e := range es { fmt.Println(e.Rank, e.Event.Label, e.Unordered) }
type UsageCount ¶ added in v0.0.14
- UsageCount is one line of an InUseError: what depends on the target, and how many. *
- Fields:
- What (string) — a short noun phrase, for example "concept link(s)".
- N (int) — how many. *
- Example:
- c := knowledge.UsageCount{What: "observation(s)", N: 3}
type Vectors ¶ added in v0.0.29
type Vectors struct {
// contains filtered or unexported fields
}
* Vectors is an open vector sidecar. Make one with OpenVectors or
- CreateVectors and close it with Close.
func CreateVectors ¶ added in v0.0.29
* CreateVectors opens the sidecar of a database, creating it for the embedder
- if it does not exist. An existing sidecar must have been built by the same
- model. *
- Parameters:
- dbPath (string) — the knowledge database's path (the sidecar's is derived)
- e (Embedder) — the embedder whose vectors the sidecar will hold *
- Returns:
- *Vectors — the open sidecar
- error — ErrModelMismatch when the existing sidecar was built by another
- model; otherwise as OpenVectors *
- Example:
- v, err := knowledge.CreateVectors("agents/knowledge.db", embedder)
func OpenVectors ¶ added in v0.0.29
* OpenVectors opens the sidecar of a database that already has one. It never
- creates the file, so a search cannot build an index by accident. *
- Parameters:
- dbPath (string) — the knowledge database's path (the sidecar's is derived) *
- Returns:
- *Vectors — the open sidecar
- error — ErrNoIndex when there is no sidecar; ErrInvalid when the file is not
- a vector index or was written by a newer schema; an OS error otherwise *
- Example:
- v, err := knowledge.OpenVectors("agents/knowledge.db")
func ResetVectors ¶ added in v0.0.29
* ResetVectors deletes the sidecar of a database, if there is one, and creates
- a fresh one for the embedder. It is the explicit rebuild: EmbedIndex refuses a
- different model, and this is how the user chooses to start over. *
- Parameters:
- dbPath (string) — the knowledge database's path (the sidecar's is derived)
- e (Embedder) — the embedder whose vectors the new sidecar will hold *
- Returns:
- *Vectors — the new, empty sidecar
- error — an OS error removing the old file, or as CreateVectors *
- Example:
- v, err := knowledge.ResetVectors("agents/knowledge.db", embedder)
func (*Vectors) Building ¶ added in v0.0.29
* Building reports whether a kb embed run holds a live claim on the sidecar, so
- the index is part way through being built and a search of it would see only
- some of the rows. A claim whose heartbeat is older than LockStaleAfter is a
- run that died, and does not count. *
- Returns:
- bool — true while another run is building the index
- error — a database error *
- Example:
- if busy, _ := v.Building(); busy { fmt.Println("try again later") }
func (*Vectors) CheckModel ¶ added in v0.0.29
* CheckModel reports whether e is the model the sidecar was built with: same
- name, dimensions and fingerprint. *
- Parameters:
- e (Embedder) — the embedder about to use the sidecar *
- Returns:
- error — nil, or ErrModelMismatch naming both models and the remedy *
- Example:
- if err := v.CheckModel(embedder); err != nil { return err }
func (*Vectors) ChunkCount ¶ added in v0.0.29
- ChunkCount returns how many chunks the sidecar stores. *
- Returns:
- int — the count
- error — a database error *
- Example:
- n, err := v.ChunkCount()
func (*Vectors) DeleteRow ¶ added in v0.0.29
- DeleteRow removes every chunk of a row. A row with none is not an error. *
- Parameters:
- sourceType (string) — kb_fts source_type of the row
- sourceID (int64) — the row's id *
- Returns:
- error — a database error *
- Example:
- err := v.DeleteRow("observation", 12)
func (*Vectors) IndexedRows ¶ added in v0.0.29
- IndexedRows lists the rows that have chunks in the sidecar. *
- Returns:
- []RowKey — the rows, ordered by type then id
- error — a database error *
- Example:
- rows, err := v.IndexedRows()
func (*Vectors) Lock ¶ added in v0.0.29
func (v *Vectors) Lock() (*VectorsLock, error)
* Lock claims the sidecar for writing. A claim made by another run blocks it
- until that run releases or its heartbeat is older than LockStaleAfter. *
- Returns:
- *VectorsLock — the claim; call Heartbeat as work goes on and Release when done
- error — ErrLocked, with who holds it and since when; a database error otherwise *
- Example:
- l, err := v.Lock()
- if err != nil { return err }
- defer l.Release()
func (*Vectors) Meta ¶ added in v0.0.29
func (v *Vectors) Meta() VectorsMeta
- Meta returns what the sidecar recorded about how it was built. *
- Returns:
- VectorsMeta — the schema version, model, dimensions and fingerprint
func (*Vectors) PutRow ¶ added in v0.0.29
func (v *Vectors) PutRow(sourceType string, sourceID int64, chunks []StoredChunk) error
* PutRow stores the chunks of one row, replacing any it had, in one
- transaction: after it returns the row has exactly these chunks, and if it
- fails the row is as it was. *
- Parameters:
- sourceType (string) — kb_fts source_type of the row
- sourceID (int64) — the row's id
- chunks ([]StoredChunk) — the row's chunks; each vector must have the sidecar's dimensions *
- Returns:
- error — ErrInvalid for a vector of the wrong length; a database error otherwise *
- Example:
- err := v.PutRow("observation", 12, chunks)
func (*Vectors) RowChunks ¶ added in v0.0.29
func (v *Vectors) RowChunks(sourceType string, sourceID int64) ([]StoredChunk, error)
- RowChunks returns the chunks stored for a row, in chunk order. *
- Parameters:
- sourceType (string) — kb_fts source_type of the row
- sourceID (int64) — the row's id *
- Returns:
- []StoredChunk — the chunks, none if the row is not indexed
- error — a database error *
- Example:
- chunks, err := v.RowChunks("record", 3)
type VectorsLock ¶ added in v0.0.29
type VectorsLock struct {
// contains filtered or unexported fields
}
* VectorsLock is a claim on a vector sidecar, held by one run. The claim is a
- row in the sidecar itself, not an operating-system lock, so it behaves the
- same on every platform and in a directory that is synced or on a network.
func (*VectorsLock) Heartbeat ¶ added in v0.0.29
func (l *VectorsLock) Heartbeat() error
* Heartbeat refreshes the claim so it does not go stale, and confirms this run
- still holds it. *
- Returns:
- error — ErrLocked when the claim was taken over after it went stale (the
- run should stop without writing); a database error otherwise *
- Example:
- if err := l.Heartbeat(); err != nil { return err }
func (*VectorsLock) Release ¶ added in v0.0.29
func (l *VectorsLock) Release() error
* Release gives up the claim. It only drops a claim this run still owns, so
- releasing after the claim was taken over, or releasing twice, leaves the new
- owner's claim alone. *
- Returns:
- error — a database error *
- Example:
- defer l.Release()
type VectorsMeta ¶ added in v0.0.29
- VectorsMeta is what the sidecar records about how it was built. *
- Fields:
- SchemaVersion (int) — the version of the sidecar's tables
- Model (string) — the embedding model's name
- Dimensions (int) — the length of each vector
- Fingerprint (string) — identifies the exact model files *
- Example:
- m := v.Meta()
- fmt.Println(m.Model, m.Dimensions)
type WhoKnowsResult ¶ added in v0.0.25
type WhoKnowsResult struct {
Character string
Scene string
Facts []KnownFact
Unordered []KnownFact
}
- WhoKnowsResult is what WhoKnows returns (DR-0083 item 5). *
- Character is the character as the story spells them, Scene the name of the
- scene asked about ("" when none was). Facts are what the character has learned
- at or before that scene, in story order. Unordered are facts learned only in
- scenes whose order against the scene is not established; they are neither
- counted as known nor left out (DR-0075 item 8). Both are empty, not nil. *
- Example:
- r, _ := kb.WhoKnows(pid, "Anna", "12A")
- for _, f := range r.Facts { fmt.Println(f.Fact) }
Source Files
¶
- chunk.go
- comparejsonl.go
- conceptcluster.go
- conceptdelete.go
- conceptdetail.go
- conceptkind.go
- conceptrecall.go
- conceptsuggest.go
- documentfrontmatter.go
- documentfuzzytag.go
- documentingest.go
- documents.go
- documenttag.go
- embedcorpus.go
- embedder.go
- errors.go
- hitprovenance.go
- jsonl.go
- knowledge.go
- knowledge_merge.go
- mergedetect.go
- observationreview.go
- provenance.go
- recordfile.go
- recordfuzzytag.go
- records.go
- recordtransitions.go
- ref.go
- removal.go
- retraction_check.go
- retrieval.go
- scope.go
- scopedsearch.go
- searchhit.go
- searchsemantic.go
- sourcefields.go
- sourcelinks.go
- sourcerefs.go
- stats.go
- story.go
- storycheck.go
- storyevents.go
- storyknowledge.go
- storyknowledgecheck.go
- storytime.go
- storytimeline.go
- vectors.go
- vectorsearch.go
- vectorsfuse.go
- vectorsindex.go
- vectorslock.go
- version.go
- workspace.go
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
kb
command
kb is a command-line and interactive (TUI) interface for a github.com/rsdoiel/knowledge knowledge base.
|
kb is a command-line and interactive (TUI) interface for a github.com/rsdoiel/knowledge knowledge base. |
|
Package embedtest is a deterministic fake embedder for tests of semantic search, in this module's tests, the CLI's and the semantic module's.
|
Package embedtest is a deterministic fake embedder for tests of semantic search, in this module's tests, the CLI's and the semantic module's. |
|
internal
|
|
|
cli
Package cli is the kb command line and interactive (TUI) interface for a github.com/rsdoiel/knowledge knowledge base.
|
Package cli is the kb command line and interactive (TUI) interface for a github.com/rsdoiel/knowledge knowledge base. |
|
evalset
Package evalset measures how well the lexical, semantic and hybrid searches find the rows a person would want, against a set of labelled queries (semantic plan T9).
|
Package evalset measures how well the lexical, semantic and hybrid searches find the rows a person would want, against a set of labelled queries (semantic plan T9). |
|
models
Package models manages the embedding model files kb's semantic search needs (DR-0089 item 6): which models kb knows, where installed ones live, and how to install one from a directory or archive (offline) or fetch it (online), checking every file against a recorded size and SHA-256.
|
Package models manages the embedding model files kb's semantic search needs (DR-0089 item 6): which models kb knows, where installed ones live, and how to install one from a directory or archive (offline) or fetch it (online), checking every file against a recorded size and SHA-256. |
|
semantic
module
|