feat: implement global workspace, working memory and the cognitive cycle

Phase 4 (ADR-0001). internal/attention scores thought candidates as a
normalised weighted sum over ten named features with a per-term
breakdown, ranked by (score, id) so ordering is total and replayable.
internal/workspace holds the capacity-limited workspace (refresh by
subject, decayed competition, explained admit/reject outcomes) and the
decaying working memory.

internal/brain runs one runtime per active mind: debounced wake-ups from
the event bus (own output never re-triggers), a settle window so
concurrently committing events are not skipped, bounded concurrent
Observe calls with per-process isolation and timeouts, deterministic
scoring, a loop detector that suppresses recurring thoughts and raises a
metacognition warning, executive dispatch by thought kind, and one
transaction per cycle whose events are published only after commit.
Every candidate, selection, attention shift and broadcast is an event
with provenance back to the triggering observation. Operators can run a
cycle, pause, resume, reset transient state and change attention
weights live; the manager reconciles runtimes with mind status.

cognition/attend is the first process: deterministic candidates from
external events using an urgency lexicon, novelty against context and
trust-based operator priority.
This commit is contained in:
Andy Dixon
2026-06-18 22:54:07 +01:00
parent 85d769b245
commit e9c1b25c80
28 changed files with 2289 additions and 12 deletions
+74
View File
@@ -29,6 +29,9 @@ func (u *UI) mindRoutes(m *http.ServeMux) {
m.Handle("POST /minds/{mind}/personality/template", u.require(auth.RoleAdministrator, u.personalityTemplate))
m.Handle("POST /minds/{mind}/personality/versions/{n}/restore", u.require(auth.RoleAdministrator, u.personalityRestore))
m.Handle("GET /minds/{mind}/personality/diff", u.require(auth.RoleObserver, u.personalityDiff))
m.Handle("GET /minds/{mind}/workspace", u.require(auth.RoleObserver, u.workspacePage))
m.Handle("POST /minds/{mind}/workspace/control", u.require(auth.RoleOperator, u.workspaceControl))
m.Handle("POST /minds/{mind}/workspace/weights", u.require(auth.RoleAdministrator, u.workspaceWeights))
m.Handle("GET /personality-templates", u.require(auth.RoleObserver, u.templates))
m.Handle("POST /personality-templates", u.require(auth.RoleAdministrator, u.templateCreate))
m.Handle("GET /personality-templates/{id}", u.require(auth.RoleObserver, u.templateEdit))
@@ -109,6 +112,7 @@ func (u *UI) mindStatus(w http.ResponseWriter, r *http.Request) {
}
u.deps.Audit.Log(r.Context(), "mind.status", "mind", m.ID.String(), map[string]any{"status": st})
u.deps.Events.OperatorAction(r.Context(), m.ID, username(r), "mind.status", "Operator "+username(r)+" set status to "+string(st), map[string]any{"status": st})
u.deps.Brain.Reconcile(r.Context()) //nolint:errcheck
u.flash(w, r, "ok", "Mind is now "+string(st)+".", "/minds/"+m.Slug)
}
@@ -419,3 +423,73 @@ func (u *UI) templateDelete(w http.ResponseWriter, r *http.Request) {
u.deps.Audit.Log(r.Context(), "template.delete", "personality_template", t.ID.String(), map[string]any{"name": t.Name})
u.flash(w, r, "ok", "Template deleted.", "/personality-templates")
}
func (u *UI) workspacePage(w http.ResponseWriter, r *http.Request) {
m, ok := u.mind(w, r)
if !ok {
return
}
v, err := u.wsF(r, m)
if err != nil {
u.errorPage(w, r, 500, "Could not load workspace: "+err.Error())
return
}
u.render(w, r, "workspace", m.DisplayName+" · Workspace", map[string]any{"Mind": m, "View": v})
}
func (u *UI) workspaceControl(w http.ResponseWriter, r *http.Request) {
m, ok := u.mind(w, r)
if !ok {
return
}
action := r.PostFormValue("action")
var err error
switch action {
case "cycle", "pause", "resume":
err = u.deps.Brain.Command(r.Context(), m.ID, action, nil)
case "reset":
err = u.deps.Brain.Command(r.Context(), m.ID, "reset", map[string]bool{"workspace": true, "working_memory": true, "loops": true})
default:
err = errors.New("unknown action")
}
if err != nil {
u.flash(w, r, "error", err.Error(), "/minds/"+m.Slug+"/workspace")
return
}
u.deps.Audit.Log(r.Context(), "mind."+action, "mind", m.ID.String(), nil)
u.flash(w, r, "ok", "Done: "+action+".", "/minds/"+m.Slug+"/workspace")
}
func (u *UI) workspaceWeights(w http.ResponseWriter, r *http.Request) {
m, ok := u.mind(w, r)
if !ok {
return
}
r.ParseForm() //nolint:errcheck
cfg := m.Config
for _, f := range minds.AttentionFeatures {
if v, err := strconv.ParseFloat(r.PostFormValue("w."+f), 64); err == nil {
cfg.AttentionWeights[f] = v
}
}
if v, err := strconv.Atoi(r.PostFormValue("workspace_capacity")); err == nil {
cfg.WorkspaceCapacity = v
}
if v, err := strconv.Atoi(r.PostFormValue("working_memory_capacity")); err == nil {
cfg.WorkingMemoryCapacity = v
}
if v, err := strconv.ParseFloat(r.PostFormValue("working_memory_decay"), 64); err == nil {
cfg.WorkingMemoryDecay = v
}
if v, err := strconv.Atoi(r.PostFormValue("loop_detect_threshold")); err == nil {
cfg.LoopDetectThreshold = v
}
if _, err := u.deps.Minds.Update(r.Context(), m.ID, minds.UpdateParams{Config: &cfg}); err != nil {
u.flash(w, r, "error", err.Error(), "/minds/"+m.Slug+"/workspace")
return
}
u.deps.Audit.Log(r.Context(), "mind.config", "mind", m.ID.String(), map[string]any{"weights": cfg.AttentionWeights, "workspace_capacity": cfg.WorkspaceCapacity})
u.deps.Events.OperatorAction(r.Context(), m.ID, username(r), "mind.config", "Operator "+username(r)+" changed attention weights and capacities", map[string]any{"weights": cfg.AttentionWeights})
u.deps.Brain.Command(r.Context(), m.ID, "reload", nil) //nolint:errcheck // not running is fine
u.flash(w, r, "ok", "Configuration saved and applied.", "/minds/"+m.Slug+"/workspace")
}
+34 -2
View File
@@ -6,6 +6,7 @@ package ui
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"html/template"
"io/fs"
@@ -17,6 +18,7 @@ import (
"github.com/andydixon/noema/internal/api"
"github.com/andydixon/noema/internal/app"
"github.com/andydixon/noema/internal/attention"
"github.com/andydixon/noema/internal/auth"
"github.com/andydixon/noema/internal/minds"
"github.com/andydixon/noema/internal/version"
@@ -31,6 +33,7 @@ type UI struct {
static fs.FS
statusF func(r *http.Request) any // system status provider injected by api
ctxF func(r *http.Request, id ids.ID) (api.EventContext, error) // event forensic context, shared with api
wsF func(r *http.Request, m minds.Mind) (api.WorkspaceView, error)
}
// View is the data passed to every template.
@@ -51,7 +54,7 @@ const flashCookie = "noema_flash"
// New parses templates. In development, when ./web exists on disk, templates
// and static files are read from disk so edits show without a rebuild.
func New(deps app.Deps, statusF func(r *http.Request) any, ctxF func(r *http.Request, id ids.ID) (api.EventContext, error)) (*UI, error) {
func New(deps app.Deps, statusF func(r *http.Request) any, ctxF func(r *http.Request, id ids.ID) (api.EventContext, error), wsF func(r *http.Request, m minds.Mind) (api.WorkspaceView, error)) (*UI, error) {
tmplFS, staticFS := web.Templates(), web.Static()
if !deps.Config.Production() {
if st, err := os.Stat("web/templates"); err == nil && st.IsDir() {
@@ -59,7 +62,7 @@ func New(deps app.Deps, statusF func(r *http.Request) any, ctxF func(r *http.Req
deps.Log.Info("ui: serving templates and static files from ./web (development)")
}
}
u := &UI{deps: deps, static: staticFS, statusF: statusF, ctxF: ctxF}
u := &UI{deps: deps, static: staticFS, statusF: statusF, ctxF: ctxF, wsF: wsF}
if err := u.parse(tmplFS); err != nil {
return nil, err
}
@@ -85,6 +88,35 @@ func (u *UI) parse(fsys fs.FS) error {
},
"title": func(s string) string { s = strings.ReplaceAll(s, "_", " "); return strings.ToUpper(s[:1]) + s[1:] },
"valueKeys": func() []string { return minds.ValueKeys },
"features": func() []string { return minds.AttentionFeatures },
"trunc": func(s string, n int) string {
if len(s) > n {
return s[:n] + "…"
}
return s
},
"candSummary": func(s string) string {
if i := strings.Index(s, "] "); i > 0 && strings.HasPrefix(s, "[") {
return s[i+2:]
}
return s
},
"payloadField": func(raw json.RawMessage, field string) string {
var m map[string]any
if json.Unmarshal(raw, &m) != nil {
return ""
}
return fmt.Sprint(m[field])
},
"breakdownOf": func(raw json.RawMessage) *attention.Breakdown {
var p struct {
Breakdown attention.Breakdown `json:"breakdown"`
}
if json.Unmarshal(raw, &p) != nil || len(p.Breakdown.Terms) == 0 {
return nil
}
return &p.Breakdown
},
"traitKeys": func() []string { return minds.TraitKeys },
"dict": func(kv ...any) map[string]any {
m := map[string]any{}