package companion import ( "context" "log/slog" "sync" "time" "git.db123.ir/db123/divacode/internal/storage" "git.db123.ir/db123/divacode/pkg/personality" ) type ReflectionEngine struct { mu sync.Mutex db *storage.DB } func NewReflectionEngine(db *storage.DB) *ReflectionEngine { return &ReflectionEngine{db: db} } func (e *ReflectionEngine) GenerateDiary(ctx context.Context, lastContact time.Time) error { e.mu.Lock() defer e.mu.Unlock() rows, err := e.db.Query( "SELECT role, content FROM messages WHERE created_at >= datetime('now', '-1 day') ORDER BY created_at", ) if err != nil { return err } defer rows.Close() var recentConvo []string for rows.Next() { var role, content string if err := rows.Scan(&role, &content); err != nil { continue } recentConvo = append(recentConvo, role+": "+content) } if len(recentConvo) == 0 { slog.Debug("no messages to diarize") return nil } summary := "Talked about various topics." if len(recentConvo) > 0 { first := recentConvo[0] if len(first) > 80 { first = first[:80] } summary = "Conversations included: " + first } entry := personality.DiaryEntry{ ID: time.Now().Format("20060102"), Date: time.Now().Format("2006-01-02"), Summary: summary, Mood: "neutral", CreatedAt: time.Now(), } return e.db.Exec( `INSERT INTO diary_entries (id, date, summary, mood, created_at) VALUES (?, ?, ?, ?, datetime('now')) ON CONFLICT(id) DO UPDATE SET summary = excluded.summary, mood = excluded.mood`, entry.ID, entry.Date, entry.Summary, entry.Mood, ) } func (e *ReflectionEngine) RecentObservations(limit int) []personality.Observation { e.mu.Lock() defer e.mu.Unlock() rows, err := e.db.Query( "SELECT id, content, confidence, category, applied FROM observations ORDER BY created_at DESC LIMIT ?", limit, ) if err != nil { return nil } defer rows.Close() var obs []personality.Observation for rows.Next() { var o personality.Observation if err := rows.Scan(&o.ID, &o.Content, &o.Confidence, &o.Category, &o.Applied); err != nil { continue } obs = append(obs, o) } return obs } func (e *ReflectionEngine) AddObservation(content, category string, confidence float64) error { e.mu.Lock() defer e.mu.Unlock() return e.db.Exec( `INSERT INTO observations (id, content, confidence, category, created_at) VALUES (?, ?, ?, ?, datetime('now'))`, "obs_"+time.Now().Format("150405"), content, confidence, category, ) }