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
data/lib/htm/cli/db.rb ADDED
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ # HTM database tasks: htm db SUBCOMMAND
4
+ #
5
+ # The database is chosen by environment, HTM_ENV > RAILS_ENV > RACK_ENV >
6
+ # development, and named <service>_<environment> (htm_development,
7
+ # htm_test, ...). HTM_DATABASE__URL overrides the connection.
8
+ #
9
+ # htm db create # create the database with pgvector and pg_trgm
10
+ # htm db setup [--dump-schema] # schema and migrations
11
+ # HTM_ENV=test htm db reset --yes
12
+
13
+ require_relative "group"
14
+
15
+ class HTM
16
+ class CLI < Thor
17
+ # The database commands (htm db SUBCOMMAND): create, set up, migrate, inspect and reset it
18
+ class Db < Thor
19
+ include Group
20
+
21
+ desc "create", "Create the database if it doesn't exist, with pgvector and pg_trgm"
22
+ def create = htm_task { it::DatabaseCommands.create }
23
+
24
+ desc "setup", "Set up the HTM database schema and run migrations"
25
+ option :dump_schema, type: :boolean, default: false, desc: "Dump db/schema.sql afterwards"
26
+ def setup = htm_task { HTM::Database.setup(dump_schema: options[:dump_schema]) }
27
+
28
+ desc "migrate", "Run pending database migrations"
29
+ def migrate = htm_task { HTM::Database.migrate }
30
+
31
+ desc "status", "Show migration status"
32
+ def status = htm_task { HTM::Database.migration_status }
33
+
34
+ desc "drop", "Drop all HTM tables (destructive; asks unless --yes)"
35
+ option :yes, aliases: "-y", type: :boolean, default: false, desc: "Skip the confirmation prompt"
36
+ def drop = htm_task { it::DatabaseCommands.drop(confirm: options[:yes]) }
37
+
38
+ desc "reset", "Drop all HTM tables and set the schema up again (destructive; asks unless --yes)"
39
+ option :yes, aliases: "-y", type: :boolean, default: false, desc: "Skip the confirmation prompt"
40
+ def reset = htm_task { it::DatabaseCommands.reset(confirm: options[:yes]) }
41
+
42
+ desc "verify", "Verify the database connection and pgvector"
43
+ def verify = htm_task { it::DatabaseCommands.verify }
44
+
45
+ desc "console", "Open a psql console on the database"
46
+ def console
47
+ command = htm_task { it::DatabaseCommands.console_command }
48
+ puts "Connecting to #{command.last} (#{HTM.env})..."
49
+ exec(*command)
50
+ end
51
+
52
+ desc "seed", "Seed the database with sample data"
53
+ def seed = htm_task { HTM::Database.seed }
54
+
55
+ desc "info", "Show database info (size, tables, extensions)"
56
+ def info = htm_task { HTM::Database.info }
57
+
58
+ desc "stats", "Show record counts for all HTM tables"
59
+ def stats = htm_task { it::DatabaseCommands.stats }
60
+
61
+ desc "schema_dump", "Dump the current schema to db/schema.sql"
62
+ def schema_dump = htm_task { HTM::Database.dump_schema }
63
+
64
+ desc "schema_load", "Load the schema from db/schema.sql"
65
+ def schema_load = htm_task { HTM::Database.load_schema }
66
+
67
+ desc "rebuild_embeddings", "Clear every embedding and regenerate them all via the LLM (asks first)"
68
+ def rebuild_embeddings = htm_task { it::DatabaseCommands.rebuild_embeddings }
69
+
70
+ desc "rebuild_propositions", "Delete every proposition node and extract them again via the LLM (asks first)"
71
+ def rebuild_propositions = htm_task { it::DatabaseCommands.rebuild_propositions }
72
+
73
+ desc "rebuild_relationships", "Delete the related-memory edges and compute them again (no LLM calls)"
74
+ def rebuild_relationships = htm_task { it::DatabaseCommands.rebuild_relationships }
75
+
76
+ desc "purge_all", "Permanently delete soft-deleted and orphaned records (irreversible; asks first)"
77
+ def purge_all = htm_task { it::DatabaseCommands.purge_all }
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ # HTM enrichment tasks: htm enrich SUBCOMMAND
4
+ #
5
+ # Catch up on, inspect and redo what HTM's background jobs add to each node:
6
+ # embeddings, tags, entities and propositions.
7
+ #
8
+ # htm enrich stats
9
+ # htm enrich process_all
10
+
11
+ require_relative "group"
12
+
13
+ class HTM
14
+ class CLI < Thor
15
+ # The enrichment commands (htm enrich SUBCOMMAND): embeddings, tags, entities and propositions
16
+ class Enrich < Thor
17
+ include Group
18
+
19
+ desc "stats", "Show embedding, tag and entity coverage of the nodes"
20
+ def stats = htm_task { it::EnrichCommands.stats }
21
+
22
+ desc "process_embeddings", "Generate embeddings for nodes that have none"
23
+ def process_embeddings = enrich(:process_embeddings)
24
+
25
+ desc "process_tags", "Extract tags for nodes that have none"
26
+ def process_tags = enrich(:process_tags)
27
+
28
+ desc "process_entities", "Extract entities for nodes that mention none and were never examined (also while entity.enabled is off)"
29
+ def process_entities = enrich(:process_entities)
30
+
31
+ desc "process_propositions", "Extract propositions from nodes not yet processed"
32
+ def process_propositions = enrich(:process_propositions)
33
+
34
+ desc "process_all", "Process all pending embeddings, tags, entities (when entity.enabled) and propositions"
35
+ def process_all = enrich(:process_all)
36
+
37
+ desc "reprocess_embeddings", "Regenerate the embedding of every node (asks first)"
38
+ def reprocess_embeddings = enrich(:reprocess_embeddings)
39
+
40
+ desc "failed", "Show nodes over an hour old still without an embedding or tags"
41
+ def failed = htm_task { it::EnrichCommands.failed }
42
+
43
+ desc "clear_all", "Clear every embedding and tag, for testing (asks first)"
44
+ def clear_all = htm_task { it::EnrichCommands.clear_all }
45
+
46
+ private
47
+
48
+ # Run the named enrichment command; exit 1 when it processed no node and failed on at least one
49
+ def enrich(name) = htm_task { it::EnrichCommands.checked(name) }
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,268 @@
1
+ # frozen_string_literal: true
2
+
3
+ # HTM entity commands: htm entities SUBCOMMAND
4
+ #
5
+ # The people, organizations, places, products and events memory mentions
6
+ # (named entity recognition; see docs/guides/entities.md).
7
+ #
8
+ # htm entities list --type person
9
+ # htm entities show "Alice Chen"
10
+ # htm entities nodes "Alice Chen" --as-of 2025-01-01
11
+ # htm entities report "Alice Chen" --json # what do we hold about her
12
+ # htm entities merge "A. Chen" "Alice Chen" # htm entities unmerge "A. Chen" undoes it
13
+ # htm entities graph Globex -o globex.html
14
+
15
+ require_relative "group"
16
+ require_relative "memory_command"
17
+
18
+ class HTM
19
+ class CLI < Thor
20
+ # The entity commands (htm entities SUBCOMMAND): list and describe the
21
+ # entities memory mentions, find the memories about one, correct them by
22
+ # hand (add, remove, merge, unmerge, alias), draw them and extract them again
23
+ class Entities < Thor
24
+ include Group
25
+ include MemoryCommand
26
+
27
+ # How every command reads its NAME argument
28
+ NAMING = <<~TEXT
29
+ NAME is the entity's name, one of its aliases or its id (`htm entities
30
+ list` shows them), whatever the case; quote a name of several words.
31
+ The answer is about the entity the name stands for, with everything
32
+ merged into it. When entities of several types share a name, pass
33
+ --type TYPE or use the id.
34
+ TEXT
35
+
36
+ class << self
37
+ # --type for the next command, which names one entity
38
+ def type_option = option(:type, banner: "TYPE", desc: "The entity's type, when several types share the name")
39
+ end
40
+
41
+ desc "list", "List the entities memory mentions, most mentioned first"
42
+ long_desc <<~DESC, wrap: false
43
+ List the entities that active memories mention, most mentioned first,
44
+ with each one's id, the number of memories mentioning it, its type,
45
+ when it was last mentioned and its other names. Entities nothing
46
+ mentions (any more) are left out; --unmentioned lists those instead,
47
+ by name (`htm entities delete NAME` removes one).
48
+
49
+ Entities are found while a memory is stored when entity.enabled is on
50
+ (HTM_ENTITY__ENABLED=true); `htm enrich process_entities` catches up
51
+ on older memories.
52
+
53
+ Examples:
54
+
55
+ htm entities list
56
+ htm entities list --type person -l 50
57
+ htm entities list --unmentioned
58
+ htm entities list --json | jq '.entities[].name'
59
+ DESC
60
+ memory_options
61
+ limit_option 20
62
+ option :type, banner: "TYPE", desc: "Only entities of this type (person, organization, location, product, event, ...)"
63
+ option :unmentioned, type: :boolean, desc: "List the entities no memory mentions instead"
64
+ def list = entities_console { it.list(limit: options[:limit], unmentioned: options[:unmentioned] == true) }
65
+
66
+ desc "show NAME", "Show one entity: its names, when it was mentioned and the entities named with it"
67
+ long_desc <<~DESC, wrap: false
68
+ #{NAMING}
69
+ Examples:
70
+
71
+ htm entities show "Alice Chen"
72
+ htm entities show Mercury --type product
73
+ htm entities show 7 --json
74
+ DESC
75
+ memory_options
76
+ type_option
77
+ def show(name) = entities_console { it.show(name) }
78
+
79
+ desc "nodes NAME", "List the memories that mention an entity, latest first"
80
+ long_desc <<~DESC, wrap: false
81
+ #{NAMING}
82
+ --as-of TIME: only memories whose state was true at TIME (ISO8601 or
83
+ natural language). --timeframe: only memories that happened then
84
+ ("last week", an ISO8601 date or start..end range).
85
+
86
+ Examples:
87
+
88
+ htm entities nodes "Alice Chen"
89
+ htm entities nodes "Alice Chen" --as-of 2025-01-01 --full
90
+ htm entities nodes Globex -t "last month" -l 50 --json
91
+ DESC
92
+ memory_options
93
+ full_option
94
+ limit_option 20
95
+ type_option
96
+ option :as_of, banner: "TIME", desc: "Only memories whose state was true at TIME"
97
+ option :timeframe, aliases: "-t", desc: "Only memories from this time ('last week', ISO8601 start..end)"
98
+ def nodes(name)
99
+ entities_console do |console|
100
+ console.nodes(name, as_of: options[:as_of], timeframe: options[:timeframe], limit: options[:limit])
101
+ end
102
+ end
103
+
104
+ desc "related NAME", "List the entities mentioned in the same memories as an entity, most shared first"
105
+ long_desc "#{NAMING}\nExamples:\n\n htm entities related \"Alice Chen\"\n htm entities related Globex -l 25 --json\n", wrap: false
106
+ memory_options
107
+ limit_option 10
108
+ type_option
109
+ def related(name) = entities_console { it.related(name, limit: options[:limit]) }
110
+
111
+ desc "report NAME", "Show what memory holds about an entity: its names, counts and every memory mentioning it"
112
+ long_desc <<~DESC, wrap: false
113
+ Everything memory holds about one entity: its names, how many active
114
+ and soft-deleted memories mention it, the entities named with it, and
115
+ every active memory mentioning it, oldest first, with the names that
116
+ memory uses for it. With --json this is the export to hand over when
117
+ someone asks what is stored about them; `htm forget --entity NAME`
118
+ forgets it.
119
+
120
+ #{NAMING}
121
+ Examples:
122
+
123
+ htm entities report "Alice Chen" --full
124
+ htm entities report "Alice Chen" --json > alice.json
125
+ DESC
126
+ memory_options
127
+ full_option
128
+ type_option
129
+ def report(name) = entities_console { it.about(name) }
130
+
131
+ desc "add NODE_ID NAME", "Record that a memory mentions an entity (created when it is new)"
132
+ long_desc <<~DESC, wrap: false
133
+ Link memory NODE_ID to the entity NAME of type TYPE, and the memory's
134
+ propositions that name it. An unknown NAME becomes a new entity; a
135
+ known name or alias links the entity it stands for. TYPE must be one
136
+ of the configured types (entity.types and entity.custom_types).
137
+
138
+ Examples:
139
+
140
+ htm entities add 42 "Alice Chen" --type person
141
+ htm entities add 42 Globex --type organization --json
142
+ DESC
143
+ memory_options
144
+ option :type, required: true, banner: "TYPE", desc: "The entity's type (person, organization, location, product, event, ...)"
145
+ def add(id, name) = entities_console { it.add(node_id(id), name) }
146
+
147
+ desc "remove NODE_ID NAME", "Remove an entity from a memory: every mention of it there"
148
+ long_desc "The entity and its other mentions stay; the memory's propositions keep theirs.\n\n#{NAMING}", wrap: false
149
+ memory_options
150
+ type_option
151
+ def remove(id, name) = entities_console { it.remove(node_id(id), name) }
152
+
153
+ desc "merge FROM INTO", "Merge the entity FROM into the entity INTO (undo with unmerge)"
154
+ long_desc <<~DESC, wrap: false
155
+ From now on FROM's name, aliases and mentions count for INTO. Nothing
156
+ is rewritten, so `htm entities unmerge FROM` undoes it. FROM and INTO
157
+ are names, aliases or ids of entities of one type (entities of
158
+ different types are never merged); --type applies to both, and picks
159
+ each when several types share its name.
160
+
161
+ Examples:
162
+
163
+ htm entities merge "A. Chen" "Alice Chen"
164
+ htm entities merge 12 7
165
+ DESC
166
+ memory_options
167
+ option :type, banner: "TYPE", desc: "The type of both entities, when several types share a name"
168
+ def merge(from, into) = entities_console { it.merge(from, into) }
169
+
170
+ desc "unmerge NAME", "Undo a merge: the merged entity NAME stands for itself again"
171
+ long_desc <<~DESC, wrap: false
172
+ NAME is the merged entity's own name or id (the FROM of the merge),
173
+ not the entity it was merged into. It gets back the aliases and
174
+ mentions it had.
175
+
176
+ Example:
177
+
178
+ htm entities unmerge "A. Chen"
179
+ DESC
180
+ memory_options
181
+ def unmerge(name) = entities_console { it.unmerge(name) }
182
+
183
+ desc "alias NAME ALIAS", "Record another name for an entity"
184
+ long_desc <<~DESC, wrap: false
185
+ ALIAS then finds the entity wherever a NAME is taken, and recall
186
+ ranks the entity's memories up for a query that uses it. An alias
187
+ that is another entity's name is refused: merge the two instead.
188
+
189
+ #{NAMING}
190
+ Example:
191
+
192
+ htm entities alias "Alice Chen" "Dr. Chen"
193
+ DESC
194
+ memory_options
195
+ type_option
196
+ def alias(name, other_name) = entities_console { it.alias_entity(name, other_name) }
197
+
198
+ desc "delete NAME", "Delete an entity that no memory mentions"
199
+ long_desc <<~DESC, wrap: false
200
+ Remove an entity nothing mentions (`htm entities list --unmentioned`
201
+ shows them), such as one left behind by `htm entities remove` or made
202
+ by a mistyped `htm entities add`. Its name then stops being looked
203
+ up, so it no longer makes a name ambiguous.
204
+
205
+ An entity that memories still mention is refused: unlink it from
206
+ each (`htm entities remove NODE_ID NAME`) or forget those memories
207
+ (`htm forget --entity NAME`) first. So is one that other entities
208
+ are merged into: `htm entities unmerge` them first.
209
+
210
+ #{NAMING}
211
+ Examples:
212
+
213
+ htm entities delete Mercury --type person
214
+ htm entities delete 71 --json
215
+ DESC
216
+ memory_options
217
+ type_option
218
+ def delete(name) = entities_console { it.delete(name) }
219
+
220
+ desc "graph [NAME]", "Write an interactive graph of an entity (or of the most mentioned entities) to one HTML file"
221
+ long_desc <<~DESC, wrap: false
222
+ Write a self-contained, dark-themed HTML page with an interactive
223
+ force-directed graph (the page `htm tags graph` writes, for entities).
224
+
225
+ With NAME: that entity, the latest --limit memories mentioning it
226
+ (default 200) and the other entities those memories mention; every
227
+ mention is a link. Without NAME: the --limit most mentioned entities
228
+ (default 60; only those of --type when given), two of them linked
229
+ when one memory mentions both.
230
+
231
+ #{NAMING}
232
+ Examples:
233
+
234
+ htm entities graph Globex -o globex.html
235
+ htm entities graph --type person --limit 100
236
+ DESC
237
+ method_option :output, type: :string, default: "entities_graph.html", aliases: "-o", desc: "File to write"
238
+ method_option :title, type: :string, desc: "Page title (default names the entity)"
239
+ method_option :type, type: :string, banner: "TYPE", desc: "NAME's type when several share it; without NAME, only this type"
240
+ method_option :limit, type: :numeric, aliases: "-l", desc: "Memories (with NAME) or entities (without) at most"
241
+ def graph(name = nil)
242
+ htm_task do |admin|
243
+ admin::EntityGraph.for(name, type: options[:type], limit: options[:limit]).write(path: options[:output], title: options[:title])
244
+ end
245
+ end
246
+
247
+ desc "rebuild", "Extract the entities of every memory again via the LLM (asks first)"
248
+ long_desc <<~DESC, wrap: false
249
+ Extract entities again for every memory that is not a proposition and
250
+ store them in place of the mentions it has; its propositions then
251
+ inherit again. It makes one LLM call per memory, so it can take long.
252
+
253
+ Mentions linked by hand (`htm entities add`, `htm remember
254
+ --entities`) cannot be told from extracted ones and are deleted too.
255
+ Entities, aliases and merges are kept; a memory whose extraction
256
+ fails keeps the mentions it had. It runs whether or not
257
+ entity.enabled is on. Asks for confirmation unless --yes.
258
+ DESC
259
+ option :yes, aliases: "-y", type: :boolean, default: false, desc: "Skip the confirmation prompt"
260
+ def rebuild = htm_task { it::EntityCommands.rebuild(confirm: options[:yes]) }
261
+
262
+ private
263
+
264
+ # Yield the entities console, its type the command's --type
265
+ def entities_console(&) = memory_console(:Entities, type: options[:type], &)
266
+ end
267
+ end
268
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "thor"
4
+
5
+ class HTM
6
+ class CLI < Thor
7
+ # The configuration environment variables, for `htm env`. Each names a
8
+ # key in lib/htm/config/defaults.yml (test/cli_test.rb checks).
9
+ ENVIRONMENT_HELP = <<~TEXT
10
+ HTM configuration environment variables. Nested settings use double
11
+ underscores (e.g., HTM_EMBEDDING__PROVIDER).
12
+
13
+ Environment:
14
+ HTM_ENV Environment name: development, test, production
15
+ (priority: HTM_ENV > RAILS_ENV > RACK_ENV > 'development')
16
+
17
+ Command line:
18
+ HTM_ROBOT_NAME Robot the memory commands act as (default: htm_cli)
19
+
20
+ Database:
21
+ HTM_DATABASE__URL PostgreSQL connection URL (preferred)
22
+ Example: postgresql://user:pass@localhost:5432/htm_development
23
+ HTM_DATABASE__HOST Database host (default: localhost)
24
+ HTM_DATABASE__PORT Database port (default: 5432)
25
+ HTM_DATABASE__NAME Database name
26
+ HTM_DATABASE__USER Database username
27
+ HTM_DATABASE__PASSWORD Database password
28
+ HTM_DATABASE__SSLMODE SSL mode (default: prefer)
29
+ HTM_DATABASE__POOL_SIZE Connection pool size (default: 10)
30
+
31
+ Embedding:
32
+ HTM_EMBEDDING__PROVIDER Provider (default: lms)
33
+ HTM_EMBEDDING__MODEL Model (default: text-embedding-nomic-embed-text-v1.5)
34
+ HTM_EMBEDDING__DIMENSIONS Dimensions (default: 768)
35
+ HTM_EMBEDDING__TIMEOUT Timeout seconds (default: 120)
36
+ HTM_EMBEDDING__MAX_DIMENSION Max dimensions (default: 2000)
37
+
38
+ Tag Extraction:
39
+ HTM_TAG__PROVIDER Provider (default: lms)
40
+ HTM_TAG__MODEL Model (default: google/gemma-3-4b)
41
+ HTM_TAG__TIMEOUT Timeout seconds (default: 180)
42
+ HTM_TAG__MAX_DEPTH Max hierarchy depth (default: 4)
43
+
44
+ Proposition Extraction:
45
+ HTM_PROPOSITION__PROVIDER Provider (default: lms)
46
+ HTM_PROPOSITION__MODEL Model (default: google/gemma-3-4b)
47
+ HTM_PROPOSITION__TIMEOUT Timeout seconds (default: 180)
48
+ HTM_PROPOSITION__ENABLED Enable extraction (default: true)
49
+
50
+ Chunking:
51
+ HTM_CHUNKING__CHUNK_SIZE Max chars per chunk (default: 1024)
52
+ HTM_CHUNKING__CHUNK_OVERLAP Chunk overlap chars (default: 64)
53
+
54
+ Job Backend:
55
+ HTM_JOB__BACKEND Backend: fiber (default), thread, inline, active_job, sidekiq
56
+
57
+ Provider API Keys:
58
+ HTM_PROVIDERS__LMS__URL LM Studio URL (default: http://localhost:1234/v1)
59
+ HTM_PROVIDERS__LMS__API_KEY LM Studio API key (only if the server requires auth)
60
+ HTM_PROVIDERS__APFEL__URL apfel URL (unset: the apfel gem's own base URL)
61
+ HTM_PROVIDERS__OPENAI__API_KEY OpenAI API key
62
+ HTM_PROVIDERS__ANTHROPIC__API_KEY Anthropic API key
63
+ HTM_PROVIDERS__GEMINI__API_KEY Google Gemini API key
64
+ HTM_PROVIDERS__AZURE__API_KEY Azure OpenAI API key
65
+ HTM_PROVIDERS__AZURE__ENDPOINT Azure OpenAI endpoint
66
+
67
+ Other:
68
+ HTM_LOG_LEVEL Log level (default: info)
69
+ HTM_CONNECTION_TIMEOUT Connection timeout seconds (default: 60)
70
+ HTM_TELEMETRY_ENABLED Enable OpenTelemetry (default: false)
71
+
72
+ TEXT
73
+ end
74
+ end
@@ -0,0 +1,97 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "thor"
4
+
5
+ class HTM
6
+ class CLI < Thor
7
+ # A fix-it hint for a database error. It applies to a (downcased) error
8
+ # message that contains every `all` substring, at least one `any`
9
+ # substring when any are given, and none of the `none` substrings.
10
+ # A "{dbname}" token in its lines is replaced with the database name.
11
+ ErrorSuggestion = Data.define(:lines, :all, :any, :none) do
12
+ def initialize(lines:, all: [], any: [], none: [])
13
+ super
14
+ end
15
+
16
+ def applies_to?(message)
17
+ found = message.method(:include?)
18
+ all.all?(&found) && (any.empty? || any.any?(&found)) && none.none?(&found)
19
+ end
20
+
21
+ def lines_for(dbname) = lines.map { it.sub("{dbname}", dbname.to_s) }
22
+
23
+ # The fix-it lines for a database error message, naming the configured
24
+ # database (HTM_DATABASE__URL or HTM_DATABASE__NAME)
25
+ #
26
+ # @param message [String]
27
+ # @param database [String, nil] a database name or connection URL
28
+ # @return [Array<String>]
29
+ #
30
+ def self.for_error(message, database = ENV["HTM_DATABASE__URL"] || ENV.fetch("HTM_DATABASE__NAME", nil))
31
+ text = message.to_s.downcase
32
+ suggestion = self::ALL.find { it.applies_to?(text) } || self::FALLBACK
33
+ suggestion.lines_for(database_name(database))
34
+ end
35
+
36
+ # The database name in a connection URL, or the value itself when it is a name
37
+ def self.database_name(url_or_name)
38
+ return url_or_name unless url_or_name&.include?("://")
39
+
40
+ url_or_name[%r{/([^/?]+)(?:\?|$)}, 1] || "htm_development"
41
+ end
42
+ end
43
+
44
+ # Suggestions for database errors, most specific first
45
+ ErrorSuggestion::ALL = [
46
+ ErrorSuggestion.new(
47
+ all: ["does not exist"],
48
+ none: ["role"],
49
+ lines: ["Suggestion: The database does not exist. Create it with:",
50
+ " createdb {dbname}",
51
+ "Then initialize the schema with:", " htm db setup"]
52
+ ),
53
+ ErrorSuggestion.new(
54
+ any: ["password authentication failed", "no password supplied"],
55
+ lines: ["Suggestion: Check your database credentials.",
56
+ "Verify HTM_DATABASE__URL has correct username and password:",
57
+ " postgresql://USER:PASSWORD@localhost:5432/DATABASE"]
58
+ ),
59
+ ErrorSuggestion.new(
60
+ any: ["connection refused", "could not connect"],
61
+ lines: ["Suggestion: PostgreSQL server is not running or not accepting connections.",
62
+ "Start PostgreSQL with:",
63
+ " brew services start postgresql@17 # macOS with Homebrew",
64
+ " sudo systemctl start postgresql # Linux"]
65
+ ),
66
+ ErrorSuggestion.new(
67
+ all: ["role", "does not exist"],
68
+ lines: ["Suggestion: The database user does not exist. Create it with:",
69
+ " createuser -s YOUR_USERNAME"]
70
+ ),
71
+ ErrorSuggestion.new(
72
+ all: ["permission denied"],
73
+ lines: ["Suggestion: The user lacks permission to access this database.",
74
+ "Grant access or use a different user with appropriate privileges."]
75
+ ),
76
+ ErrorSuggestion.new(
77
+ any: ["timeout", "timed out"],
78
+ lines: ["Suggestion: Connection timed out. Check:",
79
+ " - PostgreSQL is running",
80
+ " - Firewall allows connections on port 5432",
81
+ " - Host address is correct"]
82
+ ),
83
+ ErrorSuggestion.new(
84
+ all: %w[extension vector],
85
+ lines: ["Suggestion: pgvector extension is not installed. Install it with:",
86
+ " brew install pgvector # macOS",
87
+ "Then enable it in your database:",
88
+ " psql -d DATABASE -c 'CREATE EXTENSION vector;'"]
89
+ )
90
+ ].freeze
91
+
92
+ # Shown when no suggestion applies
93
+ ErrorSuggestion::FALLBACK = ErrorSuggestion.new(
94
+ lines: ["Suggestion: Run 'htm env' for the configuration variables."]
95
+ )
96
+ end
97
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ # HTM file loading tasks: htm files SUBCOMMAND
4
+ #
5
+ # htm files load docs/guide.md [--force]
6
+ # htm files load_dir docs/ ["**/*.md"] [--force]
7
+ # htm files sync
8
+
9
+ require_relative "group"
10
+
11
+ class HTM
12
+ class CLI < Thor
13
+ # The file commands (htm files SUBCOMMAND): load markdown files into memory and keep them in sync
14
+ class Files < Thor
15
+ include Group
16
+
17
+ desc "load PATH", "Load a markdown file into long-term memory"
18
+ option :force, type: :boolean, default: false, desc: "Reload even if the file hasn't changed"
19
+ def load(path) = htm_task { it::FileCommands.load(path, force: options[:force]) }
20
+
21
+ desc "load_dir PATH [PATTERN]", "Load every file matching PATTERN (default **/*.md) under PATH"
22
+ option :force, type: :boolean, default: false, desc: "Reload even if a file hasn't changed"
23
+ def load_dir(path, pattern = "**/*.md") = htm_task { it::FileCommands.load_dir(path, pattern:, force: options[:force]) }
24
+
25
+ desc "list", "List all loaded files"
26
+ def list = htm_task { it::FileCommands.list }
27
+
28
+ desc "info PATH", "Show details for a loaded file"
29
+ def info(path) = htm_task { it::FileCommands.info(path) }
30
+
31
+ desc "unload PATH", "Unload a file from memory (soft deletes its chunks)"
32
+ def unload(path) = htm_task { it::FileCommands.unload(path) }
33
+
34
+ desc "sync", "Reload every loaded file that changed on disk"
35
+ def sync = htm_task { it::FileCommands.sync }
36
+
37
+ desc "stats", "Show file loading statistics"
38
+ def stats = htm_task { it::FileCommands.stats }
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "support"
4
+ require_relative "config_file"
5
+
6
+ class HTM
7
+ class CLI < Thor
8
+ # Mixed into every HTM::CLI command class: the shared helpers, a
9
+ # non-zero exit status on failure, and the -c/--config option.
10
+ module Group
11
+ def self.included(base)
12
+ base.include Support
13
+ base.extend ClassMethods
14
+ base.check_unknown_options!
15
+ base.class_option :config, aliases: "-c", type: :string, banner: "PATH",
16
+ desc: "Load configuration from a YAML file"
17
+ end
18
+
19
+ # Thor class settings
20
+ module ClassMethods
21
+ def exit_on_failure? = true
22
+ end
23
+
24
+ # Load --config before the command runs. Thor runs the root command
25
+ # (db, tags, ...) and then the subcommand; ConfigFile.load loads a path once.
26
+ # A setting HTM's configuration rejects (HTM_JOB__BACKEND=bogus) ends
27
+ # the command with its message and exit status 1 instead of a backtrace.
28
+ def invoke_command(*)
29
+ path = options[:config]
30
+ ConfigFile.load(path) if path
31
+ super
32
+ rescue StandardError => e
33
+ raise unless configuration_error?(e)
34
+
35
+ # Not warn: it is silent once HTM sets $VERBOSE to nil
36
+ $stderr.puts "Configuration error: #{e.message}", ErrorSuggestion::FALLBACK.lines # rubocop:disable Style/StderrPuts
37
+ exit 1
38
+ end
39
+
40
+ private
41
+
42
+ # Whether +error+ is anyway_config refusing a setting (its class is only there once HTM is loaded)
43
+ def configuration_error?(error) = defined?(Anyway::Config::ValidationError) && error.is_a?(Anyway::Config::ValidationError)
44
+ end
45
+ end
46
+ end