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,319 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>{{TITLE}}</title>
7
+ <link rel="preconnect" href="https://fonts.googleapis.com">
8
+ <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Literata:opsz,wght@7..72,400;7..72,600&family=Inter:wght@400;500;600&display=swap">
9
+ <!--
10
+ Written by `htm tags graph` (HTM::Admin::TagGraph) and `htm entities graph`
11
+ (HTM::Admin::EntityGraph). The graph data and d3 are embedded below, so the
12
+ file opens straight from disk. A node may carry h (heading), k (kind line),
13
+ tl (label of its t list) and r (radius); meta may carry theme, note, lede,
14
+ figs, slider and labels (group, others, find, links) in place of the tag
15
+ graph's look and wording.
16
+ -->
17
+ <style>
18
+ /* VOICE work: a research figure for one person exploring their own memory store
19
+ IDEA a journal's network figure plate, inked in a few printing colours
20
+ PICTURE the live force-directed network of tagged nodes, coloured by tag branch or source
21
+ COLOUR white plate / ink #10131a; prussian, carmine, violet, ochre, teal, magenta, olive, umber
22
+ TYPE Literata for the title and figures, Inter for labels and controls
23
+ LAYOUT laptop: title row with figures, then network (1fr) beside a node panel (340px); phone: title, network, panel */
24
+ :root{color-scheme:light dark;--bg:light-dark(#ffffff,#0f1217);--ink:light-dark(#10131a,#e8eaef);--mute:light-dark(#5b6170,#a2a8b6);--rule:light-dark(#e3e5ea,#262b35);--zone:light-dark(#f5f6f8,#161a22);--acc:light-dark(#c1121f,#ff6b74);
25
+ --c0:light-dark(#0b4f8a,#6fb1f0);--c1:light-dark(#c1121f,#ff6b74);--c2:light-dark(#6a3d9a,#b99be0);--c3:light-dark(#a8690c,#f0b44c);--c4:light-dark(#0f766e,#4fd1c5);--c5:light-dark(#be185d,#f472b6);--c6:light-dark(#4d7c0f,#a3d65c);--c7:light-dark(#7c4a2d,#d6a07a);--other:light-dark(#8a8f98,#7d8494)}
26
+ :root[data-theme=light]{color-scheme:light}:root[data-theme=dark]{color-scheme:dark}
27
+ *{box-sizing:border-box;min-width:0}
28
+ [hidden]{display:none!important}
29
+ html,body{margin:0}
30
+ body{background:var(--bg);color:var(--ink);font:16px/1.55 Inter,system-ui,sans-serif;overflow-x:clip}
31
+ .band{padding:clamp(20px,3vw,40px) max(4vw,16px)}
32
+ .head{display:grid;grid-template-columns:minmax(0,1.3fr) minmax(0,1fr);gap:24px 40px;align-items:end;border-bottom:1px solid var(--rule)}
33
+ h1{font:600 clamp(30px,4vw,46px)/1.05 Literata,Georgia,serif;letter-spacing:-.02em;margin:0 0 10px;text-wrap:balance}
34
+ .lede{margin:0;color:var(--mute);max-width:62ch}
35
+ .lede b{color:var(--ink);font-weight:600}
36
+ .figs{display:grid;grid-template-columns:repeat(auto-fit,minmax(6.5em,1fr));gap:12px}
37
+ .figs div{border-top:2px solid var(--ink);padding-top:6px}
38
+ .figs strong{display:block;font:600 clamp(24px,3vw,32px)/1.1 Literata,Georgia,serif;font-variant-numeric:tabular-nums}
39
+ .figs span{font-size:13px;color:var(--mute)}
40
+ .main{display:grid;grid-template-columns:minmax(0,1fr) 340px;gap:24px;padding-top:20px}
41
+ .ctl{display:flex;flex-wrap:wrap;gap:10px 18px;align-items:center;margin-bottom:12px;font-size:14px}
42
+ .ctl label{display:flex;align-items:center;gap:8px;white-space:nowrap}
43
+ input[type=range]{width:150px;accent-color:var(--ink);height:28px}
44
+ input[type=search]{font:16px Inter,sans-serif;padding:8px 12px;border:1px solid var(--rule);border-radius:6px;background:var(--bg);color:var(--ink);width:15em}
45
+ input[type=checkbox]{width:18px;height:18px;accent-color:var(--ink)}
46
+ .seg{display:inline-flex;border:1px solid var(--rule);border-radius:6px;overflow:hidden}
47
+ .seg button{font:500 14px Inter,sans-serif;border:0;background:none;color:var(--mute);padding:9px 14px;cursor:pointer;min-height:40px}
48
+ .seg button[aria-pressed=true]{background:var(--ink);color:var(--bg)}
49
+ button:focus-visible,input:focus-visible{outline:2px solid var(--acc);outline-offset:2px}
50
+ .fig{position:relative;height:min(72svh,700px);min-height:420px;background:var(--zone);border-radius:8px;overflow:hidden}
51
+ .fig canvas{position:absolute;inset:0;width:100%;height:100%;cursor:grab;touch-action:none}
52
+ .fig canvas.hover{cursor:pointer}
53
+ .status{position:absolute;left:12px;bottom:10px;font-size:13px;color:var(--mute);pointer-events:none}
54
+ .tip{position:absolute;pointer-events:none;max-width:300px;background:var(--bg);border:1px solid var(--rule);border-radius:6px;padding:8px 10px;font-size:13px;line-height:1.4;box-shadow:0 4px 14px color-mix(in srgb,var(--ink) 12%,transparent);display:none}
55
+ .legend{display:flex;flex-wrap:wrap;gap:6px 8px;margin-top:12px}
56
+ .legend button{display:flex;align-items:center;gap:7px;font:13px Inter,sans-serif;color:var(--ink);background:none;border:1px solid var(--rule);border-radius:20px;padding:6px 12px;cursor:pointer;min-height:36px}
57
+ .legend button[aria-pressed=true]{border-color:var(--ink);background:var(--zone)}
58
+ .legend i{width:11px;height:11px;border-radius:50%;flex:none}
59
+ .legend em{font-style:normal;color:var(--mute);font-variant-numeric:tabular-nums}
60
+ .panel{border-left:1px solid var(--rule);padding-left:22px;font-size:15px}
61
+ .panel h2{font:600 22px/1.2 Literata,Georgia,serif;margin:0 0 4px}
62
+ .kind{font-size:13px;color:var(--mute);margin:0 0 12px}
63
+ .content{background:var(--zone);border-radius:6px;padding:12px 14px;margin:0 0 14px;line-height:1.5;max-height:240px;overflow:auto;overflow-wrap:anywhere}
64
+ .panel h3{font:600 14px Inter,sans-serif;margin:16px 0 6px}
65
+ .tags{display:flex;flex-wrap:wrap;gap:6px}
66
+ .tags span{font-size:13px;background:var(--zone);border-radius:4px;padding:2px 7px;overflow-wrap:anywhere}
67
+ .nbrs{list-style:none;margin:0;padding:0;max-height:300px;overflow:auto}
68
+ .nbrs button{display:grid;grid-template-columns:10px minmax(0,1fr) auto;gap:8px;align-items:baseline;width:100%;text-align:left;background:none;border:0;border-bottom:1px solid var(--rule);padding:8px 2px;font:13px/1.4 Inter,sans-serif;color:var(--ink);cursor:pointer}
69
+ .nbrs button:hover{background:var(--zone)}
70
+ .nbrs i{width:9px;height:9px;border-radius:50%;align-self:center}
71
+ .nbrs span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
72
+ .nbrs b{font-weight:600;font-variant-numeric:tabular-nums}
73
+ .src{font-size:13px;color:var(--mute);margin-top:14px;overflow-wrap:anywhere}
74
+ .src a{color:var(--ink)}
75
+ .foot{font-size:13px;color:var(--mute);border-top:1px solid var(--rule)}
76
+ @media(max-width:900px){.main{grid-template-columns:minmax(0,1fr)}.panel{border-left:0;padding-left:0;border-top:1px solid var(--rule);padding-top:18px}.head{grid-template-columns:minmax(0,1fr)}}
77
+ @media(max-width:600px){.fig{height:62svh;min-height:360px}input[type=search]{width:100%}.ctl label.grow{flex:1 1 100%}}
78
+ </style>
79
+ </head>
80
+ <body>
81
+ <header class="band head">
82
+ <div>
83
+ <h1>{{TITLE}}</h1>
84
+ <p class="lede" id="lede">Loading data…</p>
85
+ </div>
86
+ <div class="figs" id="figs"></div>
87
+ </header>
88
+ <section class="band main">
89
+ <div>
90
+ <div class="ctl">
91
+ <label for="w" id="wl">Min link weight <input type="range" id="w" min="0.1" max="1" step="0.05" value="0.35"><b id="wv">0.35</b></label>
92
+ <span class="seg" id="by" role="group" aria-label="Colour nodes by"><button type="button" id="byB" aria-pressed="true">Tag branch</button><button type="button" id="byA" aria-pressed="false">Source</button></span>
93
+ <label for="props" id="pl"><input type="checkbox" id="props" checked> Propositions</label>
94
+ <label class="grow" for="q"><input type="search" id="q" placeholder="Find text or tag" autocomplete="off"></label>
95
+ </div>
96
+ <div class="fig" id="fig"><canvas id="cv" aria-label="Network of memory nodes"></canvas><div class="tip" id="tip"></div><div class="status" id="status">Loading graph…</div></div>
97
+ <div class="legend" id="legend"></div>
98
+ </div>
99
+ <aside class="panel" id="panel" aria-live="polite"></aside>
100
+ </section>
101
+ <footer class="band foot">Snapshot of <code>{{DATABASE}}</code> taken {{GENERATED}}. <span id="note">Link weight is the cosine similarity of two nodes' embeddings, or the Jaccard overlap of the entities they mention when that is higher, as computed by <code>GenerateRelationshipsJob</code>. A node is linked to its nearest neighbors only, and never to its own source or sibling propositions. Drag to pan, scroll or pinch to zoom, click a node for its details. Regenerate with <code>htm tags graph</code>.</span></footer>
102
+ <script type="application/json" id="graph-data">{{DATA}}</script>
103
+ {{D3}}
104
+ <script>
105
+ {
106
+ const COLORS = 8, BRANCH_COLORS = 6;
107
+ const $ = id => document.getElementById(id);
108
+ const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
109
+ const cv = $('cv'), ctx = cv.getContext('2d'), fig = $('fig'), tip = $('tip');
110
+ const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
111
+ let data, nodes, byId, byKey, adj, srcById, L, colorBy = 'b', isolate = null, sel = null, pinned = false, fitted = false, hover = null, query = '';
112
+ let transform = d3.zoomIdentity, W = 0, H = 0, sim, links = [], pal = {};
113
+
114
+ function readPalette() {
115
+ // light-dark() resolves only on use, so read each colour back through an element
116
+ const probe = document.createElement('i'); document.body.appendChild(probe);
117
+ const res = v => { probe.style.color = `var(${v})`; return getComputedStyle(probe).color; };
118
+ pal.c = Array.from({ length: COLORS }, (_, i) => res('--c' + i));
119
+ pal.other = res('--other'); pal.ink = res('--ink'); pal.mute = res('--mute'); pal.bg = res('--zone');
120
+ probe.remove();
121
+ }
122
+ const branchKey = n => data.branches.indexOf(n.b) >= 0 ? n.b : 'other';
123
+ const sourceKey = n => n.s ?? 'none';
124
+ const groupOf = n => colorBy === 'b' ? branchKey(n) : sourceKey(n);
125
+ function colorOf(n) {
126
+ const i = colorBy === 'b' ? data.branches.indexOf(n.b) : data.sources.findIndex(s => s.id === n.s);
127
+ return i >= 0 && i < (colorBy === 'b' ? BRANCH_COLORS : COLORS) ? pal.c[i] : pal.other;
128
+ }
129
+ const short = (s, n = 110) => s.length > n ? s.slice(0, n - 2) + '…' : s;
130
+ const plural = (n, word) => `${n.toLocaleString()} ${word}${n === 1 ? '' : 's'}`;
131
+ const LABELS = { group: 'Tag branch', others: 'other branches', find: 'Find text or tag', links: 'Strongest links' };
132
+ const rad = n => n.r ?? (n.p ? 4 : 7.5);
133
+ const nameOf = n => n.h ?? short(n.c);
134
+
135
+ function figures() {
136
+ if (data.meta.lede) $('lede').textContent = data.meta.lede; else tagLede();
137
+ const props = nodes.filter(n => n.p).length;
138
+ const figs = data.meta.figs ?? [[nodes.length, 'nodes'], [props, 'propositions'], [data.edges.length, 'tag links'], [data.sources.length, 'sources']];
139
+ $('figs').innerHTML = figs.map(([v, l]) => `<div><strong>${esc(v.toLocaleString())}</strong><span>${esc(l)}</span></div>`).join('');
140
+ }
141
+
142
+ function tagLede() {
143
+ const top = data.branches[0];
144
+ const scope = data.meta.prefix ? ` tagged under <b>${esc(data.meta.prefix)}</b>` : '';
145
+ const lead = top ? ` <b>${esc(top)}</b> is the main branch of ${nodes.filter(n => n.b === top).length} of them; raise the weight to see tighter clusters.` : '';
146
+ $('lede').innerHTML = `${plural(nodes.length, 'memory node')}${scope} from ${plural(data.sources.length, 'source')}, joined by ${plural(data.edges.length, 'shared-tag link')}.${lead}`;
147
+ }
148
+
149
+ function legend() {
150
+ const groups = colorBy === 'b'
151
+ ? data.branches.slice(0, BRANCH_COLORS).map(b => ({ k: b, label: b }))
152
+ : data.sources.slice(0, COLORS).map(s => ({ k: s.id, label: short(s.title, 46) }));
153
+ const rest = nodes.filter(n => !groups.some(g => g.k === groupOf(n)));
154
+ if (rest.length) groups.push({ k: '__rest', label: colorBy === 'b' ? L.others : 'other sources' });
155
+ $('legend').innerHTML = groups.map((g, i) => {
156
+ const count = g.k === '__rest' ? rest.length : nodes.filter(n => groupOf(n) === g.k).length;
157
+ const color = g.k === '__rest' ? pal.other : pal.c[i];
158
+ return `<button type="button" data-k="${esc(g.k)}" aria-pressed="${isolate === g.k}" title="${esc(g.label)}"><i style="background:${color}"></i>${esc(g.label)} <em>${count}</em></button>`;
159
+ }).join('');
160
+ }
161
+
162
+ function inGroup(n) {
163
+ if (!isolate) return true;
164
+ if (isolate !== '__rest') return groupOf(n) === isolate;
165
+ return colorOf(n) === pal.other;
166
+ }
167
+
168
+ function rebuild(alpha = 0.6) {
169
+ const w = +$('w').value; $('wv').textContent = w.toFixed(2);
170
+ const vis = new Set(nodes.filter(n => $('props').checked || !n.p).map(n => n.id));
171
+ links = data.edges.filter(e => e[2] >= w && vis.has(e[0]) && vis.has(e[1])).map(e => ({ source: byId.get(e[0]), target: byId.get(e[1]), w: e[2] }));
172
+ sim.nodes(nodes.filter(n => vis.has(n.id)));
173
+ sim.force('link').links(links);
174
+ sim.alpha(reduce ? 0 : alpha).restart();
175
+ if (reduce) { for (let i = 0; i < 200; i++) sim.tick(); draw(); }
176
+ $('status').textContent = `Showing ${vis.size.toLocaleString()} nodes and ${links.length.toLocaleString()} of ${data.edges.length.toLocaleString()} links`;
177
+ }
178
+
179
+ function matches(n) { if (!query) return true; const q = query.toLowerCase(); return `${n.h ?? ''} ${n.c}`.toLowerCase().includes(q) || n.t.some(t => t.toLowerCase().includes(q)); }
180
+
181
+ function draw() {
182
+ ctx.save(); ctx.clearRect(0, 0, W, H);
183
+ ctx.translate(transform.x, transform.y); ctx.scale(transform.k, transform.k);
184
+ const lit = sel && pinned ? new Set([sel.id, ...adj.get(sel.id).map(x => x.id)]) : null;
185
+ ctx.lineWidth = 1 / transform.k;
186
+ for (const l of links) {
187
+ const on = lit ? (l.source === sel || l.target === sel) : true;
188
+ ctx.globalAlpha = on ? (lit ? 0.75 : 0.06 + l.w * 0.3) : 0.025;
189
+ ctx.strokeStyle = on && lit ? colorOf(sel) : pal.mute;
190
+ ctx.beginPath(); ctx.moveTo(l.source.x, l.source.y); ctx.lineTo(l.target.x, l.target.y); ctx.stroke();
191
+ }
192
+ for (const n of sim.nodes()) {
193
+ const dim = (lit && !lit.has(n.id)) || !inGroup(n) || !matches(n);
194
+ ctx.globalAlpha = dim ? 0.13 : 1;
195
+ const r = rad(n);
196
+ ctx.beginPath(); ctx.arc(n.x, n.y, r, 0, 2 * Math.PI);
197
+ ctx.fillStyle = colorOf(n); ctx.fill();
198
+ if (!n.p) { ctx.lineWidth = 2 / transform.k; ctx.strokeStyle = pal.bg; ctx.stroke(); ctx.lineWidth = 1 / transform.k; }
199
+ if (n === sel || n === hover) { ctx.globalAlpha = 1; ctx.beginPath(); ctx.arc(n.x, n.y, r + 4 / transform.k, 0, 2 * Math.PI); ctx.lineWidth = 2 / transform.k; ctx.strokeStyle = pal.ink; ctx.stroke(); ctx.lineWidth = 1 / transform.k; }
200
+ }
201
+ ctx.restore();
202
+ }
203
+
204
+ function tagList(tags) { return tags.map(t => `<span>${esc(t)}</span>`).join(''); }
205
+
206
+ function panel(n) {
207
+ const src = srcById.get(n.s);
208
+ const nb = adj.get(n.id).slice().sort((a, b) => b.w - a.w);
209
+ const pre = data.meta.prefix, deep = (a, b) => b.split(':').length - a.split(':').length || a.localeCompare(b);
210
+ const under = pre ? n.t.filter(t => t.startsWith(pre + ':')).sort(deep).map(t => t.slice(pre.length + 1)) : n.t.slice().sort(deep);
211
+ const other = pre ? n.t.filter(t => t !== pre && !t.startsWith(pre + ':')) : [];
212
+ const where = src ? (src.url ? `<a href="${esc(src.url)}" target="_blank" rel="noopener">${esc(src.title)}</a>` : esc(src.title)) : '';
213
+ $('panel').innerHTML = `
214
+ <h2>${esc(n.h ?? 'Node ' + n.id)}</h2>
215
+ <p class="kind">${esc(n.k ?? `${n.p ? 'Proposition' : 'Memory'} · ${n.b}`)} · ${esc(plural(nb.length, 'link'))}</p>
216
+ <p class="content">${esc(n.c)}</p>
217
+ <h3>${esc(n.tl ?? (pre ? `Tags under ${pre}` : 'Tags'))}</h3><div class="tags">${tagList(under) || '<span>none</span>'}</div>
218
+ ${other.length ? `<h3>Other tags</h3><div class="tags">${tagList(other)}</div>` : ''}
219
+ <h3>${esc(L.links)}</h3>
220
+ <ul class="nbrs">${nb.slice(0, 40).map(x => `<li><button type="button" data-id="${esc(x.id)}"><i style="background:${colorOf(byId.get(x.id))}"></i><span>${esc(nameOf(byId.get(x.id)))}</span><b>${x.w.toFixed(2)}</b></button></li>`).join('') || '<li>none</li>'}</ul>
221
+ ${src ? `<p class="src">From ${where}${src.detail ? ', ' + esc(src.detail) : ''}</p>` : ''}`;
222
+ }
223
+
224
+ function fit() {
225
+ const on = new Set(links.flatMap(l => [l.source, l.target]));
226
+ const ns = sim.nodes().filter(n => on.has(n));
227
+ if (!ns.length) return;
228
+ const xs = ns.map(n => n.x).sort((a, b) => a - b), ys = ns.map(n => n.y).sort((a, b) => a - b);
229
+ const q = (a, f) => a[Math.floor((a.length - 1) * f)];
230
+ const x0 = q(xs, 0.02), x1 = q(xs, 0.98), y0 = q(ys, 0.02), y1 = q(ys, 0.98);
231
+ const k = Math.min(4, 0.85 * Math.min(W / (x1 - x0 || 1), H / (y1 - y0 || 1)));
232
+ d3.select(cv).transition().duration(reduce ? 0 : 600).call(zoom.transform, d3.zoomIdentity.translate(W / 2, H / 2).scale(k).translate(-(x0 + x1) / 2, -(y0 + y1) / 2));
233
+ }
234
+
235
+ function select(n, center, pin = true) {
236
+ sel = n; pinned = pin; panel(n); draw();
237
+ if (center && n.x != null) d3.select(cv).transition().duration(reduce ? 0 : 500).call(zoom.translateTo, n.x, n.y);
238
+ }
239
+
240
+ function nodeAt(ev) {
241
+ const [mx, my] = d3.pointer(ev, cv); const [x, y] = transform.invert([mx, my]);
242
+ const n = sim.find(x, y, 12 / transform.k);
243
+ return n && ((n.x - x) ** 2 + (n.y - y) ** 2) <= (rad(n) + 6 / transform.k) ** 2 ? n : null;
244
+ }
245
+
246
+ const zoom = d3.zoom().scaleExtent([0.1, 8]).on('zoom', ev => { transform = ev.transform; draw(); });
247
+
248
+ function size() {
249
+ const r = fig.getBoundingClientRect(), dpr = window.devicePixelRatio || 1;
250
+ W = r.width; H = r.height; cv.width = W * dpr; cv.height = H * dpr; ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
251
+ if (sim) draw();
252
+ }
253
+
254
+ function start(d) {
255
+ data = d; nodes = d.nodes; byId = new Map(nodes.map(n => [n.id, n])); byKey = new Map(nodes.map(n => [String(n.id), n]));
256
+ L = { ...LABELS, ...d.meta.labels }; controls();
257
+ srcById = new Map(d.sources.map(s => [s.id, s]));
258
+ adj = new Map(nodes.map(n => [n.id, []]));
259
+ for (const [s, t, w] of d.edges) { adj.get(s)?.push({ id: t, w }); adj.get(t)?.push({ id: s, w }); }
260
+ readPalette(); figures(); legend();
261
+ if (!nodes.length) { $('status').textContent = 'No nodes to show'; return; }
262
+ sim = d3.forceSimulation().force('charge', d3.forceManyBody().strength(-38).distanceMax(400))
263
+ .force('link', d3.forceLink().strength(l => 0.08 + l.w * 0.5).distance(l => 70 - l.w * 40))
264
+ .force('collide', d3.forceCollide(n => rad(n) + 1.5)).force('x', d3.forceX().strength(0.04)).force('y', d3.forceY().strength(0.04))
265
+ .on('tick', draw).on('end', () => { if (!fitted) { fitted = true; fit(); } });
266
+ size(); transform = d3.zoomIdentity.translate(W / 2, H / 2).scale(0.8);
267
+ d3.select(cv).call(zoom).call(zoom.transform, transform);
268
+ rebuild(1);
269
+ const hub = nodes.filter(n => !n.p).sort((a, b) => adj.get(b.id).length - adj.get(a.id).length)[0] || nodes[0];
270
+ select(hub, false, false);
271
+ if (reduce) { fitted = true; fit(); }
272
+ }
273
+
274
+ function controls() {
275
+ if (data.meta.theme) document.documentElement.dataset.theme = data.meta.theme;
276
+ if (data.meta.note) $('note').textContent = data.meta.note;
277
+ const slider = data.meta.slider;
278
+ if (slider === false) { $('w').value = $('w').min = 0; $('wl').hidden = true; }
279
+ else if (slider) { $('w').min = slider.min; $('w').value = slider.value; }
280
+ $('byB').textContent = L.group; $('q').placeholder = L.find;
281
+ $('by').hidden = !data.sources.length; $('pl').hidden = !nodes.some(n => n.p);
282
+ }
283
+
284
+ function refresh() { if (!data) return; readPalette(); legend(); if (sel) panel(sel); if (sim) draw(); }
285
+
286
+ cv.addEventListener('pointermove', ev => {
287
+ if (!sim) return;
288
+ const n = nodeAt(ev); cv.classList.toggle('hover', !!n);
289
+ if (n !== hover) { hover = n; draw(); }
290
+ if (n) { const [mx, my] = d3.pointer(ev, fig); tip.style.display = 'block'; tip.textContent = nameOf(n);
291
+ tip.style.left = Math.min(mx + 14, W - 310) + 'px'; tip.style.top = Math.min(my + 14, H - 90) + 'px'; }
292
+ else tip.style.display = 'none';
293
+ });
294
+ cv.addEventListener('pointerleave', () => { tip.style.display = 'none'; hover = null; if (sim) draw(); });
295
+ cv.addEventListener('click', ev => { if (!sim) return; const n = nodeAt(ev); if (n) select(n, false); else if (pinned) { pinned = false; draw(); } });
296
+ $('panel').addEventListener('click', ev => { const b = ev.target.closest('button[data-id]'); if (b) select(byKey.get(b.dataset.id), true); });
297
+ $('legend').addEventListener('click', ev => { const b = ev.target.closest('button[data-k]'); if (!b) return; isolate = isolate === b.dataset.k ? null : b.dataset.k; legend(); if (sim) draw(); });
298
+ $('w').addEventListener('input', () => sim && rebuild(0.4));
299
+ $('props').addEventListener('change', () => sim && rebuild(0.5));
300
+ $('q').addEventListener('input', ev => {
301
+ if (!sim) return;
302
+ query = ev.target.value.trim();
303
+ const hit = query && sim.nodes().find(matches); if (hit) select(hit, false, false); else draw();
304
+ });
305
+ for (const [id, k] of [['byB', 'b'], ['byA', 'a']]) $(id).addEventListener('click', () => {
306
+ colorBy = k; isolate = null; $('byB').setAttribute('aria-pressed', k === 'b'); $('byA').setAttribute('aria-pressed', k === 'a');
307
+ refresh();
308
+ });
309
+ const ro = new ResizeObserver(() => sim && size()); ro.observe(fig);
310
+ const themeObs = new MutationObserver(refresh);
311
+ themeObs.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
312
+ matchMedia('(prefers-color-scheme: dark)').addEventListener('change', refresh);
313
+
314
+ try { start(JSON.parse($('graph-data').textContent)); }
315
+ catch (err) { $('status').textContent = 'Could not read the embedded graph data: ' + err.message; }
316
+ }
317
+ </script>
318
+ </body>
319
+ </html>
data/lib/htm/admin.rb ADDED
@@ -0,0 +1,266 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'ruby-progressbar'
4
+ require "htm"
5
+
6
+ class HTM
7
+ # Operational commands behind the htm command line (lib/htm/cli/*.rb).
8
+ #
9
+ # Each command is a thin wrapper that parses its arguments and calls one
10
+ # method here. The methods write their report to +out+ and read any
11
+ # confirmation from +input+, so they run the same from the command line,
12
+ # a console or a test.
13
+ #
14
+ # @example
15
+ # require "htm/admin"
16
+ # HTM::Admin::DatabaseCommands.stats
17
+ #
18
+ module Admin
19
+ # A command that cannot proceed (a missing file, an unknown path). The
20
+ # task reports the message and exits non-zero.
21
+ class Error < HTM::Error; end
22
+
23
+ PROGRESS_FORMAT = '%t: |%B| %c/%C (%p%%) %e'
24
+
25
+ # The terminal an admin command talks to: the command reports to +out+
26
+ # and reads confirmations from +input+. Each command module subclasses
27
+ # it with the commands that print, so a test runs one against StringIOs.
28
+ #
29
+ # @example
30
+ # HTM::Admin::TagCommands::Console.new(out: StringIO.new).tree("ai")
31
+ #
32
+ class Console
33
+ # @return [IO] where the command's report goes
34
+ attr_reader :out
35
+
36
+ # @return [IO] where confirmations are read from
37
+ attr_reader :input
38
+
39
+ # @param out [IO]
40
+ # @param input [IO]
41
+ # @param assume_yes [Boolean, nil] answer every confirmation "yes" (a --yes flag)
42
+ #
43
+ def initialize(out: $stdout, input: $stdin, assume_yes: nil)
44
+ @out = out
45
+ @input = input
46
+ @assume_yes = assume_yes
47
+ end
48
+
49
+ # @return [Boolean] true with assume_yes, else whether the answer to +prompt+ is "yes"
50
+ def confirmed?(prompt) = @assume_yes || Admin.confirmed?(prompt, input:, out: prompt_out)
51
+
52
+ # @return [Boolean] whether the user typed "yes" to go ahead
53
+ def proceed? = confirmed?("\nType 'yes' to confirm: ")
54
+
55
+ # @return [nil] after reporting a cancelled command
56
+ def cancelled = Admin.cancelled(out)
57
+
58
+ # @return [nil] after reporting an aborted command
59
+ def aborted = Admin.aborted(out)
60
+
61
+ # @return [nil] after writing +line+
62
+ def say(line) = Admin.say(out, line)
63
+
64
+ # Print +title+ on a line of its own, underlined with +width+ "="
65
+ def heading(title, width = 50)
66
+ out.puts "\n#{title}"
67
+ out.puts "=" * width
68
+ end
69
+
70
+ # Print +title+ and one line per entry of +counts+ (see Admin.print_counts)
71
+ def print_counts(title, counts) = Admin.print_counts(title, counts, out:)
72
+
73
+ # Admin.each_with_progress, reporting to +out+
74
+ def each_with_progress(dataset, title, &) = Admin.each_with_progress(dataset, title, out:, &)
75
+
76
+ private
77
+
78
+ # Where confirmation prompts are written
79
+ def prompt_out = out
80
+ end
81
+
82
+ module_function
83
+
84
+ # Connect to the configured HTM database (no-op when already connected)
85
+ def connect! = HTM::SequelConfig.establish_connection!
86
+
87
+ # Print +prompt+ and read one line; true only when the answer is "yes"
88
+ #
89
+ # @param prompt [String]
90
+ # @param input [IO] Where the answer is read from
91
+ # @param out [IO] Where the prompt is written
92
+ # @return [Boolean]
93
+ #
94
+ def confirmed?(prompt, input: $stdin, out: $stdout)
95
+ out.print prompt
96
+ out.flush
97
+ input.gets.to_s.strip.casecmp?("yes")
98
+ end
99
+
100
+ # Report a cancelled command
101
+ #
102
+ # @param out [IO]
103
+ # @return [nil]
104
+ #
105
+ def cancelled(out) = say(out, "Cancelled.")
106
+
107
+ # Report an aborted command
108
+ #
109
+ # @param out [IO]
110
+ # @return [nil]
111
+ #
112
+ def aborted(out) = say(out, "Aborted.")
113
+
114
+ # Write +line+ to +out+
115
+ #
116
+ # @return [nil]
117
+ #
118
+ def say(out, line)
119
+ out.puts line
120
+ nil
121
+ end
122
+
123
+ # Yield each record of +dataset+ under a ruby-progressbar bar with an
124
+ # ETA. A record whose block raises is counted as failed and logged on
125
+ # the bar; the rest carry on. Each record's changes commit as the block
126
+ # finishes them (see each_by_id).
127
+ #
128
+ # @param dataset [Sequel::Dataset]
129
+ # @param title [String] Progress bar title
130
+ # @param out [IO]
131
+ # @yieldparam record [Sequel::Model]
132
+ # @yieldparam bar [ProgressBar::Base] For warnings (bar.log)
133
+ # @return [Hash] { ok: Integer, failed: Integer }
134
+ #
135
+ def each_with_progress(dataset, title, out: $stdout)
136
+ bar = ProgressBar.create(total: dataset.count, format: PROGRESS_FORMAT, title:, output: out, smoothing: 0.5)
137
+ counts = { ok: 0, failed: 0 }
138
+
139
+ each_by_id(dataset) do |record|
140
+ yield record, bar
141
+ counts[:ok] += 1
142
+ rescue StandardError => e
143
+ counts[:failed] += 1
144
+ bar.log " Error on node #{record.id}: #{e.message}"
145
+ ensure
146
+ bar.increment
147
+ end
148
+
149
+ bar.finish
150
+ counts
151
+ end
152
+
153
+ # Yield each record of +dataset+ in id order, fetching +batch_size+ at a
154
+ # time by keyset (id > last id seen).
155
+ #
156
+ # Not Sequel's paged_each: that holds one transaction open for the whole
157
+ # loop, so hours of LLM enrichment stayed uncommitted (and rolled back on
158
+ # any crash). Keyset paging also survives a block that removes records
159
+ # from +dataset+ (filling in the very column it filters on), which
160
+ # OFFSET paging would skip.
161
+ #
162
+ # @param dataset [Sequel::Dataset] a dataset of rows with an +id+ column
163
+ # @param batch_size [Integer]
164
+ # @yieldparam record [Sequel::Model]
165
+ # @return [void]
166
+ #
167
+ def each_by_id(dataset, batch_size: 100)
168
+ id = Sequel.qualify(dataset.first_source_alias, :id)
169
+ last_id = nil
170
+
171
+ loop do
172
+ page = (last_id ? dataset.where(id > last_id) : dataset).order(id).limit(batch_size).all
173
+ break if page.empty?
174
+
175
+ page.each { yield it }
176
+ last_id = page.last.id
177
+ end
178
+ end
179
+
180
+ # Print +title+, then one indented "Label: value" line per entry of +counts+
181
+ #
182
+ # @param title [String]
183
+ # @param counts [Hash{String => Object}] label => value, printed in order
184
+ # @param out [IO]
185
+ # @return [void]
186
+ #
187
+ def print_counts(title, counts, out: $stdout)
188
+ out.puts title
189
+ counts.each { |label, value| out.puts " #{label}: #{value}" }
190
+ end
191
+
192
+ # @return [Float, Integer] +part+ as a percentage of +whole+ (one decimal), 0 when +whole+ is zero
193
+ def percentage(part, whole)
194
+ return 0 if whole.zero?
195
+
196
+ ((part.to_f / whole) * 100).round(1)
197
+ end
198
+
199
+ # @return [String] How long before +now+ +time+ was, e.g. "3 hours ago"
200
+ def time_ago(time, now: Time.now)
201
+ seconds = now - time
202
+ case seconds
203
+ when 0...60 then "#{seconds.to_i} seconds ago"
204
+ when 60...3600 then "#{(seconds / 60).to_i} minutes ago"
205
+ when 3600...86_400 then "#{(seconds / 3600).to_i} hours ago"
206
+ else "#{(seconds / 86_400).to_i} days ago"
207
+ end
208
+ end
209
+
210
+ # Generate and store +node+'s embedding
211
+ #
212
+ # @param node [HTM::Models::Node]
213
+ # @return [HTM::Models::Node]
214
+ #
215
+ def embed!(node)
216
+ result = HTM::EmbeddingService.generate(node.content)
217
+ node.update(embedding: result[:storage_embedding], embedding_dimension: result[:dimension])
218
+ end
219
+
220
+ # Extract +node+'s propositions and store each as a proposition node
221
+ # linked to +robot+, with its own embedding; text already stored is
222
+ # skipped as the background job skips it
223
+ # (GeneratePropositionsJob.store_proposition). The propositions then
224
+ # inherit the entities +node+ mentions, as they do after the job. An
225
+ # embedding failure is reported through +warn+ and does not stop the rest.
226
+ #
227
+ # @param node [HTM::Models::Node] The source node
228
+ # @param robot [HTM::Models::Robot] Robot the proposition nodes are linked to
229
+ # @param warn [#call] Receives a warning message
230
+ # @return [Integer] Proposition nodes created or revived
231
+ #
232
+ def extract_propositions!(node, robot, warn: ->(_message) {})
233
+ job = HTM::Jobs::GeneratePropositionsJob
234
+ embed = ->(proposition) { embed_reporting!(proposition, warn) }
235
+ created = HTM::PropositionService.extract(node.content).uniq.count do |text|
236
+ job.store_proposition(text, source: node, robot_id: robot.id, &embed)
237
+ end
238
+ HTM::EntityPropagation.to_propositions(node)
239
+ created
240
+ end
241
+
242
+ # Embed +node+, reporting a failure through +warn+ instead of raising
243
+ #
244
+ # @param node [HTM::Models::Node]
245
+ # @param warn [#call] Receives a warning message
246
+ def embed_reporting!(node, warn)
247
+ embed!(node)
248
+ rescue StandardError => e
249
+ warn.call(" Warning: Embedding failed for proposition #{node.id}: #{e.message}")
250
+ end
251
+
252
+ # The robot proposition nodes are linked to: the first robot, or a new one named +name+
253
+ def proposition_robot(name)
254
+ HTM::Models::Robot.first || HTM::Models::Robot.create(name:)
255
+ end
256
+ end
257
+ end
258
+
259
+ require_relative "admin/database_commands"
260
+ require_relative "admin/enrich_commands"
261
+ require_relative "admin/tag_commands"
262
+ require_relative "admin/tag_graph"
263
+ require_relative "admin/entity_commands"
264
+ require_relative "admin/entity_graph"
265
+ require_relative "admin/file_commands"
266
+ require_relative "admin/memory_commands"
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ class HTM
4
+ class CLI < Thor
5
+ # Applies a YAML config file (the -c/--config option) to HTM.config: its
6
+ # defaults section merged with the current environment's section.
7
+ module ConfigFile
8
+ module_function
9
+
10
+ # Nested config sections a config file may set
11
+ SECTIONS = %i[
12
+ database service embedding tag proposition chunking
13
+ circuit_breaker relevance job providers
14
+ ].freeze
15
+
16
+ # Apply the file at +path+ once; later calls with the same path do nothing
17
+ #
18
+ # @param path [String]
19
+ # @return [void]
20
+ #
21
+ def load(path)
22
+ return if @loaded == path
23
+
24
+ require "htm"
25
+ abort "Error: Config file not found: #{path}" unless File.exist?(path)
26
+
27
+ env = HTM::Config.env.to_sym
28
+ apply(HTM::Config.file_settings(read(path), env))
29
+ @loaded = path
30
+ $stderr.puts "Loaded configuration from: #{path} (#{env})" # rubocop:disable Style/StderrPuts -- warn is silent once HTM loads
31
+ end
32
+
33
+ # A YAML config file as a symbol-keyed hash (empty when the file is)
34
+ def read(path)
35
+ require "yaml"
36
+ YAML.safe_load_file(path, permitted_classes: [Symbol], symbolize_names: true, aliases: true) || {}
37
+ end
38
+
39
+ def apply(config)
40
+ HTM.configure do |htm_config|
41
+ SECTIONS.each { apply_section(htm_config, it, config[it]) }
42
+ apply_scalars(htm_config, config)
43
+ end
44
+ end
45
+
46
+ # Top-level settings: week_start, connection_timeout and log_level when
47
+ # given, telemetry_enabled when not nil (false turns it off)
48
+ def apply_scalars(htm_config, config)
49
+ settings = config.slice(:week_start, :connection_timeout, :log_level).select { |_, value| value }
50
+ telemetry = config[:telemetry_enabled]
51
+ settings[:telemetry_enabled] = telemetry unless telemetry.nil?
52
+ assign_values(htm_config, settings)
53
+ end
54
+
55
+ def apply_section(htm_config, name, values)
56
+ return unless values.is_a?(Hash)
57
+
58
+ section = htm_config.send(name)
59
+ values.each do |key, value|
60
+ next if value.nil?
61
+
62
+ # Nested sections such as providers.openai
63
+ value.is_a?(Hash) ? assign_values(section.send(key), value) : section.send("#{key}=", value)
64
+ end
65
+ end
66
+
67
+ # Call target.key = value for each non-nil value
68
+ def assign_values(target, values)
69
+ values.each { |key, value| target.send("#{key}=", value) unless value.nil? }
70
+ end
71
+ end
72
+ end
73
+ end