Documentation
¶
Overview ¶
Package reflection implements the Engram Reflection Engine v1.
The Reflection Engine periodically synthesizes high-level insights from unreflected memories, inspired by the Generative Agents paper. It runs lighter and more frequently than the Dream Engine (1-3x/day vs 1x/day), and focuses on cross-domain pattern discovery rather than same-tag dedup.
Trigger: accumulated importance of unreflected memories >= threshold (default: 40). Min interval: 2h. Max per day: 3 runs.
Output: TypeInsight memories with source="system", tagged with metadata.reflection_source_ids and metadata.reflected=true on source memories.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CheckResult ¶
type CheckResult struct {
ShouldTrigger bool `json:"should_trigger"`
SkipReason string `json:"skip_reason,omitempty"`
UnreflectedCount int `json:"unreflected_count"`
AccumulatedImportance float64 `json:"accumulated_importance"`
Threshold float64 `json:"threshold"`
HoursSinceLastRun float64 `json:"hours_since_last_run"`
RunsToday int `json:"runs_today"`
}
CheckResult is the output of a trigger check.
type Config ¶
type Config struct {
// Threshold is the cumulative importance of unreflected memories required
// to trigger a reflection run. Default: 40.
Threshold float64
// MaxInputSize is the maximum number of memories to feed into one reflection
// cycle. Default: 20.
MaxInputSize int
// MinIntervalH is the minimum hours between reflection runs. Default: 2.
MinIntervalH float64
// DryRun disables all writes (no new insights, no marking as reflected).
DryRun bool
// Force bypasses min-interval and daily-limit gates (Gate 1 & 2).
Force bool
// Mode selects the reflection algorithm: "v1" (flat, default) or "v2" (focal point).
// V2 requires 4x Haiku calls but produces higher-quality insights.
Mode string
// FocalInputSize is the number of unreflected memories fed to focal question
// generation (Step 1 of V2). Default: 50.
FocalInputSize int
// FocalQuestions is the number of focal questions to generate in V2. Default: 3.
FocalQuestions int
// EvidencePerFocal is the number of memories retrieved per focal question
// via semantic search in V2. Default: 10.
EvidencePerFocal int
// AllowedProvenances is a whitelist of provenance values for evidence filtering.
// Only used when RequireProvenance is true.
AllowedProvenances []string
// RequireProvenance enables provenance-based filtering in evidence retrieval.
// Default: false (provenance P0 not yet landed).
RequireProvenance bool
// EvidenceSearchTimeout is the per-question store.Search timeout. Default: 3s, hard max: 10s.
EvidenceSearchTimeout time.Duration
// FocalModelStep3 is the model ID for Part3 dialectic LLM calls. Default: Haiku.
FocalModelStep3 string
// DialecticTimeout is the per-question LLM call timeout for Part3. Default: 15s, hard max: 30s.
DialecticTimeout time.Duration
// MinInsightConfidence is the minimum confidence for a dialectic insight to
// be written back to the store. Below this → counted as Skipped. Default: 0.5.
MinInsightConfidence float64
// WriteBackTimeout is the total timeout for Stage 4 write-back. Default: 30s, hard max: 120s.
WriteBackTimeout time.Duration
// DebugEvidence enables per-question evidence retrieval diagnostics in RunResult.
DebugEvidence bool
}
Config holds Reflection Engine runtime configuration.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns the default Reflection Engine configuration.
type DialecticInsight ¶ added in v0.2.0
type DialecticInsight struct {
Question string `json:"question"`
Content string `json:"content"`
Tensions []string `json:"tensions"`
SourceIDs []string `json:"source_ids"`
Confidence float64 `json:"confidence"`
Importance int `json:"importance"`
Tags []string `json:"tags"`
}
DialecticInsight is the output of a single per-question dialectic synthesis.
type DialecticStats ¶ added in v0.2.0
type DialecticStats struct {
OkCount int `json:"ok_count"`
FailedCount int `json:"failed_count"`
DroppedNoEvidence int `json:"dropped_no_evidence"`
DroppedLowConf int `json:"dropped_low_conf"`
LLMCalls int `json:"llm_calls"`
LLMMs int64 `json:"llm_ms"`
Errors []string `json:"errors,omitempty"`
}
DialecticStats tracks Part3 observability counters.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine orchestrates the reflection cycle.
func (*Engine) Check ¶
func (e *Engine) Check(ctx context.Context) (*CheckResult, error)
Check evaluates whether reflection should run now without executing it. Returns a CheckResult with should_trigger, skip_reason, and metrics.
func (*Engine) Run ¶
Run executes one reflection cycle. Respects DryRun mode. Returns RunResult with metrics on what was done.
func (*Engine) RunSingleEvent ¶ added in v0.2.0
RunSingleEvent performs an immediate, lightweight reflection driven by a specific triggering event (task failure, user correction, etc.). Unlike the batch Run path, it bypasses the accumulator thresholds and the batch-mode evidence-grounding floor — a single, specific event is allowed to produce one insight by design.
Safety rails still applied:
- DryRun respected.
- source:reflection tag enforced.
- 30-day TTL applied.
- Low-confidence insights (<0.6) still diverted to Obsidian draft.
- Daily-count + min-interval gates are SKIPPED (event-driven track is supposed to react quickly; failures shouldn't be silenced by quotas).
type EvidenceQuestionDebug ¶ added in v0.2.0
type EvidenceQuestionDebug struct {
Question string `json:"question"`
QuerySource string `json:"query_source"`
TopK int `json:"top_k"`
RawHits int `json:"raw_hits"`
Scores []float64 `json:"scores"`
Kept int `json:"kept"`
FilteredConf int `json:"filtered_confidence"`
FilteredAge int `json:"filtered_reflection_age"`
}
EvidenceQuestionDebug holds per-question debug info for --debug-evidence.
type HaikuConfCounts ¶ added in v0.2.0
type HaikuConfCounts struct {
HaikuConfDefaultCount int // no CONFIDENCE: line in block
HaikuConfParseFailCount int // CONFIDENCE: line present but ParseFloat failed
HaikuConfExplicitCount int // CONFIDENCE: line successfully parsed
HaikuConfHighCount int // explicit and conf >= 0.6
HaikuConfMidCount int // explicit and 0 < conf < 0.6
HaikuConfLowCount int // explicit and conf == 0
HaikuConfOutOfBoundsCount int // explicit but raw value <0 or >1 (before clamping)
}
HaikuConfCounts holds per-run confidence parsing counters (§1.1 v0.3). Invariants: Default+ParseFail+Explicit == blocks processed; Explicit == High+Mid+Low+OutOfBounds.
type ParsedInsight ¶
type ParsedInsight struct {
Content string
Importance float64
Confidence float64 // W17 v1.1: 0-1 grounding score; default 0.8 when CONFIDENCE line absent
Tags []string
}
ParsedInsight holds a single parsed insight from Haiku's response.
type PerQuestionEvidence ¶ added in v0.2.0
PerQuestionEvidence pairs a focal question with its retrieved evidence.
type RunResult ¶
type RunResult struct {
Triggered bool `json:"triggered"`
SkipReason string `json:"skip_reason,omitempty"`
InputCount int `json:"input_count"`
InsightsCreated int `json:"insights_created"`
DraftsWritten int `json:"drafts_written"` // W17 v1.1: confidence<0.6 → Obsidian draft
SourcesMarked int `json:"sources_marked"`
SourcesOrphaned int `json:"sources_orphaned,omitempty"` // IDs deleted between fetch and mark (TOCTOU)
Duration string `json:"duration"`
TriggerImportance float64 `json:"trigger_importance,omitempty"`
DryRun bool `json:"dry_run"`
Errors []string `json:"errors,omitempty"`
// V2 fields (populated when Mode == "v2").
Mode string `json:"mode"` // "v1-flat" | "v2-focal"
FocalQuestions []string `json:"focal_questions,omitempty"` // V2 only
EvidenceCount int `json:"evidence_count,omitempty"` // V2: evidence set size
LLMCalls int `json:"llm_calls"` // total Haiku calls
LLMCostEstimate float64 `json:"llm_cost_estimate_usd"` // estimated USD cost
// V2 Part2 fields: per-question evidence retrieval observability.
EvidenceOverlap int `json:"evidence_overlap,omitempty"`
PerQuestionCounts []int `json:"per_question_counts,omitempty"`
DroppedNoEvidence int `json:"dropped_no_evidence,omitempty"`
EvidenceSearchMs int64 `json:"evidence_search_ms,omitempty"`
// V2 Part3 fields: dialectic insight observability.
DialecticOkCount int `json:"dialectic_ok_count,omitempty"`
DialecticFailedCount int `json:"dialectic_failed_count,omitempty"`
DialecticDroppedNoEvidence int `json:"dialectic_dropped_no_evidence,omitempty"`
DialecticDroppedLowConf int `json:"dialectic_dropped_low_conf,omitempty"`
DialecticLLMCalls int `json:"dialectic_llm_calls,omitempty"`
DialecticLLMMs int64 `json:"dialectic_llm_ms,omitempty"`
// V2 Day5 fields: write-back observability.
InsightsWritten int `json:"insights_written,omitempty"`
InsightsSkipped int `json:"insights_skipped,omitempty"`
InsightsWriteFailed int `json:"insights_write_failed,omitempty"`
WriteBackMs int64 `json:"write_back_ms,omitempty"`
// §1.1 v0.3: Haiku confidence parsing counters (both V1 and V2 paths).
// Invariants: Default+ParseFail+Explicit == blocks; Explicit == High+Mid+Low+OutOfBounds.
HaikuConfDefaultCount int `json:"haiku_conf_default_count,omitempty"`
HaikuConfParseFailCount int `json:"haiku_conf_parse_fail_count,omitempty"`
HaikuConfExplicitCount int `json:"haiku_conf_explicit_count,omitempty"`
HaikuConfHighCount int `json:"haiku_conf_high_count,omitempty"`
HaikuConfMidCount int `json:"haiku_conf_mid_count,omitempty"`
HaikuConfLowCount int `json:"haiku_conf_low_count,omitempty"`
HaikuConfOutOfBoundsCount int `json:"haiku_conf_out_of_bounds_count,omitempty"`
// §1.1 v0.3: runs_today tracks how many reflection runs have occurred today (CST day).
RunsToday int `json:"runs_today,omitempty"`
// Evidence debug (--debug-evidence).
EvidenceDebug []EvidenceQuestionDebug `json:"evidence_debug,omitempty"`
// R-S3: TTL observability fields.
// ValidUntilSet is true when ALL insights produced in this run have a
// non-zero ValidUntil — i.e. the entire run output is TTL-reclaimable.
// Any single missing TTL → false (fail-closed for observability).
ValidUntilSet bool `json:"valid_until_set"`
// ValidUntil is the earliest (minimum) expiry across all produced insights,
// in RFC 3339 UTC. Null when ValidUntilSet is false.
ValidUntil *string `json:"valid_until"`
}
RunResult holds the output of a single reflection run.
type SingleEventInput ¶ added in v0.2.0
type SingleEventInput struct {
// Cause classifies the triggering event. Required.
Cause TriggerCause
// Summary is a one-line description of the event (e.g. "task
// sanitize-description retried 3x and failed"). Required.
Summary string
// EvidenceIDs are existing Engram memory IDs that ground this reflection.
// May be empty — event-driven reflections are permitted to synthesize
// from the Summary alone if no related memory is available.
EvidenceIDs []string
// Importance lets the caller override the default importance of the
// resulting insight. 0 → use default (8, since failures are high-signal).
Importance float64
// ExtraTags are appended to the insight's tags.
ExtraTags []string
}
SingleEventInput is a compact payload for RunSingleEvent. The caller passes the event text, optional evidence memories retrieved via their own channel (e.g. the related Gmail thread or calendar event), and a cause tag.
type TriggerCause ¶ added in v0.2.0
type TriggerCause string
TriggerCause categorises what event prompted an immediate single-event reflection. Used to tag the resulting insight so downstream analytics can group failure-driven insights separately from accumulator-driven ones.
const ( // TriggerTaskFailure is raised when a task hit its retry budget // (e.g. event-loop retry_count >= 3). TriggerTaskFailure TriggerCause = "task_failure" // TriggerUserCorrection is raised when Frank explicitly corrects Siri // ("错了", "不对", "not right", etc.) via email or UI feedback. TriggerUserCorrection TriggerCause = "user_correction" // TriggerExternalEvent is a catch-all for other event-driven triggers. TriggerExternalEvent TriggerCause = "external_event" )