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,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ class HTM
4
+ module Admin
5
+ module MemoryCommands
6
+ # Commands that search by tag: list and fuzzy-search tags, the most
7
+ # used tags and tags used together, and the memories carrying tags
8
+ #
9
+ # @example
10
+ # HTM::Admin::MemoryCommands::TagSearch.new.tagged(%w[database:postgresql], match: "all")
11
+ #
12
+ class TagSearch < Base
13
+ MATCHES = %w[any all].freeze
14
+
15
+ # Every tag (or those under +prefix+) with how many memories carry it
16
+ #
17
+ # @return [Hash] { prefix:, count:, tags: }
18
+ #
19
+ def list(prefix = nil)
20
+ Admin.connect!
21
+ tags = TagCommands.scope(prefix).order(:name).all
22
+ counts = HTM::Models::NodeTag.where(tag_id: tags.map(&:id)).group_and_count(:tag_id).to_hash(:tag_id, :count)
23
+ entries = tags.map { { name: it.name, node_count: counts.fetch(it.id, 0) } }
24
+ report({ prefix:, count: entries.length, tags: entries }) { print_counted(entries, :node_count) }
25
+ end
26
+
27
+ # Tags whose names resemble +query+ (typo-tolerant trigram match)
28
+ #
29
+ # @return [Hash] { query:, count:, tags: }
30
+ #
31
+ def search(query, limit: 20, min_similarity: 0.3)
32
+ rows = long_term_memory.search_tags(query, limit:, min_similarity:)
33
+ tags = rows.map { { name: it[:name], similarity: it[:similarity].to_f.round(3) } }
34
+ report({ query:, count: tags.length, tags: }) { print_counted(tags, :similarity) }
35
+ end
36
+
37
+ # The most used tags, optionally counting only memories from +timeframe+
38
+ #
39
+ # @return [Hash] { timeframe:, count:, tags: }
40
+ #
41
+ def popular(limit: 20, timeframe: nil)
42
+ tags = long_term_memory.popular_tags(limit:, timeframe: NodeView.timeframe_span(timeframe))
43
+ report({ timeframe:, count: tags.length, tags: }) { print_counted(tags, :usage_count) }
44
+ end
45
+
46
+ # Pairs of tags used together on the same memories, most shared first
47
+ #
48
+ # @return [Hash] { count:, relationships: }
49
+ #
50
+ def pairs(min_shared_nodes: 2, limit: 50)
51
+ rows = long_term_memory.topic_relationships(min_shared_nodes:, limit:)
52
+ pairs = rows.map { { topic1: it['topic1'], topic2: it['topic2'], shared_nodes: it['shared_nodes'].to_i } }
53
+ report({ count: pairs.length, relationships: pairs }) do
54
+ out.puts 'No tags share enough memories.' if pairs.empty?
55
+ pairs.each { out.puts format('%<shared>6d %<topic1>s + %<topic2>s', shared: it[:shared_nodes], **it) }
56
+ end
57
+ end
58
+
59
+ # Memories carrying any (or all) of +tags+, ranked by relevance
60
+ #
61
+ # @return [Hash] { tags:, match:, count:, results: }
62
+ # @raise [ArgumentError] for an unknown match
63
+ #
64
+ def tagged(tags, match: 'any', limit: 20, timeframe: nil)
65
+ raise ArgumentError, "match must be one of: #{MATCHES.join(', ')}" unless MATCHES.include?(match)
66
+
67
+ rows = long_term_memory.search_by_tags(tags:, match: match.to_sym, limit:,
68
+ filters: SearchFilters.build(timeframe: NodeView.normalized_timeframe(timeframe)))
69
+ results = NodeView.recall_entries(rows)
70
+ report({ tags:, match:, count: results.length, results: }) { print_entries(results, 'No memories carry those tags.') }
71
+ end
72
+
73
+ # Memories under a topic: tags starting with +topic+, exactly +topic+,
74
+ # or (fuzzy) tags resembling it
75
+ #
76
+ # @param mode [Hash] exact: or fuzzy:
77
+ # @return [Hash] { topic:, count:, results: }
78
+ #
79
+ def topic(topic, limit: 20, min_similarity: 0.3, **mode)
80
+ rows = long_term_memory.nodes_by_topic(topic, **mode, min_similarity:, limit:)
81
+ ids = rows.map { it[:id] || it['id'] }
82
+ nodes = HTM::Models::Node.where(id: ids).eager(:tags).all.to_h { [it.id, it] }
83
+ results = NodeView.node_summaries(ids.filter_map { nodes[it] })
84
+ report({ topic:, count: results.length, results: }) { print_entries(results, "No memories under #{topic}.") }
85
+ end
86
+
87
+ private
88
+
89
+ # One "value name" line per entry
90
+ def print_counted(entries, key)
91
+ return out.puts('No tags.') if entries.empty?
92
+
93
+ entries.each { out.puts format('%<value>8s %<name>s', value: it[key], name: it[:name]) }
94
+ end
95
+ end
96
+ end
97
+ end
98
+ end
@@ -0,0 +1,166 @@
1
+ # frozen_string_literal: true
2
+
3
+ class HTM
4
+ module Admin
5
+ module MemoryCommands
6
+ # The lines the memory commands print: each function turns a result
7
+ # hash (as NodeView builds it) into text, so the Console classes only
8
+ # decide what to print and where.
9
+ #
10
+ # @example
11
+ # HTM::Admin::MemoryCommands::Text.entry_lines({ tags: ["db"], evidence: [3] })
12
+ # # => [" tags: db", " from: #3"]
13
+ #
14
+ module Text
15
+ # The verb and closing hint of a forget report, by whether it was permanent
16
+ FORGOT = { true => ['Permanently deleted', ''], false => ['Forgot', ' (restore with: htm restore ID)'] }.freeze
17
+
18
+ module_function
19
+
20
+ # @return [String, nil] "#12, #15", or nil when there are no ids
21
+ def ids(ids) = (MemoryCommands.id_list(ids) if ids&.any?)
22
+
23
+ # @return [String, nil] "label: #12, #15", or nil when there are no ids
24
+ def id_line(label, ids)
25
+ list = ids(ids)
26
+ "#{label}: #{list}" if list
27
+ end
28
+
29
+ # How the memory in +entry+ is known (see MemoryCommands.knowledge)
30
+ def knowledge(entry) = MemoryCommands.knowledge(*entry.values_at(:epistemic_status, :confidence))
31
+
32
+ # The lines under a node's heading: its tags, entities, history note, evidence and conflicts
33
+ #
34
+ # @param entry [Hash] a node or result entry
35
+ # @return [Array<String>]
36
+ #
37
+ def entry_lines(entry)
38
+ tags, note, evidence, conflicts = entry.values_at(:tags, :history_note, :evidence, :conflicts)
39
+ [(" tags: #{tags.join(', ')}" if tags&.any?), *EntityLines.entry_lines(entry), (" #{note}" if note),
40
+ id_line(' from', evidence), id_line(' conflicts with', conflicts)].compact
41
+ end
42
+
43
+ # The lines after "Remembered node N": what it replaced, how it is known, when it happened
44
+ #
45
+ # @param entry [Hash] Edit#remember's result
46
+ # @return [Array<String>]
47
+ #
48
+ def remembered_lines(entry)
49
+ superseded, status, confidence, evidence, occurred, created, tags =
50
+ entry.values_at(:superseded, :epistemic_status, :confidence, :evidence, :occurred_at, :created_at, :tags)
51
+ [id_line(' supersedes', superseded),
52
+ (" known: #{MemoryCommands.knowledge(status, confidence)}" if status != 'asserted' || confidence),
53
+ id_line(' from', evidence),
54
+ (" occurred: #{MemoryCommands.short_time(occurred)}" if occurred != created),
55
+ (" tags: #{tags.join(', ')}" if tags&.any?), *EntityLines.entry_lines(entry).map { it[2..] }].compact
56
+ end
57
+
58
+ # "Forgot 2 nodes: 4, 5 (restore with: htm restore ID)"
59
+ #
60
+ # @param result [Hash] { node_ids:, permanent: }, with entity: ({ name:, type: }) when an entity was forgotten
61
+ # @return [String]
62
+ #
63
+ def forgot(result)
64
+ node_ids, permanent, entity = result.values_at(:node_ids, :permanent, :entity)
65
+ verb, hint = FORGOT.fetch(permanent)
66
+ about = entity ? " mentioning #{EntityLines.label(entity)}" : ''
67
+ return "#{verb} 0 nodes#{about}." if node_ids.empty?
68
+
69
+ "#{verb} #{MemoryCommands.plural(node_ids.size, 'node')}#{about}: #{node_ids.join(', ')}#{hint}"
70
+ end
71
+
72
+ # A first-mention answer (NodeView.first_mention_view) as lines
73
+ #
74
+ # @return [Array<String>]
75
+ #
76
+ def first_mention_lines(answer)
77
+ matches, topic, established, direct, earlier, known =
78
+ answer.values_at(:matches, :topic, :established, :earliest_direct, :earlier_indirect, :earliest_known)
79
+ head = "#{matches} #{matches == 1 ? 'memory' : 'memories'} for #{topic.inspect}"
80
+ return [head, 'Nothing in memory mentions it.'] if matches.zero?
81
+
82
+ [head, established ? 'First mention established:' : 'First mention NOT established.',
83
+ direct ? " earliest direct: #{mention_line(direct)}" : ' no direct evidence',
84
+ *earlier.map { " earlier indirect: #{mention_line(it)}" },
85
+ (" earliest known: #{MemoryCommands.short_time(known)}" unless established)].compact
86
+ end
87
+
88
+ # "2026-03-01 09:00 [12] stated content"
89
+ def mention_line(entry)
90
+ at = MemoryCommands.short_time(entry[:at])
91
+ at = "~#{at}" if entry[:time_source] == 'inferred'
92
+ evidence = ids(entry[:evidence])
93
+ from = evidence ? " (from #{evidence})" : ''
94
+ "#{at} [#{entry[:node_id]}] #{knowledge(entry)}#{from} #{MemoryCommands.preview(entry[:content])}"
95
+ end
96
+
97
+ # "2026-03-01 09:00 [10] superseded content" or
98
+ # "2026-06-01 09:00 -> #12 supersedes #10 (changed): reason"
99
+ def timeline_line(entry)
100
+ at = MemoryCommands.short_time(entry[:at])
101
+ return "#{at} #{state_line(entry)}" if entry[:type] == 'state'
102
+
103
+ transition, reason = entry.values_at(:transition, :reason)
104
+ "#{at} -> #{link_phrase(entry)}#{" (#{transition})" if transition}#{": #{reason}" if reason}"
105
+ end
106
+
107
+ # "[10] superseded stated content"
108
+ def state_line(entry)
109
+ "[#{entry[:node_id]}] #{entry[:status].ljust(10)} #{knowledge(entry)} " \
110
+ "#{MemoryCommands.preview(entry[:content])}"
111
+ end
112
+
113
+ # "#12 supersedes #10", "#10 merged into #12", "#10 archived into digest #12"
114
+ def link_phrase(entry)
115
+ newer, older = entry.values_at(:node_id, :replaces)
116
+ case entry[:kind]
117
+ when 'supersedes' then "##{newer} supersedes ##{older}"
118
+ when 'merged_into' then "##{older} merged into ##{newer}"
119
+ else "##{older} archived into digest ##{newer}"
120
+ end
121
+ end
122
+
123
+ # "#12 supersedes #10 (changed: moved); ..."
124
+ def link_lines(links)
125
+ links.map do |link|
126
+ extra = [link[:transition], link[:reason]].compact.join(': ')
127
+ "##{link[:from]} #{link[:kind]} ##{link[:to]}#{" (#{extra})" unless extra.empty?}"
128
+ end.join('; ')
129
+ end
130
+
131
+ # A node's details (Search#show) as "label" => value pairs, blanks left out
132
+ #
133
+ # @return [Hash{String => Object}]
134
+ #
135
+ def detail_pairs(detail)
136
+ dimension, file, links = detail.values_at(:embedding_dimension, :source_file, :links)
137
+ {
138
+ 'Occurred' => span(*detail.values_at(:occurred_at, :occurred_until)),
139
+ 'Valid' => validity(detail), 'Time source' => detail[:time_source],
140
+ 'Created' => detail[:created_at], 'Updated' => detail[:updated_at],
141
+ 'Last accessed' => detail[:last_accessed], 'Access count' => detail[:access_count],
142
+ 'Tokens' => detail[:token_count], 'Embedding' => dimension ? "#{dimension} dimensions" : 'none',
143
+ 'Proposition' => detail[:proposition] ? 'yes' : 'no',
144
+ 'Source' => file && "#{file} (chunk #{detail[:chunk_position]})",
145
+ 'Deleted' => detail[:deleted_at], 'Status' => detail[:status], 'Known' => knowledge(detail),
146
+ 'Evidence' => ids(detail[:evidence]), 'Conflicts' => ids(detail[:conflicts]),
147
+ 'Links' => (link_lines(links) if links&.any?), 'Tags' => detail[:tags].join(', '),
148
+ 'Entities' => EntityLines.names(detail[:entities]),
149
+ 'Metadata' => detail[:metadata].to_json
150
+ }.compact
151
+ end
152
+
153
+ # "[12] proposition" for a stored proposition, "- proposition" otherwise
154
+ def proposition_line(proposition, node_id) = "#{node_id ? "[#{node_id}] " : '- '}#{proposition}"
155
+
156
+ def span(from, to) = to ? "#{from} .. #{to}" : from
157
+
158
+ # "from .. until" when the node states a validity window, else nil
159
+ def validity(detail)
160
+ from, to = detail.values_at(:valid_from, :valid_until)
161
+ "#{from || 'occurred_at'} .. #{to || 'now'}" if from || to
162
+ end
163
+ end
164
+ end
165
+ end
166
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ class HTM
4
+ module Admin
5
+ module MemoryCommands
6
+ # Commands on a robot's working memory: list it, assemble it into an
7
+ # LLM context, clear it. The memory is reloaded from the database, so
8
+ # it is the context the robot built up in earlier runs.
9
+ #
10
+ # @example
11
+ # HTM::Admin::MemoryCommands::WorkingMemory.new(robot: "coder").context(strategy: "recent")
12
+ #
13
+ class WorkingMemory < Base
14
+ STRATEGIES = %w[recent frequent balanced].freeze
15
+
16
+ # The robot's working memory entries, most recently remembered first
17
+ #
18
+ # @return [Hash] { robot_name:, count:, working_memory: }
19
+ #
20
+ def list
21
+ robot_id = memory.robot_id
22
+ entries = NodeView.working_memory_entries(HTM::Models::Robot[robot_id])
23
+ count = entries.length
24
+ name = memory.robot_name
25
+ report({ robot_name: name, count:, working_memory: entries }) do
26
+ out.puts "Working memory of #{name}: #{MemoryCommands.plural(count, 'node')}"
27
+ print_entries(entries, '')
28
+ end
29
+ end
30
+
31
+ # The working memory as one context string for an LLM prompt; text
32
+ # output is the context alone, ready to pipe
33
+ #
34
+ # @param strategy [String] recent, frequent or balanced
35
+ # @param max_tokens [Integer, nil] token budget (the working memory size when nil)
36
+ # @return [Hash] { robot_name:, strategy:, node_count:, token_count:, context: }
37
+ # @raise [ArgumentError] for an unknown strategy
38
+ #
39
+ def context(strategy: 'balanced', max_tokens: nil)
40
+ raise ArgumentError, "strategy must be one of: #{STRATEGIES.join(', ')}" unless STRATEGIES.include?(strategy)
41
+
42
+ working_memory = restored
43
+ text = working_memory.assemble_context(**{ strategy: strategy.to_sym, max_tokens: }.compact)
44
+ data = { robot_name: memory.robot_name, strategy:, node_count: working_memory.node_count,
45
+ token_count: HTM.count_tokens(text), context: text }
46
+ report(data) { out.puts text }
47
+ end
48
+
49
+ # Clear the robot's working memory; the memories stay in long-term memory
50
+ #
51
+ # @return [Hash] { robot_name:, cleared: }
52
+ #
53
+ def clear
54
+ cleared = memory.clear_working_memory
55
+ name = memory.robot_name
56
+ report({ robot_name: name, cleared: }) do
57
+ out.puts "Cleared #{MemoryCommands.plural(cleared, 'node')} from #{name}'s working memory."
58
+ end
59
+ end
60
+
61
+ private
62
+
63
+ def restored
64
+ working_memory = memory.working_memory
65
+ working_memory.restore(memory.robot_id)
66
+ working_memory
67
+ end
68
+ end
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,196 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'logger'
5
+ require 'htm/node_view'
6
+
7
+ class HTM
8
+ module Admin
9
+ # The commands that work on memory itself from the command line: recall,
10
+ # remember, show, forget, restore, tag, the working memory, tag searches
11
+ # and entities (htm recall, htm remember, htm wm ..., htm tags search,
12
+ # htm entities ..., ...).
13
+ #
14
+ # The module functions parse command-line input; the Console classes
15
+ # under it run the commands against a terminal and a robot's memory and
16
+ # print text, or JSON with json: true.
17
+ module MemoryCommands
18
+ # The robot the command line remembers and recalls as, unless --robot
19
+ # or HTM_ROBOT_NAME names another
20
+ DEFAULT_ROBOT = 'htm_cli'
21
+
22
+ # Characters of content a result shows unless --full
23
+ PREVIEW_LENGTH = 300
24
+
25
+ module_function
26
+
27
+ # @return [String] +name+, else HTM_ROBOT_NAME, else DEFAULT_ROBOT
28
+ def robot_name(name = nil) = [name, ENV.fetch('HTM_ROBOT_NAME', nil), DEFAULT_ROBOT].compact.first
29
+
30
+ # Send HTM's and RubyLLM's logging to $stderr so it never mixes with
31
+ # a command's output: warnings only unless +level+ says otherwise
32
+ def log_to_stderr!(level = Logger::WARN)
33
+ logger = Logger.new($stderr, level:)
34
+ logger.formatter = proc { |severity, _time, _progname, msg| "#{severity}: #{msg}\n" }
35
+ HTM.configure { it.logger = logger }
36
+ RubyLLM.config.logger = logger if defined?(RubyLLM)
37
+ logger
38
+ end
39
+
40
+ # Metadata from --metadata key:value pairs. A value that reads as JSON
41
+ # (2, true, null, "x", [1]) becomes that value, so it matches the type
42
+ # stored in the node; anything else stays a string.
43
+ #
44
+ # @param pairs [Hash{String => String}, nil]
45
+ # @return [Hash{String => Object}]
46
+ #
47
+ def parse_metadata(pairs) = pairs.to_h.transform_values { json_value(it) }
48
+
49
+ def json_value(text)
50
+ JSON.parse(text)
51
+ rescue JSON::ParserError
52
+ text
53
+ end
54
+
55
+ # The text a command works on: its words joined by spaces, or +input+
56
+ # (stdin) when there are none or the only one is "-"
57
+ #
58
+ # @raise [HTM::Admin::Error] when there is no text
59
+ #
60
+ def read_text(words, input: $stdin)
61
+ text = words.empty? || words == ['-'] ? read_input(input) : words.join(' ')
62
+ text = text.to_s.strip
63
+ raise Admin::Error, 'Error: no text given (pass it as arguments or on stdin)' if text.empty?
64
+
65
+ text
66
+ end
67
+
68
+ def read_input(input) = input.tty? ? nil : input.read
69
+
70
+ # @return [Time] the purge cutoff: +before+ (ISO8601) when given, else +days+ ago
71
+ # @raise [ArgumentError] for an unparseable +before+
72
+ def cutoff(days:, before: nil) = before ? Time.parse(before) : Time.now - (days.to_i * 86_400)
73
+
74
+ # @return [String] +content+ on one line, cut to +length+ characters
75
+ def preview(content, length = PREVIEW_LENGTH)
76
+ text = content.to_s.gsub(/\s+/, ' ').strip
77
+ text.length > length ? "#{text[0, length]}..." : text
78
+ end
79
+
80
+ # @return [String] "3 nodes", "1 node"
81
+ def plural(count, noun) = "#{count} #{noun}#{'s' unless count == 1}"
82
+
83
+ # @return [String] an ISO8601 time as "YYYY-MM-DD HH:MM", or "-"
84
+ def short_time(iso) = iso ? iso.to_s[0, 16].tr('T', ' ') : '-'
85
+
86
+ # "#12, #15"
87
+ def id_list(ids) = Array(ids).map { "##{it}" }.join(', ')
88
+
89
+ # How a memory is known, as printed: "stated", "inferred 0.60"; nil without a status
90
+ def knowledge(status, confidence)
91
+ return unless status
92
+
93
+ name = status.to_s
94
+ word = HTM::Epistemics::WORDS.fetch(name, name)
95
+ confidence ? Kernel.format('%<word>s %<confidence>.2f', word:, confidence:) : word
96
+ end
97
+
98
+ # The memory commands' shared terminal: the robot's HTM, JSON or text
99
+ # output, and how a node or result is printed
100
+ class Base < Admin::Console
101
+ # @param robot [String, nil] robot name (see MemoryCommands.robot_name)
102
+ # @param json [Boolean, nil] print JSON instead of text
103
+ # @param full [Boolean, nil] print whole contents instead of previews
104
+ # @param memory [HTM, nil] the memory to use (a test's); built from +robot+ when nil
105
+ #
106
+ def initialize(robot: nil, json: nil, full: nil, memory: nil, **)
107
+ super(**)
108
+ @robot = robot
109
+ @json = json
110
+ @full = full
111
+ @memory = memory
112
+ end
113
+
114
+ private
115
+
116
+ # Confirmation prompts go to $stderr under --json so stdout stays JSON
117
+ def prompt_out = @json ? $stderr : out
118
+
119
+ def cancelled = Admin.cancelled(prompt_out)
120
+
121
+ # @return [HTM] the robot's memory
122
+ def memory
123
+ @memory ||= begin
124
+ Admin.connect!
125
+ HTM.new(robot_name: MemoryCommands.robot_name(@robot))
126
+ end
127
+ end
128
+
129
+ def long_term_memory = memory.long_term_memory
130
+
131
+ # The entity a command-line NAME (a name, an alias or an id) stands for
132
+ #
133
+ # @param type [String, nil] entity type, for a name several types share
134
+ # @param option [String] the command's option that takes the type
135
+ # @return [HTM::Models::Entity]
136
+ # @raise [HTM::NotFoundError, HTM::Admin::Error] for an unknown or shared name
137
+ def entity_named(name, type = nil, **option)
138
+ memory
139
+ EntityCommands.find(name, type, **option)
140
+ end
141
+
142
+ # @return [Hash] +entity+ as { id:, name:, type: }
143
+ def brief(entity) = HTM::EntityMemory::Facts.brief(entity)
144
+
145
+ # Print +data+ as JSON, or run the block to print it as text
146
+ #
147
+ # @return [Hash] +data+
148
+ #
149
+ def report(data)
150
+ @json ? out.puts(JSON.pretty_generate(data)) : yield
151
+ data
152
+ end
153
+
154
+ # Print each entry, or +empty+ when there are none
155
+ def print_entries(entries, empty)
156
+ return out.puts(empty) if entries.empty?
157
+
158
+ entries.each { print_entry(it) }
159
+ end
160
+
161
+ # One node or result: a heading line, its tags and its content
162
+ def print_entry(entry)
163
+ out.puts
164
+ out.puts entry_heading(entry), Text.entry_lines(entry), content_lines(entry[:content])
165
+ end
166
+
167
+ def entry_heading(entry)
168
+ scores = entry.slice(:score, :relevance, :weight, :remember_count).compact.map { |key, value| "#{key} #{value}" }
169
+ knowledge = Text.knowledge(entry)
170
+ ["[#{entry[:id]}]", MemoryCommands.short_time(entry[:occurred_at] || entry[:created_at]), knowledge, *scores]
171
+ .compact.join(' ')
172
+ end
173
+
174
+ def content_lines(content)
175
+ text = @full ? content.to_s : MemoryCommands.preview(content)
176
+ text.lines.map { " #{it.chomp}" }
177
+ end
178
+
179
+ # Print +pairs+ as aligned "label: value" lines under +title+
180
+ def print_pairs(title, pairs)
181
+ out.puts title
182
+ width = pairs.keys.map(&:length).max.to_i
183
+ pairs.each { |label, value| out.puts " #{label.ljust(width)} #{value}" }
184
+ end
185
+ end
186
+ end
187
+ end
188
+ end
189
+
190
+ require_relative 'memory_commands/text'
191
+ require_relative 'memory_commands/entity_lines'
192
+ require_relative 'memory_commands/search'
193
+ require_relative 'memory_commands/edit'
194
+ require_relative 'memory_commands/working_memory'
195
+ require_relative 'memory_commands/tag_search'
196
+ require_relative 'memory_commands/entities'