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,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ # HTM tag tasks: htm tags SUBCOMMAND
4
+ #
5
+ # htm tags tree # the whole hierarchy as text
6
+ # htm tags tree database # only tags under database
7
+ # htm tags export ai # tags.txt, tags.md and tags.svg for ai*
8
+ # htm tags graph medicine # interactive node graph in tags_graph.html
9
+ # htm tags search postgrsql # tags resembling a (misspelled) name
10
+ # htm tags nodes database:postgresql performance --match all
11
+
12
+ require_relative "group"
13
+ require_relative "memory_command"
14
+
15
+ class HTM
16
+ class CLI < Thor
17
+ # The tag commands (htm tags SUBCOMMAND): list and search tags, find
18
+ # the memories carrying them, and show, export, rebuild and repair the
19
+ # tag hierarchy
20
+ class Tags < Thor
21
+ include Group
22
+ include MemoryCommand
23
+
24
+ desc "list [PREFIX]", "List the tags (or those under PREFIX) with how many memories carry each"
25
+ memory_options
26
+ def list(prefix = nil) = memory_console(:TagSearch) { it.list(prefix) }
27
+
28
+ desc "search QUERY", "Find tags whose names resemble QUERY (typo-tolerant)"
29
+ memory_options
30
+ limit_option 20
31
+ option :min_similarity, type: :numeric, default: 0.3, desc: "Minimum similarity, 0.0-1.0 (lower is fuzzier)"
32
+ def search(query)
33
+ memory_console(:TagSearch) { it.search(query, limit: options[:limit], min_similarity: options[:min_similarity]) }
34
+ end
35
+
36
+ desc "popular", "List the most used tags"
37
+ memory_options
38
+ limit_option 20
39
+ option :timeframe, aliases: "-t", desc: "Only count memories from this time ('last week', ISO8601 start..end)"
40
+ def popular = memory_console(:TagSearch) { it.popular(limit: options[:limit], timeframe: options[:timeframe]) }
41
+
42
+ desc "pairs", "List pairs of tags used together on the same memories, most shared first"
43
+ memory_options
44
+ limit_option 50
45
+ option :min_shared, type: :numeric, default: 2, desc: "Minimum memories a pair shares"
46
+ def pairs = memory_console(:TagSearch) { it.pairs(min_shared_nodes: options[:min_shared], limit: options[:limit]) }
47
+
48
+ desc "nodes TAG...", "List the memories carrying any (or --match all) of the given tags, most relevant first"
49
+ memory_options
50
+ full_option
51
+ limit_option 20
52
+ option :match, default: "any", enum: %w[any all], desc: "Memories with any of the tags, or all of them"
53
+ option :timeframe, aliases: "-t", desc: "Only memories from this time ('last week', ISO8601 start..end)"
54
+ def nodes(*tags)
55
+ memory_console(:TagSearch) do |console|
56
+ console.tagged(tags, match: options[:match], limit: options[:limit], timeframe: options[:timeframe])
57
+ end
58
+ end
59
+
60
+ desc "topic TOPIC", "List the memories under a topic: tags starting with TOPIC (--exact, or --fuzzy for typos)"
61
+ memory_options
62
+ full_option
63
+ limit_option 20
64
+ option :exact, type: :boolean, desc: "Only the tag TOPIC itself"
65
+ option :fuzzy, type: :boolean, desc: "Tags resembling TOPIC (typo-tolerant)"
66
+ option :min_similarity, type: :numeric, default: 0.3, desc: "Minimum similarity for --fuzzy"
67
+ def topic(topic)
68
+ memory_console(:TagSearch) do |console|
69
+ console.topic(topic, limit: options[:limit], min_similarity: options[:min_similarity],
70
+ exact: options[:exact], fuzzy: options[:fuzzy])
71
+ end
72
+ end
73
+
74
+ desc "tree [PREFIX]", "Display the tags as a text tree, optionally only those under PREFIX"
75
+ def tree(prefix = nil) = htm_task { it::TagCommands.tree(prefix) }
76
+
77
+ desc "mermaid [PREFIX]", "Export the tags as a Mermaid flowchart to tags.md"
78
+ def mermaid(prefix = nil) = htm_task { it::TagCommands.mermaid(prefix) }
79
+
80
+ desc "svg [PREFIX]", "Export the tags as an SVG diagram to tags.svg"
81
+ def svg(prefix = nil) = htm_task { it::TagCommands.svg(prefix) }
82
+
83
+ desc "export [PREFIX]", "Export the tags to tags.txt, tags.md and tags.svg"
84
+ def export(prefix = nil) = htm_task { it::TagCommands.export(prefix) }
85
+
86
+ desc "graph [PREFIX]", "Write an interactive graph of the nodes under PREFIX and their shared-tag links to one HTML file"
87
+ method_option :output, type: :string, default: "tags_graph.html", aliases: "-o", desc: "File to write"
88
+ method_option :title, type: :string, desc: "Page title (default names the prefix)"
89
+ def graph(prefix = nil) = htm_task { it::TagGraph.write(prefix, path: options[:output], title: options[:title]) }
90
+
91
+ desc "rebuild", "Delete every tag and extract them again for every node via the LLM (asks first)"
92
+ def rebuild = htm_task { it::TagCommands.rebuild }
93
+
94
+ desc "restore_plurals [PREFIX]",
95
+ "List tags whose plural names the old normalizer trimmed (alchemycm, ruby-on-rail); --apply renames them"
96
+ method_option :apply, type: :boolean, default: false, desc: "Rename the tags instead of only listing them"
97
+ def restore_plurals(prefix = nil) = htm_task { it::TagCommands.restore_plurals(prefix, apply: options[:apply]) }
98
+
99
+ desc "cleanup", "Soft delete orphaned tags and node_tags rows of deleted nodes (asks first)"
100
+ def cleanup = htm_task { it::TagCommands.cleanup }
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "thor"
4
+
5
+ class HTM
6
+ class CLI < Thor
7
+ # Kept in step with the htm library's minor version: htm-cli 0.2.x runs
8
+ # against htm 0.2.x
9
+ VERSION = "0.2.0"
10
+ end
11
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ # HTM working memory commands: htm wm SUBCOMMAND
4
+ #
5
+ # htm wm list --robot coder
6
+ # htm wm context --strategy recent > context.txt
7
+ # htm wm clear
8
+
9
+ require_relative "group"
10
+ require_relative "memory_command"
11
+
12
+ class HTM
13
+ class CLI < Thor
14
+ # The working memory commands (htm wm SUBCOMMAND): a robot's active
15
+ # context, as it built up over earlier runs and MCP sessions
16
+ class WorkingMemory < Thor
17
+ include Group
18
+ include MemoryCommand
19
+
20
+ namespace :wm
21
+
22
+ desc "list", "List the robot's working memory, most recently remembered first"
23
+ memory_options
24
+ full_option
25
+ def list = memory_console(:WorkingMemory, &:list)
26
+
27
+ desc "context", "Print the working memory as one context string for an LLM prompt"
28
+ memory_options
29
+ option :strategy, aliases: "-s", default: "balanced", enum: %w[balanced recent frequent],
30
+ desc: "Order: balanced (frequency x recency), recent or frequent"
31
+ option :max_tokens, type: :numeric, desc: "Token budget (default: the working memory size)"
32
+ def context
33
+ memory_console(:WorkingMemory) { it.context(strategy: options[:strategy], max_tokens: options[:max_tokens]&.to_i) }
34
+ end
35
+
36
+ desc "clear", "Clear the robot's working memory (the memories stay in long-term memory)"
37
+ memory_options
38
+ def clear = memory_console(:WorkingMemory, &:clear)
39
+ end
40
+ end
41
+ end
data/lib/htm/cli.rb ADDED
@@ -0,0 +1,96 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "htm/version"
4
+ require_relative "cli/version"
5
+ require_relative "cli/group"
6
+ require_relative "cli/environment"
7
+ require_relative "cli/db"
8
+ require_relative "cli/enrich"
9
+ require_relative "cli/entities"
10
+ require_relative "cli/files"
11
+ require_relative "cli/robots"
12
+ require_relative "cli/tags"
13
+ require_relative "cli/working_memory"
14
+ require_relative "cli/memory"
15
+
16
+ class HTM
17
+ # The htm command line (bin/htm). `htm mcp` starts the MCP server; the
18
+ # other commands work on memory from the terminal. HTM itself loads only
19
+ # when a command needs it, so `htm help` stays fast.
20
+ #
21
+ # @example
22
+ # HTM::CLI.start(%w[db stats])
23
+ #
24
+ class CLI < Thor
25
+ include Group
26
+
27
+ map %w[-v --version] => :version
28
+
29
+ desc "mcp", "Start the MCP server on stdio (for Claude Desktop and other MCP clients)"
30
+ long_desc <<~DESC
31
+ Start HTM's MCP server, speaking JSON-RPC on stdin/stdout. MCP clients
32
+ launch it; for Claude Desktop add to ~/.config/claude/claude_desktop_config.json:
33
+
34
+ {
35
+ "mcpServers": {
36
+ "htm-memory": {
37
+ "command": "htm",
38
+ "args": ["mcp"],
39
+ "env": { "HTM_DATABASE__URL": "postgresql://postgres@localhost:5432/htm_development" }
40
+ }
41
+ }
42
+ }
43
+ DESC
44
+ def mcp
45
+ require "htm"
46
+ require_relative "mcp/server"
47
+ HTM::MCP::Server.start
48
+ end
49
+
50
+ desc "config", "Print the default configuration (YAML), a starting point for a --config file"
51
+ def config = puts(File.read(self.class.defaults_path))
52
+
53
+ desc "env", "List the environment variables that configure HTM"
54
+ def env = puts(ENVIRONMENT_HELP)
55
+
56
+ desc "version", "Show the versions of the htm command line and the htm library it runs"
57
+ def version = puts(self.class.version_line)
58
+
59
+ class << self
60
+ # The defaults.yml the htm library ships, found beside its version
61
+ # file so that printing it does not load HTM
62
+ #
63
+ # @return [String] absolute path
64
+ #
65
+ def defaults_path
66
+ _, version_file = $LOAD_PATH.resolve_feature_path("htm/version")
67
+ File.expand_path("config/defaults.yml", File.dirname(version_file))
68
+ end
69
+
70
+ # @return [String] both versions; they differ when the command line
71
+ # and the library were not installed together
72
+ def version_line = "htm-cli #{VERSION} (htm #{HTM::VERSION})"
73
+ end
74
+
75
+ desc "db SUBCOMMAND", "Database: create, setup, migrate, verify, stats, console, purge_all, ..."
76
+ subcommand "db", Db
77
+
78
+ desc "enrich SUBCOMMAND", "Node enrichment: process pending embeddings, tags, entities and propositions"
79
+ subcommand "enrich", Enrich
80
+
81
+ desc "entities SUBCOMMAND", "Entities: list, show, nodes, related, report, graph, add, remove, merge, alias, delete, rebuild, ..."
82
+ subcommand "entities", Entities
83
+
84
+ desc "files SUBCOMMAND", "File loading: load, load_dir, list, info, unload, sync, stats"
85
+ subcommand "files", Files
86
+
87
+ desc "robots SUBCOMMAND", "Robots: list those sharing memory; run the maintenance teams (work, once, status)"
88
+ subcommand "robots", Robots
89
+
90
+ desc "tags SUBCOMMAND", "Tags: list, search, popular, pairs, nodes, topic, tree, export, graph, rebuild, ..."
91
+ subcommand "tags", Tags
92
+
93
+ desc "wm SUBCOMMAND", "Working memory: list, context, clear"
94
+ subcommand "wm", WorkingMemory
95
+ end
96
+ end
@@ -0,0 +1,334 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'tool'
4
+
5
+ class HTM
6
+ module MCP
7
+ # How the entity tools' arguments name an entity
8
+ ENTITY_REFERENCE = "The entity's name, one of its aliases, or its id (use the id when several entities share a name)"
9
+
10
+ # How the entity tools' type argument picks one of several entities
11
+ ENTITY_TYPE = "The entity's type, for a name that entities of several types share"
12
+
13
+ # Finds entities by a name that may be misspelled
14
+ module EntitySearch
15
+ private
16
+
17
+ # Summaries of the entities whose name or an alias resembles +query+,
18
+ # most similar first; a merged match gives the entity standing for it
19
+ #
20
+ # @param query [String]
21
+ # @param type [String, nil] only entities of this type
22
+ # @param limit [Integer]
23
+ # @param min_similarity [Float] pg_trgm similarity to reach, 0.0-1.0
24
+ # @return [Array<Hash>] see HTM#entity
25
+ # @raise [HTM::ValidationError] for a limit that is not a positive Integer
26
+ def matching_entities(query, type:, limit:, min_similarity:)
27
+ HTM::InputValidator.positive_integer!(limit, "limit")
28
+ model = HTM::Models::Entity
29
+ found = of_type(model.standing_for(model.search(query, min_similarity:).all), type)
30
+
31
+ HTM::EntityMemory::Facts.summaries(found.first(limit))
32
+ end
33
+
34
+ # +entities+ of the given type; all of them without one
35
+ def of_type(entities, type)
36
+ return entities unless type
37
+
38
+ wanted = HTM::EntityText.normalize_type(type)
39
+ entities.select { it.entity_type == wanted }
40
+ end
41
+ end
42
+
43
+ # Tool: List or search the entities memory mentions
44
+ class EntitiesTool < Tool
45
+ include EntitySearch
46
+
47
+ read_only!
48
+ description "List the entities memory is about (people, organizations, locations, products, events), most " \
49
+ "mentioned first. With query, search entity names and aliases instead (typo-tolerant), most similar " \
50
+ "first. With unmentioned, list instead the entities no memory mentions (delete_entity removes one)."
51
+
52
+ arguments do
53
+ optional(:query).filled(:string).description("Name to search for - can contain typos (e.g., 'alice chenn' finds 'Alice Chen')")
54
+ optional(:type).filled(:string).description("Only entities of this type (e.g., 'person', 'organization')")
55
+ optional(:limit).filled(:integer).description("Maximum number of entities (default: 20)")
56
+ optional(:min_similarity).filled(:float).description("Minimum similarity for query, 0.0-1.0 (default: 0.3, lower = more fuzzy)")
57
+ optional(:unmentioned).filled(:bool).description(
58
+ "List the entities no memory mentions, by name, instead of the mentioned ones (default: false; not with query)"
59
+ )
60
+ end
61
+
62
+ def call(query: nil, type: nil, limit: 20, min_similarity: 0.3, unmentioned: false)
63
+ log_info "EntitiesTool called: query=#{query.inspect}, type=#{type.inspect}, limit=#{limit}, unmentioned=#{unmentioned}"
64
+ return failure("unmentioned lists entities; give it without a query") if query && unmentioned
65
+
66
+ guarded do
67
+ entity_type!(type)
68
+ found = query ? matching_entities(query, type:, limit:, min_similarity:) : session_htm.entities(type:, limit:, unmentioned:)
69
+ entities = entities_view(found)
70
+
71
+ success(query:, type:, unmentioned:, count: entities.length, entities:)
72
+ end
73
+ end
74
+ end
75
+
76
+ # Tool: One entity's names and how often and when memory mentions it
77
+ class EntityTool < Tool
78
+ read_only!
79
+ description "Show one entity: its canonical name, type, aliases (every other name it answers to), how many " \
80
+ "memories mention it, and when it was first and last seen"
81
+
82
+ arguments do
83
+ required(:entity).filled(:string).description(ENTITY_REFERENCE)
84
+ optional(:type).filled(:string).description(ENTITY_TYPE)
85
+ end
86
+
87
+ def call(entity:, type: nil)
88
+ log_info "EntityTool called: entity=#{entity.inspect}, type=#{type.inspect}"
89
+
90
+ guarded { success(entity: entity_view(session_htm.entity(entity_named(entity, type)))) }
91
+ end
92
+ end
93
+
94
+ # Tool: Entities mentioned together with an entity
95
+ class RelatedEntitiesTool < Tool
96
+ read_only!
97
+ description "Find the entities mentioned in the same memories as an entity, most shared memories first " \
98
+ "(weight is the number of memories mentioning both)"
99
+
100
+ arguments do
101
+ required(:entity).filled(:string).description(ENTITY_REFERENCE)
102
+ optional(:type).filled(:string).description(ENTITY_TYPE)
103
+ optional(:limit).filled(:integer).description("Maximum number of related entities (default: 10)")
104
+ end
105
+
106
+ def call(entity:, type: nil, limit: 10)
107
+ log_info "RelatedEntitiesTool called: entity=#{entity.inspect}, limit=#{limit}"
108
+
109
+ guarded do
110
+ about = entity_named(entity, type)
111
+ related = related_entities_view(session_htm.related_entities(about, limit:))
112
+
113
+ success(entity: entity_brief(about), count: related.length, related:)
114
+ end
115
+ end
116
+ end
117
+
118
+ # Tool: The memories mentioning an entity
119
+ class EntityNodesTool < Tool
120
+ read_only!
121
+ description "List the memories that mention an entity (under any of its names), latest event first, " \
122
+ "optionally only those from a timeframe or whose state was true at a moment"
123
+
124
+ arguments do
125
+ required(:entity).filled(:string).description(ENTITY_REFERENCE)
126
+ optional(:type).filled(:string).description(ENTITY_TYPE)
127
+ optional(:limit).filled(:integer).description("Maximum number of memories (default: 20)")
128
+ optional(:timeframe).filled(:string).description(
129
+ "Only memories from this time: natural language ('last week') or ISO8601 'start..end'"
130
+ )
131
+ optional(:as_of).filled(:string).description(
132
+ "Only memories whose state was true at this moment (ISO8601 or natural language)"
133
+ )
134
+ end
135
+
136
+ def call(entity:, type: nil, limit: 20, timeframe: nil, as_of: nil)
137
+ log_info "EntityNodesTool called: entity=#{entity.inspect}, limit=#{limit}, timeframe=#{timeframe.inspect}"
138
+
139
+ guarded do
140
+ about = entity_named(entity, type)
141
+ found = session_htm.entity_nodes(about, limit:, as_of:, timeframe: timeframe_input(timeframe))
142
+ nodes = node_summaries(nodes_with_tags(found.map(&:id)))
143
+
144
+ success(entity: entity_brief(about), as_of:, timeframe:, count: nodes.length, nodes:)
145
+ end
146
+ end
147
+ end
148
+
149
+ # Tool: Everything memory holds about an entity
150
+ class EntityReportTool < Tool
151
+ read_only!
152
+ description "Report everything memory holds about an entity: its names, counts (memories, soft-deleted " \
153
+ "memories still stored, mentions), the entities it appears with, and every memory mentioning it " \
154
+ "(oldest event first) with how each one writes its name"
155
+
156
+ arguments do
157
+ required(:entity).filled(:string).description(ENTITY_REFERENCE)
158
+ optional(:type).filled(:string).description(ENTITY_TYPE)
159
+ end
160
+
161
+ def call(entity:, type: nil)
162
+ log_info "EntityReportTool called: entity=#{entity.inspect}"
163
+
164
+ guarded { success(**entity_report_view(session_htm.entity_report(entity_named(entity, type)))) }
165
+ end
166
+ end
167
+
168
+ # Tool: Say that a node mentions an entity
169
+ class AddEntityTool < Tool
170
+ description "Record that a memory node mentions an entity. The entity is created when memory does not know " \
171
+ "it; the node's propositions that name it get the mention too."
172
+
173
+ arguments do
174
+ required(:node_id).filled(:integer).description("The ID of the node")
175
+ required(:name).filled(:string).description("The entity's name or one of its aliases")
176
+ required(:type).filled(:string).description("The entity's type: one of the configured types (e.g., 'person', 'organization')")
177
+ end
178
+
179
+ def call(node_id:, name:, type:)
180
+ log_info "AddEntityTool called: node_id=#{node_id}, name=#{name.inspect}, type=#{type.inspect}"
181
+
182
+ guarded do
183
+ entity = session_htm.add_entity(node_id, name, type: configured_entity_type!(type))
184
+
185
+ success(node_id:, entity:, entities: entities_of(node_id))
186
+ end
187
+ end
188
+ end
189
+
190
+ # Tool: Say that a node does not mention an entity
191
+ class RemoveEntityTool < Tool
192
+ description "Remove an entity from a memory node: every mention of it on that node (its propositions keep " \
193
+ "theirs). The entity and its other mentions are left alone."
194
+
195
+ arguments do
196
+ required(:node_id).filled(:integer).description("The ID of the node")
197
+ required(:entity).filled(:string).description(ENTITY_REFERENCE)
198
+ optional(:type).filled(:string).description(ENTITY_TYPE)
199
+ end
200
+
201
+ def call(node_id:, entity:, type: nil)
202
+ log_info "RemoveEntityTool called: node_id=#{node_id}, entity=#{entity.inspect}"
203
+
204
+ guarded do
205
+ about = entity_named(entity, type)
206
+ removed = session_htm.remove_entity(node_id, about)
207
+
208
+ success(node_id:, entity: entity_brief(about), removed:, entities: entities_of(node_id))
209
+ end
210
+ end
211
+ end
212
+
213
+ # Tool: Merge a duplicate entity into another
214
+ class MergeEntitiesTool < Tool
215
+ description "Merge a duplicate entity into the entity of the same type that stays: its name, aliases and " \
216
+ "mentions then answer to that one. Nothing is deleted; unmerge_entity undoes it."
217
+
218
+ arguments do
219
+ required(:entity).filled(:string).description("The duplicate: its name, one of its aliases, or its id")
220
+ required(:into).filled(:string).description("The entity that stays: its name, one of its aliases, or its id")
221
+ optional(:type).filled(:string).description("The type of both entities, for a name that entities of several types share")
222
+ end
223
+
224
+ def call(entity:, into:, type: nil)
225
+ log_info "MergeEntitiesTool called: entity=#{entity.inspect}, into=#{into.inspect}"
226
+
227
+ guarded do
228
+ merged = entity_brief(entity_named(entity, type))
229
+ kept = session_htm.merge_entities(merged[:id], into: entity_named(into, type)).slice(:id, :name, :type)
230
+
231
+ success(merged:, into: kept, message: "Merged into '#{kept[:name]}'. Use unmerge_entity to undo.")
232
+ end
233
+ end
234
+ end
235
+
236
+ # Tool: Undo an entity merge
237
+ class UnmergeEntityTool < Tool
238
+ description "Undo a merge: the merged entity stands for itself again, with the aliases and mentions it had"
239
+
240
+ arguments do
241
+ required(:entity).filled(:string).description("The merged entity's own name, or its id")
242
+ end
243
+
244
+ def call(entity:)
245
+ log_info "UnmergeEntityTool called: entity=#{entity.inspect}"
246
+
247
+ guarded { success(entity: entity_view(session_htm.unmerge_entity(entity))) }
248
+ end
249
+ end
250
+
251
+ # Tool: Give an entity another name
252
+ class AliasEntityTool < Tool
253
+ description "Record another name for an entity (e.g., 'Dr. Chen' for 'Alice Chen'), so that name finds it " \
254
+ "too. To join two entities that both exist, use merge_entities."
255
+
256
+ arguments do
257
+ required(:entity).filled(:string).description(ENTITY_REFERENCE)
258
+ required(:alias_text).filled(:string).description("The other name")
259
+ optional(:type).filled(:string).description(ENTITY_TYPE)
260
+ end
261
+
262
+ def call(entity:, alias_text:, type: nil)
263
+ log_info "AliasEntityTool called: entity=#{entity.inspect}, alias_text=#{alias_text.inspect}"
264
+
265
+ guarded { success(entity: entity_view(session_htm.alias_entity(entity_named(entity, type), alias_text))) }
266
+ end
267
+ end
268
+
269
+ # Tool: Forget every memory mentioning an entity
270
+ class ForgetEntityTool < Tool
271
+ destructive!
272
+ description "Forget an entity: soft-delete every memory that mentions it (recoverable with restore, one " \
273
+ "node at a time). The entity's name and aliases stay. Requires confirm: 'confirmed'."
274
+
275
+ arguments do
276
+ required(:entity).filled(:string).description(ENTITY_REFERENCE)
277
+ required(:confirm).filled(:string).description("Must be 'confirmed'")
278
+ optional(:type).filled(:string).description(ENTITY_TYPE)
279
+ end
280
+
281
+ def call(entity:, confirm:, type: nil)
282
+ log_info "ForgetEntityTool called: entity=#{entity.inspect}"
283
+
284
+ guarded do
285
+ about = entity_named(entity, type)
286
+ node_ids = session_htm.forget_entity(about, confirm: htm_confirmation(confirm))
287
+
288
+ success(entity: entity_brief(about), count: node_ids.length, node_ids:,
289
+ message: "Memories soft-deleted. Use restore on each node_id to recover.")
290
+ end
291
+ end
292
+ end
293
+
294
+ # Tool: Delete an entity nothing mentions
295
+ class DeleteEntityTool < Tool
296
+ destructive!
297
+ description "Delete an entity that no memory mentions (entities with unmentioned: true lists them), e.g. one " \
298
+ "created by mistake: its name is no longer looked up. An entity memories still mention is refused " \
299
+ "(remove_entity or forget_entity first), as is one other entities are merged into (unmerge_entity first)."
300
+
301
+ arguments do
302
+ required(:entity).filled(:string).description(ENTITY_REFERENCE)
303
+ optional(:type).filled(:string).description(ENTITY_TYPE)
304
+ end
305
+
306
+ def call(entity:, type: nil)
307
+ log_info "DeleteEntityTool called: entity=#{entity.inspect}, type=#{type.inspect}"
308
+
309
+ guarded do
310
+ about = entity_named(entity, type)
311
+ session_htm.delete_entity(about)
312
+
313
+ success(entity: entity_brief(about), message: "Entity deleted; no memory mentioned it.")
314
+ end
315
+ end
316
+ end
317
+
318
+ # Entity tools for registration
319
+ ENTITY_TOOLS = [
320
+ EntitiesTool,
321
+ EntityTool,
322
+ RelatedEntitiesTool,
323
+ EntityNodesTool,
324
+ EntityReportTool,
325
+ AddEntityTool,
326
+ RemoveEntityTool,
327
+ MergeEntitiesTool,
328
+ UnmergeEntityTool,
329
+ AliasEntityTool,
330
+ ForgetEntityTool,
331
+ DeleteEntityTool
332
+ ].freeze
333
+ end
334
+ end