Documentation
¶
Index ¶
- Constants
- func AgentMemoriesRoot(agentDir string) string
- func AgentMemoryPromptSection(indexContent string, readErr error) string
- func AgentMemoryRoot(agentDir, key string) string
- func ApplyCaptureOp(s *Store, op CaptureOp, originSession string, capturedOn time.Time) error
- func ApplyEdit(content, oldString, newString string, replaceAll bool) (string, int, error)
- func ArchiveDir(projectDir string) string
- func ArchiveSessionsDir(projectDir string) string
- func BuildIndex(in IndexInput) string
- func CaptureAttemptFile(projectDir string) string
- func CaptureStateFile(projectDir string) string
- func ChainBackfillCandidates(text, root string, max int) []string
- func ChainFile(projectDir string) string
- func CodeOf(err error) string
- func CollapseLine(s string) string
- func ContainPathForTest(root, name string) (string, error)
- func CountFacts(projectDir string) (int, error)
- func DetectProjectRoot(cwd string) (string, error)
- func DigestLine(field string) string
- func DigestUsable(digest Digest) bool
- func ExtractJSONObjectForTest(raw string) (string, error)
- func FactSlug(text string) string
- func FormatDigest(digest Digest) string
- func FormatFact(fact Fact) string
- func FormatPage(page Page) string
- func HeadBytes(s string, max int) (string, bool)
- func IndexFile(projectDir string) string
- func IsFullyPrivate(content string) bool
- func JournalFile(projectDir string) string
- func ManifestKindRankForTest(kind string) int
- func MemoryRoot(agentDir string) string
- func NextKey(existing map[string]bool, base string) string
- func NormalizeFactType(raw string) string
- func NormalizeNewlines(s string) string
- func NormalizeScene(raw string) string
- func PageQuestion(name string) (string, bool)
- func PagesDir(projectDir string) string
- func ParseCaptureDigest(raw string) (topic, summary string, err error)
- func ProjectDir(agentDir, root string) string
- func ProjectDirForKey(agentDir, key string) string
- func ProjectKey(root string) string
- func ProjectMetaFile(projectDir string) string
- func Redact(text string) string
- func RenderIndex(facts []Fact) string
- func RenderManifest(entries []ManifestEntry, maxBytes int) string
- func RepairJSONEscapesForTest(payload string) string
- func SanitizeAgentMemoryKey(name string) string
- func SecretHoldback(s string) int
- func SecretLike(text string) bool
- func SecretPatterns() []*regexp.Regexp
- func SessionsDir(projectDir string) string
- func SlugKey(text string, max int) string
- func SlugifyForTest(name string) string
- func StripPrivateContent(content string) string
- func TailBytes(s string, max int) (string, bool)
- func TopicsDir(projectDir string) string
- func TruncateIndex(content string) string
- func UserFile(memoryRoot string) string
- func ValidTopicName(name string) bool
- func ValidateFactName(name string) error
- func ValidateFactPath(path string) error
- type CaptureAttempt
- type CaptureAttempts
- type CaptureOp
- type CapturePhase
- type CaptureResult
- type CaptureState
- type ChainRevision
- type Digest
- type DigestRetention
- type EmbeddingProvider
- type Error
- type Fact
- type FactMatch
- type HTTPEmbedConfig
- type IndexInput
- type JournalEntry
- type Limits
- type LinksField
- type ManifestEntry
- type Match
- type MigrateResult
- type Options
- type Page
- type PageDraft
- type PageDraftResult
- type PageSpec
- type ProjectMeta
- type ScoredFactForTest
- type Store
- func (s *Store) AppendChainRevisions(revisions []ChainRevision) error
- func (s *Store) AppendFact(fact Fact) (Fact, error)
- func (s *Store) AppendUser(reason, content string) (int, error)
- func (s *Store) ChainPaths() ([]string, error)
- func (s *Store) ChainRevisions(path string, max int) ([]ChainRevision, error)
- func (s *Store) Close() error
- func (s *Store) CountDanglingLinks() (int, error)
- func (s *Store) DeleteFact(name string) (bool, error)
- func (s *Store) DeleteTopic(topic string) (bool, error)
- func (s *Store) EditFact(name, oldString, newString string, replaceAll bool) (Fact, int, error)
- func (s *Store) EnsureProject(meta ProjectMeta) (bool, error)
- func (s *Store) IndexBytes() (int, error)
- func (s *Store) IndexPath() string
- func (s *Store) JournalStatus() (bytes int, last JournalEntry, ok bool)
- func (s *Store) Limits() Limits
- func (s *Store) ListDigests() ([]Digest, error)
- func (s *Store) ListFacts() ([]Fact, error)
- func (s *Store) ListPages() ([]Page, error)
- func (s *Store) Manifest() ([]ManifestEntry, error)
- func (s *Store) ManifestBlock() (string, error)
- func (s *Store) MarkChainBackfillPending(candidates []string, chained map[string]bool)
- func (s *Store) Meta() ProjectMeta
- func (s *Store) MigrateError() error
- func (s *Store) MigrateLegacyIfPresent() (MigrateResult, error)
- func (s *Store) MoveFactToTopic(name, topic string) (Fact, error)
- func (s *Store) Ping() error
- func (s *Store) ProjectDir() string
- func (s *Store) PruneDigests() (int, error)
- func (s *Store) ReadCaptureAttempts() (CaptureAttempts, error)
- func (s *Store) ReadCaptureState() (CaptureState, error)
- func (s *Store) ReadDigest(sessionID string) (Digest, error)
- func (s *Store) ReadFact(name string) (Fact, error)
- func (s *Store) ReadFactWithBytes(name string) (Fact, []byte, error)
- func (s *Store) ReadIndex() (string, error)
- func (s *Store) ReadProjectMeta() (ProjectMeta, bool, error)
- func (s *Store) ReadUser() (string, error)
- func (s *Store) ReadUserBytes() ([]byte, error)
- func (s *Store) RefreshSearch() error
- func (s *Store) RegenerateIndex() error
- func (s *Store) ResolveLinks(name string) ([]Fact, []string, error)
- func (s *Store) SearchFacts(query, scene string, max int) ([]FactMatch, error)
- func (s *Store) SearchUser(query string) ([]Match, error)
- func (s *Store) SessionsDir() string
- func (s *Store) SetDigestLimits(maxDigests, ttlDays int)
- func (s *Store) StalePages() ([]string, error)
- func (s *Store) TopicDirs() ([]string, error)
- func (s *Store) UpdateCaptureState(mutate func(*CaptureState) bool) error
- func (s *Store) UpdateFact(name, description, body string, links []string) (Fact, error)
- func (s *Store) UpsertFact(fact Fact) (Fact, error)
- func (s *Store) UpsertPage(page Page) (Page, error)
- func (s *Store) UserPath() string
- func (s *Store) WriteCaptureAttempt(phase CapturePhase, attempt CaptureAttempt) error
- func (s *Store) WriteCaptureState(state CaptureState) error
- func (s *Store) WriteDigest(digest Digest) (string, error)
Constants ¶
const ( CodeInvalidOperation = "INVALID_OPERATION" CodeMissingField = "MISSING_FIELD" CodeInvalidTopic = "INVALID_TOPIC" CodeInvalidReply = "INVALID_REPLY" CodeReasonRequired = "REASON_REQUIRED" CodeOldNotFound = "OLD_NOT_FOUND" CodeOldAmbiguous = "OLD_AMBIGUOUS" CodeFileInvalid = "MEMORY_FILE_INVALID" CodeIO = "MEMORY_IO" CodeCaptureTimeout = "CAPTURE_TIMEOUT" CodeDisabled = "MEMORY_DISABLED" CodeDigestNotFound = "DIGEST_NOT_FOUND" CodeFactNotFound = "FACT_NOT_FOUND" CodeDuplicate = "DUPLICATE_FACT" CodeSecretRejected = "SECRET_REJECTED" CodePrivateRejected = "PRIVATE_REJECTED" CodePathEscape = "PATH_ESCAPE" )
Error codes surfaced by the memory tool and pinned by tests. Size-refusal codes are gone with the caps (ADR-005): the remaining failures are IO, invalid input, boundary rules, and the capture timeout, which is a slow provider rather than a file.
const ( ArchiveDigestKeepForTest = archiveDigestKeep JournalPrevFileForTest = journalPrevFile JournalRotateBytesForTest = journalRotateBytes MaxFactLinksForTest = maxFactLinks MaxFactNameBytesForTest = maxFactNameBytes )
The caps and filenames the tests pin.
const ( FactTypeUser = "user" FactTypeFeedback = "feedback" FactTypeProject = "project" FactTypeReference = "reference" FactTypeExperience = "experience" )
The shared fact-type vocabulary. Unknown types are preserved as read and never rejected; writers default an empty type to project. Experience marks the second layer: a reusable approach whose links name the facts it was learned from.
const ( FactSceneChat = "chat" FactSceneWorking = "working" FactSceneCoding = "coding" )
The scene vocabulary: the domain a fact belongs to, adapted from Hy-Memory's task scenes. An empty scene is unscoped: the fact matches every scene-scoped search, so a missing tag can never hide knowledge.
const ( IndexLineLimit = 200 IndexCharLimit = 25_000 )
The injection caps. They are format constants (docs/memory.md), not settings: xi truncates what the model sees the way ZCode does.
const ( DefaultProjectSoftBytes = 16 * 1024 DefaultUserInjectBytes = 4 * 1024 DefaultPagesInjectBytes = 10 * 1024 DefaultMaxSearchResults = 50 DefaultMaxDigests = 20 DefaultDigestTTLDays = 30 DefaultManifestMaxFiles = 200 DefaultManifestPreviewLines = 30 DefaultManifestMaxBytes = 6 * 1024 )
const ( ManifestKindIndex = "index" ManifestKindFact = "fact" ManifestKindDigest = "digest" )
Manifest kinds label one memory file in the inventory.
const ( SearchBackendSQLite = "sqlite" SearchBackendHybrid = "hybrid" )
const AgentMemoryScopeLine = "Scope: this is user-level memory — it applies across all projects; " +
"keep learnings general rather than project-specific. " +
"target=project addresses your own agent memory directory; target=user is the user's global profile. " +
"Repo-true, team-shareable findings belong in your report to the parent, not memory."
AgentMemoryScopeLine steers a memory-enabled child at general learnings and states the addressing its agent-scoped tool provides: its project layer is its own cross-project directory and repo-true findings stay out of user-scope memory (ADR-006).
const CaptureConsolidationPrompt = `` /* 3394-byte string literal not displayed */
CaptureConsolidationPrompt asks for durable project memory operations.
const CaptureDigestPrompt = `` /* 510-byte string literal not displayed */
CaptureDigestPrompt asks for a short session handoff digest.
const CaptureOverflowTopic = "capture-overflow"
CaptureOverflowTopic receives detail moved out of the root by a demote op. One fixed topic keeps the demotion path bounded: the write either lands there or fails, and the topic list shows it.
const DefaultDigestMaxBytes = 4 * 1024
DefaultDigestMaxBytes bounds how much summary text the deterministic fallback digest renders. It is a generation budget, not a write refusal: model-written digests are never size-checked.
const EvolvePagesPrompt = `` /* 662-byte string literal not displayed */
EvolvePagesPrompt asks for the standing pages the sweep requested. The schema is its own envelope: pages are derived state, not fact ops, so they never ride the capture op vocabulary.
const EvolvePrompt = `` /* 1091-byte string literal not displayed */
EvolvePrompt asks for a maintenance sweep over the existing fact store. The ops schema is the capture consolidation schema restricted to the two actions a sweep may take, so the reply parses and applies through the shared paths.
const FactNodeType = "memory"
FactNodeType is the fixed node_type every writer stamps, matching the ZCode files the format conforms to.
const MemoryInstructions = `` /* 2591-byte string literal not displayed */
MemoryInstructions is the shared memory contract injected with both the workspace project prompt and the agent prompt, so the two cannot drift.
const MinDigestSummaryBytes = 20
MinDigestSummaryBytes is the shortest summary worth storing.
const RedactedPlaceholder = "[redacted]"
RedactedPlaceholder replaces secret-like matches.
Variables ¶
This section is empty.
Functions ¶
func AgentMemoriesRoot ¶
AgentMemoriesRoot is the parent of every agent memory directory.
func AgentMemoryPromptSection ¶
AgentMemoryPromptSection builds the system-prompt section a memory-enabled subagent spawns with: the shared contract, the user-scope steering, then the agent's own index truncated at the injection caps. A read error omits the index body entirely rather than claiming the memory is empty (the child would re-derive and re-append facts that already exist); an empty store still teaches — the child needs the contract to make its first save.
func AgentMemoryRoot ¶
AgentMemoryRoot is the memory directory for one agent key.
func ApplyCaptureOp ¶
ApplyCaptureOp applies one consolidation op to the store. A missing fact is already the end state a drop asks for, so it is a no-op, not a failure. originSession stamps the fact's provenance when the capture knows the session id. capturedOn is the window's observation date: new facts record when the conversation happened, not when the capture ran; zero falls back to the store clock.
func ApplyEdit ¶
ApplyEdit replaces oldString with newString, literally: no regular expressions and no replacement-pattern expansion, so "$&" and friends land byte-for-byte. Zero matches and ambiguous matches (more than one without replaceAll) are coded errors.
func ArchiveDir ¶
ArchiveDir is the project snapshot directory.
func ArchiveSessionsDir ¶
ArchiveSessionsDir holds digests that aged out of the searchable set. Archived files stay readable by path and are never searched.
func BuildIndex ¶
func BuildIndex(in IndexInput) string
BuildIndex renders the project memory block for the system prompt: the capped index inside a project_memory envelope, with the newest session digest as the continuity anchor. Deterministic for the same inputs.
func CaptureAttemptFile ¶
CaptureAttemptFile is the persisted last-capture-phase record.
func CaptureStateFile ¶
CaptureStateFile is the persisted capture-marker file.
func ChainBackfillCandidates ¶
ChainBackfillCandidates extracts up to max workspace files the text names: path-like tokens that stat as regular files under root, spelled in the chain's root-relative identity. Out-of-root absolutes and directories drop.
func CollapseLine ¶
CollapseLine flattens whitespace runs into single spaces and trims.
func ContainPathForTest ¶
ContainPathForTest exposes the path containment check.
func CountFacts ¶
CountFacts counts the facts in a project-shaped directory with the same file selection listFactsLocked applies (top-level .md files plus ValidTopicName topic subdirectories, stray files skipped). Surfaces that only need the count — /memory status over agent directories — use this instead of keeping a second enumeration rule.
func DetectProjectRoot ¶
DetectProjectRoot resolves the project boundary for cwd: the nearest ancestor (including cwd) containing a .git entry, else the resolved cwd. A .xi-project marker takes precedence over git detection so nested repos can share one store. Symlinks are resolved first so the same directory reached two ways maps to one project.
func DigestLine ¶
DigestLine renders a digest topic or summary as one clamped line. The injected continuity anchor and a session-digest list row both read it through here: one line keeps the prompt envelope well formed, and the byte bound keeps a row from carrying a model-authored field whole.
func DigestUsable ¶
DigestUsable reports whether a digest carries enough content to store.
func ExtractJSONObjectForTest ¶
ExtractJSONObjectForTest exposes the JSON object slicer.
func FactSlug ¶
FactSlug slugs a fact name: lowercase [a-z0-9] runs joined by single dashes, capped at maxFactNameBytes.
func FormatDigest ¶
FormatDigest renders the canonical digest file.
func FormatFact ¶
FormatFact renders the canonical fact file. The description is collapsed to one line; an empty body emits the frontmatter block only.
func FormatPage ¶
FormatPage renders the canonical page file. An empty body emits the frontmatter block only.
func HeadBytes ¶
HeadBytes returns the first max bytes of s, cut on a rune boundary, and whether anything was dropped. A non-positive max keeps nothing.
func IsFullyPrivate ¶
IsFullyPrivate reports whether nothing survives redaction.
func JournalFile ¶
JournalFile is the project change journal path.
func ManifestKindRankForTest ¶
ManifestKindRankForTest exposes the manifest kind ordering.
func MemoryRoot ¶
MemoryRoot is the parent of user.md and projects/ under the agent dir.
func NextKey ¶
NextKey slugs base to the name cap. A free slug stays as-is; a taken slug gets a numeric suffix and only its stem shortens, so every suffixed name survives write-time normalization while existing long names stay intact.
func NormalizeFactType ¶
NormalizeFactType trims and lowercases a fact type. Known and unknown types are preserved: a writer must not silently relabel an existing or imported type. Only an empty type defaults to project.
func NormalizeNewlines ¶
NormalizeNewlines folds CRLF and lone CR to LF so parsers see one shape.
func NormalizeScene ¶
NormalizeScene maps the scene vocabulary onto its canonical lower-case form and blanks anything else, so a scene-scoped search can filter on exact values and a hand-edited junk tag cannot leak into a rewrite.
func PageQuestion ¶
PageQuestion returns the standing question for a catalog slug.
func PagesDir ¶
PagesDir holds the derived knowledge pages. Engine state outside format v1: external readers must ignore the directory.
func ParseCaptureDigest ¶
ParseCaptureDigest parses the model's digest JSON.
func ProjectDir ¶
ProjectDir is the per-project memory directory under the agent dir.
func ProjectDirForKey ¶
ProjectDirForKey is the memory directory for a workspace key: ProjectKey(root) or an explicit, path-safe workspace id.
func ProjectKey ¶
ProjectKey returns the stable "<slug>-<hash8>" directory name for a canonical project root.
func ProjectMetaFile ¶
ProjectMetaFile is the project identity record written once per project.
func RenderIndex ¶
RenderIndex renders MEMORY.md from the facts: one `- [name](path) — description` line per fact, newest first, ties by name.
func RenderManifest ¶
func RenderManifest(entries []ManifestEntry, maxBytes int) string
RenderManifest renders the inventory within maxBytes, newest first. Files that do not fit are counted in a trailing marker.
func RepairJSONEscapesForTest ¶
RepairJSONEscapesForTest exposes the escape repairer.
func SanitizeAgentMemoryKey ¶
SanitizeAgentMemoryKey maps a profile name onto a filesystem-safe directory key: every rune outside [a-zA-Z0-9_-] becomes a dash, and an empty result falls back to "unknown". The rule matches ZCode's agent-key sanitization so profile names stay convention-compatible.
func SecretHoldback ¶
SecretHoldback reports how many trailing bytes of s a streamed reader must withhold: the tail that could still grow into a secret match.
Redact runs over a whole buffer, so it fires only on a complete match. A buffer that ends mid-secret carries a prefix no matcher sees, and a reader handed that prefix learns the start of the credential — up to the matcher's whole minimum window. Withholding the tail until the match completes (redaction then fires and the tail is re-delivered redacted) or the producer settles (it can no longer complete, so it is safe as written) closes that window.
The checks below mirror secretPatterns. The PRIVATE KEY banner needs no entry: its whole match is its own lead-in, so no prefix of it can be a secret the banner would have redacted.
func SecretLike ¶
SecretLike reports whether text carries a secret-like pattern.
func SecretPatterns ¶
SecretPatterns exposes the secret matchers for the obfuscation pass, which needs spans (not just a verdict) to mint placeholders.
func SessionsDir ¶
SessionsDir is the per-session digest directory.
func SlugKey ¶
SlugKey lowercases text and keeps [a-z0-9] runs joined by single dashes, capped at max bytes with trailing dashes trimmed. It returns "" when nothing usable remains.
func SlugifyForTest ¶
SlugifyForTest exposes the name slugifier.
func StripPrivateContent ¶
StripPrivateContent replaces every <private>...</private> span with [REDACTED]. An unclosed opening tag redacts to the end of the input; a stray closing tag is dropped.
func TailBytes ¶
TailBytes returns the last max bytes of s, cut on a rune boundary, and whether anything was dropped. A non-positive max keeps nothing.
func TruncateIndex ¶
TruncateIndex applies the injection caps to index content. Content within both caps is returned unchanged; over-cap content is cut and carries the warning, which mirrors ZCode's index truncation so both agents steer the model the same way.
func ValidTopicName ¶
ValidTopicName reports whether name is a legal topic directory name.
func ValidateFactName ¶
ValidateFactName rejects names whose files collide with store-owned files.
func ValidateFactPath ¶
ValidateFactPath accepts an empty root path or a valid topics/<name> path.
Types ¶
type CaptureAttempt ¶
type CaptureAttempt struct {
Phase CapturePhase `json:"phase"`
At time.Time `json:"at"`
// Duration is the wall time the phase spent, including its retries.
Duration time.Duration `json:"duration"`
// Attempts counts the calls this phase's own loop made. A token-cap
// retry inside one reply call is not itemized: the record reports the
// attempt that answered, not the transport ladder beneath it.
Attempts int `json:"attempts"`
// Bytes is the reply length the last attempt returned, partial or not.
Bytes int `json:"bytes"`
StopReason string `json:"stopReason,omitempty"`
Truncated bool `json:"truncated,omitempty"`
// Model is the model that answered the pass. It differs from the
// configured capture model when the provider refused that one and the
// pass ran on the session model.
Model string `json:"model,omitempty"`
// RefusedModel is the capture model the provider refused, empty when
// the pass ran on the configured model.
RefusedModel string `json:"refusedModel,omitempty"`
// Err is the phase failure: a provider error, a spent budget, or the
// parse diagnosis for a body the parsers rejected.
Err string `json:"err,omitempty"`
}
CaptureAttempt is what one phase saw. StopReason and Truncated separate a cap cut from a body that ended early under a clean terminal event: the first earns the doubled-cap retry, the second earns the parse retry, and a report that cannot tell them apart cannot choose.
type CaptureAttempts ¶
type CaptureAttempts struct {
Typed CaptureAttempt `json:"typed"`
Digest CaptureAttempt `json:"digest"`
}
CaptureAttempts holds the last record for each phase of a capture pass. The zero value reads as "no pass has run".
func (CaptureAttempts) Phase ¶
func (a CaptureAttempts) Phase(phase CapturePhase) CaptureAttempt
Phase returns one phase's record.
func (*CaptureAttempts) Set ¶
func (a *CaptureAttempts) Set(phase CapturePhase, attempt CaptureAttempt)
Set replaces one phase's record, leaving the other phase's slot alone.
type CaptureOp ¶
type CaptureOp struct {
Action string `json:"action"`
Type string `json:"type"`
Scene string `json:"scene,omitempty"`
Key string `json:"key"`
Summary string `json:"summary"`
Content string `json:"content"`
Links LinksField `json:"links,omitempty"`
}
CaptureOp is one memory operation parsed from a consolidation reply.
func FilterEvolveOps ¶
func FilterEvolveOps(result CaptureResult) (ops []CaptureOp, skipped int)
FilterEvolveOps restricts a parsed sweep reply to the actions evolve may take: correct and drop. The skipped count lets the caller report what the reply tried outside its contract.
type CapturePhase ¶
type CapturePhase string
CapturePhase names the pass phase a record describes.
const ( CapturePhaseTyped CapturePhase = "typed" CapturePhaseDigest CapturePhase = "digest" )
type CaptureResult ¶
CaptureResult is a parsed consolidation reply. Dropped counts the ops normalization rejected (unknown action, missing key or summary): they are capture's tolerance rule — one malformed field must not lose the rest — and the count lets a caller report what the reply tried.
func ParseCaptureResult ¶
func ParseCaptureResult(raw string) (CaptureResult, error)
ParseCaptureResult parses the model's consolidation JSON, tolerating code fences, surrounding prose, and near-JSON (unquoted keys, single-quoted or curly-quoted strings, trailing commas). Invalid ops are dropped; unparseable JSON is a stable coded error with no model text.
type CaptureState ¶
type CaptureState struct {
LastConsolidatedMessage int `json:"lastConsolidatedMessage"`
// LastDigestMessage is the digest phase's own cursor. It trails
// LastConsolidatedMessage exactly when a digest failed or has not run
// yet, so the window the digest still owes survives a consolidation
// that landed in the same pass. A store written before this field
// reads as zero, so the next due digest covers the bounded window once
// and the cursor catches up.
LastDigestMessage int `json:"lastDigestMessage"`
// LastChainMessage is the revision chain's cursor: how far the
// transcript's edit calls were scraped into chains.jsonl. LastChainSession
// binds it to that transcript: a new session's transcript is a fresh
// history scraped from zero, and a transcript that shrank under its
// marker (compaction) re-scrapes from zero like the consolidation and
// digest markers, so the retained tail bounds the repeat. A store
// written before either field existed catches up over its current
// window once.
LastChainMessage int `json:"lastChainMessage"`
LastChainSession string `json:"lastChainSession,omitempty"`
SessionID string `json:"sessionID,omitempty"`
LastDigestAt time.Time `json:"lastDigestAt"`
LastTypedAt time.Time `json:"lastTypedAt"`
// LastEvolveAt ages the automatic evolve sweep (ultra mode): a store
// written before this field reads as never-swept, so the first eligible
// trigger sweeps once and the stamp catches up.
LastEvolveAt time.Time `json:"lastEvolveAt,omitempty"`
// ChainBackfill records which files' git history the revision chain
// already scraped: "" pending, a commit sha done, "-" no history. A
// store written before the field reads as empty.
ChainBackfill map[string]string `json:"chainBackfill,omitempty"`
// TypedFailures counts consecutive typed passes whose ops all failed;
// the parking signal for a store that cannot land anything.
TypedFailures int `json:"typedFailures"`
}
CaptureState tracks the last capture for one project. SessionID is the session the message marker indexes: a new or resumed session resets the marker, so its opening is captured instead of skipped.
type ChainRevision ¶
type ChainRevision struct {
ID string `json:"id,omitempty"`
Path string `json:"path"`
SessionID string `json:"sessionID,omitempty"`
At time.Time `json:"at"`
OldText string `json:"oldText,omitempty"`
NewText string `json:"newText"`
}
ChainRevision is one applied edit: the file, the session that applied it, and the replaced text pair exactly as the tool call carried them.
type Digest ¶
type Digest struct {
SessionID string
Topic string
Summary string
Date time.Time
Updated time.Time
Fallback bool
Path string
}
Digest is one session handoff record. Date is the session start, Updated is the last capture; retention ages from Updated.
func ParseDigest ¶
ParseDigest reads a digest file. ok is false without a Session line, so a stray Markdown file in the sessions directory is ignored.
func RetainDigests ¶
func RetainDigests(digests []Digest, now time.Time, retention DigestRetention) (keep, archive []Digest)
RetainDigests splits digests into the searchable set and the archive set. The newest digest is always kept, regardless of age.
type DigestRetention ¶
DigestRetention bounds the searchable digest set: the newest MaxCount and no older than TTLDays by last capture. Zero disables a bound.
type EmbeddingProvider ¶
type EmbeddingProvider interface {
Embed(ctx context.Context, texts []string) ([][]float32, error)
Dimensions() int
Name() string
}
The host owns the provider; the engine never loads a model or holds credentials.
func NewDeterministicEmbedder ¶
func NewDeterministicEmbedder(dimensions int) EmbeddingProvider
NewDeterministicEmbedder is deterministic and offline, not a replacement for a real model.
func NewHTTPEmbedder ¶
func NewHTTPEmbedder(config HTTPEmbedConfig) EmbeddingProvider
NewHTTPEmbedder returns an embedder that calls an OpenAI-compatible endpoint.
type Fact ¶
type Fact struct {
Name string // slug; the file's base name and the stable address
Description string // one line; the index hook and recall summary
Type string // user|feedback|project|reference|experience, preserved as read
// Scene is the fact's domain: chat|working|coding, or "" when
// unclassified. Unscoped facts match every scene-scoped search.
Scene string
OriginSessionID string // optional provenance, stamped by capture
// CapturedOn is the creation date (YYYY-MM-DD). Append stamps it and
// replace keeps it, so a fact records when the knowledge was learned
// however often it is corrected.
CapturedOn string
// Links names the facts this one continues, updates, or contradicts.
Links []string
Body string
// Path is the slash-separated directory of the file relative to the
// project directory: "" at the root, "topics/<topic>" inside a topic.
Path string
// ModTime is the file's modification time; zero for facts not read from
// disk. It orders the index, newest first.
ModTime time.Time
// contains filtered or unexported fields
}
Fact is one memory record: a markdown file with frontmatter.
func ParseFact ¶
ParseFact parses fact-file content. Unknown frontmatter keys are ignored; folded (indented continuation) description lines are joined with single spaces.
func PrepareFactForTest ¶
PrepareFactForTest exposes the fact normalizer.
func PrepareForWrite ¶
prepareFact normalizes a fact for writing: the description collapses to one line, an empty type defaults to project, and the name slugs from the given name or the description, falling back to a stable hash of the description when nothing usable remains (non-ASCII descriptions). PrepareForWrite applies the store's write-time normalization to a fact. Adapters that route writes through the engine use it to keep stored facts identical to those written by the store directly.
func (Fact) FallbackName ¶
FallbackName derives a stable name for a fact whose description slugs to nothing (non-ASCII descriptions): the first 8 hex characters of sha256(description), so distinct descriptions stay distinct.
type FactMatch ¶
type FactMatch struct {
Channel string `json:"channel"`
Name string `json:"name"`
Description string `json:"description"`
Path string `json:"path"`
Field string `json:"field"`
Scene string `json:"scene,omitempty"`
Score float64 `json:"score"`
Kind string `json:"kind,omitempty"`
}
FactMatch is one fact search hit. Channel is "project" for a root fact and "topic" for a fact inside a topic directory. Scene is the fact's domain tag; empty means unscoped. Score is the ranking score; only order is contractual, the number is advisory.
type HTTPEmbedConfig ¶
HTTPEmbedConfig identifies a host-supplied embeddings endpoint.
type IndexInput ¶
type IndexInput struct {
Name string
Root string
IndexPath string
Index string // raw MEMORY.md content
Digests []Digest
}
IndexInput is the material the prompt block renders.
type JournalEntry ¶
type JournalEntry struct {
TS time.Time `json:"ts"`
Op string `json:"op"`
Key string `json:"key"`
Old string `json:"old,omitempty"`
New string `json:"new,omitempty"`
Session string `json:"session,omitempty"`
}
JournalEntry is one recorded store mutation. Old and New carry the description before and after when it changed; Session is the fact's OriginSessionID, which both capture and tool writes stamp.
func DecodeJournalLineForTest ¶
func DecodeJournalLineForTest(line string) (JournalEntry, error)
DecodeJournalLineForTest exposes the journal line decoder.
type Limits ¶
type Limits struct {
// ProjectSoftBytes is advisory: it drives the capture "index is nearly
// full" hint and nothing else.
ProjectSoftBytes int
// UserInjectBytes clamps how much of user.md is injected into the
// prompt; the file itself is uncapped.
UserInjectBytes int
// PagesInjectBytes clamps the derived knowledge pages injected into the
// prompt; the page files are write-clamped smaller (page.go).
PagesInjectBytes int
MaxSearchResults int
// MaxDigests caps the searchable digest set: 0 uses the default, and a
// negative value keeps every digest.
MaxDigests int
// DigestTTLDays ages digests out by last capture: 0 uses the default,
// and a negative value disables the age bound.
DigestTTLDays int
ManifestMaxFiles int
ManifestPreviewLines int
ManifestMaxBytes int
}
Limits bounds the read-side and housekeeping surfaces: search result caps, prompt-injection clamps, digest retention, and the capture manifest budgets. Write paths carry no size caps (ADR-005): the only size guard in the system is prompt-injection truncation. One copy lives here so readers cannot drift.
type LinksField ¶
type LinksField []string
LinksField tolerates the two shapes a model writes links in: a JSON array of names or one comma-separated string. Anything else decodes as absent: links are auxiliary, so garbage there must not fail an op that would otherwise land.
func (*LinksField) UnmarshalJSON ¶
func (f *LinksField) UnmarshalJSON(data []byte) error
type ManifestEntry ¶
type ManifestEntry struct {
Name string
Kind string
Description string
ModTime time.Time
Preview string
}
ManifestEntry is one memory file described for the capture prompt.
type Match ¶
type Match struct {
Line int `json:"line"`
Text string `json:"text"`
Context []string `json:"context,omitempty"`
}
Match is one search hit: a 1-based line number plus one line of context on either side.
func SearchLines ¶
SearchLines finds case-insensitive substring matches, capped at max results (non-positive max means no cap).
type MigrateResult ¶
MigrateResult reports what a migration converted.
type Options ¶
type Options struct {
UserDir string
ProjectDir string
Meta ProjectMeta
Now func() time.Time
Limits Limits
SearchBackend string
Embedder EmbeddingProvider
ReadOnly bool
}
Options configures a Store. UserDir holds the global user.md and ProjectDir holds this project's files; Meta is the project identity recorded once in project.json. Now is the injected clock (nil means time.Now) and Limits zero fields fall back to DefaultLimits. ReadOnly skips construction-time legacy migration, so a read-only caller never copies, removes, or rebuilds files under the memory tree.
type Page ¶
type Page struct {
Name string // catalog slug; the file's base name
Question string // the standing question the page answers
Sources []string // cited fact names; empty only for hand-written pages
// SourceHashes holds one hash per source, in Sources order. It makes
// staleness independent of filesystem timestamp resolution.
SourceHashes []string
UpdatedOn string // YYYY-MM-DD stamp of the last regeneration
Body string
// ModTime is the file's modification time; zero for pages not read from
// disk. Staleness compares it against the cited facts' mtimes.
ModTime time.Time
}
Page is one derived knowledge page.
func FilterPageDrafts ¶
func FilterPageDrafts(result PageDraftResult, factNames, requested map[string]bool) (pages []Page, skipped int)
FilterPageDrafts polices parsed drafts against the fact-name snapshot a caller took after the sweep's ops applied, and against the slugs the pass actually requested, so a chatty reply cannot rewrite pages the bound never asked for. A source the snapshot does not name is stripped from the draft; a draft left without any valid source is skipped, so every sweep-written page cites at least one fact that exists. A secret-bearing body is skipped. The skipped count lets the caller report what the reply tried outside its contract.
type PageDraft ¶
type PageDraft struct {
Name string
Sources LinksField
Content string
}
PageDraft is one page op parsed from a page-pass reply.
type PageDraftResult ¶
PageDraftResult is a parsed page reply. Dropped counts the drafts normalization rejected: a slug outside the catalog, or no content.
func ParsePageDrafts ¶
func ParsePageDrafts(raw string) (PageDraftResult, error)
ParsePageDrafts parses the model's page JSON, tolerating code fences, surrounding prose, and near-JSON through the shared capture extractor.
type PageSpec ¶
PageSpec is one catalog entry: the slug and the standing question.
func PageCatalog ¶
func PageCatalog() []PageSpec
PageCatalog returns the fixed page registry in canonical order.
type ProjectMeta ¶
type ProjectMeta struct {
Root string `json:"root"`
Name string `json:"name"`
Slug string `json:"slug"`
CreatedAt time.Time `json:"createdAt"`
}
ProjectMeta is the project.json payload: which canonical root owns this directory, recorded once on first use so /memory and debugging can map a key back to a path.
func ProjectMetaFor ¶
func ProjectMetaFor(root string) ProjectMeta
ProjectMetaFor builds the identity record for root. CreatedAt stays zero until the store stamps it from its injected clock.
type ScoredFactForTest ¶
ScoredFactForTest is the ranked-fact view with exported fields, so a black-box adapter can read the score and the underlying fact without naming the unexported scoredFact.
func RankFactsForTest ¶
func RankFactsForTest(facts []Fact, query string, now time.Time) []ScoredFactForTest
RankFactsForTest runs the fact ranking and converts to the view above. A nil result stays nil, which the tests assert.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store owns every read and write of the memory files. Writers serialize on one mutex and land through a temp file plus rename, so a reader sees the old or the new file, never a partial one. No write is ever refused for size or count (ADR-005): the fact files, the index, user.md, and the digests all grow without caps.
func NewReadOnlyStore ¶
NewReadOnlyStore builds a store that reads memory without migrating a legacy tree. Read-only callers, such as the prompt dump, use it so a seeded legacy store stays byte-for-byte intact.
func NewStore ¶
NewStore builds a store over the given directories. A legacy-format project directory is migrated in place on construction (copy-first); a failed migration is recorded and surfaced by MigrateError.
func (*Store) AppendChainRevisions ¶
func (s *Store) AppendChainRevisions(revisions []ChainRevision) error
AppendChainRevisions appends new revisions in order, rotating at the bound. The whole batch lands through one write, so a failure leaves no partial batch for a retry to duplicate. A revision with an ID already on disk is skipped, so a replay of an applied job cannot double a revision. The caller turns an error into a warning, never a failed phase.
func (*Store) AppendFact ¶
AppendFact writes a new fact, never overwriting: a name taken anywhere in the project gets a numeric suffix, and the fact actually written (with its resolved name) is returned. An empty Path creates at the root; "topics/<topic>" creates inside a topic directory.
func (*Store) AppendUser ¶
AppendUser adds a reasoned entry to the global user memory. The reason is recorded beside the content so a reader can tell durable additions from noise; size is never refused. The per-path lock brackets the read-modify-write so stores sharing this user file serialize on it before their instance mutexes.
func (*Store) ChainPaths ¶
ChainPaths lists the chain's distinct paths, sorted, capped at chainMaxPaths. A decoration sweep walks this list, so the cap keeps the sweep bounded on a store that touched many files.
func (*Store) ChainRevisions ¶
func (s *Store) ChainRevisions(path string, max int) ([]ChainRevision, error)
ChainRevisions returns one path's revisions in write order, capped at the newest max (non-positive max means no cap).
func (*Store) Close ¶
Close releases the derived search index handle. Markdown stays authoritative, so a store without an index needs no cleanup.
func (*Store) CountDanglingLinks ¶
CountDanglingLinks counts distinct link targets that name no fact across the whole project, for the /memory rebuild report.
func (*Store) DeleteFact ¶
DeleteFact removes the fact file with the given name and reports whether it existed. A missing fact is not an error: a drop is maintenance, and the end state it asks for already holds.
func (*Store) DeleteTopic ¶
DeleteTopic removes a topic directory with every fact inside it and reports whether it existed. A missing topic is not an error and records nothing: the end state it asks for already holds.
func (*Store) EditFact ¶
EditFact replaces oldString in a fact's body, returning the number of replacements. Replacement is literal.
func (*Store) EnsureProject ¶
func (s *Store) EnsureProject(meta ProjectMeta) (bool, error)
EnsureProject writes project.json on first use and reports whether it created the file. Later calls keep the original bytes untouched.
func (*Store) IndexBytes ¶
IndexBytes reports the index file's size on disk, for the capture fullness hint and /memory status.
func (*Store) JournalStatus ¶
func (s *Store) JournalStatus() (bytes int, last JournalEntry, ok bool)
JournalStatus reports the journal's size and its last decodable entry. ok is false when no journal exists yet. The read takes the store mutex so it cannot interleave with a rotation.
func (*Store) Limits ¶
Limits returns the resolved bounds (search caps, injection caps, digest retention, manifest budgets).
func (*Store) ListDigests ¶
ListDigests returns the searchable digests, newest capture first. Files without a Session line are ignored.
func (*Store) ListFacts ¶
ListFacts walks the project directory and parses every markdown file except the index: root files are root facts, topics/<topic>/*.md are topic facts, and stray files or directories are skipped so hand-placed content can never break the walk. Newest first, ties by name — the index order.
func (*Store) ListPages ¶
ListPages returns the project's pages, newest UpdatedOn first with catalog order breaking ties. Files outside the catalog are still read (hand-placed files must not break the surface); staleness never rewrites them.
func (*Store) Manifest ¶
func (s *Store) Manifest() ([]ManifestEntry, error)
Manifest builds the project memory file inventory. Durable knowledge files come first, newest first within each kind, so the render byte budget always covers the update-not-duplicate targets before session history. A file that is not a regular file (a planted symlink or a directory) is skipped; a genuine read failure is returned.
func (*Store) ManifestBlock ¶
ManifestBlock returns the rendered inventory for the capture prompt, empty when the project has no memory files.
func (*Store) MarkChainBackfillPending ¶
MarkChainBackfillPending records candidate paths the revision chain has never seen as pending backfill targets. chained is the chain's distinct path set the caller already fetched; a candidate it names is ignored, as is one already marked, and the map caps at chainBackfillMaxEntries. Best effort: a state failure drops the hint.
func (*Store) Meta ¶
func (s *Store) Meta() ProjectMeta
Meta returns the project identity (the zero value before the first EnsureProject).
func (*Store) MigrateError ¶
MigrateError returns the error from the automatic legacy-format migration, if one ran and failed.
func (*Store) MigrateLegacyIfPresent ¶
func (s *Store) MigrateLegacyIfPresent() (MigrateResult, error)
MigrateLegacyIfPresent converts a legacy store and reports what it did. A store already in the per-fact format is untouched.
func (*Store) MoveFactToTopic ¶
MoveFactToTopic moves a fact file into topics/<topic>/ — the demote operation. Moving into the fact's current topic is a no-op; a name collision inside the target gets a numeric suffix. The moved fact is returned.
func (*Store) Ping ¶
Ping reports whether the project directory is writable, so capture parking can distinguish "failed lately" from "cannot ever land a write".
func (*Store) ProjectDir ¶
ProjectDir is the store's project memory directory.
func (*Store) PruneDigests ¶
PruneDigests applies the retention bounds and returns how many files moved to the archive. It is idempotent.
func (*Store) ReadCaptureAttempts ¶
func (s *Store) ReadCaptureAttempts() (CaptureAttempts, error)
ReadCaptureAttempts returns the recorded phases; a missing file is the zero record.
func (*Store) ReadCaptureState ¶
func (s *Store) ReadCaptureState() (CaptureState, error)
ReadCaptureState returns the stored markers; a missing file is zero state.
func (*Store) ReadDigest ¶
ReadDigest returns the digest for one session id.
func (*Store) ReadFact ¶
ReadFact returns the fact with the given name, searching the root first and then the topic directories.
func (*Store) ReadFactWithBytes ¶
ReadFactWithBytes returns a fact and the exact bytes it was parsed from. Enumeration applies the same file checks as ReadFact, and parseFactBytes supplies the fallback name and description for facts without frontmatter.
func (*Store) ReadProjectMeta ¶
func (s *Store) ReadProjectMeta() (ProjectMeta, bool, error)
ReadProjectMeta returns the recorded project identity; exists is false when the project has never been written to.
func (*Store) ReadUserBytes ¶
ReadUserBytes reads user.md through the same file checks as ReadUser and returns the bytes a revision can be computed from. A missing file returns os.ErrNotExist.
func (*Store) RefreshSearch ¶
func (*Store) RegenerateIndex ¶
RegenerateIndex rewrites MEMORY.md from the fact files. /memory rebuild and the migrator use it to re-derive the index after hand edits or conversion.
func (*Store) ResolveLinks ¶
ResolveLinks returns the facts name's links point at, in link order, plus the targets that resolve to nothing. One hop, so cycles cannot occur.
func (*Store) SearchFacts ¶
SearchFacts ranks the corpus against query and caps the results at max (non-positive means no cap). A scene filters the corpus to facts tagged with that scene plus unscoped facts, so a missing tag never hides knowledge; an empty scene searches everything.
func (*Store) SearchUser ¶
SearchUser finds matches in the user memory, capped by MaxSearchResults.
func (*Store) SessionsDir ¶
SessionsDir exposes the digest directory for the project.
func (*Store) SetDigestLimits ¶
SetDigestLimits updates the digest bounds in place. One store is shared by the memory tool, capture, and /memory, and the bounds are settings-driven, so they are refreshed at write time rather than fixed at construction. Zero or negative values keep every digest / disable the age bound.
func (*Store) StalePages ¶
StalePages returns the catalog slugs needing a rewrite, in rewrite order: missing pages first in catalog order, then existing pages whose cited facts dropped or changed, oldest UpdatedOn first. A page with no sources never goes stale, so a hand-written page survives until there is a provable reason to rewrite it.
func (*Store) UpdateCaptureState ¶
func (s *Store) UpdateCaptureState(mutate func(*CaptureState) bool) error
UpdateCaptureState applies mutate to the persisted markers under the store mutex, so a read-modify-write issued from outside the capture pass (the evolve sweep's stamp) cannot revert a concurrent pass's marker advance: the mutex spans the read, the mutation, and the write. Mutate reports whether anything changed; an unchanged state skips the write.
func (*Store) UpdateFact ¶
UpdateFact corrects a fact in place: a non-empty description replaces the old one and non-empty body content replaces the body. A nil links slice keeps the existing links; a non-nil one replaces them (normalized). The fact must exist; nothing is ever refused for size.
func (*Store) UpsertFact ¶
UpsertFact writes fact, replacing an existing fact with the same name in place (at its current location) and creating it otherwise. Capture's add and update ops converge through here. Replacing keeps the existing CapturedOn: a correction does not move the date the knowledge was learned. A body the store already holds under any name is a no-op that returns the existing fact, so a retried or re-derived extraction cannot duplicate knowledge or refresh a file it did not change.
func (*Store) UpsertPage ¶
UpsertPage writes page, replacing the page with the same slug in place. The name must be a catalog slug. The body clamps at maxPageBodyBytes (derived state, so the composition clamp is a write bound), and an empty UpdatedOn stamps from the store clock.
func (*Store) WriteCaptureAttempt ¶
func (s *Store) WriteCaptureAttempt(phase CapturePhase, attempt CaptureAttempt) error
WriteCaptureAttempt persists one phase's record atomically, keeping the other phase's record.
func (*Store) WriteCaptureState ¶
func (s *Store) WriteCaptureState(state CaptureState) error
WriteCaptureState persists the markers atomically.
Source Files
¶
- agent_memory.go
- backfill.go
- capture_apply.go
- capture_attempt.go
- capture_parse.go
- capture_prompt.go
- capture_state.go
- chain.go
- digest.go
- digest_store.go
- edit.go
- embed.go
- embed_http.go
- errors.go
- evolve.go
- export.go
- fact.go
- fact_dedup.go
- fact_links.go
- facts_rank.go
- facts_search.go
- facts_store.go
- holdback.go
- index.go
- journal.go
- limits.go
- manifest.go
- migrator.go
- page.go
- page_evolve.go
- page_store.go
- parse.go
- paths.go
- privacy.go
- project.go
- redact.go
- search.go
- search_dir_unix.go
- search_index.go
- search_privacy.go
- secret.go
- store.go
- terms.go