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,175 @@
1
+ # frozen_string_literal: true
2
+
3
+ class HTM
4
+ module Admin
5
+ module MemoryCommands
6
+ # Commands that change memory: remember, forget, restore, purge and
7
+ # tagging. Permanent deletes ask first unless assume_yes.
8
+ #
9
+ # @example
10
+ # HTM::Admin::MemoryCommands::Edit.new.remember("We use pgvector", tags: ["database:postgresql"])
11
+ #
12
+ class Edit < Base
13
+ # Store +content+ as a memory; its embedding and tags (and
14
+ # propositions, when enabled) are generated before this returns
15
+ #
16
+ # @param details [Hash] occurred_at:, occurred_until:, valid_from:,
17
+ # valid_until: (ISO8601 or natural language) and entities: ([{ name:, type: }],
18
+ # the entities the memory is known to mention); see HTM#remember
19
+ # @param supersedes [Array<Integer>] nodes this memory replaces (kept in its timeline)
20
+ # @param reason [String, nil] why they are wrong now
21
+ # @param transition [String, nil] removed, restored or changed
22
+ # @param status [String] asserted, extracted, inferred or hypothesis
23
+ # @param confidence [Float, String, nil] 0 to 1
24
+ # @param evidence [Array<Integer>] nodes the memory rests on
25
+ # @return [Hash] { node_id:, robot_name:, superseded:, epistemic_status:, confidence:, evidence:,
26
+ # tags:, entities:, occurred_at:, created_at:, content: }
27
+ #
28
+ def remember(content, tags: [], metadata: {}, supersedes: [], reason: nil, transition: nil, status: 'asserted',
29
+ confidence: nil, evidence: [], **details)
30
+ node_id = memory.remember(content, tags:, metadata:, supersedes:, reason:, transition:, status:, confidence:,
31
+ evidence:, **details.compact)
32
+ node = NodeView.find_node!(node_id)
33
+ entry = { node_id:, robot_name: memory.robot_name, superseded: supersedes,
34
+ **NodeView.knowledge(node).except(:conflicts), **NodeView.node_summary(node).except(:id) }
35
+ report(entry) { out.puts "Remembered node #{node_id}", Text.remembered_lines(entry) }
36
+ end
37
+
38
+ # Confirm a memory: upgrade it to asserted on the strength of +evidence+
39
+ #
40
+ # @param node_id [Integer]
41
+ # @param evidence [Array<Integer>] nodes that confirm it
42
+ # @param reason [String, nil]
43
+ # @param confidence [Float, String, nil] its new confidence
44
+ # @return [Hash] { node_id:, epistemic_status:, prior_status:, confidence:, evidence: }
45
+ #
46
+ def confirm(node_id, evidence:, reason: nil, confidence: nil)
47
+ result = memory.confirm(node_id, evidence:, reason:, confidence:)
48
+ report(result) do
49
+ out.puts "Confirmed node #{node_id} (was #{HTM::Epistemics::WORDS.fetch(result[:prior_status])}) " \
50
+ "by #{MemoryCommands.id_list(result[:evidence])}"
51
+ end
52
+ end
53
+
54
+ # Forget nodes by id: soft delete (restorable), or permanently after confirmation
55
+ #
56
+ # @param node_ids [Array<Integer>]
57
+ # @return [Hash, nil] { node_ids:, permanent: }, nil when cancelled
58
+ #
59
+ def forget(node_ids, permanent: nil)
60
+ return cancelled if permanent && !proceed_with?("Permanently delete #{plural(node_ids.size, 'node')}?")
61
+
62
+ soft = !permanent
63
+ node_ids.each { memory.forget(it, soft:, confirm: :confirmed) }
64
+ forgot({ node_ids:, permanent: !soft })
65
+ end
66
+
67
+ # Forget every node whose content contains +text+ (case-insensitive)
68
+ #
69
+ # @return [Hash, nil] { content:, node_ids:, permanent: }, nil when cancelled
70
+ #
71
+ def forget_matching(text, permanent: nil)
72
+ return cancelled if permanent && !proceed_with?("Permanently delete every node containing #{text.inspect}?")
73
+
74
+ soft = !permanent
75
+ forgot({ content: text, node_ids: memory.forget_content(text, soft:, confirm: :confirmed), permanent: !soft })
76
+ end
77
+
78
+ # Forget an entity: soft delete every node mentioning it, after
79
+ # confirmation. `htm restore ID` brings a node back.
80
+ #
81
+ # @param name [String] the entity's name, alias or id
82
+ # @param type [String, nil] entity type, for a name several types share
83
+ # @return [Hash, nil] { entity:, node_ids:, permanent: false }, nil when cancelled
84
+ # @raise [HTM::NotFoundError, HTM::Admin::Error] for an unknown or shared name
85
+ #
86
+ def forget_entity(name, type: nil)
87
+ entity = entity_named(name, type, option: '--entity-type')
88
+ about = brief(entity)
89
+ count = entity.mention_count
90
+ return cancelled if count.positive? && !proceed_with?(EntityLines.forget_question(about, count))
91
+
92
+ forgot({ entity: about, node_ids: memory.forget_entity(entity, confirm: :confirmed), permanent: false })
93
+ end
94
+
95
+ # Restore soft-deleted nodes
96
+ #
97
+ # @return [Hash] { node_ids: }
98
+ # @raise [HTM::ValidationError] when a node is not soft-deleted
99
+ #
100
+ def restore(node_ids)
101
+ node_ids.each { memory.restore(it) }
102
+ report({ node_ids: }) { out.puts "Restored #{plural(node_ids.size, 'node')}: #{node_ids.join(', ')}" }
103
+ end
104
+
105
+ # Soft-deleted nodes, newest deletions first
106
+ #
107
+ # @return [Hash] { count:, nodes: }
108
+ #
109
+ def deleted(limit: 20)
110
+ Admin.connect!
111
+ nodes = NodeView.deleted_entries(limit:)
112
+ report({ count: nodes.length, nodes: }) do
113
+ print_entries(nodes, 'No soft-deleted memories.')
114
+ end
115
+ end
116
+
117
+ # Permanently delete the nodes soft-deleted before +cutoff+, after confirmation
118
+ #
119
+ # @param cutoff [Time]
120
+ # @return [Hash, nil] { older_than:, purged: }, nil when cancelled
121
+ #
122
+ def purge(cutoff)
123
+ return cancelled unless proceed_with?("Permanently delete every memory soft-deleted before #{cutoff}?")
124
+
125
+ purged = memory.purge_deleted(older_than: cutoff, confirm: :confirmed)
126
+ report({ older_than: cutoff.iso8601, purged: }) { out.puts "Purged #{plural(purged, 'node')}." }
127
+ end
128
+
129
+ # Add hierarchical tags to a node (parents are created too)
130
+ #
131
+ # @return [Hash] { node_id:, tags: } with every tag the node now has
132
+ #
133
+ def tag(node_id, tags)
134
+ HTM::InputValidator.tags!(tags)
135
+ node = node_for_tagging(node_id)
136
+ node.add_tags(tags)
137
+ tags_changed(node_id, node.tag_names)
138
+ end
139
+
140
+ # Remove one tag from a node (its parent and child tags stay)
141
+ #
142
+ # @return [Hash] { node_id:, tags: }
143
+ # @raise [HTM::Admin::Error] when the node does not carry +tag+
144
+ #
145
+ def untag(node_id, tag)
146
+ node = node_for_tagging(node_id)
147
+ names = node.tag_names
148
+ raise Admin::Error, "Error: node #{node_id} is not tagged '#{tag}'" unless names.include?(tag)
149
+
150
+ node.remove_tag(tag)
151
+ tags_changed(node_id, names - [tag])
152
+ end
153
+
154
+ private
155
+
156
+ def proceed_with?(question) = confirmed?("#{question} Type 'yes' to confirm: ")
157
+
158
+ def plural(...) = MemoryCommands.plural(...)
159
+
160
+ def forgot(result) = report(result) { out.puts Text.forgot(result) }
161
+
162
+ def node_for_tagging(node_id)
163
+ memory
164
+ NodeView.find_node!(node_id)
165
+ end
166
+
167
+ def tags_changed(node_id, names)
168
+ long_term_memory.clear_cache!
169
+ tags = names.sort
170
+ report({ node_id:, tags: }) { out.puts "Node #{node_id} tags: #{tags.empty? ? '(none)' : tags.join(', ')}" }
171
+ end
172
+ end
173
+ end
174
+ end
175
+ end
@@ -0,0 +1,189 @@
1
+ # frozen_string_literal: true
2
+
3
+ class HTM
4
+ module Admin
5
+ module MemoryCommands
6
+ # The entity commands (htm entities ...): list and describe the
7
+ # entities memory mentions, find the memories about one, and correct
8
+ # entities by hand (link, unlink, merge, unmerge, alias).
9
+ #
10
+ # An entity is named by its name, one of its aliases or its id; the
11
+ # console's type (--type) picks one when entities of several types
12
+ # share the name.
13
+ #
14
+ # @example
15
+ # HTM::Admin::MemoryCommands::Entities.new(json: true).show("Alice Chen")
16
+ # HTM::Admin::MemoryCommands::Entities.new(type: "product").show("Mercury")
17
+ #
18
+ class Entities < Base
19
+ # @param type [String, nil] the entity type of the command (--type): the type of the
20
+ # entities it names, lists (list) or creates (add)
21
+ #
22
+ def initialize(type: nil, **)
23
+ super(**)
24
+ @type = type
25
+ end
26
+
27
+ # The entities memory mentions most (those of the console's type, when it has one)
28
+ #
29
+ # @param limit [Integer] entities at most
30
+ # @param which [Hash] unmentioned: true lists the entities no memory mentions instead, by name
31
+ # @return [Hash] { type:, unmentioned:, count:, entities: }
32
+ # @raise [HTM::Admin::Error] for a type no entity has
33
+ #
34
+ def list(limit: 20, **which)
35
+ entities = NodeView.entities_view(memory.entities(type: EntityCommands.known_type!(@type), limit:, **which))
36
+ report({ type: @type, unmentioned: which[:unmentioned] == true, count: entities.length, entities: }) do
37
+ out.puts EntityLines.table(entities)
38
+ end
39
+ end
40
+
41
+ # Delete an entity that no memory mentions (HTM#delete_entity)
42
+ #
43
+ # @return [Hash] { entity: { id:, name:, type: }, deleted: true }
44
+ # @raise [HTM::EntityError] when memories still mention it or entities are merged into it
45
+ #
46
+ def delete(name)
47
+ entity = entity(name)
48
+ about = brief(entity)
49
+ memory.delete_entity(entity)
50
+ report({ entity: about, deleted: true }) { out.puts "Deleted #{EntityLines.full_label(about)}; no memory mentioned it" }
51
+ end
52
+
53
+ # One entity: its names, when memory mentions it and the entities named with it
54
+ #
55
+ # @return [Hash] the entity view (NodeView.entity_view) with related: [{ id:, name:, type:, weight: }]
56
+ # @raise [HTM::NotFoundError, HTM::Admin::Error] for an unknown or shared name
57
+ #
58
+ def show(name)
59
+ entity = entity(name)
60
+ detail = { **NodeView.entity_view(memory.entity(entity)), related: related_to(entity) }
61
+ report(detail) do
62
+ print_pairs(EntityLines.full_label(detail), EntityLines.pairs(detail))
63
+ out.puts '', 'Mentioned with:', EntityLines.related(detail[:related])
64
+ end
65
+ end
66
+
67
+ # The memories that mention an entity, latest event first
68
+ #
69
+ # @param filters [Hash] as_of: (a moment the memories were true at), timeframe:, limit:
70
+ # @return [Hash] { entity:, as_of:, timeframe:, count:, nodes: }
71
+ #
72
+ def nodes(name, as_of: nil, timeframe: nil, limit: 20)
73
+ entity = entity(name)
74
+ found = memory.entity_nodes(entity, as_of:, timeframe: NodeView.timeframe_input(timeframe), limit:)
75
+ nodes = NodeView.node_summaries(NodeView.nodes_with_tags(found.map(&:id)))
76
+ about = brief(entity)
77
+ count = nodes.length
78
+ report({ entity: about, as_of:, timeframe:, count:, nodes: }) do
79
+ out.puts "#{EntityLines.memories(count)} mentioning #{EntityLines.label(about)}"
80
+ print_entries(nodes, '')
81
+ end
82
+ end
83
+
84
+ # The entities mentioned together with an entity, most shared memories first
85
+ #
86
+ # @return [Hash] { entity:, count:, related: }
87
+ #
88
+ def related(name, limit: 10)
89
+ entity = entity(name)
90
+ related = related_to(entity, limit:)
91
+ about = brief(entity)
92
+ report({ entity: about, count: related.length, related: }) do
93
+ out.puts "Mentioned with #{EntityLines.label(about)}, by memories shared:", EntityLines.related(related)
94
+ end
95
+ end
96
+
97
+ # Record that a node mentions an entity of the console's type (created when memory does not know it)
98
+ #
99
+ # @return [Hash] { node_id:, entity: { id:, name:, type: } }
100
+ # @raise [HTM::Admin::Error] for a type that is not configured
101
+ #
102
+ def add(node_id, name)
103
+ entity = memory.add_entity(node_id, name, type: EntityCommands.type!(@type))
104
+ report({ node_id:, entity: }) { out.puts "Node #{node_id} mentions #{EntityLines.full_label(entity)}" }
105
+ end
106
+
107
+ # Remove an entity from a node: every mention of it there
108
+ #
109
+ # @return [Hash] { node_id:, entity:, removed: } with the number of mentions removed
110
+ #
111
+ def remove(node_id, name)
112
+ entity = entity(name)
113
+ removed = memory.remove_entity(node_id, entity)
114
+ about = brief(entity)
115
+ report({ node_id:, entity: about, removed: }) do
116
+ label = EntityLines.label(about)
117
+ out.puts removed.zero? ? "Node #{node_id} does not mention #{label}" : "Node #{node_id} no longer mentions #{label}"
118
+ end
119
+ end
120
+
121
+ # Merge one entity into another; unmerge undoes it
122
+ #
123
+ # @param from [String] the duplicate
124
+ # @param into [String] the entity that stays
125
+ # @return [Hash] { merged: { id:, name:, type: }, into: { id:, name:, type: } }
126
+ #
127
+ def merge(from, into)
128
+ source = entity(from)
129
+ merged = brief(source)
130
+ target = memory.merge_entities(source, into: entity(into))
131
+ report({ merged:, into: target.slice(:id, :name, :type) }) do
132
+ out.puts "Merged #{EntityLines.full_label(merged)} into #{EntityLines.full_label(target)}",
133
+ " now in #{EntityLines.memories(target[:mention_count])}; undo with: htm entities unmerge #{merged[:id]}"
134
+ end
135
+ end
136
+
137
+ # Undo a merge: the entity stands for itself again
138
+ #
139
+ # @param name [String] the merged entity's own name or id
140
+ # @return [Hash] its entity view
141
+ #
142
+ def unmerge(name)
143
+ entity = NodeView.entity_view(memory.unmerge_entity(merged(name)))
144
+ report(entity) do
145
+ out.puts "#{EntityLines.full_label(entity)} stands for itself again, in #{EntityLines.memories(entity[:mention_count])}"
146
+ end
147
+ end
148
+
149
+ # Record another name for an entity
150
+ #
151
+ # @return [Hash] its entity view
152
+ #
153
+ def alias_entity(name, alias_text)
154
+ entity = NodeView.entity_view(memory.alias_entity(entity(name), alias_text))
155
+ report(entity) do
156
+ out.puts "#{EntityLines.full_label(entity)} is also known as: #{EntityLines.list(entity[:aliases])}"
157
+ end
158
+ end
159
+
160
+ # What memory holds about an entity: its names, counts, the entities
161
+ # named with it and every active memory mentioning it, oldest first
162
+ #
163
+ # @return [Hash] NodeView.entity_report_view
164
+ #
165
+ def about(name)
166
+ held = NodeView.entity_report_view(memory.entity_report(entity(name)))
167
+ report(held) do
168
+ print_pairs("What memory holds about #{EntityLines.full_label(held[:entity])}", EntityLines.report_pairs(held))
169
+ out.puts '', 'Mentioned with:', EntityLines.related(held[:related]), '', 'Memories, oldest first:'
170
+ print_entries(held[:nodes], ' None.')
171
+ end
172
+ end
173
+
174
+ private
175
+
176
+ # The entity +name+ stands for, among those of the console's type when it has one
177
+ def entity(name) = entity_named(name, @type)
178
+
179
+ def related_to(entity, **) = NodeView.related_entities_view(memory.related_entities(entity, **))
180
+
181
+ # What names the merged entity +name+ (see EntityCommands.merged_reference)
182
+ def merged(name)
183
+ memory
184
+ EntityCommands.merged_reference(name)
185
+ end
186
+ end
187
+ end
188
+ end
189
+ end
@@ -0,0 +1,111 @@
1
+ # frozen_string_literal: true
2
+
3
+ class HTM
4
+ module Admin
5
+ module MemoryCommands
6
+ # The lines the entity commands print: each function turns an entity
7
+ # view (as NodeView builds it) into text.
8
+ #
9
+ # @example
10
+ # HTM::Admin::MemoryCommands::EntityLines.label({ name: "Alice Chen", type: "person" })
11
+ # # => "Alice Chen (person)"
12
+ #
13
+ module EntityLines
14
+ # One line of the entity list
15
+ ROW = '%<id>6s %<memories>8s %<type>-14s %<seen>-16s %<name>s'
16
+
17
+ # The list's heading line
18
+ HEADING = Kernel.format(ROW, id: 'ID', memories: 'Memories', type: 'Type', seen: 'Last seen', name: 'Name').freeze
19
+
20
+ module_function
21
+
22
+ # @return [String] "Alice Chen (person)"
23
+ def label(entity) = "#{entity[:name]} (#{entity[:type]})"
24
+
25
+ # @return [String] "Alice Chen (person, #7)"
26
+ def full_label(entity) = "#{entity[:name]} (#{entity[:type]}, ##{entity[:id]})"
27
+
28
+ # @return [String, nil] "Alice Chen (person), Globex (organization)", or nil when there are none
29
+ def names(entities) = (entities.map { label(it) }.join(', ') if entities&.any?)
30
+
31
+ # @return [String] "1 memory", "3 memories"
32
+ def memories(count) = "#{count} #{count == 1 ? 'memory' : 'memories'}"
33
+
34
+ # @return [String, nil] the names joined by commas, or nil when there are none
35
+ def list(names) = (names.join(', ') if names&.any?)
36
+
37
+ # The entity list: a heading line and one line per entity
38
+ #
39
+ # @param entities [Array<Hash>] entity views
40
+ # @return [Array<String>]
41
+ #
42
+ def table(entities)
43
+ return ['No entities.'] if entities.empty?
44
+
45
+ [HEADING, *entities.map { row(it) }]
46
+ end
47
+
48
+ # " 7 12 person 2026-03-01 09:00 Alice Chen (Dr. Chen)"
49
+ def row(entity)
50
+ also = list(entity[:aliases])
51
+ Kernel.format(ROW, id: entity[:id], memories: entity[:mention_count], type: entity[:type],
52
+ seen: MemoryCommands.short_time(entity[:last_seen_at]),
53
+ name: "#{entity[:name]}#{" (#{also})" if also}")
54
+ end
55
+
56
+ # An entity's details as "label" => value pairs, blanks left out
57
+ #
58
+ # @param entity [Hash] an entity view
59
+ # @return [Hash{String => String}]
60
+ #
61
+ def pairs(entity)
62
+ first, last = entity.values_at(:first_seen_at, :last_seen_at)
63
+ {
64
+ 'Also known as' => list(entity[:aliases]), 'Description' => entity[:description],
65
+ 'Mentioned in' => memories(entity[:mention_count]),
66
+ 'First seen' => (MemoryCommands.short_time(first) if first), 'Last seen' => (MemoryCommands.short_time(last) if last)
67
+ }.compact
68
+ end
69
+
70
+ # A report's details: the entity's, then what is stored about it
71
+ #
72
+ # @param report [Hash] an entity report view
73
+ # @return [Hash{String => String}]
74
+ #
75
+ def report_pairs(report)
76
+ active, deleted, mentions = report[:counts].values_at(:nodes, :deleted_nodes, :mentions)
77
+ held = "#{active} active#{", #{deleted} soft-deleted (stored until purged; see htm deleted)" if deleted.positive?}"
78
+ pairs(report[:entity]).except('Mentioned in').merge('Memories' => held, 'Mentions' => mentions.to_s)
79
+ end
80
+
81
+ # The entities named with an entity: " 4 Globex (organization)" each
82
+ #
83
+ # @param related [Array<Hash>] { name:, type:, weight: }
84
+ # @return [Array<String>]
85
+ #
86
+ def related(related)
87
+ return [' None.'] if related.empty?
88
+
89
+ related.map { Kernel.format('%<weight>8d %<label>s', weight: it[:weight], label: label(it)) }
90
+ end
91
+
92
+ # The entity lines under a node's heading: who it mentions, and (in a report) under which names
93
+ #
94
+ # @param entry [Hash] a node or result entry
95
+ # @return [Array<String>]
96
+ #
97
+ def entry_lines(entry)
98
+ mentions = names(entry[:entities])
99
+ written = list(entry[:mentioned_as])
100
+ [(" entities: #{mentions}" if mentions), (" as: #{written}" if written)].compact
101
+ end
102
+
103
+ # "Soft delete 3 nodes mentioning Alice Chen (person)? `htm restore ID` brings each one back."
104
+ def forget_question(entity, count)
105
+ "Soft delete #{MemoryCommands.plural(count, 'node')} mentioning #{label(entity)}? " \
106
+ '`htm restore ID` brings each one back.'
107
+ end
108
+ end
109
+ end
110
+ end
111
+ end
@@ -0,0 +1,205 @@
1
+ # frozen_string_literal: true
2
+
3
+ class HTM
4
+ module Admin
5
+ module MemoryCommands
6
+ # Commands that read memory: recall (search), show, related,
7
+ # propositions, stats and the robots sharing memory
8
+ #
9
+ # @example
10
+ # HTM::Admin::MemoryCommands::Search.new(json: true).recall("pgvector", strategy: "hybrid")
11
+ #
12
+ class Search < Base
13
+ STRATEGIES = %w[vector fulltext hybrid].freeze
14
+
15
+ # @return [Symbol] +strategy+ as a Symbol
16
+ # @raise [ArgumentError] unless it is one of STRATEGIES
17
+ def self.strategy!(strategy)
18
+ raise ArgumentError, "strategy must be one of: #{STRATEGIES.join(', ')}" unless STRATEGIES.include?(strategy.to_s)
19
+
20
+ strategy.to_sym
21
+ end
22
+
23
+ # One line of the robots table
24
+ ROBOT_ROW = '%<id>6s %<nodes>7s %<active>-16s %<name>s'
25
+
26
+ # Search memory. Found memories join the robot's working memory.
27
+ #
28
+ # @param query [String]
29
+ # @param strategy [String] vector, fulltext or hybrid
30
+ # @param filters [Hash] limit:, timeframe:, metadata:, query_tags:, with_relevance:,
31
+ # time_axis: (event or recorded), as_of: (a moment the memories were true at),
32
+ # include_history: (follow each result with the states it replaced),
33
+ # status: (epistemic statuses to keep), min_confidence:, and the entity filters
34
+ # entities: (names, aliases or ids), entity_match: (any or all), entity_type:
35
+ # @return [Hash] { query:, strategy:, robot_name:, count:, results: }
36
+ # @raise [ArgumentError] for an unknown strategy or a bad timeframe
37
+ # @raise [HTM::Admin::Error] for an entity_type no entity has
38
+ #
39
+ def recall(query, strategy: 'hybrid', limit: 10, **filters)
40
+ Search.strategy!(strategy)
41
+ # memory connects before the filters' entity type is looked up
42
+ rows = memory.recall(query, **EntityCommands.typed(NodeView.recall_options(limit:, strategy:, **filters)))
43
+ results = NodeView.recall_entries(rows)
44
+ count = results.length
45
+ report({ query:, strategy:, robot_name: memory.robot_name, count:, results: }) do
46
+ out.puts "#{count} #{count == 1 ? 'memory' : 'memories'} for #{query.inspect} (#{strategy})"
47
+ print_entries(results, '')
48
+ end
49
+ end
50
+
51
+ # The history of a memory: its states and the changes between them
52
+ #
53
+ # @param subject [String] a node id, or a query whose top matches seed the histories
54
+ # @param strategy [String] vector, fulltext or hybrid (for a query)
55
+ # @param limit [Integer] matches to seed from
56
+ # @param depth [Integer] links to follow at most
57
+ # @return [Hash] { subject:, count:, histories: } (see HTM#timeline)
58
+ # @raise [ArgumentError] for an unknown strategy
59
+ # @raise [HTM::NotFoundError] for an unknown node id
60
+ #
61
+ def timeline(subject, strategy: 'fulltext', limit: 5, depth: HTM::Timeline::MAX_DEPTH)
62
+ histories = memory.timeline(subject, strategy: Search.strategy!(strategy), limit:, max_depth: depth)
63
+ report_histories({ subject: }, histories, "No memories for #{subject.inspect}")
64
+ end
65
+
66
+ # The history of an entity: its latest memories and the states they replaced, in time order
67
+ #
68
+ # @param name [String] the entity's name, alias or id
69
+ # @param type [String, nil] its type, for a name several types share
70
+ # @param depth [Integer] links to follow at most
71
+ # @return [Hash] { entity: { id:, name:, type: }, count:, histories: } (see HTM#timeline)
72
+ # @raise [HTM::NotFoundError, HTM::Admin::Error] for an unknown or shared name
73
+ #
74
+ def entity_timeline(name, type: nil, depth: HTM::Timeline::MAX_DEPTH)
75
+ entity = entity_named(name, type, option: '--entity-type')
76
+ about = brief(entity)
77
+ report_histories({ entity: about }, memory.timeline(entity:, max_depth: depth),
78
+ "No active memory mentions #{EntityLines.label(about)}")
79
+ end
80
+
81
+ # When was +query+ first mentioned, and can memory establish it?
82
+ #
83
+ # @param query [String]
84
+ # @param strategy [String] vector, fulltext or hybrid
85
+ # @param limit [Integer] matches to judge
86
+ # @param timeframe [String, nil] as for recall
87
+ # @return [Hash] see HTM#first_mention, times as ISO8601
88
+ # @raise [ArgumentError] for an unknown strategy
89
+ #
90
+ def first_mention(query, strategy: 'fulltext', limit: 50, timeframe: nil)
91
+ answer = NodeView.first_mention_view(
92
+ memory.first_mention(query, strategy: Search.strategy!(strategy), limit:, timeframe: NodeView.timeframe_input(timeframe))
93
+ )
94
+ report(answer) { out.puts Text.first_mention_lines(answer) }
95
+ end
96
+
97
+ # Print one node in full, soft-deleted or not
98
+ #
99
+ # @return [Hash] the node's details (NodeView.node_detail) and source_file
100
+ # @raise [HTM::NotFoundError] when there is no such node
101
+ #
102
+ def show(node_id)
103
+ Admin.connect!
104
+ node = NodeView.find_node!(node_id)
105
+ source_id = node.source_id
106
+ source = source_id && HTM::Models::FileSource[source_id]
107
+ detail = { **NodeView.node_detail(node), source_file: source&.file_path }
108
+ report(detail) do
109
+ print_pairs("Node #{detail[:id]}", Text.detail_pairs(detail))
110
+ out.puts '', detail[:content]
111
+ end
112
+ end
113
+
114
+ # Nodes linked to +node_id+ in the relationship graph, strongest first
115
+ #
116
+ # @return [Hash] { node_id:, count:, related: }
117
+ #
118
+ def related(node_id, limit: 10, min_weight: 0.0)
119
+ Admin.connect!
120
+ NodeView.find_node!(node_id)
121
+ entries = NodeView.related_entries(node_id, limit:, min_weight:)
122
+ report({ node_id:, count: entries.length, related: entries }) do
123
+ out.puts "Memories related to node #{node_id}:"
124
+ print_entries(entries, 'None.')
125
+ end
126
+ end
127
+
128
+ # Break +text+ into atomic propositions with the configured LLM
129
+ #
130
+ # @return [Hash] { count:, propositions:, node_ids: [] }
131
+ #
132
+ def propositions(text) = report_propositions(HTM.extract_propositions(text), [])
133
+
134
+ # Break +text+ into atomic propositions and store each one as its own memory
135
+ #
136
+ # @return [Hash] { count:, propositions:, node_ids: }
137
+ #
138
+ def remember_propositions(text)
139
+ found = HTM.extract_propositions(text)
140
+ report_propositions(found, found.map { memory.remember(it, status: :extracted) })
141
+ end
142
+
143
+ # Counts across all of memory (NodeView.memory_statistics), with the
144
+ # entity counts (EntityCommands.counts) as entities:
145
+ #
146
+ # @return [Hash]
147
+ #
148
+ def stats
149
+ Admin.connect!
150
+ statistics = { **NodeView.memory_statistics, entities: EntityCommands.counts }
151
+ report(statistics) do
152
+ statistics.each { |section, counts| print_pairs(section.to_s.capitalize, labelled(counts)) }
153
+ end
154
+ end
155
+
156
+ # The robots sharing memory, most recently active first
157
+ #
158
+ # @return [Hash] { count:, robots: }
159
+ #
160
+ def robots(limit: 50)
161
+ Admin.connect!
162
+ robots = NodeView.robot_entries(limit:)
163
+ report({ count: robots.length, robots: }) do
164
+ out.puts format(ROBOT_ROW, id: 'ID', nodes: 'Nodes', active: 'Last active', name: 'Name')
165
+ robots.each { out.puts robot_line(it) }
166
+ end
167
+ end
168
+
169
+ private
170
+
171
+ # Report HTM#timeline's histories under +subject+ ({ subject: } or { entity: }), or +none+ without any
172
+ def report_histories(subject, histories, none)
173
+ histories = NodeView.timeline_view(histories)
174
+ count = histories.length
175
+ report({ **subject, count:, histories: }) do
176
+ out.puts none if count.zero?
177
+ histories.each_with_index { |history, idx| print_history(history, idx + 1) }
178
+ end
179
+ end
180
+
181
+ def report_propositions(found, node_ids)
182
+ report({ count: found.length, propositions: found, node_ids: }) do
183
+ found.each_with_index { |proposition, idx| out.puts Text.proposition_line(proposition, node_ids[idx]) }
184
+ end
185
+ end
186
+
187
+ # Statistic names as labels: "with_tags" => "with tags"; a breakdown as "person 3, organization 2"
188
+ def labelled(counts)
189
+ counts.to_h { |key, value| [key.to_s.tr('_', ' '), value.is_a?(Hash) ? EntityCommands.type_list(value) : value] }
190
+ end
191
+
192
+ def robot_line(robot)
193
+ Kernel.format(ROBOT_ROW, id: robot[:id], nodes: robot[:node_count],
194
+ active: MemoryCommands.short_time(robot[:last_active]), name: robot[:name])
195
+ end
196
+
197
+ def print_history(history, number)
198
+ out.puts '' if number > 1
199
+ out.puts "History #{number} (#{MemoryCommands.plural(history[:node_ids].size, 'state')})"
200
+ history[:entries].each { out.puts " #{Text.timeline_line(it)}" }
201
+ end
202
+ end
203
+ end
204
+ end
205
+ end