vault

package
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package vault provides core Obsidian vault operations.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultTemplateContent

func DefaultTemplateContent(name string) string

DefaultTemplateContent returns starter Obsidian Templater content for a named template type. Returns a generic template for unknown names.

func ExtractWikilinks(content string) []string

ExtractWikilinks returns all [[link]] targets from text.

func GetTags

func GetTags(note ParsedNote) []string

GetTags returns the tags from a parsed note's frontmatter as a []string.

func LoadTemplate

func LoadTemplate(templatesDir, templateName string) (string, error)

LoadTemplate reads a template file from templatesDir. templateName should not include .md extension.

func MergeContentIntoTemplate

func MergeContentIntoTemplate(templateContent, existingContent string) string

MergeContentIntoTemplate merges existing note content into template sections. For each ## Section in the template, looks for matching content in existingContent. Missing sections are marked with <!-- TODO -->.

func MergeTags

func MergeTags(existing, toAdd []string) []string

MergeTags deduplicates and merges two tag slices, preserving order.

func ScaffoldNote

func ScaffoldNote(templateContent string, vars TemplateVars) string

ScaffoldNote replaces Obsidian Templater placeholders with vars. Handles:

  • <% tp.file.title %> → vars.Title
  • <% tp.date.now("...") %> → vars.Date

func ScaffoldVault

func ScaffoldVault(cfg *config.RicketConfig) error

ScaffoldVault creates any missing folders, template stubs, and MOC files defined in cfg. Safe to call on an existing vault — skips files that already exist.

func SerializeNote

func SerializeNote(frontmatter map[string]interface{}, content string) string

SerializeNote reconstructs markdown from frontmatter and content.

func UpdateMOCFile

func UpdateMOCFile(mocAbsPath, noteTitle, notePath string) (bool, error)

UpdateMOCFile appends a wikilink to a MOC (Map of Content) file. Finds the last line containing "- [[" and inserts after it. If no such line exists, appends at end of file. Returns false if the MOC file does not exist (non-fatal).

Types

type FileNoteOptions

type FileNoteOptions struct {
	Source       string   // relative path of source (typically in Inbox/)
	Destination  string   // relative path of destination
	Content      string   // optional content override
	Tags         []string // tags to add to frontmatter
	Links        []string // wikilinks to add to ## Links section
	MOC          string   // MOC file to update (relative path)
	Template     string   // template name (without .md)
	SourceAction string   // what to do with source note after filing: delete (default), archive, keep
}

FileNoteOptions controls how FileNote moves and transforms a note.

type FileNoteResult

type FileNoteResult struct {
	Destination      string
	GitCommitMessage string
	GitCommitted     bool
}

FileNoteResult is returned by FileNote.

type FolderEntry

type FolderEntry struct {
	Path        string   `json:"path"` // relative to vault root, trailing slash
	NoteCount   int      `json:"noteCount"`
	SampleNames []string `json:"sampleNames,omitempty"` // up to 5 filenames
}

FolderEntry describes a directory that contains markdown notes directly.

type FolderResult

type FolderResult struct {
	Path  string
	Title string
	Tags  []string
}

FolderResult is returned from folder-based lookups.

type FrontmatterSchema

type FrontmatterSchema struct {
	KeyFrequency  []KeyCount     `json:"keyFrequency"`
	NotableCombos []NotableCombo `json:"notableCombos,omitempty"`
}

FrontmatterSchema holds frontmatter key frequency and notable key combinations.

type InferredCategory

type InferredCategory struct {
	Name       string   `json:"name"`
	Folder     string   `json:"folder"`
	Template   string   `json:"template,omitempty"`
	Naming     string   `json:"naming,omitempty"`
	Tags       []string `json:"tags"`
	MOC        string   `json:"moc,omitempty"`
	Signals    []string `json:"signals"`
	Confidence float64  `json:"confidence"`
	Reasoning  string   `json:"reasoning"`
}

InferredCategory is ricket's best-guess category derived from vault structure.

type KeyCount

type KeyCount struct {
	Key   string `json:"key"`
	Count int    `json:"count"`
}

KeyCount tracks how often a frontmatter key appears.

type LinkAnalysis

type LinkAnalysis struct {
	TotalLinks     int      `json:"totalLinks"`
	AverageDensity float64  `json:"averageDensity"`
	HubNotes       []string `json:"hubNotes,omitempty"`
	MOCLikeCount   int      `json:"mocLikeCount"`
	OrphanCount    int      `json:"orphanCount"`
}

LinkAnalysis holds wikilink structure statistics.

type NamingPattern

type NamingPattern struct {
	Folder   string   `json:"folder"`         // relative, trailing slash
	Pattern  string   `json:"pattern"`        // e.g. "YYYY-MM-DD-{topic}.md"
	Type     string   `json:"type,omitempty"` // e.g. "zettelkasten-uid", "date-topic"
	Examples []string `json:"examples,omitempty"`
}

NamingPattern captures the filename convention detected in a folder.

type NotableCombo

type NotableCombo struct {
	Keys   []string `json:"keys"`
	Signal string   `json:"signal"`
	Count  int      `json:"count"`
}

NotableCombo is a known frontmatter key combination that signals a PKM system.

type NoteRecord

type NoteRecord struct {
	Path    string
	Title   string
	Tags    []string
	Content string
}

NoteRecord is a row stored in the SQLite index.

type PKMSystemResult

type PKMSystemResult struct {
	Primary             string   `json:"primary,omitempty"`
	Confidence          float64  `json:"confidence,omitempty"`
	Evidence            []string `json:"evidence,omitempty"`
	Secondary           string   `json:"secondary,omitempty"`
	SecondaryConfidence float64  `json:"secondaryConfidence,omitempty"`
	IsHybrid            bool     `json:"isHybrid,omitempty"`
}

PKMSystemResult holds the detected PKM methodology with confidence and evidence.

type ParsedNote

type ParsedNote struct {
	Frontmatter map[string]interface{} // parsed YAML metadata
	Content     string                 // everything after the frontmatter
	Raw         string                 // original full text
}

ParsedNote holds a note split into its frontmatter, content, and raw text.

func AddFrontmatterTags

func AddFrontmatterTags(note ParsedNote, tags []string) ParsedNote

AddFrontmatterTags adds tags to a note's frontmatter, merging without duplicates.

func ParseNote

func ParseNote(raw string) ParsedNote

ParseNote splits a markdown note into frontmatter and content. Frontmatter is YAML between --- delimiters at the start.

type SearchOptions

type SearchOptions struct {
	Folder string
	Tags   []string
	Query  string
}

SearchOptions controls SearchNotes filtering.

type SearchResult

type SearchResult struct {
	Path    string
	Title   string
	Snippet string // empty unless content search
}

SearchResult is returned from content/tag searches.

type SourceNote

type SourceNote struct {
	Source string // source name from config
	Path   string // relative path within the source directory
	VaultNote
}

SourceNote is a note from a read-only reference source.

type StatusResult

type StatusResult struct {
	InboxCount int
	TotalNotes int
	Categories int
}

StatusResult holds vault health metrics.

type TagCount

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

TagCount tracks how often a tag appears across the vault.

type TagPrefix

type TagPrefix struct {
	Prefix string `json:"prefix"`
	Count  int    `json:"count"`
}

TagPrefix tracks a nested tag prefix and its frequency.

type TagTaxonomy

type TagTaxonomy struct {
	MaxDepth    int         `json:"maxDepth"`
	Prefixes    []TagPrefix `json:"prefixes,omitempty"`
	ContextTags []string    `json:"contextTags,omitempty"`
}

TagTaxonomy holds tag structure analysis.

type TemplateEntry

type TemplateEntry struct {
	Name     string   `json:"name"`
	Sections []string `json:"sections"` // ## heading names
}

TemplateEntry describes a template file found in the templates directory.

type TemplateVars

type TemplateVars struct {
	Title string // note title (filename without .md)
	Date  string // YYYY-MM-DD
}

TemplateVars holds substitution values for template scaffolding.

type TriagePlan

type TriagePlan struct {
	GeneratedAt string             `json:"generatedAt"`
	Proposals   []TriageProposal   `json:"proposals"`
	Unresolved  []TriageUnresolved `json:"unresolved"`
}

TriagePlan contains deterministic filing suggestions for inbox notes.

type TriageProposal

type TriageProposal struct {
	Source       string   `json:"source"`
	Category     string   `json:"category"`
	Destination  string   `json:"destination"`
	Template     string   `json:"template,omitempty"`
	Tags         []string `json:"tags,omitempty"`
	MOC          string   `json:"moc,omitempty"`
	Confidence   float64  `json:"confidence"`
	Signals      []string `json:"matchedSignals,omitempty"`
	NeedsApprove bool     `json:"needsApproval"`
}

TriageProposal is a suggested filing action for a single inbox note.

type TriageUnresolved

type TriageUnresolved struct {
	Source  string `json:"source"`
	Preview string `json:"preview"`
	Reason  string `json:"reason"`
}

TriageUnresolved captures inbox notes that could not be confidently classified.

type UpdateNoteOptions

type UpdateNoteOptions struct {
	Path    string   // relative path of the note to update (required)
	Content string   // if non-empty, replaces the existing note body
	Tags    []string // tags to add to frontmatter (additive)
	Links   []string // wikilinks to append to the ## Links section
}

UpdateNoteOptions controls how UpdateNote modifies an existing note.

type UpdateNoteResult

type UpdateNoteResult struct {
	Path         string
	GitCommitted bool
}

UpdateNoteResult is returned by UpdateNote.

type Vault

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

Vault provides operations on an Obsidian vault.

func New

func New(cfg *config.RicketConfig) *Vault

New creates a Vault for the given config. Initialises the SQLite index and git audit trail (both best-effort; failures result in degraded-mode operation, not a fatal error).

func (*Vault) Close

func (v *Vault) Close() error

Close releases the SQLite connection (call when the vault is no longer needed).

func (*Vault) CreateNote

func (v *Vault) CreateNote(destination, content string, tags, links []string, moc string) error

CreateNote creates a new note at destination with optional tags, links, and MOC update. Auto-commits to git if the vault is a git repo.

func (*Vault) FileNote

func (v *Vault) FileNote(opts FileNoteOptions) (FileNoteResult, error)

FileNote moves a note from source to destination, applying optional template, tags, links, and MOC update. Auto-commits to git if the vault is a git repo.

func (*Vault) GetCategories

func (v *Vault) GetCategories() []config.Category

GetCategories returns all configured categories.

func (*Vault) GetTemplateList

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

GetTemplateList returns the names (without .md) of all templates.

func (*Vault) ListInbox

func (v *Vault) ListInbox() ([]VaultNote, error)

ListInbox returns all notes in the inbox folder.

func (*Vault) PlanInboxTriage

func (v *Vault) PlanInboxTriage() (TriagePlan, error)

PlanInboxTriage analyzes inbox notes and proposes filing actions.

func (*Vault) ReadNote

func (v *Vault) ReadNote(relativePath string) (VaultNote, error)

ReadNote reads a single note by relative path.

func (*Vault) ReadSourceNote

func (v *Vault) ReadSourceNote(sourceName, relPath string) (VaultNote, error)

ReadSourceNote reads a note from a named source by relative path.

func (*Vault) SearchNotes

func (v *Vault) SearchNotes(opts SearchOptions) ([]VaultNote, error)

SearchNotes searches notes by folder, tags, and/or text query. Uses the SQLite index for tag/content queries when available; falls back to a filesystem walk otherwise.

func (*Vault) SearchSources

func (v *Vault) SearchSources(query string) []SourceNote

SearchSources searches all configured read-only sources for notes matching the query string. Returns SourceNote results with the source name attached.

func (*Vault) Status

func (v *Vault) Status() (StatusResult, error)

Status returns inbox count, total notes, and category count.

func (*Vault) UpdateMOC

func (v *Vault) UpdateMOC(mocPath, noteTitle, notePath string) error

UpdateMOC updates a MOC file by appending a link.

func (*Vault) UpdateNote

func (v *Vault) UpdateNote(opts UpdateNoteOptions) (UpdateNoteResult, error)

UpdateNote modifies an existing note's content, tags, and/or links in-place. At least one of Content, Tags, or Links must be non-empty.

type VaultAnalysis

type VaultAnalysis struct {
	VaultRoot             string             `json:"vaultRoot"`
	ObsidianVaultDetected bool               `json:"obsidianVaultDetected"`
	HasExistingConfig     bool               `json:"hasExistingConfig"`
	IsNewVault            bool               `json:"isNewVault"`
	TotalNoteCount        int                `json:"totalNoteCount"`
	Folders               []FolderEntry      `json:"folders"`
	TagFrequency          []TagCount         `json:"tagFrequency"`
	NamingPatterns        []NamingPattern    `json:"namingPatterns"`
	Templates             []TemplateEntry    `json:"templates"`
	InferredCategories    []InferredCategory `json:"inferredCategories"`
	MOCFiles              []string           `json:"mocFiles"`
	DetectedInbox         string             `json:"detectedInbox"`
	DetectedArchive       string             `json:"detectedArchive"`
	DetectedTemplatesDir  string             `json:"detectedTemplatesDir"`
	PKMSystem             *PKMSystemResult   `json:"pkmSystem,omitempty"`
	FrontmatterSchema     *FrontmatterSchema `json:"frontmatterSchema,omitempty"`
	LinkAnalysis          *LinkAnalysis      `json:"linkAnalysis,omitempty"`
	TagTaxonomy           *TagTaxonomy       `json:"tagTaxonomy,omitempty"`
}

VaultAnalysis is the complete result of analyzing a vault's structure. Produced by AnalyzeVaultRoot — does not require ricket.yaml.

func AnalyzeVaultRoot

func AnalyzeVaultRoot(root string) (*VaultAnalysis, error)

AnalyzeVaultRoot scans root and returns a VaultAnalysis. Works without ricket.yaml — safe to call in migration mode.

type VaultIndex

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

VaultIndex is a SQLite-backed search index for vault notes.

func NewVaultIndex

func NewVaultIndex(vaultRoot string) *VaultIndex

NewVaultIndex creates a VaultIndex for the given vault root. Call Init() before use.

func (*VaultIndex) Close

func (idx *VaultIndex) Close() error

Close closes the database connection.

func (*VaultIndex) GetByFolder

func (idx *VaultIndex) GetByFolder(folder string) ([]FolderResult, error)

GetByFolder returns all notes in folder (prefix match).

func (*VaultIndex) Init

func (idx *VaultIndex) Init() error

Init opens or creates the SQLite database at .ricket/index.db.

func (*VaultIndex) Rebuild

func (idx *VaultIndex) Rebuild(notes []NoteRecord) error

Rebuild replaces the entire index with the provided notes.

func (*VaultIndex) SearchByTags

func (idx *VaultIndex) SearchByTags(tags []string) ([]SearchResult, error)

SearchByTags returns notes that contain ALL specified tags.

func (*VaultIndex) SearchContent

func (idx *VaultIndex) SearchContent(query string) ([]SearchResult, error)

SearchContent returns notes whose content contains query, with a 100-char snippet.

type VaultNote

type VaultNote struct {
	Path         string // relative to vault root (always forward slashes)
	AbsolutePath string
	Parsed       ParsedNote
	Name         string // filename without .md
}

VaultNote represents a note with its parsed content and metadata.

Jump to

Keyboard shortcuts

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