vault

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2026 License: MIT Imports: 15 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package 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

View Source
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.

View Source
const DefaultMaxFileSize = 10 << 20

DefaultMaxFileSize is the default cap for a single note (10 MB).

Variables

View Source
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

func TypeOf(e Entry) string

TypeOf returns the effective note type of an index entry, applying the knowledge default.

func ValidStatus

func ValidStatus(s string) bool

ValidStatus reports whether s is one of the task statuses.

Types

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 NewIndex

func NewIndex(v *Vault) *Index

NewIndex creates an empty index bound to a vault. Call Build to populate.

func (*Index) All

func (ix *Index) All() []Entry

All returns a snapshot of all entries, sorted by path.

func (ix *Index) Backlinks(path string) []string

Backlinks returns the sorted paths of notes linking to path.

func (*Index) Build

func (ix *Index) Build() error

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

func (ix *Index) FindInboxStale(inbox string, maxAge time.Duration) []Entry

FindInboxStale returns inbox notes untouched for longer than maxAge, oldest first.

func (*Index) FindOrphans

func (ix *Index) FindOrphans() []Entry

FindOrphans returns notes with no incoming and no outgoing resolved links.

func (*Index) FindUntagged

func (ix *Index) FindUntagged() []Entry

FindUntagged returns notes without any tags.

func (*Index) Get

func (ix *Index) Get(path string) (Entry, bool)

Get returns the entry for a path.

func (*Index) Len

func (ix *Index) Len() int

Len returns the number of indexed notes.

func (ix *Index) Links(path string) []string

Links returns the sorted resolved outgoing links of a note.

func (*Index) ListTasks

func (ix *Index) ListTasks(status, project string) []Entry

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) PathsByTag

func (ix *Index) PathsByTag(tag string) []string

PathsByTag returns the sorted paths carrying a tag.

func (*Index) Remove

func (ix *Index) Remove(path string)

Remove drops a note from the index (after Delete).

func (*Index) Rename

func (ix *Index) Rename(from, to string) error

Rename moves an entry (after Move) without re-reading unaffected files.

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.

func (*Index) Tags

func (ix *Index) Tags() []TagCount

Tags returns all tags with counts, sorted by tag.

func (*Index) Update

func (ix *Index) Update(path string) error

Update re-reads a single note after a write (or first write) and refreshes the derived maps. If the file no longer exists it is removed instead.

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"`
	SharedTags []string `json:"sharedTags,omitempty"`
	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

func WithMaxFileSize(n int64) Option

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 scans candidate files in parallel, narrowing first through the metadata index (tags, directory) so only the remainder is read. No warm-up, no index to corrupt.

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 case-insensitive substring (or regex) search. An empty query returns the metadata-filtered notes without snippets, which is how a pure tag filter is expressed.

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 parallel scan; a bleve-backed index can slot in behind the same interface later if scanning 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

type Structure struct {
	Inbox    string
	Projects string
	Archive  string
}

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 TagCount

type TagCount struct {
	Tag   string `json:"tag"`
	Count int    `json:"count"`
}

TagCount is a tag with its number of notes.

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 New

func New(dir string, opts ...Option) (*Vault, error)

New opens a vault rooted at dir. The directory must exist.

func (*Vault) AddTags

func (v *Vault) AddTags(path string, tags []string, expectedHash string) ([]string, error)

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) Append

func (v *Vault) Append(path, content, expectedHash string) error

Append adds content at the end of an existing note.

func (*Vault) Delete

func (v *Vault) Delete(path string) error

Delete removes a note.

func (*Vault) InitStructure

func (v *Vault) InitStructure(s Structure) (bool, error)

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

func (v *Vault) List(dir string, recursive bool) ([]NoteInfo, error)

List returns the notes in dir ("" = vault root), optionally recursive. Dotfiles, dot-directories and symlinks are skipped.

func (*Vault) Move

func (v *Vault) Move(from, to string) error

Move renames a note. The target must not exist; parent directories are created as needed.

func (*Vault) Patch

func (v *Vault) Patch(path, section, newContent, expectedHash string) error

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

func (v *Vault) Prepend(path, content, expectedHash string) error

Prepend inserts content at the top of the body of an existing note, after the frontmatter block if present.

func (*Vault) Read

func (v *Vault) Read(path string) (*Note, error)

Read returns the full note including parsed frontmatter, tags, links and the sha256 content hash used for optimistic concurrency.

func (*Vault) ReadRaw

func (v *Vault) ReadRaw(path string) (string, error)

ReadRaw returns the raw content of a note without any markdown parsing. Same path validation and size limits as Read.

func (*Vault) RemoveTags

func (v *Vault) RemoveTags(path string, tags []string, expectedHash string) ([]string, error)

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

func (v *Vault) ResolveWritePath(requested, content string, s Structure) (string, error)

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.

func (*Vault) Root

func (v *Vault) Root() string

Root returns the absolute vault root directory.

func (*Vault) SetStatus

func (v *Vault) SetStatus(path, status, expectedHash string) error

SetStatus marks a note as a task with the given status via a surgical frontmatter edit: only the `status` (and if needed `type`) lines change, every other frontmatter field and the body stay byte-identical. A note without frontmatter gets a minimal block prepended.

func (*Vault) Write

func (v *Vault) Write(path, content string, opts WriteOptions) error

Write creates or replaces a note. Parent directories are created as needed.

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.

Jump to

Keyboard shortcuts

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