vaultapi

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: BSD-2-Clause Imports: 20 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"
)
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 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 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 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
}

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

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 baseline up to head and
	// returns the baseline to carry forward.
	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.

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. isPermanent classifies an Emit error as one the broker will never accept; nil treats every error as permanent.

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.

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.

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
}

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.

type Readiness

type Readiness struct {
	Ready           bool   `json:"ready"`
	Vault           string `json:"vault"`
	IndexAgeSeconds int64  `json:"index_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
}

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"`
	Stage    string   `json:"stage"`
	Assignee string   `json:"assignee"`
	Goals    []string `json:"goals"`
	Cluster  *string  `json:"cluster"`
	Flag     bool     `json:"flag"`
	Vault    string   `json:"vault"`
}

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