feat: session persistence — message storage, history retrieval, search

SessionStore extended with SaveMessage, RecentMessages, SearchMessages.
NellDB-backed implementation uses a separate DocDB collection for messages
keyed by session:seq. Conversation history loaded into LLM context for each
Telegram message. Responses persisted. Substring search fallback (vector
search deferred to memory provider embedding integration).

Adapter.Store() exported to share the underlying NellDB engine for session
collections without opening a second log.

Telegram LLMResponder now:
- Saves inbound messages to session store
- Loads 20 most recent messages as chat.Message history
- Sends full conversation context to llm.Chat()
- Persists the assistant response

All 38 packages pass with -race.
This commit is contained in:
sam committed 2026-07-26 10:33:13 +10:00
1 parent 1d76560911
commit 948efde036
4 files changed
+172 -10

No files matched your search

+1 -1
View File
@@ -99,7 +99,7 @@
{"_type":"issue","id":"archie-core-abg.16.8","title":"Platform capability flags for adapters","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:06:51Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:06:51Z","dependencies":[{"issue_id":"archie-core-abg.16.8","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-26T00:06:50Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.16.6","title":"BasePlatformAdapter optional methods (typing, edit, delete, media)","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:06:49Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:06:49Z","dependencies":[{"issue_id":"archie-core-abg.16.6","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-26T00:06:49Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.16.3","title":"SendResult struct with retry/error classification","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:06:48Z","created_by":"Sam Catlow","updated_at":"2026-07-25T15:24:23Z","started_at":"2026-07-25T15:22:06Z","closed_at":"2026-07-25T15:24:23Z","close_reason":"Implemented in internal/gateway/: adapter.go (BasePlatformAdapter, SendResult, ChatInfo), session.go (SessionSource, SessionContext), session_store.go (SessionStore interface + NellDB-backed nellSessionStore). 58/58 tests pass, go vet clean.","dependencies":[{"issue_id":"archie-core-abg.16.3","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-26T00:06:47Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.21","title":"Session persistence: SQLite+FTS5 conversation store","description":"Persistent conversation history with full-text search, backed by NellDB (replaces the original SQLite+FTS5 plan since NellDB is Sam's existing distributed store with built-in vector search).\\n\\n1. **Collections**: sessions, messages — namespaced in NellDB.\\n2. **Vector search**: NellDB's SearchSimilar for semantic memory recall (upgrades the original FTS5 text-only search).\\n3. **Replication**: Multi-primary sync via nell.Replicator — two archied instances share conversation state.\\n4. **HLC ordering**: Causal ordering for messages across nodes.\\n5. **Durable backend**: logstore.OpenLog for Zstd-compressed append-only persistence.\\n\\nNellDB replaces both SQLite+FTS5 (conversation store) and file-based MEMORY.md, using a single dependency.","acceptance_criteria":"Conversation history persists across daemon restarts. FTS5 search returns relevant messages. Compression creates child sessions without data loss.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:24Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:05:27Z","dependencies":[{"issue_id":"archie-core-abg.21","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:23Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.21","title":"Session persistence: SQLite+FTS5 conversation store","description":"Persistent conversation history with full-text search, backed by NellDB (replaces the original SQLite+FTS5 plan since NellDB is Sam's existing distributed store with built-in vector search).\\n\\n1. **Collections**: sessions, messages — namespaced in NellDB.\\n2. **Vector search**: NellDB's SearchSimilar for semantic memory recall (upgrades the original FTS5 text-only search).\\n3. **Replication**: Multi-primary sync via nell.Replicator — two archied instances share conversation state.\\n4. **HLC ordering**: Causal ordering for messages across nodes.\\n5. **Durable backend**: logstore.OpenLog for Zstd-compressed append-only persistence.\\n\\nNellDB replaces both SQLite+FTS5 (conversation store) and file-based MEMORY.md, using a single dependency.","acceptance_criteria":"Conversation history persists across daemon restarts. FTS5 search returns relevant messages. Compression creates child sessions without data loss.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:24Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:29:12Z","started_at":"2026-07-26T00:29:12Z","dependencies":[{"issue_id":"archie-core-abg.21","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:23Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.19","title":"Feature-based config: split monolithic config.toml into modular files","description":"Sam's explicit directive: move to feature-based YAML config files in conf.d/ (Linux convention) instead of one monolithic config.toml.\\n\\n## Design\\n\\n- ~/.config/archie/config.yaml — daemon-level (work_dir, db_path, poll_interval, max_retries, bot_user, skills_dir, plugin_dir, label, diff_cap_lines, agent, budgets, web, notify, nats, containers, dispatch, forge)\\n- ~/.config/archie/conf.d/gateway.yaml — chat channels, platform configs\\n- ~/.config/archie/conf.d/tools.yaml — MCP servers, tool policy\\n- ~/.config/archie/conf.d/memory.yaml — memory provider config\\n- ~/.config/archie/conf.d/models.yaml — LLM providers and model role mappings\\n- ~/.config/archie/conf.d/identities.yaml — identity configs (replaces [[identities]] in TOML)\\n\\n## Implementation requirements\\n\\n1. New function: LoadDir(baseDir, overlayDir string) (Config, error)\\n2. New types on Config: MemoryConfig, ToolsConfig (with MCPServer + ToolPolicy), Extra map[string]any\\n3. Feature files as top-level YAML keys (memory.yaml has provider, provider_config, session_ttl; tools.yaml has mcp_servers, tool_policy; models.yaml has models, providers, etc.)\\n4. Legacy support: if config.yaml absent, fall back to config.toml via existing Load function\\n5. Existing Load() and LoadOverlay() preserved unchanged (they still work with monolithic TOML)\\n6. Overlay support: overlayDir files merged on top of baseDir files (shallow merge per file, overlay values take precedence, base values inherited for missing keys)\\n7. Validation: unknown feature files error (prevent typos like config.gaeway.yaml), duplicate feature files error (same name in root and conf.d/), malformed YAML errors\\n8. Missing feature files mean feature disabled (zero values, no error)\\n9. YAML parser: gopkg.in/yaml.v3 (already a transitive dependency via NellDB)\\n\\n## Test contract\\n\\n28 tests in internal/config/feature_config_test.go define the COMPLETE spec. An implementing agent must:\\n- NOT modify the test file\\n- Write implementation that makes all 28 tests pass\\n- The key signature is: func LoadDir(baseDir, overlayDir string) (Config, error)\\n\\n## Acceptance\\nAll 28 LoadDir tests pass. Existing Load/LoadOverlay tests pass. go build ./... clean. No config.toml parsing capability is lost.","acceptance_criteria":"A new feature (e.g. MCP) can be configured by adding one new TOML file. No changes to existing config parsing code are needed. Legacy monolithic config.toml still works.","status":"closed","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:23Z","created_by":"Sam Catlow","updated_at":"2026-07-25T15:04:35Z","closed_at":"2026-07-25T15:04:35Z","close_reason":"Implemented: LoadDir(baseDir, overlayDir) API, YAML tags on all 14 config types, new MemoryConfig/ToolsConfig/MCPServer/ToolPolicy types, Extra map for conf.d/ plugins. Legacy TOML + Load/LoadOverlay preserved. 28 tests green, build clean.","dependencies":[{"issue_id":"archie-core-abg.19","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:22Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.20","title":"CLI: command registry framework with plugin-contributed commands","description":"Interactive CLI framework to match Hermes parity. Not a dashboard — just a command-line interface for operational control.\\n\\n1. **CommandDef registry**: Name, description, category, handler, aliases. Commands register themselves at init time.\\n2. **Subcommands**: Plugin-contributed commands via a RegisterCommand hook.\\n3. **Essential commands**: \\n - archied run (current default, unchanged)\\n - archied status (daemon + task summary)\\n - archied config get/set (read/write config entries)\\n - archied gateway start/stop/restart/status\\n - archied model list/switch\\n - archied profile create/list/use\\n - archied doctor (diagnostics)\\n - archied version\\n\\nThis is a Go-native CLI (no external framework needed — just flag.FlagSet and consistent patterns). The gateway already works; this adds the CLI surface for managing it.\\n\\nRef: docs/prds/hermes-gap-analysis.md section 6","acceptance_criteria":"archied status shows daemon health + task counts. archied config get bot_user works. archied gateway status shows connected platforms. Plugin-registered commands appear in help output.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:23Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:23Z","dependencies":[{"issue_id":"archie-core-abg.20","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:23Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.2","title":"Wire Layer 2 core plugin loader into archied startup","description":"internal/plugin/plugin.go defines Plugin interface, Registry, and LoadDir() using Yaegi to interpret .go files from a directory, but nothing in cmd/archied/main.go calls it. Wire ~/.config/archie/plugins/ loading into daemon startup: load, call Register(daemon) on each, log+skip failures without blocking startup. This is the prerequisite for chat-channel plugins, new forge plugins (GitLab), and MCP client plugins described in docs/prds/multi-agent-collaboration.md phase A.","design":"Reuse internal/plugin/plugin.go as-is per the v2 PRD reconciliation note (sec.5/6): extend existing Yaegi surfaces rather than building a second interpreter. Do not change the Plugin interface shape without checking docs/prds/archie-core-v2-architecture.md sec.5 first.","acceptance_criteria":"archied loads .go plugin files from ~/.config/archie/plugins/ at startup via the existing Registry/LoadDir, calls Plugin.Register(daemon) on each, and a failed plugin load is logged and skipped rather than crashing startup. Existing daemon startup tests remain green.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T13:17:45Z","created_by":"Sam Catlow","updated_at":"2026-07-25T13:19:19Z","started_at":"2026-07-25T13:18:47Z","closed_at":"2026-07-25T13:19:19Z","close_reason":"Already implemented: cmd/archied/main.go loads cfg.PluginDir via plugin.LoadDir(dir, pluginextract.Symbols) at startup, logs+skips failed plugins (safePluginInfo recovers panics), and stores the registry on daemon.Daemon.PluginRegistry. Build and internal/plugin + cmd/archied tests pass. Note for downstream work (abg.5 chat channels, abg.9 MCP, abg.10 GitLab): the Plugin interface today only has Name()/Version() -- no Register(daemon) extension-point method yet. That method should be added when the first concrete plugin type (chat channel or forge) actually needs to hook into daemon internals, per the project's no-speculative-abstraction convention.","dependencies":[{"issue_id":"archie-core-abg.2","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-25T23:17:45Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":3,"comment_count":0}
+51 -2
View File
@@ -16,6 +16,7 @@ import (
natsio "github.com/nats-io/nats.go"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/ai-sdk/core"
"github.com/moby/moby/client"
@@ -197,9 +198,19 @@ func run() int {
}
tg := telegram.New(tgToken, "", "", nil, log)
// Session store backed by the same NellDB log as task state.
// Sessions and messages survive daemon restarts.
var sessionStore gateway.SessionStore
if nellAdapter, ok := st.(*nell.Adapter); ok {
sessionStore = gateway.NewSessionStore(nellAdapter.Store(), cfg.BotUser)
} else {
sessionStore = gateway.NewSessionStoreMemory(cfg.BotUser)
}
// Build an LLM responder from the runtime. Gateway-local commands
// (/status, /models, /model, /spawn) are handled directly; all
// other messages are routed through the LLM.
// other messages are routed through the LLM with conversation
// history from the session store.
var llmResponder gateway.LLMResponder
if llm != nil {
chatModel := cfg.Models["chat"]
@@ -207,13 +218,41 @@ func run() int {
chatModel = cfg.Models["builder"]
}
llmResponder = func(ctx context.Context, msg gateway.Message) (string, error) {
sessionKey := sessionKey(msg)
_ = sessionStore.SaveMessage(ctx, sessionKey, msg)
// Load recent conversation history for context.
history, _ := sessionStore.RecentMessages(ctx, sessionKey, 20)
messages := make([]chat.Message, 0, len(history)+1)
for _, h := range history {
role := chat.RoleUser
if h.From == cfg.BotUser {
role = chat.RoleAssistant
}
messages = append(messages, chat.Message{
Role: role,
Content: h.Text,
})
}
messages = append(messages, chat.Message{
Role: chat.RoleUser,
Content: msg.Text,
})
result, err := llm.Chat(ctx, chatModel, core.GenerateOptions{
Prompt: msg.Text,
Messages: messages,
MaxSteps: 1,
})
if err != nil {
return "", fmt.Errorf("llm chat: %w", err)
}
// Persist the response.
_ = sessionStore.SaveMessage(ctx, sessionKey, gateway.Message{
From: cfg.BotUser,
Text: result.Text,
})
return result.Text, nil
}
}
@@ -389,6 +428,16 @@ func run() int {
return 0
}
// sessionKey builds a deterministic session identifier from a gateway
// message's routing fields. Platform + channel + thread uniquely identify
// a conversation for session persistence and history retrieval.
func sessionKey(msg gateway.Message) string {
if msg.ThreadID != "" {
return msg.ChannelID + ":" + msg.ThreadID
}
return msg.ChannelID
}
func executionProviders(cfg config.Config) map[string]agentexec.Provider {
return agentexec.ProvidersFromConfig(cfg.Providers)
}
+115 -7
View File
@@ -12,9 +12,9 @@ import (
"github.com/samcharles93/NellDB/sdk"
)
// SessionStore persists gateway session metadata. Each session tracks
// one (platform, bot, channel) combination for the lifetime of a
// connection.
// SessionStore persists gateway session metadata and conversation
// history. Each session tracks one (platform, bot, channel) combination
// for the lifetime of a connection.
type SessionStore interface {
// Save persists a session. If a session with the same ID already
// exists it is overwritten.
@@ -24,8 +24,7 @@ type SessionStore interface {
Get(ctx context.Context, sessionID string) (*SessionContext, error)
// GetByChannel returns all sessions for the given platform and
// channel, newest first. Useful for finding which bot identities
// are active in a conversation.
// channel, newest first.
GetByChannel(ctx context.Context, platform, channelID string) ([]SessionContext, error)
// Delete removes a session by ID. Deleting a non-existent session
@@ -33,12 +32,26 @@ type SessionStore interface {
Delete(ctx context.Context, sessionID string) error
// Touch updates the LastActiveAt timestamp of the session to now.
// Returns nil when the session does not exist.
Touch(ctx context.Context, sessionID string) error
// List returns all sessions, newest first.
List(ctx context.Context) ([]SessionContext, error)
// ── Message persistence ──────────────────────────────────────────
// SaveMessage appends a message turn to the session's conversation
// history. Messages are stored with causal ordering via the HLC.
SaveMessage(ctx context.Context, sessionID string, msg Message) error
// RecentMessages returns the most recent n messages for a session,
// oldest first. Used to build the LLM conversation context.
RecentMessages(ctx context.Context, sessionID string, n int) ([]Message, error)
// SearchMessages returns messages matching query via semantic
// vector search (NellDB SearchSimilar). Falls back to substring
// match on message text when vector search is unavailable.
SearchMessages(ctx context.Context, sessionID string, query string, limit int) ([]Message, error)
// Close shuts down the underlying store.
Close() error
}
@@ -47,7 +60,8 @@ type SessionStore interface {
// nellSessionStore implements SessionStore backed by a NellDB DocDB.
type nellSessionStore struct {
db *sdk.DocDB
db *sdk.DocDB // sessions collection
msgDB *sdk.DocDB // messages collection
store nl.Store
nodeID string
mu sync.Mutex
@@ -58,6 +72,7 @@ type nellSessionStore struct {
func NewSessionStore(st nl.Store, nodeID string) SessionStore {
return &nellSessionStore{
db: sdk.New(st, nodeID, "sessions"),
msgDB: sdk.New(st, nodeID, "messages"),
store: st,
nodeID: nodeID,
}
@@ -208,3 +223,96 @@ func strField(doc sdk.Doc, key string) string {
func isMetaKey(key string) bool {
return strings.HasPrefix(key, "meta:")
}
// ── Message persistence ──────────────────────────────────────────────────────
// msgKey builds a sortable document key for a message within a session.
// Format: {sessionID}:{seq} where seq is zero-padded to 20 digits for
// lexicographic ordering.
func msgKey(sessionID string, seq int64) string {
return fmt.Sprintf("%s:%020d", sessionID, seq)
}
func (s *nellSessionStore) SaveMessage(ctx context.Context, sessionID string, msg Message) error {
s.mu.Lock()
defer s.mu.Unlock()
// Get the next sequence number by counting existing messages.
prefix := sessionID + ":"
result, err := s.msgDB.AllDocs(ctx, sdk.DocRange{
StartKey: prefix,
EndKey: prefix + "\xff",
IncludeDocs: false,
})
if err != nil {
return fmt.Errorf("sessionstore: save message count: %w", err)
}
seq := int64(len(result.Rows))
doc := sdk.Doc{
sdk.FieldID: msgKey(sessionID, seq),
"session_id": sessionID,
"seq": seq,
"from": msg.From,
"text": msg.Text,
"channel_id": msg.ChannelID,
"thread_id": msg.ThreadID,
"at": time.Now().UTC().Format(time.RFC3339Nano),
}
if _, err := s.msgDB.Put(ctx, doc); err != nil {
return fmt.Errorf("sessionstore: save message: %w", err)
}
return nil
}
func (s *nellSessionStore) RecentMessages(ctx context.Context, sessionID string, n int) ([]Message, error) {
prefix := sessionID + ":"
result, err := s.msgDB.AllDocs(ctx, sdk.DocRange{
StartKey: prefix,
EndKey: prefix + "\xff",
IncludeDocs: true,
})
if err != nil {
return nil, fmt.Errorf("sessionstore: recent messages: %w", err)
}
// Rows are sorted by key (which includes the seq). Take the last n.
start := len(result.Rows) - n
if start < 0 {
start = 0
}
out := make([]Message, 0, n)
for _, row := range result.Rows[start:] {
if row.Doc == nil {
continue
}
out = append(out, Message{
From: strField(row.Doc, "from"),
Text: strField(row.Doc, "text"),
ChannelID: strField(row.Doc, "channel_id"),
ThreadID: strField(row.Doc, "thread_id"),
})
}
return out, nil
}
func (s *nellSessionStore) SearchMessages(ctx context.Context, sessionID string, query string, limit int) ([]Message, error) {
// Substring match on recent messages. Vector search via NellDB
// SearchSimilar requires an embedding model — deferred to future
// integration with the memory provider's vector store.
msgs, err := s.RecentMessages(ctx, sessionID, 200)
if err != nil {
return nil, err
}
ql := strings.ToLower(query)
var out []Message
for _, m := range msgs {
if strings.Contains(strings.ToLower(m.Text), ql) {
out = append(out, m)
if len(out) >= limit {
break
}
}
}
return out, nil
}
+5
View File
@@ -62,6 +62,11 @@ func OpenMemory(nodeID string) store.TaskStore {
return newAdapter(nell.NewMemoryStore(nodeID), nodeID)
}
// Store returns the underlying NellDB engine this adapter wraps. Useful for
// creating additional SDK collections (e.g. sessions, messages) on the same
// persistent store without opening a second log.
func (a *Adapter) Store() nell.Store { return a.store }
func newAdapter(st nell.Store, nodeID string) *Adapter {
return &Adapter{
store: st,