feat: add metacognition, reflection, consolidation, narrative and notifications
Phase 10. Metacognition is a cognitive process with deterministic self-checks (insufficient evidence, single-source reliance, model output without evidence, repeated failed hypotheses, stale contradictions, calibration overconfidence); its warnings compete for attention and, when admitted, add counter-evidence or open an investigation goal. Reflection reviews the period since the last run (prediction errors, rejected beliefs, corrections, status changes, completed goals, contradictions, calibration), turns repeated failures into procedural lessons written once, and records a reflection event; a model may only word the prose within the mind's budget. Consolidation clusters unconsolidated episodes by shared stemmed terms, creates a belief whose confidence is computed from the episodes as evidence and a semantic memory linked to each episode by derived_from, and records jobs with inputs and outputs. Wording may come from the consolidate prompt within a per-run model budget; the job says which. Operators can run, pause and reject; originals are never touched. The narrative hook keeps a five-part first-person narrative built from state and stored with narrative_updated events. The notification hook applies explicit thresholded rules, aggregates repeats within a cooldown and records suppressions with reasons. A scheduled job runs consolidation and reflection per mind, switching the runtime mode while it works. API, Background tab, notifications page with unread badge, overview narrative and warnings, CLI commands, docs/cognition.md.
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
// Package narrative keeps a mind's concise internal narrative: what it is
|
||||
// doing, why, what happened recently, what it is trying to resolve and what
|
||||
// might happen next. It is built deterministically from state; a model may
|
||||
// rephrase it but never adds content (spec §17).
|
||||
package narrative
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/andydixon/noema/internal/storage"
|
||||
"github.com/andydixon/noema/pkg/ids"
|
||||
)
|
||||
|
||||
// Structured is the machine-readable narrative.
|
||||
type Structured struct {
|
||||
Doing []string `json:"doing"`
|
||||
Why []string `json:"why"`
|
||||
Recently []string `json:"recently"`
|
||||
Resolving []string `json:"resolving"`
|
||||
Next []string `json:"next"`
|
||||
Mode string `json:"mode"`
|
||||
Cycle int64 `json:"cycle"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
}
|
||||
|
||||
// Narrative is the stored record.
|
||||
type Narrative struct {
|
||||
MindID ids.ID `json:"mind_id"`
|
||||
Text string `json:"text"`
|
||||
Structured Structured `json:"structured"`
|
||||
EventID ids.ID `json:"event_id,omitempty"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// Render turns the structured narrative into plain first-person prose.
|
||||
func Render(s Structured) string {
|
||||
var b strings.Builder
|
||||
line := func(label string, items []string, empty string) {
|
||||
if len(items) == 0 {
|
||||
if empty != "" {
|
||||
b.WriteString(label + " " + empty + "\n")
|
||||
}
|
||||
return
|
||||
}
|
||||
b.WriteString(label + " " + strings.Join(items, "; ") + ".\n")
|
||||
}
|
||||
line("I am", s.Doing, "not attending to anything in particular.")
|
||||
line("Because", s.Why, "")
|
||||
line("Recently:", s.Recently, "nothing notable.")
|
||||
line("Trying to resolve:", s.Resolving, "nothing open.")
|
||||
line("Next:", s.Next, "waiting for input.")
|
||||
return strings.TrimSpace(b.String())
|
||||
}
|
||||
|
||||
// Store persists narratives.
|
||||
type Store struct{ db *pgxpool.Pool }
|
||||
|
||||
// NewStore creates a store.
|
||||
func NewStore(db *pgxpool.Pool) *Store { return &Store{db: db} }
|
||||
|
||||
// Save upserts the narrative.
|
||||
func (s *Store) Save(ctx context.Context, q storage.Querier, mind ids.ID, text string, st Structured, eventID ids.ID) error {
|
||||
raw, _ := json.Marshal(st)
|
||||
var ev *string
|
||||
if !eventID.IsZero() {
|
||||
e := string(eventID)
|
||||
ev = &e
|
||||
}
|
||||
_, err := q.Exec(ctx, `INSERT INTO narratives (mind_id, text, structured, event_id) VALUES ($1,$2,$3,$4)
|
||||
ON CONFLICT (mind_id) DO UPDATE SET text=excluded.text, structured=excluded.structured, event_id=excluded.event_id, updated_at=now()`, mind, text, raw, ev)
|
||||
return err
|
||||
}
|
||||
|
||||
// Get returns the current narrative.
|
||||
func (s *Store) Get(ctx context.Context, mind ids.ID) (Narrative, error) {
|
||||
var n Narrative
|
||||
var raw []byte
|
||||
var ev *string
|
||||
err := s.db.QueryRow(ctx, `SELECT mind_id, text, structured, event_id, updated_at FROM narratives WHERE mind_id=$1`, mind).Scan(&n.MindID, &n.Text, &raw, &ev, &n.UpdatedAt)
|
||||
if err != nil {
|
||||
if err == pgx.ErrNoRows {
|
||||
return Narrative{MindID: mind, Text: "No narrative yet."}, nil
|
||||
}
|
||||
return n, storage.Translate(err)
|
||||
}
|
||||
json.Unmarshal(raw, &n.Structured) //nolint:errcheck
|
||||
if ev != nil {
|
||||
n.EventID = ids.ID(*ev)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// Changed reports whether the new structure differs enough to record.
|
||||
func Changed(old, new Structured) bool {
|
||||
return fmt.Sprint(old.Doing) != fmt.Sprint(new.Doing) || fmt.Sprint(old.Resolving) != fmt.Sprint(new.Resolving) || fmt.Sprint(old.Next) != fmt.Sprint(new.Next)
|
||||
}
|
||||
Reference in New Issue
Block a user