Documentation
¶
Overview ¶
Package dream implements the /dream memory-consolidation feature's foundation layer: the resolved dream configuration, on-disk run state, and the deterministic due-check that decides whether an auto-trigger is warranted. This layer has no LLM dependency; the runner, scheduler, lock, and plan/apply logic live in this package. See tasks/spec-dream-memory-consolidation.md §3.2/§3.3/§5.1/§5.4.
Index ¶
- Constants
- Variables
- func ResolveMemoryRoot() string
- func SaveState(memoryRoot string, s State) error
- type BackgroundDeps
- type BackgroundSpawn
- type Config
- type ConsolidateInput
- type ConsolidateResult
- type Consolidator
- type DedupeGroup
- type InvalidPathRef
- type Lock
- type MemoryFile
- type NearDupPair
- type NewEntry
- type Plan
- type Report
- type RunOptions
- type Runner
- type Scheduler
- type SessionSource
- type State
Constants ¶
const ( DefaultEnabled = true DefaultIntervalDays = 7 DefaultRecentSessions = 20 )
Built-in defaults for the dream table, exposed so config normalization and tests share one source of truth.
const NearDupThreshold = 0.7
NearDupThreshold is the normalized-token Jaccard similarity at or above which two memory files are emitted as a near-duplicate candidate pair for the later LLM merge-decision step (spec §5.1.1). It is deliberately conservative: this node only PAIRS candidates, it never merges, so a false-positive pair costs only one extra LLM comparison while a missed pair silently loses a merge opportunity.
Variables ¶
var DefaultStaleAfter = 30 * time.Minute
DefaultStaleAfter is how long after a lock's started_at the lock is considered abandoned (e.g. the holder crashed) and may be taken over. See spec §5.4.
var ErrLocked = errors.New("dream: consolidation already running")
ErrLocked is returned by AcquireLock when a live (non-stale) lock is already held by another process. Callers detect it (via errors.Is) to exit "skipped" rather than treating it as a real failure. It is deliberately distinct from the I/O errors AcquireLock may also return.
Functions ¶
func ResolveMemoryRoot ¶
func ResolveMemoryRoot() string
ResolveMemoryRoot returns the persistent memory root directory the same way the CLI does (internal/cli/run.MemoryDir), through the one resolver both use (internal/golderhome). Returns "" when the state root is unresolvable.
Types ¶
type BackgroundDeps ¶
type BackgroundDeps struct {
// MemoryRoot is the dream state root read to decide whether a run is due. It
// must match the root the subprocess consolidates (dream.ResolveMemoryRoot),
// so the parent's Due check sees the same last_run_at the child updates.
MemoryRoot string
// ProjectDir is the working directory attributed to the run (project scope).
ProjectDir string
// Config is the resolved [dream] configuration (enabled / interval).
Config Config
// Now supplies the current time for the due check; nil uses time.Now. It is a
// seam so tests can drive Due deterministically.
Now func() time.Time
// Spawn launches the subprocess. When nil, MaybeRunBackground does nothing.
Spawn BackgroundSpawn
// OnReport is invoked (from the background goroutine) with the completed
// report only when the run produced actual changes — worth a one-line notice.
// A skipped run (another dream held the lock → all-zero report) or a no-op run
// yields no call, keeping the trigger non-intrusive. Nil disables the notice.
OnReport func(Report)
}
BackgroundDeps carries everything MaybeRunBackground needs to decide on and run a startup auto-consolidation without pulling process/exec or presentation concerns into this package.
type BackgroundSpawn ¶
BackgroundSpawn launches one dream consolidation subprocess for projectDir and returns its decoded Report. Implementations live in the CLI layer (they shell out to `golder --dream -C <projectDir>` and parse the stdout Report), so this package stays free of os/exec concerns and there is no import cycle back through the CLI. A non-nil error means the run failed; background failures are silent to the user (the subprocess itself records last_status="failed"), so MaybeRunBackground swallows the error rather than surfacing it.
type Config ¶
Config is the resolved dream configuration with defaults applied. It is the shape the scheduler and runner consume, distinct from the raw config.DreamConfig (which uses *bool / zero to distinguish "unset").
func NewConfig ¶
NewConfig normalizes a raw dream table into a Config, applying defaults: a nil enabled pointer means true (only an explicit false disables); a non-positive interval_days falls back to 7; a non-positive recent_sessions falls back to 20. A missing dream table is representable as the zero arguments (nil, 0, 0) and yields all defaults, so parsing never errors on an absent table.
type ConsolidateInput ¶
type ConsolidateInput struct {
Plan Plan `json:"plan"`
MemoryRoot string `json:"memory_root"`
ProjectDir string `json:"project_dir"`
// Transcripts is the collected, budget-truncated text of the current
// project's recent session JSONL, gathered deterministically by the Runner
// (SPEC §5.3). It is the input to the separate distillation pass; an empty
// string means there is nothing to distill (no matching sessions), so the
// Consolidator skips the distill call entirely (SPEC §5.5 no-op).
Transcripts string `json:"transcripts,omitempty"`
}
ConsolidateInput is the plain-data view handed to the Consolidator. It carries the deterministic Plan (which already embeds the dedupe groups, invalid-path refs and near-dup pairs) plus the resolved roots so the implementation can compute in-scope write targets. It intentionally carries no behavior and no live handles (no *memory.Store, no *sql.DB) so it stays trivially serializable if #523 chooses to marshal it across a subprocess/RPC boundary.
type ConsolidateResult ¶
type ConsolidateResult struct {
// MergedBodies maps an existing memory file path to its rewritten (merged /
// compacted) body. The Runner overwrites each file in place.
MergedBodies map[string]string `json:"merged_bodies,omitempty"`
// Deletions are memory files to remove (entries merged away or pruned as
// stale/contradictory).
Deletions []string `json:"deletions,omitempty"`
// NewEntries are freshly distilled memory files to create.
NewEntries []NewEntry `json:"new_entries,omitempty"`
Merged int `json:"merged"`
Pruned int `json:"pruned"`
Distilled int `json:"distilled"`
Notes []string `json:"notes,omitempty"`
}
ConsolidateResult is the Consolidator's decision set. All paths are absolute and must lie within the memory root scope. Merged/Pruned/Distilled are the report counters the Runner surfaces verbatim; the deterministic Deduped and PathsCleaned counters are computed by the Runner itself, not here.
type Consolidator ¶
type Consolidator interface {
Consolidate(ctx context.Context, in ConsolidateInput) (ConsolidateResult, error)
}
Consolidator is the LLM-driven apply step, injected so the deterministic Runner skeleton can run end-to-end without an LLM. It receives the plain-data plan (dedupe groups + invalid-path refs + near-dup candidate pairs) and returns the semantic decisions: which merged bodies to rewrite, which entries to delete (merged-away / pruned), and which new entries to distill.
#523 will implement a real Consolidator backed by the main-session model and the dream system prompt (SPEC §5.1 step 5, §5.1.1). Until then the Runner uses nopConsolidator, so the deterministic half (exact dedup + path clean + Reconcile) is fully exercised and testable in isolation.
func NewLLMConsolidator ¶
func NewLLMConsolidator(model, baseURL, protocol, providerName, apiKey string, thinking agentcore.ThinkingLevel) (Consolidator, error)
NewLLMConsolidator builds the production Consolidator backed by the given model configuration — the same tuple cmd/golder resolves for the main session (CLI flags overlaid with config.toml). It resolves the Provider once so every Consolidate call reuses it. A resolution failure (bad model / missing provider) is returned so the caller can decide whether to fall back to the no-op Consolidator or fail the run.
type DedupeGroup ¶
DedupeGroup is a set of two or more files whose content is byte-identical (same ContentHash). The apply node keeps one representative and removes the rest; Deduped in the Report counts len(Paths)-1 per group.
type InvalidPathRef ¶
type InvalidPathRef struct {
File string `json:"file"` // memory file containing the reference
Ref string `json:"ref"` // the original (unresolved) reference text
}
InvalidPathRef is a local filesystem path mentioned in a memory file's body that no longer exists on disk. External references (URLs, mailto:, etc.) are never recorded here (spec §5.2 / PRD US-004).
type Lock ¶
type Lock struct {
// contains filtered or unexported fields
}
Lock represents an acquired dream single-instance lock backed by the file <memoryRoot>/global/dream/dream.lock. It guarantees at most one consolidation runs at a time across processes, with crash-safe stale takeover.
func AcquireLock ¶
AcquireLock attempts to acquire the dream single-instance lock under memoryRoot. On success it returns a *Lock the caller must Release (typically via defer). If a live lock is already held it returns ErrLocked. If the existing lock is stale (its started_at is older than now-DefaultStaleAfter) or malformed/unparseable, it is treated as abandoned and taken over. Any other error (permissions, unexpected I/O) is returned as-is so the caller can distinguish it from the ErrLocked "skipped" case.
type MemoryFile ¶
type MemoryFile struct {
Path string // absolute path on disk
Scope string // "global" | "projects"
Type string // layout <type> segment ("" for a file directly under the scope root)
Size int64 // byte size of the file content
ContentHash string // sha256 hex of the raw file content
Body string // full file content (used for path extraction + tokenization)
}
MemoryFile is one enumerated memory file under the global or the active project scope, with the derived metadata the deterministic plan needs. Body is retained so the near-duplicate pairing can tokenize it without a second read.
type NearDupPair ¶
type NearDupPair struct {
A string `json:"a"`
B string `json:"b"`
Similarity float64 `json:"similarity"`
}
NearDupPair is a candidate pair of files whose token-set similarity is at or above NearDupThreshold but whose content is not byte-identical. It is a suggestion for the LLM to decide whether an actual merge is warranted; this node performs no merge.
type NewEntry ¶
NewEntry is a distilled memory file the Consolidator wants created. Path must resolve within the memory root's global/project scope; the Runner rejects any out-of-scope target before writing (SPEC §5.2 / §7.1).
type Plan ¶
type Plan struct {
Files []MemoryFile `json:"files"`
DedupeGroups []DedupeGroup `json:"dedupe_groups"`
InvalidPathRefs []InvalidPathRef `json:"invalid_path_refs"`
NearDupPairs []NearDupPair `json:"near_dup_pairs"`
BytesBefore int64 `json:"bytes_before"`
FilesBefore int `json:"files_before"`
}
Plan is the plain-data output of the deterministic half of a /dream run. It carries no behavior and makes no LLM calls; the later apply node consumes it to drive merges/prunes and to compute the final Report counters.
func BuildPlan ¶
BuildPlan enumerates the consolidation-eligible memory files (global scope + the given project's scope) under memoryRoot and computes the deterministic consolidation plan: exact-dedup groups, invalid local path references, and near-duplicate candidate pairs. It excludes the sessions scope entirely and any file whose layout type is "checkpoint" (session-transient state, not long-term memory — spec §1.3 / §5.1.1).
projectDir is the working directory of the active project; its stable project id (matching internal/memory's resolveProjectId) selects the projects sub-scope. An empty projectDir restricts the plan to the global scope. A missing memoryRoot or scope directory is not an error — it yields an empty plan, mirroring memory.Reconcile's tolerance of an absent root.
type Report ¶
type Report struct {
Merged int `json:"merged"` // entries merged away by the LLM apply step
Deduped int `json:"deduped"` // exact (content-hash) duplicates removed
PathsCleaned int `json:"paths_cleaned"` // stale local path references cleaned
Pruned int `json:"pruned"` // stale/contradictory entries pruned
Distilled int `json:"distilled"` // new memories distilled from session JSONL
BytesBefore int64 `json:"bytes_before"`
BytesAfter int64 `json:"bytes_after"`
FilesBefore int `json:"files_before"`
FilesAfter int `json:"files_after"`
DryRun bool `json:"dry_run"`
Notes []string `json:"notes,omitempty"` // human-readable reasons (prune causes, etc.)
Reconciled struct {
Indexed int `json:"indexed"`
Pruned int `json:"pruned"`
} `json:"reconciled"`
}
Report is the structured change summary produced by a /dream consolidation run. It is persisted inside State.LastReport (state.go) and emitted as a single line of JSON on the child process stdout (spec §4.2). Every count is a deterministic tally the runner fills in after the plan (Go-deterministic) and apply (LLM) phases; the zero value is a valid "nothing changed" report.
The JSON tags match spec §3.2 exactly so the parent process (and any scripted/headless caller) can decode the stdout contract without a shared Go type.
type RunOptions ¶
type RunOptions struct {
DryRun bool
ProjectDir string
// RecentSessions is the first-run distillation window: when dream has never
// run, the most-recent RecentSessions project sessions are distilled (SPEC
// §5.3). Non-positive falls back to DefaultRecentSessions (20).
RecentSessions int
}
RunOptions are the per-invocation parameters mirroring the CLI flags. ProjectDir selects the projects sub-scope (empty → global-only); DryRun analyzes without writing files or updating state (but still takes the lock — SPEC §5.5).
type Runner ¶
type Runner struct {
// Consolidator is the injected LLM apply step; nil selects nopConsolidator.
Consolidator Consolidator
// MemoryRoot overrides the environment-resolved memory root. Empty means
// resolve via ResolveMemoryRoot (GOLDER_HOME / ~/.golder). Tests set it to a temp
// dir; production leaves it empty.
MemoryRoot string
// Sessions is the source of recent session transcripts for the distillation
// pass (SPEC §5.3). nil resolves the default store at $GOLDER_HOME/sessions (or
// ~/.golder/sessions); tests inject a stub. If it cannot be resolved,
// distillation degrades to a no-op rather than failing the run.
Sessions SessionSource
}
Runner is the subprocess-side consolidation entry point (SPEC §2.2 / §5.1). It runs the deterministic plan, delegates semantic merge/prune/distill to an injected Consolidator, applies the results within the memory-root scope, and rebuilds the FTS index via memory.Reconcile. The zero value is usable: an empty MemoryRoot is resolved from the environment and a nil Consolidator falls back to nopConsolidator.
func (*Runner) Run ¶
Run executes one consolidation pass and returns the change Report. The flow is the deterministic algorithm of SPEC §5.1:
open store → resolve memoryRoot → acquire lock (ErrLocked → skipped, no error) → BuildPlan → Consolidate → if !DryRun: apply dedup + path-clean + consolidation → Reconcile → recount → SaveState(ok); if DryRun: counts only, no writes/state.
A held lock is not a failure: Run returns a zero-count Report and a nil error so the caller exits 0 ("skipped"). Genuine errors (I/O, plan, apply) are returned for the caller to map to exit 1 / status "failed".
type Scheduler ¶
type Scheduler struct{}
Scheduler owns the startup auto-trigger decision (SPEC §2.1 Scheduler component). It is stateless: Due reads state.json on demand and MaybeRunBackground spawns at most one background run per call. The single-instance guarantee is enforced by the subprocess's O_EXCL lock, not here — a second trigger simply results in a skipped child.
func (Scheduler) Due ¶
Due reports whether an auto-triggered consolidation is warranted now. It is cheap by design (SPEC §8.2 zero-startup-overhead): when dream is disabled it returns immediately without touching the filesystem; otherwise it reads state.json once and defers to State.Due (which also returns false for a never-run zero LastRunAt, so the first-ever run is never auto-triggered).
func (Scheduler) MaybeRunBackground ¶
func (s Scheduler) MaybeRunBackground(ctx context.Context, deps BackgroundDeps) bool
MaybeRunBackground checks (cheaply) whether a consolidation is due and, if so, spawns it in a detached goroutine and returns immediately — it never blocks the caller, so the first interactive response is never delayed (SPEC FR-4 / §8.2). It returns true when a background run was launched. When dream is disabled or not due it returns false after at most a single state.json read (no goroutine, no subprocess).
On completion the goroutine surfaces a one-line notice via OnReport only for a run that changed something; a skipped run (lock held elsewhere → zero report), a no-op run, or a failed run is silent (SPEC §6.1 background row).
type SessionSource ¶
type SessionSource interface {
List() ([]session.SessionHeader, error)
Load(id string) (session.SessionHeader, agentcore.MessageList, error)
}
SessionSource is the read-only view of the session store the distiller needs: list session headers and load a session's messages. *session.Store satisfies it; tests inject a stub so no real session files (or LLM) are required.
type State ¶
type State struct {
LastRunAt time.Time `json:"last_run_at"`
LastStatus string `json:"last_status"` // "ok" | "failed" | "skipped"
// LastReport holds the structured change report from the last run. It is
// nil until dream has completed at least one non-dry-run pass.
LastReport *Report `json:"last_report,omitempty"`
}
State is the persisted /dream run state, stored as JSON at <memoryRoot>/global/dream/state.json. A zero-value State (LastRunAt zero, empty status, nil report) means dream has never run.
func LoadState ¶
LoadState reads the dream state from <memoryRoot>/global/dream/state.json. A missing file returns a zero-value State (never run) with no error. Corrupt or unreadable JSON is tolerated the same way: the caller gets a zero-value State and no error, so a damaged state file degrades to "never run" rather than breaking dream entirely.
func (State) Due ¶
Due reports whether an auto-triggered consolidation is warranted at now given cfg. It returns true only when dream is enabled and the configured interval has elapsed since the last run. Two cases deliberately return false:
- cfg.Enabled is false: auto-trigger is disabled entirely (US-001).
- a zero LastRunAt (dream has never run): the first-ever run is NOT auto-triggered — the user is prompted to run /dream manually instead — to avoid a cold-start token cost for new users. See spec §11.1.