Documentation
¶
Overview ¶
Package tracker owns the repository-local issue and memory JSONL truth.
Index ¶
- Constants
- Variables
- func AgeText(value string, now time.Time) string
- func AppendPrimeSections(base string, sections ...string) string
- func ArchivedMemoryListLine(a ArchivedMemory, now time.Time) string
- func AtomicWriteFile(path string, data []byte) error
- func ClaudeImportsAgents(root string) bool
- func CommitPolicyText(policy string) (string, error)
- func DisplayMemorySummary(meta MemoryMeta, content string) string
- func EffectiveMemoryKind(meta MemoryMeta, tags []string) string
- func ExecGit(ctx context.Context, dir string, args ...string) (string, error)
- func FallbackMemorySummary(content string) string
- func FormatDoctorReport(r DoctorReport) string
- func GenerateIssueID(items []Issue, prefix, parent string) (string, error)
- func ImportTransfer(sourceDir, targetRoot string, bundle TransferBundle) (published bool, resultErr error)
- func IsArchiveTombstone(deletedBy string) bool
- func IsLegacyTrackerID(id string) bool
- func IssueTouchedAt(item Issue) string
- func ManagedBlock() string
- func ManagedBlockFor(policy string) (string, error)
- func MatchMemoryPath(pattern, rel string) bool
- func MemoryCreatedAt(meta MemoryMeta, updatedAt string) string
- func MemoryDetail(m Memory, now time.Time) string
- func MemoryExpired(meta MemoryMeta, tags []string, updatedAt string, now time.Time) bool
- func MemoryExpiresAt(meta MemoryMeta, tags []string, updatedAt string) (time.Time, bool)
- func MemoryFlagPrefix(meta MemoryMeta) string
- func MemoryForAgent(tags []string, agentName string) bool
- func MemoryIndexGroup(tags []string) string
- func MemoryListLine(m Memory, now time.Time) string
- func MemoryMatchesCommand(meta MemoryMeta, command string) (string, bool)
- func MemoryMatchesFilter(item Memory, filter MemoryFilter) bool
- func MemoryMatchesKeyword(meta MemoryMeta, text string) (string, bool)
- func MemoryMatchesPath(meta MemoryMeta, rel string) bool
- func MemoryMatchesSelection(m Memory, sel PrimeSelection) bool
- func MemoryStale(meta MemoryMeta, tags []string, updatedAt string, now time.Time) bool
- func MergeKindForPath(p string) string
- func MergeServerMemories(base, local, remote []ServerMemory) ([]ServerMemory, SyncReport)
- func NewTrackerID() string
- func Now() string
- func ParseMemoryTTL(value string) (time.Duration, error)
- func ParseTags(value string) []string
- func RenderFocus(in FocusInput) string
- func RenderScopedPrimeSection(title string, items []Memory, opts ScopedPrimeOptions) string
- func RepoBoundary(start string) (string, bool)
- func RepoCwd(repoPath string, roots []string) (string, bool)
- func RunMergeDriver(base, ours, theirs, name string, stderr io.Writer) int
- func ShortTrackerID(legacy string) string
- func SniffMergeKind(data ...[]byte) string
- func SplitPrimeKeywords(value string) []string
- func SyncContext(endpoint string) (context.Context, context.CancelFunc)
- func ThreeWayMerge(base, local, remote SyncSnapshot) (SyncSnapshot, SyncReport)
- func ValidDoctorSlug(slug string) bool
- func ValidMemoryKind(kind string) bool
- func ValidStatus(status string) bool
- func ValidateMemoryForWrite(item Memory) error
- func WriteTransferBundle(sourceDir, path string, bundle TransferBundle) error
- type ArchivedMemory
- type BriefConfig
- type BriefVerifyRule
- type Change
- type ChangeReport
- type Comment
- type Config
- type Dep
- type DoctorEntry
- type DoctorFinding
- type DoctorOptions
- type DoctorReport
- type FocusGit
- type FocusInput
- type FocusPlan
- type FocusRemote
- type FocusServer
- type FocusSources
- type FocusWorker
- type GitRunner
- type InitOptions
- type Issue
- type IssueFilter
- type IssuePatch
- type JobIssueEvent
- type Lock
- type Memory
- type MemoryFilter
- type MemoryFlag
- type MemoryMeta
- type MemoryPatch
- type MemoryWhen
- type MergeConflict
- type MergeDriverSetup
- type NoteEntry
- type PrimeConfig
- func (c PrimeConfig) ActiveLimit() int
- func (c PrimeConfig) DoctorSuppress() []string
- func (c PrimeConfig) FocusEnabled() bool
- func (c PrimeConfig) FocusEnvEnabled() bool
- func (c PrimeConfig) FocusTagEnabled() bool
- func (c PrimeConfig) HandoffEnabled() bool
- func (c PrimeConfig) InjectOnCommandEnabled() bool
- func (c PrimeConfig) InjectOnPromptEnabled() bool
- func (c PrimeConfig) IssuesEnabled() bool
- func (c PrimeConfig) MemoryEnabled() bool
- func (c PrimeConfig) ReadyCount() int
- func (c PrimeConfig) ReadyEnabled() bool
- func (c PrimeConfig) ScopedMemoryEnabled() bool
- func (c PrimeConfig) SummaryLimit() int
- type PrimeDoctorConfig
- type PrimeOptions
- type PrimeSelection
- type Relations
- type RepoStatus
- type ScopedPrimeOptions
- type ServerMemory
- type Store
- func Discover(start, explicit string) (*Store, error)
- func DiscoverWithinRepo(start, explicit string) (*Store, error)
- func Init(root, prefix string, noAgentsMD bool) (*Store, bool, error)
- func InitWith(root string, opts InitOptions) (*Store, bool, error)
- func NewStore(dir string) *Store
- func OpenGlobal(dir string) (*Store, error)
- func (s *Store) AcquireLock() (*Lock, error)
- func (s *Store) AddComment(id, text, actor string) (Issue, error)
- func (s *Store) AddDep(id, on string) (Issue, error)
- func (s *Store) AddDepType(id, on, kind string) (Issue, error)
- func (s *Store) ArchiveMemory(key, reason, actor string) (ArchivedMemory, error)
- func (s *Store) BuildFocus(ctx context.Context, now time.Time, src FocusSources) string
- func (s *Store) ChangedSinceHEAD() (ChangeReport, error)
- func (s *Store) CloseIssue(id, reason string) (Issue, error)
- func (s *Store) CreateIssue(item Issue) (Issue, error)
- func (s *Store) CwdRel(cwd string) (string, bool)
- func (s *Store) Doctor(now time.Time) (DoctorReport, error)
- func (s *Store) FlagMemory(key string, flag MemoryFlag) (Memory, error)
- func (s *Store) Issue(id string) (Issue, error)
- func (s *Store) ListArchivedMemories(filter MemoryFilter) ([]ArchivedMemory, error)
- func (s *Store) ListIssues(filter IssueFilter) ([]Issue, error)
- func (s *Store) ListMemories(keyword string, tags ...string) ([]Memory, error)
- func (s *Store) ListMemoriesFiltered(filter MemoryFilter) ([]Memory, error)
- func (s *Store) Memory(key string) (Memory, error)
- func (s *Store) NextIssueID(prefix, parent string) (string, error)
- func (s *Store) Prime() (string, error)
- func (s *Store) PrimeEstimate() (bytes int, truncated bool, err error)
- func (s *Store) PrimeRule(cwd string, sel PrimeSelection) (string, error)
- func (s *Store) PrimeWith(opts PrimeOptions) (string, error)
- func (s *Store) PrimeWithHandoffFetch(ctx context.Context, fetch func(context.Context) (string, error)) (string, error)
- func (s *Store) PrimeWithHandoffSection(handoff string) (string, error)
- func (s *Store) PromoteMemory(key, kind string, summary *string, actor string) (Memory, error)
- func (s *Store) ReadArchivedMemories() ([]ArchivedMemory, error)
- func (s *Store) ReadConfig() (Config, error)
- func (s *Store) ReadIssues() ([]Issue, error)
- func (s *Store) ReadMemories() ([]Memory, error)
- func (s *Store) Ready() ([]Issue, error)
- func (s *Store) Relations(id string) (Issue, Relations, error)
- func (s *Store) RemoveDep(id, on, kind string) (Issue, error)
- func (s *Store) RemoveMemory(key string) error
- func (s *Store) ReopenIssue(id, reason, actor string) (Issue, error)
- func (s *Store) RepoRoot() string
- func (s *Store) RestoreMemory(key, actor string) (Memory, error)
- func (s *Store) SetMemory(key, content, actor string, tags ...string) (Memory, error)
- func (s *Store) SetMemoryPatch(key string, patch MemoryPatch, validate bool) (Memory, error)
- func (s *Store) SetProjectKey(key string) error
- func (s *Store) Status() (RepoStatus, error)
- func (s *Store) SyncedBefore() bool
- func (s *Store) UnflagMemory(key string) (Memory, error)
- func (s *Store) UpdateConfig(change func(*Config)) error
- func (s *Store) UpdateIssue(id string, patch IssuePatch) (Issue, error)
- func (s *Store) UpdateIssues(change func([]Issue) ([]Issue, error)) (err error)
- func (s *Store) UpdateMemories(change func([]Memory) ([]Memory, error)) (err error)
- func (s *Store) WriteIssues(items []Issue) (err error)
- type SyncConflict
- type SyncReport
- type SyncSnapshot
- type SyncState
- type TransferBoundary
- type TransferBundle
- type TransferCandidates
- type TransferHashes
- type TransferSelection
Constants ¶
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`.
const ( MemoryKindRule = "rule" MemoryKindNote = "note" MemoryKindHandoff = "handoff" )
Memory kinds (design 2026-10-09-prime-memory-quality-design.md §2.1).
const ( MergeKindIssues = "issues" MergeKindMemories = "memories" MergeKindMemoryArchive = "memories-archive" )
Tracker JSONL kinds the merge understands.
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).
const ( BeginBlock = beginBlock EndBlock = endBlock )
BeginBlock / EndBlock delimit the gofer-managed block in AGENTS.md / CLAUDE.md.
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.
const DefaultCommitPolicy = "local-commit"
DefaultCommitPolicy is the commit_policy of a new tracker.
const DefaultHandoffTTL = 14 * 24 * time.Hour
DefaultHandoffTTL is the lifetime of a handoff memory without an explicit --ttl.
const DepDiscoveredFrom = "discovered-from"
DepDiscoveredFrom links an issue to the one it was found while working on (`issue create --from <id>`).
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.
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).
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).
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.
const MemoryFlagsMax = 5
MemoryFlagsMax caps the flags a memory keeps (newest first).
const MemorySummaryMaxRunes = 80
MemorySummaryMaxRunes caps summaries (written and derived) shown in indexes.
const MemorySummaryRequiredRunes = 200
MemorySummaryRequiredRunes: rule / note content longer than this needs a summary.
const MemoryWriteHint = "" /* 190-byte string literal not displayed */
MemoryWriteHint is the writing guidance (design §2.8) shared by prime and the managed AGENTS block.
const PrimeMaxBytes = 8 << 10
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).
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).
const PrimeStaleMarker = "⚠ 可能过期"
PrimeStaleMarker is appended to flagged rule / note entries in prime.
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 配合」).
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.
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 ¶
var ClearableFields = []string{"description", "design", "acceptance", "assignee", "owner", "parent", "close-reason"}
ClearableFields are the names `issue update --clear` accepts.
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.
var DoctorSlugs = []string{DoctorFlagged, DoctorHandoffExpired, DoctorNoteStale, DoctorPathMissing, DoctorCommitMissing, DoctorSummaryMissing, DoctorDuplicate}
DoctorSlugs lists every finding slug in report order.
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.
var SortFields = []string{"id", "priority", "created", "updated"}
SortFields are the names IssueFilter.Sort accepts.
Functions ¶
func AppendPrimeSections ¶
AppendPrimeSections appends optional server-backed sections within the same bounded prime budget. Each section must include its heading and body.
func ArchivedMemoryListLine ¶
func ArchivedMemoryListLine(a ArchivedMemory, now time.Time) string
ArchivedMemoryListLine is one `memory ls --archived` row.
func AtomicWriteFile ¶
AtomicWriteFile replaces path with data without ever leaving a half-written file.
func ClaudeImportsAgents ¶
ClaudeImportsAgents is claudeImportsAgents for other packages (the bd migration).
func CommitPolicyText ¶
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 FallbackMemorySummary ¶
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 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 ¶
IsArchiveTombstone reports whether a tombstone's deleted_by marks an archive.
func IsLegacyTrackerID ¶
IsLegacyTrackerID reports whether id has the old UUID form.
func IssueTouchedAt ¶
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
ManagedBlockFor renders the managed block for a commit_policy value; its commit line is CommitPolicyText, so the block and prime always agree.
func MatchMemoryPath ¶
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 ¶
MemoryDetail renders every field of a memory for `memory show`, then the content.
func MemoryExpired ¶
MemoryExpired reports whether a handoff memory is past its expiry at now.
func MemoryExpiresAt ¶
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 ¶
MemoryForAgent filters `agent:<name>` tagged memories: untagged memories are for every agent, tagged ones only for the named agents.
func MemoryIndexGroup ¶
MemoryIndexGroup is the index group of a memory: its first tag (ignoring the legacy `prime` and `agent:*` tags), else 其他.
func MemoryListLine ¶
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 ¶
MemoryStale reports a note not updated for 90 days (§2.1 「久未更新」).
func MergeKindForPath ¶ added in v0.135.0
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 ParseMemoryTTL ¶
ParseMemoryTTL accepts Nd / Nw plus Go durations (36h, 90m).
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 RepoBoundary ¶ added in v0.157.0
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 ¶
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
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 ShortTrackerID ¶
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
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
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 ¶
ValidDoctorSlug reports whether slug is a known finding slug.
func ValidMemoryKind ¶
ValidMemoryKind reports whether kind is one of rule|note|handoff.
func ValidStatus ¶
func ValidateMemoryForWrite ¶
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 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 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 ¶
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 ¶
FocusWorker is one worker runner as the server sees it.
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 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 ¶
EffectiveKind returns the effective kind of the memory.
type MemoryFilter ¶
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
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 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
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 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 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 DiscoverWithinRepo ¶ added in v0.157.0
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 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 OpenGlobal ¶ added in v0.151.0
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 (*Store) AddComment ¶
AddComment appends one comment to an issue. Comments are append-only and merge by union across sync.
func (*Store) AddDepType ¶
AddDepType records that id depends on `on` with the given kind ("" = blocks). A blocking edge that would close a cycle is rejected.
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 ¶
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) CwdRel ¶
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) 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 (*Store) ListMemoriesFiltered ¶
func (s *Store) ListMemoriesFiltered(filter MemoryFilter) ([]Memory, error)
func (*Store) PrimeEstimate ¶
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 ¶
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 ¶
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 (*Store) ReadIssues ¶
func (*Store) ReadMemories ¶
func (*Store) RemoveDep ¶
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 (*Store) ReopenIssue ¶
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 ¶
RepoRoot is the repository root of a `<root>/.gofer/tracker` store ("" for an explicit tracker directory elsewhere).
func (*Store) RestoreMemory ¶
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 ¶
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 ¶
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 (*Store) Status ¶
func (s *Store) Status() (RepoStatus, error)
func (*Store) SyncedBefore ¶ added in v0.151.0
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 ¶
UnflagMemory clears every flag of a repository memory (the human review).
func (*Store) UpdateConfig ¶
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 (*Store) UpdateMemories ¶
func (*Store) WriteIssues ¶
type SyncConflict ¶
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 ¶
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 ¶
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 ¶
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
type TransferBoundary ¶
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 TransferSelection ¶
type TransferSelection struct {
IssueIDs []string `json:"issue_ids"`
MemoryKeys []string `json:"memory_keys"`
}
TransferSelection is an exact allowlist. Candidate searches never add records.
Source Files
¶
- changed.go
- discovery.go
- entries.go
- entries_ops.go
- focus.go
- focus_git.go
- global.go
- id.go
- lock.go
- memory_archive.go
- memory_doctor.go
- memory_flag.go
- memory_format.go
- memory_meta.go
- merge.go
- merge_driver.go
- model.go
- prime.go
- prime_layout.go
- prime_memory.go
- prime_selection.go
- ready.go
- remote_sync.go
- repo.go
- store.go
- sync.go
- sync_http.go
- tracker_id.go
- transfer.go