htm-cli 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +11 -0
  3. data/COMMITS.md +196 -0
  4. data/LICENSE.txt +21 -0
  5. data/README.md +99 -0
  6. data/Rakefile +23 -0
  7. data/bin/htm +18 -0
  8. data/lib/htm/admin/database_commands.rb +489 -0
  9. data/lib/htm/admin/enrich_commands.rb +275 -0
  10. data/lib/htm/admin/entity_commands.rb +203 -0
  11. data/lib/htm/admin/entity_graph.rb +313 -0
  12. data/lib/htm/admin/file_commands.rb +323 -0
  13. data/lib/htm/admin/memory_commands/edit.rb +175 -0
  14. data/lib/htm/admin/memory_commands/entities.rb +189 -0
  15. data/lib/htm/admin/memory_commands/entity_lines.rb +111 -0
  16. data/lib/htm/admin/memory_commands/search.rb +205 -0
  17. data/lib/htm/admin/memory_commands/tag_search.rb +98 -0
  18. data/lib/htm/admin/memory_commands/text.rb +166 -0
  19. data/lib/htm/admin/memory_commands/working_memory.rb +71 -0
  20. data/lib/htm/admin/memory_commands.rb +196 -0
  21. data/lib/htm/admin/tag_commands.rb +352 -0
  22. data/lib/htm/admin/tag_graph.rb +345 -0
  23. data/lib/htm/admin/templates/tag_graph.html +319 -0
  24. data/lib/htm/admin.rb +266 -0
  25. data/lib/htm/cli/config_file.rb +73 -0
  26. data/lib/htm/cli/db.rb +80 -0
  27. data/lib/htm/cli/enrich.rb +52 -0
  28. data/lib/htm/cli/entities.rb +268 -0
  29. data/lib/htm/cli/environment.rb +74 -0
  30. data/lib/htm/cli/error_suggestion.rb +97 -0
  31. data/lib/htm/cli/files.rb +41 -0
  32. data/lib/htm/cli/group.rb +46 -0
  33. data/lib/htm/cli/memory.rb +410 -0
  34. data/lib/htm/cli/memory_command.rb +72 -0
  35. data/lib/htm/cli/robots.rb +82 -0
  36. data/lib/htm/cli/support.rb +46 -0
  37. data/lib/htm/cli/tags.rb +103 -0
  38. data/lib/htm/cli/version.rb +11 -0
  39. data/lib/htm/cli/working_memory.rb +41 -0
  40. data/lib/htm/cli.rb +96 -0
  41. data/lib/htm/mcp/entity_tools.rb +334 -0
  42. data/lib/htm/mcp/file_tools.rb +196 -0
  43. data/lib/htm/mcp/group_tools.rb +466 -0
  44. data/lib/htm/mcp/node_tools.rb +358 -0
  45. data/lib/htm/mcp/resources.rb +192 -0
  46. data/lib/htm/mcp/robot_team_tools.rb +129 -0
  47. data/lib/htm/mcp/server.rb +111 -0
  48. data/lib/htm/mcp/tag_tools.rb +130 -0
  49. data/lib/htm/mcp/tool.rb +40 -0
  50. data/lib/htm/mcp/tool_support.rb +108 -0
  51. data/lib/htm/mcp/tools.rb +461 -0
  52. metadata +181 -0
@@ -0,0 +1,358 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'tool'
4
+
5
+ class HTM
6
+ module MCP
7
+ # Tool: Get one memory node in full
8
+ class GetNodeTool < Tool
9
+ read_only!
10
+ description "Get a memory node by ID: content, tags, metadata, event time (occurred_at, validity), status " \
11
+ "(current, superseded, merged, archived, deleted), links to other nodes, timestamps, access count, " \
12
+ "embedding status, proposition flag and source file. Finds soft-deleted nodes too."
13
+
14
+ arguments do
15
+ required(:node_id).filled(:integer).description("The ID of the node")
16
+ end
17
+
18
+ def call(node_id:)
19
+ log_info "GetNodeTool called: node_id=#{node_id}"
20
+
21
+ guarded do
22
+ node = find_node!(node_id)
23
+ source_id = node.source_id
24
+ source = source_id && HTM::Models::FileSource[source_id]
25
+
26
+ success(node: { **node_detail(node), source_file: source&.file_path })
27
+ end
28
+ end
29
+ end
30
+
31
+ # Tool: Forget every node containing some text
32
+ class ForgetContentTool < Tool
33
+ destructive!
34
+ description "Forget every memory whose content contains the given text (case-insensitive). " \
35
+ "Soft-deletes by default; permanent: true requires confirm: 'confirmed'."
36
+
37
+ arguments do
38
+ required(:content).filled(:string).description("Text to look for in memory content")
39
+ optional(:permanent).filled(:bool).description("Delete permanently instead of soft-deleting (default: false)")
40
+ optional(:confirm).filled(:string).description("Must be 'confirmed' when permanent is true")
41
+ end
42
+
43
+ def call(content:, permanent: false, confirm: nil)
44
+ log_info "ForgetContentTool called: content=#{content.inspect}, permanent=#{permanent}"
45
+
46
+ guarded do
47
+ node_ids = session_htm.forget_content(content, soft: !permanent, confirm: htm_confirmation(confirm))
48
+
49
+ success(content:, permanent:, count: node_ids.length, node_ids:)
50
+ end
51
+ end
52
+ end
53
+
54
+ # Tool: Permanently delete old soft-deleted nodes
55
+ class PurgeDeletedTool < Tool
56
+ destructive!
57
+ description "Permanently delete memories that were soft-deleted before a cutoff. Requires confirm: 'confirmed'."
58
+
59
+ arguments do
60
+ optional(:older_than_days).filled(:integer).description("Purge nodes soft-deleted more than this many days ago (default: 30)")
61
+ optional(:older_than).filled(:string).description("ISO8601 cutoff time; overrides older_than_days")
62
+ required(:confirm).filled(:string).description("Must be 'confirmed'")
63
+ end
64
+
65
+ def call(confirm:, older_than_days: 30, older_than: nil)
66
+ log_info "PurgeDeletedTool called: older_than=#{older_than.inspect}, older_than_days=#{older_than_days}"
67
+
68
+ guarded do
69
+ cutoff = older_than ? Time.parse(older_than) : Time.now - (older_than_days * 86_400)
70
+ count = session_htm.purge_deleted(older_than: cutoff, confirm: htm_confirmation(confirm))
71
+
72
+ success(older_than: cutoff.iso8601, purged: count)
73
+ end
74
+ end
75
+ end
76
+
77
+ # Tool: List soft-deleted nodes
78
+ class ListDeletedTool < Tool
79
+ read_only!
80
+ description "List soft-deleted memories (newest deletions first) so they can be restored or purged"
81
+
82
+ arguments do
83
+ optional(:limit).filled(:integer).description("Maximum number of nodes (default: 20)")
84
+ end
85
+
86
+ def call(limit: 20)
87
+ log_info "ListDeletedTool called: limit=#{limit}"
88
+
89
+ guarded do
90
+ nodes = deleted_entries(limit:)
91
+
92
+ success(count: nodes.length, nodes:)
93
+ end
94
+ end
95
+ end
96
+
97
+ # Tool: Clear the robot's working memory
98
+ class ClearWorkingMemoryTool < Tool
99
+ description "Clear the current robot's working memory. The memories stay in long-term memory."
100
+
101
+ arguments do
102
+ end
103
+
104
+ def call
105
+ htm = session_htm
106
+ log_info "ClearWorkingMemoryTool called for robot=#{htm.robot_name}"
107
+
108
+ guarded { success(**robot_identity(htm), cleared: htm.clear_working_memory) }
109
+ end
110
+ end
111
+
112
+ # Tool: Assemble working memory into an LLM context string
113
+ class AssembleContextTool < Tool
114
+ read_only!
115
+ description "Assemble the current robot's working memory into a single context string for an LLM prompt"
116
+
117
+ STRATEGIES = %w[recent frequent balanced].freeze
118
+
119
+ arguments do
120
+ optional(:strategy).filled(:string).description(
121
+ "'recent' (most recently used first), 'frequent' (most used first) or 'balanced' (frequency x recency, default)"
122
+ )
123
+ optional(:max_tokens).filled(:integer).description("Token budget for the context (default: the working memory size)")
124
+ end
125
+
126
+ def call(strategy: 'balanced', max_tokens: nil)
127
+ log_info "AssembleContextTool called: strategy=#{strategy}, max_tokens=#{max_tokens.inspect}"
128
+
129
+ guarded do
130
+ raise ArgumentError, "strategy must be one of: #{STRATEGIES.join(', ')}" unless STRATEGIES.include?(strategy)
131
+
132
+ working_memory = session_htm.working_memory
133
+ options = { strategy: strategy.to_sym, max_tokens: }.compact
134
+ context = working_memory.assemble_context(**options)
135
+
136
+ success(strategy:, node_count: working_memory.node_count, token_count: HTM.count_tokens(context), context:)
137
+ end
138
+ end
139
+ end
140
+
141
+ # Tool: Add tags to a node
142
+ class TagNodeTool < Tool
143
+ description "Add tags to a memory node. Parent tags are created too (a:b:c also adds a and a:b)."
144
+
145
+ arguments do
146
+ required(:node_id).filled(:integer).description("The ID of the node")
147
+ required(:tags).array(:string).description("Hierarchical tags to add (e.g., ['database:postgresql'])")
148
+ end
149
+
150
+ def call(node_id:, tags:)
151
+ log_info "TagNodeTool called: node_id=#{node_id}, tags=#{tags.inspect}"
152
+
153
+ guarded do
154
+ HTM::InputValidator.tags!(tags)
155
+ node = find_node!(node_id)
156
+ node.add_tags(tags)
157
+ session_htm.long_term_memory.clear_cache!
158
+
159
+ success(node_id:, tags: node.tag_names.sort)
160
+ end
161
+ end
162
+ end
163
+
164
+ # Tool: Remove a tag from a node
165
+ class UntagNodeTool < Tool
166
+ description "Remove one tag from a memory node (its parent and child tags are left alone)"
167
+
168
+ arguments do
169
+ required(:node_id).filled(:integer).description("The ID of the node")
170
+ required(:tag).filled(:string).description("The exact tag name to remove")
171
+ end
172
+
173
+ def call(node_id:, tag:)
174
+ log_info "UntagNodeTool called: node_id=#{node_id}, tag=#{tag.inspect}"
175
+
176
+ guarded do
177
+ node = find_node!(node_id)
178
+ tags = node.tag_names
179
+ next failure("Node #{node_id} is not tagged '#{tag}'") unless tags.include?(tag)
180
+
181
+ node.remove_tag(tag)
182
+ session_htm.long_term_memory.clear_cache!
183
+
184
+ success(node_id:, removed: tag, tags: (tags - [tag]).sort)
185
+ end
186
+ end
187
+ end
188
+
189
+ # Tool: Nodes related through the relationship graph
190
+ class RelatedNodesTool < Tool
191
+ read_only!
192
+ description "Find memories related to a node through the relationship graph " \
193
+ "(edges weighted by embedding similarity or shared entities), strongest first"
194
+
195
+ arguments do
196
+ required(:node_id).filled(:integer).description("The ID of the node")
197
+ optional(:limit).filled(:integer).description("Maximum number of related nodes (default: 10)")
198
+ optional(:min_weight).filled(:float).description("Minimum edge weight 0.0-1.0 (default: 0.0)")
199
+ end
200
+
201
+ def call(node_id:, limit: 10, min_weight: 0.0)
202
+ log_info "RelatedNodesTool called: node_id=#{node_id}, limit=#{limit}, min_weight=#{min_weight}"
203
+
204
+ guarded do
205
+ find_node!(node_id)
206
+ related = related_entries(node_id, limit:, min_weight:)
207
+
208
+ success(node_id:, count: related.length, related:)
209
+ end
210
+ end
211
+ end
212
+
213
+ # Tool: How a memory changed over time
214
+ class TimelineTool < Tool
215
+ read_only!
216
+ description "Show the history of a memory: every state it went through (including superseded, merged and " \
217
+ "archived ones that recall leaves out) and each change between them (removed, restored, changed) " \
218
+ "with its reason, oldest first. Give a node_id, a query whose top matches seed the histories, or an " \
219
+ "entity for the one history of everything memory says about it."
220
+
221
+ arguments do
222
+ optional(:query).filled(:string).description("What the memory is about (searched with strategy)")
223
+ optional(:node_id).filled(:integer).description("Any node in the history, retired or not")
224
+ optional(:entity).filled(:string).description(
225
+ "An entity (name, alias or id) instead of a query or node_id: the history of the memories mentioning it"
226
+ )
227
+ optional(:entity_type).filled(:string).description("The entity's type, for a name that entities of several types share")
228
+ optional(:strategy).filled(:string).description("Search strategy for query: 'vector', 'fulltext' (default) or 'hybrid'")
229
+ optional(:limit).filled(:integer).description("Matches to seed histories from (default: 5)")
230
+ optional(:max_depth).filled(:integer).description("Links to follow at most (default: 25)")
231
+ end
232
+
233
+ def call(query: nil, node_id: nil, entity: nil, entity_type: nil, strategy: 'fulltext', limit: 5, max_depth: HTM::Timeline::MAX_DEPTH)
234
+ log_info "TimelineTool called: query=#{query.inspect}, node_id=#{node_id.inspect}, entity=#{entity.inspect}"
235
+ return failure("Give a query, a node_id or an entity") unless query || node_id || entity
236
+
237
+ guarded do
238
+ subject = node_id || query
239
+ about = entity && entity_named(entity, entity_type, argument: 'entity_type')
240
+ histories = timeline_view(session_htm.timeline(subject, entity: about, strategy: strategy.to_sym, limit:, max_depth:))
241
+
242
+ success(subject:, entity: about && entity_brief(about), count: histories.length, histories:)
243
+ end
244
+ end
245
+ end
246
+
247
+ # Tool: Confirm a memory
248
+ class ConfirmTool < Tool
249
+ description "Confirm a memory: upgrade an inferred memory or hypothesis (or an extracted fact) to asserted " \
250
+ "on the strength of evidence memories. Each is linked as confirming it, keeping its prior status."
251
+
252
+ arguments do
253
+ required(:node_id).filled(:integer).description("The memory to confirm")
254
+ required(:evidence).array(:integer).description("IDs of the memories that confirm it (at least one)")
255
+ optional(:reason).filled(:string).description("Why the evidence settles it")
256
+ optional(:confidence).filled(:float).description("Its new confidence, 0.0-1.0")
257
+ end
258
+
259
+ def call(node_id:, evidence:, reason: nil, confidence: nil)
260
+ log_info "ConfirmTool called: node_id=#{node_id}, evidence=#{evidence.inspect}"
261
+
262
+ guarded { success(**session_htm.confirm(node_id, evidence:, reason:, confidence:)) }
263
+ end
264
+ end
265
+
266
+ # Tool: When was something first mentioned?
267
+ class FirstMentionTool < Tool
268
+ read_only!
269
+ description "Find when something was first mentioned and whether memory can establish it. Direct evidence " \
270
+ "is a memory stated or extracted from a source with a known event time; inferred memories, " \
271
+ "hypotheses and dates read from text are indirect. established is false when indirect evidence " \
272
+ "points earlier than the earliest direct match; those matches are listed in earlier_indirect. " \
273
+ "When the query is the name or alias of a known entity, entity names it and the answer " \
274
+ "covers every memory mentioning it, under any of its names."
275
+
276
+ arguments do
277
+ required(:query).filled(:string).description("What was mentioned")
278
+ optional(:strategy).filled(:string).description("Search strategy: 'vector', 'fulltext' (default) or 'hybrid'")
279
+ optional(:limit).filled(:integer).description("Matches to judge (default: 50)")
280
+ optional(:timeframe).filled(:string).description("Only memories from this time (as for recall)")
281
+ end
282
+
283
+ def call(query:, strategy: 'fulltext', limit: 50, timeframe: nil)
284
+ log_info "FirstMentionTool called: query=#{query.inspect}, strategy=#{strategy}"
285
+
286
+ guarded do
287
+ answer = session_htm.first_mention(query, strategy: strategy.to_sym, limit:,
288
+ timeframe: timeframe_input(timeframe))
289
+ success(**first_mention_view(answer))
290
+ end
291
+ end
292
+ end
293
+
294
+ # Tool: Extract atomic propositions from text
295
+ class ExtractPropositionsTool < Tool
296
+ description "Break text into atomic, self-contained factual propositions using the configured LLM. " \
297
+ "With remember: true each proposition is stored as its own memory."
298
+
299
+ arguments do
300
+ required(:text).filled(:string).description("The text to decompose")
301
+ optional(:remember).filled(:bool).description("Store each proposition as a memory node (default: false)")
302
+ end
303
+
304
+ def call(text:, remember: false)
305
+ log_info "ExtractPropositionsTool called: text=#{text[0..50].inspect}..., remember=#{remember}"
306
+
307
+ guarded do
308
+ propositions = HTM.extract_propositions(text)
309
+ node_ids = remember == true ? propositions.map { store(it) } : []
310
+
311
+ success(count: propositions.length, propositions:, node_ids:)
312
+ end
313
+ end
314
+
315
+ private
316
+
317
+ def store(proposition) = session_htm.remember(proposition, status: :extracted)
318
+ end
319
+
320
+ # Tool: List the robots sharing memory
321
+ class ListRobotsTool < Tool
322
+ read_only!
323
+ description "List the robots that share HTM's memory (the hive mind), most recently active first"
324
+
325
+ arguments do
326
+ optional(:limit).filled(:integer).description("Maximum number of robots (default: 50)")
327
+ end
328
+
329
+ def call(limit: 50)
330
+ log_info "ListRobotsTool called: limit=#{limit}"
331
+
332
+ guarded do
333
+ robots = robot_entries(limit:)
334
+
335
+ success(current_robot: session_htm.robot_name, count: robots.length, robots:)
336
+ end
337
+ end
338
+ end
339
+
340
+ # Node, working memory, proposition and robot tools for registration
341
+ NODE_TOOLS = [
342
+ GetNodeTool,
343
+ ForgetContentTool,
344
+ PurgeDeletedTool,
345
+ ListDeletedTool,
346
+ ClearWorkingMemoryTool,
347
+ AssembleContextTool,
348
+ TagNodeTool,
349
+ UntagNodeTool,
350
+ RelatedNodesTool,
351
+ TimelineTool,
352
+ ConfirmTool,
353
+ FirstMentionTool,
354
+ ExtractPropositionsTool,
355
+ ListRobotsTool
356
+ ].freeze
357
+ end
358
+ end
@@ -0,0 +1,192 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fast_mcp'
4
+ require_relative 'tool_support'
5
+ require_relative '../admin'
6
+
7
+ class HTM
8
+ module MCP
9
+ # Resource: Robot Groups
10
+ class RobotGroupsResource < FastMcp::Resource
11
+ include ToolSupport
12
+
13
+ uri "htm://groups"
14
+ resource_name "HTM Robot Groups"
15
+ mime_type "application/json"
16
+
17
+ def content
18
+ groups = GroupSession.group_names.map { find_group(it).status }
19
+
20
+ { count: groups.length, groups: }.to_json
21
+ end
22
+ end
23
+
24
+ # Resource: Memory Statistics
25
+ class MemoryStatsResource < FastMcp::Resource
26
+ include ToolSupport
27
+
28
+ uri "htm://statistics"
29
+ resource_name "HTM Memory Statistics"
30
+ mime_type "application/json"
31
+
32
+ def content
33
+ { **record_counts, **robot_fields(session_htm), **embedding_fields(HTM.configuration) }.to_json
34
+ end
35
+
36
+ private
37
+
38
+ def record_counts
39
+ {
40
+ total_nodes: HTM::Models::Node.count,
41
+ total_tags: HTM::Models::Tag.count,
42
+ total_entities: HTM::Models::Entity.canonical.count,
43
+ total_robots: HTM::Models::Robot.count
44
+ }
45
+ end
46
+
47
+ def robot_fields(htm)
48
+ {
49
+ current_robot: htm.robot_name,
50
+ robot_id: htm.robot_id,
51
+ robot_initialized: Session.robot_initialized?
52
+ }
53
+ end
54
+
55
+ def embedding_fields(config)
56
+ { embedding_provider: config.embedding_provider, embedding_model: config.embedding_model }
57
+ end
58
+ end
59
+
60
+ # Resource: Tag Hierarchy
61
+ class TagHierarchyResource < FastMcp::Resource
62
+ uri "htm://tags/hierarchy"
63
+ resource_name "HTM Tag Hierarchy"
64
+ mime_type "text/plain"
65
+
66
+ # The tree of every tag, or of the tags in the given dataset
67
+ def initialize(params = {}, tags: HTM::Models::Tag.dataset)
68
+ super(params)
69
+ @tags = tags
70
+ end
71
+
72
+ def content
73
+ HTM::Models::Tag.tree_string(@tags)
74
+ end
75
+ end
76
+
77
+ # Resource: Recent Memories
78
+ class RecentMemoriesResource < FastMcp::Resource
79
+ include ToolSupport
80
+
81
+ uri "htm://memories/recent"
82
+ resource_name "Recent HTM Memories"
83
+ mime_type "application/json"
84
+
85
+ def content
86
+ recent = HTM::Models::Node.eager(:tags)
87
+ .order(Sequel.desc(:created_at))
88
+ .limit(20)
89
+ .all
90
+
91
+ { recent_memories: node_summaries(recent, content_limit: 200) }.to_json
92
+ end
93
+ end
94
+
95
+ # Resource: Active configuration (no credentials)
96
+ class ConfigResource < FastMcp::Resource
97
+ uri "htm://config"
98
+ resource_name "HTM Configuration"
99
+ mime_type "application/json"
100
+
101
+ def content
102
+ config = HTM.configuration
103
+ {
104
+ environment: config.environment,
105
+ embedding: { provider: config.embedding_provider, model: config.embedding_model,
106
+ dimensions: config.embedding_dimensions },
107
+ tag: { provider: config.tag_provider, model: config.tag_model },
108
+ proposition: { provider: config.proposition_provider, model: config.proposition_model,
109
+ enabled: config.extract_propositions },
110
+ entity: entity_settings(config),
111
+ chunking: { chunk_size: config.chunk_size, chunk_overlap: config.chunk_overlap },
112
+ job_backend: config.job_backend,
113
+ week_start: config.week_start,
114
+ robots: HTM::Robots.settings.slice(:provider, :model, :teams, :batch_size, :idle_seconds)
115
+ }.to_json
116
+ end
117
+
118
+ private
119
+
120
+ def entity_settings(config)
121
+ { provider: config.entity_provider, model: config.entity_model, enabled: config.extract_entities,
122
+ types: config.entity_types, resolution: config.entity_resolution }
123
+ end
124
+ end
125
+
126
+ # Resource: Loaded files
127
+ class FileSourcesResource < FastMcp::Resource
128
+ uri "htm://files"
129
+ resource_name "HTM Loaded Files"
130
+ mime_type "application/json"
131
+
132
+ def content
133
+ files = HTM::Models::FileSource.order(:file_path).all.map do |source|
134
+ { file_path: source.file_path, chunk_count: source.chunks_dataset.count,
135
+ sync_state: HTM::Admin::FileCommands.sync_state(source).to_s,
136
+ last_synced_at: source.last_synced_at&.iso8601 }
137
+ end
138
+
139
+ { count: files.length, totals: HTM::Admin::FileCommands.file_totals, files: }.to_json
140
+ end
141
+ end
142
+
143
+ # Resource: The entities memory mentions most
144
+ class EntitiesResource < FastMcp::Resource
145
+ include ToolSupport
146
+
147
+ # Entities listed
148
+ LIMIT = 50
149
+
150
+ uri "htm://entities"
151
+ resource_name "HTM Entities"
152
+ description "The people, organizations, locations, products and events memory mentions most"
153
+ mime_type "application/json"
154
+
155
+ def content
156
+ entities = entities_view(session_htm.entities(limit: LIMIT))
157
+
158
+ { count: entities.length, entities: }.to_json
159
+ end
160
+ end
161
+
162
+ # Resource: Startup prompt telling the robot how to use its long-term memory
163
+ class StartupPromptResource < FastMcp::Resource
164
+ uri "htm://prompts/startup"
165
+ resource_name "HTM Startup Prompt"
166
+ description "System prompt for a robot that uses HTM as its long-term memory"
167
+ mime_type "text/plain"
168
+
169
+ # @param session [#robot_name, #robot_initialized?] The MCP session
170
+ def initialize(params = {}, session: Session)
171
+ super(params)
172
+ @session = session
173
+ end
174
+
175
+ def content
176
+ HTM::StartupPrompt.render(robot_name: (@session.robot_name if @session.robot_initialized?), channel: :mcp)
177
+ end
178
+ end
179
+
180
+ # All resources for registration
181
+ RESOURCES = [
182
+ StartupPromptResource,
183
+ MemoryStatsResource,
184
+ TagHierarchyResource,
185
+ RecentMemoriesResource,
186
+ RobotGroupsResource,
187
+ ConfigResource,
188
+ FileSourcesResource,
189
+ EntitiesResource
190
+ ].freeze
191
+ end
192
+ end
@@ -0,0 +1,129 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'stringio'
4
+ require_relative 'tool'
5
+ require_relative '../admin'
6
+
7
+ class HTM
8
+ module MCP
9
+ # Validates the team names a robot-team tool was given
10
+ module TeamNames
11
+ private
12
+
13
+ # @return [Array<String>, nil] the requested teams, nil for the configured ones
14
+ # @raise [ArgumentError] for an unknown team
15
+ def team_names(teams)
16
+ return nil if teams.nil? || teams.empty?
17
+
18
+ known = HTM::Robots.team_classes.keys
19
+ unknown = teams - known
20
+ raise ArgumentError, "Unknown team(s): #{unknown.join(', ')}. Known teams: #{known.join(', ')}" if unknown.any?
21
+
22
+ teams
23
+ end
24
+ end
25
+
26
+ # Tool: Cases waiting for each robot team
27
+ class RobotTeamsStatusTool < Tool
28
+ include TeamNames
29
+
30
+ read_only!
31
+ description "Count the cases waiting for HTM's memory-maintenance robot teams " \
32
+ "(tag_curator, consolidator, contradiction_detector, archivist, entity_curator). SQL only, no LLM calls."
33
+
34
+ arguments do
35
+ optional(:teams).array(:string).description("Teams to check (default: the configured teams)")
36
+ end
37
+
38
+ def call(teams: nil)
39
+ log_info "RobotTeamsStatusTool called: teams=#{teams.inspect}"
40
+
41
+ guarded do
42
+ pending = HTM::Robots.status(team_names(teams))
43
+
44
+ success(teams: pending, total: pending.values.sum)
45
+ end
46
+ end
47
+ end
48
+
49
+ # Tool: Run one batch of each robot team
50
+ class RunRobotTeamsTool < Tool
51
+ include TeamNames
52
+
53
+ destructive!
54
+ description "Run one batch of each memory-maintenance robot team. Teams merge duplicate tags and " \
55
+ "near-duplicate memories, retire contradicted memories and archive cold ones (all soft " \
56
+ "deletes, undone with restore), and merge duplicate entities (undone by unmerging). " \
57
+ "Uses the configured LLM; may take a while."
58
+
59
+ arguments do
60
+ optional(:teams).array(:string).description("Teams to run (default: the configured teams)")
61
+ end
62
+
63
+ def call(teams: nil)
64
+ log_info "RunRobotTeamsTool called: teams=#{teams.inspect}"
65
+
66
+ guarded do
67
+ names = team_names(teams)
68
+ handled = quietly { HTM::Robots.supervisor(names).cycle }
69
+
70
+ success(teams: names || HTM::Robots.teams.map(&:slug), cases_handled: handled,
71
+ pending: HTM::Robots.status(names))
72
+ end
73
+ end
74
+ end
75
+
76
+ # Tool: Generate missing embeddings, tags, entities and propositions
77
+ class EnrichPendingTool < Tool
78
+ description "Generate what background jobs missed: embeddings and tags for nodes without them, " \
79
+ "entities for nodes that mention none and were never examined for them, and propositions " \
80
+ "for nodes not yet decomposed. By default entities are skipped while entity.enabled is off; " \
81
+ "naming 'entities' in kinds extracts them anyway. Uses the configured LLM; may take a while."
82
+
83
+ # What can be asked for by name, in the order processed
84
+ KINDS = %w[embeddings tags entities propositions].freeze
85
+
86
+ arguments do
87
+ optional(:kinds).array(:string).description("What to process: any of 'embeddings', 'tags', 'entities', 'propositions' " \
88
+ "(default: all; entities only while entity.enabled is on)")
89
+ end
90
+
91
+ def call(kinds: nil)
92
+ log_info "EnrichPendingTool called: kinds=#{kinds.inspect}"
93
+
94
+ guarded do
95
+ kinds ||= default_kinds
96
+ unknown = kinds - KINDS
97
+ raise ArgumentError, "Unknown kind(s): #{unknown.join(', ')}. Known kinds: #{KINDS.join(', ')}" if unknown.any?
98
+
99
+ results = kinds.to_h { [it, process(it)] }
100
+
101
+ success(results:, pending: pending_counts)
102
+ end
103
+ end
104
+
105
+ private
106
+
107
+ # Every kind, less entities while entity.enabled is off (as `htm enrich process_all` does)
108
+ def default_kinds = HTM.config.extract_entities ? KINDS : KINDS - ['entities']
109
+
110
+ def process(kind)
111
+ counts = quietly { HTM::Admin::EnrichCommands.public_send(:"process_#{kind}", out: StringIO.new) }
112
+ counts || { ok: 0, failed: 0 }
113
+ end
114
+
115
+ def pending_counts
116
+ enrich = HTM::Admin::EnrichCommands
117
+ { embeddings: enrich.nodes_without_embeddings.count, tags: enrich.nodes_without_tags.count,
118
+ entities: HTM::Admin::EntityCommands.nodes_awaiting_entities.count }
119
+ end
120
+ end
121
+
122
+ # Robot team and enrichment tools for registration
123
+ ROBOT_TEAM_TOOLS = [
124
+ RobotTeamsStatusTool,
125
+ RunRobotTeamsTool,
126
+ EnrichPendingTool
127
+ ].freeze
128
+ end
129
+ end