feat(memory): four-scope contract and builtin engine CRUD (unification slice 2) (#886)
* 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.
This commit is contained in:
23 files changed
+3578
-607
No files matched your search
@@ -1,129 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A missing memory directory is indistinguishable from an empty memory: both
|
||||
// stores treat ENOENT as "no content yet". That makes a misconfigured Dir
|
||||
// invisible until the agent's first memory write fails mid-conversation.
|
||||
//
|
||||
// New settles the question at construction, but an unusable directory is not
|
||||
// grounds for refusing to start -- the daemon falls back to the default
|
||||
// location and carries on. So New reports the problem through IsAvailable and
|
||||
// Err rather than by failing.
|
||||
func TestNewEstablishesDir(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
dir func(t *testing.T) string
|
||||
wantUsabl bool
|
||||
}{
|
||||
{
|
||||
name: "existing directory",
|
||||
dir: func(t *testing.T) string { return t.TempDir() },
|
||||
wantUsabl: true,
|
||||
},
|
||||
{
|
||||
name: "missing directory is created",
|
||||
dir: func(t *testing.T) string {
|
||||
return filepath.Join(t.TempDir(), "nested", "memory")
|
||||
},
|
||||
wantUsabl: true,
|
||||
},
|
||||
{
|
||||
name: "unwritable parent is reported, not fatal",
|
||||
dir: func(t *testing.T) string {
|
||||
parent := filepath.Join(t.TempDir(), "ro")
|
||||
if err := os.Mkdir(parent, 0o500); err != nil {
|
||||
t.Fatalf("mkdir: %v", err)
|
||||
}
|
||||
return filepath.Join(parent, "memory")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "path occupied by a file is reported, not fatal",
|
||||
dir: func(t *testing.T) string {
|
||||
p := filepath.Join(t.TempDir(), "memory")
|
||||
if err := os.WriteFile(p, []byte("not a dir"), 0o600); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
return p
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Running as root defeats permission-based cases.
|
||||
if !tc.wantUsabl && os.Geteuid() == 0 {
|
||||
t.Skip("running as root: permission cases are not meaningful")
|
||||
}
|
||||
dir := tc.dir(t)
|
||||
|
||||
p, err := New(Config{Dir: dir})
|
||||
if err != nil {
|
||||
t.Fatalf("New(%q) = %v, want a usable provider: an unusable "+
|
||||
"directory must not stop the daemon starting", dir, err)
|
||||
}
|
||||
if p == nil {
|
||||
t.Fatal("New returned a nil provider without an error")
|
||||
}
|
||||
|
||||
if got := p.IsAvailable(); got != tc.wantUsabl {
|
||||
t.Fatalf("IsAvailable() = %v, want %v", got, tc.wantUsabl)
|
||||
}
|
||||
if tc.wantUsabl {
|
||||
if p.Err() != nil {
|
||||
t.Fatalf("Err() = %v, want nil", p.Err())
|
||||
}
|
||||
info, statErr := os.Stat(dir)
|
||||
if statErr != nil {
|
||||
t.Fatalf("provider reports available but %q does not exist: %v", dir, statErr)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
t.Fatalf("%q is not a directory", dir)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// An unavailable provider must say why: the operator's only clue
|
||||
// is what gets logged, and "memory unavailable" alone is not
|
||||
// actionable.
|
||||
if p.Err() == nil {
|
||||
t.Fatal("IsAvailable() is false but Err() is nil, leaving the operator nothing to act on")
|
||||
}
|
||||
if !strings.Contains(p.Err().Error(), dir) {
|
||||
t.Fatalf("Err() = %q, want it to name the offending directory %q", p.Err(), dir)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A provider on an unusable directory must still answer every read, so a
|
||||
// degraded memory reads as empty rather than panicking mid-conversation.
|
||||
func TestUnusableDirStillReadable(t *testing.T) {
|
||||
if os.Geteuid() == 0 {
|
||||
t.Skip("running as root: permission cases are not meaningful")
|
||||
}
|
||||
parent := filepath.Join(t.TempDir(), "ro")
|
||||
if err := os.Mkdir(parent, 0o500); err != nil {
|
||||
t.Fatalf("mkdir: %v", err)
|
||||
}
|
||||
|
||||
p, err := New(Config{Dir: filepath.Join(parent, "memory")})
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
if err := p.Initialize("session-1"); err != nil {
|
||||
t.Fatalf("Initialize on an unusable dir: %v", err)
|
||||
}
|
||||
if block := p.SystemPromptBlock(); block != "" {
|
||||
t.Fatalf("SystemPromptBlock() = %q, want empty", block)
|
||||
}
|
||||
if len(p.GetToolSchemas()) == 0 {
|
||||
t.Fatal("GetToolSchemas() is empty: the tool must still be offered")
|
||||
}
|
||||
}
|
||||
@@ -1,403 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/memory"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// providerName is the value returned by Provider.Name() and used to route
|
||||
// tool calls to this provider.
|
||||
const providerName = "builtin"
|
||||
|
||||
// toolName is the single tool this provider exposes to the agent.
|
||||
const toolName = "memory_edit"
|
||||
|
||||
// Config configures a Provider.
|
||||
type Config struct {
|
||||
// Dir is the directory MEMORY.md and USER.md are read from and written
|
||||
// to (e.g. ~/.config/archie/profiles/{profile}/memory/). It is created
|
||||
// if it does not exist.
|
||||
Dir string
|
||||
|
||||
// MaxFileBytes bounds the size of each file. Zero or negative uses
|
||||
// defaultMaxFileBytes (100KB).
|
||||
MaxFileBytes int
|
||||
|
||||
// DisableFrozenSnapshot, when true, causes SystemPromptBlock() to read
|
||||
// live content from the stores on every call instead of using the
|
||||
// snapshot captured at Initialize() time. Defaults to false (frozen
|
||||
// snapshot enabled).
|
||||
DisableFrozenSnapshot bool
|
||||
}
|
||||
|
||||
// Provider is the built-in, file-backed MemoryProvider. It persists agent
|
||||
// memory to MEMORY.md and user-provided context to USER.md under Config.Dir,
|
||||
// and exposes a single "memory_edit" tool with add/replace/remove actions.
|
||||
//
|
||||
// By default, the provider captures a frozen snapshot of both files at
|
||||
// Initialize() time and uses that snapshot for the system prompt block
|
||||
// (SystemPromptProvider). Writes go to disk immediately but the snapshot is
|
||||
// not updated mid-session -- only the next session (or next Initialize call)
|
||||
// picks up the changes. Set Config.FrozenSnapshot to false to read live
|
||||
// content on every SystemPromptBlock() call.
|
||||
type Provider struct {
|
||||
memory *Store
|
||||
user *Store
|
||||
|
||||
// frozenSnapshotEnabled mirrors Config.FrozenSnapshot. When unset
|
||||
// (default), Initialize() captures a snapshot that SystemPromptBlock()
|
||||
// returns for the lifetime of the session.
|
||||
frozenSnapshotEnabled bool
|
||||
|
||||
// frozenMu guards frozenMemory and frozenUser, since Initialize() can
|
||||
// race with SystemPromptBlock() if a caller re-initializes a session on
|
||||
// a Provider shared across goroutines.
|
||||
frozenMu sync.RWMutex
|
||||
|
||||
// frozen memory and frozen user hold the Render() output captured at
|
||||
// Initialize() time. They are only valid after Initialize() has been
|
||||
// called and only used when frozenSnapshotEnabled is true.
|
||||
frozenMemory string
|
||||
frozenUser string
|
||||
|
||||
// dirErr records a Config.Dir that could not be established. The
|
||||
// provider stays usable for reads -- a memory that cannot be written is
|
||||
// still better than a daemon that will not start -- and reports itself
|
||||
// unavailable so the failure is visible rather than looking like a
|
||||
// memory that simply has nothing in it yet.
|
||||
dirErr error
|
||||
}
|
||||
|
||||
// New creates a Provider backed by the two markdown files under cfg.Dir.
|
||||
// Both files are read immediately so the provider is ready for use as soon
|
||||
// as New returns.
|
||||
//
|
||||
// An unusable cfg.Dir is reported through IsAvailable and Err, not by
|
||||
// failing: memory is one capability among many, and a bad path is not worth
|
||||
// refusing to start over. The caller decides whether to fall back elsewhere.
|
||||
// Establishing the directory here is still what makes the problem visible at
|
||||
// all -- both stores treat a missing file as an empty document, so otherwise
|
||||
// a directory that does not exist is indistinguishable from a memory that
|
||||
// simply has nothing in it yet, and the failure surfaces at the agent's
|
||||
// first write, mid-conversation.
|
||||
//
|
||||
// FrozenSnapshot defaults to true (frozen snapshot enabled). Set it
|
||||
// explicitly to false to have SystemPromptBlock() read live content from
|
||||
// the stores.
|
||||
func New(cfg Config) (*Provider, error) {
|
||||
if cfg.Dir == "" {
|
||||
return nil, fmt.Errorf("builtin: Config.Dir must not be empty")
|
||||
}
|
||||
|
||||
var dirErr error
|
||||
if err := os.MkdirAll(cfg.Dir, 0o755); err != nil {
|
||||
dirErr = fmt.Errorf("builtin: memory directory %s unusable: %w", cfg.Dir, err)
|
||||
}
|
||||
|
||||
// A store that cannot read its file starts empty rather than failing,
|
||||
// for the same reason: reads must keep working on a degraded provider.
|
||||
memStore, err := NewStore(filepath.Join(cfg.Dir, "MEMORY.md"), cfg.MaxFileBytes)
|
||||
if err != nil {
|
||||
if dirErr == nil {
|
||||
dirErr = err
|
||||
}
|
||||
memStore = emptyStore(filepath.Join(cfg.Dir, "MEMORY.md"), cfg.MaxFileBytes)
|
||||
}
|
||||
userStore, err := NewStore(filepath.Join(cfg.Dir, "USER.md"), cfg.MaxFileBytes)
|
||||
if err != nil {
|
||||
if dirErr == nil {
|
||||
dirErr = err
|
||||
}
|
||||
userStore = emptyStore(filepath.Join(cfg.Dir, "USER.md"), cfg.MaxFileBytes)
|
||||
}
|
||||
|
||||
// Frozen snapshot is enabled by default (DisableFrozenSnapshot defaults
|
||||
// to false).
|
||||
frozen := !cfg.DisableFrozenSnapshot
|
||||
|
||||
return &Provider{
|
||||
memory: memStore,
|
||||
user: userStore,
|
||||
frozenSnapshotEnabled: frozen,
|
||||
dirErr: dirErr,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Name returns the provider's identifier.
|
||||
func (p *Provider) Name() string { return providerName }
|
||||
|
||||
// IsAvailable reports whether the backing directory could be established.
|
||||
// The built-in provider has one external dependency after all -- the
|
||||
// filesystem -- and a directory it cannot write to means memory reads as
|
||||
// empty and every write will fail.
|
||||
func (p *Provider) IsAvailable() bool { return p.dirErr == nil }
|
||||
|
||||
// Err returns why the provider is unavailable, or nil. Callers log this: an
|
||||
// operator told only that memory is unavailable has nothing to act on.
|
||||
func (p *Provider) Err() error { return p.dirErr }
|
||||
|
||||
// SystemPromptBlock implements memory.SystemPromptProvider. It returns a
|
||||
// markdown-formatted block containing the frozen snapshot of MEMORY.md and
|
||||
// USER.md content, wrapped in <memory>…</memory> fences.
|
||||
//
|
||||
// When the frozen snapshot is enabled (the default), the block is built from
|
||||
// the snapshot captured at Initialize() time and does not change for the
|
||||
// duration of the session. When disabled (Config.DisableFrozenSnapshot =
|
||||
// true), the block is built from the live store content on every call.
|
||||
//
|
||||
// Returns an empty string when both stores are empty.
|
||||
func (p *Provider) SystemPromptBlock() string {
|
||||
mem, user := p.snapshotContent()
|
||||
if mem == "" && user == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
sb.WriteString("<memory>\n")
|
||||
if mem != "" {
|
||||
sb.WriteString(mem)
|
||||
}
|
||||
if user != "" {
|
||||
if mem != "" {
|
||||
sb.WriteString("\n")
|
||||
}
|
||||
sb.WriteString(user)
|
||||
}
|
||||
sb.WriteString("\n</memory>\n")
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// snapshotContent returns the memory and user content, either from the frozen
|
||||
// snapshot or live from the stores, depending on the FrozenSnapshot config.
|
||||
func (p *Provider) snapshotContent() (memory, user string) {
|
||||
if p.frozenSnapshotEnabled {
|
||||
p.frozenMu.RLock()
|
||||
defer p.frozenMu.RUnlock()
|
||||
return p.frozenMemory, p.frozenUser
|
||||
}
|
||||
return p.memory.Render(), p.user.Render()
|
||||
}
|
||||
|
||||
// Initialize reloads MEMORY.md and USER.md from disk so that any changes
|
||||
// made outside this process (or by a previous provider instance) since
|
||||
// New was called are picked up before the session begins.
|
||||
//
|
||||
// When frozen snapshot is enabled (the default), Initialize captures the
|
||||
// rendered content of both files for use by SystemPromptBlock(). The snapshot
|
||||
// is not updated on subsequent writes -- only the next Initialize() call (or
|
||||
// the next session) picks up the fresh content.
|
||||
func (p *Provider) Initialize(sessionID string) error {
|
||||
if err := p.memory.Reload(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.user.Reload(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if p.frozenSnapshotEnabled {
|
||||
mem := p.memory.Render()
|
||||
user := p.user.Render()
|
||||
p.frozenMu.Lock()
|
||||
p.frozenMemory = mem
|
||||
p.frozenUser = user
|
||||
p.frozenMu.Unlock()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetToolSchemas returns the memory_edit tool definition. Handler is left
|
||||
// nil so the MemoryManager injects a delegating handler via
|
||||
// ToolCallProvider (see Manager.GetToolSchemas); callers that bypass the
|
||||
// Manager should invoke HandleToolCall directly.
|
||||
func (p *Provider) GetToolSchemas() []tools.ToolEntry {
|
||||
return []tools.ToolEntry{
|
||||
{
|
||||
Name: toolName,
|
||||
Toolset: "memory",
|
||||
Description: "Persist or edit agent memory. Add, replace, or remove content in a named section of MEMORY.md (agent memory) or USER.md (user-provided context).",
|
||||
Schema: toolSchema,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// toolSchema is the JSON Schema for the memory_edit tool's input.
|
||||
var toolSchema = tools.JSONSchema{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"file": map[string]any{
|
||||
"type": "string",
|
||||
"enum": []string{"memory", "user"},
|
||||
"description": "Which file to edit: \"memory\" for MEMORY.md (agent memory) or \"user\" for USER.md (user-provided context). Defaults to \"memory\".",
|
||||
},
|
||||
"action": map[string]any{
|
||||
"type": "string",
|
||||
"enum": []string{"add", "replace", "remove"},
|
||||
"description": "The action to perform: add a new entry, replace a substring, or remove a matching entry.",
|
||||
},
|
||||
"section": map[string]any{
|
||||
"type": "string",
|
||||
"description": "Name of the section (markdown header) to operate on. Alphanumeric and spaces only, max 64 characters. Created automatically by \"add\" if it does not exist.",
|
||||
},
|
||||
"content": map[string]any{
|
||||
"type": "string",
|
||||
"description": "Content to append as a new entry. Required for the \"add\" action.",
|
||||
},
|
||||
"substring": map[string]any{
|
||||
"type": "string",
|
||||
"description": "Exact substring to locate within the section. Required for \"replace\" and \"remove\".",
|
||||
},
|
||||
"replacement": map[string]any{
|
||||
"type": "string",
|
||||
"description": "Text to substitute in place of substring. Required for the \"replace\" action.",
|
||||
},
|
||||
"case_sensitive": map[string]any{
|
||||
"type": "boolean",
|
||||
"description": "Whether substring matching is case-sensitive. Defaults to true.",
|
||||
},
|
||||
},
|
||||
"required": []string{"action", "section"},
|
||||
}
|
||||
|
||||
// HandleToolCall implements memory.ToolCallProvider. It dispatches the
|
||||
// memory_edit tool's add/replace/remove actions to the selected store.
|
||||
func (p *Provider) HandleToolCall(name string, args map[string]any) (any, error) {
|
||||
if name != toolName {
|
||||
return nil, fmt.Errorf("builtin: unknown tool %q", name)
|
||||
}
|
||||
|
||||
store, fileLabel, err := p.selectStore(args)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
action, _ := args["action"].(string)
|
||||
caseSensitive := true
|
||||
if v, ok := args["case_sensitive"].(bool); ok {
|
||||
caseSensitive = v
|
||||
}
|
||||
|
||||
switch action {
|
||||
case "add":
|
||||
return p.handleAdd(store, fileLabel, args)
|
||||
case "replace":
|
||||
return p.handleReplace(store, fileLabel, args, caseSensitive)
|
||||
case "remove":
|
||||
return p.handleRemove(store, fileLabel, args, caseSensitive)
|
||||
default:
|
||||
return nil, fmt.Errorf("builtin: unknown action %q (want add, replace, or remove)", action)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Provider) handleAdd(store *Store, fileLabel string, args map[string]any) (any, error) {
|
||||
content, _ := args["content"].(string)
|
||||
if content == "" {
|
||||
return nil, fmt.Errorf("builtin: add requires non-empty \"content\"")
|
||||
}
|
||||
section, _ := args["section"].(string)
|
||||
res, err := store.Add(section, content)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
verb := "appended to"
|
||||
if res.Created {
|
||||
verb = "created"
|
||||
}
|
||||
return map[string]any{
|
||||
"success": true,
|
||||
"file": fileLabel,
|
||||
"action": "add",
|
||||
"section": res.Section,
|
||||
"chars_added": res.CharsAdded,
|
||||
"section_chars": res.SectionChars,
|
||||
"file_bytes": res.FileBytes,
|
||||
"message": fmt.Sprintf("%s section %q (%d chars added, %d bytes in file)", capitalize(verb), res.Section, res.CharsAdded, res.FileBytes),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *Provider) handleReplace(store *Store, fileLabel string, args map[string]any, caseSensitive bool) (any, error) {
|
||||
substring, _ := args["substring"].(string)
|
||||
replacement, _ := args["replacement"].(string)
|
||||
if substring == "" {
|
||||
return nil, fmt.Errorf("builtin: replace requires non-empty \"substring\"")
|
||||
}
|
||||
section, _ := args["section"].(string)
|
||||
res, err := store.Replace(section, substring, replacement, caseSensitive)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{
|
||||
"success": true,
|
||||
"file": fileLabel,
|
||||
"action": "replace",
|
||||
"section": res.Section,
|
||||
"chars_removed": res.CharsRemoved,
|
||||
"chars_added": res.CharsAdded,
|
||||
"section_chars": res.SectionChars,
|
||||
"file_bytes": res.FileBytes,
|
||||
"message": fmt.Sprintf("Replaced %d chars with %d chars in section %q (%d bytes in file)", res.CharsRemoved, res.CharsAdded, res.Section, res.FileBytes),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *Provider) handleRemove(store *Store, fileLabel string, args map[string]any, caseSensitive bool) (any, error) {
|
||||
substring, _ := args["substring"].(string)
|
||||
if substring == "" {
|
||||
return nil, fmt.Errorf("builtin: remove requires non-empty \"substring\"")
|
||||
}
|
||||
section, _ := args["section"].(string)
|
||||
res, err := store.Remove(section, substring, caseSensitive)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{
|
||||
"success": true,
|
||||
"file": fileLabel,
|
||||
"action": "remove",
|
||||
"section": res.Section,
|
||||
"chars_removed": res.CharsRemoved,
|
||||
"section_chars": res.SectionChars,
|
||||
"file_bytes": res.FileBytes,
|
||||
"message": fmt.Sprintf("Removed %d chars from section %q (%d bytes in file)", res.CharsRemoved, res.Section, res.FileBytes),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// selectStore resolves the "file" argument to the corresponding store,
|
||||
// defaulting to the memory (MEMORY.md) store.
|
||||
func (p *Provider) selectStore(args map[string]any) (*Store, string, error) {
|
||||
file, _ := args["file"].(string)
|
||||
switch file {
|
||||
case "", "memory":
|
||||
return p.memory, "memory", nil
|
||||
case "user":
|
||||
return p.user, "user", nil
|
||||
default:
|
||||
return nil, "", fmt.Errorf("builtin: unknown file %q (want \"memory\" or \"user\")", file)
|
||||
}
|
||||
}
|
||||
|
||||
// capitalize upper-cases the first byte of s. It is only used for
|
||||
// short, ASCII, English status verbs, so byte-level capitalization is
|
||||
// sufficient.
|
||||
func capitalize(s string) string {
|
||||
if s == "" {
|
||||
return s
|
||||
}
|
||||
b := []byte(s)
|
||||
if b[0] >= 'a' && b[0] <= 'z' {
|
||||
b[0] -= 'a' - 'A'
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// Compile-time interface checks.
|
||||
var (
|
||||
_ memory.MemoryProvider = (*Provider)(nil)
|
||||
_ memory.ToolCallProvider = (*Provider)(nil)
|
||||
_ memory.SystemPromptProvider = (*Provider)(nil)
|
||||
)
|
||||
@@ -1,507 +0,0 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -1,500 +0,0 @@
|
||||
// Package builtin implements the built-in, file-backed MemoryProvider. It
|
||||
// persists agent memory to MEMORY.md and USER.md as plain markdown, using
|
||||
// "## " headers to delimit named sections. Content within a section is
|
||||
// organized into blank-line-separated blocks; add/replace/remove act on
|
||||
// those blocks and on substrings within them.
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// defaultMaxFileBytes is the default per-file size bound (100KB).
|
||||
const defaultMaxFileBytes = 100 * 1024
|
||||
|
||||
// sectionNamePattern restricts section names to alphanumerics and spaces,
|
||||
// matching the tool's input-validation contract.
|
||||
var sectionNamePattern = regexp.MustCompile(`^[A-Za-z0-9 ]{1,64}$`)
|
||||
|
||||
// ValidateSectionName reports an error if name is empty, too long, or
|
||||
// contains characters outside [A-Za-z0-9 ].
|
||||
func ValidateSectionName(name string) error {
|
||||
if !sectionNamePattern.MatchString(name) {
|
||||
return fmt.Errorf("builtin: invalid section name %q: must be 1-64 alphanumeric/space characters", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// section is a named markdown block within a store file. blocks holds the
|
||||
// section's content split into blank-line-separated paragraphs.
|
||||
type section struct {
|
||||
name string
|
||||
blocks []string
|
||||
}
|
||||
|
||||
// clone returns a deep copy of the section so callers can mutate a
|
||||
// candidate version without touching the committed state.
|
||||
func (s *section) clone() *section {
|
||||
blocks := make([]string, len(s.blocks))
|
||||
copy(blocks, s.blocks)
|
||||
return §ion{name: s.name, blocks: blocks}
|
||||
}
|
||||
|
||||
// Store is a thread-safe, size-bounded, file-backed markdown document. It
|
||||
// reads its full content at construction and rewrites the whole file on
|
||||
// every mutation.
|
||||
type Store struct {
|
||||
mu sync.RWMutex
|
||||
path string
|
||||
maxBytes int
|
||||
|
||||
preamble string
|
||||
sections []*section
|
||||
}
|
||||
|
||||
// NewStore loads path if it exists (creating an empty in-memory document
|
||||
// otherwise) and returns a Store bounded to maxBytes. maxBytes <= 0 uses
|
||||
// defaultMaxFileBytes.
|
||||
func NewStore(path string, maxBytes int) (*Store, error) {
|
||||
if maxBytes <= 0 {
|
||||
maxBytes = defaultMaxFileBytes
|
||||
}
|
||||
s := &Store{path: path, maxBytes: maxBytes}
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return s, nil
|
||||
}
|
||||
return nil, fmt.Errorf("builtin: reading %s: %w", path, err)
|
||||
}
|
||||
s.preamble, s.sections = parseSections(string(data))
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// emptyStore returns a Store bound to path with no content, for a file that
|
||||
// could not be read. Reads answer as empty and a later write still attempts
|
||||
// the file, so a directory that becomes usable repairs itself.
|
||||
func emptyStore(path string, maxBytes int) *Store {
|
||||
if maxBytes <= 0 {
|
||||
maxBytes = defaultMaxFileBytes
|
||||
}
|
||||
return &Store{path: path, maxBytes: maxBytes}
|
||||
}
|
||||
|
||||
// Reload re-reads the backing file from disk, replacing all in-memory
|
||||
// state. A missing file resets the store to empty rather than erroring.
|
||||
func (s *Store) Reload() error {
|
||||
data, err := os.ReadFile(s.path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
s.mu.Lock()
|
||||
s.preamble, s.sections = "", nil
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("builtin: reading %s: %w", s.path, err)
|
||||
}
|
||||
|
||||
preamble, sections := parseSections(string(data))
|
||||
s.mu.Lock()
|
||||
s.preamble, s.sections = preamble, sections
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Path returns the file path backing this store.
|
||||
func (s *Store) Path() string {
|
||||
return s.path
|
||||
}
|
||||
|
||||
// MaxBytes returns the configured size bound for this store.
|
||||
func (s *Store) MaxBytes() int {
|
||||
return s.maxBytes
|
||||
}
|
||||
|
||||
// Render returns the current serialized document. Safe for concurrent use.
|
||||
func (s *Store) Render() string {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return renderSections(s.preamble, s.sections)
|
||||
}
|
||||
|
||||
// Size returns the current serialized document length in bytes.
|
||||
func (s *Store) Size() int {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return len(renderSections(s.preamble, s.sections))
|
||||
}
|
||||
|
||||
// AddResult describes the outcome of a successful Add.
|
||||
type AddResult struct {
|
||||
Section string
|
||||
CharsAdded int
|
||||
SectionChars int
|
||||
FileBytes int
|
||||
Created bool // true if the section did not exist before this call
|
||||
}
|
||||
|
||||
// Add appends content as a new block in the named section, creating the
|
||||
// section if it does not already exist. The write is rejected -- with no
|
||||
// change to in-memory state or disk -- if the resulting file would exceed
|
||||
// the store's size bound.
|
||||
func (s *Store) Add(sectionName, content string) (AddResult, error) {
|
||||
if err := ValidateSectionName(sectionName); err != nil {
|
||||
return AddResult{}, err
|
||||
}
|
||||
content = strings.TrimSpace(content)
|
||||
if content == "" {
|
||||
return AddResult{}, fmt.Errorf("builtin: content must not be empty")
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
candidate := cloneSections(s.sections)
|
||||
sec, created := findOrCreateSection(&candidate, sectionName)
|
||||
sec.blocks = append(sec.blocks, content)
|
||||
|
||||
rendered := renderSections(s.preamble, candidate)
|
||||
if len(rendered) > s.maxBytes {
|
||||
return AddResult{}, fmt.Errorf("builtin: add to section %q would exceed max file size (%d > %d bytes)", sectionName, len(rendered), s.maxBytes)
|
||||
}
|
||||
if err := writeFileAtomic(s.path, rendered); err != nil {
|
||||
return AddResult{}, err
|
||||
}
|
||||
|
||||
s.sections = candidate
|
||||
return AddResult{
|
||||
Section: sectionName,
|
||||
CharsAdded: len(content),
|
||||
SectionChars: sectionChars(sec),
|
||||
FileBytes: len(rendered),
|
||||
Created: created,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ReplaceResult describes the outcome of a successful Replace.
|
||||
type ReplaceResult struct {
|
||||
Section string
|
||||
CharsRemoved int
|
||||
CharsAdded int
|
||||
SectionChars int
|
||||
FileBytes int
|
||||
}
|
||||
|
||||
// Replace finds the first occurrence of substring within the named
|
||||
// section's content and replaces it with replacement. It returns an error
|
||||
// if the section does not exist, if substring is not found, or if the
|
||||
// result would exceed the store's size bound.
|
||||
func (s *Store) Replace(sectionName, substring, replacement string, caseSensitive bool) (ReplaceResult, error) {
|
||||
if err := ValidateSectionName(sectionName); err != nil {
|
||||
return ReplaceResult{}, err
|
||||
}
|
||||
if substring == "" {
|
||||
return ReplaceResult{}, fmt.Errorf("builtin: substring must not be empty")
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
candidate := cloneSections(s.sections)
|
||||
sec := findSection(candidate, sectionName)
|
||||
if sec == nil {
|
||||
return ReplaceResult{}, fmt.Errorf("builtin: section %q not found", sectionName)
|
||||
}
|
||||
|
||||
blockIdx, pos, matchLen := findInBlocks(sec.blocks, substring, caseSensitive)
|
||||
if blockIdx < 0 {
|
||||
return ReplaceResult{}, fmt.Errorf("builtin: substring %q not found in section %q", substring, sectionName)
|
||||
}
|
||||
|
||||
block := sec.blocks[blockIdx]
|
||||
sec.blocks[blockIdx] = block[:pos] + replacement + block[pos+matchLen:]
|
||||
|
||||
rendered := renderSections(s.preamble, candidate)
|
||||
if len(rendered) > s.maxBytes {
|
||||
return ReplaceResult{}, fmt.Errorf("builtin: replace in section %q would exceed max file size (%d > %d bytes)", sectionName, len(rendered), s.maxBytes)
|
||||
}
|
||||
if err := writeFileAtomic(s.path, rendered); err != nil {
|
||||
return ReplaceResult{}, err
|
||||
}
|
||||
|
||||
s.sections = candidate
|
||||
return ReplaceResult{
|
||||
Section: sectionName,
|
||||
CharsRemoved: matchLen,
|
||||
CharsAdded: len(replacement),
|
||||
SectionChars: sectionChars(sec),
|
||||
FileBytes: len(rendered),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RemoveResult describes the outcome of a successful Remove.
|
||||
type RemoveResult struct {
|
||||
Section string
|
||||
CharsRemoved int
|
||||
SectionChars int
|
||||
FileBytes int
|
||||
}
|
||||
|
||||
// Remove deletes the first block within the named section whose text
|
||||
// contains substring. It returns an error if the section does not exist
|
||||
// or if no block matches.
|
||||
func (s *Store) Remove(sectionName, substring string, caseSensitive bool) (RemoveResult, error) {
|
||||
if err := ValidateSectionName(sectionName); err != nil {
|
||||
return RemoveResult{}, err
|
||||
}
|
||||
if substring == "" {
|
||||
return RemoveResult{}, fmt.Errorf("builtin: substring must not be empty")
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
candidate := cloneSections(s.sections)
|
||||
sec := findSection(candidate, sectionName)
|
||||
if sec == nil {
|
||||
return RemoveResult{}, fmt.Errorf("builtin: section %q not found", sectionName)
|
||||
}
|
||||
|
||||
blockIdx, _, _ := findInBlocks(sec.blocks, substring, caseSensitive)
|
||||
if blockIdx < 0 {
|
||||
return RemoveResult{}, fmt.Errorf("builtin: substring %q not found in section %q", substring, sectionName)
|
||||
}
|
||||
|
||||
removed := sec.blocks[blockIdx]
|
||||
sec.blocks = append(sec.blocks[:blockIdx], sec.blocks[blockIdx+1:]...)
|
||||
|
||||
rendered := renderSections(s.preamble, candidate)
|
||||
// Removal only ever shrinks the file, but a bound check is kept for
|
||||
// consistency with Add/Replace and to guard against pathological
|
||||
// preamble/header growth from re-serialization.
|
||||
if len(rendered) > s.maxBytes {
|
||||
return RemoveResult{}, fmt.Errorf("builtin: remove from section %q would exceed max file size (%d > %d bytes)", sectionName, len(rendered), s.maxBytes)
|
||||
}
|
||||
if err := writeFileAtomic(s.path, rendered); err != nil {
|
||||
return RemoveResult{}, err
|
||||
}
|
||||
|
||||
s.sections = candidate
|
||||
return RemoveResult{
|
||||
Section: sectionName,
|
||||
CharsRemoved: len(removed),
|
||||
SectionChars: sectionChars(sec),
|
||||
FileBytes: len(rendered),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ── Parsing & rendering ────────────────────────────────────────────────
|
||||
|
||||
// sectionHeaderPrefix is the markdown header marker that delimits sections.
|
||||
const sectionHeaderPrefix = "## "
|
||||
|
||||
// parseSections splits document content into a preamble (any content before
|
||||
// the first section header) and an ordered list of sections. Each section's
|
||||
// body is split into blocks on blank lines.
|
||||
func parseSections(content string) (preamble string, sections []*section) {
|
||||
lines := strings.Split(content, "\n")
|
||||
|
||||
var preambleLines []string
|
||||
var cur *section
|
||||
var bodyLines []string
|
||||
|
||||
flush := func() {
|
||||
if cur != nil {
|
||||
cur.blocks = splitBlocks(bodyLines)
|
||||
sections = append(sections, cur)
|
||||
}
|
||||
bodyLines = nil
|
||||
}
|
||||
|
||||
for _, line := range lines {
|
||||
if strings.HasPrefix(line, sectionHeaderPrefix) {
|
||||
flush()
|
||||
name := strings.TrimSpace(strings.TrimPrefix(line, sectionHeaderPrefix))
|
||||
cur = §ion{name: name}
|
||||
continue
|
||||
}
|
||||
if cur == nil {
|
||||
preambleLines = append(preambleLines, line)
|
||||
} else {
|
||||
bodyLines = append(bodyLines, line)
|
||||
}
|
||||
}
|
||||
flush()
|
||||
|
||||
preamble = strings.TrimRight(strings.Join(preambleLines, "\n"), "\n \t")
|
||||
return preamble, sections
|
||||
}
|
||||
|
||||
// splitBlocks groups lines into blank-line-separated blocks, trimming
|
||||
// leading/trailing blank lines and skipping empty blocks.
|
||||
func splitBlocks(lines []string) []string {
|
||||
var blocks []string
|
||||
var cur []string
|
||||
|
||||
flush := func() {
|
||||
if len(cur) > 0 {
|
||||
blocks = append(blocks, strings.TrimRight(strings.Join(cur, "\n"), "\n"))
|
||||
cur = nil
|
||||
}
|
||||
}
|
||||
|
||||
for _, line := range lines {
|
||||
if strings.TrimSpace(line) == "" {
|
||||
flush()
|
||||
continue
|
||||
}
|
||||
cur = append(cur, line)
|
||||
}
|
||||
flush()
|
||||
return blocks
|
||||
}
|
||||
|
||||
// renderSections serializes a preamble and ordered sections back into the
|
||||
// on-disk markdown format.
|
||||
func renderSections(preamble string, sections []*section) string {
|
||||
var sb strings.Builder
|
||||
if preamble != "" {
|
||||
sb.WriteString(preamble)
|
||||
if len(sections) > 0 {
|
||||
sb.WriteString("\n\n")
|
||||
} else {
|
||||
sb.WriteString("\n")
|
||||
}
|
||||
}
|
||||
for i, sec := range sections {
|
||||
if i > 0 {
|
||||
sb.WriteString("\n")
|
||||
}
|
||||
sb.WriteString(sectionHeaderPrefix)
|
||||
sb.WriteString(sec.name)
|
||||
sb.WriteString("\n")
|
||||
if len(sec.blocks) > 0 {
|
||||
sb.WriteString("\n")
|
||||
for j, block := range sec.blocks {
|
||||
if j > 0 {
|
||||
sb.WriteString("\n\n")
|
||||
}
|
||||
sb.WriteString(block)
|
||||
}
|
||||
sb.WriteString("\n")
|
||||
}
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// sectionChars returns the serialized character count of a single section's
|
||||
// body (blocks only, joined as they would appear on disk).
|
||||
func sectionChars(sec *section) int {
|
||||
return len(strings.Join(sec.blocks, "\n\n"))
|
||||
}
|
||||
|
||||
// cloneSections returns a deep copy of a section slice.
|
||||
func cloneSections(sections []*section) []*section {
|
||||
out := make([]*section, len(sections))
|
||||
for i, sec := range sections {
|
||||
out[i] = sec.clone()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// findSection returns the section with the given name, or nil.
|
||||
func findSection(sections []*section, name string) *section {
|
||||
for _, sec := range sections {
|
||||
if sec.name == name {
|
||||
return sec
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// findOrCreateSection returns the named section from *sections, appending a
|
||||
// new empty section (and reporting created=true) if none exists.
|
||||
func findOrCreateSection(sections *[]*section, name string) (sec *section, created bool) {
|
||||
if sec := findSection(*sections, name); sec != nil {
|
||||
return sec, false
|
||||
}
|
||||
sec = §ion{name: name}
|
||||
*sections = append(*sections, sec)
|
||||
return sec, true
|
||||
}
|
||||
|
||||
// findInBlocks searches blocks in order for the first occurrence of
|
||||
// substring, returning the block index, the byte offset within that block,
|
||||
// and the byte length of the match. Returns (-1, -1, 0) if not found.
|
||||
func findInBlocks(blocks []string, substring string, caseSensitive bool) (blockIdx, pos, matchLen int) {
|
||||
for i, block := range blocks {
|
||||
if caseSensitive {
|
||||
if idx := strings.Index(block, substring); idx >= 0 {
|
||||
return i, idx, len(substring)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if idx, l := indexFold(block, substring); idx >= 0 {
|
||||
return i, idx, l
|
||||
}
|
||||
}
|
||||
return -1, -1, 0
|
||||
}
|
||||
|
||||
// indexFold finds the first byte index in haystack where a substring of the
|
||||
// same rune length as needle case-insensitively equals needle, using
|
||||
// strings.EqualFold for comparison. Returns (-1, 0) if not found.
|
||||
func indexFold(haystack, needle string) (int, int) {
|
||||
needleRunes := len([]rune(needle))
|
||||
runes := []rune(haystack)
|
||||
for i := range runes {
|
||||
if i+needleRunes > len(runes) {
|
||||
break
|
||||
}
|
||||
candidate := string(runes[i : i+needleRunes])
|
||||
if strings.EqualFold(candidate, needle) {
|
||||
// Translate the rune index back to a byte offset.
|
||||
byteOffset := len(string(runes[:i]))
|
||||
return byteOffset, len(candidate)
|
||||
}
|
||||
}
|
||||
return -1, 0
|
||||
}
|
||||
|
||||
// writeFileAtomic writes content to path by writing to a temp file in the
|
||||
// same directory and renaming it into place, so a crash mid-write cannot
|
||||
// leave a truncated file behind.
|
||||
func writeFileAtomic(path, content string) error {
|
||||
dir := filepath.Dir(path)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return fmt.Errorf("builtin: creating directory %s: %w", dir, err)
|
||||
}
|
||||
|
||||
tmp, err := os.CreateTemp(dir, ".tmp-*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("builtin: creating temp file in %s: %w", dir, err)
|
||||
}
|
||||
tmpPath := tmp.Name()
|
||||
|
||||
if _, err := tmp.WriteString(content); err != nil {
|
||||
_ = tmp.Close()
|
||||
_ = os.Remove(tmpPath)
|
||||
return fmt.Errorf("builtin: writing %s: %w", path, err)
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
_ = os.Remove(tmpPath)
|
||||
return fmt.Errorf("builtin: closing %s: %w", path, err)
|
||||
}
|
||||
if err := os.Chmod(tmpPath, 0o644); err != nil {
|
||||
_ = os.Remove(tmpPath)
|
||||
return fmt.Errorf("builtin: setting permissions on %s: %w", path, err)
|
||||
}
|
||||
if err := os.Rename(tmpPath, path); err != nil {
|
||||
_ = os.Remove(tmpPath)
|
||||
return fmt.Errorf("builtin: renaming into %s: %w", path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,444 +0,0 @@
|
||||
package builtin
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidateSectionName(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
wantErr bool
|
||||
}{
|
||||
{"valid simple", "Facts", false},
|
||||
{"valid with spaces", "User Preferences", false},
|
||||
{"valid alphanumeric", "Section 123", false},
|
||||
{"empty", "", true},
|
||||
{"too long", strings.Repeat("a", 65), true},
|
||||
{"exactly max length", strings.Repeat("a", 64), false},
|
||||
{"invalid punctuation", "Facts!", true},
|
||||
{"invalid hyphen", "my-section", true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := ValidateSectionName(tt.input)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("ValidateSectionName(%q) error = %v, wantErr %v", tt.input, err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func newTestStore(t *testing.T, maxBytes int) *Store {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
s, err := NewStore(filepath.Join(dir, "MEMORY.md"), maxBytes)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func TestStore_NewStore_MissingFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "MEMORY.md")
|
||||
s, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
if s.Render() != "" {
|
||||
t.Fatalf("expected empty render for missing file, got %q", s.Render())
|
||||
}
|
||||
if s.MaxBytes() != defaultMaxFileBytes {
|
||||
t.Fatalf("expected default max bytes, got %d", s.MaxBytes())
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Add_CreatesSection(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
|
||||
res, err := s.Add("Facts", "the sky is blue")
|
||||
if err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if !res.Created {
|
||||
t.Fatalf("expected Created=true for new section")
|
||||
}
|
||||
if res.Section != "Facts" {
|
||||
t.Fatalf("expected section Facts, got %q", res.Section)
|
||||
}
|
||||
|
||||
rendered := s.Render()
|
||||
if !strings.Contains(rendered, "## Facts") {
|
||||
t.Fatalf("expected rendered content to contain header, got %q", rendered)
|
||||
}
|
||||
if !strings.Contains(rendered, "the sky is blue") {
|
||||
t.Fatalf("expected rendered content to contain the entry, got %q", rendered)
|
||||
}
|
||||
|
||||
// Verify the write actually landed on disk.
|
||||
data, err := os.ReadFile(s.Path())
|
||||
if err != nil {
|
||||
t.Fatalf("reading file: %v", err)
|
||||
}
|
||||
if string(data) != rendered {
|
||||
t.Fatalf("disk content does not match in-memory render:\ndisk: %q\nmem: %q", data, rendered)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Add_AppendsToExistingSection(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
|
||||
if _, err := s.Add("Facts", "first entry"); err != nil {
|
||||
t.Fatalf("first Add: %v", err)
|
||||
}
|
||||
res, err := s.Add("Facts", "second entry")
|
||||
if err != nil {
|
||||
t.Fatalf("second Add: %v", err)
|
||||
}
|
||||
if res.Created {
|
||||
t.Fatalf("expected Created=false when appending to existing section")
|
||||
}
|
||||
|
||||
rendered := s.Render()
|
||||
if strings.Count(rendered, "## Facts") != 1 {
|
||||
t.Fatalf("expected exactly one Facts header, got: %q", rendered)
|
||||
}
|
||||
if !strings.Contains(rendered, "first entry") || !strings.Contains(rendered, "second entry") {
|
||||
t.Fatalf("expected both entries present, got %q", rendered)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Add_InvalidSectionName(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Add("bad-name!", "content"); err == nil {
|
||||
t.Fatalf("expected error for invalid section name")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Add_EmptyContent(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Add("Facts", " "); err == nil {
|
||||
t.Fatalf("expected error for empty content")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Add_RejectsOversizedWrite(t *testing.T) {
|
||||
s := newTestStore(t, 32) // tiny bound
|
||||
|
||||
_, err := s.Add("Facts", strings.Repeat("x", 100))
|
||||
if err == nil {
|
||||
t.Fatalf("expected error when write would exceed max bytes")
|
||||
}
|
||||
if s.Render() != "" {
|
||||
t.Fatalf("expected no mutation on rejected write, got %q", s.Render())
|
||||
}
|
||||
if _, statErr := os.Stat(s.Path()); statErr == nil {
|
||||
t.Fatalf("expected no file to be written on rejected write")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Replace_FindsAndReplaces(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Add("Facts", "the sky is blue"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
|
||||
res, err := s.Replace("Facts", "blue", "green", true)
|
||||
if err != nil {
|
||||
t.Fatalf("Replace: %v", err)
|
||||
}
|
||||
if res.CharsRemoved != len("blue") || res.CharsAdded != len("green") {
|
||||
t.Fatalf("unexpected char counts: %+v", res)
|
||||
}
|
||||
|
||||
rendered := s.Render()
|
||||
if !strings.Contains(rendered, "the sky is green") {
|
||||
t.Fatalf("expected replacement applied, got %q", rendered)
|
||||
}
|
||||
if strings.Contains(rendered, "blue") {
|
||||
t.Fatalf("expected original substring gone, got %q", rendered)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Replace_CaseInsensitive(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Add("Facts", "The Sky Is Blue"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
|
||||
if _, err := s.Replace("Facts", "sky", "ocean", false); err != nil {
|
||||
t.Fatalf("Replace: %v", err)
|
||||
}
|
||||
rendered := s.Render()
|
||||
if !strings.Contains(rendered, "The ocean Is Blue") {
|
||||
t.Fatalf("expected case-insensitive replacement, got %q", rendered)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Replace_CaseSensitiveMismatchFails(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Add("Facts", "The Sky Is Blue"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if _, err := s.Replace("Facts", "sky", "ocean", true); err == nil {
|
||||
t.Fatalf("expected case-sensitive mismatch to fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Replace_MissingSection(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Replace("Nope", "a", "b", true); err == nil {
|
||||
t.Fatalf("expected error for missing section")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Replace_SubstringNotFound(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Add("Facts", "the sky is blue"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if _, err := s.Replace("Facts", "purple", "green", true); err == nil {
|
||||
t.Fatalf("expected error when substring not found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Replace_FirstOccurrenceOnly(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Add("Facts", "cat cat cat"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if _, err := s.Replace("Facts", "cat", "dog", true); err != nil {
|
||||
t.Fatalf("Replace: %v", err)
|
||||
}
|
||||
rendered := s.Render()
|
||||
if !strings.Contains(rendered, "dog cat cat") {
|
||||
t.Fatalf("expected only first occurrence replaced, got %q", rendered)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Remove_RemovesMatchingBlock(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Add("Facts", "entry one"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if _, err := s.Add("Facts", "entry two"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
|
||||
res, err := s.Remove("Facts", "entry one", true)
|
||||
if err != nil {
|
||||
t.Fatalf("Remove: %v", err)
|
||||
}
|
||||
if res.CharsRemoved != len("entry one") {
|
||||
t.Fatalf("unexpected chars removed: %d", res.CharsRemoved)
|
||||
}
|
||||
|
||||
rendered := s.Render()
|
||||
if strings.Contains(rendered, "entry one") {
|
||||
t.Fatalf("expected entry one removed, got %q", rendered)
|
||||
}
|
||||
if !strings.Contains(rendered, "entry two") {
|
||||
t.Fatalf("expected entry two to remain, got %q", rendered)
|
||||
}
|
||||
// The section header should remain even though a block was removed.
|
||||
if !strings.Contains(rendered, "## Facts") {
|
||||
t.Fatalf("expected section header to remain, got %q", rendered)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Remove_MissingSection(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Remove("Nope", "a", true); err == nil {
|
||||
t.Fatalf("expected error for missing section")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Remove_SubstringNotFound(t *testing.T) {
|
||||
s := newTestStore(t, 0)
|
||||
if _, err := s.Add("Facts", "entry one"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if _, err := s.Remove("Facts", "nonexistent", true); err == nil {
|
||||
t.Fatalf("expected error when substring not found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_PersistsAcrossReload(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "MEMORY.md")
|
||||
|
||||
s1, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
if _, err := s1.Add("Facts", "persisted entry"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
|
||||
s2, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore reload: %v", err)
|
||||
}
|
||||
if !strings.Contains(s2.Render(), "persisted entry") {
|
||||
t.Fatalf("expected reloaded store to contain persisted entry, got %q", s2.Render())
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Reload_PicksUpExternalChanges(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "MEMORY.md")
|
||||
|
||||
s, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
if s.Render() != "" {
|
||||
t.Fatalf("expected empty store initially")
|
||||
}
|
||||
|
||||
// Simulate an external write (e.g. a prior process, or manual edit)
|
||||
// happening after construction but before Reload.
|
||||
if err := os.WriteFile(path, []byte("## Facts\n\nexternal entry\n"), 0o644); err != nil {
|
||||
t.Fatalf("writing external content: %v", err)
|
||||
}
|
||||
|
||||
if err := s.Reload(); err != nil {
|
||||
t.Fatalf("Reload: %v", err)
|
||||
}
|
||||
if !strings.Contains(s.Render(), "external entry") {
|
||||
t.Fatalf("expected reload to pick up external entry, got %q", s.Render())
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_Reload_MissingFileResetsToEmpty(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "MEMORY.md")
|
||||
|
||||
s, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
if _, err := s.Add("Facts", "entry"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if err := os.Remove(path); err != nil {
|
||||
t.Fatalf("removing file: %v", err)
|
||||
}
|
||||
if err := s.Reload(); err != nil {
|
||||
t.Fatalf("Reload: %v", err)
|
||||
}
|
||||
if s.Render() != "" {
|
||||
t.Fatalf("expected empty store after reload of missing file, got %q", s.Render())
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_EmptySectionRoundTrip(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "MEMORY.md")
|
||||
|
||||
const original = "## Empty\n\n## Next\n\nContent\n"
|
||||
if err := os.WriteFile(path, []byte(original), 0o644); err != nil {
|
||||
t.Fatalf("writing seed file: %v", err)
|
||||
}
|
||||
|
||||
s, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
got := s.Render()
|
||||
if got != original {
|
||||
t.Fatalf("expected stable round-trip for empty section:\nwant %q\ngot %q", original, got)
|
||||
}
|
||||
|
||||
// Re-rendering after a fresh reload must be idempotent (no growth from
|
||||
// repeated parse/render cycles).
|
||||
if err := s.Reload(); err != nil {
|
||||
t.Fatalf("Reload: %v", err)
|
||||
}
|
||||
if got := s.Render(); got != original {
|
||||
t.Fatalf("expected reload to preserve round-trip:\nwant %q\ngot %q", original, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_ConsecutiveEmptySectionsRoundTrip(t *testing.T) {
|
||||
// Extends TestStore_EmptySectionRoundTrip to two consecutive empty
|
||||
// sections followed by a populated one, since the fix must generalize
|
||||
// past a single degenerate case.
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "MEMORY.md")
|
||||
multi := "## E1\n\n## E2\n\n## Facts\n\nfact one\n"
|
||||
if err := os.WriteFile(path, []byte(multi), 0o644); err != nil {
|
||||
t.Fatalf("writing fixture: %v", err)
|
||||
}
|
||||
s2, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
if got := s2.Render(); got != multi {
|
||||
t.Fatalf("round-trip mismatch for consecutive empty sections:\norig: %q\nrender: %q", multi, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_PreambleOnlyRoundTrip(t *testing.T) {
|
||||
// Regression test: a file with no section headers at all (just
|
||||
// preamble content) must not gain a spurious trailing blank line.
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "MEMORY.md")
|
||||
content := "Hello\nWorld\n"
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
t.Fatalf("writing fixture: %v", err)
|
||||
}
|
||||
s, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
if got := s.Render(); got != content {
|
||||
t.Fatalf("round-trip mismatch for preamble-only file:\norig: %q\nrender: %q", content, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStore_MultipleSectionsRoundTrip(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "MEMORY.md")
|
||||
|
||||
s1, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore: %v", err)
|
||||
}
|
||||
if _, err := s1.Add("Facts", "fact one"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if _, err := s1.Add("Preferences", "pref one"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
if _, err := s1.Add("Facts", "fact two"); err != nil {
|
||||
t.Fatalf("Add: %v", err)
|
||||
}
|
||||
|
||||
s2, err := NewStore(path, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("NewStore reload: %v", err)
|
||||
}
|
||||
rendered := s2.Render()
|
||||
for _, want := range []string{"## Facts", "## Preferences", "fact one", "fact two", "pref one"} {
|
||||
if !strings.Contains(rendered, want) {
|
||||
t.Fatalf("expected rendered content to contain %q, got %q", want, rendered)
|
||||
}
|
||||
}
|
||||
|
||||
// Now mutate the reloaded store and ensure both sections survive.
|
||||
if _, err := s2.Remove("Facts", "fact one", true); err != nil {
|
||||
t.Fatalf("Remove: %v", err)
|
||||
}
|
||||
rendered = s2.Render()
|
||||
if strings.Contains(rendered, "fact one") {
|
||||
t.Fatalf("expected fact one removed, got %q", rendered)
|
||||
}
|
||||
if !strings.Contains(rendered, "fact two") || !strings.Contains(rendered, "pref one") {
|
||||
t.Fatalf("expected other entries to survive, got %q", rendered)
|
||||
}
|
||||
}
|
||||
+26
-117
@@ -1,123 +1,32 @@
|
||||
package memory
|
||||
|
||||
import "regexp"
|
||||
import domainmemory "github.com/samcharles93/archie-core/internal/domain/memory"
|
||||
|
||||
// ThreatLevel indicates the severity of a threat detected by a Scanner.
|
||||
type ThreatLevel int
|
||||
// The content scanner moved into the memory engine family
|
||||
// (internal/domain/memory/scanner.go, docs/prds/memory-engine-unification.md
|
||||
// §7), where the engine that persists memory applies it. This package's
|
||||
// legacy Manager still needs the same types until it is deleted in slice 5 of
|
||||
// that PRD, so they are re-exported here rather than duplicated: the
|
||||
// behaviour, the patterns and the tests stay exactly where the decision put
|
||||
// them.
|
||||
//
|
||||
// Delete this file with internal/memory.
|
||||
type (
|
||||
// ThreatLevel is domainmemory.ThreatLevel.
|
||||
ThreatLevel = domainmemory.ThreatLevel
|
||||
// ThreatResult is domainmemory.ThreatResult.
|
||||
ThreatResult = domainmemory.ThreatResult
|
||||
// Scanner is domainmemory.Scanner.
|
||||
Scanner = domainmemory.Scanner
|
||||
// DefaultScanner is domainmemory.DefaultScanner.
|
||||
DefaultScanner = domainmemory.DefaultScanner
|
||||
)
|
||||
|
||||
const (
|
||||
// ThreatNone means no suspicious patterns were found.
|
||||
ThreatNone ThreatLevel = iota
|
||||
|
||||
// ThreatWarn means a potentially problematic pattern was found, but the
|
||||
// write should be allowed with a warning logged.
|
||||
ThreatWarn
|
||||
|
||||
// ThreatBlock means a dangerous pattern was found and the write should
|
||||
// be rejected.
|
||||
ThreatBlock
|
||||
// ThreatNone is domainmemory.ThreatNone.
|
||||
ThreatNone = domainmemory.ThreatNone
|
||||
// ThreatWarn is domainmemory.ThreatWarn.
|
||||
ThreatWarn = domainmemory.ThreatWarn
|
||||
// ThreatBlock is domainmemory.ThreatBlock.
|
||||
ThreatBlock = domainmemory.ThreatBlock
|
||||
)
|
||||
|
||||
// ThreatResult describes a single threat detected during content scanning.
|
||||
type ThreatResult struct {
|
||||
// Level indicates the severity: none, warn, or block.
|
||||
Level ThreatLevel
|
||||
|
||||
// Pattern is the regexp that matched (for audit logging).
|
||||
Pattern string
|
||||
|
||||
// Message is a human-readable description of the threat.
|
||||
Message string
|
||||
}
|
||||
|
||||
// Scanner inspects memory content for dangerous or sensitive patterns before
|
||||
// the content is persisted. Implementations are pluggable; the zero-value
|
||||
// DefaultScanner is a reasonable default for production use.
|
||||
type Scanner interface {
|
||||
// ScanContent examines content and returns a ThreatResult. A result
|
||||
// with Level == ThreatNone means the content is clean.
|
||||
ScanContent(content string) ThreatResult
|
||||
}
|
||||
|
||||
// DefaultScanner is the built-in Scanner implementation. It checks for
|
||||
// prompt-injection patterns (block-level) and sensitive-data leakage
|
||||
// (warn-level). The zero value is usable.
|
||||
type DefaultScanner struct{}
|
||||
|
||||
// Compile-time check: DefaultScanner implements Scanner.
|
||||
var _ Scanner = (*DefaultScanner)(nil)
|
||||
|
||||
// ── Patterns ────────────────────────────────────────────────────────────
|
||||
//
|
||||
// These patterns are compiled once at init time. They are intentionally
|
||||
// broad to catch common variants without being so broad that they
|
||||
// produce false positives on normal memory content.
|
||||
|
||||
var (
|
||||
promptInjectionPatterns = []*regexp.Regexp{
|
||||
// Override / ignore previous instructions
|
||||
regexp.MustCompile(`(?i)(ignore|forget|override|disregard)\s+(all\s+)?(the\s+)?(previous|above|prior|earlier)\s+(instructions?|directions?|commands?|prompts?)`),
|
||||
|
||||
// Role-change / identity attacks
|
||||
regexp.MustCompile(`(?i)(you\s+(are|now)\s+|act\s+as\s+|pretend\s+(to\s+be|you\s+are)\s+|roleplay\s+as\s+)(now\s+)?(an?\s+)?(different|new|another|unrestricted|uncensored)`),
|
||||
|
||||
// Delimiter injection (common in adversarial prompts)
|
||||
regexp.MustCompile(`(?i)<\|im_start\|>`),
|
||||
regexp.MustCompile(`(?i)<\|im_end\|>`),
|
||||
|
||||
// System prompt extraction attempts
|
||||
regexp.MustCompile(`(?i)(print|output|repeat|display|show|tell\s+me)\s+(your\s+)?(system\s+)?(prompt|instructions?|directions?)\s*(exactly|verbatim)?`),
|
||||
}
|
||||
|
||||
sensitiveDataPatterns = []*regexp.Regexp{
|
||||
// API keys and secrets with common key=value patterns
|
||||
regexp.MustCompile(`(?i)(api[_\s-]?key|apikey|api[_\s-]?secret)\s*[:=]\s*['"\x60]?[\w-]{8,}['"\x60]?`),
|
||||
|
||||
// Passwords in key=value form
|
||||
regexp.MustCompile(`(?i)(password|passwd|pwd)\s*[:=]\s*['"\x60]?\S{4,}['"\x60]?`),
|
||||
|
||||
// Generic secrets and tokens
|
||||
regexp.MustCompile(`(?i)(secret|token|credential|authorization)\s*[:=]\s*['"\x60]?[\w-]{8,}['"\x60]?`),
|
||||
|
||||
// Private key blocks (PEM format)
|
||||
regexp.MustCompile(`(?i)-----BEGIN\s+(RSA\s+|EC\s+|DSA\s+|OPENSSH\s+)?PRIVATE\s+KEY-----`),
|
||||
|
||||
// JWT tokens (base64-encoded header.payload.signature pattern)
|
||||
regexp.MustCompile(`eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}`),
|
||||
}
|
||||
)
|
||||
|
||||
// ScanContent examines content against the prompt-injection and
|
||||
// sensitive-data patterns. Prompt-injection matches produce ThreatBlock;
|
||||
// sensitive-data matches produce ThreatWarn. The first match wins.
|
||||
func (s *DefaultScanner) ScanContent(content string) ThreatResult {
|
||||
for _, p := range promptInjectionPatterns {
|
||||
if m := p.FindString(content); m != "" {
|
||||
return ThreatResult{
|
||||
Level: ThreatBlock,
|
||||
Pattern: p.String(),
|
||||
Message: "content matches prompt injection pattern: " + truncateMatch(m),
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, p := range sensitiveDataPatterns {
|
||||
if m := p.FindString(content); m != "" {
|
||||
return ThreatResult{
|
||||
Level: ThreatWarn,
|
||||
Pattern: p.String(),
|
||||
Message: "content may contain sensitive data: " + truncateMatch(m),
|
||||
}
|
||||
}
|
||||
}
|
||||
return ThreatResult{Level: ThreatNone}
|
||||
}
|
||||
|
||||
// truncateMatch limits the matched string for log/error messages so that
|
||||
// a long match (e.g. an entire private key) is not echoed in full.
|
||||
func truncateMatch(s string) string {
|
||||
const maxMatchLen = 40
|
||||
if len(s) <= maxMatchLen {
|
||||
return s
|
||||
}
|
||||
return s[:maxMatchLen] + "..."
|
||||
}
|
||||
Reference in new issue
Block a user