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,313 @@
1
+ # frozen_string_literal: true
2
+
3
+ class HTM
4
+ module Admin
5
+ # `htm entities graph`: write an interactive force-directed graph of
6
+ # entities as one self-contained, dark-themed HTML file. It draws the
7
+ # page `htm tags graph` draws (TagGraph.page_data, publish and the
8
+ # template behind them) with other nodes and wording.
9
+ #
10
+ # With an entity: that entity, the memories that mention it and the
11
+ # entities those memories also mention, each mention a link. Without:
12
+ # the most mentioned entities, two of them linked when one memory
13
+ # mentions both.
14
+ #
15
+ # Reading the database (Focus#rows, Overview#rows) is kept apart from
16
+ # shaping the data (EntityGraph::Shape), so each can be tested on its own.
17
+ #
18
+ # @example
19
+ # HTM::Admin::EntityGraph.for("Globex").write(path: "globex.html")
20
+ # HTM::Admin::EntityGraph.for(type: "person", limit: 100).write
21
+ #
22
+ class EntityGraph
23
+ DEFAULT_PATH = 'entities_graph.html'
24
+
25
+ # The graph of one entity, or the overview without a name
26
+ #
27
+ # @param name [String, nil] an entity's name, alias or id
28
+ # @param scope [Hash] type: (of +name+ when several types share it, else the only type shown)
29
+ # and limit: (memories of an entity, or entities, at most)
30
+ # @return [EntityGraph]
31
+ #
32
+ def self.for(name = nil, **scope) = name ? Focus.new(name, **scope) : Overview.new(**scope)
33
+
34
+ # Write the graph page
35
+ #
36
+ # @param path [String] Output file
37
+ # @param title [String, nil] Page title; defaults to one naming the entity
38
+ # @param d3_js [String, nil, Symbol] as for TagGraph.write
39
+ # @param out [IO]
40
+ # @return [String, nil] the path written, nil when there is nothing to draw
41
+ # @raise [HTM::NotFoundError, HTM::Admin::Error] for an unknown or shared name
42
+ #
43
+ def write(path: DEFAULT_PATH, title: nil, d3_js: :fetch, out: $stdout)
44
+ Admin.connect!
45
+ drawn = data
46
+ return Admin.say(out, nothing_to_draw) if drawn[:nodes].empty?
47
+
48
+ title ||= default_title
49
+ TagGraph.publish(drawn, path:, out:, d3_js:, title:)
50
+ out.puts Shape.written_summary(path, drawn)
51
+ path
52
+ end
53
+
54
+ # One entity with the memories that mention it and the entities those memories also mention
55
+ class Focus < EntityGraph
56
+ # Memories shown unless a limit is given
57
+ LIMIT = 200
58
+
59
+ # @param name [String] the entity's name, alias or id
60
+ # @param type [String, nil] its type, when several types share the name
61
+ # @param limit [Integer, nil] memories at most, latest event first
62
+ #
63
+ def initialize(name, type: nil, limit: nil)
64
+ super()
65
+ limit ||= LIMIT
66
+ @name = name
67
+ @type = type
68
+ @limit = limit
69
+ end
70
+
71
+ # @return [Hash] the page's data: { meta:, branches:, sources:, nodes:, edges: }
72
+ def data = Shape.focus(rows)
73
+
74
+ # @return [String] "HTM entity graph: Globex"
75
+ def default_title = "HTM entity graph: #{@name}"
76
+
77
+ # @return [String] why there is no page to write
78
+ def nothing_to_draw = "No active memory mentions #{@name}."
79
+
80
+ # Read the entity's latest memories, the entities they mention and the files they came from
81
+ #
82
+ # @return [Hash] { entity: { id:, name:, type: }, nodes:, mentions:, parents:, sources: } as
83
+ # plain rows, mentions being node id => [{ id:, name:, type:, aliases: }]
84
+ #
85
+ def rows
86
+ entity = EntityCommands.find(@name, @type)
87
+ nodes = entity.nodes.reverse(:occurred_at, HTM::Models::Node::ID).limit(@limit)
88
+ .select(:id, :content, :epistemic_status, :source_id, :occurred_at).naked.all
89
+ {
90
+ entity: HTM::EntityMemory::Facts.brief(entity), nodes:, mentions: mentions_on(nodes.map { it[:id] }),
91
+ parents: TagGraph.parent_rows(nodes), sources: HTM.db[:file_sources].select(:id, :file_path, :frontmatter).all
92
+ }
93
+ end
94
+
95
+ private
96
+
97
+ # @return [Hash{Integer => Array<Hash>}] node id => the entities it mentions, each with its other names
98
+ def mentions_on(node_ids)
99
+ mentions = HTM::EntityLookup.by_node(node_ids)
100
+ named = HTM::Models::Entity.with_ids(mentions.values.flatten.map { it[:id] }.uniq).all
101
+ Shape.with_aliases(mentions, HTM::EntityMemory::Facts.other_names(named))
102
+ end
103
+ end
104
+
105
+ # The most mentioned entities, two of them linked when one memory mentions both
106
+ class Overview < EntityGraph
107
+ # Entities shown unless a limit is given
108
+ LIMIT = 60
109
+
110
+ # Pairs of the given entities (each with everything merged into it)
111
+ # that active nodes mention together, with the number of such nodes
112
+ PAIRS_SQL = <<~SQL
113
+ WITH RECURSIVE roots(id, root_id) AS (
114
+ SELECT id, id FROM entities WHERE id IN :ids
115
+ UNION ALL
116
+ SELECT e.id, r.root_id FROM entities e JOIN roots r ON e.merged_into_id = r.id WHERE e.deleted_at IS NULL
117
+ ),
118
+ mentions AS (
119
+ SELECT DISTINCT r.root_id AS entity_id, ne.node_id
120
+ FROM roots r
121
+ JOIN node_entities ne ON ne.entity_id = r.id
122
+ JOIN nodes n ON n.id = ne.node_id AND n.deleted_at IS NULL
123
+ )
124
+ SELECT a.entity_id AS source, b.entity_id AS target, COUNT(*) AS shared
125
+ FROM mentions a
126
+ JOIN mentions b ON b.node_id = a.node_id AND a.entity_id < b.entity_id
127
+ GROUP BY a.entity_id, b.entity_id
128
+ ORDER BY a.entity_id, b.entity_id
129
+ SQL
130
+
131
+ # @param type [String, nil] only entities of this type
132
+ # @param limit [Integer, nil] entities at most, most mentioned first
133
+ #
134
+ def initialize(type: nil, limit: nil)
135
+ super()
136
+ limit ||= LIMIT
137
+ @type = type
138
+ @limit = limit
139
+ end
140
+
141
+ # @return [Hash] the page's data: { meta:, branches:, sources:, nodes:, edges: }
142
+ def data = Shape.overview(rows)
143
+
144
+ # @return [String] the page's title
145
+ def default_title = 'HTM entity graph'
146
+
147
+ # @return [String] why there is no page to write
148
+ def nothing_to_draw = @type ? "No memory mentions an entity of type '#{@type}'." : 'No memory mentions an entity yet.'
149
+
150
+ # Read the most mentioned entities and how often each two are mentioned together
151
+ #
152
+ # @return [Hash] { entities:, pairs: } with entity summaries (HTM::EntityMemory::Facts.summary)
153
+ # and [entity id, entity id, nodes mentioning both] pairs
154
+ #
155
+ def rows
156
+ entities = HTM::Models::Entity.most_mentioned(type: EntityCommands.known_type!(@type), limit: @limit)
157
+ ids = entities.map(&:id)
158
+ pairs = ids.empty? ? [] : HTM.db.fetch(PAIRS_SQL, ids:).map { it.values_at(:source, :target, :shared) }
159
+ { entities: HTM::EntityMemory::Facts.summaries(entities), pairs: }
160
+ end
161
+ end
162
+
163
+ # The page's data from plain rows: no database, so each function can
164
+ # be tested with rows written by hand
165
+ module Shape
166
+ # The branch (legend group) of the memories in an entity's graph
167
+ MEMORY_BRANCH = 'memory'
168
+
169
+ # Radius of the least and of the most mentioned entity
170
+ RADIUS = [6.0, 14.0].freeze
171
+
172
+ # What every entity graph tells the page in place of the tag graph's look and wording
173
+ PAGE = {
174
+ theme: 'dark',
175
+ labels: { group: 'Entity type', others: 'other types', find: 'Find a name or text', links: 'Linked to' }
176
+ }.freeze
177
+
178
+ # Closes the footer of an entity's graph and of the overview
179
+ NOTES = {
180
+ focus: 'Each link is one memory mentioning one entity.',
181
+ overview: 'Two entities are linked when one memory mentions both; the weight is the share of the ' \
182
+ 'memories mentioning either that mention both (Jaccard).'
183
+ }.transform_values do |links|
184
+ "#{links} An entity counts with everything merged into it, and only active memories count. Drag to pan, " \
185
+ 'scroll or pinch to zoom, click a node for its details. Regenerate with htm entities graph.'
186
+ end.freeze
187
+
188
+ module_function
189
+
190
+ # @return [Array<String>] the lines reported once +data+ is written to +path+
191
+ def written_summary(path, data)
192
+ entities, memories = data[:nodes].partition { it[:id].is_a?(String) }.map(&:size)
193
+ ["Entity graph written to: #{path}",
194
+ "Entities: #{entities}, memories: #{memories}, links: #{data[:edges].size}, sources: #{data[:sources].size}"]
195
+ end
196
+
197
+ # @param mentions [Hash{Integer => Array<Hash>}] node id => [{ id:, name:, type: }]
198
+ # @param other_names [Hash{Integer => Array<String>}] entity id => its other names
199
+ # @return [Hash{Integer => Array<Hash>}] +mentions+, each entity with aliases:
200
+ def with_aliases(mentions, other_names) = mentions.transform_values { aliased(it, other_names) }
201
+
202
+ # @return [Array<Hash>] the entities, each with aliases: from +other_names+
203
+ def aliased(entities, other_names) = entities.map { it.merge(aliases: other_names.fetch(it[:id], [])) }
204
+
205
+ # One entity's graph: the entity, its memories and the entities
206
+ # named with it, a link per mention
207
+ #
208
+ # @param rows [Hash] see EntityGraph::Focus#rows
209
+ # @return [Hash] { meta:, branches:, sources:, nodes:, edges: } (see TagGraph.page_data)
210
+ #
211
+ def focus(rows)
212
+ mentions = rows[:mentions]
213
+ sources = rows[:sources].to_h { [it[:id], it] }
214
+ entities = entity_vertices(mentions.values.flatten.tally)
215
+ memories = rows[:nodes].map { memory_vertex(it, rows, sources) }
216
+ edges = mentions.flat_map { |node_id, named| mention_edges(node_id, named) }
217
+ TagGraph.page_data(entities + memories, edges, sources, **PAGE, note: NOTES[:focus], slider: false,
218
+ figs: figures(entities, memories, edges),
219
+ lede: focus_lede(rows[:entity], memories.size, entities.size - 1))
220
+ end
221
+
222
+ # @return [Array<Array>] a [node id, entity key, 1.0] link from the node to each entity it mentions
223
+ def mention_edges(node_id, entities) = entities.map { [node_id, key(it[:id]), 1.0] }
224
+
225
+ # The overview: the entities, two of them linked by the Jaccard
226
+ # overlap of the memories mentioning them
227
+ #
228
+ # @param rows [Hash] see EntityGraph::Overview#rows
229
+ # @return [Hash] { meta:, branches:, sources:, nodes:, edges: } (see TagGraph.page_data)
230
+ #
231
+ def overview(rows)
232
+ counted = rows[:entities].to_h { [it, it[:mention_count]] }
233
+ nodes = entity_vertices(counted)
234
+ edges = overlaps(rows[:pairs], counted.transform_keys { it[:id] })
235
+ TagGraph.page_data(nodes, edges, {}, **PAGE, note: NOTES[:overview], slider: { min: 0, value: 0 },
236
+ figs: figures(nodes, [], edges),
237
+ lede: "The #{nodes.size} most mentioned entities, linked when one memory mentions both.")
238
+ end
239
+
240
+ # @param pairs [Array<Array>] [entity id, entity id, nodes mentioning both]
241
+ # @param counts [Hash{Integer => Integer}] nodes mentioning each entity
242
+ # @return [Array<Array>] [entity key, entity key, Jaccard overlap]: shared nodes over nodes mentioning either
243
+ def overlaps(pairs, counts)
244
+ pairs.map { |from, to, shared| [key(from), key(to), shared.fdiv(counts[from] + counts[to] - shared)] }
245
+ end
246
+
247
+ # @return [String] how the page keys entity +id+, apart from the node ids
248
+ def key(id) = "e#{id}"
249
+
250
+ # @return [Array<Array>] the page's headline figures, [value, label] pairs, zeros left out
251
+ def figures(entities, memories, edges)
252
+ [[entities.size, 'entities'], [memories.size, 'memories'], [edges.size, 'links']].reject { |value, _label| value.zero? }
253
+ end
254
+
255
+ # @return [String] the page's opening sentence for one entity's graph
256
+ def focus_lede(entity, memories, others)
257
+ "#{entity[:name]} (#{entity[:type]}): the #{memories} latest #{memories == 1 ? 'memory' : 'memories'} mentioning it " \
258
+ "and the #{others} other #{others == 1 ? 'entity' : 'entities'} they mention."
259
+ end
260
+
261
+ # The entities as the page draws them, sized by how many memories mention each
262
+ #
263
+ # @param counted [Hash{Hash => Integer}] entity ({ id:, name:, type:, aliases: }, maybe
264
+ # description:) => memories mentioning it
265
+ # @return [Array<Hash>]
266
+ #
267
+ def entity_vertices(counted)
268
+ most = counted.values.max
269
+ counted.map { |entity, count| entity_vertex(entity, count, radius(count, most)) }
270
+ end
271
+
272
+ # One entity as the page draws it
273
+ #
274
+ # @param entity [Hash] { id:, name:, type:, aliases: }, maybe description:
275
+ # @param count [Integer] memories mentioning it
276
+ # @param radius [Float]
277
+ # @return [Hash] { id:, h: heading, k: kind line, c: content, p: false, s: nil, b: type, t: names, tl:, r: }
278
+ #
279
+ def entity_vertex(entity, count, radius)
280
+ name, type = entity.values_at(:name, :type)
281
+ mentioned = "in #{count} #{count == 1 ? 'memory' : 'memories'}"
282
+ {
283
+ id: key(entity[:id]), h: name, k: "#{type} · #{mentioned}", c: entity[:description] || "#{name} is mentioned #{mentioned}.",
284
+ p: false, s: nil, b: type, t: entity[:aliases], tl: 'Also known as', r: radius
285
+ }
286
+ end
287
+
288
+ # @return [Float] an entity's radius: its share of the most mentions, by area
289
+ def radius(count, most)
290
+ least, widest = RADIUS
291
+ (least + ((widest - least) * Math.sqrt(count.fdiv(most)))).round(1)
292
+ end
293
+
294
+ # One memory as the page draws it
295
+ #
296
+ # @param row [Hash] nodes row with :id, :content, :epistemic_status, :source_id, :occurred_at
297
+ # @param rows [Hash] EntityGraph::Focus#rows' rows (for :mentions and :parents)
298
+ # @param sources [Hash{Integer => Hash}] file_sources rows by id
299
+ # @return [Hash] { id:, k: kind line, c: content, p: proposition?, s: source id, b: "memory", t: entity names, tl: }
300
+ #
301
+ def memory_vertex(row, rows, sources)
302
+ id = row[:id]
303
+ proposition = TagGraph.proposition?(row)
304
+ {
305
+ id:, k: [proposition ? 'Proposition' : 'Memory', row[:occurred_at]&.strftime('%Y-%m-%d')].compact.join(' · '),
306
+ c: row[:content].to_s[0, TagGraph::CONTENT_CHARS], p: proposition, s: TagGraph.source_key(id, rows[:parents], sources),
307
+ b: MEMORY_BRANCH, t: rows[:mentions].fetch(id, []).map { it[:name] }, tl: 'Mentions'
308
+ }
309
+ end
310
+ end
311
+ end
312
+ end
313
+ end
@@ -0,0 +1,323 @@
1
+ # frozen_string_literal: true
2
+
3
+ class HTM
4
+ module Admin
5
+ # The `htm files ...` commands: load markdown files into long-term
6
+ # memory and keep them in sync
7
+ #
8
+ # The module functions are the task entry points and the helpers that
9
+ # print nothing; Console runs the commands against a given terminal and
10
+ # memory.
11
+ module FileCommands
12
+ ROBOT_NAME = "FileLoader"
13
+
14
+ # Chunk counts load_totals reports, by the HTM#load_file result key they sum
15
+ CHUNK_TOTALS = { created: :chunks_created, updated: :chunks_updated, deleted: :chunks_deleted }.freeze
16
+
17
+ # list's note per sync_state
18
+ LIST_NOTES = { missing: " [missing]", needs_sync: " [needs sync]", synced: "" }.freeze
19
+
20
+ # info's "Needs sync" value per sync_state
21
+ INFO_NOTES = { missing: 'File missing!', needs_sync: 'Yes', synced: 'No' }.freeze
22
+
23
+ module_function
24
+
25
+ # Load one markdown file (see Console#load)
26
+ def load(path, force: nil) = Console.new.load(path, force:)
27
+
28
+ # Load every file matching +pattern+ under +path+ (see Console#load_dir)
29
+ def load_dir(path, pattern: '**/*.md', force: nil) = Console.new.load_dir(path, pattern:, force:)
30
+
31
+ # Print every loaded file source (see Console#list)
32
+ def list = Console.new.list
33
+
34
+ # Print the details of one loaded file (see Console#info)
35
+ def info(path) = Console.new.info(path)
36
+
37
+ # Soft delete the chunks loaded from +path+ (see Console#unload)
38
+ def unload(path) = Console.new.unload(path)
39
+
40
+ # Reload every loaded file that changed on disk (see Console#sync)
41
+ def sync = Console.new.sync
42
+
43
+ # Print totals over every loaded file (see Console#stats)
44
+ def stats = Console.new.stats
45
+
46
+ # @return [HTM] the robot the files are loaded as
47
+ def htm
48
+ Admin.connect!
49
+ HTM.new(robot_name: ROBOT_NAME)
50
+ end
51
+
52
+ # @return [String] "created, updated, deleted" counts of one load result
53
+ def chunk_summary(result)
54
+ "#{result[:chunks_created]} created, #{result[:chunks_updated]} updated, #{result[:chunks_deleted]} deleted"
55
+ end
56
+
57
+ # @return [Symbol] :missing, :needs_sync or :synced for a file source
58
+ def sync_state(source)
59
+ path = source.file_path
60
+ return :missing unless File.exist?(path)
61
+
62
+ source.needs_sync?(File.mtime(path)) ? :needs_sync : :synced
63
+ end
64
+
65
+ # Totals over HTM#load_directory's results
66
+ #
67
+ # @return [Hash] { files:, skipped:, created:, updated:, deleted: }
68
+ #
69
+ def load_totals(results)
70
+ files = results.size
71
+ loaded = results.reject { it[:skipped] }
72
+ { files:, skipped: files - loaded.size, **CHUNK_TOTALS.transform_values { sum_of(loaded, it) } }
73
+ end
74
+
75
+ # @return [Integer] the sum of +key+ over +results+
76
+ def sum_of(results, key) = results.sum { it[key] }
77
+
78
+ # @return [Array<String>] list's two lines for +source+
79
+ def source_lines(source)
80
+ synced = source.last_synced_at&.strftime('%Y-%m-%d %H:%M')
81
+ [" #{source.file_path}",
82
+ " ID: #{source.id} | Chunks: #{source.chunks.count} | Last synced: #{synced}#{LIST_NOTES.fetch(sync_state(source))}"]
83
+ end
84
+
85
+ # @return [Hash{String => Object}] info's details of +source+, by label
86
+ def source_details(source)
87
+ {
88
+ 'ID' => source.id,
89
+ 'File size' => "#{source.file_size} bytes",
90
+ 'Last synced' => source.last_synced_at,
91
+ 'Needs sync' => INFO_NOTES.fetch(sync_state(source)),
92
+ 'Created' => source.created_at
93
+ }
94
+ end
95
+
96
+ # @return [Hash] { files:, chunks:, needs_sync:, missing: } over every loaded file
97
+ def file_totals
98
+ states = HTM::Models::FileSource.all.map { sync_state(it) }.tally
99
+ {
100
+ files: HTM::Models::FileSource.count,
101
+ chunks: HTM::Models::Node.exclude(source_id: nil).count,
102
+ needs_sync: states.fetch(:needs_sync, 0),
103
+ missing: states.fetch(:missing, 0)
104
+ }
105
+ end
106
+
107
+ # @return [Hash{String => Object}] the counts of one HTM#load_file result, by label
108
+ def load_counts(result)
109
+ {
110
+ 'File source ID' => result[:file_source_id],
111
+ 'Chunks created' => result[:chunks_created],
112
+ 'Chunks updated' => result[:chunks_updated],
113
+ 'Chunks deleted' => result[:chunks_deleted]
114
+ }
115
+ end
116
+
117
+ # @return [Array<String>] stats' lines on missing files and chunks per file, when they apply
118
+ def stat_notes(totals)
119
+ files, chunks, missing = totals.values_at(:files, :chunks, :missing)
120
+ [
121
+ (" Missing files: #{missing}" if missing.positive?),
122
+ (" Average chunks per file: #{(chunks.to_f / files).round(1)}" if files.positive?)
123
+ ].compact
124
+ end
125
+
126
+ # @return [HTM::Models::FileSource, nil] the source loaded from +path+, as given or expanded
127
+ def find_source(path)
128
+ HTM::Models::FileSource.first(file_path: path) || HTM::Models::FileSource.first(file_path: File.expand_path(path))
129
+ end
130
+
131
+ # @return [String] the first 60 characters of +content+ on one line
132
+ def preview(content)
133
+ text = content[0..60].tr("\n", " ")
134
+ content.length > 60 ? "#{text}..." : text
135
+ end
136
+
137
+ # The `htm files ...` commands, reporting to +out+ and loading
138
+ # through +memory+ (an HTM; the FileLoader robot when nil)
139
+ #
140
+ # @example
141
+ # HTM::Admin::FileCommands::Console.new(out: StringIO.new, memory: htm).load("docs/guide.md")
142
+ #
143
+ class Console < Admin::Console
144
+ # @param memory [HTM, nil]
145
+ def initialize(memory: nil, **)
146
+ super(**)
147
+ @memory = memory
148
+ end
149
+
150
+ # Load one markdown file
151
+ #
152
+ # @return [Hash] HTM#load_file's result
153
+ # @raise [HTM::Admin::Error] when +path+ is not a file
154
+ #
155
+ def load(path, force: nil)
156
+ raise Admin::Error, "Error: File not found: #{path}" unless File.file?(path.to_s)
157
+
158
+ out.puts "Loading file: #{path}#{' (force)' if force}"
159
+ result = memory.load_file(path, force:)
160
+ if result[:skipped]
161
+ out.puts "Skipped: File unchanged since last sync.", "Use --force to reload anyway."
162
+ else
163
+ print_counts("Loaded successfully:", FileCommands.load_counts(result))
164
+ end
165
+ result
166
+ end
167
+
168
+ # Load every file matching +pattern+ under +path+
169
+ #
170
+ # @return [Array<Hash>] HTM#load_directory's results
171
+ # @raise [HTM::Admin::Error] when +path+ is not a directory
172
+ #
173
+ def load_dir(path, pattern: '**/*.md', force: nil)
174
+ raise Admin::Error, "Error: Directory not found: #{path}" unless File.directory?(path.to_s)
175
+
176
+ out.puts "Loading files from: #{path}", "Pattern: #{pattern}#{' (force)' if force}", ""
177
+ memory.load_directory(path, pattern:, force:).tap { report_load_dir(it) }
178
+ end
179
+
180
+ # Print every loaded file source
181
+ #
182
+ # @return [Integer] how many there are
183
+ #
184
+ def list
185
+ Admin.connect!
186
+ sources = HTM::Models::FileSource.order(:file_path).all
187
+ count = sources.size
188
+ if count.zero?
189
+ out.puts "No files loaded."
190
+ return 0
191
+ end
192
+
193
+ out.puts "Loaded files (#{count}):"
194
+ out.puts "-" * 80
195
+ sources.each { out.puts FileCommands.source_lines(it) }
196
+ count
197
+ end
198
+
199
+ # Print the details of one loaded file
200
+ #
201
+ # @return [HTM::Models::FileSource]
202
+ # @raise [HTM::Admin::Error] when +path+ was never loaded
203
+ #
204
+ def info(path)
205
+ Admin.connect!
206
+ source = FileCommands.find_source(path) or raise Admin::Error, "Error: File not loaded: #{path}"
207
+
208
+ out.puts "File: #{source.file_path}"
209
+ print_counts("-" * 60, FileCommands.source_details(source))
210
+ out.puts
211
+ print_frontmatter(source.frontmatter)
212
+ print_chunks(source.chunks)
213
+ source
214
+ end
215
+
216
+ # Soft delete the chunks loaded from +path+
217
+ #
218
+ # @return [Integer] chunks unloaded (0 when +path+ was never loaded)
219
+ #
220
+ def unload(path)
221
+ count = memory.unload_file(path)
222
+ out.puts count.positive? ? "Unloaded: #{path} (#{count} chunks)" : "File not found: #{path}"
223
+ count
224
+ end
225
+
226
+ # Reload every loaded file that changed on disk
227
+ #
228
+ # @return [Hash] { synced:, skipped:, missing: }
229
+ #
230
+ def sync
231
+ loader = memory
232
+ sources = HTM::Models::FileSource.all
233
+ if sources.empty?
234
+ out.puts "No files loaded."
235
+ return { synced: 0, skipped: 0, missing: 0 }
236
+ end
237
+
238
+ totals = sync_all(sources, loader)
239
+ print_counts("Summary:", {
240
+ 'Synced' => totals[:synced],
241
+ 'Skipped (unchanged)' => totals[:skipped],
242
+ 'Missing files' => totals[:missing]
243
+ })
244
+ totals
245
+ end
246
+
247
+ # Print totals over every loaded file
248
+ #
249
+ # @return [Hash] { files:, chunks:, needs_sync:, missing: }
250
+ #
251
+ def stats
252
+ Admin.connect!
253
+ totals = FileCommands.file_totals
254
+ out.puts "File Loading Statistics"
255
+ print_counts("=" * 40, {
256
+ 'Total files loaded' => totals[:files],
257
+ 'Total chunks' => totals[:chunks],
258
+ 'Files needing sync' => totals[:needs_sync]
259
+ })
260
+ FileCommands.stat_notes(totals).each { out.puts it }
261
+ totals
262
+ end
263
+
264
+ private
265
+
266
+ # @return [HTM] the memory files are loaded into
267
+ def memory = @memory ||= FileCommands.htm
268
+
269
+ def report_load_dir(results)
270
+ results.reject { it[:skipped] }.each { out.puts " #{it[:file_path]}: #{FileCommands.chunk_summary(it)}" }
271
+ totals = FileCommands.load_totals(results)
272
+ out.puts
273
+ print_counts("Summary:", {
274
+ 'Files processed' => totals[:files],
275
+ 'Files skipped (unchanged)' => totals[:skipped],
276
+ 'Total chunks created' => totals[:created],
277
+ 'Total chunks updated' => totals[:updated],
278
+ 'Total chunks deleted' => totals[:deleted]
279
+ })
280
+ end
281
+
282
+ def print_frontmatter(frontmatter)
283
+ return if frontmatter.empty?
284
+
285
+ out.puts "Frontmatter:"
286
+ frontmatter.each { |key, value| out.puts " #{key}: #{value}" }
287
+ out.puts
288
+ end
289
+
290
+ def print_chunks(chunks)
291
+ out.puts "Chunks (#{chunks.count}):"
292
+ chunks.each_with_index { |chunk, idx| out.puts " [#{idx}] #{FileCommands.preview(chunk.content)}" }
293
+ end
294
+
295
+ # Sync each of +sources+ through +loader+
296
+ #
297
+ # @return [Hash] { synced:, skipped:, missing: }
298
+ #
299
+ def sync_all(sources, loader)
300
+ out.puts "Syncing #{sources.size} files...", ""
301
+ totals = { synced: 0, skipped: 0, missing: 0 }
302
+ sources.each { totals[sync_source(it, loader)] += 1 }
303
+ out.puts
304
+ totals
305
+ end
306
+
307
+ # Reload +source+ if it changed; returns :synced, :skipped or :missing
308
+ def sync_source(source, loader)
309
+ path = source.file_path
310
+ case FileCommands.sync_state(source)
311
+ when :missing
312
+ out.puts " [missing] #{path}"
313
+ :missing
314
+ when :synced then :skipped
315
+ else
316
+ out.puts " [synced] #{path}: #{FileCommands.chunk_summary(loader.load_file(path))}"
317
+ :synced
318
+ end
319
+ end
320
+ end
321
+ end
322
+ end
323
+ end