* feat(memory): four-scope contract with CRUD and revisions
Seam for memory unification slice 2 (docs/prds/memory-engine-unification.md
§1, §2, §7): internal/domain/memory is now a scope-addressed CRUD contract.
- Scope{Kind,Agent,User} with the four ratified kinds, Validate rejecting a
component present where it is not required, and a length-prefixed Key so
opaque channel-native ids cannot collide.
- Subject{AgentID,UserID} with Scopes()/WritableScopes(): global is never
writable, and an absent user id removes every scope requiring one.
- Store becomes Create/Get/Query/List/Update/Forget/Revisions over
NewRecord/RecordUpdate/Record/Revision, with ErrNotFound/ErrStaleRevision.
Observation, Identity and Metadata are deleted.
- The content scanner moves into the family (internal/domain/memory) so every
engine applies it in Create and Update; internal/memory re-exports the types
until slice 5 deletes it.
- The markdown store moves to internal/infrastructure/memory/builtin, its
correct home per organisation.md.
WIP: internal/infrastructure/memory and internal/infrastructure/sessioncurator
are converted in the lanes that follow this commit.
* feat(memory): builtin engine CRUD, retained revisions and the curator's agent-user write
Slice 2 implementation (docs/prds/memory-engine-unification.md §1, §2, §6,
§7), on top of the contract seam in the previous commit.
- internal/infrastructure/memory: per-scope markdown heads with a JSON
provenance marker, per-scope HISTORY.md retaining superseded and deleted
states, Update superseding before replacing the live block, ErrStaleRevision
via RecordUpdate.Expected, idempotent Forget, and the family scanner applied
in Create and Update. Scope directories are hex(sha256(Scope.Key())).
- internal/infrastructure/sessioncurator: the participant is derived from the
session's user-role senders; exactly one writes agent-user scope, zero or
several write nothing and return ActionSkipped naming the count.
- docs/architecture: the settled decision recorded in migration-decisions §5
(superseding the 2026-09-02 marker entry) and agent-system.md pointing at it.
Draft: to be squashed and reviewed before publication.
* test(curator): conform the registry's fake memory engine to the CRUD contract
The fake still implemented the pre-CRUD Store surface (Write taking an
Observation, List/Forget keyed by a bare string), so the package's test
binary no longer compiles: fakeMemoryEngine is missing Create, Get, Update
and Revisions, and domainmemory.Observation no longer exists. That took
`go fix ./...`, `go vet ./...` and `go test ./...` down with it, which is
what `task check` runs first.
Missed by the same commit that updated internal/infrastructure/sessioncurator's
own fake to the new interface. Repaired on the fake, not by loosening the
interface: the fake is the only thing out of date.
* fix(sessioncurator): refuse to attribute a session with unidentified user messages
sessionParticipant skipped user-role messages with an empty SenderID and
counted only the identified ones, so a session holding one identified sender
plus any number of unidentified user messages yielded that sender as the
single participant. Those messages are still part of the excerpt the
extraction model reads, so facts derived from content of unknown provenance
were written into the identified sender's agent-user scope: user A's memory
can end up crediting content that may belong to someone else. It is exactly
the case the function's own doc comment claims to handle, which it only
caught when no message at all was identified.
An unidentified user message now makes the session unattributable outright,
beside any number of identified senders, and the skip action's reason names
the count instead of reporting a sender count that no longer explains the
skip. Assistant-role messages are unaffected: they carry the bot, so they
still cannot manufacture a participant.
Fixed in sessionParticipant rather than at the write, because it is the
single producer of the attribution decision: it now returns the participant
or the reason there is none, so the caller cannot print a reason that
disagrees with what it decided. The fail-closed path (nothing written, one
ActionSkipped) and the extraction flow are unchanged.
* fix(memory): carry record content through the block format intact
builtin.Store's format ends a block at a blank line and starts a section at a
"## " line, but storeContent only trimmed the content and rejected an empty
one. Content holding either delimiter was accepted, written, and answered back
to the caller in full -- then read back truncated at the delimiter by Get,
List, or a process restart, with the remainder unaddressable and no error
anywhere along the path.
Fixed at the producer, in the render/parse pair that owns the block format:
renderBlock escapes the two delimiter shapes (an empty line becomes a single
backslash, a line already starting with a backslash or "## " gains one) and
parseBlocks undoes it on the way back, so a record's content survives the
write whole. Rejecting the content instead would have made an ordinary
multi-paragraph note or a quoted heading unrepresentable; escaping every line
would have changed the on-disk shape of every record. Only the lines that need
it are escaped, so a one-paragraph record is byte-identical to what the
unfixed engine wrote and the document stays hand-editable.
Reachable from both producers: the chat tool's note and the curator's
model-extracted fact are free text, and neither is constrained to one
paragraph.
Tests: TestBuiltinEngineRenderedBlockRoundTripsContent asserts
parseBlocks(renderBlock(c)) == c for eleven content shapes, and
TestBuiltinEngineContentSurvivesTheWriteAndAReopen carries the same shapes
through Create, Get, and a second engine reading the file a restart would.
* fix(memory): compare Update's expected revision against the file, not the cache
Update read the record to compare against out of findBlock(stores.live, ...)
-- the engine's cached copy of the scope document -- and checked Expected
against that copy. This engine caches one document per scope and rewrites it
whole, so a second engine over the same scope file (archied and the gateway,
or a restart) holds a copy taken when it last read the file: its view of the
record's revision is superseded, Expected matches the revision it remembers,
ErrStaleRevision never fires, and the rewrite that follows writes that stale
copy back over the file -- discarding the other writer's update and every
record written since the copy was loaded. The field existed and could not
fire.
Reload the scope document before anything is decided from it, so the check
answers about the revision actually on disk and the rewrite starts from the
current document. That is the smaller of the two fixes the PRD leaves open
("Not determined": a reload-before-mutate or an advisory lock); no locking
scheme, no retry loop, and no change to the read paths.
Still unsolved, and deliberately: the whole-document rewrite is
last-writer-wins between the reload and the write, so two engines writing one
scope concurrently can still lose one of the two writes, and HISTORY.md is
rewritten from the cached copy the same way.
Tests: TestBuiltinEngineSecondEngineCannotReuseAStaleRevision asserts the
second engine gets ErrStaleRevision and the first writer's state survives;
TestBuiltinEngineUpdateDoesNotEraseRecordsItHasNotLoaded asserts the record
written after the second engine loaded is still there after its update.
* fix(memory): emit the scanner's warning instead of dropping it
scanContent returned nil for every result that was not ThreatBlock, so a
ThreatWarn result -- documented in the scanner as "allow the write but emit a
warning", and what every sensitive-data match produces (API keys, passwords,
tokens, private keys) -- was stored with no audit signal anywhere. The
comment justified the silence by pointing at Bind, but Bind's argument is
about Registrar.Events: internal/events declares no memory kind and the
composition binds no memory event sink, so an invented kind would look wired
and not be. A scanner warning is a diagnostic rather than an event, and there
was nothing else to carry it: the registrar had no logger.
Bind now takes Registrar.Log, optional and mirroring the curator family's
Registrar for the same reason, scanContent emits the warn-level result
through it before the write is allowed, and bootstrap passes the daemon's
logger so the line reaches archied's configured sinks instead of only the
process default. The write is still allowed: only the silence changed.
Tests: TestBuiltinEngineScanWarnsWithoutRefusingTheWrite runs Create and
Update over warn, clean and block content, asserting the write lands either
way, that a warn-level scan result logs exactly one warning carrying the
scanner's own message, that clean content logs none, and that a refused
block-level match logs none.
* test(memory): carry every content shape through Update and Revisions
Update replaces the block it read out of the document by that text, and
retains the superseded state in HISTORY.md, so an escaped block has to be
found, superseded and retained exactly like an unescaped one. Covered here
rather than left to the Create path: without the escaping, every shape in
this table came back truncated after an update, including the plain
one-paragraph record whose replacement holds a blank line.
The test asserts values only: the updated record as a second engine reads it
off disk, and the superseded content as Revisions returns it.
* style(memory): apply the linter's gofumpt form to the Update revision error
golangci-lint's bundled gofumpt wants the closing paren of that wrapped
fmt.Errorf on its own line; the standalone gofumpt binary the fmt task uses
(0.7.0, a different version) leaves it as it was. The text is unchanged from
before the engine fixes in this branch, so this is pre-existing drift inside a
function these commits already touch -- taken so the file is clean under both
formatters rather than only one.
290 lines
11 KiB
Go
290 lines
11 KiB
Go
package sessioncurator
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/samcharles93/archie-core/internal/domain/curator"
|
|
domainmemory "github.com/samcharles93/archie-core/internal/domain/memory"
|
|
)
|
|
|
|
// Name is the identifier this curator registers under.
|
|
const Name = "session-memory"
|
|
|
|
// ActionExtracted records a session's extracted observations being
|
|
// written.
|
|
const ActionExtracted = "memory.extracted"
|
|
|
|
// ActionSkipped records a session the pass could not attribute to exactly
|
|
// one participant, so nothing was written for it. The reason names how many
|
|
// distinct senders were found (zero for a dashboard or webhook session,
|
|
// more than one for a group chat), and how many user messages carried no
|
|
// sender at all -- unknown provenance rules a session out on its own, beside
|
|
// any number of identified senders.
|
|
const ActionSkipped = "memory.skipped"
|
|
|
|
// DefaultInterval is the check-in cadence used when nothing more
|
|
// specific configures one, matching skillcurator.DefaultInterval's
|
|
// convention (no per-curator interval config surface exists yet).
|
|
const DefaultInterval = time.Hour
|
|
|
|
const (
|
|
// messageTailSize bounds how much of a session's history one pass
|
|
// reads, deliberately generous against the model's context rather
|
|
// than tuned tightly. See docs/prds/session-memory-curator.md.
|
|
messageTailSize = 40
|
|
// maxObservationsPerSession caps how many facts one pass writes for
|
|
// one session -- a prompt-precision problem to fix, not a limit to
|
|
// quietly lift.
|
|
maxObservationsPerSession = 5
|
|
// defaultLookback is what an unset PassInput.Since resolves to (the
|
|
// first pass, or the runtime declining to name a horizon).
|
|
defaultLookback = 24 * time.Hour
|
|
)
|
|
|
|
// Curator implements domain/curator.CuratorEngine. See
|
|
// docs/prds/session-memory-curator.md for what a pass does and why:
|
|
// session-scoped extraction only, written through the bound memory
|
|
// engine, no cross-session consolidation, no forgetting.
|
|
type Curator struct {
|
|
interval time.Duration
|
|
engineName string
|
|
host curator.Registrar
|
|
}
|
|
|
|
// New builds a session-memory curator that checks in every interval and
|
|
// writes through the named memory engine.
|
|
func New(interval time.Duration, engineName string) *Curator {
|
|
return &Curator{interval: interval, engineName: engineName}
|
|
}
|
|
|
|
func (c *Curator) Name() string { return Name }
|
|
func (c *Curator) Version() string { return "1" }
|
|
|
|
func (c *Curator) Manifest() curator.Manifest {
|
|
return curator.Manifest{
|
|
Interval: c.interval,
|
|
OnInput: true,
|
|
Conversations: true,
|
|
MemoryEngine: c.engineName,
|
|
}
|
|
}
|
|
|
|
func (c *Curator) Bind(host curator.Registrar) { c.host = host }
|
|
|
|
func (c *Curator) Start(context.Context) error { return nil }
|
|
|
|
func (c *Curator) Health(context.Context) curator.Health {
|
|
return curator.Health{Status: curator.HealthHealthy}
|
|
}
|
|
|
|
func (c *Curator) Stop(context.Context) error { return nil }
|
|
|
|
// Check reports whether any session has been active since the effective
|
|
// lookback horizon. Cheap: a session list, no model call.
|
|
func (c *Curator) Check(ctx context.Context) (bool, error) {
|
|
sessions, err := c.host.Conversations.RecentSessions(ctx, effectiveSince(time.Time{}, c.host.Clock.Now()))
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return len(sessions) > 0, nil
|
|
}
|
|
|
|
// Pass extracts durable observations from every session active since the
|
|
// last pass (or defaultLookback on the first pass) and writes them
|
|
// through the bound memory engine. See docs/prds/session-memory-curator.md
|
|
// for the exact extraction and classification rules.
|
|
func (c *Curator) Pass(ctx context.Context, in curator.PassInput) (curator.PassResult, error) {
|
|
engine, ok := c.host.MemoryEngines.Get(c.engineName)
|
|
if !ok {
|
|
return curator.PassResult{}, fmt.Errorf("sessioncurator: memory engine %q not found", c.engineName)
|
|
}
|
|
|
|
since := effectiveSince(in.Since, c.host.Clock.Now())
|
|
sessions, err := c.host.Conversations.RecentSessions(ctx, since)
|
|
if err != nil {
|
|
return curator.PassResult{}, err
|
|
}
|
|
|
|
var actions []curator.Action
|
|
for _, sess := range sessions {
|
|
action, err := c.reviewOne(ctx, engine, sess)
|
|
if err != nil {
|
|
return curator.PassResult{}, fmt.Errorf("session %q: %w", sess.ID, err)
|
|
}
|
|
if action != nil {
|
|
actions = append(actions, *action)
|
|
}
|
|
}
|
|
return curator.PassResult{Actions: actions}, nil
|
|
}
|
|
|
|
// effectiveSince resolves a zero PassInput.Since to defaultLookback
|
|
// before now, rather than the beginning of time -- extracting from a
|
|
// session's entire history on the first pass is exactly the unbounded
|
|
// cold-start cost Check exists to keep cheap.
|
|
func effectiveSince(since, now time.Time) time.Time {
|
|
if since.IsZero() {
|
|
return now.Add(-defaultLookback)
|
|
}
|
|
return since
|
|
}
|
|
|
|
// reviewOne extracts observations from one session's recent messages and
|
|
// writes them through engine as agent-user memory for the session's single
|
|
// participant. Returns nil (no Action) when nothing was extracted --
|
|
// matching the skill curator's "a pass with nothing to report is not an
|
|
// error" -- or when the session carries no messages at all. A session that
|
|
// cannot be attributed to one participant is skipped with an Action saying
|
|
// so.
|
|
func (c *Curator) reviewOne(ctx context.Context, engine domainmemory.MemoryEngine, sess curator.SessionSummary) (*curator.Action, error) {
|
|
msgs, err := c.host.Conversations.Messages(ctx, sess.ID, messageTailSize)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(msgs) == 0 {
|
|
return nil, nil
|
|
}
|
|
|
|
// Resolve the participant before spending a model call: an
|
|
// unattributable session has nowhere addressable to write, so there is
|
|
// nothing a model response could add. ScopeAgentUser is addressed by
|
|
// both ids, and a guess would file one person's facts under another's.
|
|
participant, reason := sessionParticipant(msgs)
|
|
if participant == "" {
|
|
return &curator.Action{
|
|
At: c.host.Clock.Now(),
|
|
Type: ActionSkipped,
|
|
Detail: sess.ID,
|
|
Reason: reason,
|
|
}, nil
|
|
}
|
|
|
|
text, err := c.askModel(ctx, msgs)
|
|
if err != nil {
|
|
// A real model-call failure (provider down, timeout) is a Pass
|
|
// error: it says nothing about whether this session had anything
|
|
// worth extracting, unlike an unparseable response below.
|
|
return nil, err
|
|
}
|
|
facts, err := parseFacts(text)
|
|
if err != nil {
|
|
// A response that doesn't parse is "nothing extracted", not a
|
|
// pass failure -- the next pass tries again, and this is a
|
|
// curator, not a build gate.
|
|
return nil, nil //nolint:nilerr // documented above: a parse failure degrades to a no-op for this session, not a Pass error
|
|
}
|
|
if len(facts) == 0 {
|
|
return nil, nil
|
|
}
|
|
if len(facts) > maxObservationsPerSession {
|
|
facts = facts[:maxObservationsPerSession]
|
|
}
|
|
|
|
// Agent-user is the only defensible home for a derived fact about a
|
|
// person: agent scope would leak user A's facts to user B through the
|
|
// same agent, user scope would pool them across agents, and the session
|
|
// id this used to write stops meaning anything when the session ends.
|
|
// ScopeAgentUser is also what a later chat turn reads back, which is
|
|
// the whole point of writing these at all.
|
|
scope := domainmemory.Scope{
|
|
Kind: domainmemory.ScopeAgentUser,
|
|
Agent: domainmemory.AgentID(sess.AgentID),
|
|
User: domainmemory.IdentityID(participant),
|
|
}
|
|
for _, fact := range facts {
|
|
if _, err := engine.Create(ctx, domainmemory.NewRecord{
|
|
Scope: scope,
|
|
Kind: "note",
|
|
Content: fact,
|
|
Author: Name,
|
|
OriginUser: domainmemory.IdentityID(participant),
|
|
Source: sess.ID,
|
|
}); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
return &curator.Action{
|
|
At: c.host.Clock.Now(),
|
|
Type: ActionExtracted,
|
|
Detail: fmt.Sprintf("%s: wrote %d observation(s)", sess.ID, len(facts)),
|
|
Reason: "session active since last pass",
|
|
}, nil
|
|
}
|
|
|
|
// sessionParticipant returns the one participant a session's memory may be
|
|
// attributed to, or -- when there is none -- the reason there isn't.
|
|
//
|
|
// Only user-role messages carry a person: an assistant message carries the
|
|
// bot, so it can never manufacture a participant.
|
|
//
|
|
// A user-role message with an empty SenderID is part of the excerpt the
|
|
// model reads but names nobody, so the session is unattributable outright,
|
|
// even beside exactly one identified sender. The alternative -- skipping it
|
|
// and attributing the rest -- would credit whoever that sender is with
|
|
// facts drawn from content of unknown provenance, which is the isolation
|
|
// failure the agent-user scope exists to prevent.
|
|
func sessionParticipant(msgs []curator.ConversationMessage) (participant, reason string) {
|
|
senders := make(map[string]struct{})
|
|
unidentified := 0
|
|
for _, m := range msgs {
|
|
if m.Role != "user" {
|
|
continue
|
|
}
|
|
if m.SenderID == "" {
|
|
unidentified++
|
|
continue
|
|
}
|
|
senders[m.SenderID] = struct{}{}
|
|
}
|
|
|
|
if unidentified > 0 {
|
|
return "", fmt.Sprintf("no single participant: %d distinct sender(s), %d unidentified user message(s)", len(senders), unidentified)
|
|
}
|
|
if len(senders) == 1 {
|
|
for id := range senders {
|
|
return id, ""
|
|
}
|
|
}
|
|
return "", fmt.Sprintf("no single participant: %d distinct sender(s)", len(senders))
|
|
}
|
|
|
|
// extractPrompt instructs the model to return a JSON array of short,
|
|
// durable strings -- facts, preferences, or corrections worth keeping --
|
|
// or [] if nothing in the excerpt is worth keeping. No prose outside the
|
|
// array: the response is parsed directly as JSON.
|
|
const extractPrompt = `Review this conversation excerpt. List any durable facts, preferences, or corrections about the user or their work that are worth remembering for future conversations -- not the flow of the conversation itself, not anything already obvious from context, not one-off task details.
|
|
|
|
Respond with ONLY a JSON array of short strings, one per fact. Respond with [] if nothing in this excerpt is worth keeping. No other text.`
|
|
|
|
// askModel sends msgs plus the extraction instruction and returns the
|
|
// model's raw response text. A non-nil error here is a real failure
|
|
// (provider down, timeout) -- distinct from parseFacts failing on a
|
|
// response that came back but wasn't valid JSON.
|
|
func (c *Curator) askModel(ctx context.Context, msgs []curator.ConversationMessage) (string, error) {
|
|
chatMsgs := make([]curator.Message, 0, len(msgs)+1)
|
|
chatMsgs = append(chatMsgs, curator.Message{Role: "system", Content: extractPrompt})
|
|
for _, m := range msgs {
|
|
chatMsgs = append(chatMsgs, curator.Message{Role: m.Role, Content: m.Content})
|
|
}
|
|
|
|
res, err := c.host.LLM.Chat(ctx, curator.ChatRequest{Model: c.host.Model, Messages: chatMsgs})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return res.Text, nil
|
|
}
|
|
|
|
// parseFacts parses the model's response as a JSON array of strings.
|
|
func parseFacts(text string) ([]string, error) {
|
|
var facts []string
|
|
if err := json.Unmarshal([]byte(strings.TrimSpace(text)), &facts); err != nil {
|
|
return nil, err
|
|
}
|
|
return facts, nil
|
|
}
|