* 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.
508 lines
14 KiB
Go
508 lines
14 KiB
Go
package builtin
|
|
|
|
import (
|
|
"context"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
)
|
|
|
|
func newTestProvider(t *testing.T) *Provider {
|
|
t.Helper()
|
|
p, err := New(Config{Dir: t.TempDir()})
|
|
if err != nil {
|
|
t.Fatalf("New: %v", err)
|
|
}
|
|
return p
|
|
}
|
|
|
|
func TestProvider_Identity(t *testing.T) {
|
|
p := newTestProvider(t)
|
|
if p.Name() != "builtin" {
|
|
t.Fatalf("expected name builtin, got %q", p.Name())
|
|
}
|
|
if !p.IsAvailable() {
|
|
t.Fatalf("expected builtin provider to always be available")
|
|
}
|
|
if err := p.Initialize("session-1"); err != nil {
|
|
t.Fatalf("Initialize: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestProvider_Initialize_ReloadsFromDisk(t *testing.T) {
|
|
dir := t.TempDir()
|
|
p, err := New(Config{Dir: dir})
|
|
if err != nil {
|
|
t.Fatalf("New: %v", err)
|
|
}
|
|
|
|
if err := os.WriteFile(filepath.Join(dir, "MEMORY.md"), []byte("## Facts\n\nexternal entry\n"), 0o644); err != nil {
|
|
t.Fatalf("writing external content: %v", err)
|
|
}
|
|
|
|
if err := p.Initialize("session-1"); err != nil {
|
|
t.Fatalf("Initialize: %v", err)
|
|
}
|
|
if !strings.Contains(p.memory.Render(), "external entry") {
|
|
t.Fatalf("expected Initialize to reload MEMORY.md, got %q", p.memory.Render())
|
|
}
|
|
}
|
|
|
|
func TestProvider_New_RequiresDir(t *testing.T) {
|
|
if _, err := New(Config{}); err == nil {
|
|
t.Fatalf("expected error for empty Dir")
|
|
}
|
|
}
|
|
|
|
func TestProvider_New_CreatesDirAndFiles(t *testing.T) {
|
|
dir := filepath.Join(t.TempDir(), "nested", "memory")
|
|
p, err := New(Config{Dir: dir})
|
|
if err != nil {
|
|
t.Fatalf("New: %v", err)
|
|
}
|
|
if _, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "add",
|
|
"section": "Facts",
|
|
"content": "hello",
|
|
}); err != nil {
|
|
t.Fatalf("HandleToolCall add: %v", err)
|
|
}
|
|
if _, statErr := os.Stat(filepath.Join(dir, "MEMORY.md")); statErr != nil {
|
|
t.Fatalf("expected MEMORY.md to exist: %v", statErr)
|
|
}
|
|
}
|
|
|
|
// TestProvider_GetToolSchemas checks the exported schema shape, and that
|
|
// Handler is left nil for the Manager to inject via ToolCallProvider (per
|
|
// Manager.GetToolSchemas' documented behavior).
|
|
func TestProvider_GetToolSchemas(t *testing.T) {
|
|
p := newTestProvider(t)
|
|
entries := p.GetToolSchemas()
|
|
if len(entries) != 1 {
|
|
t.Fatalf("expected exactly one tool entry, got %d", len(entries))
|
|
}
|
|
e := entries[0]
|
|
if e.Name != toolName {
|
|
t.Fatalf("expected tool name %q, got %q", toolName, e.Name)
|
|
}
|
|
if e.Handler != nil {
|
|
t.Fatalf("expected nil Handler so Manager injects the ToolCallProvider delegate")
|
|
}
|
|
|
|
// Simulate the Manager's injection and confirm the resulting entry
|
|
// passes Validate().
|
|
e = e.Clone()
|
|
e.Handler = func(ctx context.Context, input map[string]any) (any, error) {
|
|
return p.HandleToolCall(e.Name, input)
|
|
}
|
|
if err := e.Validate(); err != nil {
|
|
t.Fatalf("ToolEntry.Validate() after injection: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestProvider_HandleToolCall_UnknownTool(t *testing.T) {
|
|
p := newTestProvider(t)
|
|
if _, err := p.HandleToolCall("not_memory_edit", map[string]any{}); err == nil {
|
|
t.Fatalf("expected error for unknown tool name")
|
|
}
|
|
}
|
|
|
|
func TestProvider_HandleToolCall_Add_DefaultsToMemoryFile(t *testing.T) {
|
|
p := newTestProvider(t)
|
|
out, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "add",
|
|
"section": "Facts",
|
|
"content": "the sky is blue",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("HandleToolCall: %v", err)
|
|
}
|
|
result, ok := out.(map[string]any)
|
|
if !ok {
|
|
t.Fatalf("expected map[string]any result, got %T", out)
|
|
}
|
|
if result["file"] != "memory" {
|
|
t.Fatalf("expected default file \"memory\", got %v", result["file"])
|
|
}
|
|
if !strings.Contains(p.memory.Render(), "the sky is blue") {
|
|
t.Fatalf("expected content written to MEMORY.md, got %q", p.memory.Render())
|
|
}
|
|
if strings.Contains(p.user.Render(), "the sky is blue") {
|
|
t.Fatalf("did not expect content in USER.md")
|
|
}
|
|
}
|
|
|
|
func TestProvider_HandleToolCall_Add_UserFile(t *testing.T) {
|
|
p := newTestProvider(t)
|
|
_, err := p.HandleToolCall(toolName, map[string]any{
|
|
"file": "user",
|
|
"action": "add",
|
|
"section": "Preferences",
|
|
"content": "likes dark mode",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("HandleToolCall: %v", err)
|
|
}
|
|
if !strings.Contains(p.user.Render(), "likes dark mode") {
|
|
t.Fatalf("expected content written to USER.md, got %q", p.user.Render())
|
|
}
|
|
}
|
|
|
|
func TestProvider_HandleToolCall_UnknownFile(t *testing.T) {
|
|
p := newTestProvider(t)
|
|
_, err := p.HandleToolCall(toolName, map[string]any{
|
|
"file": "bogus",
|
|
"action": "add",
|
|
"section": "Facts",
|
|
"content": "x",
|
|
})
|
|
if err == nil {
|
|
t.Fatalf("expected error for unknown file selector")
|
|
}
|
|
}
|
|
|
|
func TestProvider_HandleToolCall_UnknownAction(t *testing.T) {
|
|
p := newTestProvider(t)
|
|
_, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "delete",
|
|
"section": "Facts",
|
|
})
|
|
if err == nil {
|
|
t.Fatalf("expected error for unknown action")
|
|
}
|
|
}
|
|
|
|
func TestProvider_HandleToolCall_Replace(t *testing.T) {
|
|
p := newTestProvider(t)
|
|
if _, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "add", "section": "Facts", "content": "the sky is blue",
|
|
}); err != nil {
|
|
t.Fatalf("add: %v", err)
|
|
}
|
|
out, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "replace", "section": "Facts", "substring": "blue", "replacement": "green",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("replace: %v", err)
|
|
}
|
|
result, ok := out.(map[string]any)
|
|
if !ok {
|
|
t.Fatalf("out is %T, want map[string]any", out)
|
|
}
|
|
if result["action"] != "replace" {
|
|
t.Fatalf("expected action replace, got %v", result["action"])
|
|
}
|
|
if !strings.Contains(p.memory.Render(), "the sky is green") {
|
|
t.Fatalf("expected replacement applied, got %q", p.memory.Render())
|
|
}
|
|
}
|
|
|
|
func TestProvider_HandleToolCall_Remove(t *testing.T) {
|
|
p := newTestProvider(t)
|
|
if _, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "add", "section": "Facts", "content": "entry one",
|
|
}); err != nil {
|
|
t.Fatalf("add: %v", err)
|
|
}
|
|
out, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "remove", "section": "Facts", "substring": "entry one",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("remove: %v", err)
|
|
}
|
|
result, ok := out.(map[string]any)
|
|
if !ok {
|
|
t.Fatalf("out is %T, want map[string]any", out)
|
|
}
|
|
if result["action"] != "remove" {
|
|
t.Fatalf("expected action remove, got %v", result["action"])
|
|
}
|
|
if strings.Contains(p.memory.Render(), "entry one") {
|
|
t.Fatalf("expected entry removed, got %q", p.memory.Render())
|
|
}
|
|
}
|
|
|
|
func TestProvider_HandleToolCall_Add_RequiresContent(t *testing.T) {
|
|
p := newTestProvider(t)
|
|
if _, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "add", "section": "Facts",
|
|
}); err == nil {
|
|
t.Fatalf("expected error when content is missing")
|
|
}
|
|
}
|
|
|
|
func TestProvider_HandleToolCall_Replace_RequiresSubstring(t *testing.T) {
|
|
p := newTestProvider(t)
|
|
if _, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "replace", "section": "Facts", "replacement": "x",
|
|
}); err == nil {
|
|
t.Fatalf("expected error when substring is missing")
|
|
}
|
|
}
|
|
|
|
func TestProvider_HandleToolCall_InvalidSectionName(t *testing.T) {
|
|
p := newTestProvider(t)
|
|
if _, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "add", "section": "bad-section!", "content": "x",
|
|
}); err == nil {
|
|
t.Fatalf("expected error for invalid section name")
|
|
}
|
|
}
|
|
|
|
// TestProvider_ConcurrentToolCalls exercises the store's mutex under
|
|
// concurrent add calls from multiple goroutines, simulating concurrent
|
|
// tool invocations against the same provider.
|
|
func TestProvider_ConcurrentToolCalls(t *testing.T) {
|
|
p := newTestProvider(t)
|
|
const n = 50
|
|
|
|
var wg sync.WaitGroup
|
|
for i := range n {
|
|
wg.Add(1)
|
|
go func(i int) {
|
|
defer wg.Done()
|
|
_, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "add",
|
|
"section": "Facts",
|
|
"content": "entry " + strconv.Itoa(i),
|
|
})
|
|
if err != nil {
|
|
t.Errorf("concurrent add %d: %v", i, err)
|
|
}
|
|
}(i)
|
|
}
|
|
wg.Wait()
|
|
|
|
rendered := p.memory.Render()
|
|
if strings.Count(rendered, "## Facts") != 1 {
|
|
t.Fatalf("expected exactly one Facts header after concurrent writes, got: %q", rendered)
|
|
}
|
|
}
|
|
|
|
// ── Frozen snapshot tests ─────────────────────────────────────────────
|
|
|
|
func TestProvider_FrozenSnapshot_NotUpdatedOnWrite(t *testing.T) {
|
|
p := newTestProvider(t)
|
|
|
|
// Add content before Initialize so the snapshot captures it.
|
|
if _, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "add", "section": "Facts", "content": "initial fact",
|
|
}); err != nil {
|
|
t.Fatalf("add before init: %v", err)
|
|
}
|
|
|
|
if err := p.Initialize("session-1"); err != nil {
|
|
t.Fatalf("Initialize: %v", err)
|
|
}
|
|
|
|
firstBlock := p.SystemPromptBlock()
|
|
if !strings.Contains(firstBlock, "initial fact") {
|
|
t.Fatalf("snapshot should contain initial fact, got: %s", firstBlock)
|
|
}
|
|
if !strings.Contains(firstBlock, "<memory>") {
|
|
t.Fatalf("snapshot should be wrapped in <memory> fences, got: %s", firstBlock)
|
|
}
|
|
|
|
// Write after initialization -- the snapshot must not change.
|
|
if _, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "add", "section": "Facts", "content": "new fact after init",
|
|
}); err != nil {
|
|
t.Fatalf("add after init: %v", err)
|
|
}
|
|
|
|
secondBlock := p.SystemPromptBlock()
|
|
if secondBlock != firstBlock {
|
|
t.Fatalf("snapshot changed after write!\nbefore: %s\nafter: %s", firstBlock, secondBlock)
|
|
}
|
|
|
|
// The file on disk should have the new content.
|
|
if !strings.Contains(p.memory.Render(), "new fact after init") {
|
|
t.Fatal("file on disk should contain the new fact")
|
|
}
|
|
}
|
|
|
|
func TestProvider_FrozenSnapshot_Disabled_ReadsLive(t *testing.T) {
|
|
dir := t.TempDir()
|
|
p, err := New(Config{Dir: dir, DisableFrozenSnapshot: true})
|
|
if err != nil {
|
|
t.Fatalf("New: %v", err)
|
|
}
|
|
|
|
if _, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "add", "section": "Facts", "content": "first",
|
|
}); err != nil {
|
|
t.Fatalf("add: %v", err)
|
|
}
|
|
|
|
if err := p.Initialize("session-1"); err != nil {
|
|
t.Fatalf("Initialize: %v", err)
|
|
}
|
|
|
|
block1 := p.SystemPromptBlock()
|
|
if !strings.Contains(block1, "first") {
|
|
t.Fatalf("expected 'first' in block, got: %s", block1)
|
|
}
|
|
|
|
// With frozen disabled, writes are immediately visible.
|
|
if _, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "add", "section": "Facts", "content": "second",
|
|
}); err != nil {
|
|
t.Fatalf("add: %v", err)
|
|
}
|
|
|
|
block2 := p.SystemPromptBlock()
|
|
if !strings.Contains(block2, "second") {
|
|
t.Fatalf("expected 'second' in live block, got: %s", block2)
|
|
}
|
|
if block1 == block2 {
|
|
t.Fatal("live mode should reflect writes immediately, but blocks are identical")
|
|
}
|
|
}
|
|
|
|
func TestProvider_FrozenSnapshot_EmptyStores(t *testing.T) {
|
|
p := newTestProvider(t)
|
|
if err := p.Initialize("session-1"); err != nil {
|
|
t.Fatalf("Initialize: %v", err)
|
|
}
|
|
|
|
block := p.SystemPromptBlock()
|
|
if block != "" {
|
|
t.Fatalf("expected empty block for empty stores, got: %s", block)
|
|
}
|
|
}
|
|
|
|
func TestProvider_FrozenSnapshot_OnlyMemory(t *testing.T) {
|
|
p := newTestProvider(t)
|
|
if _, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "add", "section": "Facts", "content": "mem only",
|
|
}); err != nil {
|
|
t.Fatalf("add: %v", err)
|
|
}
|
|
if err := p.Initialize("session-1"); err != nil {
|
|
t.Fatalf("Initialize: %v", err)
|
|
}
|
|
|
|
block := p.SystemPromptBlock()
|
|
if !strings.Contains(block, "mem only") {
|
|
t.Fatalf("expected memory content, got: %s", block)
|
|
}
|
|
if !strings.Contains(block, "<memory>") {
|
|
t.Fatal("missing <memory> fence")
|
|
}
|
|
}
|
|
|
|
func TestProvider_FrozenSnapshot_OnlyUser(t *testing.T) {
|
|
p := newTestProvider(t)
|
|
if _, err := p.HandleToolCall(toolName, map[string]any{
|
|
"file": "user", "action": "add", "section": "Preferences", "content": "user only",
|
|
}); err != nil {
|
|
t.Fatalf("add: %v", err)
|
|
}
|
|
if err := p.Initialize("session-1"); err != nil {
|
|
t.Fatalf("Initialize: %v", err)
|
|
}
|
|
|
|
block := p.SystemPromptBlock()
|
|
if !strings.Contains(block, "user only") {
|
|
t.Fatalf("expected user content, got: %s", block)
|
|
}
|
|
}
|
|
|
|
func TestProvider_FrozenSnapshot_ReInitialize(t *testing.T) {
|
|
p := newTestProvider(t)
|
|
if _, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "add", "section": "Facts", "content": "before",
|
|
}); err != nil {
|
|
t.Fatalf("add: %v", err)
|
|
}
|
|
if err := p.Initialize("session-1"); err != nil {
|
|
t.Fatalf("Initialize: %v", err)
|
|
}
|
|
|
|
block1 := p.SystemPromptBlock()
|
|
if !strings.Contains(block1, "before") {
|
|
t.Fatalf("expected 'before', got: %s", block1)
|
|
}
|
|
|
|
// Add more content and re-initialize -- snapshot should refresh.
|
|
if _, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "add", "section": "Facts", "content": "after",
|
|
}); err != nil {
|
|
t.Fatalf("add: %v", err)
|
|
}
|
|
if err := p.Initialize("session-2"); err != nil {
|
|
t.Fatalf("Initialize: %v", err)
|
|
}
|
|
|
|
block2 := p.SystemPromptBlock()
|
|
if !strings.Contains(block2, "after") {
|
|
t.Fatalf("re-init should capture new content, got: %s", block2)
|
|
}
|
|
if block1 == block2 {
|
|
t.Fatal("re-init should produce a fresh snapshot")
|
|
}
|
|
}
|
|
|
|
func TestProvider_FrozenSnapshot_DefaultEnabled(t *testing.T) {
|
|
// When FrozenSnapshot is not explicitly set, it defaults to true.
|
|
dir := t.TempDir()
|
|
p, err := New(Config{Dir: dir})
|
|
if err != nil {
|
|
t.Fatalf("New: %v", err)
|
|
}
|
|
|
|
if _, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "add", "section": "Facts", "content": "pre-init",
|
|
}); err != nil {
|
|
t.Fatalf("add: %v", err)
|
|
}
|
|
if err := p.Initialize("session-1"); err != nil {
|
|
t.Fatalf("Initialize: %v", err)
|
|
}
|
|
|
|
block1 := p.SystemPromptBlock()
|
|
|
|
// Write after init -- snapshot should be frozen.
|
|
if _, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "add", "section": "Facts", "content": "post-init",
|
|
}); err != nil {
|
|
t.Fatalf("add: %v", err)
|
|
}
|
|
|
|
block2 := p.SystemPromptBlock()
|
|
if block1 != block2 {
|
|
t.Fatal("default frozen snapshot should not change after writes")
|
|
}
|
|
}
|
|
|
|
func TestProvider_FrozenSnapshot_BothFiles(t *testing.T) {
|
|
p := newTestProvider(t)
|
|
if _, err := p.HandleToolCall(toolName, map[string]any{
|
|
"action": "add", "section": "Facts", "content": "mem content",
|
|
}); err != nil {
|
|
t.Fatalf("add memory: %v", err)
|
|
}
|
|
if _, err := p.HandleToolCall(toolName, map[string]any{
|
|
"file": "user", "action": "add", "section": "Preferences", "content": "user content",
|
|
}); err != nil {
|
|
t.Fatalf("add user: %v", err)
|
|
}
|
|
if err := p.Initialize("session-1"); err != nil {
|
|
t.Fatalf("Initialize: %v", err)
|
|
}
|
|
|
|
block := p.SystemPromptBlock()
|
|
if !strings.Contains(block, "mem content") {
|
|
t.Fatal("missing memory content")
|
|
}
|
|
if !strings.Contains(block, "user content") {
|
|
t.Fatal("missing user content")
|
|
}
|
|
if !strings.Contains(block, "<memory>") && !strings.Contains(block, "</memory>") {
|
|
t.Fatal("missing <memory> fences")
|
|
}
|
|
}
|