memory

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: May 26, 2026 License: MIT Imports: 34 Imported by: 0

Documentation

Index

Constants

View Source
const (

	// RecallAugmenterBudget is the declared daemon-side budget for durable
	// memory recall when it participates in the prompt augmentation composite.
	RecallAugmenterBudget = maxRecallCharacters
)

Variables

View Source
var (
	// ErrDreamGateNotSatisfied reports a lock-protected dream run skipped
	// because recall-signal promotion thresholds were not met.
	ErrDreamGateNotSatisfied = errors.New("memory: dream signal gate is not satisfied")
)
View Source
var (
	// ErrLockUnavailable reports that a consolidation run could not obtain the lock.
	ErrLockUnavailable = errors.New("memory: consolidation lock is unavailable")
)
View Source
var (
	// ErrValidation marks memory input and metadata validation failures.
	ErrValidation = errors.New("memory: validation error")
)

Functions

func ConsolidationLockPath

func ConsolidationLockPath(globalDir string) string

ConsolidationLockPath returns the canonical lock path for a global memory directory.

func ConsolidationPrompt

func ConsolidationPrompt() string

ConsolidationPrompt returns the embedded four-phase consolidation prompt.

func FreshnessWarning

func FreshnessWarning(modTime time.Time, now time.Time) string

FreshnessWarning reports whether a memory should be treated as stale.

func NewRecallAugmenter

func NewRecallAugmenter(store *Store) session.PromptInputAugmenter

NewRecallAugmenter returns a bounded prompt augmenter that prepends durable memory recall ahead of the live user message.

func ParseHeader

func ParseHeader(content []byte) (memcontract.Header, error)

ParseHeader decodes and validates memory frontmatter from a raw document.

func RenderRecallPromptSection

func RenderRecallPromptSection(packaged memcontract.Packaged, opts RecallPromptOptions) string

RenderRecallPromptSection renders deterministic Packaged recall output.

Types

type Assembler

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

Assembler loads prompt-safe memory indexes and prepends them to the agent prompt.

func NewAssembler

func NewAssembler(store *Store, opts ...AssemblerOption) *Assembler

NewAssembler constructs a prompt assembler for the provided store.

func (*Assembler) Assemble

func (a *Assembler) Assemble(
	ctx context.Context,
	agent aghconfig.AgentDef,
	workspace *workspacepkg.ResolvedWorkspace,
) (string, error)

Assemble renders the dual-scope memory context ahead of the agent system prompt.

func (*Assembler) PromptSection

func (a *Assembler) PromptSection(ctx context.Context, workspace *workspacepkg.ResolvedWorkspace) (string, error)

PromptSection renders the frozen memory context block without the base agent prompt so it can participate in composed prompt assembly.

func (*Assembler) PromptStartupSection

func (a *Assembler) PromptStartupSection(
	ctx context.Context,
	startup session.StartupPromptContext,
	_ aghconfig.AgentDef,
	workspace *workspacepkg.ResolvedWorkspace,
) (string, error)

PromptStartupSection renders memory using durable startup metadata.

type AssemblerOption

type AssemblerOption func(*Assembler)

AssemblerOption customizes memory startup prompt assembly.

func WithSnapshotProvider

func WithSnapshotProvider(provider SnapshotProvider) AssemblerOption

WithSnapshotProvider lets the assembler source prompt blocks from an active provider.

func WithSnapshotService

func WithSnapshotService(service *SnapshotService) AssemblerOption

WithSnapshotService installs the frozen-snapshot service used by the assembler.

type ConsolidationLock

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

ConsolidationLock coordinates cross-process consolidation runs via a PID file whose mtime doubles as the last successful consolidation timestamp.

func NewConsolidationLock

func NewConsolidationLock(path string) *ConsolidationLock

NewConsolidationLock constructs a lock rooted at path with the default stale age.

func (*ConsolidationLock) LastConsolidatedAt

func (l *ConsolidationLock) LastConsolidatedAt() (time.Time, error)

LastConsolidatedAt returns the lock file mtime, or the zero time when the lock file does not exist.

func (*ConsolidationLock) Release

func (l *ConsolidationLock) Release() error

Release clears the lock PID and leaves the file mtime at the release time.

func (*ConsolidationLock) Rollback

func (l *ConsolidationLock) Rollback(priorMtime time.Time) error

Rollback clears the lock PID and restores the mtime from before acquisition.

func (*ConsolidationLock) TryAcquire

func (l *ConsolidationLock) TryAcquire() (priorMtime time.Time, acquired bool, err error)

TryAcquire attempts to acquire the consolidation lock and returns the prior mtime for rollback when acquisition succeeds.

type DailyLogListQuery

type DailyLogListQuery struct {
	Date        string
	Scope       memcontract.Scope
	WorkspaceID string
	AgentName   string
	AgentTier   memcontract.AgentTier
	Limit       int
}

DailyLogListQuery filters daily memory operation summaries.

type DailyLogRecord

type DailyLogRecord struct {
	Date           string
	Scope          memcontract.Scope
	WorkspaceID    string
	AgentName      string
	AgentTier      memcontract.AgentTier
	OperationCount int
}

DailyLogRecord summarizes memory event activity for one date and selector.

type DecisionApplyResult

type DecisionApplyResult struct {
	Decision memcontract.Decision
	Applied  bool
}

DecisionApplyResult reports one controller-backed mutation application.

type DecisionListQuery

type DecisionListQuery struct {
	Scope       memcontract.Scope
	WorkspaceID string
	AgentName   string
	AgentTier   memcontract.AgentTier
	Operation   string
	Since       time.Time
	Reason      string
	Limit       int
}

DecisionListQuery filters persisted controller decisions.

type DecisionRecord

type DecisionRecord struct {
	Decision    memcontract.Decision
	WorkspaceID string
	AgentName   string
	AgentTier   memcontract.AgentTier
	AppliedAt   *time.Time
}

DecisionRecord is the redaction-safe query model for persisted decisions.

type DecisionRevertResult

type DecisionRevertResult struct {
	DecisionID     string
	TargetFilename string
	Reverted       bool
}

DecisionRevertResult reports one deterministic rollback from memory_decisions.

type DerivedResetResult

type DerivedResetResult struct {
	DeletedRows int
	IndexedRows int
	ResetAt     time.Time
}

DerivedResetResult reports derived-catalog reset work.

type DreamCandidate

type DreamCandidate struct {
	ChunkID            string
	EntryID            string
	WorkspaceID        string
	Scope              memcontract.Scope
	AgentName          string
	AgentTier          memcontract.AgentTier
	Type               memcontract.Type
	Slug               string
	Filename           string
	Title              string
	Body               string
	RecallCount        int
	SessionCount       int
	RecallScore        float64
	LastRecalledAt     time.Time
	FreshnessStartedAt time.Time
	Score              float64
}

DreamCandidate is one unpromoted recall-signal candidate eligible for dreaming.

type DreamGateConfig

type DreamGateConfig struct {
	MinCandidates   int
	MinRecallCount  int
	MinScore        float64
	CandidateLimit  int
	HalfLife        time.Duration
	FrequencyWeight float64
	RelevanceWeight float64
	RecencyWeight   float64
	FreshnessWeight float64
}

DreamGateConfig controls the recall-signal gate that precedes dreaming.

type DreamRunListQuery

type DreamRunListQuery struct {
	Scope       memcontract.Scope
	WorkspaceID string
	AgentName   string
	AgentTier   memcontract.AgentTier
	Limit       int
}

DreamRunListQuery filters dreaming run records.

type DreamRunRecord

type DreamRunRecord struct {
	ID            string
	WorkspaceID   string
	Scope         memcontract.Scope
	AgentName     string
	AgentTier     memcontract.AgentTier
	Status        string
	InputCount    int
	PromotedCount int
	Error         string
	Metadata      map[string]string
	StartedAt     time.Time
	FinishedAt    *time.Time
}

DreamRunRecord is a redaction-safe memory_consolidations query row.

type FrozenSnapshot

type FrozenSnapshot struct {
	ID             string
	SessionID      string
	WorkspaceID    string
	WorkspaceRoot  string
	AgentName      string
	CapturedAt     time.Time
	Generation     uint64
	ControllerMode SnapshotControllerMode
	InheritedFrom  string
	Blocks         []SnapshotBlock
	Header         memcontract.CacheStableHeader
	Section        string
}

FrozenSnapshot is immutable prompt memory captured at a session boot boundary.

func (FrozenSnapshot) Clone

func (s FrozenSnapshot) Clone() FrozenSnapshot

Clone returns a deep copy of the frozen snapshot.

type Option

type Option func(*Service)

Option configures a consolidation Service.

func WithDreamGateConfig

func WithDreamGateConfig(config DreamGateConfig) Option

WithDreamGateConfig overrides recall-signal promotion thresholds for dreaming.

func WithLockPath

func WithLockPath(path string) Option

WithLockPath configures the path to the consolidation lock file.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger injects the logger used for gate evaluation and run lifecycle logs.

func WithMemoryStore

func WithMemoryStore(store *Store) Option

WithMemoryStore wires the memory store used for consolidation-path setup.

func WithMinHours

func WithMinHours(hours float64) Option

WithMinHours overrides the minimum age threshold for the time gate.

func WithMinSessions

func WithMinSessions(count int) Option

WithMinSessions overrides the completed-session threshold for the session gate.

func WithSessionsDir

func WithSessionsDir(path string) Option

WithSessionsDir configures the root directory containing persisted sessions.

func WithWorkspaceResolver

func WithWorkspaceResolver(resolver workspacepkg.RuntimeResolver) Option

WithWorkspaceResolver wires workspace resolution for consolidation runs that need a workspace root path.

type PromptSnapshotRequest

type PromptSnapshotRequest struct {
	SessionID      string
	WorkspaceID    string
	WorkspaceRoot  string
	AgentName      string
	SessionType    session.Type
	ParentSnapshot *FrozenSnapshot
}

PromptSnapshotRequest identifies the session boot boundary being captured.

type RecallPromptOptions

type RecallPromptOptions struct {
	MaxEntries    int
	MaxCharacters int
}

RecallPromptOptions controls prompt rendering for Packaged recall output.

type ReplayResult

type ReplayResult struct {
	Applied   int
	Stamped   int
	Reindexed int
}

ReplayResult reports boot-time recovery work applied from memory_decisions.

type Service

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

Service evaluates consolidation gates and runs the dream worker when the lock and thresholds allow it.

func NewService

func NewService(opts ...Option) *Service

NewService constructs a Service with default gate thresholds and prompt.

func (*Service) Run

func (s *Service) Run(ctx context.Context, spawn SessionSpawner, workspaceRef string) error

Run acquires the consolidation lock when needed and invokes the spawner with the embedded prompt and a normalized workspace ID when provided.

func (*Service) ShouldRun

func (s *Service) ShouldRun() (bool, error)

ShouldRun evaluates the time and session gates in that order.

type SessionSpawner

type SessionSpawner func(ctx context.Context, goal, prompt, workspaceID string, lastConsolidatedAt time.Time) error

SessionSpawner starts a one-shot consolidation session with the provided goal, prompt, and normalized workspace ID. A blank workspace ID lets the spawner derive the eligible workspaces itself using the supplied timestamp from the most recent successful consolidation.

type SnapshotBlock

type SnapshotBlock struct {
	Scope     memcontract.Scope
	AgentTier memcontract.AgentTier
	Title     string
	Markdown  string
	AgeMs     int64
	Truncated bool
	Hash      string
}

SnapshotBlock is one prompt-safe memory block captured at session boot.

type SnapshotControllerMode

type SnapshotControllerMode string

SnapshotControllerMode describes the write posture attached to a captured snapshot.

const (
	// SnapshotControllerWritable allows root sessions to propose memory writes.
	SnapshotControllerWritable SnapshotControllerMode = "writable"
	// SnapshotControllerReadOnly marks inherited sub-agent snapshots as non-mutating.
	SnapshotControllerReadOnly SnapshotControllerMode = "read_only"
)

type SnapshotProvider

type SnapshotProvider interface {
	SystemPromptBlock(ctx context.Context, req memcontract.SnapshotRequest) (memcontract.SnapshotResult, error)
}

SnapshotProvider supplies prompt-safe provider blocks for frozen snapshots.

type SnapshotService

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

SnapshotService captures prompt-safe memory once per session boot.

func NewSnapshotService

func NewSnapshotService(store *Store, opts ...SnapshotServiceOption) *SnapshotService

NewSnapshotService constructs a frozen memory snapshot service.

func (*SnapshotService) Capture

Capture freezes prompt-safe memory for the supplied session boot request.

func (*SnapshotService) InheritForSubAgent

func (s *SnapshotService) InheritForSubAgent(parent FrozenSnapshot, req PromptSnapshotRequest) FrozenSnapshot

InheritForSubAgent clones a parent snapshot without re-resolving memory state.

func (*SnapshotService) InvalidateNextBoot

func (s *SnapshotService) InvalidateNextBoot() uint64

InvalidateNextBoot records that future session boots must recapture memory.

type SnapshotServiceOption

type SnapshotServiceOption func(*SnapshotService)

SnapshotServiceOption customizes frozen snapshot capture.

func WithProviderSnapshotSource

func WithProviderSnapshotSource(provider SnapshotProvider) SnapshotServiceOption

WithProviderSnapshotSource installs the active provider snapshot source.

func WithSnapshotClock

func WithSnapshotClock(now func() time.Time) SnapshotServiceOption

WithSnapshotClock injects a deterministic capture clock.

func WithSnapshotMaxCharacters

func WithSnapshotMaxCharacters(maxCharacters int) SnapshotServiceOption

WithSnapshotMaxCharacters caps the rendered memory prompt section.

type Store

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

Store manages memory files for the global and workspace scopes.

func NewStore

func NewStore(globalDir string, opts ...StoreOption) *Store

NewStore constructs a Store for the provided global memory directory.

func (*Store) ApplyDecision

func (s *Store) ApplyDecision(ctx context.Context, decision memcontract.Decision) (DecisionApplyResult, error)

ApplyDecision persists the Decision WAL row before applying the corresponding file mutation.

func (*Store) Candidates

func (s *Store) Candidates(
	ctx context.Context,
	query memcontract.Query,
	opts memcontract.RecallOptions,
) ([]memoryrecall.Candidate, error)

Candidates implements recall.Source on top of the derived chunk catalog.

func (*Store) CloseRecallSignalRecorders

func (s *Store) CloseRecallSignalRecorders(ctx context.Context) error

CloseRecallSignalRecorders drains and stops every async recall-signal worker.

func (*Store) Delete

func (s *Store) Delete(scope memcontract.Scope, filename string) error

Delete removes a memory file and strips any matching entry from the local MEMORY.md index.

func (*Store) EnsureDirs

func (s *Store) EnsureDirs() error

EnsureDirs creates the configured memory directories when missing.

func (*Store) Exists

func (s *Store) Exists(scope memcontract.Scope, filename string) (bool, error)

Exists reports whether a memory file exists in the requested scope.

func (*Store) ForAgent

func (s *Store) ForAgent(workspaceID string, agentName string, tier memcontract.AgentTier) *Store

ForAgent returns a clone of the store bound to one agent memory tier.

func (*Store) ForWorkspace

func (s *Store) ForWorkspace(workspaceRoot string) *Store

ForWorkspace returns a clone of the store bound to the supplied workspace root.

func (*Store) HealthStats

func (s *Store) HealthStats(ctx context.Context, workspaces []string) (memcontract.HealthStats, error)

HealthStats returns derived-catalog stats for the visible scopes.

func (*Store) History

History returns durable memory operation history ordered newest-first.

func (*Store) List

func (s *Store) List(scope memcontract.Scope) ([]memcontract.Header, error)

List is the backend-aligned alias for Scan.

func (*Store) ListDailyLogRecords

func (s *Store) ListDailyLogRecords(ctx context.Context, query DailyLogListQuery) ([]DailyLogRecord, error)

ListDailyLogRecords returns memory-event daily summaries ordered newest first.

func (*Store) ListDecisionRecords

func (s *Store) ListDecisionRecords(ctx context.Context, query DecisionListQuery) ([]DecisionRecord, error)

ListDecisionRecords returns persisted controller decisions ordered newest first.

func (*Store) ListDreamRunRecords

func (s *Store) ListDreamRunRecords(ctx context.Context, query DreamRunListQuery) ([]DreamRunRecord, error)

ListDreamRunRecords returns persisted dreaming runs ordered newest first.

func (*Store) ListMemoryEventSummaries

func (s *Store) ListMemoryEventSummaries(
	ctx context.Context,
	workspaces []string,
	query storepkg.EventSummaryQuery,
) ([]storepkg.EventSummary, error)

ListMemoryEventSummaries returns canonical memory events from every visible memory authority, keeping workspace DB rows visible to observe adapters.

func (*Store) ListTargets

func (s *Store) ListTargets(ctx context.Context, candidate memcontract.Candidate) ([]controller.Target, error)

func (*Store) LoadDecisionRecord

func (s *Store) LoadDecisionRecord(ctx context.Context, id string) (DecisionRecord, error)

LoadDecisionRecord returns one persisted controller decision.

func (*Store) LoadDreamRunRecord

func (s *Store) LoadDreamRunRecord(ctx context.Context, id string) (DreamRunRecord, error)

LoadDreamRunRecord returns one persisted dreaming run.

func (*Store) LoadIndex

func (s *Store) LoadIndex(scope memcontract.Scope) (content string, truncated bool, err error)

LoadIndex reads MEMORY.md for a scope and truncates it to the prompt-safe limits.

func (*Store) LoadPromptIndex

func (s *Store) LoadPromptIndex(scope memcontract.Scope) (content string, truncated bool, err error)

LoadPromptIndex is the backend-aligned alias for LoadIndex.

func (*Store) ProposeCandidate

func (s *Store) ProposeCandidate(
	ctx context.Context,
	candidate memcontract.Candidate,
) (memcontract.Decision, error)

ProposeCandidate decides and applies one already-structured memory candidate.

func (*Store) ProposeDelete

func (s *Store) ProposeDelete(
	ctx context.Context,
	scope memcontract.Scope,
	filename string,
	origin memcontract.Origin,
) (DecisionApplyResult, error)

ProposeDelete decides and applies a controller-backed memory delete.

func (*Store) ProposeWrite

func (s *Store) ProposeWrite(
	ctx context.Context,
	scope memcontract.Scope,
	filename string,
	content []byte,
	origin memcontract.Origin,
) (DecisionApplyResult, error)

ProposeWrite decides and applies a controller-backed memory write.

func (*Store) Read

func (s *Store) Read(scope memcontract.Scope, filename string) ([]byte, error)

Read returns the raw file contents for a memory file in the requested scope.

func (*Store) Recall

Recall returns prompt-ready deterministic memory recall output.

func (*Store) RecallSignalRecorderStats

func (s *Store) RecallSignalRecorderStats(workspaceID string) memoryrecall.SignalRecorderStats

RecallSignalRecorderStats returns per-workspace async signal recorder counters.

func (*Store) RecordExtractorEvent

func (s *Store) RecordExtractorEvent(ctx context.Context, event memoryextractor.Event) error

RecordExtractorEvent persists canonical extractor telemetry into memory_events.

func (*Store) RecordMemoryWriteRejected

func (s *Store) RecordMemoryWriteRejected(ctx context.Context, event WriteRejectedEvent) error

RecordMemoryWriteRejected emits an audit event for denied direct write attempts.

func (*Store) RecordRecall

func (s *Store) RecordRecall(ctx context.Context, signals []memoryrecall.Signal) error

RecordRecall persists live recall signals for later dreaming gates.

func (*Store) RecordRecallExecuted

func (s *Store) RecordRecallExecuted(ctx context.Context, query memcontract.Query, resultCount int) error

func (*Store) RecordRecallSignalDropped

func (s *Store) RecordRecallSignalDropped(
	ctx context.Context,
	query memcontract.Query,
	signals []memoryrecall.Signal,
	queueDepth int,
) error

func (*Store) RecordRecallSignalFailed

func (s *Store) RecordRecallSignalFailed(ctx context.Context, query memcontract.Query, cause error) error

func (*Store) RecordRecallSkipped

func (s *Store) RecordRecallSkipped(ctx context.Context, query memcontract.Query, reason string) error

func (*Store) RecordShadow

func (s *Store) RecordShadow(ctx context.Context, shadow memoryrecall.Shadow) error

func (*Store) Reindex

Reindex rebuilds the derived catalog from the Markdown source of truth.

func (*Store) ReplayPendingDecisions

func (s *Store) ReplayPendingDecisions(ctx context.Context) (ReplayResult, error)

ReplayPendingDecisions applies unapplied memory_decisions rows idempotently.

func (*Store) ResetDerived

func (s *Store) ResetDerived(ctx context.Context, opts memcontract.ReindexOptions) (DerivedResetResult, error)

ResetDerived clears derived catalog rows and rebuilds them from Markdown sources.

func (*Store) RevertDecision

func (s *Store) RevertDecision(ctx context.Context, id string) (DecisionRevertResult, error)

RevertDecision restores curated Markdown from one previously applied Decision row.

func (*Store) Scan

func (s *Store) Scan(scope memcontract.Scope) ([]memcontract.Header, error)

Scan lists memory headers for a scope, sorted newest-first and capped at 200 files.

func (*Store) Search

func (s *Store) Search(
	ctx context.Context,
	query string,
	opts memcontract.SearchOptions,
) ([]memcontract.SearchResult, error)

Search performs bounded lexical memory search across the visible scopes.

func (*Store) Write

func (s *Store) Write(scope memcontract.Scope, filename string, content []byte) error

Write validates the memory frontmatter and persists the raw file contents atomically.

type StoreOption

type StoreOption func(*Store)

StoreOption customizes a Store instance.

func WithCatalogDatabasePath

func WithCatalogDatabasePath(path string) StoreOption

WithCatalogDatabasePath enables the derived SQLite-backed memory catalog in the shared global database file.

func WithRecallSignalRecorderConfig

func WithRecallSignalRecorderConfig(config aghconfig.MemoryRecallSignalsConfig) StoreOption

WithRecallSignalRecorderConfig configures asynchronous recall-signal writes.

type WriteRejectedEvent

type WriteRejectedEvent struct {
	Scope       memcontract.Scope
	WorkspaceID string
	AgentName   string
	AgentTier   memcontract.AgentTier
	SessionID   string
	ActorKind   string
	TargetID    string
	Reason      string
	ToolID      string
}

WriteRejectedEvent captures denied direct memory-write attempts.

Directories

Path Synopsis
Package contract defines the shared Memory v2 data contract.
Package contract defines the shared Memory v2 data contract.
Package prompts provides explicit, versioned Memory v2 prompt assets.
Package prompts provides explicit, versioned Memory v2 prompt assets.
provider
Package scan provides deterministic Memory v2 pre-write content checks.
Package scan provides deterministic Memory v2 pre-write content checks.

Jump to

Keyboard shortcuts

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