store

package
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2026 License: MIT Imports: 27 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package store owns the READ path over tasks.jsonl and archive.jsonl: the coherent snapshot, the API-grade checked read, and the revision tokens derived from the exact bytes that read captured.

There is deliberately no write path here — no journal append, no atomic replace, no mutation. What there IS, and what a read-only package would not obviously need, is the lock: a read takes the same advisory sidecar lock a mutation does, so `.tasks.jsonl.lock` is a real observable effect of reading and the conformance corpus compares its presence and its mode.

Index

Constants

View Source
const (
	DelegationField     = record.DelegationField
	DelegationDelegated = "delegated" // human, awaiting the person
	DelegationReady     = "ready"     // agent pool, unclaimed
	DelegationClaimed   = "claimed"   // agent pool, held by one worker
	// AssigneeLimit bounds both an assignee address and a worker id.
	AssigneeLimit = 200
)

The delegation vocabulary, spelled as lib/tasks/delegation.rb spells it.

View Source
const (
	ProposalApprove = "approve"
	ProposalReject  = "reject"
)

The two decisions.

View Source
const DeferTag = "defer"

DeferTag is the semantic tag that means someday/maybe. Closing a task drops it, because a finished task is not deferred.

Variables

View Source
var (
	DelegationKinds = []string{"human", "agent"}
	DelegationModes = []string{"refine", "research", "implement"}
)

DelegationKinds and DelegationModes are the closed vocabularies a refusal quotes back to the caller.

View Source
var Priorities = []string{"A", "B", "C"}

Priorities is Check::PRIORITIES.

Functions

func DelegationStamp

func DelegationStamp(instant time.Time) string

DelegationStamp is the second-resolution UTC instant every marker records.

func FormatStamp

func FormatStamp(instant time.Time, device string) string

FormatStamp is UpdateStamp.format: one sortable token so the timestamp and the device tiebreaker cannot drift apart.

func StoreRevisionForContents

func StoreRevisionForContents(live, archive []byte) string

StoreRevisionForContents is the content-derived global revision: a digest of the exact bytes of both files, length-prefixed so that no pair of contents can be re-split into another pair with the same digest. An absent file contributes the length -1, which no present file can spell.

It is produced for invalid bytes too, and that is the honest answer: the token is a digest of bytes, not an assertion that they parse.

Types

type ArchiveBlock

type ArchiveBlock struct {
	RootID     string
	RootTitle  string
	OpenIDs    []string
	OpenTitles []string
}

ArchiveBlock is one closed root the sweep refuses to move: archiving it would take live, open work into the archive with it.

type ArchivePreview

type ArchivePreview struct {
	Roots       int
	Descendants int
	Blocks      []ArchiveBlock
	// CandidateIDs is every id in the moved set, roots and descendants, in
	// file order.
	CandidateIDs []string
	Fingerprint  string
}

ArchivePreview is a read-only summary of what the next sweep would move. Roots are the DONE/CANCELLED tasks it selects; Descendants excludes those roots.

CandidateIDs and Fingerprint exist for one purpose: a `--json` caller reads the preview to learn WHICH records will move, then pins the sweep to it. If anything changed in between — including the day stamp a moved record carries, so a sweep prepared either side of local midnight also refuses — the sweep refuses rather than reporting a stale list as though it were true.

func (ArchivePreview) Blocked

func (p ArchivePreview) Blocked() bool

Blocked reports whether any closed root still contains open work.

func (ArchivePreview) BlockedRoots

func (p ArchivePreview) BlockedRoots() int

BlockedRoots is how many roots are blocked.

func (ArchivePreview) OpenDescendants

func (p ArchivePreview) OpenDescendants() int

OpenDescendants is how many open tasks are blocking, across every root.

func (ArchivePreview) Total

func (p ArchivePreview) Total() int

Total is every task the sweep would move.

type ArchiveRefusal

type ArchiveRefusal string

ArchiveRefusal names a safety gate that stopped the sweep. The spellings are the `reason` field of the CLI's error envelope and of the planned HTTP endpoint, so a caller branches on one vocabulary across every surface.

const (
	// ArchiveNotRefused is the zero value: the sweep was allowed to proceed.
	ArchiveNotRefused ArchiveRefusal = ""
	// ArchiveUnsupportedSchema is the version gate.
	ArchiveUnsupportedSchema ArchiveRefusal = "unsupported_schema"
	// ArchivePreviewChanged means the live file moved while the sweep was being
	// prepared, so the pinned preview no longer describes it.
	ArchivePreviewChanged ArchiveRefusal = "preview_changed"
	// ArchiveOpenDescendants means a closed root still contains open work.
	ArchiveOpenDescendants ArchiveRefusal = "open_descendants"
	// ArchiveConflict means archive.jsonl already holds partial or differing
	// copies of the candidate ids — an interrupted sweep that cannot be
	// resumed safely.
	ArchiveConflict ArchiveRefusal = "archive_conflict"
)

The refusals.

type ArchiveResult

type ArchiveResult struct {
	// Roots is how many closed roots moved. Zero with no refusal means there
	// was nothing to archive.
	Roots int
	// Refusal is the gate that stopped the sweep, or "" when none did.
	Refusal ArchiveRefusal
	// Preview is what the sweep saw, carried on every refusal that has one so
	// the caller can report the blocked subtrees without a second read.
	Preview ArchivePreview
	// Details are the conflicting ids behind ArchiveConflict.
	Details []string
	// Failed marks a sweep that WROTE and was rolled back. Live tasks were
	// preserved; the reason is in LastRollback.
	Failed bool
}

ArchiveResult is the outcome of one sweep.

func (ArchiveResult) OK

func (r ArchiveResult) OK() bool

OK reports a sweep that was allowed to run, whether or not it moved anything.

type Change

type Change struct {
	Field PatchField
	Value PatchValue
}

Change is one field and the value it takes.

type Changeset

type Changeset struct {
	// ID is the target task's stable id.
	ID string
	// Changes is the set of field changes, in any order.
	Changes []Change
	// ExpectedRevision is the token the caller read before deciding. Empty
	// means "no precondition", which only an adapter with its own guard should
	// send.
	ExpectedRevision string
	// HistoryLabel is the undo entry's text; empty takes Ruby's spelling.
	HistoryLabel string
	// CoalesceKey groups byte-contiguous edits into one undo step.
	CoalesceKey string
	// Today is the ISO day a close stamps and a roll measures from.
	Today string
	// Context is the clock a temporal field resolves against.
	Context temporal.Context
}

Changeset is an immutable, transport-neutral request to change one task in one checked transaction.

`ExpectedRevision` is an opaque store-produced value: a caller carries it forward from TaskRevision rather than constructing it from a file coordinate or a wall-clock timestamp, because neither of those is a statement about what the task SAID when the caller decided.

Changes is a SLICE rather than a map for two reasons. Ruby applies a changeset in `TaskChangeset::FIELD_ORDER` rather than in the order a caller happened to write it — several fields interact, and the order is part of the command contract — and a slice is also the only shape in which a caller can name the same field twice, which is a refusal rather than a last-one-wins.

type CheckedRead

type CheckedRead struct {
	Status        Status
	Snapshot      *Snapshot
	StoreRevision string
	Errors        []Entry
	Warnings      []Entry
}

CheckedRead is the typed result of the API-grade read path. Unlike Snapshot it can represent an invalid or unavailable store without attempting to build a tree from untrusted records.

func (CheckedRead) OK

func (c CheckedRead) OK() bool

OK reports whether the read produced a snapshot.

type CreateCommand

type CreateCommand struct {
	Title    string
	Priority string
	Tags     []string
	State    string
	Project  string
	ParentID string
	Notes    []string
	Deferred bool
	// Scheduled and Deadline are the two dates a capture may name, each
	// optionally carrying a wall time and a zone. HasScheduled / HasDeadline
	// distinguish "not supplied" from the zero date, which a bare
	// temporal.Value cannot.
	Scheduled    temporal.Value
	HasScheduled bool
	Deadline     temporal.Value
	HasDeadline  bool
	// Recurrence is a canonical cookie and Lead a canonical span. Both are
	// intents ABOUT a date, and both are validated here against the dates this
	// very create is about to write — a create that would need an immediate
	// repair is a create that should have been refused.
	Recurrence string
	Lead       string
}

CreateCommand is the typed create every capture goes through.

type Entry

type Entry struct {
	Source  Source `json:"source,omitempty"`
	Line    int    `json:"line"`
	Message string `json:"message"`
}

Entry is one validation diagnostic. It carries only source, line and a safe message — never a configured filesystem path.

type HistoryOutcome

type HistoryOutcome string

HistoryOutcome is what a planned undo or redo would do, without doing it.

const (
	// HistoryUnsupportedSchema means this build cannot read the store at all.
	HistoryUnsupportedSchema HistoryOutcome = "unsupported_schema"
	// HistoryEmpty means there is no step in that direction — no journal, an
	// exhausted one, or one whose blobs no longer verify.
	HistoryEmpty HistoryOutcome = "empty"
	// HistoryConflict means the step could not be applied: the live files no
	// longer match the state it expects — an out-of-band edit landed after the
	// journal's tip and replaying across it would clobber that edit — or the
	// application itself failed and the files were put back.
	HistoryConflict HistoryOutcome = "conflict"
	// HistoryOK means the step was applied and the cursor committed.
	HistoryOK HistoryOutcome = "ok"
)

type Item

type Item struct {
	Line     int
	ID       string
	HasID    bool
	State    string
	Priority string
	Title    string
	// AllTags is the tag list exactly as the record stored it, contexts and
	// ordinary tags interleaved. Tags and Contexts are the same list split for
	// rendering; AllTags is what the headline and every tag filter read, because
	// stored order is part of the headline's bytes.
	AllTags  []string
	Tags     []string
	Contexts []string
	// Scheduled, Deadline and Closed are normalized ISO dates, or "" when the
	// stored value is missing or unparseable.
	Scheduled     string
	Deadline      string
	Closed        string
	Archived      string
	ScheduledTime json.RawMessage
	DeadlineTime  json.RawMessage
	Recur         string
	Lead          string
	LeadSkip      string
	Delegation    json.RawMessage
	FormalLinks   []links.FormalLink
	Parent        string
	HasParent     bool
	Source        Source
}

Item is a task as the read surfaces see it: coerced defensively so a hand-edited or malformed record can never crash a reader before Check gets to report it. The coercion only keeps readers alive; it never repairs the underlying breakage.

type MutationResult

type MutationResult struct {
	Status MutationStatus
	Errors []string
	// FieldErrors is the per-field breakdown of a refusal, when the refusal has
	// one. A placement that names a missing anchor says so under `before_id`,
	// which is what lets a caller correct the right argument.
	FieldErrors   map[string][]string
	TouchedIDs    []string
	ReadSnapshot  *Snapshot
	StoreRevision string
	// RolledBack distinguishes a failed mutation that WROTE and restored the
	// previous bytes from a preflight refusal that never wrote. The two leave
	// byte-identical files behind and exit the same way, so the filesystem
	// cannot tell them apart and the boolean is the only thing that can.
	RolledBack    bool
	RollbackStage RollbackStage
	// Summary carries the per-operation facts an adapter renders: the
	// delegation holder for a conflict, the action for the error envelope.
	Summary MutationSummary
}

MutationResult is the immutable outcome every write path returns.

func (MutationResult) Changed

func (r MutationResult) Changed() bool

Changed reports whether the mutation actually wrote.

func (MutationResult) ExitCode

func (r MutationResult) ExitCode() int

ExitCode is the CLI status this outcome exits with.

func (MutationResult) FirstError

func (r MutationResult) FirstError() string

FirstError is the message a refusal quotes, or "" when it carries none.

func (MutationResult) OK

func (r MutationResult) OK() bool

OK is MutationResult#ok?: a no-op that succeeded is a success.

type MutationStatus

type MutationStatus string

MutationStatus is MutationResult::STATUSES. Refusals are values rather than errors so an adapter can map the same outcome consistently for a CLI, a TUI, or a transport that does not exist yet.

const (
	MutationOK                MutationStatus = "ok"
	MutationNoChange          MutationStatus = "no_change"
	MutationNotFound          MutationStatus = "not_found"
	MutationStale             MutationStatus = "stale"
	MutationInvalid           MutationStatus = "invalid"
	MutationConflict          MutationStatus = "conflict"
	MutationCycle             MutationStatus = "cycle"
	MutationTooDeep           MutationStatus = "too_deep"
	MutationUnsupportedSchema MutationStatus = "unsupported_schema"
	MutationStoreInvalid      MutationStatus = "store_invalid"
	MutationUnavailable       MutationStatus = "unavailable"
)

The statuses, spelled exactly as lib/tasks/patch_result.rb spells them.

type MutationSummary

type MutationSummary struct {
	Action string
	Holder string
	At     string
	TaskID string
	// From and To are a state transition's endpoints, which a proposal decision
	// reports and the CLI prints. A move reuses them for the old and the new
	// parent id, which is the same question asked of a different axis.
	From string
	To   string
	// Before is the anchor an anchored move placed the subtree in front of, and
	// CurrentParentID is the anchor's ACTUAL parent when that anchor turned out
	// not to be a child of the destination. The second is the whole content of a
	// placement conflict: the caller decided against a sibling list that has
	// since changed, and needs to know what it changed to.
	Before          string
	CurrentParentID string
	// CreatedID, RootID and CreatedRoot are a project create's report. The
	// bootstrapped root is called out separately because it is a SECOND section
	// the caller never asked for, and a caller that renders "created X" without
	// knowing a "Projects" heading also appeared has described half the write.
	CreatedID   string
	RootID      string
	CreatedRoot bool
	// MovedIDs is every task id the move relocated, root first. An empty (but
	// non-nil) slice is a real answer: the task was already where it was asked
	// to be, so nothing moved and no undo slot was burned.
	MovedIDs []string
	// Removed, Descendants and OpenDescendants are the delete's counts. They
	// are what the cascade refusal quotes back — "3 descendants (2 open)" — so
	// the caller learns what --cascade would actually remove.
	Removed         int
	Descendants     int
	OpenDescendants int
	// ProposedDescendantIDs is the leaves-first refusal: the undecided
	// proposals under this one that must be decided before it can be.
	ProposedDescendantIDs []string
	// Previous is the delegation marker this write REPLACED, as stored JSON,
	// captured inside the transaction. A caller that read it before the write
	// instead would be racing: whether an inherited WAITING is cleared depends
	// on what the marker was at the moment the marker changed, not a moment
	// earlier.
	Previous string
}

MutationSummary is the union of the summary fields the CLI reads. Ruby returns an untyped Hash per operation; the fields any surface here consumes are few and naming them is what keeps a typo from silently reading nil.

type Options

type Options struct {
	// JournalDir is the history directory for this store.
	JournalDir string
	// Now is the clock every stamp reads.
	Now func() time.Time
	// Device is the update stamp's tiebreaker half.
	Device string
	// IDSource mints task ids; nil means the collision-checked random mint.
	IDSource func() string
	// CoalesceScope is the journal's per-process coalescing scope.
	CoalesceScope string
	// MaxDepth is the nesting cap a create may not push a subtree past.
	MaxDepth int
	// UndoLimit is how many undo steps the journal retains.
	UndoLimit int
}

Options carries everything a WRITING store needs and a reading one does not: where history goes, what time it is, who is writing, and how ids are minted.

They are injected rather than read from the environment here for the reason lib/tasks/determinism.rb states: the store stays env-free, and the adapter boundary is the single place a harness pin turns into a value.

type PatchField

type PatchField string

PatchField names the single-field patches this build implements. The set is deliberately closed: a field the port has not reached refuses at the CLI rather than silently taking a default path through the transaction. The vocabulary and the transaction both live in patch.go.

const (
	// FieldTitle replaces the task's title.
	FieldTitle PatchField = "title"
	// FieldDeferred adds or removes the someday/maybe tag.
	FieldDeferred PatchField = "deferred"
	// FieldScheduled sets or clears the available-from date.
	FieldScheduled PatchField = "scheduled"
	// FieldDeadline sets or clears the deadline.
	FieldDeadline PatchField = "deadline"
	// FieldRecurrence sets or clears the recurrence cookie.
	FieldRecurrence PatchField = "recurrence"
	// FieldLead sets or clears the lead-time window.
	FieldLead PatchField = "lead"
	// FieldContexts replaces the @context slice of the tag list.
	FieldContexts PatchField = "contexts"
	// FieldTags replaces the ordinary slice of the tag list.
	FieldTags PatchField = "tags"
	// FieldBody replaces the note body.
	FieldBody PatchField = "body"
	// FieldLinks replaces the ordered formal-link list.
	FieldLinks PatchField = "links"
	// FieldLocation moves the task. Not implemented — see applyFieldPatch.
	FieldLocation PatchField = "location"

	// FieldTagDelta is the CLI `tag` verb's whole-sequence add/remove.
	FieldTagDelta PatchField = "tag_delta"
	// FieldActivate is the composite "available now" operation.
	FieldActivate PatchField = "activate"
	// FieldDateClear is `undate`: both date fields in one checked write.
	FieldDateClear PatchField = "date_clear"
)

The implemented fields. The list is EditSnapshot::FIELDS plus the three composite commands TaskChangeset::SPECIAL_FIELDS names, which are not editor fields but do reach the same transaction.

const (
	FieldPriority PatchField = "priority"
	FieldState    PatchField = "state"
)

The two fields whose value is a plain word. The rest are in patch.go, with the value shapes they accept.

type PatchRequest

type PatchRequest struct {
	// ID is the target task's stable id.
	ID string
	// Field is the single field this patch owns.
	Field PatchField
	// Value is the new value, in the field's own shape.
	Value PatchValue
	// Expected is the baseline ExpectedFor produced before the caller decided.
	Expected string
	// Label is the history entry's text; "" takes Ruby's default spelling.
	Label string
	// Today is the ISO day a close stamps and a roll measures from.
	Today string
	// Context is the clock a temporal roll resolves candidates against. The
	// zero value means noon UTC on Today, which is `advance_recurrence_records`'
	// own default.
	Context temporal.Context
	// CoalesceKey groups byte-contiguous edits into one undo step.
	CoalesceKey string
	// Force is `patch_location`'s `force:` — re-append a subtree to the parent
	// it already has instead of treating the move as satisfied. No other field
	// reads it, which is why it is a request flag rather than part of the value.
	Force bool
}

PatchRequest is one field-owned semantic change plus everything the field needs to decide it. Field, Value and Expected are the command; Today and Context are the ambient facts a temporal field reads.

type PatchValue

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

PatchValue is the typed value a field patch carries.

Ruby's `apply_semantic_patch` receives an untyped Ruby object and each field asserts the shape it accepts: a String for `title`, `true`/`false` for `deferred`, an Array for the tag slices, a Date or TemporalValue for the two date fields, `nil` for "clear this". A single Go string cannot express that — most importantly it cannot tell "clear the priority" (nil) apart from "set the priority to the empty string" (which Ruby refuses) — so the value model is explicit instead. The zero value is the CLEARING value, which is what the absent-argument spelling of every clearing verb means.

func BoolValue

func BoolValue(value bool) PatchValue

BoolValue is a `true`/`false` value.

func LinksValue added in v1.7.0

func LinksValue(values []links.FormalLink) PatchValue

LinksValue is an ordered full replacement of the stored formal-link list.

func ListValue

func ListValue(values []string) PatchValue

ListValue is an Array-of-String value.

func NoValue

func NoValue() PatchValue

NoValue is Ruby's `nil`: clear this field.

func PlacementValue

func PlacementValue(parentID, beforeID string) PatchValue

PlacementValue is a location change expressed as a structural destination.

func TagDeltaValue

func TagDeltaValue(add, remove []string) PatchValue

TagDeltaValue is the `{add:, remove:}` Hash the CLI's `tag` verb sends.

func TemporalValue

func TemporalValue(value temporal.Value) PatchValue

TemporalValue is a date, optionally qualified by a wall time and a zone.

func TextValue

func TextValue(text string) PatchValue

TextValue is a String value.

func UnnestValue

func UnnestValue() PatchValue

UnnestValue is TaskChangeset::UNNEST: "move this task up to the section that encloses it", resolved against the file rather than named by the caller.

func (PatchValue) IsNone

func (v PatchValue) IsNone() bool

IsNone reports the clearing value.

func (PatchValue) Placement

func (v PatchValue) Placement() (Placement, bool)

Placement is the structural destination of a placement value.

func (PatchValue) Text

func (v PatchValue) Text() string

Text is the string half of a text value, or "" for any other kind.

type Placement

type Placement struct {
	ParentID string
	BeforeID string
}

Placement is Tasks::TaskPlacement: an immutable, transport-neutral structural destination for one task subtree.

It is a VALUE, not a pair of record indexes, and that is the whole point. The store resolves the two stable ids under its own mutation lock; an adapter that translated them into positions first would be resolving them against a read it no longer holds, so a concurrent write between the read and the mutation would silently move a different task.

An empty BeforeID means "append as the destination parent's last child".

func (Placement) Appends

func (p Placement) Appends() bool

Appends reports the no-anchor spelling: land at the end of the parent's children rather than in front of a named sibling.

type RepairBlocker

type RepairBlocker struct {
	File    string
	Line    int
	Message string
}

RepairBlocker is a defect repair does NOT know how to converge. Reported so the caller learns what still blocks the store rather than only that repair refused.

type RepairFix

type RepairFix struct {
	File    string
	Line    int
	Kind    RepairKind
	Message string
	ID      string
}

RepairFix is one defect repair knows how to converge, named by the file and the physical line it sits on.

Message deliberately restates the DEFECT in Check's own wording rather than the action taken: the report then reads as a line-for-line answer to what `tasks check` just printed, and it means the same thing whether the pass wrote or refused. ID carries the minted id, and only a written pass should show it — a plan that is never written mints an id nothing will ever hold.

type RepairKind

type RepairKind string

RepairKind is the machine-readable discriminator for a defect repair knows.

const (
	// RepairMintedID is a record with no id. The targeted repair mints one, but
	// only for the record it was asked about.
	RepairMintedID RepairKind = "minted_id"
	// RepairDroppedTemporalKeys is an unknown key inside `scheduled_time` or
	// `deadline_time` — the drop the format calls "the repair path, not data
	// loss", made explicit here so the in-memory re-check sees it and the
	// report can enumerate it.
	RepairDroppedTemporalKeys RepairKind = "dropped_temporal_keys"
)

The two known members of the class.

type RepairResult

type RepairResult struct {
	Status   RepairStatus
	Fixes    []RepairFix
	Blockers []RepairBlocker
	Written  bool
	DryRun   bool
}

RepairResult is the outcome of one Repair pass. Written distinguishes a pass that changed the files from a clean store and from a dry run, so a caller never has to infer it from Fixes.

func (RepairResult) OK

func (r RepairResult) OK() bool

OK reports a pass that left the store valid.

type RepairStatus

type RepairStatus string

RepairStatus is the outcome vocabulary of one pass.

const (
	// RepairOK means the store validates now, or would under a dry run.
	RepairOK RepairStatus = "ok"
	// RepairUnrepairable means at least one blocker was left and NOTHING was
	// written.
	RepairUnrepairable RepairStatus = "unrepairable"
	// RepairUnsupportedSchema is the version gate.
	RepairUnsupportedSchema RepairStatus = "unsupported_schema"
)

The statuses.

type Resource

type Resource struct {
	ID       string `json:"id"`
	Kind     string `json:"kind"`
	Revision string `json:"revision"`
}

Resource is one revisioned object in a snapshot: the shape the HTTP surface publishes and the conformance probe reports.

type RollbackStage

type RollbackStage string

RollbackStage names which half of a mutation failed and forced the rollback. `write` means the atomic replace itself raised and validation never ran; `validation` means the bytes landed and the post-write check refused them. They are indistinguishable in `rolled_back` alone, and naming the wrong one misattributes the failure in the only diagnostic the user gets.

const (
	RollbackWrite      RollbackStage = "write"
	RollbackValidation RollbackStage = "validation"
)

The two stages.

type Snapshot

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

Snapshot is a coherent view of the task files. A caller can hold one while rendering and safely ask for a task's revision or its place in the tree without mixing fields from a later reload.

func (*Snapshot) ArchiveItems

func (s *Snapshot) ArchiveItems() []Item

ArchiveItems returns a detached copy of the archived tasks in file order.

func (*Snapshot) ArchiveLoaded

func (s *Snapshot) ArchiveLoaded() bool

ArchiveLoaded reports whether the archive half was captured.

func (*Snapshot) ArchiveRecords

func (s *Snapshot) ArchiveRecords() []record.Record

ArchiveRecords returns a detached copy of the parsed archive records.

func (*Snapshot) ChildrenOf

func (s *Snapshot) ChildrenOf(id string) []Item

ChildrenOf is the live items whose parent is `id`, in file order. The tree lives in the parent pointers, so no boundary is ever inferred by scanning.

func (*Snapshot) FieldBaselines

func (s *Snapshot) FieldBaselines(id string, fields []PatchField) (map[PatchField]string, bool)

FieldBaselines returns conflict tokens computed from this snapshot's exact record set. Values and baselines therefore come from one read; callers never pair an old display value with a fresh expectation from another store read.

func (*Snapshot) Items

func (s *Snapshot) Items() []Item

Items returns a detached copy of the live tasks in file order.

func (*Snapshot) LiveRecords

func (s *Snapshot) LiveRecords() []record.Record

LiveRecords returns a detached copy of the parsed live records.

func (*Snapshot) Resources

func (s *Snapshot) Resources() []Resource

Resources is every identified item with its revision, sorted by (id, kind) so two implementations that agree about content agree about order too.

func (*Snapshot) RevisionFor

func (s *Snapshot) RevisionFor(item Item) string

RevisionFor is the store-produced token for an item. There is deliberately no line-number fallback: an id-less legacy item has no API-safe revision.

func (*Snapshot) Roots

func (s *Snapshot) Roots() []Item

Roots is the live items with no parent, in file order.

type Source

type Source string

Source names which file an item came from.

const (
	// SourceLive is tasks.jsonl.
	SourceLive Source = "live"
	// SourceArchive is archive.jsonl.
	SourceArchive Source = "archive"
)

type Status

type Status string

Status is the outcome of a checked read.

const (
	// StatusOK means both files parsed and validated; a snapshot is present.
	StatusOK Status = "ok"
	// StatusUnsupportedSchema means a file declares a schema version this
	// binary cannot read. Its records are never interpreted: reading v1 or a
	// future v3 as if it were v2 is how a store gets silently corrupted.
	StatusUnsupportedSchema Status = "unsupported_schema"
	// StatusStoreInvalid means the bytes parsed but failed validation.
	StatusStoreInvalid Status = "store_invalid"
	// StatusUnavailable means the bytes could not be read at all.
	StatusUnavailable Status = "unavailable"
)

type Store

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

Store owns one live/archive pair. A store built with New can only read; one built with NewWriter carries the Options a mutation needs — the journal directory, the clock, the device, and the id mint.

func New

func New(org, archive string) *Store

New builds a store over the two resolved paths.

func NewWriter

func NewWriter(org, archive string, options Options) *Store

NewWriter builds a store that can mutate. New stays the read-only constructor, so a surface that has no business writing cannot accidentally acquire the ability by construction.

func (*Store) ApplyChangeset

func (s *Store) ApplyChangeset(changeset Changeset) MutationResult

ApplyChangeset applies an atomic multi-field semantic change.

Every field is applied to a DETACHED copy of the records first, so an invalid later field cannot leak a partial in-memory mutation into a file write or a journal step. The transaction is otherwise the one every other mutation runs in: lock, schema gate, preflight, precondition, apply, write, post-write validation, rollback, one journal step, re-read.

func (*Store) Archive

func (s *Store) Archive() string

Archive is the resolved archive path, as the caller spelled it.

func (*Store) ArchivePreviewFor

func (s *Store) ArchivePreviewFor(today string) ArchivePreview

ArchivePreviewFor is the read-only plan of the next sweep. `today` is the stamp a moved record would carry, and it is part of the fingerprint, so the caller must pass the same day to the sweep it pins with this preview.

func (*Store) ArchiveProject

func (s *Store) ArchiveProject(id, today string) ([]string, bool, bool)

ArchiveProject moves a section's entire contiguous subtree to the archive, mirroring the sweep's serialization: the root section drops its parent and gains today's `archived` stamp.

Open tasks do not block — that is caller policy — but an undecided proposal is never archival material, because a proposal archived without a decision is a decision nobody made.

The archive is written FIRST. An interruption between the two writes can then only leave retry-safe duplicates across the files, never a lost subtree. `today` is the day the swept root is stamped with, exactly as the sweep takes it: the READER's day, resolved through their configured time zone. Ruby read `Date.today` here — the one date this store wrote that neither a configured zone nor a harness pin could reach — and that was fixed in lib/tasks/store.rb rather than reproduced.

func (*Store) ArchiveSweep

func (s *Store) ArchiveSweep(today string, expected *ArchivePreview) ArchiveResult

ArchiveSweep moves every fully closed DONE/CANCELLED task subtree to the archive file.

The archive is written FIRST, then the live file. Interruption between the two can leave retry-safe duplicates across the pair, but can never silently lose a task — and the reverse order could. A retry converges only when every stable id has exactly one canonically equal archived copy; partial or mismatched overlap refuses and keeps the live data.

`expected`, when supplied, pins the sweep to a preview the caller already reported: a store that changed in between refuses rather than moving a different set than it announced.

func (*Store) CheckFiles

func (s *Store) CheckFiles() check.Result

CheckFiles is `--all-files`: coherent validation over live and archive under ONE store lock, plus the store-wide id invariant. Unlike the API's checked read this deliberately rejects even a retry-safe id shared across both files — a git push must wait until an archive operation converges to one durable location.

func (*Store) CheckLive

func (s *Store) CheckLive() check.Result

CheckLive is the default `tasks check` report: the live file's structural lint, plus the archive's schema-version header.

Structural errors stay file-scoped — the archive's own records are what `--all-files` is for. The version gate is the deliberate exception, because it is the one condition that is store-wide rather than file-scoped: a v1 archive under a v2 live file makes every read and every mutation refuse the whole store, so a check that could not see it would answer "no structural errors" to a user the refusal had just sent here.

func (*Store) CheckedReadSnapshot

func (s *Store) CheckedReadSnapshot() (CheckedRead, error)

CheckedReadSnapshot captures and validates both files under ONE store lock, returning canonical resources and a content-derived global revision from those exact bytes. The archive is optional, matching first-run behaviour; the live file is required. Invalid records never reach the tree.

An unreadable store is the `unavailable` STATUS, not an error return: that is a fact about the store, and a caller has to be able to report it.

func (*Store) Claim

func (s *Store) Claim(id, worker, coalesceKey string) MutationResult

Claim takes an agent-pool task for one worker.

func (*Store) CompleteProject

func (s *Store) CompleteProject(id, today string) (int, bool)

CompleteProject closes every open descendant task of a section — DONE, today's closed date, the defer tag dropped, the recurrence cookie retired.

Zero closed is a CLEAN result for a project that was already fully closed, and it is also what a rollback returns. Only the second records a rollback, which is the only way a caller can tell them apart.

func (*Store) CreatePreflightFailure

func (s *Store) CreatePreflightFailure() (string, bool)

CreatePreflightFailure is the gate a creating mutation passes before it may inspect or extend the store: both files must already validate. It returns the FIRST error's message, which is what the refusal quotes.

An empty or missing live file is the deliberate exception — that is the first-run state, and creation bootstraps its meta and Inbox records. Any non-empty file, including an archive, has to be valid first: extending a file that is already broken is how one bad record becomes two.

func (*Store) CreateProject

func (s *Store) CreateProject(title string) MutationResult

CreateProject creates one project section under the top-level "Projects" root, bootstrapping that root in the SAME checked write when it is absent.

The duplicate check spans the root's whole child list, projects and areas alike, because those titles are the project-ref candidate set: a second "Home" would make every later ref to it ambiguous.

func (*Store) CreateSection

func (s *Store) CreateSection(title, parentID string) string

CreateSection creates a new empty section.

With no parent it is appended at end of file as a top-level list; with a parent section id it is inserted as the LAST record of that section's subtree, which the DFS pre-order invariant keeps valid. The id is minted against live AND archived ids, so a fresh section can never collide with swept history.

It returns the new section id, or "" when the title is blank, the parent names no section, or the write rolled back.

func (*Store) CreateTask

func (s *Store) CreateTask(command CreateCommand, today string) MutationResult

CreateTask creates one task from a complete typed command in one checked transaction: preflight, normalize, plan, serialize, write, validate, journal.

Serialization happens BEFORE the file is replaced, so a value the emitter refuses is an invalid-command result rather than a partially installed record.

func (*Store) DecideProposal

func (s *Store) DecideProposal(id, action string, notes []string, expectedRevision, today string) MutationResult

DecideProposal accepts or declines one proposal in a single checked transaction.

It is deliberately stricter than an arbitrary state patch, and the two extra rules are the reason it exists as its own operation:

  • it only targets PROPOSED tasks, so a decision can never silently move a task that was never proposed; and
  • a proposal tree is decided LEAVES-FIRST, so approving a parent can never imply approval of the undecided work beneath it.

Approval moves the task to INBOX, rejection to CANCELLED. `notes` are only meaningful on a rejection — withdrawal rationale appended to the body in the SAME write, so the reason and the decision cannot come apart.

func (*Store) Delegate

func (s *Store) Delegate(id, kind, mode, assignee, coalesceKey string) MutationResult

Delegate hands a task to the agent pool or to a named person.

func (*Store) DeleteTask

func (s *Store) DeleteTask(id string, cascade bool, expectedRevision, historyLabel string) MutationResult

DeleteTask hard-deletes a task's subtree from the live file in one checked transaction.

It follows the same transaction shape every other mutation uses — lock, schema gate, preflight refusal, atomic write, post-write rollback, one journal entry, re-read — with two rules of its own:

  • Deletion is never a repair route. A field patch may fix its own invalid record; a delete may not, because the record it would fix is the one it is about to remove, and "the file validates now" would then be true for the wrong reason. Any preflight failure refuses outright.
  • The archive is never consulted or written. An archived-only id is simply not found here, and this is not an alias for CANCELLED.

`expectedRevision` is optional; empty skips the concurrency check, which is the CLI's convenience. A supplied revision guards ALL THREE components, unlike an ordinary field edit, because a cascading delete must be refused if the task, its siblings, or any descendant changed since it was read.

func (*Store) EnsureID

func (s *Store) EnsureID(line int, existing, title string) (string, bool)

EnsureID gives a legacy record without a stable id one, and reports it. It is idempotent: a record that already has an id is returned untouched, with no write and no undo slot burned.

func (*Store) ExpectedFor

func (s *Store) ExpectedFor(id string, field PatchField) (string, bool)

ExpectedFor is the baseline a caller reads before proposing a patch. It is exported because the conflict check is only meaningful when the SAME expression produces the value on both sides of the decision.

func (*Store) FileSnapshot

func (s *Store) FileSnapshot() journal.Snapshot

FileSnapshot is the raw bytes of both task files right now. It is what the journal's states are compared against, so absence has to be representable: an archive that does not exist yet is a different state from an empty one.

func (*Store) HistoryStep

func (s *Store) HistoryStep(delta int) (HistoryOutcome, string)

HistoryStep applies an undo (delta -1) or redo (delta +1) planned by the journal, under the lock so the plan and its commit cannot race another writer. It is Store#history_step, whole: restore, gate, commit, roll back.

The ORDER of the three refusals is the contract. An unsupported schema is refused before the journal is even consulted, because a history that would restore bytes this build cannot read is not a history it may act on. Then "nothing to undo", then the conflict — which is the only one that names a label, because it is the only one where the caller could have been about to undo something specific.

Everything after the conflict check is the write half, and its shape is one promise: an undo either lands completely or leaves the files as it found them. The cursor commit is LAST, so a failed file restore never has a cursor to undo; and the cursor is rolled back before the files are, so a rollback that cannot finish leaves a stale cursor pointing at a step that still exists rather than a committed cursor pointing at bytes that never landed.

func (*Store) LastRollback

func (s *Store) LastRollback() (string, RollbackStage)

LastRollback is the reason and the stage of the most recent mutation that WROTE a file and then restored it, or ("", "") when the last mutation was clean.

It exists for the operations that report failure through a bare boolean or count — the project lifecycle calls — where the recorded rollback is the only evidence that anything was written at all. Set and cleared together through the single writer below, so the pair can never drift apart.

func (*Store) LockPath

func (s *Store) LockPath() string

LockPath is the per-file advisory sidecar beside the resolved live file. The path is canonicalized first, so two spellings of the same file (a symlink, a relative path) lock in common rather than each taking a lock the other cannot see.

func (*Store) Org

func (s *Store) Org() string

Org is the resolved live path, as the caller spelled it.

func (*Store) Patch

func (s *Store) Patch(request PatchRequest) MutationResult

Patch is the typed entry point. It shares one transaction with every other mutation: lock, schema gate, preflight, conflict check, detached apply, write, post-write validation, rollback, one journal step, re-read.

func (*Store) PatchTask

func (s *Store) PatchTask(id string, field PatchField, value string, expected string, label string, today string) MutationResult

PatchTask applies one field-owned semantic change in the same transaction shape a changeset uses.

`expected` is the patch's narrow conflict check: the value the caller read before deciding. It is compared against the value under the write lock, so an edit that landed in between refuses instead of silently overwriting.

The string spelling of the value is retained for the fields whose value IS a string, with "" meaning nil for the two clearable ones. Everything else goes through Patch, which carries the value's real shape.

func (*Store) PatchTaskCoalesced

func (s *Store) PatchTaskCoalesced(id string, field PatchField, value, expected, label, today,
	coalesceKey string) MutationResult

PatchTaskCoalesced is PatchTask with a journal coalesce key.

It exists because a composed operation is TWO writes that have to cost the user ONE undo: setting WAITING behind a human delegation, or appending a blocker note behind a release. Ruby spells that `coalesce_key:`; without it the second write opens its own history step and the user has to undo twice to get back to where they started.

func (*Store) PatchesField

func (s *Store) PatchesField(field PatchField) bool

PatchesField publishes the closed vocabulary, so a caller can ask the side that OWNS the set rather than maintaining a mirror of it that goes stale the moment a field lands here.

func (*Store) ReadSnapshot

func (s *Store) ReadSnapshot(includeArchive bool) (*Snapshot, error)

ReadSnapshot captures live records and, when requested, archive records together under the store lock. The result never changes in place, so a caller can hold it across a render without mixing fields from a later reload.

func (*Store) Release

func (s *Store) Release(id, worker string, force bool, coalesceKey string) MutationResult

Release hands a claim back to the ready queue: claimed → ready, dropping the assignee. A worker must supply the id that matches the live claim; the owner passes force (with no worker id) to clear a stale claim without undelegating.

func (*Store) RenameSection

func (s *Store) RenameSection(id, title string) (string, bool)

RenameSection retitles a section in one checked transaction. It reports the section id, or false when the id names no section, the title is blank, or the write rolled back.

func (*Store) Repair

func (s *Store) Repair(dryRun bool) RepairResult

Repair converges a readable-but-unwritable store in ONE pass, and writes once.

The targeted repairs — minting a missing id, dropping an unknown key inside a temporal object — are each a RECORD repair, while every mutation pre- or post-flights Check over the WHOLE file. So a record repair lands only when its record is the file's last remaining error; with two or more instances the file never validates, every attempt refuses or rolls back, and the store is readable but unrepairable except by hand. This is the command that closes that loop: it fixes every instance it knows about across the store, then writes, so the file Check sees is already converged.

It repairs the ARCHIVE as well as the live file, because post-write validation covers both: a live-only repair would leave every mutation still refusing on account of the archive, which is the same dead end one file over.

Two invariants, both load-bearing:

  • It never writes a partially repaired file. The repaired records are re-checked in memory first, and any remaining error refuses the whole pass with nothing written. An unparseable line therefore always refuses — Check folds the parser's errors in — so a write can never silently drop a line this binary could not read.
  • It never touches `updated`. A repair asserts nothing about a task's content; stamping would falsify when the task last changed and, in the last-write-wins merge, hand the repairing device a win it did not earn.

func (*Store) SectionNamed

func (s *Store) SectionNamed(name string) (record.Record, bool)

SectionNamed is the record of the section matching `name`, resolved with capture's widening tiers: exact top-level, exact any-level, substring top-level, substring any-level, all case-insensitive. It lets a move destination reach a nested project sub-section by name, not just a top-level heading.

func (*Store) SetWorkRef

func (s *Store) SetWorkRef(id, workRef, worker, _ string) MutationResult

SetWorkRef records where the work lives, or clears it with an empty ref. One reference: setting overwrites. The owner (an empty worker) may always set it; a worker only while its own claim stands. It is not a status transition, so `at` is deliberately left alone.

The coalesce key is accepted and DELIBERATELY IGNORED, for the same reason it is on Undelegate: Ruby's `set_work_ref!` takes none, and merging a reference update into a neighbouring delegation write would make one undo revert both.

func (*Store) TaskRevision

func (s *Store) TaskRevision(id string) (string, bool)

TaskRevision is the opaque token a caller carries into a changeset. It is taken under the store lock, so it describes a task at one coherent moment rather than at whichever moment each read happened to land on.

func (*Store) Undelegate

func (s *Store) Undelegate(id, _ string) MutationResult

Undelegate clears the marker: an ordinary undelegate, or the revocation of a live claim. Revocation wins — afterwards the stale worker's release and work-ref calls fail their worker match. It is allowed whatever the marker's status and whatever the task's state, because clearing provenance from a closed task is an owner's prerogative; an undelegated task is no_change.

The coalesce key is accepted and DELIBERATELY IGNORED. Ruby's `undelegate_task!` takes none — only `delegate` and `release` compose a second write that has to share an undo step — so honouring one here would merge a revocation into whatever unrelated delegation write happened to precede it, and one undo would then revert two decisions. The parameter stays in the signature because the application layer's optional interface declares it.

func (*Store) UnsupportedSchemaError

func (s *Store) UnsupportedSchemaError() string

UnsupportedSchemaError is the diagnostic for a store this build cannot read, or "" when it can. Every refusal leads with it, because the version found and the version expected are the only part an operator can act on.

Jump to

Keyboard shortcuts

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