vaultapi

package
v0.21.8 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: BSD-2-Clause Imports: 21 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 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 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 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 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).

Types

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
	// 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 GoalItem

type GoalItem struct {
	ID       string   `json:"id"`
	Title    string   `json:"title"`
	Path     string   `json:"path"`
	Status   string   `json:"status"`
	Themes   []string `json:"themes"`
	Assignee string   `json:"assignee,omitempty"`
	Vault    string   `json:"vault"`
}

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) 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) 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) 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) 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) 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 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 differently.
	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 both sides changed differently is not merged at all — it quarantines, because concatenating two writers' 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.

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 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"`
}

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
}

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"`
	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"`
}

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

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