vaultapi

package
v0.37.2 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: BSD-2-Clause Imports: 26 Imported by: ? 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

Index

Constants

View Source
const (
	// FileReadKindList counts files read while listing a directory.
	FileReadKindList = "page_list"
	// FileReadKindRead counts files read by a single-page lookup.
	FileReadKindRead = "page_read"
)

File-read kinds. They are the label values of vault_api_file_reads_total and are bounded by construction, so the counter is pre-initialised for each.

View Source
const (
	// TaskTypeUnknown is the label value used for a task whose frontmatter carries
	// no task_type. It keeps the gauge's total equal to the real open-task count
	// instead of silently dropping untyped pages.
	TaskTypeUnknown = "unknown"
	// StageUnknown is the label value used for a task whose frontmatter carries no
	// stage, for the same reason as TaskTypeUnknown.
	StageUnknown = "unknown"
	// PhaseUnknown is the label value used for a task whose frontmatter carries no
	// phase, for the same reason as TaskTypeUnknown.
	PhaseUnknown = "unknown"
	// JobRunning is the job_state value for a task carrying a non-empty
	// current_job. It means "a job was claimed", not "the job is alive": nothing
	// here polls the executor, so a job that died leaves its id behind and still
	// reads running.
	JobRunning = "running"
	// JobNone is the job_state value for a task with no current_job. It is a value
	// rather than an absent label because only a value is queryable: PromQL has no
	// positive matcher for label absence.
	JobNone = "none"
	// PRStateUnknown is the pr_state value for a task no sweep has observed yet. It
	// is deliberately distinct from PRStateNone (no PR at all): unknown means "ask
	// again after the next sweep", none means "this task will never have one".
	PRStateUnknown = "unknown"
	// AssigneeUnassigned is the assignee value for a task whose frontmatter names no
	// owner. Like JobNone it is a positive reading — nobody owns this task — not a
	// missing one, so it is a value rather than an absent label: only a value is
	// queryable, and PromQL has no positive matcher for label absence.
	//
	// Spelled "unassigned" rather than the "none" used by job_state and pr_state
	// because this label carries an identity, not an object: "none" in a column of
	// names reads as a person called none, while "unassigned" is also the word the
	// panel legend has to show to make the split legible.
	AssigneeUnassigned = "unassigned"
)
View Source
const MaxPublishRetries = 3

MaxPublishRetries is the number of attempts a permanently failing baseline gets before it is abandoned.

View Source
const MergeMarker = "pull: merged"

MergeMarker prefixes every resolved-merge log line. It is a fixed literal rather than a configurable one so a probe can grep for exactly one string: a marker the caller chooses is a marker the caller's own probe can be written to match.

Variables

View Source
var ErrInvalidRef = stderrors.New("invalid ref")

ErrInvalidRef reports a ref this package refuses to hand to git.

A ref can reach ReadAt from a request query string, and git parses a leading `-` in argument position as an option: `--output=<file>` makes `git show` create or truncate a file. Rejecting the shape here is what keeps the value from being an argument at all.

View Source
var ErrNotAtRef = stderrors.New("path is not present at the ref")

ErrNotAtRef reports that a ref resolves but does not carry the requested path.

It is deliberately distinct from a failure about the ref itself, because the two mean opposite things to a caller waiting for a write to land: "not committed yet" is the expected state before the next git-rest flush, while an unresolvable ref is a configuration fault. Collapsing them would make a typo in a ref name indistinguishable from every write being dropped.

View Source
var MergeLog = glog.Infof

MergeLog records one resolved merge. It is a variable rather than a direct glog call so the specs can assert the line without depending on glog's file sinks, which offer no capture hook. Production never reassigns it.

Functions

func FetchAge added in v0.12.0

func FetchAge(vaultPath string) (ageSeconds int64, known bool)

FetchAge reports how long ago the working tree was last fetched from its remote, read from the modification time of .git/FETCH_HEAD. Every git fetch rewrites that file, including one that brings nothing new, so its age is the puller's heartbeat rather than a record of the last change: a tree that nothing fetches into keeps an age that only grows.

That is the one signal a pod has for a tree that has stopped advancing. The local HEAD cannot show it — a frozen tree and a quiet one both leave the HEAD unmoved — so a pod comparing HEAD to HEAD sees nothing wrong while the tree falls arbitrarily far behind the remote.

known is false when the file is absent: a tree created by git clone and never fetched has no fetch to measure, and no claim about its freshness can be made either way.

func IsNotFound added in v0.36.0

func IsNotFound(err error) bool

IsNotFound reports whether err means the page cannot be served: it is absent, its path is not a markdown path inside the vault, or it is reached through a symlink that leaves the vault. The HTTP layer maps exactly this to a 404.

func IsTerminalStatus added in v0.21.0

func IsTerminalStatus(status string) bool

IsTerminalStatus reports whether a task status ends the task's life. The vault has exactly two, and this is the one definition of them: the open-task gauge uses it to decide what counts as open (openTasksByState), and the create route uses it to decide whether an occupying task may be reopened. A second copy of this predicate is how the two answers drift apart.

func LinkTargets added in v0.36.0

func LinkTargets(content string) []string

LinkTargets returns the page names a body links to, with the same rules github.com/bborbe/vault-markdown's Backlinks applies: a link inside the frontmatter, a fenced block or an inline code span does not count, and the target is the text before the first `|` or `#` with no trimming — so `[[Foo #anchor]]` is not a link to Foo, exactly as Backlinks decides it.

func LogResolvedMerge added in v0.11.0

func LogResolvedMerge(path string, base, ours, theirs Side)

LogResolvedMerge emits the merge marker for a divergence the service resolved.

It is separate from the write because the two paths that resolve a divergence differ only in who writes: an API caller has no working tree, so the service writes for it, while git-rest is mid-pull holding the repository and takes the bytes itself. Both reconciled a real divergence, so both must produce the same marker — a probe that could only see one of them would report the puller's automatic path as silent.

Only a file both sides changed counts. When either side still equals the base, nothing diverged: the winning side is written, but logging it would make the line indistinguishable from a real reconciliation.

func NewCountingPageStorage

func NewCountingPageStorage(next storage.PageStorage, metrics Metrics) storage.PageStorage

NewCountingPageStorage wraps a PageStorage so every file it reads increments vault_api_file_reads_total. The index build is the only caller that reads files; query handlers serve from the index and never reach this decorator, which is what makes a flat counter across a query window meaningful.

func PageLinkTargets added in v0.37.1

func PageLinkTargets(content string) []string

PageLinkTargets returns every wikilink target a page renderer must resolve: the body's targets, plus the ones the frontmatter carries. The body set is exactly LinkTargets — the set the index and Backlinks use — and the frontmatter set is added here because the renderer emits a frontmatter wikilink value as an anchor too, and the resolver it is handed can only answer for a target this map carries. The two stay separate on purpose: a page that links to another only from its frontmatter is not that page's backlink.

func ResolveBaseline added in v0.16.1

func ResolveBaseline(ctx context.Context, differ Differ, baseline string) string

ResolveBaseline returns baseline when the repository still holds that commit, and "" otherwise.

A persisted baseline can outlive the commit it names — a re-cloned volume, a force-push, a gc — and the feed cannot diff a commit that is gone: the error is not a broker error, so it is classified as transient and retried forever, and publishing stops permanently. Adopting HEAD is what every instance did before the file existed, so falling back to it degrades rather than breaks.

A repository that cannot be read at all also yields "", with a distinct warning: the alternative is failing startup and taking the read API down over a baseline, and the two causes must stay distinguishable in the log.

func ResolveHead

func ResolveHead(vaultPath string) string

ResolveHead reads the commit the vault working tree currently points at, shortened to 8 characters. It reads .git/HEAD and the ref file directly so the service needs no git binary in its image. An empty string means the directory is not a git working tree (or the ref could not be read).

func UnavailableLine added in v0.34.0

func UnavailableLine(vault string) string

UnavailableLine is the log token that names a configured vault whose index could not be built. It is a fixed shape so an operator and a probe can grep it: an attached vault that fails silently would make its rows vanish from every list query, which reads exactly like "that vault has nothing flagged".

func WatchRefresh added in v0.29.0

func WatchRefresh(
	ctx context.Context,
	index *Index,
	store storage.PageStorage,
	targets []ops.WatchTarget,
	refreshInterval time.Duration,
	onHead func(head string),
) error

WatchRefresh runs the local-mode refresh loop: it rebuilds the index whenever the file watcher reports a change, with no git-HEAD gate, and falls back to a periodic full rebuild so a dropped filesystem event cannot leave the index stale forever. onHead is called with the working tree's HEAD after each rebuild, which is where the change-event feed advances its baseline.

refreshInterval spaces the readiness heartbeat (index.Verify) and bounds the resync; a value <= 0 falls back to 30s.

func WatchTargets added in v0.29.0

func WatchTargets(cfg Config) []ops.WatchTarget

WatchTargets returns the directories a local-mode instance watches: the same task, goal and topic directories the index reads. It is the vault-cli pkg/ops.WatchTarget shape, so the watcher is the shared library's rather than a second implementation.

Types

type BacklinkRef added in v0.36.0

type BacklinkRef struct {
	Path string `json:"path"`
	Name string `json:"name"`
}

BacklinkRef is one page that links to the requested page.

type BaselineStore added in v0.16.1

type BaselineStore interface {
	// Load returns the persisted baseline, or "" when none is stored yet.
	Load(ctx context.Context) (string, error)
	// Save persists the baseline a restart should resume from.
	Save(ctx context.Context, baseline string) error
}

BaselineStore persists the last commit whose changes were published, so a restart resumes from it instead of adopting the current HEAD.

Without a store the feed's baseline is process-local: a commit pushed while the process was down is adopted silently as the new baseline and never published. The failure is invisible from outside — the instance keeps serving reads and looks healthy; it simply stops publishing, and a task's last record stays at whatever it was when the process was last up.

func NewFileBaselineStore added in v0.16.1

func NewFileBaselineStore(path string) BaselineStore

NewFileBaselineStore persists the baseline in a file at path.

A missing file is not an error: it is the first run, and Load reports "". A directory that cannot be created is reported by Save, not here, so a misconfigured path degrades to the process-local baseline with a warning rather than failing startup.

func NoopBaselineStore added in v0.16.1

func NoopBaselineStore() BaselineStore

NoopBaselineStore persists nothing. An instance with no configured path keeps exactly the process-local baseline it had before this seam existed, so enabling persistence is opt-in rather than a behaviour change for every deployment.

type Change added in v0.7.0

type Change struct {
	Path   string
	Status ChangeStatus
}

Change is one path git reported as different between two commits.

type ChangeStatus added in v0.7.0

type ChangeStatus string

ChangeStatus is git's single-letter status for one path in a HEAD-to-HEAD diff.

const (
	// ChangeAdded marks a path that exists at the new commit and not at the old one.
	ChangeAdded ChangeStatus = "A"
	// ChangeModified marks a path whose blob differs between the two commits.
	ChangeModified ChangeStatus = "M"
	// ChangeDeleted marks a path that existed at the old commit and not at the new one.
	ChangeDeleted ChangeStatus = "D"
)

type Config

type Config struct {
	VaultPath string
	VaultName string
	TasksDir  string
	GoalsDir  string
	// TopicsDir is the directory the topic pages live in. Empty disables topic
	// indexing, which is what a caller that only serves tasks and goals wants.
	TopicsDir string
	// StaleAfter is how long either freshness signal may go unrefreshed before
	// Readiness stops reporting ready: the index's own verification, and the
	// working tree's last fetch from its remote. Zero disables the rule, which is
	// what a caller serving a tree nothing fetches (a plain clone) wants.
	StaleAfter time.Duration
}

Config locates the vault working tree and the directories the index reads.

type Differ added in v0.7.0

type Differ interface {
	// Diff returns the paths that differ between oldHead and newHead.
	Diff(ctx context.Context, oldHead string, newHead string) ([]Change, error)
	// ReadAt returns the content of path as it existed at head.
	ReadAt(ctx context.Context, head string, path string) ([]byte, error)
	// Exists reports whether commit is present in the repository. A persisted
	// baseline can name a commit the tree no longer holds — a re-cloned volume, a
	// force-push, a gc — and Diff then fails in a way that is not a broker error,
	// so the feed treats it as transient and retries forever. Callers use this to
	// drop such a baseline before it can wedge publishing.
	Exists(ctx context.Context, commit string) (bool, error)
}

Differ reports the files that changed between two commits, and reads a file as it existed at a commit. The second half is what makes deletions publishable: the bytes of a deleted task are gone from the working tree, so the only place its identifier still exists is the old commit.

func NewGitDiffer added in v0.7.0

func NewGitDiffer(vaultPath string) Differ

NewGitDiffer returns a Differ that runs git inside vaultPath.

type Emitter added in v0.7.0

type Emitter interface {
	// Emit publishes the change events for oldHead..newHead. A read or publish
	// failure is returned so the caller can leave its baseline unadvanced and retry
	// the same diff; content that does not parse is skipped and logged, because the
	// same bytes will not become parseable on the next tick.
	Emit(ctx context.Context, oldHead string, newHead string) error
}

Emitter publishes one change event per task file that differs between two commits.

It is the pull-side producer: the write handlers cover mutations vault-api itself performed, and this covers everything else — Obsidian on the Mac, vault-ui, git-ai-sync — which is what lets the controller's git scan retire. Only task files are published; a goals-only pull emits nothing.

func NewEmitter added in v0.7.0

func NewEmitter(cfg Config, differ Differ, taskPublisher publisher.TaskPublisher) Emitter

NewEmitter creates an Emitter over the vault described by cfg.

type EmitterFactory added in v0.7.0

type EmitterFactory func(ctx context.Context) (Emitter, func() error, error)

EmitterFactory builds the change-event producer on demand. It is called at most once on success; a failed call is retried on the next change that needs publishing, so a broker that comes up late still gets the backlog.

type Feed added in v0.7.0

type Feed interface {
	// Advance publishes the changes from the current publish position up to head
	// and returns the baseline a restart should resume from. That value lags the
	// publish position by exactly the ranges that were abandoned, so a caller that
	// persists it re-attempts them rather than skipping them.
	Advance(ctx context.Context, head string) string
	// Close releases the producer if it was ever built.
	Close()
}

Feed publishes the changes between the last published commit and the current one, and owns the baseline that makes that possible.

The baseline advances only after a batch published, so a failure retries the same diff rather than dropping it. A failure the broker will never accept — a payload over message.max.bytes — is abandoned after maxPublishRetries attempts on the same baseline, because one poison event must not stop every later change from publishing. Transient failures are never abandoned.

Abandoning a range moves the publish position past it but deliberately leaves the persisted baseline before it: the skipped changes are then re-attempted after a restart instead of being lost for good.

func NewFeed added in v0.7.0

func NewFeed(factory EmitterFactory, isPermanent func(err error) bool) Feed

NewFeed creates a Feed over the given factory with a process-local baseline. isPermanent classifies an Emit error as one the broker will never accept; nil treats every error as permanent.

A process-local baseline cannot survive a restart, so a caller that can persist one should use NewFeedWithBaseline instead.

func NewFeedWithBaseline added in v0.16.1

func NewFeedWithBaseline(
	factory EmitterFactory,
	isPermanent func(err error) bool,
	baseline string,
) Feed

NewFeedWithBaseline creates a Feed that starts from baseline rather than adopting the first HEAD it sees.

An empty baseline is the first run: there is no earlier commit to compare against, so adopting the current HEAD is correct and publishes nothing.

type FileWriter added in v0.6.0

type FileWriter interface {
	WriteFile(ctx context.Context, path string, content []byte) error
}

FileWriter writes one complete file back to the vault. It is satisfied by the git-rest client the write endpoints use, so a resolved pull lands the same way an API edit does.

type Fingerprint added in v0.34.4

type Fingerprint struct {
	MaxModTime time.Time
	Count      int
}

Fingerprint is a cheap change signal for a vault's page directories: the newest modification time and the number of *.md files across the tasks, goals and topics directories. A write moves the newest mtime, a create or delete moves the count, so any edit made outside vault-api (vault-cli writing frontmatter, an editor) moves it without a git commit or a filesystem watch.

func PageFingerprint added in v0.34.4

func PageFingerprint(cfg Config) Fingerprint

PageFingerprint computes the Fingerprint of the directories the index reads. It lists each directory once and stats each entry, with no recursion and no file reads, mirroring what Build lists. A directory that cannot be read contributes nothing: Build reports that failure itself.

type GoalItem

type GoalItem struct {
	ID     string `json:"id"`
	Title  string `json:"title"`
	Path   string `json:"path"`
	Status string `json:"status"`
	// Phase is the page's frontmatter `phase:`, carried raw. Goals and topics
	// keep their own phase convention (GoalFrontmatter.Phase preserves legacy
	// and hand-typed values rather than normalising them), and the board's
	// displayPhase maps `in_progress` onto the `execution` column client-side.
	// It is served because the board groups goals and topics into phase columns
	// exactly as it groups tasks: without it every card lands in the "—" column.
	Phase    string   `json:"phase"`
	Themes   []string `json:"themes"`
	Assignee string   `json:"assignee,omitempty"`
	// Priority is the page's frontmatter priority as an integer, 0 when absent,
	// always emitted like TaskItem.Priority so the board can order goal cards.
	Priority int    `json:"priority"`
	Vault    string `json:"vault"`
	// Flag is the page's frontmatter `flag:`, served so a consumer selecting the
	// operator-flagged rows can filter server-side instead of re-reading the page.
	// Without it a goal's flag was invisible to every API consumer, which is why
	// the flagged tick had to parse goal pages itself.
	Flag bool `json:"flag"`
	// SessionID is the page's recorded `claude_session_id`, empty when none. A
	// consumer resolving a subject's live manager needs the recorded session, and
	// this is the only field that carries it.
	SessionID string `json:"claude_session_id"`
	// The five fields below exist so a goal or topic can be enriched from this
	// projection alone. A consumer that selects flagged rows needs the same
	// per-kind facts a task's frontmatter carries — role, mode, due date,
	// unresolved blockers and flag provenance — and without them it must either
	// read the page itself or silently apply the task rule to goals and topics.
	// Both outcomes are wrong: the first defeats the index, the second lets a
	// future-deferred goal open a manager early.
	Role      string   `json:"role"`
	Mode      string   `json:"mode"`
	DeferDate string   `json:"defer_date,omitempty"`
	BlockedBy []string `json:"blocked_by,omitempty"`
	// FlagSetBy is the page's `flag_set_by`, empty when absent. Empty is a real
	// value here — it means the page carries no provenance, which a consumer may
	// treat as a refusal — so it is not omitted.
	FlagSetBy string `json:"flag_set_by"`
	// Jira is the page's own `jira:` value, carried verbatim and null when
	// absent, on the same terms as TaskItem.Jira. Without it a goal's ticket is
	// reachable only by reading the page, so a consumer rendering the goal's
	// card has to guess it from the title — and a title that does not lead with
	// the key then shows no ticket at all.
	Jira *string `json:"jira"`
}

GoalItem is the typed projection of one goal page. It is served by GET /api/v1/goals and GET /api/v1/goals/{id}.

type Index

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

Index is the in-memory view of the vault. It is rebuilt at startup and again whenever the working tree's HEAD changes, so list queries are map lookups rather than per-file reads.

func NewIndex

func NewIndex(cfg Config, metrics Metrics) *Index

NewIndex creates an empty index. Build populates it and refreshes the open-task gauge.

func (*Index) Attach added in v0.34.0

func (i *Index) Attach(extras ...*Index)

Attach registers secondary vault indexes whose rows the list queries merge with this index's own. It is the multi-vault mode's only seam: lookups by id, writes and change events stay with this (the primary) vault, so a caller that never attaches anything — every cluster deployment — behaves exactly as before.

func (*Index) Build

func (i *Index) Build(ctx context.Context, store storage.PageStorage) error

Build reads every task and goal page and replaces the index atomically. A page whose frontmatter does not parse, or whose status/phase is present but not a known value, is excluded and counted in Warnings — never coerced.

A failed build leaves the previous index in place but marks it unbuilt, so the read path keeps serving the last good data while Readiness reports the failure. Before that mark existed a pod that had built once answered ready forever, and handleReadiness's 503 branch was unreachable.

func (*Index) Built added in v0.12.0

func (i *Index) Built() bool

Built reports whether the last build succeeded. It is the rebuild trigger for the refresh loop, deliberately narrower than Readiness().Ready: a tree that is stale but unmoved must not make the loop rebuild on every tick.

func (*Index) GetAttachedTask added in v0.34.0

func (i *Index) GetAttachedTask(id string) (TaskItem, Config, bool)

GetAttachedTask resolves id in the attached vaults, in attach order, and returns the task with the config of the vault that holds it, so the caller can read the page from that vault's own tree.

⚠️ It is for the single-task READ only. GetTask deliberately stays primary-only: the write endpoints resolve through it and then write to the primary vault's tree and git-rest, so widening it would send an attached vault's task write into the wrong vault. A caller checks GetTask first; the primary vault wins any id that exists in both.

func (*Index) GetGoal

func (i *Index) GetGoal(id string) (GoalItem, bool, string)

GetGoal resolves one goal by identifier or filename slug.

func (*Index) GetTask

func (i *Index) GetTask(id string) (TaskItem, bool, string)

GetTask resolves one task by identifier or filename slug. found is false when the id is absent; invalid carries the exclusion reason for a file that was refused rather than served.

func (*Index) GetTopic added in v0.30.0

func (i *Index) GetTopic(id string) (TopicItem, bool)

GetTopic resolves one topic by identifier or filename slug. There is no invalid-topic map: buildTopics does not refuse a page for an unknown status the way buildGoals does, so an unknown id is simply not found.

func (*Index) Head

func (i *Index) Head() string

Head returns the working-tree commit the current index was built from.

func (*Index) QueryGoals

func (i *Index) QueryGoals() ([]GoalItem, int, int64)

QueryGoals returns every indexed goal, the warning count and the index age.

func (*Index) QueryTasks

func (i *Index) QueryTasks(filter TaskFilter) ([]TaskItem, int, int64)

QueryTasks returns the tasks matching filter, the current warning count and the index age in seconds.

func (*Index) QueryTopics added in v0.29.0

func (i *Index) QueryTopics() ([]TopicItem, int, int64)

QueryTopics returns every indexed topic, the warning count and the index age. The slice is never nil: a vault with no topics answers an empty JSON array, matching every other list endpoint, rather than null.

func (*Index) Readiness

func (i *Index) Readiness() Readiness

Readiness reports whether the index is usable and how stale it is.

Ready answers a narrower question than "did a build succeed once": it also requires both freshness signals to be inside the staleness window, so a pod whose index stopped being confirmed, or whose tree stopped being fetched from its remote, reports not-ready instead of serving stale data behind a green light. The two signals are separate because they fail independently: a rebuild can fail on a live tree, and a tree can freeze under a perfectly healthy loop.

func (*Index) UpsertGoal added in v0.34.4

func (i *Index) UpsertGoal(ctx context.Context, page *domain.Page)

UpsertGoal applies one edited goal page in place, replacing the entry at the same Path or appending. It spares a full Build for a goal flag/unflag. A page the full build would reject (unknown status) is not indexed: its entry is dropped and recorded invalid, as Build would.

func (*Index) UpsertTask added in v0.22.5

func (i *Index) UpsertTask(ctx context.Context, page *domain.Page)

UpsertTask adds or replaces the indexed task for page. The write path calls it after a create or a reopen, so the task it just wrote is readable by identifier immediately.

Without it, a create and the read that follows it disagree for up to one refresh interval. The create writes the file and answers 201; the read path resolves identifiers through this index; and the index is rebuilt only when the working tree's HEAD moves, on the refresh ticker. A caller that creates a task and then addresses it — the executor's probe publishes create-task and update-frontmatter back to back — therefore gets a 404 for a task that exists, and the follow-up write is dropped. Measured on dev 2026-11-09: the update ran 4 ms after the create and reported "task not found".

It does NOT make a genuine miss resolvable: nothing is recorded for an identifier no file carries, so an unknown identifier still answers 404. That distinction is the point — the read path must stay able to say "no such task", which is why the create answers with the task it stored rather than the read path being made lenient.

The byID map and the filter sets are rebuilt from the slice rather than patched in place: a replace has to drop the old item's keys and set memberships, and rebuilding is O(tasks) over memory already held, with no file read — the cost this index exists to avoid is I/O, not map writes.

func (*Index) UpsertTopic added in v0.34.4

func (i *Index) UpsertTopic(_ context.Context, page *domain.Page)

UpsertTopic applies one edited topic page in place, replacing the entry at the same Path or appending.

func (*Index) VaultName added in v0.34.0

func (i *Index) VaultName() string

VaultName is the vault this index reports on its rows.

func (*Index) Verify added in v0.12.0

func (i *Index) Verify()

Verify records that the tree still points at the head this index was built from. The refresh loop calls it on every tick where the HEAD did not move, so a loop that is running keeps the index's age bounded and a loop that stopped lets it grow. It is not a rebuild: an unmoved HEAD means no file changed, so re-reading every page would spend the reads the HEAD check exists to save.

type LinkIndex added in v0.36.0

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

LinkIndex answers whole-vault page reads and backlinks without walking the vault on the request path.

It holds three things: every page's name→relative-path so a wikilink target resolves, the link targets each page carries so a target's inbound set is a map lookup, and each file's size and modification time so a refresh re-reads only what changed. It deliberately holds no page body: a page read is one file read, and a vault of 22k pages stays a few tens of megabytes of strings rather than the 260 MB its bodies would cost.

The index is per vault. A multi-vault instance holds one per vault in a LinkRegistry, which is what lets a caller name the vault it wants.

func NewLinkIndex added in v0.36.0

func NewLinkIndex(cfg Config) *LinkIndex

NewLinkIndex returns an empty index for the vault cfg locates. It is built by Refresh, which the caller runs at startup and again on its refresh tick.

func (i *LinkIndex) Backlinks(ctx context.Context, pagePath string) ([]BacklinkRef, error)

Backlinks returns every page whose body links to the page at pagePath, sorted by relative path. The set matches github.com/bborbe/vault-markdown's Backlinks exactly, including the case where a root-level page links to itself; the caller applies its own self filter.

func (*LinkIndex) Built added in v0.36.0

func (i *LinkIndex) Built() bool

Built reports whether a build has completed.

func (*LinkIndex) Ensure added in v0.36.0

func (i *LinkIndex) Ensure(ctx context.Context) error

Ensure builds the index on first use, so the first page view after a restart is correct without the caller having run Refresh first. Concurrent cold callers share one build: the second check runs under buildMu, which a concurrent build holds.

func (*LinkIndex) Page added in v0.36.0

func (i *LinkIndex) Page(ctx context.Context, pagePath string) (*PageContent, error)

Page returns one page's body plus the links and embeds a renderer needs. The body is read from disk so a just-edited page renders fresh; the resolution of its targets comes from the index.

func (*LinkIndex) Refresh added in v0.36.0

func (i *LinkIndex) Refresh(ctx context.Context) error

Refresh brings the index up to date with the working tree. It walks the vault (stat only), re-reads the files whose size or modification time moved, and drops the files that vanished. It is the only expensive operation here and it runs on the refresh tick, never on the request path.

A walk that fails part-way leaves the previous index serving: a page view over a slightly stale index beats a page view that errors because one directory was momentarily unreadable.

func (*LinkIndex) VaultName added in v0.36.0

func (i *LinkIndex) VaultName() string

VaultName is the vault this index answers for.

type LinkRegistry added in v0.36.0

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

LinkRegistry maps a vault name to its link index, so one multi-vault instance can answer a page read for any vault it serves.

func NewLinkRegistry added in v0.36.0

func NewLinkRegistry(primary *LinkIndex) *LinkRegistry

NewLinkRegistry returns a registry with the primary vault registered. A caller attaches the other vaults it serves with Attach.

func (*LinkRegistry) Attach added in v0.36.0

func (r *LinkRegistry) Attach(index *LinkIndex)

Attach registers another vault's index. A nil index, or one whose vault has no name, is ignored, so a caller that could not build one does not have to branch.

func (*LinkRegistry) For added in v0.36.0

func (r *LinkRegistry) For(vaultName string) (*LinkIndex, bool)

For returns the index for a vault name, case-insensitively. An empty name selects the primary vault, which is what a single-vault deployment expects.

func (*LinkRegistry) Indexes added in v0.36.0

func (r *LinkRegistry) Indexes() []*LinkIndex

Indexes returns every registered index, so a caller can refresh them all.

type ListResponse

type ListResponse[T any] struct {
	Items           []T   `json:"items"`
	Total           int   `json:"total"`
	Warnings        int   `json:"warnings"`
	IndexAgeSeconds int64 `json:"index_age_seconds"`
}

ListResponse is the envelope every list endpoint returns. Total is the number of items in the response; Warnings counts files excluded from the index because they could not be parsed or carry a value outside the enum.

type MergeReason added in v0.3.0

type MergeReason string

MergeReason names why a file could not be resolved. The empty value means the merge succeeded.

const (
	// ReasonUnparsable names a side whose frontmatter does not parse.
	ReasonUnparsable MergeReason = "frontmatter does not parse"
	// ReasonBodyConflict names a body both sides changed in a way no rule can
	// merge: a rewrite, a deletion, or a mid-body edit. Two appends after a
	// common base merge instead, and do not reach this reason.
	ReasonBodyConflict MergeReason = "body conflict outside the frontmatter"
	// ReasonLifecycle names status/phase edits that are not a legal transition.
	ReasonLifecycle MergeReason = "lifecycle fields are not a legal transition"
	// ReasonCounter names a counter field that is not an integer on both sides.
	ReasonCounter MergeReason = "a counter field is not an integer"
	// ReasonListConflict names a list one side deleted while the other changed
	// it: neither the union nor the deletion is right without a human.
	ReasonListConflict MergeReason = "a list was deleted on one side and changed on the other"
	// ReasonRenderFailed names a merge that resolved but could not be encoded.
	ReasonRenderFailed MergeReason = "merged frontmatter could not be rendered"
)

func ResolveDivergedPull added in v0.6.0

func ResolveDivergedPull(
	ctx context.Context,
	writer FileWriter,
	path string,
	base, ours, theirs Side,
) (MergeReason, error)

ResolveDivergedPull resolves a file that changed on both sides and writes the outcome. It is the pull seam: the three sides come from a diverged pull, and MergeFile — not this function — decides what the merged bytes are.

A quarantined merge writes nothing and returns the reason, so the caller can record it and leave the file for a human. A resolved merge writes Content verbatim: it is already the complete file, and re-rendering it through storage.SerializeFrontmatter would rewrite bytes the merge just decided.

type MergeResult added in v0.3.0

type MergeResult struct {
	Content    []byte
	Quarantine bool
	Reason     MergeReason
}

MergeResult is the outcome of resolving a diverged file. Content is the file to write when Quarantine is false. When Quarantine is true, Content is empty and Reason names why no rule could resolve the file.

func MergeFile added in v0.3.0

func MergeFile(base, ours, theirs Side) MergeResult

MergeFile resolves a three-way merge of one vault file.

The merge is per frontmatter key, never per line: a key edited on one side only is kept, and a key edited on both sides follows the rule its field class names. A body only one side changed, or both sides changed identically, is taken as-is. A body both sides changed differently is kept only when both changes are appends after a common base: the two appended sections are concatenated, ordered by committer time so the result does not depend on which side the caller calls "ours". A rewrite, a deletion or a mid-body edit quarantines, because concatenating two writers' rival prose produces a file neither of them wrote.

This function performs no I/O. The pull path supplies the three sides and writes the merged bytes through whatever write path it owns.

Named for the operation rather than as NewMergeResult: it is not a constructor. It takes no context and returns no error for the same reason it does no I/O — an unparsable side, an illegal lifecycle pair and a body conflict are outcomes of the merge, reported as Quarantine with a Reason, not failures of it.

type Metrics

type Metrics interface {
	AddFileReads(kind string, count int64)
	SetOpenTasks(counts map[OpenTaskKey]int)
}

Metrics is the instrumentation the storage decorator and the index write to.

func NewMetrics

func NewMetrics(instanceStage string, vault string) Metrics

NewMetrics creates the service metrics and registers them. The file-read counter is pre-initialised with Add(0) so its series exists from boot — otherwise rate() is empty until the first read, and a counter diff taken across an index-served query window would be ambiguous.

instanceStage and vault are constant labels: both are fixed for the lifetime of the process, and vault keeps two instances of the same stage from merging their per-type counts into one series at query time. instanceStage is deliberately not called stage: that label carries each task's own frontmatter stage, which varies within one scrape.

func NewNoopMetrics added in v0.34.0

func NewNoopMetrics() Metrics

NewNoopMetrics returns metrics that record nothing.

Attached vaults use it. The service's gauges carry the primary vault as a constant label, so an attached vault's index build must not publish through them: Build calls SetOpenTasks with that vault's counts, which would overwrite the primary vault's open-task series with another vault's numbers.

type OpenTaskKey added in v0.5.0

type OpenTaskKey struct {
	Stage    string
	TaskType string
	Phase    string
	JobState string
	PRState  string
	Assignee string
}

OpenTaskKey identifies one vault_api_open_tasks series. Stage is the task's own frontmatter stage — the environment its work targets — not the stage of the vault-api instance serving it; that one is the constant instance_stage label. Phase is the task's normalized frontmatter phase: the index normalises through domain.NormalizeTaskPhase before storing it, so the label never carries both spellings of one phase (in_progress is reported as execution).

JobState and PRState are the two labels the four-state split needs. JobState separates a task an agent is working from one merely marked open; PRState makes "the PR is already merged" provable from this metric alone.

Assignee is the task's own frontmatter assignee, carried raw. It is what separates an owned record from an abandoned one at the same phase: without it two tasks in identical states are indistinguishable on the dashboard, and the unowned one — the one that needs a human — cannot be picked out.

type PageContent added in v0.36.0

type PageContent struct {
	Vault   string            `json:"vault"`
	Path    string            `json:"path"`
	Name    string            `json:"name"`
	Content string            `json:"content"`
	Links   map[string]string `json:"links"`
	Embeds  map[string]string `json:"embeds"`
}

PageContent is one page as a renderer needs it: the body, the vault-relative path of every wikilink target the body resolves, and the body of every page the body embeds. Links and embeds are resolved against the index, so a caller needs no second request and no local vault walk.

type Readiness

type Readiness struct {
	Ready           bool   `json:"ready"`
	Vault           string `json:"vault"`
	IndexAgeSeconds int64  `json:"index_age_seconds"`
	// TreeAgeSeconds is how long ago the working tree was last fetched from its
	// remote, and is null when the tree carries no FETCH_HEAD to measure. It is
	// separate from IndexAgeSeconds because the two fail independently: the index
	// can stop being confirmed on a live tree, and a tree can freeze under a
	// healthy loop. A caller gating on Ready does not need to read it, but an
	// operator diagnosing a red pod does: it says which half went stale.
	TreeAgeSeconds *int64 `json:"tree_age_seconds"`
	Head           string `json:"head"`
	Warnings       int    `json:"warnings"`
	// UnavailableVaults names every attached vault whose index has not built. It
	// is empty outside multi-vault mode. An attached vault never gates Ready —
	// the primary vault's freshness does — but a list query that silently lacks a
	// vault's rows reads exactly like "that vault has nothing", so the gap is
	// named here as well as in the log.
	UnavailableVaults []string `json:"unavailable_vaults,omitempty"`
}

Readiness is the body of GET /readiness.

type Side added in v0.3.0

type Side struct {
	Content       []byte
	CommitterTime time.Time
}

Side is one side of a three-way merge: the file's content at that side plus the committer time of the commit that produced it. The time is what breaks a same-key tie under the last-writer-wins rule.

type TaskFilter

type TaskFilter struct {
	Assignee string
	Status   string
	Phase    string
	Goal     string
	Cluster  string
	// TaskTypes is a set: a task matches when its type is any one of them, so a
	// caller whose population spans several types asks once instead of issuing a
	// query per type. A single-value filter is the one-element case.
	//
	// Two consequences a caller should know. An empty slice means "unset" like
	// every other field here, but a slice holding one empty string means "match
	// nothing" — build it from parsed input rather than from an optional field.
	// And a value that resolves to no task is silently absorbed when another value
	// matches: {a, typo} returns the a-tasks rather than nothing. That tolerance is
	// deliberate, because a type with no pages yet is legitimate, but a dedup
	// caller must not rely on the result being complete — it is the caller's own
	// set that a dropped type would silently shrink.
	TaskTypes []string
	ShortID   string
	// UpdatedSince keeps only tasks whose page was modified at or after it. It is
	// a pointer so "no bound" and "modified at the zero instant" stay distinct.
	UpdatedSince *time.Time
	// Flag, when non-nil, keeps only tasks whose frontmatter flag equals it. A
	// pointer because "unset" and "flag: false" are different queries.
	Flag *bool
	// DueNow keeps only tasks due at Now: defer_date absent (nothing postpones it)
	// or defer_date at or before Now. Now must be set when DueNow is true.
	DueNow bool
	// Now is the instant DueNow measures against. It is injected rather than read
	// from the wall clock so a test can pin the boundary.
	Now time.Time
}

TaskFilter narrows a task list. Empty fields are ignored; a query with no fields returns every indexed task.

type TaskItem

type TaskItem struct {
	ID string `json:"id"`
	// TaskIdentifierPrevious is the page's recorded predecessor identifier, empty
	// when the page was never re-addressed. ID carries the CURRENT identifier; this
	// carries the one it replaced, so a consumer holding only the listing can answer
	// "which file carries this identifier" for both keys. Without it the predecessor
	// is readable only by reading every page — the N+1 this projection exists to
	// remove, and the reason an alias lookup could never be answered from the index.
	TaskIdentifierPrevious string   `json:"task_identifier_previous,omitempty"`
	Title                  string   `json:"title"`
	Path                   string   `json:"path"`
	Status                 string   `json:"status"`
	Phase                  string   `json:"phase"`
	TaskType               string   `json:"task_type"`
	ShortID                string   `json:"short_id,omitempty"`
	Stage                  string   `json:"stage"`
	Assignee               string   `json:"assignee"`
	Goals                  []string `json:"goals"`
	Cluster                *string  `json:"cluster"`
	Flag                   bool     `json:"flag"`
	Vault                  string   `json:"vault"`
	// CurrentJob is the task's raw frontmatter current_job — the id of the job
	// that claimed it, empty when none has. The gauge reports its presence as
	// job_state; the id itself is served because a reader chasing a stuck record
	// needs the job, not just the fact of one.
	CurrentJob string `json:"current_job,omitempty"`
	// PRState is the task's last observed PR state, written into the frontmatter
	// by the daily close-obsolete sweep: open, merged, closed or none. Empty means
	// the sweep has not looked at this record yet.
	PRState string `json:"pr_state,omitempty"`
	// UpdatedAt is the page's last-modified time, which is what `updated_since`
	// filters on. It is a pointer because a page the storage layer reported no
	// mtime for must be distinguishable from one modified at the zero instant.
	UpdatedAt *time.Time `json:"updated_at,omitempty"`
	// DeferDate is the task's frontmatter defer_date, nil when the field is
	// absent. It is served because the `due` filter reads it and a caller checking
	// the boundary needs the value the filter saw.
	DeferDate *time.Time `json:"defer_date,omitempty"`

	// The fields below are the rest of what the board renders. Without them a
	// consumer serving the board from this list must read each task page itself —
	// an N+1 over the whole vault — or drop the field from the card.
	//
	// BlockedBy is the page's blocked_by list, always non-nil so a row with no
	// blockers serialises as [] rather than null. The board's blocked badge reads
	// the list itself, not a precomputed boolean, because it also names the
	// blockers on the card.
	BlockedBy []string `json:"blocked_by"`
	// Priority is the frontmatter priority as an integer, 0 when absent. It is
	// always emitted so a caller ordering the board never has to infer "missing"
	// from an absent key.
	Priority int `json:"priority"`
	// DueDate and PlannedDate are the frontmatter dates rendered by vault-cli's
	// own rule: YYYY-MM-DD for a date-only value, RFC3339 for one carrying a time,
	// nil when absent. The board's urgency tiers compare the date-only form
	// against today, which is why this is a string and not a timestamp.
	DueDate     *string `json:"due_date"`
	PlannedDate *string `json:"planned_date"`
	// ClaudeSessionID is the page's recorded session, null when it carries none.
	// The board's live-session badge resolves liveness from it.
	ClaudeSessionID *string `json:"claude_session_id"`
	// Jira is the page's own `jira:` value, carried verbatim — in the vaults it is
	// as often a bare key as a browse URL — and null when absent.
	Jira *string `json:"jira"`
	// Mode is the page's own `mode:` value, the execution mode the row opens with,
	// null when absent. It is carried verbatim because the field is free-form on
	// disk.
	Mode *string `json:"mode"`
	// OpenQuestions is the task's Open Questions section in section order, always
	// non-nil so a task with none serialises as [] rather than null.
	OpenQuestions []domain.OpenQuestion `json:"open_questions"`
}

TaskItem is the typed projection of one task page. It is served by GET /api/v1/tasks and GET /api/v1/tasks/{id}.

type TopicItem added in v0.29.0

type TopicItem struct {
	ID     string `json:"id"`
	Title  string `json:"title"`
	Path   string `json:"path"`
	Status string `json:"status"`
	// Phase is the topic's own `phase:` on the same terms as GoalItem.Phase.
	Phase    string   `json:"phase"`
	Goals    []string `json:"goals"`
	Themes   []string `json:"themes"`
	Assignee string   `json:"assignee,omitempty"`
	// Priority is the topic's own `priority:` on the same terms as GoalItem.Priority.
	Priority int    `json:"priority"`
	Vault    string `json:"vault"`
	// Flag and SessionID carry the same two fields GoalItem documents, for the
	// same reason: a topic can be flagged, and its manager's recorded session is
	// what a consumer resolves a subject's liveness from. The enrichment fields
	// are documented on GoalItem and apply identically here.
	Flag      bool     `json:"flag"`
	SessionID string   `json:"claude_session_id"`
	Role      string   `json:"role"`
	Mode      string   `json:"mode"`
	DeferDate string   `json:"defer_date,omitempty"`
	BlockedBy []string `json:"blocked_by,omitempty"`
	FlagSetBy string   `json:"flag_set_by"`
	// Jira is the topic's own `jira:` value, on the same terms as GoalItem.Jira.
	// No topic page declares one today, so it reads null everywhere — the key is
	// served anyway, because a consumer's card slot is already wired to it and
	// absence would read as "this build has no such field".
	Jira *string `json:"jira"`
}

TopicItem is the typed projection of one topic page. It is served by GET /api/v1/topics.

Directories

Path Synopsis
Package gitrest is the write half of the API.
Package gitrest is the write half of the API.
Package handler owns the HTTP surface: the five canonical admin endpoints and the typed /api/v1 read endpoints.
Package handler owns the HTTP surface: the five canonical admin endpoints and the typed /api/v1 read endpoints.
Package publisher emits typed task change events onto the vault's task topic.
Package publisher emits typed task change events onto the vault's task topic.
Package rules carries the write rules the API enforces: which phase and status transitions are legal, and which guards gate the approve endpoint.
Package rules carries the write rules the API enforces: which phase and status transitions are legal, and which guards gate the approve endpoint.

Jump to

Keyboard shortcuts

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