tracker

package
v0.159.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 33 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 tracker owns the repository-local issue and memory JSONL truth.

Index

Constants

View Source
const (
	DoctorHandoffExpired = "handoff-expired"
	DoctorNoteStale      = "note-stale"
	DoctorPathMissing    = "path-missing"
	DoctorCommitMissing  = "commit-missing"
	DoctorSummaryMissing = "summary-missing"
	DoctorDuplicate      = "duplicate"
	// DoctorFlagged: an agent reported the memory out of date (`memory flag`).
	DoctorFlagged = "flagged"
)

Doctor finding slugs (design §2.5). They are stable: `prime.doctor.suppress` and a memory's `doctor_ignore` refer to them, and the steward reads them from `memory doctor --json`.

View Source
const (
	MemoryKindRule    = "rule"
	MemoryKindNote    = "note"
	MemoryKindHandoff = "handoff"
)

Memory kinds (design 2026-10-09-prime-memory-quality-design.md §2.1).

View Source
const (
	ScopeConfidenceHigh   = "high"
	ScopeConfidenceMedium = "medium"
)

Confidence of a `memory scope` suggestion (gofer-opv5): `source` and key / tag evidence are high (they name the subproject), a mention in the text is medium.

View Source
const (
	MergeKindIssues        = "issues"
	MergeKindMemories      = "memories"
	MergeKindMemoryArchive = "memories-archive"
)

Tracker JSONL kinds the merge understands.

View Source
const (
	// MergeDriverName is the driver name in .gitattributes and git config.
	MergeDriverName = "gofer-tracker"
	// MergeDriverDesc is merge.<name>.name (shown by git).
	MergeDriverDesc = "gofer tracker JSONL merge (by record id)"
	// MergeDriverCommand is merge.<name>.driver. It calls `gofer` from PATH: the
	// git config is shared by every worktree and often by a host and a container
	// mounting the same checkout, so an absolute binary path would be wrong for
	// one of them.
	//
	// The driver exits 0 (merged) or 1 (real conflict, markers written). Any other
	// failure — no gofer on this side's PATH, a gofer too old to know the subcommand —
	// would leave git with an unmarked "conflict" on ours as-is, worse than having no
	// driver; MergeDriverFallback then runs git's own text merge instead.
	MergeDriverCommand = "gofer repo merge-driver %O %A %B %P" + MergeDriverFallback
	// MergeDriverFallback follows the driver invocation in MergeDriverCommand (git
	// runs the driver through the shell, Git for Windows included).
	MergeDriverFallback = "; rc=$?; [ $rc -le 1 ] && exit $rc; git merge-file %A %O %B"
	// MergeAttributesLine routes the tracker files to the driver. The pattern is
	// relative to the .gitattributes beside .gofer/ and does not reach .local/.
	MergeAttributesLine = ".gofer/tracker/*.jsonl merge=" + MergeDriverName
)

Git merge driver wiring for the tracker JSONL files (gofer-7rqx).

View Source
const (
	BeginBlock = beginBlock
	EndBlock   = endBlock
)

BeginBlock / EndBlock delimit the gofer-managed block in AGENTS.md / CLAUDE.md.

View Source
const ArchiveTombstonePrefix = "archive:"

ArchiveTombstonePrefix marks a server tombstone that means "archive", not "delete": the server writes it when a person adopts the steward's archive suggestion (design prime-memory-quality §2.6, P4). DeletedBy is "archive:<actor>" and the tombstone body carries {"archive_reason": "..."}. A clone that syncs it moves its local copy into memories-archive.jsonl instead of dropping it; older clients just delete it.

View Source
const DefaultCommitPolicy = "local-commit"

DefaultCommitPolicy is the commit_policy of a new tracker.

View Source
const DefaultHandoffTTL = 14 * 24 * time.Hour

DefaultHandoffTTL is the lifetime of a handoff memory without an explicit --ttl.

View Source
const DepDiscoveredFrom = "discovered-from"

DepDiscoveredFrom links an issue to the one it was found while working on (`issue create --from <id>`).

View Source
const (
	// FocusBudget is the byte budget of the whole section (heading included).
	FocusBudget = primeFocusBudget
)

「当前重点」 section of prime (design §2.4). Everything is fetched fresh and best effort: a part that fails or runs out of time is simply left out, never an error.

View Source
const GlobalDirName = "tracker"

GlobalDirName is the directory of the global memory tracker under the gofer config directory: <config-dir>/tracker (docs/design/2026-10-12-local-global-memory-design.md).

View Source
const GlobalTrackerID = "global"

GlobalTrackerID is the reserved tracker that holds the global memories: on the server as a tracker_memories set, on each machine as <config-dir>/tracker. It can never collide with a repository's id ("tracker-<hex>" or a legacy UUID).

View Source
const MemoryFlagHint = "" /* 180-byte string literal not displayed */

MemoryFlagHint is the one-line prompt hint (prime rules area, dispatched-job rules) that tells an agent to flag a stale memory rather than bypass it.

View Source
const MemoryFlagsMax = 5

MemoryFlagsMax caps the flags a memory keeps (newest first).

View Source
const MemorySummaryMaxRunes = 80

MemorySummaryMaxRunes caps summaries (written and derived) shown in indexes.

View Source
const MemorySummaryRequiredRunes = 200

MemorySummaryRequiredRunes: rule / note content longer than this needs a summary.

View Source
const MemoryWriteHint = "" /* 190-byte string literal not displayed */

MemoryWriteHint is the writing guidance (design §2.8) shared by prime and the managed AGENTS block.

View Source
const PrimeMaxBytes = 8 << 10
View Source
const PrimeSelectionMaxKeywords = 64

PrimeSelectionMaxKeywords bounds a keyword list (a run-away flag or environment value must not turn into a 10k-term scan per memory).

View Source
const PrimeSelectionTextBytes = 2000

PrimeSelectionTextBytes is how much of the prompt the selection keeps: enough for the opening paragraph that names the goal, the subsystem and the files, without re-reading a whole task book (a rendered template can be tens of kilobytes).

View Source
const PrimeStaleMarker = "⚠ 可能过期"

PrimeStaleMarker is appended to flagged rule / note entries in prime.

View Source
const PrimeTakeoverHint = "" /* 167-byte string literal not displayed */

PrimeTakeoverHint is the last line of the local prime: the entry point for taking over an issue or a plan (design 2026-10-10 §一 「prime 配合」).

View Source
const TrackerPrimeHint = "任务:`gofer issue ready|show <id>|update <id> --claim|comment <id> \"…\"|close <id>`;记忆:`gofer memory ls <关键字>`(搜 key+摘要+内容)/ `show <key>`(全文)/ `set <key> \"…\" --summary \"一句话\"`;tracker 改动用 `gofer repo status --changed` 看,不要 diff `.gofer/tracker/*.jsonl`。\n" + MemoryWriteHint

TrackerPrimeHint is the one-line command memory aid in the fixed header: how to pick up work and how to recall memories that the summaries below only abbreviate.

View Source
const WorkPrimeHint = "" /* 144-byte string literal not displayed */

WorkPrimeHint is the one-line SessionStart hint about work-item reports: a session that is asked to report its work item knows the command. It lives in the fixed header so it always fits the byte budget, but only when PrimeOptions.WorkHint is set (work items are an opt-in feature; most repositories never see a report request).

Variables

View Source
var ClearableFields = []string{"description", "design", "acceptance", "assignee", "owner", "parent", "close-reason"}

ClearableFields are the names `issue update --clear` accepts.

View Source
var DepTypes = []string{"blocks", "related", "relates-to", DepDiscoveredFrom, "supersedes"}

DepTypes are the dependency kinds `issue dep add --type` accepts. Only "blocks" gates Ready; the rest are informational links (bd vocabulary). parent-child is deliberately absent: the parent field owns that relation.

DoctorSlugs lists every finding slug in report order.

View Source
var ErrGlobalNotSynced = errors.New("the global memory copy has never synced")

ErrGlobalNotSynced is returned for a global copy that never synced and holds nothing yet: a reader should ask the server instead of showing nothing.

View Source
var SortFields = []string{"id", "priority", "created", "updated"}

SortFields are the names IssueFilter.Sort accepts.

Functions

func AgeText

func AgeText(value string, now time.Time) string

AgeText renders the age of a timestamp as 今天 / N 天前 ("" when unparsable).

func AppendPrimeSections

func AppendPrimeSections(base string, sections ...string) string

AppendPrimeSections appends optional server-backed sections within the same bounded prime budget. Each section must include its heading and body.

func AppendScopedPrimeSections added in v0.159.0

func AppendScopedPrimeSections(base string, opts ScopedPrimeOptions, sections ...ScopedPrimeSection) string

AppendScopedPrimeSections appends server-scoped memory sections to a job's tracker-prime body (base) within the shared PrimeMaxBytes total. The sections keep the order they are given in, each one is budgeted on its own out of what is left of the total (the caller's ScopedPrimeOptions.Budget is ignored) and marked with ScopedPrimeSectionCutMark when entries were dropped. A section with no room left is marked cut as well instead of being squeezed out silently.

func ArchivedMemoryListLine

func ArchivedMemoryListLine(a ArchivedMemory, now time.Time) string

ArchivedMemoryListLine is one `memory ls --archived` row.

func AtomicWriteFile

func AtomicWriteFile(path string, data []byte) error

AtomicWriteFile replaces path with data without ever leaving a half-written file.

func ClaudeImportsAgents

func ClaudeImportsAgents(root string) bool

ClaudeImportsAgents is claudeImportsAgents for other packages (the bd migration).

func CommitPolicyText

func CommitPolicyText(policy string) (string, error)

func DisplayMemorySummary

func DisplayMemorySummary(meta MemoryMeta, content string) string

DisplayMemorySummary is the stored summary, else the derived one.

func EffectiveMemoryKind

func EffectiveMemoryKind(meta MemoryMeta, tags []string) string

EffectiveMemoryKind is the kind used for display: the stored kind, else the legacy `prime` tag as rule, else note.

func ExecGit

func ExecGit(ctx context.Context, dir string, args ...string) (string, error)

ExecGit is the real GitRunner; ctx bounds the child process.

func FallbackMemorySummary

func FallbackMemorySummary(content string) string

FallbackMemorySummary derives a summary for a memory without one: the first sentence of the first line that is not empty, not a heading (`#`, `【…】`) and not a bare link, capped at MemorySummaryMaxRunes.

func FormatDoctorReport

func FormatDoctorReport(r DoctorReport) string

FormatDoctorReport is the human `memory doctor` output.

func GenerateIssueID

func GenerateIssueID(items []Issue, prefix, parent string) (string, error)

func ImportTransfer

func ImportTransfer(sourceDir, targetRoot string, bundle TransferBundle) (published bool, resultErr error)

ImportTransfer stages an entire tracker under targetRoot/.gofer, verifies it, then publishes its directory. Source freshness is checked both before and immediately before publish. It never removes source records or syncs.

func IsArchiveTombstone

func IsArchiveTombstone(deletedBy string) bool

IsArchiveTombstone reports whether a tombstone's deleted_by marks an archive.

func IsLegacyTrackerID

func IsLegacyTrackerID(id string) bool

IsLegacyTrackerID reports whether id has the old UUID form.

func IssueTouchedAt

func IssueTouchedAt(item Issue) string

IssueTouchedAt is the last activity time of an issue: updated, else started, else created.

func ManagedBlock

func ManagedBlock() string

ManagedBlock returns the managed block for the default commit policy.

func ManagedBlockFor added in v0.138.0

func ManagedBlockFor(policy string) (string, error)

ManagedBlockFor renders the managed block for a commit_policy value; its commit line is CommitPolicyText, so the block and prime always agree.

func MatchMemoryPath

func MatchMemoryPath(pattern, rel string) bool

MatchMemoryPath reports whether the slash-separated repository-relative path rel (a cwd or a touched file) falls under a `when.paths` glob. `**` matches any number of segments, `*` / `?` stay inside one segment, and a pattern without glob characters matches the directory itself and everything below it. The repository root ("" / ".") matches nothing but `**`.

func MemoryCreatedAt

func MemoryCreatedAt(meta MemoryMeta, updatedAt string) string

MemoryCreatedAt falls back to updated_at for memories written before created_at existed.

func MemoryDetail

func MemoryDetail(m Memory, now time.Time) string

MemoryDetail renders every field of a memory for `memory show`, then the content.

func MemoryExpired

func MemoryExpired(meta MemoryMeta, tags []string, updatedAt string, now time.Time) bool

MemoryExpired reports whether a handoff memory is past its expiry at now.

func MemoryExpiresAt

func MemoryExpiresAt(meta MemoryMeta, tags []string, updatedAt string) (time.Time, bool)

MemoryExpiresAt is the handoff expiry: the stored expires_at, else updated_at + DefaultHandoffTTL. Non-handoff memories never expire (zero time, false).

func MemoryFlagPrefix

func MemoryFlagPrefix(meta MemoryMeta) string

MemoryFlagPrefix is 「⚠ 待复核(<latest reason>)」 for a flagged memory, else "".

func MemoryForAgent

func MemoryForAgent(tags []string, agentName string) bool

MemoryForAgent filters `agent:<name>` tagged memories: untagged memories are for every agent, tagged ones only for the named agents.

func MemoryIndexGroup

func MemoryIndexGroup(tags []string) string

MemoryIndexGroup is the index group of a memory: its first tag (ignoring the legacy `prime` and `agent:*` tags), else 其他.

func MemoryListLine

func MemoryListLine(m Memory, now time.Time) string

MemoryListLine is one `memory ls` row: key [kind] · age · summary, with the 已过期 marker for an expired handoff and 久未更新 for a 90-day-old note.

func MemoryMatchesCommand

func MemoryMatchesCommand(meta MemoryMeta, command string) (string, bool)

MemoryMatchesCommand returns the first when.commands prefix of command (P5).

func MemoryMatchesFilter

func MemoryMatchesFilter(item Memory, filter MemoryFilter) bool

MemoryMatchesFilter is the shared local / scoped `memory ls` predicate.

func MemoryMatchesKeyword

func MemoryMatchesKeyword(meta MemoryMeta, text string) (string, bool)

MemoryMatchesKeyword returns the first when.keywords entry contained in text (case-insensitive), for the P1b UserPromptSubmit injection.

func MemoryMatchesPath

func MemoryMatchesPath(meta MemoryMeta, rel string) bool

MemoryMatchesPath reports whether any when.paths glob matches rel.

func MemoryMatchesSelection added in v0.158.0

func MemoryMatchesSelection(m Memory, sel PrimeSelection) bool

MemoryMatchesSelection reports whether a memory is relevant to the task behind sel:

  • one of the memory's own `when.keywords` triggers appears in the task text, or
  • one of the dispatcher's explicit keywords is carried by the memory — in its key, one of its tags, its summary, or one of its own `when.keywords`.

Everything is compared case-insensitively. A memory with no metadata at all can be matched by the second rule (its key or summary), which is what makes a plain memory about a subsystem reachable by naming that subsystem.

func MemoryStale

func MemoryStale(meta MemoryMeta, tags []string, updatedAt string, now time.Time) bool

MemoryStale reports a note not updated for 90 days (§2.1 「久未更新」).

func MergeKindForPath added in v0.135.0

func MergeKindForPath(p string) string

MergeKindForPath maps a tracker file name to its merge kind ("" = unknown).

func MergeServerMemories

func MergeServerMemories(base, local, remote []ServerMemory) ([]ServerMemory, SyncReport)

MergeServerMemories applies the fixed deletion policy. The returned slice is the server mirror representation; deleted entries are retained as tombstones while the repository projection may omit them.

func NewTrackerID

func NewTrackerID() string

NewTrackerID returns a fresh short tracker id: "tracker-" + 10 lowercase hex chars.

func Now

func Now() string

func ParseMemoryTTL

func ParseMemoryTTL(value string) (time.Duration, error)

ParseMemoryTTL accepts Nd / Nw plus Go durations (36h, 90m).

func ParseTags

func ParseTags(value string) []string

func RenderFocus

func RenderFocus(in FocusInput) string

RenderFocus renders the 「当前重点」 section within the budget, dropping whole lines in the order env → 未收尾 → 刚解锁 → 在做 (last line of a category first).

func RenderScopedPrimeSection

func RenderScopedPrimeSection(title string, items []Memory, opts ScopedPrimeOptions) string

RenderScopedPrimeSection applies the local memory rules to scoped memories in one budgeted section: full rules (and `agent:<name>` memories) first, then the grouped index with the newest unexpired handoffs.

func RenderScopedPrimeSectionTruncated added in v0.159.0

func RenderScopedPrimeSectionTruncated(title string, items []Memory, opts ScopedPrimeOptions) (string, bool)

RenderScopedPrimeSectionTruncated is RenderScopedPrimeSection plus whether the budget left entries out. The session prime only shows the 「另有 N 条」 note; a dispatched job's tracker-prime says so explicitly (ScopedPrimeSectionCutMark).

func RepoBoundary added in v0.157.0

func RepoBoundary(start string) (string, bool)

RepoBoundary returns the top directory of the git repository start lives in: the nearest ancestor (start included) holding a `.git` entry — a directory in a normal checkout, a file in a linked worktree or a submodule. ok=false when no ancestor is a repository.

func RepoCwd

func RepoCwd(repoPath string, roots []string) (string, bool)

RepoCwd turns the repository path a sync reported (an absolute path on the machine that ran `repo sync`) into a cwd relative to one of the project's root views. roots are tried in order (the runner's own view first, then the other views of the project). The result is slash separated, "." for the project root itself. ok is false when the repository lies in none of the roots.

func RunMergeDriver added in v0.135.0

func RunMergeDriver(base, ours, theirs, name string, stderr io.Writer) int

RunMergeDriver is `gofer repo merge-driver <base> <ours> <theirs> [<path>]`: git's %O %A %B %P. The result replaces the ours file. It returns the exit code git expects: 0 = merged, non-zero = conflict left for a person.

A tracker file merges by record id (MergeJSONL); the decisions between two real changes are printed to stderr. A file the merge cannot read safely (unknown name, conflict markers, a field from a newer gofer) falls back to git's own text merge (`git merge-file`), so the outcome is exactly what git would have done without the driver: conflict markers and a non-zero exit when it collides.

func ScopeConfidenceLabel added in v0.159.0

func ScopeConfidenceLabel(confidence string) string

ScopeConfidenceLabel is the label of a confidence level shown by `memory scope`.

func ScopeConfidenceRank added in v0.159.0

func ScopeConfidenceRank(confidence string) int

ScopeConfidenceRank orders the confidence levels (higher = stronger evidence).

func ScopedPrimeSectionCutMark added in v0.159.0

func ScopedPrimeSectionCutMark(title string) string

ScopedPrimeSectionCutMark marks a section the byte budget had to cut, so the job knows the list it was given is not the whole story.

func ShortTrackerID

func ShortTrackerID(legacy string) string

ShortTrackerID derives the short id of a legacy tracker id. It is deterministic so every clone of a repository (which all carry the same committed legacy UUID) derives the same new id.

DEPRECATED(v0.126): remove in v0.129 (legacy UUID tracker_id migration).

func SniffMergeKind added in v0.135.0

func SniffMergeKind(data ...[]byte) string

SniffMergeKind guesses the kind from the first record found in data (used when git does not pass the path). "" when every input is empty or unrecognized.

func SplitPrimeKeywords added in v0.158.0

func SplitPrimeKeywords(value string) []string

SplitPrimeKeywords parses a comma-separated keyword list (the CLI flag, the GOFER_PRIME_KEYWORDS environment variable). An item may carry its own whitespace (`rux, prime` is two keywords); empty items are dropped.

func SyncContext

func SyncContext(endpoint string) (context.Context, context.CancelFunc)

func ThreeWayMerge

func ThreeWayMerge(base, local, remote SyncSnapshot) (SyncSnapshot, SyncReport)

func ValidDoctorSlug

func ValidDoctorSlug(slug string) bool

ValidDoctorSlug reports whether slug is a known finding slug.

func ValidMemoryKind

func ValidMemoryKind(kind string) bool

ValidMemoryKind reports whether kind is one of rule|note|handoff.

func ValidStatus

func ValidStatus(status string) bool

func ValidateMemoryForWrite

func ValidateMemoryForWrite(item Memory) error

ValidateMemoryForWrite applies the CLI write rule (§2.2): rule / note content longer than MemorySummaryRequiredRunes needs a summary. The error proposes the derived first sentence as a candidate.

func WriteTransferBundle

func WriteTransferBundle(sourceDir, path string, bundle TransferBundle) error

Types

type ArchivedMemory

type ArchivedMemory struct {
	Memory
	ArchivedAt    string `json:"archived_at"`
	ArchivedBy    string `json:"archived_by,omitempty"`
	ArchiveReason string `json:"archive_reason,omitempty"`
}

ArchivedMemory is a memory moved out of prime: every field is kept (summary, kind, when, source …) plus when, by whom and why it was archived.

type BriefConfig added in v0.138.0

type BriefConfig struct {
	// Verify lists the repository's own verification commands. A rule applies when
	// one of its paths globs (MatchMemoryPath syntax) matches a code-entry file of
	// the issue; a rule without paths always applies. Unset = the generic fallback
	// (a plain `go test` hint when the repository has a go.mod).
	Verify []BriefVerifyRule `yaml:"verify,omitempty" json:"verify,omitempty"`
}

BriefConfig configures `gofer issue brief` for this repository.

type BriefVerifyRule added in v0.138.0

type BriefVerifyRule struct {
	Paths []string `yaml:"paths,omitempty" json:"paths,omitempty"`
	Cmd   string   `yaml:"cmd" json:"cmd"`
}

BriefVerifyRule is one `brief.verify` entry. Cmd may carry {dirs} (the matched files' directories as ./dir, sorted) and {files} (the matched files).

type Change

type Change struct {
	// Kind is "issue" or "memory".
	Kind string `json:"kind"`
	// Op is "added", "changed" or "removed".
	Op string `json:"op"`
	// ID is the issue id or the memory key.
	ID        string   `json:"id"`
	Title     string   `json:"title,omitempty"`
	OldStatus string   `json:"old_status,omitempty"`
	NewStatus string   `json:"new_status,omitempty"`
	Fields    []string `json:"fields,omitempty"`
}

Change is one tracker entry that differs from git HEAD.

type ChangeReport

type ChangeReport struct {
	Tracker string   `json:"tracker"`
	InGit   bool     `json:"in_git"`
	Added   int      `json:"added"`
	Changed int      `json:"changed"`
	Removed int      `json:"removed"`
	Changes []Change `json:"changes"`
}

ChangeReport lists tracker changes of the working tree relative to HEAD.

func (ChangeReport) Lines

func (r ChangeReport) Lines() []string

Lines renders the report as one line per change plus a summary line.

type Comment

type Comment struct {
	At   string `json:"at"`
	By   string `json:"by"`
	Text string `json:"text"`
}

type Config

type Config struct {
	Prefix       string      `yaml:"prefix" json:"prefix"`
	TrackerID    string      `yaml:"tracker_id" json:"tracker_id"`
	ProjectKey   string      `yaml:"project_key,omitempty" json:"project_key,omitempty"`
	CommitPolicy string      `yaml:"commit_policy" json:"commit_policy"`
	AutoSync     bool        `yaml:"auto_sync" json:"auto_sync"`
	Prime        PrimeConfig `yaml:"prime,omitempty" json:"prime,omitempty"`
	Brief        BriefConfig `yaml:"brief,omitempty" json:"brief,omitempty"`
}

type Dep

type Dep struct {
	ID   string `json:"id"`
	Type string `json:"type"`
}

type DoctorEntry

type DoctorEntry struct {
	Key       string          `json:"key"`
	Kind      string          `json:"kind"`
	Summary   string          `json:"summary,omitempty"`
	UpdatedAt string          `json:"updated_at,omitempty"`
	Findings  []DoctorFinding `json:"findings"`
}

DoctorEntry lists the findings of one memory.

type DoctorFinding

type DoctorFinding struct {
	Slug   string `json:"slug"`
	Detail string `json:"detail,omitempty"`
}

DoctorFinding is one problem of one memory.

type DoctorOptions

type DoctorOptions struct {
	Now time.Time
	// Roots are the directories relative paths are resolved against (repository
	// root first, then workspace roots). Empty disables path-missing.
	Roots []string
	// CommitsMissing returns the hashes git does not know; nil disables
	// commit-missing.
	CommitsMissing func(hashes []string) map[string]bool
	// Suppress silences slugs repository-wide (prime.doctor.suppress).
	Suppress []string
}

DoctorOptions are the inputs of DiagnoseMemories.

type DoctorReport

type DoctorReport struct {
	GeneratedAt string        `json:"generated_at"`
	Checked     int           `json:"checked"`
	Flagged     int           `json:"flagged"`
	Suppressed  int           `json:"suppressed"`
	Memories    []DoctorEntry `json:"memories"`
}

DoctorReport is `gofer memory doctor --json`. Memories without findings are left out; Suppressed counts findings silenced by config or doctor_ignore.

func DiagnoseMemories

func DiagnoseMemories(items []Memory, opts DoctorOptions) DoctorReport

DiagnoseMemories runs every check and returns the unsuppressed findings.

type FocusGit

type FocusGit struct {
	Branch         string
	Head           string
	Changed        int  // tracked files with staged or unstaged changes
	ChangedKnown   bool // false when the full worktree scan did not finish in time
	TrackerChanged int  // files under the tracker directory with changes
	HasUpstream    bool
	Ahead          int
	HasTag         bool
	Tag            string
	SinceTag       int
}

FocusGit is the repository state; HasTag / HasUpstream gate their parts.

func CollectFocusGit

func CollectFocusGit(ctx context.Context, run GitRunner, root, trackerDir string) (*FocusGit, error)

CollectFocusGit reads the repository line from cheap commands — branch and HEAD (`rev-parse`), commits ahead of the upstream (`rev-list --count`), the latest tag (`describe`) and the tracker directory's own changes (a path-limited `status`) — in parallel, plus a full worktree scan (`status --porcelain=v2`, untracked files ignored) that is dropped when it misses focusStatusBudget. root is the repository root of the tracker ("" = unknown, git runs in trackerDir). An error means the directory is not usable as a git repository.

type FocusInput

type FocusInput struct {
	Now      time.Time
	Issues   []Issue
	Memories []Memory
	Plans    []FocusPlan
	Git      *FocusGit
	Server   *FocusServer
	Budget   int // 0 = FocusBudget
	// NoEnv drops the environment lines (仓库 / 服务), prime.focus_env=false.
	NoEnv bool
	// ShowTag adds the latest tag to the repository line, prime.focus_tag=true.
	ShowTag bool
}

FocusInput is everything RenderFocus needs; nil / empty parts are omitted.

type FocusPlan

type FocusPlan struct {
	ID       string
	Title    string
	Done     int // done + skipped todos
	Total    int
	NextTodo string // title of the first unfinished todo ("" = unknown / none)
}

FocusPlan is an open plan of this project with its progress and next todo.

type FocusRemote

type FocusRemote struct {
	Server *FocusServer
	Plans  []FocusPlan
}

FocusRemote is what the command layer fetched from the server; either part may be nil / empty when unavailable.

type FocusServer

type FocusServer struct {
	Version string
	Workers []FocusWorker
	// UTCOffsetSec is the server's UTC offset (nil = unknown): the section header
	// shows the time in the operator's zone, not the container's.
	UTCOffsetSec *int
}

FocusServer is the server version and the workers that serve this project (the caller leaves out every other worker).

type FocusSources

type FocusSources struct {
	Git    GitRunner
	Remote func(ctx context.Context) (FocusRemote, error)
}

FocusSources are the slow inputs of BuildFocus. Nil members are skipped.

type FocusWorker

type FocusWorker struct {
	Name    string
	Version string
	Online  bool
}

FocusWorker is one worker runner as the server sees it.

type GitRunner

type GitRunner func(ctx context.Context, dir string, args ...string) (string, error)

GitRunner runs `git -C dir args...` and returns its stdout (tests use fakes).

type InitOptions added in v0.138.0

type InitOptions struct {
	// Prefix is the issue id prefix ("" = the repository directory name).
	Prefix string
	// NoAgentsMD skips the managed block in AGENTS.md / CLAUDE.md.
	NoAgentsMD bool
	// CommitPolicy sets commit_policy (local-commit | ask | none); "" keeps the
	// current value (a new tracker gets DefaultCommitPolicy).
	CommitPolicy string
}

InitOptions are the inputs of InitWith.

type Issue

type Issue struct {
	ID                 string      `json:"id"`
	Title              string      `json:"title"`
	Type               string      `json:"type"`
	Status             string      `json:"status"`
	Priority           int         `json:"priority"`
	Description        string      `json:"description,omitempty"`
	Design             string      `json:"design,omitempty"`
	AcceptanceCriteria string      `json:"acceptance_criteria,omitempty"`
	Notes              []NoteEntry `json:"notes,omitempty"`
	Assignee           string      `json:"assignee,omitempty"`
	Owner              string      `json:"owner,omitempty"`
	Tags               []string    `json:"tags,omitempty"`
	Parent             string      `json:"parent,omitempty"`
	Deps               []Dep       `json:"deps,omitempty"`
	Comments           []Comment   `json:"comments,omitempty"`
	CreatedAt          string      `json:"created_at"`
	CreatedBy          string      `json:"created_by,omitempty"`
	UpdatedAt          string      `json:"updated_at,omitempty"`
	StartedAt          string      `json:"started_at,omitempty"`
	ClosedAt           string      `json:"closed_at,omitempty"`
	CloseReason        string      `json:"close_reason,omitempty"`
	// ExternalRef / SpecID carry bd's external_ref and spec_id through a migration.
	ExternalRef string `json:"external_ref,omitempty"`
	SpecID      string `json:"spec_id,omitempty"`
}

Field order is the JSONL wire order. Keep additions at the end to minimize diffs.

func LinkIssueToJob

func LinkIssueToJob(issue Issue, event JobIssueEvent) Issue

type IssueFilter

type IssueFilter struct {
	Status   string
	Type     string
	Tags     []string
	Query    string
	All      bool
	Assignee string
	Priority *int
	Sort     string
	Reverse  bool
	Limit    int
	// StaleDays > 0 keeps issues whose last touch (updated / started / created)
	// is at least that many days old (`issue ls --stale`, bd `stale`). Without a
	// Status it covers open and in_progress; with the default id sort the result
	// is oldest first.
	StaleDays int
	// Now is the reference time of StaleDays (zero = time.Now()).
	Now time.Time
}

IssueFilter narrows ListIssues. Sort is one of SortFields (default id); Reverse flips it; Limit > 0 truncates after sorting.

type IssuePatch

type IssuePatch struct {
	Title       string
	Status      string
	Claim       bool
	AppendNotes string
	Actor       string
	Tags        []string
	Untag       []string
	Type        string
	Priority    *int
	Description *string
	Design      *string
	Acceptance  *string
	Assignee    *string
	Owner       *string
	Parent      *string
	Clear       []string
	// KeepAssignee keeps the assignee when Status moves the issue back to open
	// (by default a re-opened issue is unclaimed, design §2.7).
	KeepAssignee bool
}

IssuePatch lists the fields UpdateIssue may change. Scalar pointers distinguish "leave alone" (nil) from "set"; Clear empties the named fields (ClearableFields).

type JobIssueEvent

type JobIssueEvent struct {
	JobID, Phase, Status, At string
	Commits, Uncommitted     []string
}

type Lock

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

func (*Lock) Release

func (l *Lock) Release() error

type Memory

type Memory struct {
	Key       string   `json:"key"`
	Content   string   `json:"content"`
	Tags      []string `json:"tags,omitempty"`
	UpdatedAt string   `json:"updated_at"`
	By        string   `json:"by"`
	// MemoryMeta (kind / summary / when / expires_at / source / created_at) is
	// flattened after the original fields, all omitempty (memory_meta.go).
	MemoryMeta
}

func ApplyMemoryPatch

func ApplyMemoryPatch(existing *Memory, key string, patch MemoryPatch, now time.Time) (Memory, error)

ApplyMemoryPatch merges patch into existing (nil for a new memory) at now. It checks the kind and TTL; the summary requirement is ValidateMemoryForWrite.

func (Memory) EffectiveKind

func (m Memory) EffectiveKind() string

EffectiveKind returns the effective kind of the memory.

type MemoryFilter

type MemoryFilter struct {
	Keyword string
	Tags    []string
	Kind    string
}

MemoryFilter narrows `memory ls`: keyword searches key, summary and content (case-insensitive); Kind compares the effective kind (legacy `prime` = rule).

type MemoryFlag

type MemoryFlag struct {
	At     string `json:"at"`
	By     string `json:"by,omitempty"`
	Job    string `json:"job,omitempty"`
	Reason string `json:"reason"`
}

MemoryFlag is one "this memory looks wrong" report.

func AddMemoryFlag

func AddMemoryFlag(flags []MemoryFlag, flag MemoryFlag) []MemoryFlag

AddMemoryFlag puts flag first and keeps at most MemoryFlagsMax flags.

func NewMemoryFlag

func NewMemoryFlag(reason, by, jobID string, now time.Time) (MemoryFlag, error)

NewMemoryFlag builds a flag stamped at now; the reason is required.

type MemoryMeta

type MemoryMeta struct {
	Kind      string      `json:"kind,omitempty"`
	Summary   string      `json:"summary,omitempty"`
	When      *MemoryWhen `json:"when,omitempty"`
	ExpiresAt string      `json:"expires_at,omitempty"`
	// Source is a free-form origin reference: issue:<id>, plan:<id>, job:<id>, session:<id>.
	Source    string `json:"source,omitempty"`
	CreatedAt string `json:"created_at,omitempty"`
	// DoctorIgnore lists `memory doctor` finding slugs silenced for this memory
	// (known false positives, e.g. a rule that names a removed path on purpose).
	DoctorIgnore []string `json:"doctor_ignore,omitempty"`
	// Flags are agents' "this no longer matches" reports, newest first, at most
	// MemoryFlagsMax (memory_flag.go). A content change clears them.
	Flags []MemoryFlag `json:"flags,omitempty"`
}

MemoryMeta is the shared optional part of local, synced and scoped (server global / project) memories. It is embedded so the JSON stays flat; every field is omitempty, so old bodies round-trip unchanged.

type MemoryPatch

type MemoryPatch struct {
	Content      string
	Tags         []string // nil keeps the stored tags
	Kind         *string
	Summary      *string
	Source       *string
	WhenKeywords *[]string
	WhenPaths    *[]string
	WhenCommands *[]string
	// TTL sets expires_at = now + TTL (handoff only); ExpiresAt sets it directly.
	TTL       *time.Duration
	ExpiresAt *string
	// DoctorIgnore replaces the silenced doctor slugs (nil keeps them).
	DoctorIgnore *[]string
	// DefaultSource fills source when neither the patch nor the stored memory has
	// one (the CLI passes job:<id> / session:<id> from its environment).
	DefaultSource string
	By            string
}

MemoryPatch is one `memory set` write. Nil fields keep the stored value; a non-nil empty string / slice clears it. Content is always replaced.

type MemoryWhen

type MemoryWhen struct {
	Keywords []string `json:"keywords,omitempty"`
	Paths    []string `json:"paths,omitempty"`
	Commands []string `json:"commands,omitempty"`
}

MemoryWhen lists the scenario triggers of a memory (§2.9). P1 stores them and uses Paths for the cwd ordering in prime; the hook injection (P1b) matches Keywords against prompts and Commands (P5) against tool calls.

type MergeConflict added in v0.135.0

type MergeConflict struct {
	// Kind is "issue", "memory" or "archived memory".
	Kind string `json:"kind"`
	ID   string `json:"id"`
	// Field is the issue field (or "status" for the status / assignee / started /
	// closed group), "record" for a whole memory, or "deleted" for delete vs change.
	Field string `json:"field"`
	// Took is "ours" or "theirs".
	Took string `json:"took"`
}

MergeConflict is one decision the merge had to make between two real changes. The merge still succeeds; the driver prints these so a person can check them.

func MergeJSONL added in v0.135.0

func MergeJSONL(kind string, base, ours, theirs []byte) ([]byte, []MergeConflict, error)

MergeJSONL merges the base / ours / theirs contents of one tracker file of the given kind. An error means some input could not be read safely.

func (MergeConflict) String added in v0.135.0

func (c MergeConflict) String() string

type MergeDriverSetup added in v0.135.0

type MergeDriverSetup struct {
	// Attributes is the .gitattributes path; AttributesAdded is true when the
	// driver line was appended (the file must then be committed).
	Attributes      string `json:"attributes,omitempty"`
	AttributesAdded bool   `json:"attributes_added"`
	// ConfigChanged is true when merge.gofer-tracker.* was (re)written in the
	// clone's git config (shared by all of its worktrees).
	ConfigChanged bool `json:"config_changed"`
	// Skipped explains why nothing was installed ("" = installed).
	Skipped string `json:"skipped,omitempty"`
}

MergeDriverSetup reports what InstallMergeDriver did.

func InstallMergeDriver added in v0.135.0

func InstallMergeDriver(ctx context.Context, run GitRunner, root string) (MergeDriverSetup, error)

InstallMergeDriver routes root's .gofer/tracker/*.jsonl to the gofer merge driver: the .gitattributes line beside .gofer/ and the merge.gofer-tracker entries in the clone's git config. Idempotent. A root outside a git work tree is skipped, not an error.

type NoteEntry

type NoteEntry struct {
	At   string `json:"at"`
	By   string `json:"by"`
	Text string `json:"text"`
}

type PrimeConfig

type PrimeConfig struct {
	Issues             *bool `yaml:"issues,omitempty" json:"issues,omitempty"`
	Ready              *bool `yaml:"ready,omitempty" json:"ready,omitempty"`
	Memory             *bool `yaml:"memory,omitempty" json:"memory,omitempty"`
	ScopedMemory       *bool `yaml:"scoped_memory,omitempty" json:"scoped_memory,omitempty"`
	Handoff            *bool `yaml:"handoff,omitempty" json:"handoff,omitempty"`
	IssuesLimit        *int  `yaml:"issues_limit,omitempty" json:"issues_limit,omitempty"`
	ReadyLimit         *int  `yaml:"ready_limit,omitempty" json:"ready_limit,omitempty"`
	MemorySummaryLimit *int  `yaml:"memory_summary_limit,omitempty" json:"memory_summary_limit,omitempty"`
	// InjectOnPrompt: the hook injects memories whose when.keywords match a human
	// prompt (UserPromptSubmit, design 2026-10-09 §2.9). Default on.
	InjectOnPrompt *bool `yaml:"inject_on_prompt,omitempty" json:"inject_on_prompt,omitempty"`
	// InjectOnCommand: the PreToolUse hook injects memories whose when.commands
	// prefix the shell command the agent is about to run (§2.9, P5). Default on.
	InjectOnCommand *bool `yaml:"inject_on_command,omitempty" json:"inject_on_command,omitempty"`
	// Focus toggles the auto-generated 「当前重点」 section (design §2.4).
	Focus *bool `yaml:"focus,omitempty" json:"focus,omitempty"`
	// FocusEnv toggles the environment lines of 「当前重点」: the repository line and
	// the server line (server version and the workers serving this project). Default on.
	FocusEnv *bool `yaml:"focus_env,omitempty" json:"focus_env,omitempty"`
	// FocusTag adds 「最近 tag X(之后 N 个提交)」 to the repository line, for
	// repositories that release by tag. Default off.
	FocusTag *bool `yaml:"focus_tag,omitempty" json:"focus_tag,omitempty"`
	// Doctor configures `gofer memory doctor` (and the prime 「⚠ 可能过期」 marker).
	Doctor *PrimeDoctorConfig `yaml:"doctor,omitempty" json:"doctor,omitempty"`
}

PrimeConfig uses pointers so an absent section keeps every segment enabled and distinguishes an explicit zero limit from the default limit.

func (PrimeConfig) ActiveLimit

func (c PrimeConfig) ActiveLimit() int

func (PrimeConfig) DoctorSuppress

func (c PrimeConfig) DoctorSuppress() []string

DoctorSuppress is the repository-wide list of silenced doctor slugs.

func (PrimeConfig) FocusEnabled

func (c PrimeConfig) FocusEnabled() bool

func (PrimeConfig) FocusEnvEnabled added in v0.138.0

func (c PrimeConfig) FocusEnvEnabled() bool

func (PrimeConfig) FocusTagEnabled added in v0.138.0

func (c PrimeConfig) FocusTagEnabled() bool

FocusTagEnabled reports prime.focus_tag (default false).

func (PrimeConfig) HandoffEnabled

func (c PrimeConfig) HandoffEnabled() bool

func (PrimeConfig) InjectOnCommandEnabled

func (c PrimeConfig) InjectOnCommandEnabled() bool

InjectOnCommandEnabled reports prime.inject_on_command (default true).

func (PrimeConfig) InjectOnPromptEnabled

func (c PrimeConfig) InjectOnPromptEnabled() bool

InjectOnPromptEnabled reports prime.inject_on_prompt (default true).

func (PrimeConfig) IssuesEnabled

func (c PrimeConfig) IssuesEnabled() bool

func (PrimeConfig) MemoryEnabled

func (c PrimeConfig) MemoryEnabled() bool

func (PrimeConfig) ReadyCount

func (c PrimeConfig) ReadyCount() int

func (PrimeConfig) ReadyEnabled

func (c PrimeConfig) ReadyEnabled() bool

func (PrimeConfig) ScopedMemoryEnabled

func (c PrimeConfig) ScopedMemoryEnabled() bool

func (PrimeConfig) SummaryLimit

func (c PrimeConfig) SummaryLimit() int

type PrimeDoctorConfig

type PrimeDoctorConfig struct {
	Suppress []string `yaml:"suppress,omitempty" json:"suppress,omitempty"`
}

PrimeDoctorConfig silences doctor finding slugs repository-wide (`prime.doctor.suppress`).

type PrimeOptions

type PrimeOptions struct {
	// Cwd is the session working directory; when it lies inside the repository it
	// selects `when.paths` rules for full display and orders matching memories first.
	Cwd string
	Now time.Time
	// Focus is the 「当前重点」 section (heading included) rendered right after the
	// commit-policy header. P2 fills it (design §2.4); P1 always leaves it empty.
	Focus string
	// Unbounded disables the segment budgets (PrimeEstimate).
	Unbounded bool
	// WorkHint adds WorkPrimeHint to the fixed header. The command layer sets it
	// when the project has open work items or the session relay hooks are installed.
	WorkHint bool
	// Keywords is the task selection of a session opening (gofer-11tz): `gofer repo
	// prime --keywords` (or GOFER_PRIME_KEYWORDS) names the subsystems / languages /
	// modules this session is about, so the matching memories are injected in full and
	// ranked first in every index. Empty = the plain cwd-scoped prime.
	Keywords []string
}

PrimeOptions carries the per-call inputs of the prime layout.

type PrimeSelection added in v0.158.0

type PrimeSelection struct {
	Keywords []string
	Text     string
}

PrimeSelection is what a task brings to a prime: the keywords its dispatcher named, and the task's own words (the title plus the head of the prompt). Text is the string the memories' `when.keywords` are matched against; Keywords are matched against a memory's key / tags / summary as well.

func KeywordsOnly added in v0.158.0

func KeywordsOnly(keywords []string) PrimeSelection

KeywordsOnly is the selection of a bare keyword list — what `gofer repo prime --keywords` has at a session opening, where there is no job title or prompt yet.

func NewPrimeSelection added in v0.158.0

func NewPrimeSelection(keywords []string, title, prompt string) PrimeSelection

NewPrimeSelection builds a task's selection: the keywords (trimmed, deduplicated, empty entries dropped, at most PrimeSelectionMaxKeywords — they also join the matching text, so a memory whose `when.keywords` carries one of them matches even without a prompt), the title, and the head of the prompt.

type Relations

type Relations struct {
	Parent    string   `json:"parent,omitempty"`
	Children  []string `json:"children,omitempty"`
	BlockedBy []Dep    `json:"blocked_by,omitempty"` // this issue waits on these (blocking, not yet closed)
	Blocks    []string `json:"blocks,omitempty"`     // issues waiting on this one (blocking, still unfinished)
	DependsOn []Dep    `json:"depends_on,omitempty"` // every outgoing edge, any kind or state
	Linked    []Dep    `json:"linked,omitempty"`     // incoming non-blocking edges: ID is the issue that points here
}

Relations is the dependency neighbourhood of one issue.

type RepoStatus

type RepoStatus struct {
	Tracker        string         `json:"tracker"`
	Issues         map[string]int `json:"issues"`
	Memories       int            `json:"memories"`
	CommitPolicy   string         `json:"commit_policy"`
	ManagedBlock   bool           `json:"managed_block"`
	Hooks          string         `json:"hooks"`
	Sync           string         `json:"sync"`
	ProjectKey     string         `json:"project_key,omitempty"`
	LastSyncAt     string         `json:"last_sync_at,omitempty"`
	PendingSync    int            `json:"pending_sync"`
	SyncSummary    string         `json:"sync_summary,omitempty"`
	PrimeBytes     int            `json:"prime_bytes"`
	PrimeTruncated bool           `json:"prime_truncated"`
}

type ScopeSuggestion added in v0.159.0

type ScopeSuggestion struct {
	Key        string   `json:"key"`
	Paths      []string `json:"when_paths"`
	Basis      string   `json:"basis"`
	Confidence string   `json:"confidence"`
}

ScopeSuggestion is one proposed `when.paths` for a memory that has none: the subproject it looks like it belongs to, the evidence behind it, and how strong that evidence is. Nothing is written until ApplyMemoryScopePaths runs.

type ScopedPrimeOptions

type ScopedPrimeOptions struct {
	AgentName    string
	CwdRel       string
	CwdKnown     bool
	Now          time.Time
	SummaryLimit int
	Budget       int
	// LsHint is the `gofer memory ls …` command for the omitted-entries note.
	LsHint string
	// Selection is the task the section is rendered for (gofer-11tz): the scoped
	// memories it hits are ranked first and marked (相关), exactly like the local ones.
	Selection PrimeSelection
}

ScopedPrimeOptions renders a server global / project memory section.

type ScopedPrimeSection added in v0.159.0

type ScopedPrimeSection struct {
	Title string
	Items []Memory
	// LsHint is the `gofer memory ls …` command for the omitted-entries note.
	LsHint string
}

ScopedPrimeSection is one server-scoped memory section of a dispatched job's tracker-prime: the job's project memories, then the machine's global ones.

type ServerMemory

type ServerMemory struct {
	Memory
	Deleted   bool   `json:"deleted"`
	DeletedAt string `json:"deleted_at,omitempty"`
	DeletedBy string `json:"deleted_by,omitempty"`
	// ArchiveReason is set on an archive tombstone (DeletedBy starts with
	// ArchiveTombstonePrefix): sync moves the local copy into the archive file.
	ArchiveReason string `json:"archive_reason,omitempty"`
}

type Store

type Store struct{ Dir string }

func Discover

func Discover(start, explicit string) (*Store, error)

func DiscoverWithinRepo added in v0.157.0

func DiscoverWithinRepo(start, explicit string) (*Store, error)

DiscoverWithinRepo is Discover restricted to the git repository start belongs to: the upward search stops at (and includes) that repository's top directory, so a nested checkout — its own `.git`, no `.gofer/tracker` of its own — finds nothing instead of the OUTER workspace's tracker, whose rules and memories describe another subsystem entirely (gofer-krzy). A start that no ancestor of which is a repository has no boundary to stop at and keeps Discover's behaviour, and an explicit tracker directory is always used as given.

func Init

func Init(root, prefix string, noAgentsMD bool) (*Store, bool, error)

Init is InitWith without a commit policy change.

func InitWith added in v0.138.0

func InitWith(root string, opts InitOptions) (*Store, bool, error)

InitWith creates the local tracker files and writes (or refreshes) the managed instructions block, rendered for the repository's commit_policy. Hooks and sync are the caller's business. beads reports a leftover bd integration block.

func NewStore

func NewStore(dir string) *Store

func OpenGlobal added in v0.151.0

func OpenGlobal(dir string) (*Store, error)

OpenGlobal opens the machine's copy of the global memories at dir (normally <config-dir>/tracker), creating it on first use. It is an ordinary tracker store — same files, locking and sync state — whose config names the reserved GlobalTrackerID and syncs after every write.

func (*Store) AcquireLock

func (s *Store) AcquireLock() (*Lock, error)

func (*Store) AddComment

func (s *Store) AddComment(id, text, actor string) (Issue, error)

AddComment appends one comment to an issue. Comments are append-only and merge by union across sync.

func (*Store) AddDep

func (s *Store) AddDep(id, on string) (Issue, error)

AddDep makes id wait for `on` (a blocking dependency).

func (*Store) AddDepType

func (s *Store) AddDepType(id, on, kind string) (Issue, error)

AddDepType records that id depends on `on` with the given kind ("" = blocks). A blocking edge that would close a cycle is rejected.

func (*Store) ApplyMemoryScopePaths added in v0.159.0

func (s *Store) ApplyMemoryScopePaths(suggestions []ScopeSuggestion) ([]Memory, error)

ApplyMemoryScopePaths writes paths into the memories of suggestions: `when.paths` (and `updated_at`, because the tracker merge takes the newer record, so a change that leaves the stamp alone can be reverted by the next merge) and nothing else. A key that disappeared, or that gained a scope since the suggestion was computed, is skipped. It returns the rewritten memories, sorted by key by the underlying write.

func (*Store) ArchiveMemory

func (s *Store) ArchiveMemory(key, reason, actor string) (ArchivedMemory, error)

ArchiveMemory moves key from memories.jsonl to memories-archive.jsonl. An older archived copy of the same key is replaced.

func (*Store) BuildFocus

func (s *Store) BuildFocus(ctx context.Context, now time.Time, src FocusSources) string

BuildFocus collects the focus inputs within ctx (git and server in parallel) and renders the section; "" when there is nothing to show. Local tracker read errors and slow / failing sources only drop their own lines.

func (*Store) ChangedSinceHEAD

func (s *Store) ChangedSinceHEAD() (ChangeReport, error)

ChangedSinceHEAD compares issues.jsonl and memories.jsonl in the working tree with their versions at git HEAD. A tracker outside git, or a file that does not exist at HEAD, counts as empty at HEAD.

func (*Store) CloseIssue

func (s *Store) CloseIssue(id, reason string) (Issue, error)

func (*Store) CreateIssue

func (s *Store) CreateIssue(item Issue) (Issue, error)

func (*Store) CwdRel

func (s *Store) CwdRel(cwd string) (string, bool)

CwdRel turns an absolute cwd into the slash path relative to the repository root; ok=false when it is outside the repository (or the root is unknown).

func (*Store) Doctor

func (s *Store) Doctor(now time.Time) (DoctorReport, error)

Doctor checks every local memory (archived ones excluded) and records the raw findings in .local/doctor.json so prime can show path / commit findings without running git. It never changes a memory.

func (*Store) FlagMemory

func (s *Store) FlagMemory(key string, flag MemoryFlag) (Memory, error)

FlagMemory adds a flag to a repository memory. It leaves updated_at alone: a flag is a report about the content, not a change of it.

func (*Store) Issue

func (s *Store) Issue(id string) (Issue, error)

func (*Store) ListArchivedMemories

func (s *Store) ListArchivedMemories(filter MemoryFilter) ([]ArchivedMemory, error)

ListArchivedMemories filters the archive like `memory ls` (keyword over key, summary and content; tags; kind).

func (*Store) ListIssues

func (s *Store) ListIssues(filter IssueFilter) ([]Issue, error)

func (*Store) ListMemories

func (s *Store) ListMemories(keyword string, tags ...string) ([]Memory, error)

func (*Store) ListMemoriesFiltered

func (s *Store) ListMemoriesFiltered(filter MemoryFilter) ([]Memory, error)

func (*Store) Memory

func (s *Store) Memory(key string) (Memory, error)

func (*Store) NextIssueID

func (s *Store) NextIssueID(prefix, parent string) (string, error)

func (*Store) Prime

func (s *Store) Prime() (string, error)

func (*Store) PrimeEstimate

func (s *Store) PrimeEstimate() (bytes int, truncated bool, err error)

PrimeEstimate reports the unbudgeted local context size and whether the budgets cut anything. Server-backed scoped memories and handoffs are outside it.

func (*Store) PrimeRule

func (s *Store) PrimeRule(cwd string, sel PrimeSelection) (string, error)

PrimeRule is the tracker part of a dispatched job's mandatory rules: the commit policy, the kind=rule memories that APPLY TO the job, then a one-line index of the other applicable memories (so the job knows what it can `gofer memory show`). Expired handoffs and archived memories are left out. The whole body stays within PrimeMaxBytes-64; rules that do not fit drop to the index, index lines that do not fit are counted.

cwd selects the material exactly like the session-opening prime (memoryView): a rule whose `when.paths` do not cover cwd is not injected in full, and the index lists only memories that apply to cwd (no `when.paths`, or a matching one), matching first. A job works in one subtree, so a memory about another subsystem is noise in its prompt — that is the whole point of the selection (gofer-krzy).

A cwd this store cannot place inside its repository (unknown root, a path reached through a different spelling) selects nothing and keeps the unscoped behaviour: an unknown cwd must not silently drop rules.

sel is the task the prime is FOR (gofer-11tz): the memories it hits are injected in full when their paths allow it and always appear first in the index, marked (相关). Its zero value keeps the plain cwd-scoped prime.

func (*Store) PrimeWith

func (s *Store) PrimeWith(opts PrimeOptions) (string, error)

PrimeWith renders the local prime: header → [focus] → rules → in-progress → ready → memory index → handoffs. Server sections are appended by the caller.

func (*Store) PrimeWithHandoffFetch

func (s *Store) PrimeWithHandoffFetch(ctx context.Context, fetch func(context.Context) (string, error)) (string, error)

PrimeWithHandoffFetch runs a best-effort handoff lookup supplied by the command layer. The callback owns server discovery/authentication; tracker only applies the two-second budget and the existing handoff-only truncation seam.

func (*Store) PrimeWithHandoffSection

func (s *Store) PrimeWithHandoffSection(handoff string) (string, error)

PrimeWithHandoffSection appends the caller-provided best-effort server handoff section while preserving the existing prime bytes first. The caller is expected to have applied project selection, timeout and ordering before this seam.

func (*Store) PromoteMemory

func (s *Store) PromoteMemory(key, kind string, summary *string, actor string) (Memory, error)

PromoteMemory turns a memory (typically a handoff) into a long-lived rule or note: the kind changes, expires_at is cleared, source and everything else are kept. summary (when non-nil) replaces the stored summary; the usual write rule applies (rule / note content over 200 chars needs one).

func (*Store) ReadArchivedMemories

func (s *Store) ReadArchivedMemories() ([]ArchivedMemory, error)

ReadArchivedMemories reads memories-archive.jsonl (missing file = none).

func (*Store) ReadConfig

func (s *Store) ReadConfig() (Config, error)

func (*Store) ReadIssues

func (s *Store) ReadIssues() ([]Issue, error)

func (*Store) ReadMemories

func (s *Store) ReadMemories() ([]Memory, error)

func (*Store) Ready

func (s *Store) Ready() ([]Issue, error)

func (*Store) Relations

func (s *Store) Relations(id string) (Issue, Relations, error)

Relations computes the neighbourhood of id from the whole issue set.

func (*Store) RemoveDep

func (s *Store) RemoveDep(id, on, kind string) (Issue, error)

RemoveDep drops id's dependency on `on`. kind "" removes every kind; an edge that does not exist is an error so typos are visible.

func (*Store) RemoveMemory

func (s *Store) RemoveMemory(key string) error

func (*Store) ReopenIssue

func (s *Store) ReopenIssue(id, reason, actor string) (Issue, error)

ReopenIssue moves a closed issue back to open, clearing closed_at and close_reason. A non-empty reason is recorded as a comment so the history of why it came back is kept. Reopening an issue that is not closed is an error.

func (*Store) RepoRoot

func (s *Store) RepoRoot() string

RepoRoot is the repository root of a `<root>/.gofer/tracker` store ("" for an explicit tracker directory elsewhere).

func (*Store) RestoreMemory

func (s *Store) RestoreMemory(key, actor string) (Memory, error)

RestoreMemory moves an archived memory back. updated_at is set to now so the restored record wins over the sync tombstone its archiving left on the server (created_at keeps the original age).

func (*Store) SetMemory

func (s *Store) SetMemory(key, content, actor string, tags ...string) (Memory, error)

SetMemory writes content (and tags, when non-nil) keeping every other stored field. It skips the CLI summary rule; `memory set` uses SetMemoryPatch.

func (*Store) SetMemoryPatch

func (s *Store) SetMemoryPatch(key string, patch MemoryPatch, validate bool) (Memory, error)

SetMemoryPatch merges patch into the stored memory (or creates it). validate applies ValidateMemoryForWrite to the merged result before anything is written.

func (*Store) SetProjectKey

func (s *Store) SetProjectKey(key string) error

func (*Store) Status

func (s *Store) Status() (RepoStatus, error)

func (*Store) SubrepoScope added in v0.159.0

func (s *Store) SubrepoScope(cwd string) (string, bool)

SubrepoScope returns the `when.paths` entry of a memory written from cwd: the path of the nested repository cwd lives in, relative to this tracker's repository root, as "<subrepo>/**". ok=false when cwd is not inside this repository, when it belongs to the repository at the tracker root itself (there is nothing to narrow), or when it is in no repository at all — a plain subdirectory of the workspace is not a subproject, and only a checkout of its own is.

It is the write-time half of memory scoping (gofer-opv5): one workspace root holding several independent checkouts (each with its own `.git`) shares a single tracker, and without a scope the memories of one checkout are injected into the jobs of all the others.

func (*Store) Subrepos added in v0.159.0

func (s *Store) Subrepos() []string

Subrepos lists the nested repositories directly under the tracker's repository root: the names (slash form, no trailing slash) of the directories holding a `.git` entry of their own, sorted. They are the candidate scopes `memory scope` suggests.

func (*Store) SuggestMemoryScopes added in v0.159.0

func (s *Store) SuggestMemoryScopes(cwdOf func(source string) (string, bool)) ([]ScopeSuggestion, error)

SuggestMemoryScopes proposes a `when.paths` for every memory of this tracker that has none (gofer-opv5): a workspace root whose subprojects are separate checkouts shares one tracker, and an unscoped memory reaches the jobs of all of them. cwdOf resolves a memory's `source` (job:<id> / session:<id>) to the working directory it was written from; nil means that evidence is unavailable (the caller cannot reach the server).

The evidence is tried in this order and the first one that names exactly one subproject wins:

  1. source: the cwd of the job / session the memory came from is inside a subrepo (high);
  2. one of the key's prefixes or one of its tags names a subrepo directory (high);
  3. the summary / content mentions exactly one subrepo directory (medium).

Evidence naming no subproject or several of them suggests nothing: that memory stays workspace-wide.

func (*Store) SyncedBefore added in v0.151.0

func (s *Store) SyncedBefore() bool

SyncedBefore reports whether this store has completed a sync with a server (its sync-revs state exists). A global copy that never synced holds only what was written on this machine.

func (*Store) UnflagMemory

func (s *Store) UnflagMemory(key string) (Memory, error)

UnflagMemory clears every flag of a repository memory (the human review).

func (*Store) UpdateConfig

func (s *Store) UpdateConfig(change func(*Config)) error

UpdateConfig rewrites config.yaml after applying change to the current values.

func (*Store) UpdateIssue

func (s *Store) UpdateIssue(id string, patch IssuePatch) (Issue, error)

func (*Store) UpdateIssues

func (s *Store) UpdateIssues(change func([]Issue) ([]Issue, error)) (err error)

func (*Store) UpdateMemories

func (s *Store) UpdateMemories(change func([]Memory) ([]Memory, error)) (err error)

func (*Store) WriteIssues

func (s *Store) WriteIssues(items []Issue) (err error)

type SyncConflict

type SyncConflict struct {
	Kind  string `json:"kind"`
	Key   string `json:"key"`
	Field string `json:"field"`
	Took  string `json:"took"`
	Other string `json:"other"`
}

type SyncReport

type SyncReport struct {
	Conflicts []SyncConflict `json:"conflicts,omitempty"`
	Summary   string         `json:"summary,omitempty"`
	// Rejected counts pushed records the server refused as stale (merged and
	// pushed again within the same sync).
	Rejected int `json:"rejected,omitempty"`
	// RepairedToServer / RepairedToLocal count the records the one-time repair
	// (first sync with rev tracking) settled in each direction.
	RepairedToServer int `json:"repaired_to_server,omitempty"`
	RepairedToLocal  int `json:"repaired_to_local,omitempty"`
	// Unresolved lists records ("issue:<id>" / "memory:<key>") still not on the
	// server after maxSyncRounds; the next sync pushes them again.
	Unresolved []string `json:"unresolved,omitempty"`
	// Archived counts local memories moved to memories-archive.jsonl because the
	// server sent an archive tombstone for them (P4).
	Archived int `json:"archived,omitempty"`
}

func SyncHTTP

func SyncHTTP(ctx context.Context, s *Store, endpoint string) (SyncReport, error)

SyncHTTP is the command/runtime sync path. It persists the last successful base under tracker/.local and never changes the repository files when the first request fails.

func SyncHTTPWithToken

func SyncHTTPWithToken(ctx context.Context, s *Store, endpoint, token string) (SyncReport, error)

SyncHTTPWithToken pushes local changes (each with the server rev last seen), pulls the server changes since the cursor, three-way merges them and, when the server answered a push with a conflict, pushes the merged result again (at most maxSyncRounds requests). The first sync without .local/sync-revs.json does a full pull and repairs any divergence record by record (newer body timestamp wins).

type SyncSnapshot

type SyncSnapshot struct {
	Issues   []Issue  `json:"issues"`
	Memories []Memory `json:"memories"`
}

SyncSnapshot is the versioned local view exchanged with the tracker mirror. Memories remain deletion-free in the repository; server-side tombstones are represented by ServerMemory and are folded into the snapshot during sync.

type SyncState

type SyncState struct {
	Base    SyncSnapshot
	Current SyncSnapshot
	Report  SyncReport
}

func (*SyncState) Apply

func (s *SyncState) Apply(local SyncSnapshot, remote *SyncSnapshot) error

func (SyncState) Pending

func (s SyncState) Pending() int

type TransferBoundary

type TransferBoundary struct {
	From     string `json:"from"`
	To       string `json:"to"`
	Relation string `json:"relation"`
	Reason   string `json:"reason"`
}

type TransferBundle

type TransferBundle struct {
	Version         int                `json:"version"`
	SourceTrackerID string             `json:"source_tracker_id"`
	SourceHashes    TransferHashes     `json:"source_hashes"`
	TargetTrackerID string             `json:"target_tracker_id"`
	TargetPrefix    string             `json:"target_prefix"`
	ProjectKey      string             `json:"project_key"`
	Selection       TransferSelection  `json:"selection"`
	Issues          []json.RawMessage  `json:"issues"`
	Memories        []json.RawMessage  `json:"memories"`
	Boundaries      []TransferBoundary `json:"boundaries"`
	Digest          string             `json:"digest"`
}

TransferBundle contains complete source JSON objects, including fields a newer tracker may know that this binary does not. The source directory is intentionally absent: every import names and rechecks its source explicitly.

func PrepareTransfer

func PrepareTransfer(sourceDir string, sel TransferSelection, prefix, projectKey string) (TransferBundle, error)

PrepareTransfer freezes a reviewable package; it never writes the source. Boundaries stay in the package so a reviewer can extend the allowlist.

func ReadTransferBundle

func ReadTransferBundle(path string) (TransferBundle, error)

type TransferCandidates

type TransferCandidates struct {
	SourceTrackerID string         `json:"source_tracker_id"`
	SourceHashes    TransferHashes `json:"source_hashes"`
	IssueIDs        []string       `json:"issue_ids"`
	MemoryKeys      []string       `json:"memory_keys"`
}

func FindTransferCandidates

func FindTransferCandidates(sourceDir, tag, query string) (TransferCandidates, error)

FindTransferCandidates is read-only discovery. Tags and query are hints; the final export still requires an explicit ID/key allowlist.

type TransferHashes

type TransferHashes struct {
	Config   string `json:"config"`
	Issues   string `json:"issues"`
	Memories string `json:"memories"`
}

type TransferSelection

type TransferSelection struct {
	IssueIDs   []string `json:"issue_ids"`
	MemoryKeys []string `json:"memory_keys"`
}

TransferSelection is an exact allowlist. Candidate searches never add records.

Jump to

Keyboard shortcuts

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