* 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.
695 lines
20 KiB
Go
695 lines
20 KiB
Go
package curator
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"slices"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
domainmemory "github.com/samcharles93/archie-core/internal/domain/memory"
|
|
"github.com/samcharles93/archie-core/internal/tools"
|
|
)
|
|
|
|
// --- host-service fakes -----------------------------------------------------
|
|
|
|
type testLLM struct{ calls int }
|
|
|
|
func (l *testLLM) Chat(_ context.Context, _ ChatRequest) (ChatResult, error) {
|
|
l.calls++
|
|
return ChatResult{Text: "ok"}, nil
|
|
}
|
|
|
|
type testBuilder struct{ built [][]string }
|
|
|
|
func (b *testBuilder) Build(_ context.Context, declared []string) ([]tools.ToolEntry, error) {
|
|
b.built = append(b.built, declared)
|
|
return nil, nil
|
|
}
|
|
|
|
type testStore struct{}
|
|
|
|
func (testStore) List(context.Context) ([]SkillRef, error) { return nil, nil }
|
|
func (testStore) Read(context.Context, string) (Skill, error) { return Skill{}, nil }
|
|
func (testStore) Write(context.Context, Skill) error { return nil }
|
|
func (testStore) Delete(context.Context, string) error { return nil }
|
|
|
|
// testMemoryEngines is a fake MemoryEngineSource with one engine, "builtin".
|
|
type testMemoryEngines struct{}
|
|
|
|
func (testMemoryEngines) Get(name string) (domainmemory.MemoryEngine, bool) {
|
|
if name != "builtin" {
|
|
return nil, false
|
|
}
|
|
return fakeMemoryEngine{}, true
|
|
}
|
|
|
|
// fakeMemoryEngine is the minimal domain/memory.MemoryEngine a resolved
|
|
// lookup can return; its own behavior is exercised by
|
|
// internal/domain/memory's and internal/infrastructure/memory's own test
|
|
// suites, not here.
|
|
type fakeMemoryEngine struct{}
|
|
|
|
func (fakeMemoryEngine) Name() string { return "builtin" }
|
|
func (fakeMemoryEngine) Version() string { return "test" }
|
|
func (fakeMemoryEngine) Manifest() domainmemory.Manifest { return domainmemory.Manifest{} }
|
|
func (fakeMemoryEngine) Bind(domainmemory.Registrar) {}
|
|
func (fakeMemoryEngine) Start(context.Context) error { return nil }
|
|
func (fakeMemoryEngine) Health(context.Context) domainmemory.Health {
|
|
return domainmemory.Health{Status: domainmemory.HealthHealthy}
|
|
}
|
|
func (fakeMemoryEngine) Stop(context.Context) error { return nil }
|
|
|
|
func (fakeMemoryEngine) Create(context.Context, domainmemory.NewRecord) (domainmemory.Record, error) {
|
|
return domainmemory.Record{}, nil
|
|
}
|
|
|
|
func (fakeMemoryEngine) Get(context.Context, domainmemory.Scope, domainmemory.RecordID) (domainmemory.Record, error) {
|
|
return domainmemory.Record{}, domainmemory.ErrNotFound
|
|
}
|
|
|
|
func (fakeMemoryEngine) Query(context.Context, domainmemory.Query) ([]domainmemory.Record, error) {
|
|
return nil, nil
|
|
}
|
|
|
|
func (fakeMemoryEngine) List(context.Context, domainmemory.Scope) ([]domainmemory.Record, error) {
|
|
return nil, nil
|
|
}
|
|
|
|
func (fakeMemoryEngine) Update(context.Context, domainmemory.RecordUpdate) (domainmemory.Record, error) {
|
|
return domainmemory.Record{}, domainmemory.ErrNotFound
|
|
}
|
|
|
|
func (fakeMemoryEngine) Forget(context.Context, domainmemory.Scope, domainmemory.RecordID) error {
|
|
return nil
|
|
}
|
|
|
|
func (fakeMemoryEngine) Revisions(context.Context, domainmemory.Scope, domainmemory.RecordID) ([]domainmemory.Revision, error) {
|
|
return nil, nil
|
|
}
|
|
|
|
// testConversations is a fake ConversationSource with one session and no
|
|
// messages -- enough for the presence/absence tests, which never call
|
|
// its methods.
|
|
type testConversations struct{}
|
|
|
|
func (testConversations) RecentSessions(context.Context, time.Time) ([]SessionSummary, error) {
|
|
return nil, nil
|
|
}
|
|
|
|
func (testConversations) Messages(context.Context, string, int) ([]ConversationMessage, error) {
|
|
return nil, nil
|
|
}
|
|
|
|
type testSink struct {
|
|
mu sync.Mutex
|
|
kinds []string
|
|
}
|
|
|
|
func (s *testSink) Emit(kind, _ string, _ map[string]any) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.kinds = append(s.kinds, kind)
|
|
}
|
|
|
|
func (s *testSink) kindsOf() []string {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
return slices.Clone(s.kinds)
|
|
}
|
|
|
|
func (s *testSink) count(kind string) int {
|
|
n := 0
|
|
for _, k := range s.kindsOf() {
|
|
if k == kind {
|
|
n++
|
|
}
|
|
}
|
|
return n
|
|
}
|
|
|
|
type testClock struct{ now time.Time }
|
|
|
|
func (c testClock) Now() time.Time { return c.now }
|
|
func (c testClock) After(d time.Duration) <-chan time.Time {
|
|
return time.After(d)
|
|
}
|
|
|
|
// --- fake curator ------------------------------------------------------------
|
|
|
|
type fakeCurator struct {
|
|
name string
|
|
manifest Manifest
|
|
events []string
|
|
recorder *[]string // shared lifecycle log; nil means record to events
|
|
startErr error
|
|
stopErr error
|
|
stopBlock chan struct{}
|
|
bindPanic bool
|
|
view Registrar
|
|
|
|
// pass/check control (runtime tests).
|
|
checkResult bool
|
|
checkErr error
|
|
checkPanic bool
|
|
checkCalls atomic.Int32
|
|
passResult PassResult
|
|
passErr error
|
|
passPanic bool
|
|
passBlock chan struct{} // if set, Pass blocks until closed or ctx done
|
|
passIgnoreCtx bool // if true, Pass ignores ctx while blocked
|
|
passCalls atomic.Int32
|
|
inputMu sync.Mutex
|
|
inputs []PassInput
|
|
}
|
|
|
|
func newFake(name string, manifest Manifest) *fakeCurator {
|
|
return &fakeCurator{name: name, manifest: manifest}
|
|
}
|
|
|
|
func (f *fakeCurator) record(e string) {
|
|
if f.recorder != nil {
|
|
*f.recorder = append(*f.recorder, e)
|
|
} else {
|
|
f.events = append(f.events, e)
|
|
}
|
|
}
|
|
|
|
func (f *fakeCurator) Name() string { return f.name }
|
|
func (f *fakeCurator) Version() string { return "test" }
|
|
func (f *fakeCurator) Manifest() Manifest { return f.manifest }
|
|
func (f *fakeCurator) Bind(host Registrar) {
|
|
f.view = host
|
|
f.record("bind:" + f.name)
|
|
if f.bindPanic {
|
|
panic("bind boom")
|
|
}
|
|
}
|
|
|
|
func (f *fakeCurator) Check(context.Context) (bool, error) {
|
|
f.checkCalls.Add(1)
|
|
if f.checkPanic {
|
|
panic("check boom")
|
|
}
|
|
if f.checkErr != nil {
|
|
return false, f.checkErr
|
|
}
|
|
return f.checkResult, nil
|
|
}
|
|
|
|
func (f *fakeCurator) Pass(ctx context.Context, in PassInput) (PassResult, error) {
|
|
f.passCalls.Add(1)
|
|
f.inputMu.Lock()
|
|
f.inputs = append(f.inputs, in)
|
|
f.inputMu.Unlock()
|
|
if f.passPanic {
|
|
panic("pass boom")
|
|
}
|
|
if f.passBlock != nil {
|
|
if f.passIgnoreCtx {
|
|
<-f.passBlock
|
|
} else {
|
|
select {
|
|
case <-f.passBlock:
|
|
case <-ctx.Done():
|
|
return PassResult{}, ctx.Err()
|
|
}
|
|
}
|
|
}
|
|
if f.passErr != nil {
|
|
return PassResult{}, f.passErr
|
|
}
|
|
return f.passResult, nil
|
|
}
|
|
|
|
func (f *fakeCurator) Start(context.Context) error {
|
|
if f.startErr != nil {
|
|
return f.startErr
|
|
}
|
|
f.record("start:" + f.name)
|
|
return nil
|
|
}
|
|
|
|
func (f *fakeCurator) Health(context.Context) Health { return Health{Status: HealthHealthy} }
|
|
|
|
func (f *fakeCurator) Stop(ctx context.Context) error {
|
|
if f.stopBlock != nil {
|
|
select {
|
|
case <-f.stopBlock:
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
}
|
|
}
|
|
if f.stopErr != nil {
|
|
return f.stopErr
|
|
}
|
|
f.record("stop:" + f.name)
|
|
return nil
|
|
}
|
|
|
|
// --- registry behavior -------------------------------------------------------
|
|
|
|
func TestRegistryRegisterAndDiscover(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
r := NewRegistry(Registrar{})
|
|
a := newFake("a", Manifest{Interval: time.Hour})
|
|
b := newFake("b", Manifest{Interval: time.Hour})
|
|
if err := r.Register(a); err != nil {
|
|
t.Fatalf("Register(a) = %v, want nil", err)
|
|
}
|
|
if err := r.Register(b); err != nil {
|
|
t.Fatalf("Register(b) = %v, want nil", err)
|
|
}
|
|
|
|
got, ok := r.Get("a")
|
|
if !ok || got != a {
|
|
t.Fatalf("Get(a) = (%v, %v), want (a, true)", got, ok)
|
|
}
|
|
if _, ok := r.Get("missing"); ok {
|
|
t.Fatal("Get(missing) = true, want false")
|
|
}
|
|
|
|
if got := r.Names(); len(got) != 2 || got[0] != "a" || got[1] != "b" {
|
|
t.Fatalf("Names() = %v, want [a b]", got)
|
|
}
|
|
}
|
|
|
|
func TestRegistryRegisterDuplicateRejected(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
r := NewRegistry(Registrar{})
|
|
a := newFake("a", Manifest{Interval: time.Hour})
|
|
if err := r.Register(a); err != nil {
|
|
t.Fatalf("Register(a) = %v, want nil", err)
|
|
}
|
|
err := r.Register(newFake("a", Manifest{Interval: time.Hour}))
|
|
if !errors.Is(err, ErrDuplicate) {
|
|
t.Fatalf("Register(dup) = %v, want ErrDuplicate", err)
|
|
}
|
|
if got := r.Names(); len(got) != 1 {
|
|
t.Fatalf("Names() = %v, want only the first registration", got)
|
|
}
|
|
}
|
|
|
|
func TestRegistryRegisterNilEngineRejected(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
r := NewRegistry(Registrar{})
|
|
if err := r.Register(nil); err == nil {
|
|
t.Fatal("Register(nil) = nil, want error")
|
|
}
|
|
}
|
|
|
|
func TestRegistryRegisterTypedNilEngineRejected(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
r := NewRegistry(Registrar{})
|
|
var c *fakeCurator
|
|
if err := r.Register(c); err == nil {
|
|
t.Fatal("Register(typed nil) = nil, want error")
|
|
}
|
|
}
|
|
|
|
func TestRegistryRegisterInvalidManifestRejected(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
r := NewRegistry(Registrar{})
|
|
if err := r.Register(newFake("bad", Manifest{})); err == nil {
|
|
t.Fatal("Register(zero interval) = nil, want error")
|
|
}
|
|
if got := r.Names(); len(got) != 0 {
|
|
t.Fatalf("Names() = %v, want empty after rejected registration", got)
|
|
}
|
|
}
|
|
|
|
func TestRegistryRegisterAfterStartRejected(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
r := NewRegistry(Registrar{})
|
|
if err := r.Register(newFake("a", Manifest{Interval: time.Hour})); err != nil {
|
|
t.Fatalf("Register(a) = %v, want nil", err)
|
|
}
|
|
if err := r.Start(context.Background()); err != nil {
|
|
t.Fatalf("Start() = %v, want nil", err)
|
|
}
|
|
err := r.Register(newFake("b", Manifest{Interval: time.Hour}))
|
|
if !errors.Is(err, ErrStarted) {
|
|
t.Fatalf("Register after Start = %v, want ErrStarted", err)
|
|
}
|
|
}
|
|
|
|
func TestRegistryDeclaredCapabilitiesRequireHostServices(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
tests := []struct {
|
|
name string
|
|
host Registrar
|
|
manifest Manifest
|
|
wantErr bool
|
|
}{
|
|
{
|
|
name: "tools declared, no builder",
|
|
host: Registrar{},
|
|
manifest: Manifest{Interval: time.Hour, Tools: []string{"skills.list"}},
|
|
wantErr: true,
|
|
},
|
|
{
|
|
name: "tools declared, builder present",
|
|
host: Registrar{Tools: &testBuilder{}},
|
|
manifest: Manifest{Interval: time.Hour, Tools: []string{"skills.list"}},
|
|
},
|
|
{
|
|
name: "skills declared, no store",
|
|
host: Registrar{},
|
|
manifest: Manifest{Interval: time.Hour, Skills: true},
|
|
wantErr: true,
|
|
},
|
|
{
|
|
name: "skills declared, store present",
|
|
host: Registrar{Skills: testStore{}},
|
|
manifest: Manifest{Interval: time.Hour, Skills: true},
|
|
},
|
|
{
|
|
name: "memory engine declared, no source",
|
|
host: Registrar{},
|
|
manifest: Manifest{Interval: time.Hour, MemoryEngine: "builtin"},
|
|
wantErr: true,
|
|
},
|
|
{
|
|
name: "memory engine declared, source present",
|
|
host: Registrar{MemoryEngines: testMemoryEngines{}},
|
|
manifest: Manifest{Interval: time.Hour, MemoryEngine: "builtin"},
|
|
},
|
|
{
|
|
name: "conversations declared, no source",
|
|
host: Registrar{},
|
|
manifest: Manifest{Interval: time.Hour, Conversations: true},
|
|
wantErr: true,
|
|
},
|
|
{
|
|
name: "conversations declared, source present",
|
|
host: Registrar{Conversations: testConversations{}},
|
|
manifest: Manifest{Interval: time.Hour, Conversations: true},
|
|
},
|
|
{
|
|
name: "nothing declared, empty host",
|
|
host: Registrar{},
|
|
manifest: Manifest{Interval: time.Hour},
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
r := NewRegistry(tt.host)
|
|
err := r.Register(newFake("c", tt.manifest))
|
|
if (err != nil) != tt.wantErr {
|
|
t.Fatalf("Register() = %v, wantErr %v", err, tt.wantErr)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestRegistryBindFiltersToDeclaredCapabilities(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
host := Registrar{
|
|
Model: "provider/default",
|
|
LLM: &testLLM{},
|
|
Tools: &testBuilder{},
|
|
Skills: testStore{},
|
|
MemoryEngines: testMemoryEngines{},
|
|
Conversations: testConversations{},
|
|
Events: &testSink{},
|
|
Clock: testClock{now: time.Unix(0, 0)},
|
|
}
|
|
|
|
// A curator declaring nothing agentic receives no model access and no
|
|
// capability services, but always receives events and time.
|
|
r := NewRegistry(host)
|
|
plain := newFake("plain", Manifest{Interval: time.Hour})
|
|
if err := r.Register(plain); err != nil {
|
|
t.Fatalf("Register(plain) = %v, want nil", err)
|
|
}
|
|
if plain.view.LLM != nil {
|
|
t.Error("view.LLM = non-nil for a curator declaring no agentic capability")
|
|
}
|
|
if plain.view.Tools != nil {
|
|
t.Error("view.Tools = non-nil for a curator declaring no tools")
|
|
}
|
|
if plain.view.Skills != nil {
|
|
t.Error("view.Skills = non-nil for a curator not declaring skills")
|
|
}
|
|
if plain.view.MemoryEngines != nil {
|
|
t.Error("view.MemoryEngines = non-nil for a curator declaring no memory engine")
|
|
}
|
|
if plain.view.Conversations != nil {
|
|
t.Error("view.Conversations = non-nil for a curator declaring no conversation history")
|
|
}
|
|
if plain.view.Events == nil {
|
|
t.Error("view.Events = nil; activity must always be attributable")
|
|
}
|
|
if plain.view.Clock == nil {
|
|
t.Error("view.Clock = nil; time is always available")
|
|
}
|
|
|
|
// A curator declaring tools and skills receives exactly those, plus the
|
|
// model access an agentic pass needs.
|
|
toolsy := newFake("toolsy", Manifest{Interval: time.Hour, Tools: []string{"skills.list"}, Skills: true})
|
|
if err := r.Register(toolsy); err != nil {
|
|
t.Fatalf("Register(toolsy) = %v, want nil", err)
|
|
}
|
|
if toolsy.view.LLM == nil {
|
|
t.Error("view.LLM = nil for a curator declaring agentic capabilities")
|
|
}
|
|
if toolsy.view.Tools == nil {
|
|
t.Error("view.Tools = nil for a curator declaring tools")
|
|
}
|
|
if toolsy.view.Skills == nil {
|
|
t.Error("view.Skills = nil for a curator declaring skills")
|
|
}
|
|
|
|
// A curator declaring only a memory engine still needs model access to
|
|
// reason over memory.
|
|
mem := newFake("mem", Manifest{Interval: time.Hour, MemoryEngine: "builtin"})
|
|
if err := r.Register(mem); err != nil {
|
|
t.Fatalf("Register(mem) = %v, want nil", err)
|
|
}
|
|
if mem.view.LLM == nil {
|
|
t.Error("view.LLM = nil for a curator declaring a memory engine")
|
|
}
|
|
if mem.view.Tools != nil {
|
|
t.Error("view.Tools = non-nil for a curator declaring no tools")
|
|
}
|
|
if mem.view.MemoryEngines == nil {
|
|
t.Error("view.MemoryEngines = nil for a curator declaring a memory engine")
|
|
}
|
|
if _, ok := mem.view.MemoryEngines.Get("builtin"); !ok {
|
|
t.Error("view.MemoryEngines.Get(builtin) = not found, want the fake engine registered under that name")
|
|
}
|
|
|
|
// A curator declaring conversation history receives it, and model
|
|
// access to reason over it.
|
|
convo := newFake("convo", Manifest{Interval: time.Hour, Conversations: true})
|
|
if err := r.Register(convo); err != nil {
|
|
t.Fatalf("Register(convo) = %v, want nil", err)
|
|
}
|
|
if convo.view.LLM == nil {
|
|
t.Error("view.LLM = nil for a curator declaring conversation history")
|
|
}
|
|
if convo.view.Conversations == nil {
|
|
t.Error("view.Conversations = nil for a curator declaring conversation history")
|
|
}
|
|
}
|
|
|
|
func TestRegistryBindPanicIsolated(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
r := NewRegistry(Registrar{})
|
|
panicky := newFake("panicky", Manifest{Interval: time.Hour})
|
|
panicky.bindPanic = true
|
|
if err := r.Register(panicky); err == nil {
|
|
t.Fatal("Register(panicking Bind) = nil, want error")
|
|
}
|
|
if got := r.Names(); len(got) != 0 {
|
|
t.Fatalf("Names() = %v, want empty after a panicking Bind", got)
|
|
}
|
|
|
|
// The registry survives and still accepts healthy curators.
|
|
if err := r.Register(newFake("ok", Manifest{Interval: time.Hour})); err != nil {
|
|
t.Fatalf("Register(ok) after panicking Bind = %v, want nil", err)
|
|
}
|
|
}
|
|
|
|
func TestRegistryStartStopOrdering(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
r := NewRegistry(Registrar{})
|
|
var log []string
|
|
a := newFake("a", Manifest{Interval: time.Hour})
|
|
a.recorder = &log
|
|
b := newFake("b", Manifest{Interval: time.Hour})
|
|
b.recorder = &log
|
|
c := newFake("c", Manifest{Interval: time.Hour})
|
|
c.recorder = &log
|
|
for _, cur := range []*fakeCurator{a, b, c} {
|
|
if err := r.Register(cur); err != nil {
|
|
t.Fatalf("Register(%s) = %v, want nil", cur.name, err)
|
|
}
|
|
}
|
|
|
|
if err := r.Start(context.Background()); err != nil {
|
|
t.Fatalf("Start() = %v, want nil", err)
|
|
}
|
|
if err := r.Stop(context.Background()); err != nil {
|
|
t.Fatalf("Stop() = %v, want nil", err)
|
|
}
|
|
|
|
want := []string{
|
|
"bind:a", "bind:b", "bind:c",
|
|
"start:a", "start:b", "start:c",
|
|
"stop:c", "stop:b", "stop:a",
|
|
}
|
|
if got := log; !equalStrings(got, want) {
|
|
t.Fatalf("lifecycle events = %v, want %v (start in registration order, stop reversed)", got, want)
|
|
}
|
|
}
|
|
|
|
func TestRegistryStartIsolatesFailure(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
r := NewRegistry(Registrar{})
|
|
var log []string
|
|
a := newFake("a", Manifest{Interval: time.Hour})
|
|
a.recorder = &log
|
|
bad := newFake("bad", Manifest{Interval: time.Hour})
|
|
bad.recorder = &log
|
|
bad.startErr = errBoom
|
|
c := newFake("c", Manifest{Interval: time.Hour})
|
|
c.recorder = &log
|
|
for _, cur := range []*fakeCurator{a, bad, c} {
|
|
if err := r.Register(cur); err != nil {
|
|
t.Fatalf("Register(%s) = %v, want nil", cur.name, err)
|
|
return
|
|
}
|
|
}
|
|
|
|
err := r.Start(context.Background())
|
|
if !errors.Is(err, errBoom) {
|
|
t.Fatalf("Start() error = %v, want the failing curator's error", err)
|
|
}
|
|
|
|
// The healthy curators started; the failing one never became started.
|
|
if !logHas(log, "start:a") || !logHas(log, "start:c") {
|
|
t.Fatalf("healthy curators did not start: %v", log)
|
|
}
|
|
if logHas(log, "start:bad") {
|
|
t.Fatalf("failing curator started despite Start error: %v", log)
|
|
}
|
|
|
|
health := r.Health(context.Background())
|
|
if health["bad"].Status != HealthUnhealthy {
|
|
t.Fatalf("Health(bad).Status = %v, want unhealthy", health["bad"].Status)
|
|
}
|
|
if health["a"].Status != HealthHealthy {
|
|
t.Fatalf("Health(a).Status = %v, want healthy", health["a"].Status)
|
|
}
|
|
|
|
// Stop skips the curator that never started and stops the rest in
|
|
// reverse registration order.
|
|
if err := r.Stop(context.Background()); err != nil {
|
|
t.Fatalf("Stop() = %v, want nil", err)
|
|
}
|
|
want := []string{"bind:a", "bind:bad", "bind:c", "start:a", "start:c", "stop:c", "stop:a"}
|
|
if got := log; !equalStrings(got, want) {
|
|
t.Fatalf("lifecycle events = %v, want %v", got, want)
|
|
}
|
|
}
|
|
|
|
func TestRegistryStopBoundedByContext(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
r := NewRegistry(Registrar{})
|
|
blocked := newFake("blocked", Manifest{Interval: time.Hour})
|
|
blocked.stopBlock = make(chan struct{})
|
|
if err := r.Register(blocked); err != nil {
|
|
t.Fatalf("Register(blocked) = %v, want nil", err)
|
|
}
|
|
if err := r.Start(context.Background()); err != nil {
|
|
t.Fatalf("Start() = %v, want nil", err)
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
|
|
defer cancel()
|
|
start := time.Now()
|
|
err := r.Stop(ctx)
|
|
elapsed := time.Since(start)
|
|
|
|
if !errors.Is(err, context.DeadlineExceeded) {
|
|
t.Fatalf("Stop() error = %v, want context.DeadlineExceeded", err)
|
|
}
|
|
if elapsed > 2*time.Second {
|
|
t.Fatalf("Stop() took %v; a blocking curator must not hang shutdown", elapsed)
|
|
}
|
|
}
|
|
|
|
func TestRegistryStopBeforeStartIsNoop(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
r := NewRegistry(Registrar{})
|
|
if err := r.Register(newFake("a", Manifest{Interval: time.Hour})); err != nil {
|
|
t.Fatalf("Register(a) = %v, want nil", err)
|
|
}
|
|
if err := r.Stop(context.Background()); err != nil {
|
|
t.Fatalf("Stop() before Start = %v, want nil no-op", err)
|
|
}
|
|
}
|
|
|
|
func TestRegistryStartTwiceRejected(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
r := NewRegistry(Registrar{})
|
|
if err := r.Start(context.Background()); err != nil {
|
|
t.Fatalf("Start() = %v, want nil", err)
|
|
}
|
|
if err := r.Start(context.Background()); !errors.Is(err, ErrStarted) {
|
|
t.Fatalf("second Start() = %v, want ErrStarted", err)
|
|
}
|
|
}
|
|
|
|
func TestRegistryHealthReportsEveryCurator(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
r := NewRegistry(Registrar{})
|
|
if err := r.Register(newFake("a", Manifest{Interval: time.Hour})); err != nil {
|
|
t.Fatalf("Register(a) = %v, want nil", err)
|
|
}
|
|
health := r.Health(context.Background())
|
|
if len(health) != 1 || health["a"].Status != HealthHealthy {
|
|
t.Fatalf("Health() = %v, want one healthy entry for a", health)
|
|
}
|
|
}
|
|
|
|
// --- helpers -----------------------------------------------------------------
|
|
|
|
var errBoom = errors.New("boom")
|
|
|
|
func equalStrings(a, b []string) bool {
|
|
if len(a) != len(b) {
|
|
return false
|
|
}
|
|
for i := range a {
|
|
if a[i] != b[i] {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func logHas(log []string, want string) bool {
|
|
return slices.Contains(log, want)
|
|
}
|