Documentation
¶
Overview ¶
Package vault implements the dumb, deterministic file layer over the markdown vault: CRUD with path traversal protection and optimistic concurrency via content hashes (PHY-106).
Index ¶
- Constants
- Variables
- func TypeOf(e Entry) string
- func ValidStatus(s string) bool
- type Change
- type Entry
- type Index
- func (ix *Index) All() []Entry
- func (ix *Index) Backlinks(path string) []string
- func (ix *Index) Build() error
- func (ix *Index) FindInboxStale(inbox string, maxAge time.Duration) []Entry
- func (ix *Index) FindOrphans() []Entry
- func (ix *Index) FindUntagged() []Entry
- func (ix *Index) Get(path string) (Entry, bool)
- func (ix *Index) Len() int
- func (ix *Index) Links(path string) []string
- func (ix *Index) ListTasks(status, project string) []Entry
- func (ix *Index) OnChange(fn func(Change))
- func (ix *Index) PathsByTag(tag string) []string
- func (ix *Index) Remove(path string)
- func (ix *Index) Rename(from, to string) error
- func (ix *Index) SuggestLinks(v *Vault, notePath string) ([]LinkCandidate, error)
- func (ix *Index) SuggestLocation(content string, s Structure) []LocationSuggestion
- func (ix *Index) SuggestTags(v *Vault, notePath string) (*TagsContext, error)
- func (ix *Index) Tags() []TagCount
- func (ix *Index) Update(path string) error
- type LinkCandidate
- type LocationSuggestion
- type Note
- type NoteInfo
- type Option
- type Result
- type ScanSearcher
- type SearchOpts
- type Searcher
- type Snippet
- type Structure
- type TagCount
- type TagsContext
- type Vault
- func (v *Vault) AddTags(path string, tags []string, expectedHash string) ([]string, error)
- func (v *Vault) Append(path, content, expectedHash string) error
- func (v *Vault) CreateDir(dir string) error
- func (v *Vault) Delete(path string) error
- func (v *Vault) DeleteDir(dir string) error
- func (v *Vault) InitStructure(s Structure) (bool, error)
- func (v *Vault) List(dir string, recursive bool) ([]NoteInfo, error)
- func (v *Vault) ListDirs() ([]string, error)
- func (v *Vault) Move(from, to string) error
- func (v *Vault) Patch(path, section, newContent, expectedHash string) error
- func (v *Vault) Prepend(path, content, expectedHash string) error
- func (v *Vault) Read(path string) (*Note, error)
- func (v *Vault) ReadRaw(path string) (string, error)
- func (v *Vault) RemoveTags(path string, tags []string, expectedHash string) ([]string, error)
- func (v *Vault) ResolveWritePath(requested, content string, s Structure) (string, error)
- func (v *Vault) Root() string
- func (v *Vault) SetStatus(path, status, expectedHash string) error
- func (v *Vault) Write(path, content string, opts WriteOptions) error
- type WriteOptions
Constants ¶
const ( TypeTask = "task" TypeKnowledge = "knowledge" StatusBacklog = "backlog" StatusInProgress = "in-progress" StatusDone = "done" )
Note type and task status conventions. Plain frontmatter, no task engine: a note is a task when `type: task`; without a type it is knowledge.
const DefaultMaxFileSize = 10 << 20
DefaultMaxFileSize is the default cap for a single note (10 MB).
Variables ¶
var ( ErrInvalidPath = errors.New("invalid path") ErrNotMarkdown = errors.New("not a markdown file") ErrNotFound = errors.New("note not found") ErrExists = errors.New("note already exists") ErrConflict = errors.New("content hash mismatch") ErrTooLarge = errors.New("file exceeds maximum size") ErrSectionNotFound = errors.New("section not found") )
Sentinel errors. Callers (MCP tools, REST API) map these to protocol errors; the REST layer maps ErrConflict to HTTP 409.
Functions ¶
func TypeOf ¶
TypeOf returns the effective note type of an index entry, applying the knowledge default.
func ValidStatus ¶
ValidStatus reports whether s is one of the task statuses.
Types ¶
type Change ¶ added in v1.9.0
Change is one incremental index mutation, published to OnChange observers. A rename arrives as two changes: the old path deleted, the new one updated.
type Entry ¶
type Entry struct {
Path string `json:"path"`
Title string `json:"title"`
Excerpt string `json:"excerpt,omitempty"` // first body line, for list views
Tags []string `json:"tags,omitempty"`
Links []string `json:"links,omitempty"` // raw targets as written in the note
Type string `json:"type,omitempty"` // frontmatter `type` (task|knowledge)
Status string `json:"status,omitempty"`
ModTime int64 `json:"modTime"`
Size int64 `json:"size"`
}
Entry is the indexed metadata of a single note. Raw link targets are kept as written; resolution to vault paths happens in the index maps.
type Index ¶
type Index struct {
// contains filtered or unexported fields
}
Index is the in-memory metadata index: tags and backlinks as instant lookups. It is rebuilt from disk once at startup and updated incrementally on every write that goes through the layers above (the vault file layer itself stays dumb).
func (*Index) Build ¶
Build scans the whole vault in one pass. Files are read concurrently; entries and link resolution are computed once at the end.
func (*Index) FindInboxStale ¶
FindInboxStale returns inbox notes untouched for longer than maxAge, oldest first.
func (*Index) FindOrphans ¶
FindOrphans returns notes with no incoming and no outgoing resolved links.
func (*Index) FindUntagged ¶
FindUntagged returns notes without any tags.
func (*Index) ListTasks ¶
ListTasks returns task entries from the index, optionally filtered by status and project (a folder under projects/, e.g. "vellum" matches projects/vellum/**). Instant lookup — no file IO.
func (*Index) OnChange ¶ added in v1.9.0
OnChange registers an observer called after every incremental mutation (Update/Remove/Rename). Build does not emit — it runs once at startup, before observers exist. Observers run synchronously outside the index lock, so they may read the index but must not block for long.
func (*Index) PathsByTag ¶
PathsByTag returns the sorted paths carrying a tag.
func (*Index) SuggestLinks ¶
func (ix *Index) SuggestLinks(v *Vault, notePath string) ([]LinkCandidate, error)
SuggestLinks returns link candidates for a note: shared tags, title mentions in the body, and backlinks without a forward link.
func (*Index) SuggestLocation ¶
func (ix *Index) SuggestLocation(content string, s Structure) []LocationSuggestion
SuggestLocation ranks existing directories by tag overlap with the given content. The inbox is always the fallback candidate.
func (*Index) SuggestTags ¶
func (ix *Index) SuggestTags(v *Vault, notePath string) (*TagsContext, error)
SuggestTags gathers the context for tagging: the note excerpt, its current tags, the vault-wide tag vocabulary and tags of linked notes.
type LinkCandidate ¶
type LinkCandidate struct {
Path string `json:"path"`
Title string `json:"title"`
Reason string `json:"reason"`
}
LinkCandidate is a note that might deserve a link.
type LocationSuggestion ¶
type LocationSuggestion struct {
Dir string `json:"dir"`
NoteCount int `json:"noteCount"`
Reason string `json:"reason"`
}
LocationSuggestion is a candidate directory for new content.
type Note ¶
type Note struct {
Path string `json:"path"`
Title string `json:"title"`
Content string `json:"content"` // raw file content incl. frontmatter
Body string `json:"body"` // content without the frontmatter block
Frontmatter map[string]any `json:"frontmatter,omitempty"`
Tags []string `json:"tags,omitempty"`
Links []string `json:"links,omitempty"`
Hash string `json:"hash"` // sha256 hex of Content
Size int64 `json:"size"`
ModTime time.Time `json:"modTime"`
}
Note is a fully read note.
type NoteInfo ¶
type NoteInfo struct {
Path string `json:"path"`
Title string `json:"title"`
Size int64 `json:"size"`
ModTime time.Time `json:"modTime"`
}
NoteInfo is the lightweight listing entry.
type Option ¶
type Option func(*Vault)
Option configures a Vault.
func WithMaxFileSize ¶
WithMaxFileSize overrides the per-note size cap in bytes.
type Result ¶
type Result struct {
Path string `json:"path"`
Title string `json:"title"`
Snippets []Snippet `json:"snippets,omitempty"`
}
Result is one matching note.
type ScanSearcher ¶
type ScanSearcher struct {
// contains filtered or unexported fields
}
ScanSearcher matches candidate notes against the query, narrowing first through the metadata index (tags, directory) and reading file content through an in-memory cache keyed by the index's modTime+size — so repeated searches are pure RAM, and any write (which updates the index) invalidates exactly the notes it touched. Results are ranked by relevance: title matches beat tag matches beat path matches beat body hits; a typo-tolerant fallback keeps misspelled queries working at a rank below any exact hit.
func NewScanSearcher ¶
func NewScanSearcher(v *Vault, ix *Index) *ScanSearcher
NewScanSearcher builds the default searcher.
func (*ScanSearcher) Search ¶
func (s *ScanSearcher) Search(query string, opts SearchOpts) ([]Result, error)
Search runs a ranked, case- and diacritics-insensitive search. Multi-word queries AND their terms: every term must appear in the note's title, tags, path or body — or be within its typo budget of some word. An empty query returns the metadata-filtered notes without snippets, which is how a pure tag filter is expressed. Regex mode matches line-by-line like grep.
Two phases keep it fast: a parallel scoring pass over the candidates that does no snippet work, then snippet extraction for the top MaxResults only.
type SearchOpts ¶
type SearchOpts struct {
// Tags that must all be present on a note (AND). Applied via the
// metadata index before any file is opened.
Tags []string
// Dir limits results to a vault subtree (path prefix).
Dir string
// Regex treats the query as a regular expression (case-insensitive).
Regex bool
// MaxResults caps the number of returned notes (default 50).
MaxResults int
// ContextLines is the number of lines around a match in the snippet
// (default 2).
ContextLines int
// MaxSnippets caps snippets per note (default 3).
MaxSnippets int
}
SearchOpts narrow and shape a search.
type Searcher ¶
type Searcher interface {
Search(query string, opts SearchOpts) ([]Result, error)
}
Searcher is the search abstraction. The default implementation is a zero-dependency ranked scan over an in-memory content cache; a bleve-backed index can slot in behind the same interface later if that ever hurts.
type Snippet ¶
type Snippet struct {
Line int `json:"line"` // 1-based line number of the match
Match string `json:"match"` // exact matched text (for highlighting)
Context string `json:"context"` // match line ± ContextLines
}
Snippet is one match with surrounding context.
type Structure ¶
Structure names the conventional top-level directories. It is convention plus configuration, not a vellum-specific lock-in: the layout must make sense when the vault is opened in any other editor.
func DefaultStructure ¶
func DefaultStructure() Structure
DefaultStructure returns the conventional inbox/projects/archive layout.
type TagsContext ¶
type TagsContext struct {
Path string `json:"path"`
CurrentTags []string `json:"currentTags,omitempty"`
Excerpt string `json:"excerpt"`
VaultTags []TagCount `json:"vaultTags"`
// NeighborTags are tags used by notes linked from/to this note.
NeighborTags []string `json:"neighborTags,omitempty"`
}
TagsContext is what an agent needs to propose tags for a note.
type Vault ¶
type Vault struct {
// contains filtered or unexported fields
}
Vault is a safe view over a directory of markdown files. All paths accepted by its methods are vault-relative, forward-slash separated.
func (*Vault) AddTags ¶
AddTags adds tags to the note's frontmatter `tags:` field (surgical edit, other fields untouched). Inline #tags in the body are not modified. Returns the resulting frontmatter tag list.
func (*Vault) CreateDir ¶ added in v1.2.0
CreateDir creates a directory (and any parents) inside the vault. An existing directory is a no-op; a file already at the path is an error.
func (*Vault) DeleteDir ¶ added in v1.4.0
DeleteDir removes a directory and everything under it (notes included). It refuses to touch the vault root. Callers are expected to confirm with the user first — this is a recursive, irreversible delete.
func (*Vault) InitStructure ¶
InitStructure creates the structure directories when the vault root is empty. It is idempotent and never touches an already-populated vault (so pointing vellum at an existing Obsidian vault changes nothing). It reports whether the directories were created by this call.
func (*Vault) List ¶
List returns the notes in dir ("" = vault root), optionally recursive. Dotfiles, dot-directories and symlinks are skipped.
func (*Vault) ListDirs ¶ added in v1.2.0
ListDirs returns every subdirectory of the vault (vault-relative, forward-slash), dotfiles excluded. Empty directories are included so the SPA tree can show folders that do not hold any notes yet.
func (*Vault) Move ¶
Move renames a note. The target must not exist; parent directories are created as needed.
func (*Vault) Patch ¶
Patch surgically replaces the content under the heading whose text equals section, leaving the heading itself, the frontmatter and the rest of the note untouched. The replaced region ends before the next heading of the same or higher level (or EOF).
func (*Vault) Prepend ¶
Prepend inserts content at the top of the body of an existing note, after the frontmatter block if present.
func (*Vault) Read ¶
Read returns the full note including parsed frontmatter, tags, links and the sha256 content hash used for optimistic concurrency.
func (*Vault) ReadRaw ¶
ReadRaw returns the raw content of a note without any markdown parsing. Same path validation and size limits as Read.
func (*Vault) RemoveTags ¶
RemoveTags removes tags from the note's frontmatter `tags:` field. Inline #tags in the body are not modified. Returns the remaining list.
func (*Vault) ResolveWritePath ¶
ResolveWritePath decides where a new note lands. When the agent names a directory the request is honored; a bare filename or no path at all falls back to the inbox. With no path the filename is derived from the content title and uniquified against existing notes.
type WriteOptions ¶
type WriteOptions struct {
// Overwrite allows replacing an existing note (last-write-wins).
Overwrite bool
// ExpectedHash, when set, must match the sha256 of the current content,
// otherwise ErrConflict is returned and nothing is written. A matching
// hash implies permission to overwrite.
ExpectedHash string
}
WriteOptions control Write behavior.