vault

package
v1.13.2 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 26 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 (
	RankerBM25F  = "bm25f"
	RankerLegacy = "legacy"
)

Ranker names for VELLUM_RANKER while BM25F rolls out: both rankers can be compared over the same vault and golden set. RankerLegacy goes once BM25F is accepted.

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 DefaultContextFile = "_index.md"

DefaultContextFile is the file name of a folder's description note.

View Source
const DefaultMaxFileSize = 10 << 20

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

View Source
const NoContext = -1

NoContext asks for snippets without surrounding lines: ContextLines is zero-means-default, so a real zero needs its own value.

Variables

View Source
var (
	// ErrPatchOp rejects an operation PatchSection does not know.
	ErrPatchOp = errors.New("unknown operation")
	// ErrEmptyContent rejects an insert of nothing: only replace may
	// empty a section.
	ErrEmptyContent = errors.New("content must not be empty")
)
View Source
var (
	// ErrEmptyOldText rejects a replacement without text to find: an empty
	// string matches everywhere and nowhere in particular.
	ErrEmptyOldText = errors.New("old_text must not be empty")
	// ErrTextNotFound means the text to replace does not occur in the note.
	ErrTextNotFound = errors.New("text not found")
	// ErrTextNotUnique means the text occurs more than once and the caller
	// did not ask to replace every occurrence.
	ErrTextNotUnique = errors.New("text occurs more than once")
)
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")
	// ErrSectionAmbiguous means a section name matches more than one
	// heading; nothing is read or written by guess (NSO-575).
	ErrSectionAmbiguous = errors.New("section is ambiguous")
)

Sentinel errors. Callers (MCP tools, REST API) map these to protocol errors; the REST layer maps ErrConflict to HTTP 409.

PatchOps lists the operations in the order the tool describes them.

Functions

func SectionLines added in v1.13.0

func SectionLines(content, section string) (first, last int, err error)

SectionLines returns the file lines (1-based, inclusive, frontmatter counted) of the section patch_note would edit: its heading line and everything under it up to the next heading of the same or a higher level. section may be a heading path ("Parent > Child"). A missing section fails with ErrSectionNotFound, naming the headings the note does have, one that names several headings with ErrSectionAmbiguous, naming them.

func SplitLines added in v1.13.0

func SplitLines(content string) []string

SplitLines splits content into file lines the way search numbers them (strings.Split on "\n"), but keeps each line's terminator so a slice of lines joins back into the exact bytes of the file. A trailing newline ends the last line rather than starting an empty one.

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.

func ValidateContextFile added in v1.13.0

func ValidateContextFile(name string) error

ValidateContextFile checks a folder description file name: a markdown file name without a directory, not hidden (the vault scan skips dotfiles).

Types

type Change added in v1.9.0

type Change struct {
	Path    string
	Deleted bool
	// From is set on the update half of a rename that Reconcile inferred
	// from the disk (a note moved outside vellum): the path the note had
	// before. Renames through vellum (Rename) leave it empty; their caller
	// already knows both paths.
	From string
}

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 DirCount added in v1.13.0

type DirCount struct {
	Path  string `json:"path"`  // vault-relative, usable as a dir argument
	Notes int    `json:"notes"` // notes in the folder and all its subfolders
	// Description is the folder's description (NSO-573), if it has one.
	Description string `json:"description,omitempty"`
}

DirCount is a folder with the number of notes beneath it, nested folders included.

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"`
	// contains filtered or unexported fields
}

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 Heading added in v1.13.0

type Heading struct {
	Level int    `json:"level"` // 1 for "#", up to 6
	Text  string `json:"text"`
	Line  int    `json:"line"` // 1-based file line, frontmatter counted
}

Heading is one markdown heading of a note, as read_note's outline reports it.

func Outline added in v1.13.0

func Outline(content string) []Heading

Outline lists the headings of a note's body with their file line numbers (1-based, frontmatter counted, the numbering search snippets use). Headings inside fenced code blocks are skipped.

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). Changes made outside vellum (another editor, git, a second vellum process) are picked up lazily by Reconcile, see SetRescanInterval.

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. Build does not emit changes: it runs at startup, before observers exist.

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) FindUndescribedFolders added in v1.13.0

func (ix *Index) FindUndescribedFolders(minNotes int) []UndescribedFolder

FindUndescribedFolders returns the folders with at least minNotes notes of their own (subfolders not counted) and no description, most notes first. Description notes themselves are not counted.

func (*Index) FindUntagged

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

FindUntagged returns notes without any tags.

func (*Index) FolderContexts added in v1.13.0

func (ix *Index) FolderContexts(notePaths ...string) map[string]string

FolderContexts returns the descriptions of the folders holding the given notes and of all their parent folders, keyed by folder path, each level separately (they are not merged). The vault root is left out: its description goes into the server instructions once per session. Nil when none of these folders is described, so a vault without description notes answers exactly as before. Map keys sort parent before child, so the JSON of the map reads from the top folder down.

func (*Index) FolderDescription added in v1.13.0

func (ix *Index) FolderDescription(dir string) string

FolderDescription returns the description of dir ("" = the vault root), or "" when it has none.

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) OnChange added in v1.9.0

func (ix *Index) OnChange(fn func(Change))

OnChange registers an observer called after every incremental mutation (Update/Remove/Rename/Reconcile). 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

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

PathsByTag returns the sorted paths carrying a tag.

func (*Index) Reconcile added in v1.13.0

func (ix *Index) Reconcile() (ReconcileStats, error)

Reconcile brings the index in line with the disk after changes made outside vellum: an edit in another editor, a git pull, a second vellum process over the same vault. It walks the vault by the rules of List and compares each note's size and modification time with its entry; only new and changed notes are read, entries of vanished notes are dropped, and the derived maps are rebuilt once at the end, however many notes changed. A note that disappears while one with the same file name and size appears elsewhere, the only such pair in this scan, is taken as moved (Change.From), so a share link can follow it. Observers get a Change for every touched path after the index lock is released.

An edit that keeps both the size and the modification time is not detected; with nanosecond timestamps that is rare.

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 (*Index) RescanInterval added in v1.13.0

func (ix *Index) RescanInterval() time.Duration

RescanInterval returns the interval set by SetRescanInterval, 0 if off.

func (*Index) SetRescanInterval added in v1.13.0

func (ix *Index) SetRescanInterval(d time.Duration)

SetRescanInterval turns on the lazy reconcile (NSO-562): an index read (search, tags, backlinks, tasks, the curator, folder contexts) first runs Reconcile when the last one is older than d. Only one reconcile runs at a time; a read that finds one in progress does not wait and answers from the current state. There is no background goroutine: an idle server does no work. d <= 0 turns it off (the default of a new Index).

func (*Index) Subdirs added in v1.13.0

func (ix *Index) Subdirs(dir string) ([]DirCount, error)

Subdirs returns the direct subfolders of dir ("" = vault root) in path order, each with the number of indexed notes beneath it. The counts come from the index, not from another walk of the tree; folders without notes (which the index cannot know about) are added from one read of dir itself, with a count of 0. Dot-folders and symlinks are skipped, as in List.

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 their overlap with the given content: tags shared with the folder's notes, and words shared with the folder's description (folded and split into words as search does). Each shared tag or word counts one; ties go to more shared tags, then to the path. A folder whose notes have no tag in common with the content is still offered when its description matches. 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 LineSpan added in v1.13.0

type LineSpan struct {
	First, Last int
}

LineSpan is a range of file lines, 1-based and inclusive, counted over the whole file (frontmatter included).

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 ListOptions added in v1.13.0

type ListOptions struct {
	Offset int // skip the first Offset notes of the sorted listing
	Limit  int // at most Limit notes, 0 = no cap
	// Since keeps the notes modified at or after it; zero keeps all.
	Since time.Time
	// ByModified sorts by modification time, newest first, and notes
	// modified at the same time by path, so the order is deterministic.
	ByModified bool
}

ListOptions picks the order, a modification-time filter and the window of a listing (ListWith). The zero value is List: every note, by path.

type LocationSuggestion

type LocationSuggestion struct {
	Dir        string   `json:"dir"`
	SharedTags []string `json:"sharedTags,omitempty"`
	NoteCount  int      `json:"noteCount"`
	Reason     string   `json:"reason"`
	// Description is the folder's own description (NSO-573), if it has one.
	Description string `json:"description,omitempty"`
}

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"`
	// Excerpt is the note's first line of body text, from the index. Only
	// list_notes with sort: modified fills it (NSO-576); empty elsewhere.
	Excerpt string `json:"excerpt,omitempty"`
}

NoteInfo is the lightweight listing entry.

type Option

type Option func(*Vault)

Option configures a Vault.

func WithContextFile added in v1.13.0

func WithContextFile(name string) Option

WithContextFile sets the file name of the folder description notes (VELLUM_CONTEXT_FILE), for vaults whose convention is README.md or index.md. New rejects a name that is not a plain markdown file name.

func WithMaxFileSize

func WithMaxFileSize(n int64) Option

WithMaxFileSize overrides the per-note size cap in bytes.

type Page added in v1.13.0

type Page struct {
	Results []Result
	// Total is the number of notes the query matched before Offset and
	// MaxResults cut the window out of it.
	Total int
	// Relaxed is set when no note matched every query term and the results
	// are the notes that miss one of them (NSO-578).
	Relaxed bool
}

Page is one window of a ranked or sorted list plus the length of the whole list, so a caller can tell an agent how much it did not see.

func SearchPage added in v1.13.0

func SearchPage(s Searcher, query string, opts SearchOpts) (Page, error)

SearchPage runs a paged search on any Searcher. A PagedSearcher answers directly; any other one ranks everything and the window is cut here, which gives the same results at the cost of snippets for every match.

type PagedSearcher added in v1.13.0

type PagedSearcher interface {
	Searcher
	SearchPage(query string, opts SearchOpts) (Page, error)
}

PagedSearcher is a Searcher that can report the size of the full ranking along with one window of it. ScanSearcher implements it.

type PatchOp added in v1.13.0

type PatchOp string

PatchOp says what PatchSection does with the section.

const (
	// PatchReplace swaps the section's body; its heading line stays.
	PatchReplace PatchOp = "replace"
	// PatchAppend adds content at the end of the section, after its
	// subsections if it has any, before the next heading of the same or
	// a higher level.
	PatchAppend PatchOp = "append"
	// PatchPrepend adds content at the start of the section's body,
	// right under its heading.
	PatchPrepend PatchOp = "prepend"
	// PatchInsertBefore inserts content (typically a new section with
	// its heading) before the section's heading.
	PatchInsertBefore PatchOp = "insert_before"
	// PatchInsertAfter inserts content after the end of the section,
	// before the next heading of the same or a higher level (or at the
	// end of the note).
	PatchInsertAfter PatchOp = "insert_after"
)

func ParsePatchOp added in v1.13.0

func ParsePatchOp(s string) (PatchOp, error)

ParsePatchOp maps an operation name to its PatchOp; empty means PatchReplace.

type PatchResult added in v1.13.0

type PatchResult struct {
	Content string   // the note as written
	Hash    string   // sha256 hex of Content, the next expected_hash
	Lines   LineSpan // the file lines the new content occupies, frontmatter counted
}

PatchResult describes a successful PatchSection.

type ReconcileStats added in v1.13.0

type ReconcileStats struct {
	Added   int // notes new on disk
	Updated int // notes whose size or modification time changed
	Removed int // notes gone from disk
	Moved   int // a removal and an addition recognized as one rename
}

ReconcileStats counts what one Reconcile changed in the index.

func (ReconcileStats) Changed added in v1.13.0

func (s ReconcileStats) Changed() bool

Changed reports whether the index changed at all.

type ReplaceResult added in v1.13.0

type ReplaceResult struct {
	Content string     // the note as written
	Hash    string     // sha256 hex of Content, the next expected_hash
	Count   int        // occurrences replaced
	Spans   []LineSpan // per replacement, the lines its new text occupies, in file order
}

ReplaceResult describes a successful Replace.

type Result

type Result struct {
	Path  string `json:"path"`
	Title string `json:"title"`
	// Score is the BM25F relevance of a ranked text search, 0 to 1 and not
	// relative to the best hit (see search_bm25f.go). Left out (0) where
	// nothing is ranked: regex mode and an empty query (pure tag filter).
	Score    float64   `json:"score,omitempty"`
	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 BM25F relevance over the title, path, headings, tags and body (search_bm25f.go), with a 0 to 1 score; a typo-tolerant fallback keeps misspelled queries working at a reduced weight.

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 match a word through its Czech word form, or be within its typo budget of some word (search_match.go). When no note holds every term, the BM25F ranker relaxes the AND to notes that miss one term (Page.Relaxed). 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.

func (*ScanSearcher) SearchPage added in v1.13.0

func (s *ScanSearcher) SearchPage(query string, opts SearchOpts) (Page, error)

SearchPage is Search plus paging: the window of MaxResults notes from Offset on, and the length of the whole ranking. Only the window gets snippets.

func (*ScanSearcher) SetRanker added in v1.13.0

func (s *ScanSearcher) SetRanker(name string) error

SetRanker picks the ranking of text queries: RankerBM25F (the default) or RankerLegacy. Call it before the searcher serves queries.

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
	// Offset skips the first N notes of the ranking (paging, see
	// SearchPage). Negative counts as 0.
	Offset int
	// ContextLines is the number of lines around a match in the snippet
	// (0 = default 2; NoContext or any negative value = the match line
	// alone).
	ContextLines int
	// MaxSnippets caps snippets per note (default 3).
	MaxSnippets int
	// MinScore drops ranked results whose Score is below it (0 to 1,
	// default 0 = keep all). It applies before Offset and MaxResults, so
	// Total counts only the notes that pass. Ignored where there is no
	// score: regex mode, an empty query, the legacy ranker.
	MinScore float64
}

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

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 UndescribedFolder added in v1.13.0

type UndescribedFolder struct {
	Dir    string   `json:"dir"`            // "" is the vault root
	Path   string   `json:"path"`           // where its description note goes
	Notes  int      `json:"notes"`          // notes directly in the folder
	Titles []string `json:"titles"`         // up to five note titles, by path
	Tags   []string `json:"tags,omitempty"` // up to five most used tags
}

UndescribedFolder is a folder that holds notes but no description note, with what an agent needs to propose a description.

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) ContextFile added in v1.13.0

func (v *Vault) ContextFile() string

ContextFile returns the file name of the folder description notes.

func (*Vault) CreateDir added in v1.2.0

func (v *Vault) CreateDir(dir string) error

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

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

Delete removes a note.

func (*Vault) DeleteDir added in v1.4.0

func (v *Vault) DeleteDir(dir string) error

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

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) IsContextNote added in v1.13.0

func (v *Vault) IsContextNote(p string) bool

IsContextNote reports whether p is a folder description note.

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) ListDirs added in v1.2.0

func (v *Vault) ListDirs() ([]string, error)

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) ListPage added in v1.13.0

func (v *Vault) ListPage(dir string, recursive bool, offset, limit int) ([]NoteInfo, int, error)

ListPage is List cut to a window: at most limit notes (0 = no cap) from offset on, in path order, plus the number of notes in the whole listing. Only the notes in the window have their file opened for the title, so a page of a large vault costs a directory walk, not a read of every note.

func (*Vault) ListWith added in v1.13.0

func (v *Vault) ListWith(dir string, recursive bool, opts ListOptions) ([]NoteInfo, int, error)

ListWith is ListPage with a filter and an order (NSO-576): the notes in dir modified since opts.Since, sorted by path or newest change first, cut to the window. The returned total counts the notes that pass the filter. Modification times are the files' own, read in the same walk, so a note edited in another editor sorts by that edit at once.

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). It is PatchSection with PatchReplace.

func (*Vault) PatchSection added in v1.13.0

func (v *Vault) PatchSection(path, section string, op PatchOp, content, expectedHash string) (*PatchResult, error)

PatchSection edits the section named by section (a heading text or a heading path, see findSection) of the note at path as op says. Nothing is written when the hash does not match (ErrConflict), the section is missing (ErrSectionNotFound) or ambiguous (ErrSectionAmbiguous, naming the candidates), content is empty for an insert (ErrEmptyContent) or the result would exceed the size limit (ErrTooLarge).

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) ReadVisible added in v1.13.0

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

ReadVisible is Read restricted to the notes the vault scan sees: on top of Read's path rules it refuses a path with a hidden (dot) segment, or one that resolves into a hidden directory through a symlink, with the same guard writes use (checkNotHidden). Read keeps serving such a note so nothing already there is trapped; bulk reads use ReadVisible so they can only reach what List and the index show.

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) Replace added in v1.13.0

func (v *Vault) Replace(path, oldText, newText string, all bool, expectedHash string) (*ReplaceResult, error)

Replace swaps oldText for newText in the note at path. Without all, oldText must occur exactly once; with all, every non-overlapping occurrence is replaced. An empty newText deletes the text. Nothing is written when the hash does not match (ErrConflict), the text is missing (ErrTextNotFound), ambiguous (ErrTextNotUnique, naming the lines of every occurrence) or the result would exceed the size limit (ErrTooLarge).

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. The one bare filename that stays in the vault root is the folder description file (_index.md by default): at the root it describes the whole vault (NSO-573), and in the inbox it would describe the inbox instead.

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