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,352 @@
1
+ # frozen_string_literal: true
2
+
3
+ class HTM
4
+ module Admin
5
+ # The `htm tags ...` commands: show, export, rebuild, clean up and
6
+ # repair the tag hierarchy
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.
10
+ module TagCommands
11
+ # Singular forms the skip-list rule must not pluralize back: each is a
12
+ # word of its own (async-http is not a mangled async-https)
13
+ KEEP_SINGULAR = %w[http io new].freeze
14
+
15
+ module_function
16
+
17
+ # Print the tag tree (see Console#tree)
18
+ def tree(prefix = nil) = Console.new.tree(prefix)
19
+
20
+ # Write the tags as a Mermaid flowchart to tags.md (see Console#mermaid)
21
+ def mermaid(prefix = nil) = Console.new.mermaid(prefix)
22
+
23
+ # Write the tags as an SVG diagram to tags.svg (see Console#svg)
24
+ def svg(prefix = nil) = Console.new.svg(prefix)
25
+
26
+ # Write tags.txt, tags.md and tags.svg (see Console#export)
27
+ def export(prefix = nil) = Console.new.export(prefix)
28
+
29
+ # Delete every tag and extract them again for every node, after confirmation (see Console#rebuild)
30
+ def rebuild = Console.new.rebuild
31
+
32
+ # List, or with +apply+ rename, the tags the old normalizer mangled (see Console#restore_plurals)
33
+ def restore_plurals(prefix = nil, apply: nil) = Console.new.restore_plurals(prefix, apply:)
34
+
35
+ # Soft delete stale node_tags rows and orphaned tags, after confirmation (see Console#cleanup)
36
+ def cleanup = Console.new.cleanup
37
+
38
+ # @return [Sequel::Dataset] tags under +prefix+, or every tag when nil
39
+ def scope(prefix = nil) = prefix ? HTM::Models::Tag.with_prefix(prefix) : HTM::Models::Tag.dataset
40
+
41
+ # @return [String] " (prefix: x)" or ""
42
+ def prefix_note(prefix) = prefix ? " (prefix: #{prefix})" : ''
43
+
44
+ # @return [String] the title for an SVG of +prefix+'s tags
45
+ def title(prefix) = prefix ? "HTM Tags: #{prefix}*" : 'HTM Tag Hierarchy'
46
+
47
+ # @return [String] the tag tree as text, with a heading and a total
48
+ def tree_text(tags, prefix, count)
49
+ "HTM Tags Tree#{prefix_note(prefix)}\n#{'=' * 40}\n#{HTM::Models::Tag.tree_string(tags)}\nTotal tags: #{count}\n"
50
+ end
51
+
52
+ # The files export writes
53
+ #
54
+ # @return [Hash{String => Array(String, String)}] file name => [content, label]
55
+ #
56
+ def export_files(tags, prefix, count)
57
+ {
58
+ 'tags.txt' => [tree_text(tags, prefix, count), "Text tree"],
59
+ 'tags.md' => [HTM::Models::Tag.tree_mermaid(dataset: tags), "Mermaid flowchart"],
60
+ 'tags.svg' => [HTM::Models::Tag.tree_svg(title: title(prefix), dataset: tags), "SVG visualization"]
61
+ }
62
+ end
63
+
64
+ # What rebuild will do, for the confirmation prompt
65
+ #
66
+ # @return [Array<String>]
67
+ #
68
+ def rebuild_plan(node_count)
69
+ [
70
+ "This will:",
71
+ " - Delete #{HTM::Models::NodeTag.count} node-tag associations",
72
+ " - Delete #{HTM::Models::Tag.count} tags",
73
+ " - Regenerate tags for #{node_count} nodes using LLM",
74
+ "\nThis operation cannot be undone."
75
+ ]
76
+ end
77
+
78
+ # Delete every node-tag association and every tag
79
+ #
80
+ # @return [Array(Integer, Integer)] node_tags and tags rows deleted
81
+ #
82
+ def clear_tags = [HTM::Models::NodeTag.dataset.delete, HTM::Models::Tag.dataset.delete]
83
+
84
+ # The name +name+ had before the old normalizer trimmed a trailing "s"
85
+ # from a level that is a name or a fixed plural. A level is restored
86
+ # when its plural is:
87
+ # - a name the tag's own nodes spell as one (AlchemyCMS, state_machines)
88
+ # - something with an ending no plural has (cms, js, aas)
89
+ # - a skip-list word as the last part of a hyphenated level
90
+ # (ruby-on-rails, civil-rights), or an OS or *ops name (chromeos, mlops)
91
+ #
92
+ # @param name [String] tag name
93
+ # @param contents [Array<String>] content of the nodes carrying the tag
94
+ # @return [String] the restored name, or +name+ when nothing was trimmed
95
+ #
96
+ def restored_plural_name(name, contents)
97
+ keep = contents.flat_map { HTM::TagService.proper_plurals(it) }.uniq
98
+ name.split(':').map { restored_plural_level(it, keep) }.join(':')
99
+ end
100
+
101
+ # @return [String] +level+ with its "s" back, or +level+ unchanged
102
+ def restored_plural_level(level, keep)
103
+ plural = "#{level}s"
104
+ return level if HTM::TagService.singularize_level(plural, keep:) != plural
105
+
106
+ restore = keep.include?(plural.delete('-')) ||
107
+ (plural.end_with?(*HTM::TagService::NEVER_PLURAL_SUFFIXES) &&
108
+ !level.end_with?(*HTM::TagService::NEVER_PLURAL_SUFFIXES)) ||
109
+ skip_list_plural?(level) ||
110
+ plural.end_with?('sis') # necropsi -> necropsis
111
+ restore ? plural : level
112
+ end
113
+
114
+ # @return [Boolean] whether +level+ is a skip-list word with its "s" trimmed
115
+ def skip_list_plural?(level)
116
+ last = level.split('-').last
117
+ return false if KEEP_SINGULAR.include?(last)
118
+ return false unless HTM::TagService::SINGULARIZE_SKIP_LIST.include?("#{last}s")
119
+
120
+ level.include?('-') || last.end_with?('o', 'op')
121
+ end
122
+
123
+ # Every active tag whose name the old normalizer mangled, shortest
124
+ # first so a parent is renamed (taking its subtree) before its children
125
+ #
126
+ # @param prefix [String, nil] only tags under this prefix
127
+ # @return [Array<Array(String, String)>] [old name, restored name] pairs
128
+ #
129
+ def plural_repairs(prefix = nil)
130
+ repairs = scope(prefix).eager(:nodes).all.filter_map do |tag|
131
+ name = tag.name
132
+ restored = restored_plural_name(name, tag.nodes.map(&:content))
133
+ [name, restored] unless restored == name
134
+ end
135
+ repairs.sort_by { |from, _| [from.length, from] }
136
+ end
137
+
138
+ # Rename tag +from+ (subtree included) to +into+, merging into it if it
139
+ # already exists. A rename is a soft delete plus relinks, as merge_tags.
140
+ #
141
+ # @return [Boolean] whether +from+ was renamed; false when it is gone
142
+ # (moved already with its parent)
143
+ #
144
+ def restore_plural(from, into)
145
+ return false unless HTM::Models::Tag.where(name: from).any?
146
+
147
+ HTM::Robots::Actions.merge_tags(from:, into:)
148
+ end
149
+
150
+ # @return [Sequel::Dataset] active node_tags rows whose node is soft-deleted or missing
151
+ def stale_node_tags
152
+ HTM::Models::NodeTag.left_join(:nodes, id: :node_id).where(Sequel.lit("nodes.id IS NULL OR nodes.deleted_at IS NOT NULL"))
153
+ end
154
+
155
+ # Soft delete the rows of each dataset of +targets+ that +counts+ says has any
156
+ #
157
+ # @param targets [Hash{Symbol => Sequel::Dataset}]
158
+ # @param counts [Hash{Symbol => Integer}] rows per target
159
+ # @param now [Time] the deleted_at stamp
160
+ # @return [Hash{Symbol => Integer}] rows soft-deleted per target
161
+ #
162
+ def soft_delete_all(targets, counts, now)
163
+ targets.to_h { |kind, dataset| [kind, counts[kind].positive? ? dataset.update(deleted_at: now) : 0] }
164
+ end
165
+
166
+ # The `htm tags ...` commands, reporting to +out+
167
+ #
168
+ # @example
169
+ # HTM::Admin::TagCommands::Console.new(out: StringIO.new).tree("ai")
170
+ #
171
+ class Console < Admin::Console
172
+ # restore_plurals' step by its apply: flag; anything else lists the repairs only
173
+ RESTORE_STEPS = { true => :apply_repairs }.freeze
174
+
175
+ # Print the tag tree
176
+ #
177
+ # @return [Integer, nil] tags printed, nil when there are none
178
+ #
179
+ def tree(prefix = nil)
180
+ with_tags(prefix) do |tags, count|
181
+ out.print "\n#{TagCommands.tree_text(tags, prefix, count)}"
182
+ count
183
+ end
184
+ end
185
+
186
+ # Write the tags as a Mermaid flowchart to +path+
187
+ def mermaid(prefix = nil, path: 'tags.md')
188
+ with_tags(prefix) do |tags, count|
189
+ File.write(path, HTM::Models::Tag.tree_mermaid(dataset: tags))
190
+ out.puts "Mermaid flowchart written to: #{path}"
191
+ out.puts "Tags exported: #{count}#{TagCommands.prefix_note(prefix)}"
192
+ path
193
+ end
194
+ end
195
+
196
+ # Write the tags as an SVG diagram to +path+
197
+ def svg(prefix = nil, path: 'tags.svg')
198
+ with_tags(prefix) do |tags, count|
199
+ File.write(path, HTM::Models::Tag.tree_svg(title: TagCommands.title(prefix), dataset: tags))
200
+ out.puts "SVG visualization written to: #{path}"
201
+ out.puts "Tags exported: #{count}#{TagCommands.prefix_note(prefix)}"
202
+ path
203
+ end
204
+ end
205
+
206
+ # Write tags.txt, tags.md and tags.svg into +dir+
207
+ #
208
+ # @return [Array<String>, nil] the files written
209
+ #
210
+ def export(prefix = nil, dir: '.')
211
+ with_tags(prefix) do |tags, count|
212
+ files = write_files(TagCommands.export_files(tags, prefix, count), dir)
213
+ out.puts "\nTags exported: #{count}#{TagCommands.prefix_note(prefix)}"
214
+ files
215
+ end
216
+ end
217
+
218
+ # Delete every tag and extract them again for every node, after confirmation
219
+ #
220
+ # @return [Hash, nil] { ok:, failed: }, nil when aborted
221
+ #
222
+ def rebuild
223
+ Admin.connect!
224
+ node_count = HTM::Models::Node.count
225
+ heading("HTM Tags Rebuild", 40)
226
+ out.puts TagCommands.rebuild_plan(node_count)
227
+ return aborted unless proceed?
228
+
229
+ out.puts "\nClearing existing tags..."
230
+ node_tags, tags = TagCommands.clear_tags
231
+ out.puts " Deleted #{node_tags} node-tag associations", " Deleted #{tags} tags"
232
+ regenerate_tags(node_count)
233
+ end
234
+
235
+ # List the tags the old normalizer mangled; with +apply+, rename each
236
+ # (subtree included) to its restored name, merging into it if it
237
+ # already exists. Renames are soft deletes plus relinks, as merge_tags.
238
+ #
239
+ # @param prefix [String, nil] only tags under this prefix
240
+ # @param apply [Boolean, nil] rename the tags instead of only listing them
241
+ # @return [Array<Array(String, String)>] the repairs found
242
+ #
243
+ def restore_plurals(prefix = nil, apply: nil)
244
+ Admin.connect!
245
+ repairs = TagCommands.plural_repairs(prefix)
246
+ if repairs.empty?
247
+ out.puts "No mangled tag names found."
248
+ return repairs
249
+ end
250
+
251
+ repairs.each { |from, into| out.puts " #{from} -> #{into}" }
252
+ send(RESTORE_STEPS.fetch(apply, :suggest_apply), repairs)
253
+ repairs
254
+ end
255
+
256
+ # Soft delete stale node_tags rows and orphaned tags, after confirmation
257
+ #
258
+ # @return [Hash, nil] { node_tags:, tags: } soft-deleted, nil when nothing was done
259
+ #
260
+ def cleanup(now: Time.now)
261
+ Admin.connect!
262
+ heading("HTM Tag Cleanup")
263
+ targets = { node_tags: TagCommands.stale_node_tags, tags: HTM::Models::Tag.orphaned }
264
+ counts = targets.transform_values(&:count)
265
+ print_cleanup_counts(counts, targets[:tags])
266
+ return if counts.values.sum.zero?
267
+ return cancelled unless confirmed?("\nSoft delete these entries? (yes/no): ")
268
+
269
+ result = TagCommands.soft_delete_all(targets, counts, now)
270
+ out.puts "\nSoft deleted #{result[:node_tags]} stale node_tags entries.",
271
+ "Soft deleted #{result[:tags]} orphaned tags.",
272
+ "\nCleanup complete (soft delete)."
273
+ result
274
+ end
275
+
276
+ private
277
+
278
+ # Yield the tags under +prefix+ and their count, or report that there are none
279
+ #
280
+ # @return [Object, nil] the block's value, nil when there are no tags
281
+ #
282
+ def with_tags(prefix)
283
+ Admin.connect!
284
+ tags = TagCommands.scope(prefix)
285
+ count = tags.count
286
+ if count.zero?
287
+ out.puts prefix ? "No tags found with prefix '#{prefix}'." : "No tags found in database."
288
+ return
289
+ end
290
+
291
+ yield tags, count
292
+ end
293
+
294
+ # Write each of +files+ (name => [content, label]) into +dir+
295
+ #
296
+ # @return [Array<String>] the paths written
297
+ #
298
+ def write_files(files, dir)
299
+ files.map do |name, (content, label)|
300
+ path = File.join(dir, name)
301
+ File.write(path, content)
302
+ out.puts "#{label} written to: #{path}"
303
+ path
304
+ end
305
+ end
306
+
307
+ # @return [Hash] { ok:, failed: }
308
+ def regenerate_tags(node_count)
309
+ out.puts "\nRegenerating tags for #{node_count} nodes..."
310
+ counts = each_with_progress(HTM::Models::Node.dataset, 'Processing') do |node, _bar|
311
+ HTM::Jobs::GenerateTagsJob.perform(node_id: node.id)
312
+ end
313
+ print_counts("\nRebuild complete!", {
314
+ 'Nodes processed' => node_count,
315
+ 'Errors' => counts[:failed],
316
+ 'Tags created' => HTM::Models::Tag.count,
317
+ 'Node-tag associations' => HTM::Models::NodeTag.count
318
+ })
319
+ counts
320
+ end
321
+
322
+ def apply_repairs(repairs)
323
+ applied = repairs.count { |from, into| TagCommands.restore_plural(from, into) }
324
+ out.puts "\nRestored #{applied} tags (children moved with their parents)."
325
+ end
326
+
327
+ def suggest_apply(repairs)
328
+ out.puts "\n#{repairs.size} tags to restore. Run again with --apply to rename them."
329
+ end
330
+
331
+ def print_cleanup_counts(counts, orphaned)
332
+ stale_count, orphan_count = counts.values_at(:node_tags, :tags)
333
+ if (stale_count + orphan_count).zero?
334
+ out.puts "No cleanup needed.", " Stale node_tags entries: 0", " Orphaned tags: 0"
335
+ return
336
+ end
337
+
338
+ out.puts "Found:",
339
+ " Stale node_tags entries: #{stale_count} (pointing to deleted/missing nodes)",
340
+ " Orphaned tags: #{orphan_count} (no active nodes)"
341
+ print_orphaned(orphaned, orphan_count) if orphan_count.positive?
342
+ end
343
+
344
+ def print_orphaned(orphaned, count)
345
+ out.puts "\nOrphaned tags:"
346
+ orphaned.limit(20).select_map(:name).each { out.puts " - #{it}" }
347
+ out.puts " ... and #{count - 20} more" if count > 20
348
+ end
349
+ end
350
+ end
351
+ end
352
+ end
@@ -0,0 +1,345 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'cgi'
4
+ require 'json'
5
+
6
+ class HTM
7
+ module Admin
8
+ # `htm tags graph`: write an interactive force-directed graph of the
9
+ # nodes under a tag prefix and the relationship links between them
10
+ # (node_relationships, written by GenerateRelationshipsJob) as one HTML
11
+ # file. The data and d3 are embedded, so the file opens from disk.
12
+ #
13
+ # Reading the database (graph_data) is kept apart from shaping the data
14
+ # (build, branch_of, source_of, source_info) and writing the page
15
+ # (render), so each can be tested on its own. The page itself
16
+ # (page_data, publish, render) also draws `htm entities graph`
17
+ # (HTM::Admin::EntityGraph), which gives it other nodes and labels.
18
+ #
19
+ # @example
20
+ # HTM::Admin::TagGraph.write("medicine", path: "medicine.html")
21
+ #
22
+ module TagGraph
23
+ TEMPLATE = File.expand_path("templates/tag_graph.html", __dir__)
24
+ DEFAULT_PATH = 'tags_graph.html'
25
+ D3_URL = 'https://cdnjs.cloudflare.com/ajax/libs/d3/7.9.0/d3.min.js'
26
+ CONTENT_CHARS = 600
27
+ FALLBACK_BRANCH = 'general'
28
+
29
+ module_function
30
+
31
+ # Write the graph page for the nodes under +prefix+ (every tagged node when nil)
32
+ #
33
+ # @param prefix [String, nil] Tag prefix, e.g. "medicine"
34
+ # @param path [String] Output file
35
+ # @param title [String, nil] Page title; defaults to one naming the prefix
36
+ # @param d3_js [String, nil, Symbol] d3 source to embed; :fetch downloads it,
37
+ # nil links the CDN copy instead (the page then needs a connection)
38
+ # @param out [IO]
39
+ # @return [String, nil] the path written, nil when no node matched
40
+ #
41
+ def write(prefix = nil, path: DEFAULT_PATH, title: nil, d3_js: :fetch, out: $stdout)
42
+ Admin.connect!
43
+ data = build(graph_data(prefix), prefix:)
44
+ return Admin.say(out, prefix ? "No nodes tagged under '#{prefix}'." : "No tagged nodes found.") if data[:nodes].empty?
45
+
46
+ title ||= default_title(prefix)
47
+ publish(data, path:, out:, d3_js:, title:)
48
+ out.puts written_summary(path, data)
49
+ path
50
+ end
51
+
52
+ # Write +data+ (see page_data) as a graph page of the connected database
53
+ #
54
+ # @param data [Hash] { meta:, branches:, sources:, nodes:, edges: }
55
+ # @param path [String] Output file
56
+ # @param out [IO]
57
+ # @param d3_js [String, nil, Symbol] as for write
58
+ # @param page [Hash] title: for render
59
+ # @return [String] the path written
60
+ # @raise [HTM::Admin::Error] when +path+ cannot be written (checked before d3 is downloaded)
61
+ #
62
+ def publish(data, path:, out: $stdout, d3_js: :fetch, **page)
63
+ writing(path) do
64
+ writable!(path)
65
+ d3_js = download_d3_library(out:) if d3_js == :fetch
66
+ File.write(path, render(data, database: database_name, d3_js:, **page))
67
+ end
68
+ path
69
+ end
70
+
71
+ # Runs the block, which writes +path+
72
+ #
73
+ # @raise [HTM::Admin::Error] naming the path and the reason, when the system refuses
74
+ def writing(path)
75
+ yield
76
+ rescue SystemCallError => e
77
+ raise Admin::Error, "Error: cannot write #{path}: #{e.message.sub(/ @ .*/, '')}"
78
+ end
79
+
80
+ # @raise [SystemCallError] when +path+'s directory is missing, or the file (its directory, for a new file) is read-only
81
+ def writable!(path)
82
+ directory = File.dirname(path)
83
+ raise Errno::ENOENT unless File.directory?(directory)
84
+ raise Errno::EACCES unless File.writable?(File.exist?(path) ? path : directory)
85
+ end
86
+
87
+ # @return [Array<String>] the lines write reports once +data+ is written to +path+
88
+ def written_summary(path, data)
89
+ ["Tag graph written to: #{path}",
90
+ "Nodes: #{data[:nodes].size}, links: #{data[:edges].size}, sources: #{data[:sources].size}"]
91
+ end
92
+
93
+ # @return [String] "HTM memory graph: medicine" or "HTM memory graph"
94
+ def default_title(prefix) = prefix ? "HTM memory graph: #{prefix}" : 'HTM memory graph'
95
+
96
+ # @return [String] the connected database's name
97
+ def database_name = HTM.db.get(Sequel.function(:current_database)).to_s
98
+
99
+ # Download d3 so the page works offline
100
+ #
101
+ # @return [String, nil] the library source, nil when it cannot be fetched
102
+ #
103
+ def download_d3_library(out: $stdout)
104
+ require 'net/http'
105
+ response = Net::HTTP.get_response(URI(D3_URL))
106
+ return response.body if response.is_a?(Net::HTTPSuccess)
107
+
108
+ out.puts "Could not download d3 (HTTP #{response.code}); the page will load it from the CDN."
109
+ nil
110
+ rescue StandardError => e
111
+ out.puts "Could not download d3 (#{e.message}); the page will load it from the CDN."
112
+ nil
113
+ end
114
+
115
+ # Read the nodes under +prefix+, their tags, their sources and the links between them
116
+ #
117
+ # @return [Hash] { nodes:, tags:, edges:, sources:, parents: } as plain rows
118
+ #
119
+ def graph_data(prefix)
120
+ db = HTM.db
121
+ node_ids = db[:node_tags].where(deleted_at: nil, tag_id: tag_scope(prefix).select(:id)).select(:node_id)
122
+ nodes = db[:nodes].where(id: node_ids, deleted_at: nil).order(:id)
123
+ .select(:id, :content, :epistemic_status, :source_id).all
124
+ ids = nodes.map { it[:id] }
125
+
126
+ {
127
+ nodes:,
128
+ tags: node_tags(ids),
129
+ edges: db[:node_relationships].where(source_id: ids, target_id: ids)
130
+ .where(Sequel[:source_id] < Sequel[:target_id])
131
+ .select_map(%i[source_id target_id weight]),
132
+ parents: parent_rows(nodes),
133
+ sources: db[:file_sources].select(:id, :file_path, :frontmatter).all
134
+ }
135
+ end
136
+
137
+ # @return [Sequel::Dataset] live tags named +prefix+ or under it (all live tags when nil)
138
+ def tag_scope(prefix)
139
+ tags = HTM.db[:tags].where(deleted_at: nil)
140
+ return tags unless prefix
141
+
142
+ tags.where(Sequel.|({ name: prefix }, Sequel.like(:name, "#{HTM::SqlBuilder.sanitize_like_pattern(prefix)}:%")))
143
+ end
144
+
145
+ # @return [Hash{Integer => Array<String>}] live tag names per node id
146
+ def node_tags(ids)
147
+ links = Sequel[:node_tags]
148
+ tags = Sequel[:tags]
149
+ node_id = links[:node_id]
150
+ pairs = HTM.db[:node_tags].join(:tags, id: :tag_id)
151
+ .where(node_id => ids, links[:deleted_at] => nil, tags[:deleted_at] => nil)
152
+ .select_map([node_id, tags[:name]])
153
+ pairs.group_by(&:first).transform_values { |rows| rows.map(&:last).sort }
154
+ end
155
+
156
+ # The source_id and parent of each node a proposition descends from
157
+ # that is not itself in the graph, so propositions find their file
158
+ #
159
+ # @param nodes [Array<Hash>] rows with :id, :source_id
160
+ # @param max_depth [Integer] generations followed; proposition chains
161
+ # are one level deep, so the cap only guards against cycles
162
+ # @return [Hash{Integer => Hash}] id => { source_id:, parent: }
163
+ #
164
+ def parent_rows(nodes, max_depth: 5)
165
+ known = lineage(nodes)
166
+ wanted = missing_parents(known.values, known)
167
+
168
+ max_depth.times do
169
+ break if wanted.empty?
170
+
171
+ found = lineage(HTM.db[:nodes].where(id: wanted).select(:id, :source_id).all)
172
+ known.merge!(found)
173
+ wanted = missing_parents(found.values, known)
174
+ end
175
+ known
176
+ end
177
+
178
+ # @param rows [Array<Hash>] node rows with :id, :source_id
179
+ # @return [Hash{Integer => Hash}] id => { source_id:, parent: } for each row
180
+ def lineage(rows)
181
+ parents = source_node_ids(rows.map { it[:id] })
182
+ rows.to_h do |row|
183
+ id = row[:id]
184
+ [id, { source_id: row[:source_id], parent: parents[id] }]
185
+ end
186
+ end
187
+
188
+ # @param links [Array<Hash>] { source_id:, parent: } values of lineage
189
+ # @param known [Hash{Integer => Hash}] the lineage read so far
190
+ # @return [Array<Integer>] the parents +links+ name that +known+ lacks
191
+ def missing_parents(links, known) = links.filter_map { it[:parent] }.uniq - known.keys
192
+
193
+ # @param ids [Array<Integer>] node ids
194
+ # @return [Hash{Integer => Integer}] node id => the node it was derived from
195
+ def source_node_ids(ids)
196
+ HTM::Models::NodeLink.of_kind(:derived_from).where(from_node_id: ids).select_hash(:from_node_id, :to_node_id)
197
+ end
198
+
199
+ # Shape the rows graph_data reads into the page's data
200
+ #
201
+ # @param rows [Hash] graph_data's rows:
202
+ # - nodes [Array<Hash>] rows with :id, :content, :source_id
203
+ # - tags [Hash{Integer => Array<String>}]
204
+ # - edges [Array<Array>] [source_id, target_id, weight]
205
+ # - parents [Hash{Integer => Hash}] see parent_rows
206
+ # - sources [Array<Hash>] file_sources rows
207
+ # @param prefix [String, nil]
208
+ # @return [Hash] { meta:, branches:, sources:, nodes:, edges: }
209
+ #
210
+ def build(rows, prefix: nil)
211
+ source_rows = rows[:sources].to_h { [it[:id], it] }
212
+ graph_nodes = rows[:nodes].map { graph_node(it, rows, source_rows, prefix) }
213
+
214
+ page_data(graph_nodes, rows[:edges], source_rows, prefix:)
215
+ end
216
+
217
+ # The data a graph page draws
218
+ #
219
+ # @param graph_nodes [Array<Hash>] the nodes as the page draws them (see graph_node)
220
+ # @param edges [Array<Array>] [node id, node id, weight]
221
+ # @param source_rows [Hash{Integer => Hash}] file_sources rows by id
222
+ # @param meta [Hash] what the page is told about itself: prefix: for the tag graph; a graph of
223
+ # something else replaces the tag graph's look and wording with theme:, note:, lede:, figs:,
224
+ # slider: and labels: (see the template's opening comment)
225
+ # @return [Hash] { meta:, branches:, sources:, nodes:, edges: }
226
+ #
227
+ def page_data(graph_nodes, edges, source_rows, **meta)
228
+ {
229
+ meta:,
230
+ branches: ranked(graph_nodes.map { it[:b] }) - [FALLBACK_BRANCH],
231
+ sources: ranked(graph_nodes.filter_map { it[:s] }).map { source_info(source_rows.fetch(it.to_i)) },
232
+ nodes: graph_nodes,
233
+ edges: edges.map { |from, to, weight| [from, to, weight.to_f.round(3)] }
234
+ }
235
+ end
236
+
237
+ # One node as the page draws it
238
+ #
239
+ # @param row [Hash] nodes row with :id, :content, :epistemic_status, :source_id
240
+ # @param rows [Hash] graph_data's rows (for :tags and :parents)
241
+ # @param source_rows [Hash{Integer => Hash}] file_sources rows by id
242
+ # @param prefix [String, nil]
243
+ # @return [Hash] { id:, c: content, p: proposition?, s: source id, b: branch, t: tags }
244
+ #
245
+ def graph_node(row, rows, source_rows, prefix)
246
+ id = row[:id]
247
+ tags = rows[:tags].fetch(id, [])
248
+ {
249
+ id:, c: row[:content].to_s[0, CONTENT_CHARS], p: proposition?(row),
250
+ s: source_key(id, rows[:parents], source_rows), b: branch_of(tags, prefix), t: tags
251
+ }
252
+ end
253
+
254
+ # @return [String, nil] the id of the file node +id+ came from, as the page keys its sources
255
+ def source_key(id, parents, source_rows)
256
+ source = source_of(id, parents)
257
+ source.to_s if source_rows.key?(source)
258
+ end
259
+
260
+ # @return [Array<String>] the distinct values, most frequent first (ties by name)
261
+ def ranked(values) = values.tally.sort_by { |value, count| [-count, value] }.map(&:first)
262
+
263
+ # @return [Boolean] whether a nodes row is a proposition (extracted, not a file chunk)
264
+ def proposition?(row) = row[:epistemic_status] == 'extracted' && row[:source_id].nil?
265
+
266
+ # The branch a node sits in: the level just below +prefix+ (the root
267
+ # level when nil) that most of its tags pass through
268
+ #
269
+ # @example
270
+ # branch_of(%w[medicine medicine:genetics medicine:genetics:gata1], "medicine") # => "genetics"
271
+ #
272
+ # @param tags [Array<String>]
273
+ # @param prefix [String, nil]
274
+ # @return [String] the branch, or "general" when no tag goes below +prefix+
275
+ #
276
+ def branch_of(tags, prefix)
277
+ depth = prefix ? prefix.count(':') + 1 : 0
278
+ under = prefix ? tags.select { it.start_with?("#{prefix}:") } : tags
279
+ levels = under.filter_map { it.split(':')[depth] }
280
+ levels.empty? ? FALLBACK_BRANCH : ranked(levels).first
281
+ end
282
+
283
+ # The file a node came from: its own source, or the source of the
284
+ # node it was extracted from (propositions)
285
+ #
286
+ # @param id [Integer]
287
+ # @param parents [Hash{Integer => Hash}] id => { source_id:, parent: }
288
+ # @return [Integer, nil] file_sources id
289
+ #
290
+ def source_of(id, parents)
291
+ seen = []
292
+ while (row = parents[id]) && !seen.include?(id)
293
+ source = row[:source_id]
294
+ return source if source
295
+
296
+ seen << id
297
+ id = row[:parent]
298
+ end
299
+ nil
300
+ end
301
+
302
+ # How the page names and links a file source, from its frontmatter
303
+ #
304
+ # @param row [Hash] file_sources row with :id, :file_path, :frontmatter
305
+ # @return [Hash] { id:, title:, url:, detail: }
306
+ #
307
+ def source_info(row)
308
+ fm = (row[:frontmatter] || {}).to_h.transform_keys(&:to_s)
309
+ doi = fm['doi']
310
+ {
311
+ id: row[:id].to_s,
312
+ title: fm['title'].to_s.strip.delete_suffix('.').then { it.empty? ? File.basename(row[:file_path].to_s) : it },
313
+ url: fm['url'] || (doi && "https://doi.org/#{doi}"),
314
+ detail: [fm['journal'] || fm['source'], fm['year'] || fm['date']].compact.join(' ')
315
+ }
316
+ end
317
+
318
+ # Fill the page template
319
+ #
320
+ # @param data [Hash] from build
321
+ # @param title [String]
322
+ # @param database [String]
323
+ # @param d3_js [String, nil] d3 source to embed; nil links the CDN copy
324
+ # @param generated [Time]
325
+ # @return [String] the HTML page
326
+ #
327
+ def render(data, title:, database:, d3_js: nil, generated: Time.now)
328
+ d3_tag = if d3_js
329
+ # Net::HTTP hands back a binary string; the library is UTF-8 text
330
+ "<script>#{d3_js.dup.force_encoding(Encoding::UTF_8).gsub('</script', '<\/script')}</script>"
331
+ else
332
+ %(<script src="#{D3_URL}"></script>)
333
+ end
334
+ values = {
335
+ 'TITLE' => CGI.escapeHTML(title),
336
+ 'DATABASE' => CGI.escapeHTML(database),
337
+ 'GENERATED' => generated.strftime('%-d %b %Y %H:%M'),
338
+ 'DATA' => JSON.generate(data).gsub('</', '<\/'),
339
+ 'D3' => d3_tag
340
+ }
341
+ File.read(TEMPLATE).gsub(/\{\{(TITLE|DATABASE|GENERATED|DATA|D3)\}\}/) { values.fetch(Regexp.last_match(1)) }
342
+ end
343
+ end
344
+ end
345
+ end