memory

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 29 Imported by: 0 modules, 0 packages

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

Documentation

Index

Constants

View Source
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.

View Source
const (
	ArchiveDigestKeepForTest  = archiveDigestKeep
	JournalPrevFileForTest    = journalPrevFile
	JournalRotateBytesForTest = journalRotateBytes
	MaxFactLinksForTest       = maxFactLinks
	MaxFactNameBytesForTest   = maxFactNameBytes
)

The caps and filenames the tests pin.

View Source
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.

View Source
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.

View Source
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.

View Source
const (
	DefaultProjectSoftBytes     = 16 * 1024
	DefaultUserInjectBytes      = 4 * 1024
	DefaultPagesInjectBytes     = 10 * 1024
	DefaultMaxSearchResults     = 50
	DefaultMaxDigests           = 20
	DefaultDigestTTLDays        = 30
	DefaultManifestMaxFiles     = 200
	DefaultManifestPreviewLines = 30
	DefaultManifestMaxBytes     = 6 * 1024
)
View Source
const (
	ManifestKindIndex  = "index"
	ManifestKindFact   = "fact"
	ManifestKindDigest = "digest"
)

Manifest kinds label one memory file in the inventory.

View Source
const (
	SearchBackendSQLite = "sqlite"
	SearchBackendHybrid = "hybrid"
)
View Source
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).

View Source
const CaptureConsolidationPrompt = `` /* 3394-byte string literal not displayed */

CaptureConsolidationPrompt asks for durable project memory operations.

View Source
const CaptureDigestPrompt = `` /* 510-byte string literal not displayed */

CaptureDigestPrompt asks for a short session handoff digest.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
const FactNodeType = "memory"

FactNodeType is the fixed node_type every writer stamps, matching the ZCode files the format conforms to.

View Source
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.

View Source
const MinDigestSummaryBytes = 20

MinDigestSummaryBytes is the shortest summary worth storing.

View Source
const RedactedPlaceholder = "[redacted]"

RedactedPlaceholder replaces secret-like matches.

Variables

This section is empty.

Functions

func AgentMemoriesRoot

func AgentMemoriesRoot(agentDir string) string

AgentMemoriesRoot is the parent of every agent memory directory.

func AgentMemoryPromptSection

func AgentMemoryPromptSection(indexContent string, readErr error) string

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

func AgentMemoryRoot(agentDir, key string) string

AgentMemoryRoot is the memory directory for one agent key.

func ApplyCaptureOp

func ApplyCaptureOp(s *Store, op CaptureOp, originSession string, capturedOn time.Time) error

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

func ApplyEdit(content, oldString, newString string, replaceAll bool) (string, int, error)

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

func ArchiveDir(projectDir string) string

ArchiveDir is the project snapshot directory.

func ArchiveSessionsDir

func ArchiveSessionsDir(projectDir string) string

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

func CaptureAttemptFile(projectDir string) string

CaptureAttemptFile is the persisted last-capture-phase record.

func CaptureStateFile

func CaptureStateFile(projectDir string) string

CaptureStateFile is the persisted capture-marker file.

func ChainBackfillCandidates

func ChainBackfillCandidates(text, root string, max int) []string

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 ChainFile

func ChainFile(projectDir string) string

ChainFile is the project revision chain path.

func CodeOf

func CodeOf(err error) string

CodeOf returns the memory code for err, or CodeIO for anything else.

func CollapseLine

func CollapseLine(s string) string

CollapseLine flattens whitespace runs into single spaces and trims.

func ContainPathForTest

func ContainPathForTest(root, name string) (string, error)

ContainPathForTest exposes the path containment check.

func CountFacts

func CountFacts(projectDir string) (int, error)

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

func DetectProjectRoot(cwd string) (string, error)

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

func DigestLine(field string) string

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

func DigestUsable(digest Digest) bool

DigestUsable reports whether a digest carries enough content to store.

func ExtractJSONObjectForTest

func ExtractJSONObjectForTest(raw string) (string, error)

ExtractJSONObjectForTest exposes the JSON object slicer.

func FactSlug

func FactSlug(text string) string

FactSlug slugs a fact name: lowercase [a-z0-9] runs joined by single dashes, capped at maxFactNameBytes.

func FormatDigest

func FormatDigest(digest Digest) string

FormatDigest renders the canonical digest file.

func FormatFact

func FormatFact(fact Fact) string

FormatFact renders the canonical fact file. The description is collapsed to one line; an empty body emits the frontmatter block only.

func FormatPage

func FormatPage(page Page) string

FormatPage renders the canonical page file. An empty body emits the frontmatter block only.

func HeadBytes

func HeadBytes(s string, max int) (string, bool)

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 IndexFile

func IndexFile(projectDir string) string

IndexFile is the project index (MEMORY.md) path.

func IsFullyPrivate

func IsFullyPrivate(content string) bool

IsFullyPrivate reports whether nothing survives redaction.

func JournalFile

func JournalFile(projectDir string) string

JournalFile is the project change journal path.

func ManifestKindRankForTest

func ManifestKindRankForTest(kind string) int

ManifestKindRankForTest exposes the manifest kind ordering.

func MemoryRoot

func MemoryRoot(agentDir string) string

MemoryRoot is the parent of user.md and projects/ under the agent dir.

func NextKey

func NextKey(existing map[string]bool, base string) string

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

func NormalizeFactType(raw string) string

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

func NormalizeNewlines(s string) string

NormalizeNewlines folds CRLF and lone CR to LF so parsers see one shape.

func NormalizeScene

func NormalizeScene(raw string) string

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

func PageQuestion(name string) (string, bool)

PageQuestion returns the standing question for a catalog slug.

func PagesDir

func PagesDir(projectDir string) string

PagesDir holds the derived knowledge pages. Engine state outside format v1: external readers must ignore the directory.

func ParseCaptureDigest

func ParseCaptureDigest(raw string) (topic, summary string, err error)

ParseCaptureDigest parses the model's digest JSON.

func ProjectDir

func ProjectDir(agentDir, root string) string

ProjectDir is the per-project memory directory under the agent dir.

func ProjectDirForKey

func ProjectDirForKey(agentDir, key string) string

ProjectDirForKey is the memory directory for a workspace key: ProjectKey(root) or an explicit, path-safe workspace id.

func ProjectKey

func ProjectKey(root string) string

ProjectKey returns the stable "<slug>-<hash8>" directory name for a canonical project root.

func ProjectMetaFile

func ProjectMetaFile(projectDir string) string

ProjectMetaFile is the project identity record written once per project.

func Redact

func Redact(text string) string

Redact replaces every secret-like match with the placeholder.

func RenderIndex

func RenderIndex(facts []Fact) string

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

func RepairJSONEscapesForTest(payload string) string

RepairJSONEscapesForTest exposes the escape repairer.

func SanitizeAgentMemoryKey

func SanitizeAgentMemoryKey(name string) string

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

func SecretHoldback(s string) int

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

func SecretLike(text string) bool

SecretLike reports whether text carries a secret-like pattern.

func SecretPatterns

func SecretPatterns() []*regexp.Regexp

SecretPatterns exposes the secret matchers for the obfuscation pass, which needs spans (not just a verdict) to mint placeholders.

func SessionsDir

func SessionsDir(projectDir string) string

SessionsDir is the per-session digest directory.

func SlugKey

func SlugKey(text string, max int) string

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

func SlugifyForTest(name string) string

SlugifyForTest exposes the name slugifier.

func StripPrivateContent

func StripPrivateContent(content string) string

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

func TailBytes(s string, max int) (string, bool)

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 TopicsDir

func TopicsDir(projectDir string) string

TopicsDir is the project topic directory.

func TruncateIndex

func TruncateIndex(content string) string

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 UserFile

func UserFile(memoryRoot string) string

UserFile is the global user memory file inside the memory root.

func ValidTopicName

func ValidTopicName(name string) bool

ValidTopicName reports whether name is a legal topic directory name.

func ValidateFactName

func ValidateFactName(name string) error

ValidateFactName rejects names whose files collide with store-owned files.

func ValidateFactPath

func ValidateFactPath(path string) error

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

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

type CaptureResult struct {
	Ops     []CaptureOp
	Reason  string
	Dropped int
}

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

func ParseDigest(content, path string) (Digest, bool)

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

type DigestRetention struct {
	MaxCount int
	TTLDays  int
}

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 Error

type Error struct {
	Code    string
	Message string
}

Error is a memory failure with a stable code for tool results.

func Errorf

func Errorf(code, format string, args ...any) *Error

Errorf builds a coded error.

func (*Error) Error

func (e *Error) Error() string

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

func ParseFact(content string) Fact

ParseFact parses fact-file content. Unknown frontmatter keys are ignored; folded (indented continuation) description lines are joined with single spaces.

func PrepareFactForTest

func PrepareFactForTest(fact Fact) Fact

PrepareFactForTest exposes the fact normalizer.

func PrepareForWrite

func PrepareForWrite(fact Fact) Fact

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

func (f Fact) FallbackName() string

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.

func (Fact) FileName

func (f Fact) FileName() string

FileName is the fact's file name, including the markdown extension.

func (Fact) RelPath

func (f Fact) RelPath() string

RelPath is the file's path relative to the project directory.

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

type HTTPEmbedConfig struct {
	BaseURL    string
	Model      string
	APIKey     string
	Dimensions int
}

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.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns the shipped bounds.

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

func SearchLines(content, query string, max int) []Match

SearchLines finds case-insensitive substring matches, capped at max results (non-positive max means no cap).

type MigrateResult

type MigrateResult struct {
	Facts             int
	CorrectionsFolded int
	StaleCorrections  int
	Topics            int
}

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.

func ParsePage

func ParsePage(content string) Page

type PageDraft

type PageDraft struct {
	Name    string
	Sources LinksField
	Content string
}

PageDraft is one page op parsed from a page-pass reply.

type PageDraftResult

type PageDraftResult struct {
	Drafts  []PageDraft
	Reason  string
	Dropped int
}

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

type PageSpec struct {
	Name     string
	Question string
}

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

type ScoredFactForTest struct {
	Fact  Fact
	Score float64
	Field string
}

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

func NewReadOnlyStore(opts Options) *Store

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

func NewStore(opts Options) *Store

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

func (s *Store) AppendFact(fact Fact) (Fact, error)

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

func (s *Store) AppendUser(reason, content string) (int, error)

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

func (s *Store) ChainPaths() ([]string, error)

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

func (s *Store) Close() error

Close releases the derived search index handle. Markdown stays authoritative, so a store without an index needs no cleanup.

func (s *Store) CountDanglingLinks() (int, error)

CountDanglingLinks counts distinct link targets that name no fact across the whole project, for the /memory rebuild report.

func (*Store) DeleteFact

func (s *Store) DeleteFact(name string) (bool, error)

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

func (s *Store) DeleteTopic(topic string) (bool, error)

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

func (s *Store) EditFact(name, oldString, newString string, replaceAll bool) (Fact, int, error)

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

func (s *Store) IndexBytes() (int, error)

IndexBytes reports the index file's size on disk, for the capture fullness hint and /memory status.

func (*Store) IndexPath

func (s *Store) IndexPath() string

IndexPath is the project index (MEMORY.md) path.

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

func (s *Store) Limits() Limits

Limits returns the resolved bounds (search caps, injection caps, digest retention, manifest budgets).

func (*Store) ListDigests

func (s *Store) ListDigests() ([]Digest, error)

ListDigests returns the searchable digests, newest capture first. Files without a Session line are ignored.

func (*Store) ListFacts

func (s *Store) ListFacts() ([]Fact, error)

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

func (s *Store) ListPages() ([]Page, error)

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

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

ManifestBlock returns the rendered inventory for the capture prompt, empty when the project has no memory files.

func (*Store) MarkChainBackfillPending

func (s *Store) MarkChainBackfillPending(candidates []string, chained map[string]bool)

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

func (s *Store) MigrateError() error

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

func (s *Store) MoveFactToTopic(name, topic string) (Fact, error)

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

func (s *Store) Ping() error

Ping reports whether the project directory is writable, so capture parking can distinguish "failed lately" from "cannot ever land a write".

func (*Store) ProjectDir

func (s *Store) ProjectDir() string

ProjectDir is the store's project memory directory.

func (*Store) PruneDigests

func (s *Store) PruneDigests() (int, error)

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

func (s *Store) ReadDigest(sessionID string) (Digest, error)

ReadDigest returns the digest for one session id.

func (*Store) ReadFact

func (s *Store) ReadFact(name string) (Fact, error)

ReadFact returns the fact with the given name, searching the root first and then the topic directories.

func (*Store) ReadFactWithBytes

func (s *Store) ReadFactWithBytes(name string) (Fact, []byte, error)

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

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

ReadIndex returns the raw MEMORY.md content, or "" when absent.

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

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

ReadUser returns the global user memory, or "" when absent.

func (*Store) ReadUserBytes

func (s *Store) ReadUserBytes() ([]byte, error)

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 (s *Store) RefreshSearch() error

func (*Store) RegenerateIndex

func (s *Store) RegenerateIndex() error

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 (s *Store) ResolveLinks(name string) ([]Fact, []string, error)

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

func (s *Store) SearchFacts(query, scene string, max int) ([]FactMatch, error)

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

func (s *Store) SearchUser(query string) ([]Match, error)

SearchUser finds matches in the user memory, capped by MaxSearchResults.

func (*Store) SessionsDir

func (s *Store) SessionsDir() string

SessionsDir exposes the digest directory for the project.

func (*Store) SetDigestLimits

func (s *Store) SetDigestLimits(maxDigests, ttlDays int)

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

func (s *Store) StalePages() ([]string, error)

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

func (s *Store) TopicDirs() ([]string, error)

TopicDirs lists the addressable topic directory names.

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

func (s *Store) UpdateFact(name, description, body string, links []string) (Fact, error)

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

func (s *Store) UpsertFact(fact Fact) (Fact, error)

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

func (s *Store) UpsertPage(page Page) (Page, error)

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

func (s *Store) UserPath() string

UserPath is the global user memory file path.

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.

func (*Store) WriteDigest

func (s *Store) WriteDigest(digest Digest) (string, error)

WriteDigest stores one digest, overwriting the session's previous file, then prunes best-effort. The written path is returned.

Jump to

Keyboard shortcuts

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