feat: add goals, drives, affect state, predictions and curiosity

Phase 9. Goals form a mind-scoped tree with kind, priority, progress and
blockers; their deterministic relevance to a candidate feeds the
goal_relevance attention feature and a goal monitor raises stalled goals
and observations that touch one. Drives are a closed set of eight
scalars with operator-configured ranges and personality-derived
baselines; there is no self-preservation, replication or acquisition
drive and no way to add one at runtime. Affect is ten scalars moved by an
explicit rule table over events and decaying towards baseline; both
modulate attention weights each cycle and the effective weights are
recorded with every cycle and shown beside the configured ones.

Predictions carry a window and machine-checkable criteria (event terms
occurring or staying absent, a belief reaching a confidence, or operator
judgement). A resolver job judges them deterministically, keeps an
append-only outcome history for calibration (accuracy, Brier score,
confidence buckets, overconfidence flag), emits prediction_error events
scaled by how confident the miss was, and feeds the outcome back into the
linked belief as evidence. Causal hypotheses derive predictions
automatically. Curiosity turns misses, contradictions and unexplained
observations into questions that compete for attention and become
investigation goals when admitted.

Brain gains after-cycle hooks and goal/motivation state. API, UI (goals,
prediction dashboard, cognitive state panel, effective weights) and CLI
(goal, prediction, state). Demo scenario 4 verified end to end.
This commit is contained in:
Andy Dixon
2026-06-27 20:41:03 +01:00
parent 777e8f50b5
commit 9eb873cbe6
39 changed files with 3053 additions and 50 deletions
+2
View File
@@ -11,6 +11,7 @@ import (
"github.com/andydixon/noema/internal/attention"
"github.com/andydixon/noema/internal/brain"
"github.com/andydixon/noema/internal/goals"
"github.com/andydixon/noema/internal/workspace"
"github.com/andydixon/noema/pkg/events"
"github.com/andydixon/noema/pkg/ids"
@@ -56,6 +57,7 @@ func (Attend) Observe(_ context.Context, s *brain.State) ([]brain.Candidate, err
f := attention.Features{Salience: ev.Salience, Confidence: ev.Confidence, Consequence: 0.4}
f.Urgency = urgency(toks)
f.ContextRelevance = workspace.Overlap(toks, ctxTokens)
f.GoalRelevance, _ = goals.Relevance(text, s.Goals)
f.Novelty = 1 - f.ContextRelevance*0.7 // things we are already holding are less novel
switch trust {
case events.TrustOperator:
+125
View File
@@ -0,0 +1,125 @@
package cognition
import (
"context"
"encoding/json"
"strings"
"github.com/andydixon/noema/internal/attention"
"github.com/andydixon/noema/internal/beliefs"
"github.com/andydixon/noema/internal/brain"
"github.com/andydixon/noema/internal/memory"
"github.com/andydixon/noema/pkg/events"
"github.com/andydixon/noema/pkg/ids"
)
// Curiosity proposes questions about unexplained observations, prediction
// errors and contradictions. Its output is questions and investigation goals
// only; it never grants or requests permission to act (spec §12).
type Curiosity struct{}
// Name implements brain.Process.
func (Curiosity) Name() string { return "curiosity" }
// Observe implements brain.Process.
func (Curiosity) Observe(ctx context.Context, s *brain.State) ([]brain.Candidate, error) {
drive := 0.5
for _, d := range s.Motiv.Drives {
if d.Name == "curiosity" {
drive = d.Value
}
}
var out []brain.Candidate
for _, ev := range s.NewEvents {
if strings.HasPrefix(ev.Source, "brain") && ev.Type != events.PredictionError && ev.Type != events.ContradictionDetected {
continue
}
switch ev.Type {
case events.PredictionError:
stmt, _ := payloadField(ev, "statement")
q := "Why was my prediction wrong: " + truncate(stmt, 120) + "?"
out = append(out, curiosityCandidate(ev, q, "prediction:"+ev.Metadata["prediction_id"].(string), 0.8, drive))
case events.ContradictionDetected:
q := "Which is right: " + truncate(ev.Summary, 140) + "?"
out = append(out, curiosityCandidate(ev, q, "contradiction:"+fmtID(ev.Metadata["belief_id"])+"+"+fmtID(ev.Metadata["other_id"]), 0.7, drive))
case events.Observation:
if ev.Metadata["conversation_id"] != nil || ev.Salience < 0.5 {
continue
}
text := ev.Summary
var p events.ObservationPayload
if json.Unmarshal(ev.Payload, &p) == nil && p.Text != "" {
text = p.Text
}
if urgency(tokenise(text)) < 0.5 {
continue
}
// Unexplained: no belief and no memory speaks to it.
explained := false
if s.Services.Beliefs != nil {
if bs, _ := s.Services.Beliefs.Search(ctx, s.Mind.ID, text, 3); hasLive(bs) {
explained = true
}
}
if !explained && s.Services.Memory != nil {
if hits, _ := s.Services.Memory.Retrieve(ctx, s.Mind.ID, memory.Query{Text: text, Limit: 3, Now: s.Now}); len(hits) > 0 && hits[0].Score >= 0.6 && hits[0].Memory.OriginEvent != ev.ID {
explained = true
}
}
if explained {
continue
}
q := "Why did this happen: " + truncate(text, 120) + "?"
out = append(out, curiosityCandidate(ev, q, "unexplained:"+subjectKey(text), 0.5, drive))
}
}
return out, nil
}
func curiosityCandidate(ev events.Event, question, subject string, weight, drive float64) brain.Candidate {
return brain.Candidate{Kind: "question", Subject: subject, Summary: "question: " + question,
Content: map[string]any{"question": question, "subject": subject, "source_event": string(ev.ID)},
// A failed prediction or a contradiction is an unresolved conflict between what
// was expected and what was seen, so the contradiction feature is set for both.
Features: attention.Features{Salience: 0.4 + 0.45*weight, Novelty: 0.6 + 0.3*drive, Consequence: 0.5 + 0.3*weight, Urgency: 0.4 * weight, Confidence: 0.5,
Contradiction: boolf(ev.Type == events.ContradictionDetected || ev.Type == events.PredictionError)},
Confidence: 0.5, SourceEvents: []ids.ID{ev.ID}, Evidence: []events.EvidenceRef{{Kind: "event", ID: string(ev.ID), Note: "prompted the question"}}}
}
func hasLive(bs []beliefs.Belief) bool {
for _, b := range bs {
if b.Status != beliefs.StatusRejected && b.Status != beliefs.StatusSuperseded {
return true
}
}
return false
}
func boolf(b bool) float64 {
if b {
return 1
}
return 0
}
func fmtID(v any) string {
if s, ok := v.(string); ok {
return s
}
return ""
}
// subjectKey reduces text to its three most distinctive tokens so the same
// unexplained situation yields the same question subject.
func subjectKey(text string) string {
toks := tokenise(text)
var keep []string
for _, t := range toks {
if len(t) >= 4 && len(keep) < 3 {
keep = append(keep, t)
}
}
return strings.Join(keep, "+")
}
func tokenise(text string) []string { return tokeniseWS(text) }
+96
View File
@@ -0,0 +1,96 @@
package cognition
import (
"context"
"strings"
"time"
"github.com/andydixon/noema/internal/attention"
"github.com/andydixon/noema/internal/brain"
"github.com/andydixon/noema/internal/goals"
"github.com/andydixon/noema/internal/workspace"
"github.com/andydixon/noema/pkg/events"
"github.com/andydixon/noema/pkg/ids"
)
// GoalMonitor watches the goal tree: stalled goals are raised for attention,
// and goals whose subject appears in new events get a progress nudge
// candidate. It never completes a goal on its own; that needs evidence or
// an operator.
type GoalMonitor struct {
StallAfter time.Duration
}
// Name implements brain.Process.
func (GoalMonitor) Name() string { return "goal-monitor" }
// Observe implements brain.Process.
func (g GoalMonitor) Observe(ctx context.Context, s *brain.State) ([]brain.Candidate, error) {
if s.Services.Goals == nil {
return nil, nil
}
stall := g.StallAfter
if stall <= 0 {
stall = 24 * time.Hour
}
var out []brain.Candidate
stalled, _ := s.Services.Goals.Stalled(ctx, s.Mind.ID, stall)
for i, gl := range stalled {
if i >= 3 {
break
}
out = append(out, brain.Candidate{Kind: "goal", Subject: string(gl.ID), Summary: "goal stalled: " + gl.Title,
Content: map[string]any{"goal_id": string(gl.ID), "reason": "no progress for " + stall.String(), "ref": string(gl.ID)},
Features: attention.Features{Salience: 0.4, GoalRelevance: gl.Priority, Consequence: 0.5 * gl.Priority, Urgency: 0.3, Confidence: 1}, Confidence: 1,
Evidence: []events.EvidenceRef{{Kind: "goal", ID: string(gl.ID)}}})
}
// New external events touching a goal's subject.
for _, ev := range s.NewEvents {
if strings.HasPrefix(ev.Source, "brain") || ev.Type != events.Observation {
continue
}
if rel, id := goals.Relevance(ev.Summary, s.Goals); rel >= 0.5 && !id.IsZero() {
out = append(out, brain.Candidate{Kind: "goal", Subject: string(id) + ":" + string(ev.ID), Summary: "evidence for a goal: " + truncate(ev.Summary, 100),
Content: map[string]any{"goal_id": string(id), "reason": "new observation relevant to the goal", "source_event": string(ev.ID), "relevance": rel, "ref": string(id)},
Features: attention.Features{Salience: ev.Salience * 0.7, GoalRelevance: rel, Consequence: 0.4, Confidence: 1}, Confidence: 1, SourceEvents: []ids.ID{ev.ID},
Evidence: []events.EvidenceRef{{Kind: "goal", ID: string(id)}, {Kind: "event", ID: string(ev.ID)}}})
}
}
return out, nil
}
// goal handles admitted goal thoughts: holds the goal in working memory and
// records that it was attended (progress nudges are logged, not invented).
func (h Handlers) goal(ctx context.Context, c *brain.Cycle, t workspace.Thought) error {
gid, _ := t.Content["goal_id"].(string)
reason, _ := t.Content["reason"].(string)
src, _ := t.Content["source_event"].(string)
c.Runtime.Hold(workspace.Item{Key: "goal:" + gid, Content: t.Summary, Kind: "goal", Ref: gid, SourceEvent: ids.ID(src)})
c.Emit(events.New{Type: events.GoalUpdated, Source: "brain.goals", Summary: t.Summary + " (" + reason + ")", Salience: t.Score, Confidence: 1, CausationID: t.EventID,
Evidence: t.Evidence, Metadata: map[string]any{"goal_id": gid, "attended": true}, Payload: map[string]any{"goal_id": gid, "reason": reason}})
return nil
}
// question handles admitted curiosity questions: an investigation goal is
// created (once per subject) so the question persists beyond the workspace.
func (h Handlers) question(ctx context.Context, c *brain.Cycle, t workspace.Thought) error {
if c.State.Services.Goals == nil {
return nil
}
subject, _ := t.Content["subject"].(string)
question, _ := t.Content["question"].(string)
src, _ := t.Content["source_event"].(string)
if existing, err := c.State.Services.Goals.FindBySubject(ctx, c.Tx, c.State.Mind.ID, goals.KindInvestigation, subject); err == nil {
c.Runtime.Hold(workspace.Item{Key: "goal:" + string(existing.ID), Content: existing.Title, Kind: "goal", Ref: string(existing.ID)})
return nil
}
prio := 0.3 + 0.4*c.State.Motiv.Affect.Curiosity
g, err := c.State.Services.Goals.Create(ctx, c.Tx, goals.New{MindID: c.State.Mind.ID, Title: question, Kind: goals.KindInvestigation, Priority: prio, Subject: subject, Owner: "mind", OriginEvent: t.EventID})
if err != nil {
return err
}
c.Emit(events.New{Type: events.GoalCreated, Source: "brain.curiosity", Summary: "curious: " + question, Salience: 0.4 + 0.3*prio, Confidence: 0.6, CausationID: t.EventID, ParentIDs: []ids.ID{t.EventID, ids.ID(src)},
Evidence: append(t.Evidence, events.EvidenceRef{Kind: "goal", ID: string(g.ID)}), Metadata: map[string]any{"goal_id": string(g.ID), "kind": g.Kind, "priority": prio}, Payload: g})
c.Runtime.Hold(workspace.Item{Key: "goal:" + string(g.ID), Content: "investigating: " + question, Kind: "goal", Ref: string(g.ID), SourceEvent: ids.ID(src)})
return nil
}
+36
View File
@@ -6,11 +6,13 @@ import (
"errors"
"fmt"
"strings"
"time"
"github.com/andydixon/noema/internal/beliefs"
"github.com/andydixon/noema/internal/brain"
"github.com/andydixon/noema/internal/conversation"
"github.com/andydixon/noema/internal/memory"
"github.com/andydixon/noema/internal/predictions"
"github.com/andydixon/noema/internal/storage"
"github.com/andydixon/noema/internal/workspace"
"github.com/andydixon/noema/pkg/concepts"
@@ -31,6 +33,8 @@ func (h Handlers) Register(r *brain.Registry) {
r.Handle("retrieve", h.retrieve)
r.Handle("hypothesis", h.hypothesis)
r.Handle("perceive", h.perceive)
r.Handle("goal", h.goal)
r.Handle("question", h.question)
}
// emitter adapts the cycle to the beliefs store's Emitter.
@@ -77,9 +81,41 @@ func (h Handlers) hypothesis(ctx context.Context, c *brain.Cycle, t workspace.Th
return err
}
c.Runtime.Hold(workspace.Item{Key: "belief:" + string(res.Belief.ID), Content: "hypothesis (" + fmt.Sprintf("%.2f", res.Belief.Confidence) + "): " + prop, Kind: "thought", Ref: string(res.Belief.ID), SourceEvent: t.EventID})
// A causal hypothesis implies a checkable expectation: the effect recurs
// after the cause. Its confidence is the belief's, so a miss will lower it.
if c.State.Services.Predictions != nil {
effect, _ := t.Content["effect_event"].(string)
if ev, err := c.Runtime.Events().Get(ctx, ids.ID(effect)); err == nil {
terms := distinctiveTerms(ev.Summary, 3)
if len(terms) > 0 {
p, err := c.State.Services.Predictions.Create(ctx, c.Tx, predictions.New{MindID: c.State.Mind.ID, Statement: "something like \"" + truncate(ev.Summary, 80) + "\" will recur within 24 hours if the cause is real",
Subject: subjectKey(ev.Summary), Confidence: res.Belief.Confidence, WindowEnd: c.State.Now.Add(24 * time.Hour),
Criteria: predictions.Criteria{Kind: "event_match", Expect: "occurs", Terms: terms, MinTerms: min(2, len(terms))}, Source: "brain.associate", OriginEvent: res.Events[0].ID, BeliefID: res.Belief.ID})
if err == nil {
c.Emit(events.New{Type: events.PredictionCreated, Source: "brain.associate", Summary: fmt.Sprintf("predicted (%.2f): %s", p.Confidence, p.Statement), Salience: 0.3, Confidence: p.Confidence, CausationID: res.Events[0].ID,
Evidence: []events.EvidenceRef{{Kind: "prediction", ID: string(p.ID)}, {Kind: "belief", ID: string(res.Belief.ID)}}, Metadata: map[string]any{"prediction_id": string(p.ID), "belief_id": string(res.Belief.ID), "window_end": p.WindowEnd}, Payload: p})
}
}
}
}
return nil
}
// distinctiveTerms picks the longest tokens of a summary as match terms.
func distinctiveTerms(text string, n int) []string {
toks := tokeniseWS(text)
var out []string
for _, t := range toks {
if len(t) >= 5 {
out = append(out, t)
}
if len(out) == n {
break
}
}
return out
}
// attend encodes the attended event as a memory and holds it in working
// memory. Only attended events become episodes: attention gates encoding.
func (h Handlers) attend(ctx context.Context, c *brain.Cycle, t workspace.Thought) error {
+113
View File
@@ -0,0 +1,113 @@
package cognition
import (
"context"
"fmt"
"math"
"github.com/andydixon/noema/internal/brain"
"github.com/andydixon/noema/internal/motivation"
"github.com/andydixon/noema/pkg/events"
)
// MotivationHook applies the deterministic affect and drive rules to the
// events a cycle produced, persists the result, and emits emotion_changed or
// drive_changed events only when something moved noticeably.
type MotivationHook struct{ Store *motivation.Store }
// Name implements brain.Hook.
func (MotivationHook) Name() string { return "motivation" }
// AfterCycle implements brain.Hook.
func (h MotivationHook) AfterCycle(ctx context.Context, c *brain.Cycle, emitted []events.Event) error {
if h.Store == nil {
return nil
}
st := c.State.Motiv
if len(st.Drives) == 0 {
return nil
}
before := st
before.Drives = append([]motivation.Drive{}, st.Drives...)
var reasons []string
all := append(append([]events.Event{}, c.State.NewEvents...), emitted...)
for _, ev := range all {
if d, ok := motivation.Rules(ev); ok {
motivation.Apply(&st, d)
reasons = append(reasons, d.Reason)
}
}
st.Affect.UpdatedAt = c.State.Now
if err := h.Store.SaveAffect(ctx, c.Tx, c.State.Mind.ID, st.Affect); err != nil {
return err
}
for i, d := range st.Drives {
if math.Abs(d.Value-before.Drives[i].Value) > 1e-9 {
if err := h.Store.SaveDrive(ctx, c.Tx, c.State.Mind.ID, d); err != nil {
return err
}
if math.Abs(d.Value-before.Drives[i].Value) >= 0.1 {
c.Emit(events.New{Type: events.DriveChanged, Source: "brain.motivation", Summary: fmt.Sprintf("drive %s %.2f → %.2f", d.Name, before.Drives[i].Value, d.Value), Salience: 0.2, Confidence: 1,
Metadata: map[string]any{"drive": d.Name, "from": before.Drives[i].Value, "to": d.Value}, Payload: map[string]any{"drive": d, "reasons": uniq(reasons)}})
}
}
}
if key, sig := motivation.Significant(before.Affect, st.Affect); sig {
v := st.Affect.Valence
a := st.Affect.Arousal
c.Emit(events.New{Type: events.EmotionChanged, Source: "brain.motivation", Summary: fmt.Sprintf("cognitive state shifted: %s now %.2f (%s)", key, field(st.Affect, key), joinReasons(reasons)),
Salience: 0.3, Confidence: 1, Valence: &v, Arousal: &a, Metadata: map[string]any{"field": key}, Payload: map[string]any{"before": before.Affect, "after": st.Affect, "reasons": uniq(reasons)}})
}
return nil
}
func field(a motivation.Affect, key string) float64 {
switch key {
case "valence":
return a.Valence
case "arousal":
return a.Arousal
case "curiosity":
return a.Curiosity
case "concern":
return a.Concern
case "frustration":
return a.Frustration
case "confidence":
return a.Confidence
case "uncertainty":
return a.Uncertainty
case "engagement":
return a.Engagement
case "task_pressure":
return a.TaskPressure
}
return a.Load
}
func uniq(xs []string) []string {
seen := map[string]bool{}
var out []string
for _, x := range xs {
if !seen[x] {
seen[x] = true
out = append(out, x)
}
}
return out
}
func joinReasons(xs []string) string {
u := uniq(xs)
if len(u) > 3 {
u = append(u[:3], "…")
}
s := ""
for i, x := range u {
if i > 0 {
s += ", "
}
s += x
}
return s
}
+20
View File
@@ -0,0 +1,20 @@
package cognition
import (
"encoding/json"
"github.com/andydixon/noema/internal/workspace"
"github.com/andydixon/noema/pkg/events"
)
func tokeniseWS(text string) []string { return workspace.Tokenise(text) }
// payloadField reads a string field from an event payload.
func payloadField(ev events.Event, key string) (string, bool) {
var m map[string]any
if json.Unmarshal(ev.Payload, &m) != nil {
return "", false
}
s, ok := m[key].(string)
return s, ok
}