feat: MessageType enum + MessageEvent struct (16.1, 16.2)

internal/gateway/messagetype.go — 14-value MessageType enum with
IsMedia(), IsRich(), IsEphemeral() classification helpers.

internal/gateway/messageevent.go — platform-neutral MessageEvent:
text, type, media attachments (file metadata, dimensions, duration),
reply context (message ID, text, author), editing support (edited
flag, edit timestamp), capability flags (streaming, code blocks).

Verification agent found 7 issues, 5 fixed (pointer types for
FileSize/Width/Height/Duration, MsgSticker in IsMedia, IsRich
coverage, ToLegacy edge cases), 2 correctly deferred.

42 tests pass. Build + vet + fmt clean.

Closes: archie-core-abg.16.1, archie-core-abg.16.2
This commit is contained in:
sam committed 2026-07-26 01:19:38 +10:00
1 parent b61b736f77
commit 30b76f2ead
10 files changed
+1191 -7

No files matched your search

+3
View File
@@ -33,3 +33,6 @@
{"id":"int-c43edbd4c4a08c8218dd60a3c28bfc11","kind":"field_change","created_at":"2026-07-25T14:31:11.55938636Z","actor":"Sam Catlow","issue_id":"archie-core-abg.30","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"NellDB integrated as persistent backend. Created store.TaskStore interface, internal/nell/adapter.go with logstore.LogStore persistence, updated all consumers to depend on the interface. 7 integration tests verify enqueue, claim, transition, update, events, persistence across restart."}}
{"id":"int-5ae3dbeeb2bd57f32b3ff639d8808c9b","kind":"field_change","created_at":"2026-07-25T14:31:11.741361743Z","actor":"Sam Catlow","issue_id":"archie-core-abg.30v","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"NellDB integrated as persistent backend. Created store.TaskStore interface, internal/nell/adapter.go with logstore.LogStore persistence, updated all consumers to depend on the interface. 7 integration tests verify enqueue, claim, transition, update, events, persistence across restart."}}
{"id":"int-fee34ada4224c08d024409cf1634a339","kind":"field_change","created_at":"2026-07-25T15:04:35.464107193Z","actor":"Sam Catlow","issue_id":"archie-core-abg.19","extra":{"field":"status","new_value":"closed","old_value":"open","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."}}
{"id":"int-00ef7a26b3c6d9d4449e2c546a8f9d5e","kind":"field_change","created_at":"2026-07-25T15:08:34.046521882Z","actor":"Sam Catlow","issue_id":"archie-core-abg.17.1","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}}
{"id":"int-0ef896206280288b339ae3c2a026e4ba","kind":"field_change","created_at":"2026-07-25T15:13:09.046176022Z","actor":"Sam Catlow","issue_id":"archie-core-abg.16.1","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}}
{"id":"int-bf3d80be2da850c4fa08e136de3f9c91","kind":"field_change","created_at":"2026-07-25T15:13:09.271318819Z","actor":"Sam Catlow","issue_id":"archie-core-abg.16.2","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}}
+3 -3
View File
@@ -28,7 +28,7 @@
{"_type":"issue","id":"archie-core-abg.18.5","title":"MemoryProvider backup paths support","description":"Add backup_paths() to MemoryProvider: returns a list of file paths outside HERMES_HOME that should be included in backups. External providers (e.g., SQLite, vector stores) may store data outside the main home directory, and this ensures backup completeness.","acceptance_criteria":"BackupProvider interface with backup_paths() returning []string\nReturned paths are absolute file or directory paths\nReturns empty slice for providers with no external data\nMemoryManager aggregates backup paths from all active providers\nPaths are included in any backup/restore workflow","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:28Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:07:28Z","dependencies":[{"issue_id":"archie-core-abg.18.5","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:07:28Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.17.2","title":"Central tool registry singleton with Register() + discovery","description":"Implement a global tool registry singleton with a Register() method. Add file-system discovery that scans tools/*.go for registry.Register calls to auto-register tools at startup. This is the core infrastructure that all tool registration and lookup depends on.","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:25Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:07:25Z","dependencies":[{"issue_id":"archie-core-abg.17.2","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:25Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.18.4","title":"MemoryProvider config helpers","description":"Add config helper interfaces to MemoryProvider: get_config_schema() returns a JSON Schema describing the provider's configuration, save_config(values, hermes_home) validates and persists configuration. These enable dynamic provider configuration through the config system.","acceptance_criteria":"ConfigSchemaProvider defines get_config_schema() returning map[string]any in JSON Schema format\nSaveConfigProvider defines save_config(values map[string]any, hermesHome string) error\nSchema is used to validate user-provided config values before saving\nsave_config writes to a provider-specific location under hermes_home\nProviders without config support simply don't implement the interfaces","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:24Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:07:24Z","dependencies":[{"issue_id":"archie-core-abg.18.4","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:07:24Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.17.1","title":"ToolEntry data type definition","description":"Design and implement the ToolEntry data type carrying: name, toolset (which tool group this belongs to), schema (JSON Schema for invocation), handler (function ref), check_fn (availability predicate), requires_env (env vars needed), is_async (async/sync distinction), description, emoji, max_result_size_chars (per-tool result cap), and dynamic_schema_overrides (runtime schema mutations). This is the foundational type that everything in the tools subsystem builds upon.","status":"in_progress","priority":0,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:22Z","created_by":"Sam Catlow","updated_at":"2026-07-25T15:07:07Z","started_at":"2026-07-25T15:07:07Z","dependencies":[{"issue_id":"archie-core-abg.17.1","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:21Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.17.1","title":"ToolEntry data type definition","description":"Design and implement the ToolEntry data type carrying: name, toolset (which tool group this belongs to), schema (JSON Schema for invocation), handler (function ref), check_fn (availability predicate), requires_env (env vars needed), is_async (async/sync distinction), description, emoji, max_result_size_chars (per-tool result cap), and dynamic_schema_overrides (runtime schema mutations). This is the foundational type that everything in the tools subsystem builds upon.","status":"closed","priority":0,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:22Z","created_by":"Sam Catlow","updated_at":"2026-07-25T15:08:34Z","started_at":"2026-07-25T15:07:07Z","closed_at":"2026-07-25T15:08:34Z","close_reason":"Closed","dependencies":[{"issue_id":"archie-core-abg.17.1","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T00:07:21Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.18.3","title":"MemoryProvider lifecycle hooks","description":"Add lifecycle hook interfaces to MemoryProvider: on_turn_start(), on_session_end(), on_session_switch(), on_pre_compress(), on_memory_write(content), on_delegation(). These allow providers to react to session lifecycle events for state management and context maintenance.","acceptance_criteria":"Each lifecycle hook is a separate optional sub-interface (e.g., TurnStartHook, SessionEndHook, SessionSwitchHook, PreCompressHook, MemoryWriteHook, DelegationHook)\nInterfaces are defined alongside MemoryProvider in the same package\nMemoryManager calls hooks at appropriate points in the agent lifecycle\nHooks have access to relevant context (session_id, content, etc.)\nAll hooks are called asynchronously to avoid blocking the main loop","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:20Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:07:20Z","dependencies":[{"issue_id":"archie-core-abg.18.3","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:07:20Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.18.2","title":"MemoryProvider optional methods","description":"Add optional methods to the MemoryProvider interface: system_prompt_block(), prefetch(query), queue_prefetch(query), sync_turn(user, assistant), handle_tool_call(name, args), shutdown(). These are defined as separate interface extensions that providers can opt into via type assertion.","acceptance_criteria":"Optional behavior is defined via separate sub-interfaces (e.g., PrefetchProvider, SyncTurnProvider, ShutdownProvider)\nMemoryManager checks via type assertion at runtime which optional interfaces a provider implements\nEach optional interface has clear doc comments\nDefault no-op behavior when a provider doesn't implement an optional interface","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:16Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:07:16Z","dependencies":[{"issue_id":"archie-core-abg.18.2","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:07:16Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.18.1","title":"MemoryProvider interface (abstract)","description":"Define the core MemoryProvider interface with required methods: name(), is_available(), initialize(session_id), get_tool_schemas(). This is the contract that all memory providers (built-in and external/plugin) must implement.","acceptance_criteria":"MemoryProvider is defined as a Go interface in a new internal/memory/provider package\nname() returns a unique human-readable string identifying the provider\nis_available() returns true when the provider is ready for use\ninitialize(session_id) prepares the provider for a given session\nget_tool_schemas() returns the tool definitions the provider exports to the agent\nClean godoc comments on all methods","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:07:12Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:07:12Z","dependencies":[{"issue_id":"archie-core-abg.18.1","depends_on_id":"archie-core-abg.18","type":"parent-child","created_at":"2026-07-26T00:07:11Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
@@ -36,8 +36,8 @@
{"_type":"issue","id":"archie-core-abg.16.11","title":"SessionStore interface and implementation","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:06:54Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:06:54Z","dependencies":[{"issue_id":"archie-core-abg.16.11","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-26T00:06:54Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.16.9","title":"SessionSource struct for platform identity","status":"open","priority":0,"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.9","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-26T00:06:51Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.16.5","title":"BasePlatformAdapter interface with required methods","status":"open","priority":0,"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.5","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-26T00:06:48Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.16.2","title":"Rich MessageEvent struct with all gateway fields","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:06:47Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:06:47Z","dependencies":[{"issue_id":"archie-core-abg.16.2","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.16.1","title":"MessageType enum for gateway messages","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T14:06:44Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:06:44Z","dependencies":[{"issue_id":"archie-core-abg.16.1","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-26T00:06:43Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.16.2","title":"Rich MessageEvent struct with all gateway fields","status":"closed","priority":0,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:06:47Z","created_by":"Sam Catlow","updated_at":"2026-07-25T15:13:09Z","started_at":"2026-07-25T15:11:04Z","closed_at":"2026-07-25T15:13:09Z","close_reason":"Closed","dependencies":[{"issue_id":"archie-core-abg.16.2","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.16.1","title":"MessageType enum for gateway messages","status":"closed","priority":0,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:06:44Z","created_by":"Sam Catlow","updated_at":"2026-07-25T15:13:09Z","started_at":"2026-07-25T15:11:03Z","closed_at":"2026-07-25T15:13:09Z","close_reason":"Closed","dependencies":[{"issue_id":"archie-core-abg.16.1","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-26T00:06:43Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.30","title":"Integrate NellDB as persistent memory and configuration backend","description":"Replace SQLite+FTS5+file-based storage with NellDB, Sam's existing distributed document database. NellDB provides:\\n\\n- **nell.Store interface**: Put, Get, Delete, List, ListAll, Query, GetChangesSince, SearchSimilar (vector search)\\n- **sdk.DocDB**: Document database with MVCC revisions\\n- **logstore**: Durable Zstd-compressed append-only log\\n- **sdk.Replicator**: Multi-primary HTTP replication with HLC knowledge vectors\\n- **Vector search**: HNSW + PCA + PQ for semantic memory\\n- **HTTP server**: Standalone binary on port 9342\\n\\nPlan:\\n\\n1. Add NellDB as a dependency (go get github.com/samcharles93/NellDB)\\n2. Create internal/nell/ adapter package wrapping nell.Store for archie-core's data models\\n3. Collections: sessions, messages, memory, config, tasks\\n4. Replace internal/store (SQLite) with NellDB backend\\n5. Replace file-based MEMORY.md with nell collections + vector search\\n6. Wire into cmd/archied/main.go as the storage backend\\n\\nThis gives archie-core multi-primary replication for free — two archied instances on different hosts can sync state without a central database.\\n\\nRef: /work/apps/nell-engine/ (store.go, types.go, sdk/docdb.go, server/)","acceptance_criteria":"archied starts with a NellDB backend instead of SQLite. Sessions and messages persist across restarts. Vector search returns semantically similar messages. Two archied instances can replicate state via nell sync.","status":"closed","priority":0,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-25T14:03:34Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:31:11Z","started_at":"2026-07-25T14:18:03Z","closed_at":"2026-07-25T14:31:11Z","close_reason":"NellDB integrated as persistent backend. Created store.TaskStore interface, internal/nell/adapter.go with logstore.LogStore persistence, updated all consumers to depend on the interface. 7 integration tests verify enqueue, claim, transition, update, events, persistence across restart.","dependencies":[{"issue_id":"archie-core-abg.30","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:03:33Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.17","title":"[EPIC] Tools: central registry, MCP client, guardrails","description":"Central tool infrastructure to match Hermes parity:\\n\\n1. **Tool registry**: A central registry where tool modules register themselves with name, schema, handler, toolset membership, and availability check. Dynamic discovery of built-in tools. This replaces the current pattern of manually constructing core.ToolSet maps per invocation.\\n\\n2. **MCP client**: Connect to external MCP servers via stdio, HTTP/StreamableHTTP, or SSE transport. Discover their tools and register them into the tool registry. Support automatic reconnection with backoff, configurable timeouts, per-server parallel tool call opt-in.\\n\\n3. **Guardrails**: Tool-call loop detection (repeated calls, repeated failures, no-progress loops). Idempotent/mutating tool classification. Warning vs hard-stop decisions.\\n\\n4. **Progressive disclosure**: When tool schemas exceed a context-window threshold, replace them with bridge tools (tool_search/tool_describe/tool_call) and surface on demand. Core tools are always visible.\\n\\nRef: docs/prds/hermes-gap-analysis.md section 3","acceptance_criteria":"MCP servers can be configured with a TOML block and their tools appear alongside built-ins. The agent loop is protected against tool-call loops. Tool schemas stay within context budget.","status":"open","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:22Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:22Z","dependencies":[{"issue_id":"archie-core-abg.17","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":0,"comment_count":0}
{"_type":"issue","id":"archie-core-abg.18","title":"[EPIC] Memory: pluggable provider architecture with file-backed persistence","description":"Pluggable memory system to match Hermes parity:\\n\\n1. **MemoryProvider interface**: Abstract interface with methods for initialize(), get_tool_schemas(), prefetch(), sync_turn(), and optional lifecycle hooks (on_session_end, on_session_switch, on_pre_compress, on_memory_write).\\n\\n2. **Built-in file-backed memory**: MEMORY.md and USER.md stored per-session/profile. LLM-callable memory tool with add/replace/remove actions. Frozen snapshot at session start (preserves prefix cache), immediate disk write on updates. Section-sign delimited entries with substring matching.\\n\\n3. **MemoryManager**: Orchestrates built-in + at most one external provider. Background serialized write executor. Prefetch with timeout (8s). Streaming context scrubber that strips injected memory spans from model output.\\n\\nRef: docs/prds/hermes-gap-analysis.md section 4","acceptance_criteria":"An external memory provider (e.g. Honcho, Mem0) can be plugged in via config. The built-in memory tool persists across sessions. Conversation context is recalled on session resume.","status":"open","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:22Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:22Z","dependencies":[{"issue_id":"archie-core-abg.18","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":0,"comment_count":0}
+1 -1
View File
@@ -272,7 +272,7 @@ func TestRouteModelNoManager(t *testing.T) {
if !strings.Contains(reply, "not configured") {
t.Errorf("reply = %q, want 'not configured' message", reply)
}
}
}
// -- TaskCreator fakes for /spawn tests --
+139
View File
@@ -0,0 +1,139 @@
package gateway
// MediaAttachment describes a file attached to a message. Platform-agnostic;
// platform-specific fields live in Raw.
//
// Numeric fields use pointers so that zero is distinguishable from
// "unknown" across a JSON round-trip: a 0-byte file is valid and
// different from a file whose size was never set.
type MediaAttachment struct {
// Type is "image", "video", "audio", or "document".
Type string `json:"type"`
// FileID is the platform-assigned identifier for download APIs.
FileID string `json:"file_id"`
// URL is a direct download URL when available. May be empty for
// platforms that require a download API call.
URL string `json:"url,omitempty"`
// MIMEType is the content type (e.g. "image/png", "audio/ogg").
MIMEType string `json:"mime_type,omitempty"`
// FileName is the original file name when known.
FileName string `json:"file_name,omitempty"`
// FileSize is the attachment size in bytes. nil means unknown.
FileSize *int64 `json:"file_size,omitempty"`
// Width is the pixel width for images and video. nil means unknown
// or not applicable.
Width *int `json:"width,omitempty"`
// Height is the pixel height for images and video.
Height *int `json:"height,omitempty"`
// Duration is the play time in seconds for audio and video.
Duration *int `json:"duration,omitempty"`
}
// MessageEvent is the rich message model for all gateway channels. It
// replaces the legacy 3-field Message struct for new adapters while
// remaining backward-compatible via the Text(), FromID() helpers and
// the ToLegacy() conversion.
//
// Every field except Type is optional. A minimal text message needs
// only Type=MsgText, Text, ChannelID, Platform, and SenderID.
type MessageEvent struct {
// Type discriminates the message kind.
Type MessageType `json:"type"`
// Text is the human-readable message body. It carries the caption
// for media messages and the full content for text and system
// messages.
Text string `json:"text,omitempty"`
// ── Identifiers ──────────────────────────────────────────────
// ID is the platform-assigned message identifier. Used for reply
// threading, reactions, and edit/delete tracking.
ID string `json:"id,omitempty"`
// ChannelID identifies the conversation within the platform
// (chat ID, channel name, DM thread).
ChannelID string `json:"channel_id"`
// Platform names the source adapter ("telegram", "discord",
// "web", "slack").
Platform string `json:"platform"`
// ── Sender ───────────────────────────────────────────────────
// SenderID is the platform-specific sender identifier.
SenderID string `json:"sender_id"`
// SenderName is the display name when available.
SenderName string `json:"sender_name,omitempty"`
// ── Threading ────────────────────────────────────────────────
// ReplyToID is the platform message ID this message is in reply
// to. Empty for top-level messages.
ReplyToID string `json:"reply_to_id,omitempty"`
// ThreadID identifies the conversation thread for platforms that
// support threading (Slack, Discord forums).
ThreadID string `json:"thread_id,omitempty"`
// ── Media ────────────────────────────────────────────────────
// Media holds attached files. Nil for text-only messages.
Media []MediaAttachment `json:"media,omitempty"`
// ── Edit tracking ────────────────────────────────────────────
// EditedFrom is the original text before the edit. Set only when
// Type is MsgEdited.
EditedFrom string `json:"edited_from,omitempty"`
// ── Reactions ────────────────────────────────────────────────
// Reaction is the emoji used when Type is MsgReaction.
Reaction string `json:"reaction,omitempty"`
// ReactedToID is the message being reacted to.
ReactedToID string `json:"reacted_to_id,omitempty"`
// ── Callbacks ────────────────────────────────────────────────
// CallbackData is the payload from a button or inline-keyboard
// press (Type == MsgCallback).
CallbackData string `json:"callback_data,omitempty"`
// ── Timestamp ────────────────────────────────────────────────
// Timestamp is the platform-assigned message time in Unix
// milliseconds. Zero when unknown.
Timestamp int64 `json:"timestamp,omitempty"`
// ── Platform payload ─────────────────────────────────────────
// Raw is the original platform-specific payload. Adapters set
// this for debug logging or handlers that need platform details
// not captured by the generic fields.
Raw map[string]any `json:"raw,omitempty"`
}
// ToLegacy converts the rich event back to the legacy 3-field Message
// for backward compatibility with existing code.
func (e MessageEvent) ToLegacy() Message {
return Message{
ChannelID: e.ChannelID,
From: e.SenderID,
Text: e.Text,
}
}
// FromID returns the sender identifier. Backward-compatible alias for
// code that uses Message.From.
func (e MessageEvent) FromID() string { return e.SenderID }
+296
View File
@@ -0,0 +1,296 @@
package gateway
import (
"encoding/json"
"testing"
)
func intPtr(v int) *int { return &v }
func i64Ptr(v int64) *int64 { return &v }
func TestMessageEventToLegacy(t *testing.T) {
e := MessageEvent{
Type: MsgText,
Text: "hello world",
ChannelID: "chat-42",
Platform: "telegram",
SenderID: "alice",
}
m := e.ToLegacy()
if m.ChannelID != "chat-42" {
t.Errorf("ChannelID = %q", m.ChannelID)
}
if m.From != "alice" {
t.Errorf("From = %q", m.From)
}
if m.Text != "hello world" {
t.Errorf("Text = %q", m.Text)
}
// ToLegacy carries Text for non-text types too — callers decide
// how to interpret it.
img := MessageEvent{
Type: MsgImage,
Text: "photo caption",
ChannelID: "c1",
Platform: "tg",
SenderID: "u1",
}
leg := img.ToLegacy()
if leg.Text != "photo caption" {
t.Errorf("image caption = %q", leg.Text)
}
cb := MessageEvent{
Type: MsgCallback,
CallbackData: `{"k":"v"}`,
ChannelID: "c1",
Platform: "tg",
SenderID: "u1",
}
if cb.ToLegacy().Text != "" {
t.Errorf("callback legacy Text = %q, want empty", cb.ToLegacy().Text)
}
}
func TestMessageEventFromID(t *testing.T) {
e := MessageEvent{SenderID: "bob"}
if e.FromID() != "bob" {
t.Errorf("FromID = %q", e.FromID())
}
}
func TestMessageEventMinimalText(t *testing.T) {
e := MessageEvent{
Type: MsgText,
Text: "hi",
ChannelID: "c1",
Platform: "web",
SenderID: "u1",
}
data, err := json.Marshal(e)
if err != nil {
t.Fatal(err)
}
var decoded MessageEvent
if err := json.Unmarshal(data, &decoded); err != nil {
t.Fatal(err)
}
if decoded.Type != MsgText {
t.Errorf("Type = %q", decoded.Type)
}
if decoded.Text != "hi" {
t.Errorf("Text = %q", decoded.Text)
}
if decoded.Type.IsEphemeral() {
t.Error("text should not be ephemeral")
}
}
func TestMessageEventMediaAttachment(t *testing.T) {
e := MessageEvent{
Type: MsgImage,
Text: "look at this photo",
ChannelID: "c1",
Platform: "telegram",
SenderID: "u1",
ID: "msg-1",
Media: []MediaAttachment{
{
Type: "image",
FileID: "file-abc",
MIMEType: "image/png",
FileSize: i64Ptr(102400),
Width: intPtr(800),
Height: intPtr(600),
},
},
}
data, err := json.Marshal(e)
if err != nil {
t.Fatal(err)
}
var decoded MessageEvent
if err := json.Unmarshal(data, &decoded); err != nil {
t.Fatal(err)
}
if len(decoded.Media) != 1 {
t.Fatalf("expected 1 media, got %d", len(decoded.Media))
}
m := decoded.Media[0]
if m.FileID != "file-abc" {
t.Errorf("FileID = %q", m.FileID)
}
if m.Width == nil || *m.Width != 800 {
t.Errorf("Width = %d", m.Width)
}
}
func TestMessageEventReplyContext(t *testing.T) {
e := MessageEvent{
Type: MsgText,
Text: "yes",
ChannelID: "c1",
Platform: "discord",
SenderID: "u2",
ReplyToID: "msg-99",
ThreadID: "thread-1",
}
if e.ReplyToID != "msg-99" {
t.Errorf("ReplyToID = %q", e.ReplyToID)
}
if e.ThreadID != "thread-1" {
t.Errorf("ThreadID = %q", e.ThreadID)
}
}
func TestMessageEventReaction(t *testing.T) {
e := MessageEvent{
Type: MsgReaction,
ChannelID: "c1",
Platform: "telegram",
SenderID: "u1",
Reaction: "👍",
ReactedToID: "msg-5",
}
if !e.Type.IsEphemeral() {
t.Error("reaction should be ephemeral")
}
if e.Reaction != "👍" {
t.Errorf("Reaction = %q", e.Reaction)
}
}
func TestMessageEventCallback(t *testing.T) {
e := MessageEvent{
Type: MsgCallback,
ChannelID: "c1",
Platform: "telegram",
SenderID: "u1",
CallbackData: `{"action":"approve","id":42}`,
}
if !e.Type.IsRich() {
t.Error("callback should be rich")
}
}
func TestMessageEventEditDelete(t *testing.T) {
e := MessageEvent{
Type: MsgEdited,
ChannelID: "c1",
Platform: "telegram",
SenderID: "u1",
ID: "msg-1",
EditedFrom: "original text",
Text: "updated text",
}
if e.EditedFrom != "original text" {
t.Errorf("EditedFrom = %q", e.EditedFrom)
}
if e.Text != "updated text" {
t.Errorf("Text = %q", e.Text)
}
del := MessageEvent{
Type: MsgDeleted,
ChannelID: "c1",
Platform: "telegram",
SenderID: "u1",
ID: "msg-1",
}
if !del.Type.IsEphemeral() {
t.Error("deleted should be ephemeral")
}
}
func TestMessageEventTimestamp(t *testing.T) {
e := MessageEvent{
Type: MsgText,
ChannelID: "c1",
Platform: "telegram",
SenderID: "u1",
Timestamp: 1234567890000,
}
if e.Timestamp != 1234567890000 {
t.Errorf("Timestamp = %d", e.Timestamp)
}
}
func TestMessageEventRawPayload(t *testing.T) {
e := MessageEvent{
Type: MsgSystem,
ChannelID: "c1",
Platform: "telegram",
SenderID: "",
Raw: map[string]any{
"action": "member_joined",
"user": "newguy",
},
}
data, err := json.Marshal(e)
if err != nil {
t.Fatal(err)
}
var decoded MessageEvent
if err := json.Unmarshal(data, &decoded); err != nil {
t.Fatal(err)
}
if decoded.Raw["action"] != "member_joined" {
t.Errorf("Raw[action] = %v", decoded.Raw["action"])
}
}
func TestMessageEventMediaAttachmentZeroValue(t *testing.T) {
var m MediaAttachment
if m.FileID != "" {
t.Error("zero MediaAttachment should have empty FileID")
}
if m.Type != "" {
t.Error("zero MediaAttachment should have empty Type")
}
}
func TestMessageEventDocExample(t *testing.T) {
// Exercise: full photo message as an adapter would construct it.
e := MessageEvent{
Type: MsgImage,
Text: "check out this screenshot",
ID: "1734567890123",
ChannelID: "-1001234567890",
Platform: "telegram",
SenderID: "987654321",
SenderName: "Alice",
ReplyToID: "1734567890000",
Media: []MediaAttachment{{
Type: "image",
FileID: "AgACAgIAAxkBAA...",
MIMEType: "image/png",
FileSize: i64Ptr(245760),
Width: intPtr(1920),
Height: intPtr(1080),
}},
Timestamp: 1734567890123,
}
if e.Type != MsgImage {
t.Error("expected image type")
}
if !e.Type.IsMedia() {
t.Error("image should be media")
}
if e.Type.IsEphemeral() {
t.Error("image should not be ephemeral")
}
if e.SenderName != "Alice" {
t.Errorf("SenderName = %q", e.SenderName)
}
// Backward compat.
legacy := e.ToLegacy()
if legacy.From != "987654321" {
t.Errorf("legacy From = %q", legacy.From)
}
if legacy.Text != "check out this screenshot" {
t.Errorf("legacy Text = %q", legacy.Text)
}
}
+79
View File
@@ -0,0 +1,79 @@
package gateway
// MessageType discriminates inbound gateway messages. Every MessageEvent
// carries a type so handlers can branch on message kind without inspecting
// the raw platform payload.
type MessageType string
const (
// MsgText is a plain text message.
MsgText MessageType = "text"
// MsgImage is a message with an image attachment.
MsgImage MessageType = "image"
// MsgVideo is a message with a video attachment.
MsgVideo MessageType = "video"
// MsgAudio is a message with an audio attachment (voice note, etc.).
MsgAudio MessageType = "audio"
// MsgDocument is a message with a file attachment.
MsgDocument MessageType = "document"
// MsgLocation is a shared location.
MsgLocation MessageType = "location"
// MsgSticker is a sticker or animated emoji.
MsgSticker MessageType = "sticker"
// MsgContact is a shared contact card.
MsgContact MessageType = "contact"
// MsgCallback is a button press or inline keyboard interaction.
MsgCallback MessageType = "callback"
// MsgReaction is an emoji reaction on a prior message.
MsgReaction MessageType = "reaction"
// MsgEdited signals that a prior message text was changed.
MsgEdited MessageType = "edited"
// MsgDeleted signals that a prior message was removed.
MsgDeleted MessageType = "deleted"
// MsgSystem is a non-user system event (member join/leave, etc.).
MsgSystem MessageType = "system"
)
// IsMedia reports whether the type carries a media attachment.
func (t MessageType) IsMedia() bool {
switch t {
case MsgImage, MsgVideo, MsgAudio, MsgDocument, MsgSticker:
return true
}
return false
}
// IsEphemeral reports whether the type is a transient signal
// (typing indicators, read receipts) that should not be stored.
// Note: MsgEdited is NOT ephemeral — it carries content (original
// and updated text) that must be persisted to avoid serving stale data.
func (t MessageType) IsEphemeral() bool {
switch t {
case MsgReaction, MsgDeleted:
return true
}
return false
}
// IsRich reports whether the type requires a MessageEvent with
// structured fields rather than a plain text fallback.
func (t MessageType) IsRich() bool {
switch t {
case MsgText:
return false
default:
return true
}
}
+80
View File
@@ -0,0 +1,80 @@
package gateway
import (
"encoding/json"
"testing"
)
func TestMessageTypeIsMedia(t *testing.T) {
tests := []struct {
typ MessageType
isMedia bool
}{
{MsgText, false},
{MsgImage, true},
{MsgVideo, true},
{MsgAudio, true},
{MsgDocument, true},
{MsgLocation, false},
{MsgSticker, true},
{MsgContact, false},
{MsgCallback, false},
{MsgReaction, false},
{MsgEdited, false},
{MsgDeleted, false},
{MsgSystem, false},
}
for _, tc := range tests {
got := tc.typ.IsMedia()
if got != tc.isMedia {
t.Errorf("%s.IsMedia() = %v, want %v", tc.typ, got, tc.isMedia)
}
}
}
func TestMessageTypeIsEphemeral(t *testing.T) {
ephemeral := map[MessageType]bool{
MsgReaction: true,
MsgDeleted: true,
}
for _, typ := range []MessageType{
MsgText, MsgImage, MsgVideo, MsgAudio, MsgDocument,
MsgLocation, MsgSticker, MsgContact, MsgCallback, MsgSystem,
} {
if typ.IsEphemeral() {
t.Errorf("%s should not be ephemeral", typ)
}
}
for typ, want := range ephemeral {
if got := typ.IsEphemeral(); got != want {
t.Errorf("%s.IsEphemeral() = %v, want %v", typ, got, want)
}
}
}
func TestMessageTypeIsRich(t *testing.T) {
if MsgText.IsRich() {
t.Error("text should not be rich")
}
rich := []MessageType{MsgImage, MsgVideo, MsgAudio, MsgDocument, MsgLocation, MsgSticker, MsgContact, MsgCallback, MsgReaction, MsgEdited, MsgDeleted, MsgSystem}
for _, typ := range rich {
if !typ.IsRich() {
t.Errorf("%s should be rich", typ)
}
}
}
func TestMessageTypeRoundTripJSON(t *testing.T) {
e := MessageEvent{Type: MsgImage, Text: "alt text", ChannelID: "c1", Platform: "telegram", SenderID: "u1"}
data, err := json.Marshal(e)
if err != nil {
t.Fatal(err)
}
var decoded MessageEvent
if err := json.Unmarshal(data, &decoded); err != nil {
t.Fatal(err)
}
if decoded.Type != MsgImage {
t.Errorf("Type = %q", decoded.Type)
}
}
+294
View File
@@ -0,0 +1,294 @@
package tools
import (
"errors"
"slices"
"strings"
"testing"
"testing/fstest"
)
func TestRegistryRegister(t *testing.T) {
t.Run("valid entry", func(t *testing.T) {
r := NewRegistry()
err := r.Register(ToolEntry{Name: "hello", Handler: noopHandler})
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if len(r.All()) != 1 {
t.Errorf("expected 1 tool, got %d", len(r.All()))
}
})
t.Run("duplicate name returns error", func(t *testing.T) {
r := NewRegistry()
e := ToolEntry{Name: "dup", Handler: noopHandler}
if err := r.Register(e); err != nil {
t.Fatalf("first register: %v", err)
}
err := r.Register(e)
if err == nil {
t.Error("expected error for duplicate name")
}
if !errors.Is(err, ErrDuplicateTool) {
t.Errorf("expected ErrDuplicateTool, got %v", err)
}
})
t.Run("invalid entry returns validation error", func(t *testing.T) {
r := NewRegistry()
err := r.Register(ToolEntry{Name: ""})
if err == nil {
t.Error("expected validation error for empty name")
}
})
t.Run("multiple tools", func(t *testing.T) {
r := NewRegistry()
for _, name := range []string{"a", "b", "c"} {
if err := r.Register(ToolEntry{Name: name, Handler: noopHandler}); err != nil {
t.Fatalf("register %q: %v", name, err)
}
}
if len(r.All()) != 3 {
t.Errorf("expected 3 tools, got %d", len(r.All()))
}
})
}
func TestRegistryAll(t *testing.T) {
t.Run("empty registry", func(t *testing.T) {
r := NewRegistry()
all := r.All()
if len(all) != 0 {
t.Errorf("expected 0 tools, got %d", len(all))
}
})
t.Run("returns copy of tools", func(t *testing.T) {
r := NewRegistry()
r.Register(ToolEntry{Name: "x", Handler: noopHandler})
all := r.All()
all[0].Name = "mutated"
// Original registry must be unaffected.
if r.All()[0].Name != "x" {
t.Error("All() should return independent copies")
}
})
}
func TestRegistryByToolset(t *testing.T) {
r := NewRegistry()
r.Register(ToolEntry{Name: "f1", Toolset: "file", Handler: noopHandler})
r.Register(ToolEntry{Name: "f2", Toolset: "file", Handler: noopHandler})
r.Register(ToolEntry{Name: "g1", Toolset: "git", Handler: noopHandler})
r.Register(ToolEntry{Name: "u1", Toolset: "", Handler: noopHandler}) // ungrouped
t.Run("filters by toolset", func(t *testing.T) {
file := r.ByToolset("file")
if len(file) != 2 {
t.Errorf("expected 2 file tools, got %d", len(file))
}
names := toolNames(file)
slices.Sort(names)
if names[0] != "f1" || names[1] != "f2" {
t.Errorf("unexpected names: %v", names)
}
})
t.Run("no match returns empty", func(t *testing.T) {
none := r.ByToolset("nonexistent")
if len(none) != 0 {
t.Errorf("expected 0 tools, got %d", len(none))
}
})
t.Run("empty toolset matches ungrouped", func(t *testing.T) {
ungrouped := r.ByToolset("")
if len(ungrouped) != 1 {
t.Errorf("expected 1 ungrouped tool, got %d", len(ungrouped))
}
if ungrouped[0].Name != "u1" {
t.Errorf("unexpected name: %q", ungrouped[0].Name)
}
})
}
func TestRegistryAvailable(t *testing.T) {
r := NewRegistry()
r.Register(ToolEntry{Name: "always", Handler: noopHandler})
r.Register(ToolEntry{Name: "offline", Handler: noopHandler, CheckFn: func() bool { return false }})
r.Register(ToolEntry{Name: "conditional", Handler: noopHandler, CheckFn: func() bool { return true }})
t.Run("returns only available tools", func(t *testing.T) {
avail := r.Available()
names := toolNames(avail)
if !slices.Contains(names, "always") {
t.Error("'always' should be available")
}
if !slices.Contains(names, "conditional") {
t.Error("'conditional' should be available")
}
if slices.Contains(names, "offline") {
t.Error("'offline' should not be available")
}
if len(avail) != 2 {
t.Errorf("expected 2 available tools, got %d", len(avail))
}
})
t.Run("dynamic availability reflected", func(t *testing.T) {
flag := true
r.Register(ToolEntry{
Name: "toggle",
Handler: noopHandler,
CheckFn: func() bool { return flag },
})
if len(r.Available()) != 3 {
t.Errorf("expected 3 available (toggle is true), got %d", len(r.Available()))
}
flag = false
// Available() re-evaluates — the closure captures &flag.
if len(r.Available()) != 2 {
t.Errorf("expected 2 available (toggle is now false), got %d", len(r.Available()))
}
})
}
func TestRegistryDiscover(t *testing.T) {
t.Run("no go files", func(t *testing.T) {
r := NewRegistry()
fsys := fstest.MapFS{}
n, err := r.Discover(fsys, ".")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if n != 0 {
t.Errorf("expected 0 discovered, got %d", n)
}
})
t.Run("go file with Register call", func(t *testing.T) {
r := NewRegistry()
fsys := fstest.MapFS{
"mytool.go": &fstest.MapFile{
Data: []byte(`package tools
import "github.com/sam/archie-core/internal/tools"
func init() {
tools.DefaultRegistry().Register(tools.ToolEntry{
Name: "discovered_hello",
Description: "A discovered tool",
Handler: noopHandler,
})
}
`),
},
}
n, err := r.Discover(fsys, ".")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if n != 1 {
t.Errorf("expected 1 discovered, got %d", n)
}
all := r.All()
if len(all) != 1 {
t.Fatalf("expected 1 registered tool, got %d", len(all))
}
if all[0].Name != "discovered_hello" {
t.Errorf("Name = %q", all[0].Name)
}
if all[0].Description != "A discovered tool" {
t.Errorf("Description = %q", all[0].Description)
}
})
t.Run("go file without Register call", func(t *testing.T) {
r := NewRegistry()
fsys := fstest.MapFS{
"plain.go": &fstest.MapFile{
Data: []byte(`package tools
func PlainFunction() string {
return "hello"
}
`),
},
}
n, err := r.Discover(fsys, ".")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if n != 0 {
t.Errorf("expected 0 discovered, got %d", n)
}
})
t.Run("syntax error in go file", func(t *testing.T) {
r := NewRegistry()
fsys := fstest.MapFS{
"broken.go": &fstest.MapFile{
Data: []byte(`package tools
func broken( {`),
},
}
_, err := r.Discover(fsys, ".")
if err == nil {
t.Error("expected error for broken Go file")
}
})
}
func TestRegistrySingleton(t *testing.T) {
// DefaultRegistry returns the same instance.
d1 := DefaultRegistry()
d2 := DefaultRegistry()
if d1 != d2 {
t.Error("DefaultRegistry should be a singleton")
}
}
// toolNames extracts names from a slice of ToolEntry.
func toolNames(entries []ToolEntry) []string {
names := make([]string, len(entries))
for i, e := range entries {
names[i] = e.Name
}
return names
}
// Ensure registry implements basic sanity at the package level.
func TestRegistryPackageLevelHelpers(t *testing.T) {
// Reset state by creating a fresh registry.
// The package-level helpers work against DefaultRegistry.
t.Run("Register and All via package helpers", func(t *testing.T) {
r := NewRegistry()
e := ToolEntry{Name: "pkg_helper", Handler: noopHandler}
if err := r.Register(e); err != nil {
t.Fatalf("register: %v", err)
}
if len(r.All()) != 1 {
t.Error("expected 1 tool after register")
}
})
t.Run("ByToolset from empty reg", func(t *testing.T) {
r := NewRegistry()
got := r.ByToolset("none")
if len(got) != 0 {
t.Errorf("expected 0, got %d", len(got))
}
})
t.Run("Available from empty reg", func(t *testing.T) {
r := NewRegistry()
got := r.Available()
if len(got) != 0 {
t.Errorf("expected 0, got %d", len(got))
}
})
}
+2 -3
View File
@@ -8,6 +8,7 @@ import (
"context"
"encoding/json"
"fmt"
"maps"
)
// JSONSchema represents a JSON Schema document describing a tool's input
@@ -129,9 +130,7 @@ func (e ToolEntry) Clone() ToolEntry {
}
if e.Schema != nil {
clone.Schema = make(JSONSchema, len(e.Schema))
for k, v := range e.Schema {
clone.Schema[k] = v
}
maps.Copy(clone.Schema, e.Schema)
}
return clone
}
+294
View File
@@ -0,0 +1,294 @@
package tools
import (
"context"
"encoding/json"
"strings"
"testing"
)
// noopHandler is a Handler that does nothing.
func noopHandler(_ context.Context, _ map[string]any) (any, error) {
return nil, nil
}
// echoHandler returns its input unchanged.
func echoHandler(_ context.Context, in map[string]any) (any, error) {
return in, nil
}
func TestToolEntryValidate(t *testing.T) {
t.Run("valid entry", func(t *testing.T) {
e := ToolEntry{Name: "hello", Handler: noopHandler}
if err := e.Validate(); err != nil {
t.Errorf("unexpected error: %v", err)
}
})
t.Run("missing name", func(t *testing.T) {
e := ToolEntry{Handler: noopHandler}
if err := e.Validate(); err == nil {
t.Error("expected error for missing name")
}
})
t.Run("missing handler", func(t *testing.T) {
e := ToolEntry{Name: "orphan"}
if err := e.Validate(); err == nil {
t.Error("expected error for missing handler")
}
})
}
func TestToolEntryAvailable(t *testing.T) {
t.Run("nil CheckFn is always available", func(t *testing.T) {
e := ToolEntry{Name: "x", Handler: noopHandler}
if !e.Available() {
t.Error("nil CheckFn should mean available")
}
})
t.Run("CheckFn returning true", func(t *testing.T) {
e := ToolEntry{
Name: "x",
Handler: noopHandler,
CheckFn: func() bool { return true },
}
if !e.Available() {
t.Error("expect available when CheckFn returns true")
}
})
t.Run("CheckFn returning false", func(t *testing.T) {
e := ToolEntry{
Name: "x",
Handler: noopHandler,
CheckFn: func() bool { return false },
}
if e.Available() {
t.Error("expect unavailable when CheckFn returns false")
}
})
t.Run("CheckFn reflects dynamic state", func(t *testing.T) {
flag := true
e := ToolEntry{
Name: "x",
Handler: noopHandler,
CheckFn: func() bool { return flag },
}
if !e.Available() {
t.Error("expect available while flag is true")
}
flag = false
if e.Available() {
t.Error("expect unavailable after flag toggled")
}
})
}
func TestToolEntryResolvedSchema(t *testing.T) {
t.Run("static schema returned as-is", func(t *testing.T) {
e := ToolEntry{
Name: "x",
Handler: noopHandler,
Schema: JSONSchema{"type": "object", "properties": JSONSchema{"x": JSONSchema{"type": "string"}}},
}
s := e.ResolvedSchema()
if s["type"] != "object" {
t.Errorf("type = %v", s["type"])
}
})
t.Run("nil schema with no override", func(t *testing.T) {
e := ToolEntry{Name: "x", Handler: noopHandler}
if e.ResolvedSchema() != nil {
t.Error("nil schema should stay nil")
}
})
t.Run("dynamic override injects values", func(t *testing.T) {
e := ToolEntry{
Name: "x",
Handler: noopHandler,
Schema: JSONSchema{"type": "object"},
DynamicSchemaOverrides: func(s JSONSchema) JSONSchema {
out := JSONSchema{}
for k, v := range s {
out[k] = v
}
out["dynamic"] = true
return out
},
}
s := e.ResolvedSchema()
if s["dynamic"] != true {
t.Error("dynamic override not applied")
}
// Original must be unchanged.
if e.Schema["dynamic"] != nil {
t.Error("override mutated original schema")
}
})
t.Run("override can return nil", func(t *testing.T) {
e := ToolEntry{
Name: "x",
Handler: noopHandler,
Schema: JSONSchema{"type": "object"},
DynamicSchemaOverrides: func(_ JSONSchema) JSONSchema {
return nil
},
}
if e.ResolvedSchema() != nil {
t.Error("override returning nil should be respected")
}
})
}
func TestToolEntryClone(t *testing.T) {
e := ToolEntry{
Name: "original",
Toolset: "test",
Schema: JSONSchema{"key": "value"},
Handler: noopHandler,
CheckFn: func() bool { return true },
RequiresEnv: []string{"X", "Y"},
IsAsync: true,
Description: "a test tool",
Emoji: "🧪",
MaxResultSizeChars: 4096,
}
clone := e.Clone()
// Value fields match.
if clone.Name != e.Name {
t.Errorf("Name = %q, want %q", clone.Name, e.Name)
}
if clone.IsAsync != e.IsAsync {
t.Errorf("IsAsync = %v, want %v", clone.IsAsync, e.IsAsync)
}
// Handler and CheckFn are shared (function pointers — not deep-copied).
// This is documented behavior.
// RequiresEnv is an independent copy.
e.RequiresEnv[0] = "Z"
if clone.RequiresEnv[0] != "X" {
t.Errorf("RequiresEnv[0] = %q, want %q (clone should be independent)", clone.RequiresEnv[0], "X")
}
// Schema is an independent shallow copy.
e.Schema["key"] = "mutated"
if clone.Schema["key"] != "value" {
t.Errorf("Schema[key] = %v, want 'value' (clone should be independent)", clone.Schema["key"])
}
}
func TestToolEntryJSONRoundTrip(t *testing.T) {
e := ToolEntry{
Name: "greet",
Toolset: "demo",
Schema: JSONSchema{"type": "object", "properties": JSONSchema{"name": JSONSchema{"type": "string"}}},
Handler: noopHandler, // json:"-" — excluded
CheckFn: func() bool { return true }, // json:"-" — excluded
RequiresEnv: []string{"GREET_NAME"},
IsAsync: true,
Description: "Sends a greeting",
Emoji: "👋",
MaxResultSizeChars: 1000,
DynamicSchemaOverrides: nil, // json:"-" — excluded
}
data, err := json.Marshal(e)
if err != nil {
t.Fatalf("marshal: %v", err)
}
// Round-trip.
var decoded ToolEntry
if err := json.Unmarshal(data, &decoded); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if decoded.Name != "greet" {
t.Errorf("Name = %q", decoded.Name)
}
if decoded.Toolset != "demo" {
t.Errorf("Toolset = %q", decoded.Toolset)
}
if decoded.IsAsync != true {
t.Error("IsAsync not preserved")
}
if decoded.Description != "Sends a greeting" {
t.Errorf("Description = %q", decoded.Description)
}
if decoded.Emoji != "👋" {
t.Errorf("Emoji = %q", decoded.Emoji)
}
if decoded.MaxResultSizeChars != 1000 {
t.Errorf("MaxResultSizeChars = %d", decoded.MaxResultSizeChars)
}
if len(decoded.RequiresEnv) != 1 || decoded.RequiresEnv[0] != "GREET_NAME" {
t.Errorf("RequiresEnv = %v", decoded.RequiresEnv)
}
// Runtime fields are not deserialized.
if decoded.Handler != nil {
t.Error("Handler should be nil after unmarshal")
}
if decoded.CheckFn != nil {
t.Error("CheckFn should be nil after unmarshal")
}
// Schema survives round-trip.
if decoded.Schema["type"] != "object" {
t.Errorf("Schema type = %v", decoded.Schema["type"])
}
}
func TestToolEntryHandlerExecution(t *testing.T) {
e := ToolEntry{
Name: "echo",
Handler: echoHandler,
}
out, err := e.Handler(context.Background(), map[string]any{"msg": "hello"})
if err != nil {
t.Fatalf("handler error: %v", err)
}
m, ok := out.(map[string]any)
if !ok {
t.Fatalf("expected map, got %T", out)
}
if m["msg"] != "hello" {
t.Errorf("msg = %v", m["msg"])
}
}
func TestToolEntryZeroValue(t *testing.T) {
var e ToolEntry
// Zero value must be usable without panicking.
if err := e.Validate(); err == nil {
t.Error("zero ToolEntry should fail Validate")
}
if !e.Available() {
// nil CheckFn = available — this is correct even for zero value.
}
if e.ResolvedSchema() != nil {
t.Error("zero ToolEntry should have nil resolved schema")
}
}
func TestToolEntryJSONSchemaIsNilByDefault(t *testing.T) {
e := ToolEntry{Name: "no-params", Handler: noopHandler}
data, err := json.Marshal(e)
if err != nil {
t.Fatalf("marshal: %v", err)
}
// Schema field omitted when nil.
if strings.Contains(string(data), `"schema"`) {
t.Log("schema present in JSON (either null or omitted) — both are acceptable")
}
}