Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
1513 lines (1426 loc) · 70.6 KB
/
Copy pathmain.cpp
File metadata and controls
1513 lines (1426 loc) · 70.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ragger — C++ port of Ragger Memory
*
* Verb-style CLI: ragger <verb> [options] [args]
* No verb or 'help' prints usage.
*/
#include "build_info.h"
#include <cstdio>
#include <filesystem>
#include <format>
#include <fstream>
#include <iostream>
#include <map>
#include <grp.h>
#include <pwd.h>
#include <regex>
#include <set>
#include <sstream>
#include <sys/stat.h>
#include <termios.h>
#include <unistd.h>
#include <signal.h>
#include <sys/file.h>
#include <thread>
#include <iomanip>
#include <curl/curl.h>
#include <print>
#include "ProgramOptions.h"
#include "auth.h"
#include "client.h"
#include "config.h"
#include "config_access.h"
#include "export.h"
#include "import.h"
#include "user_commands.h"
#include "inference.h"
#include "lang.h"
#include "Logger.h"
#include "mcp.h"
#include "memory.h"
#include "vector_codec.h"
#include "recipe_cli.h"
#include "embed_executor.h"
#include "sqlite/backend.h"
#include "sqlite/tables.h"
#include "user_store.h"
#include "util/fs.h"
#include "server.h"
#include "embedder.h"
#include "daemon_control.h"
#include "util/fs.h"
#include "util/time.h"
#include "storage_types.h"
#include "nlohmann_json.hpp"
using namespace ragger::lang;
namespace fs = std::filesystem;
// Import (do_import) moved to src/import.cpp / include/import.h.
// User-command helpers (read_password, provision_user, and the
// useradd/usermod/userdel/add-self/passwd verbs) moved to
// src/user_commands.cpp / include/user_commands.h.
// -----------------------------------------------------------------------
// Main
// -----------------------------------------------------------------------
// PID of a live ragger daemon (from /tmp/ragger/server-*.pid), or 0.
static pid_t find_live_daemon_pid() {
namespace fs = std::filesystem;
try {
for (const auto &entry: fs::directory_iterator("/tmp/ragger")) {
auto name = entry.path().filename().string();
if (name.rfind("server-", 0) == 0 &&
name.size() > 4 && name.substr(name.size() - 4) == ".pid") {
std::ifstream pf(entry.path());
pid_t pid = 0;
if (pf >> pid && pid > 0 && kill(pid, 0) == 0) return pid;
}
}
} catch (...) {}
return 0;
}
// Tell the running daemon (if any) to drop its in-memory search caches:
// the DB file may have just been changed by this process. Silent when no
// daemon is running -- there is nothing stale to refresh. Uses SIGHUP (reload:
// config + caches), which every daemon version already handles.
static void notify_daemon_db_changed() noexcept {
if (pid_t pid = find_live_daemon_pid(); pid > 0) kill(pid, SIGHUP);
}
// Runs notify_daemon_db_changed() when the command scope ends, on every
// path (success, error return, exception): a command that MIGHT have
// changed the DB may have done so before it failed.
struct DbChangeNotifier {
bool armed;
explicit DbChangeNotifier(const std::string& command) {
static const char* const kMayWrite[] = {
"store", "decision", "import-docs", "delete-doc",
"import-conversations", "import", "re-embed", "reindex"};
armed = false;
for (auto c : kMayWrite) if (command == c) armed = true;
}
~DbChangeNotifier() { if (armed) notify_daemon_db_changed(); }
};
int main(int argc, char **argv) {
// Record our own path so embedding can be spawned as `ragger embed`.
if (argc > 0) ragger::set_executable_path(argv[0]);
// Record full argv so the daemon can re-exec itself in place (restart).
ragger::set_full_argv(argc, argv);
Diskerror::ProgramOptions opts(CLI_DESCRIPTION);
opts.add_options()
("help,h", CLI_HELP)
("version,V", CLI_VERSION)
("host,H", Diskerror::po::value<std::string>(), CLI_HOST)
("port,p", Diskerror::po::value<int>(), CLI_PORT)
("min-chunk-size", Diskerror::po::value<int>(), CLI_MIN_CHUNK_SIZE)
("num,n", Diskerror::po::value<int>(),
"search: number of results to return (default: 3)")
("title", Diskerror::po::value<std::string>()->default_value(""), CLI_TITLE)
("year", Diskerror::po::value<int>()->default_value(0), CLI_YEAR)
("tags", Diskerror::po::value<std::string>()->default_value(""), CLI_TAGS)
("status", Diskerror::po::value<std::string>()->default_value(""),
"decision: status to store/filter by (current|roadmap|superseded|deprecated)")
// `import conversations` filters & inputs
("format", Diskerror::po::value<std::string>()->default_value(""),
"Conversation source format: code | web | telegram")
("self", Diskerror::po::value<std::string>()->default_value(""),
"Telegram format only: your display name, to split user/assistant turns")
("all,a", "import-conversations: treat a directory, or a file with sibling export "
"files (memories.json, projects/), as one multi-file import unit; "
"config get: show all settings")
("fdate", "import-conversations: use each input file's mtime as the timestamp "
"for rows with no derivable date (e.g. memories.json)")
("date", Diskerror::po::value<std::string>()->default_value(""),
"import-conversations: explicit timestamp override "
"([CC]YYMMDD or YYYY-MM-DD) for rows with no derivable date")
("since", Diskerror::po::value<std::string>()->default_value(""),
"Only turns on/after this date (YYYY-MM-DD)")
("until", Diskerror::po::value<std::string>()->default_value(""),
"Only turns before this date (YYYY-MM-DD)")
("session", Diskerror::po::value<std::string>()->default_value(""),
"Restrict to one session id")
// `import summaries` input
("jsonl", Diskerror::po::value<std::string>()->default_value(""),
"JSONL file ({text, tags?, timestamp?} per line)")
// admin flags removed — sudo is the admin gate
("yes,y", CLI_YES)
("json,j", "config get: format output as JSON")
("browser,b", "dashboard: open the URL in the default browser")
("embeddings,e", CLI_EMBEDDINGS)
("output,o", Diskerror::po::value<std::string>(), "Output file");
opts.add_hidden_options()
("command", Diskerror::po::value<std::string>()->default_value("help"), CLI_COMMAND)
("args", Diskerror::po::value<std::vector<std::string> >(), CLI_ARGS)
// Undocumented, testing-only: relocate the entire ~/.ragger base
// directory (DB, logs, models, recipes, formats,
// socket, token — everything). No env var equivalent — CLI-only.
// Must be applied before any config/path resolution happens.
("ragger-base", Diskerror::po::value<std::string>()->default_value(""), "Override the ~/.ragger base directory (undocumented, testing only)")
// --keep-data removed: always keep user data, sudoer can rm manually
;
opts.add_positional("command", 1);
opts.add_positional("args", -1);
try {
opts.run(argc, argv);
}
catch (const std::exception &e) {
std::cerr << std::format(ragger::lang::ERR_INFERENCE, e.what()) << "\n";
return 1;
}
auto command = opts["command"].as<std::string>();
if (opts.count("help") || command == "help") {
std::println(ragger::lang::HELP_VERSION_HEADER, RAGGER_VERSION);
std::cout << ragger::lang::HELP_SCREEN;
std::cout << opts.to_string() << "\n";
return 0;
}
if (opts.count("version") || command == "version") {
std::cout << std::format(ragger::lang::VERSION_FORMAT, RAGGER_VERSION, RAGGER_COMMIT, RAGGER_BUILD_DATE) << "\n";
return 0;
}
// Undocumented, testing-only --ragger-base: relocate the entire ~/.ragger
// base directory before ANY config/path resolution happens (this must run
// before init_config(), since the DB's own location depends on it).
if (auto rh = opts["ragger-base"].as<std::string>(); !rh.empty()) {
ragger::set_ragger_base_override(rh);
}
// Load config: compiled-in defaults overlaid with the settings table.
try {
ragger::init_config();
}
catch (const std::exception &e) {
std::cerr << std::format(ragger::lang::ERR_INFERENCE, e.what()) << "\n";
return 1;
}
const auto &cfg = ragger::config();
// Initialize static logging system.
Diskerror::Logger log(cfg.log_file, cfg.log_level,
cfg.log_max_size_mb, cfg.log_max_age_days);
// CLI overrides
std::string host = opts.count("host") ? opts["host"].as<std::string>() : cfg.bind_address;
const bool port_overridden = opts.count("port") > 0;
int port = port_overridden ? opts["port"].as<int>() : cfg.port;
std::string db_path = cfg.resolved_db_path();
int min_chunk_size = opts.count("min-chunk-size")
? opts["min-chunk-size"].as<int>()
: cfg.minimum_chunk_size;
DbChangeNotifier db_change_notifier(command);
try {
if (command == "start" || command == "stop" ||
command == "restart" || command == "status") {
return ragger::daemon_control(command);
}
else if (command == "serve") {
const auto &cfg = ragger::config();
// Create the memory store first so the DB + schema exist. The
// port rectify below needs it in place.
std::unique_ptr<ragger::RaggerMemory> mem_ptr;
mem_ptr = std::make_unique<ragger::RaggerMemory>(db_path);
auto &memory = *mem_ptr;
Diskerror::Logger::info(std::format(MSG_LOADED_MEMORIES, memory.count()));
// Startup port rectify: unless --port was given on the CLI, adopt
// the dashboard's desired_port into the committed port before
// binding. This makes ANY restart path (service manager, crash
// respawn, bare `ragger serve`) pick up a UI port change — not
// just the dashboard's Restart button. A --port override is
// transient: it binds the given port but leaves desired_port
// untouched, so the next plain restart falls back to desired.
if (!port_overridden && cfg.desired_port != 0 &&
cfg.desired_port != cfg.port) {
int adopted = cfg.desired_port;
Diskerror::Logger::info(std::format(
"Startup port rectify: adopting desired_port {} (was {})",
adopted, cfg.port));
auto r = ragger::set_config_persisted("port", std::to_string(adopted),
/*allow_locked=*/true);
if (r.has_value()) {
port = adopted; // bind the adopted port this run
} else {
Diskerror::Logger::error(std::format(
"Failed to persist rectified port (err={}); binding existing port",
static_cast<int>(r.error())));
}
}
// Keep the live config's `port` honest: it must reflect the port
// actually being bound this run (the CLI override when present, or
// the rectified/committed value otherwise), NOT persist it. The
// dashboard's read-only "TCP Port" field reads this, so without
// this a --port override would show the stale DB value. desired_port
// is a separate field and is left untouched.
ragger::mutable_config().port = port;
ragger::Server server(memory, host, port);
bool restart = server.run();
if (restart) {
// In-place re-exec: rebind listeners with the current config
// (e.g. a new port). Destroy the server/memory first so the
// socket + DB handles are released before the new image binds.
mem_ptr.reset();
const auto& saved_argv = ragger::full_argv();
if (!saved_argv.empty()) {
// Strip any --host/--port CLI overrides from the replayed
// argv so the restarted daemon takes host/port from config
// (the DB, which now holds the new port the dashboard set).
// Without this, a CLI -p would pin the OLD port on re-exec.
std::vector<std::string> filtered;
for (size_t i = 0; i < saved_argv.size(); ++i) {
const std::string& a = saved_argv[i];
if (a == "-p" || a == "--port" || a == "--host") {
++i; // also skip the following value token
continue;
}
if (a.rfind("--port=", 0) == 0 || a.rfind("--host=", 0) == 0 ||
(a.rfind("-p", 0) == 0 && a.size() > 2)) // -p18435
continue;
filtered.push_back(a);
}
std::vector<char*> cargv;
cargv.reserve(filtered.size() + 1);
for (const auto& a : filtered)
cargv.push_back(const_cast<char*>(a.c_str()));
cargv.push_back(nullptr);
Diskerror::Logger::info("Re-executing daemon in place for restart");
::execv(ragger::executable_path().c_str(), cargv.data());
// execv only returns on failure.
Diskerror::Logger::critical(std::format(
"re-exec failed: {} — daemon is stopped", std::strerror(errno)));
return 1;
}
}
}
else if (command == "search") {
auto args = opts.getParams("args");
if (args.empty()) {
Diskerror::Logger::error(CLI_USAGE_SEARCH);
return 1;
}
std::string query;
for (size_t i = 0; i < args.size(); ++i) {
if (i > 0) query += " ";
query += args[i];
}
std::vector<std::string> colls;
// CLI default is 3 results (overridable with -n/--num). This is the
// human-facing default and is intentionally independent of the
// daemon/MCP `default_search_limit` (which serves the agent API).
int limit = opts.count("num") ? opts["num"].as<int>() : 3;
if (limit < 1) limit = 1;
// Try daemon first (thin client — no model loading)
auto token = ragger::load_token();
ragger::RaggerClient client(host, port, token);
ragger::SearchResponse response;
if (client.is_available()) {
response = client.search(query, limit,
cfg.default_min_score, colls);
}
else {
// Fall back to direct DB access
ragger::RaggerMemory memory(db_path);
response = memory.search(query, limit,
cfg.default_min_score, colls);
}
nlohmann::json output = nlohmann::json::array();
for (const auto &r: response.results) {
output.push_back({
{"id", r.id}, {"score", r.score},
{"text", r.text}, {"metadata", r.metadata}
});
}
std::cout << output.dump(2) << "\n";
}
else if (command == "store") {
auto args = opts.getParams("args");
if (args.empty()) {
Diskerror::Logger::error(CLI_USAGE_STORE);
return 1;
}
std::string text;
for (size_t i = 0; i < args.size(); ++i) {
if (i > 0) text += " ";
text += args[i];
}
nlohmann::json meta = {};
// Try daemon first (thin client — no model loading)
auto token = ragger::load_token();
ragger::RaggerClient client(host, port, token);
std::string id;
if (client.is_available()) {
id = client.store(text, meta);
}
else {
// Fall back to direct DB access
ragger::RaggerMemory memory(db_path);
id = memory.store(text, meta);
}
std::cout << std::format(ragger::lang::MSG_STORED_WITH_ID, id) << "\n";
}
else if (command == "decision") {
auto args = opts.getParams("args");
if (args.empty()) {
Diskerror::Logger::error(ragger::lang::CLI_USAGE_DECISION);
return 1;
}
std::string sub = args[0];
ragger::RaggerMemory memory(db_path);
if (sub == "add") {
if (args.size() < 2) {
Diskerror::Logger::error(ragger::lang::CLI_USAGE_DECISION);
return 1;
}
std::string text;
for (size_t i = 1; i < args.size(); ++i) {
if (i > 1) text += " ";
text += args[i];
}
std::string status = opts["status"].as<std::string>();
if (status.empty()) status = "current";
std::string tags = opts["tags"].as<std::string>();
int id = memory.store_decision(text, status, tags);
std::println("Stored decision {} (status: {}).", id, status);
return 0;
}
if (sub == "list") {
std::string status = opts["status"].as<std::string>();
if (status.empty()) status = "current";
int limit = opts.count("num") ? opts["num"].as<int>() : 20;
if (limit < 1) limit = 1;
auto items = memory.decisions_by_status(status, limit);
if (items.empty()) {
std::println("No decisions with status \"{}\".", status);
return 0;
}
for (auto& text : items) {
std::println("- {}", text);
}
return 0;
}
if (sub == "set-status") {
if (args.size() < 3) {
Diskerror::Logger::error(ragger::lang::CLI_USAGE_DECISION);
return 1;
}
int decision_id = 0;
try { decision_id = std::stoi(args[1]); } catch (...) {
Diskerror::Logger::error("decision set-status: <decision_id> must be a number");
return 1;
}
std::string status = args[2];
if (!memory.set_decision_status(decision_id, status)) {
Diskerror::Logger::error(
"decision set-status: no decision with id " + args[1]);
return 1;
}
std::println("Decision {} set to status \"{}\".", decision_id, status);
return 0;
}
Diskerror::Logger::error(ragger::lang::CLI_USAGE_DECISION);
return 1;
}
else if (command == "count") {
// Try daemon first (thin client — no model loading)
auto token = ragger::load_token();
ragger::RaggerClient client(host, port, token);
int count;
if (client.is_available()) {
count = client.count();
}
else {
// Fall back to direct DB access
ragger::RaggerMemory memory(db_path);
count = memory.count();
}
std::cout << count << "\n";
}
else if (command == "config") {
// DB-backed config get/set. Reads/writes the settings table via the
// live (already DB-overlaid) config. No daemon required.
//
// ragger config -> help
// ragger config get -a [-j] -> all values
// ragger config get <name> [-j] -> one value
// ragger config set <name> <value> -> validate + persist
auto args = opts.getParams("args");
const bool as_json = opts.count("json") > 0;
auto print_help = []() {
std::cout <<
"Usage:\n"
" ragger config get -a [-j] Show all settings (‑j = JSON)\n"
" ragger config get <name> [-j] Show one setting\n"
" ragger config set <name> <value> Change a setting (blank value = default)\n"
"\n"
"Settings:\n";
std::string cur_section;
for (const auto& m : ragger::lang::config_schema()) {
if (m.section != cur_section) {
cur_section = std::string(m.section);
std::cout << "\n [" << cur_section << "]\n";
}
std::cout << std::format(" {:<24} {}\n",
std::string(m.key), std::string(m.help));
}
};
if (args.empty()) { // bare `config` -> help
print_help();
return 0;
}
const std::string sub = args[0];
if (sub == "get") {
const auto& cfg = ragger::config();
// `-a` OR no name -> all. A name -> that one.
std::string name;
for (size_t i = 1; i < args.size(); ++i) {
if (args[i] == "-a" || args[i] == "--all") continue;
if (args[i] == "-j" || args[i] == "--json") continue;
name = args[i];
break;
}
const bool want_all =
name.empty() || opts.count("all") > 0 ||
std::find(args.begin(), args.end(), "-a") != args.end() ||
std::find(args.begin(), args.end(), "--all") != args.end();
const bool json_out = as_json ||
std::find(args.begin(), args.end(), "-j") != args.end();
if (!want_all && !name.empty()) {
auto v = ragger::get_config_value(cfg, name);
if (!v) {
std::cerr << "Unknown config key: " << name << "\n";
return 1;
}
if (json_out)
std::cout << nlohmann::json{{name, *v}}.dump(2) << "\n";
else
std::cout << *v << "\n";
return 0;
}
// All keys.
if (json_out) {
nlohmann::json out = nlohmann::json::object();
for (auto key : ragger::all_config_keys()) {
auto v = ragger::get_config_value(cfg, key);
if (v) out[std::string(key)] = *v;
}
std::cout << out.dump(2) << "\n";
} else {
for (auto key : ragger::all_config_keys()) {
auto v = ragger::get_config_value(cfg, key);
if (v) std::cout << std::format("{:<24} = {}\n",
std::string(key), *v);
}
}
return 0;
}
else if (sub == "set") {
if (args.size() < 2) {
std::cerr << "Usage: ragger config set <name> <value>\n";
return 1;
}
const std::string name = args[1];
// Value may be empty (reset to default) or contain spaces.
std::string value;
for (size_t i = 2; i < args.size(); ++i) {
if (i > 2) value += " ";
value += args[i];
}
auto r = ragger::set_config_persisted(name, value);
if (!r) {
switch (r.error()) {
case ragger::ConfigSetError::UnknownKey:
std::cerr << "Unknown config key: " << name << "\n"; break;
case ragger::ConfigSetError::Locked:
std::cerr << "Config key is locked (not user-writable): "
<< name << "\n"; break;
case ragger::ConfigSetError::InvalidValue:
std::cerr << "Invalid value for " << name << ": \""
<< value << "\"\n"; break;
}
return 1;
}
auto v = ragger::get_config_value(ragger::config(), name);
std::cout << name << " = " << (v ? *v : value) << "\n";
if (r->restart_required)
std::cout << "(change saved — restart the daemon to apply)\n";
if (r->rebuild_required)
std::cout << "(change saved — run 'ragger re-embed' to apply)\n";
return 0;
}
else {
print_help();
return (sub == "help" || sub == "-h" || sub == "--help") ? 0 : 1;
}
}
else if (command == "dashboard") {
// Print the dashboard URL (same port as normal access) with the
// access token as a query string. -b/--browser also opens it in
// the default browser. Access is gated by the token; only a user
// with RW access to ~/.ragger can read the token file, so holding
// it proves authorization.
const auto& cfg = ragger::config();
// Scheme: HTTPS iff both TLS cert and key are configured.
const bool tls = !cfg.tls_cert.empty() && !cfg.tls_key.empty();
const std::string scheme = tls ? "https" : "http";
// Host: prefer an explicit bind address; fall back to localhost.
std::string url_host = cfg.bind_address.empty() ? "127.0.0.1"
: cfg.bind_address;
if (url_host == "0.0.0.0" || url_host == "::") url_host = "127.0.0.1";
const std::string token = ragger::ensure_token();
std::string url = std::format("{}://{}:{}/dashboard",
scheme, url_host, cfg.port);
if (!token.empty()) url += "?token=" + token;
std::cout << url << "\n";
const bool open_browser = opts.count("browser") > 0;
if (open_browser) {
#if defined(__APPLE__)
std::string cmd = "open '" + url + "'";
#else
std::string cmd = "xdg-open '" + url + "' >/dev/null 2>&1 &";
#endif
if (std::system(cmd.c_str()) != 0)
std::cerr << "Could not launch a browser; open the URL above manually.\n";
}
return 0;
}
else if (command == "import-docs") {
auto args = opts.getParams("args");
if (args.empty()) {
Diskerror::Logger::error(ragger::lang::CLI_USAGE_IMPORT);
return 1;
}
// Markdown/text (and now JSON, auto-extracted to prose) → L5
// documents. This is the old bare `ragger import <file>` path,
// given its own verb name so it's no longer an implicit
// fallthrough default.
std::string imp_title = opts["title"].as<std::string>();
int imp_year = opts["year"].as<int>();
std::string imp_tags = opts["tags"].as<std::string>();
ragger::RaggerMemory memory(db_path);
for (auto &filepath: args) {
do_import(memory, filepath, min_chunk_size,
imp_title, imp_year, imp_tags);
}
}
else if (command == "list-docs") {
ragger::RaggerMemory memory(db_path);
auto docs = memory.list_document_sources();
if (docs.empty()) {
std::println("No documents imported.");
} else {
std::println("{:>5} {:>6} {:>4} {}", "id", "chunks", "year", "title <path>");
for (const auto& d : docs) {
std::println("{:>5} {:>6} {:>4} {} <{}>",
d["id"].get<long long>(), d["chunks"].get<long long>(),
d["year"].is_null() ? std::string("-") : std::to_string(d["year"].get<int>()),
d["title"].is_null() ? std::string("(untitled)") : d["title"].get<std::string>(),
d["path"].is_null() ? std::string("") : d["path"].get<std::string>());
}
}
}
else if (command == "delete-doc") {
auto args = opts.getParams("args");
// Exactly one argument, and it must be all digits: the document's
// primary key (document_source_id) as shown by `ragger list-docs`.
int id = 0;
if (args.size() == 1 && !args[0].empty() && args[0].size() <= 9 &&
std::all_of(args[0].begin(), args[0].end(),
[](unsigned char c) { return std::isdigit(c); }))
id = std::stoi(args[0]);
if (id <= 0) {
Diskerror::Logger::error(ragger::lang::CLI_USAGE_DELETE_DOC);
return 1;
}
ragger::RaggerMemory memory(db_path);
try {
auto info = memory.delete_document_source(id);
std::println("Deleted document {} ({}): {} chunk(s) removed.",
id,
info["title"].is_null() ? std::string("(untitled)") : info["title"].get<std::string>(),
info["chunks"].get<long long>());
} catch (const std::invalid_argument& e) {
Diskerror::Logger::error(e.what());
return 1;
}
}
else if (command == "import-conversations") {
auto args = opts.getParams("args");
if (args.empty()) {
Diskerror::Logger::error(ragger::lang::CLI_USAGE_IMPORT_CONVERSATIONS);
return 1;
}
// ISO-8601 (or already-db) timestamp → "YYYY-MM-DD HH:MM:SS".
auto to_db_ts = [](std::string s) -> std::string {
if (s.empty()) return s;
for (auto& c : s) if (c == 'T') c = ' ';
auto cut = s.find_first_of(".Z+");
if (cut != std::string::npos) s.erase(cut);
if (s.size() == 10) s += " 00:00:00";
return s;
};
// `summaries` sub-verb unchanged, just reachable from the new
// top-level name (hand-authored L4 project summaries).
if (args[0] == "summaries") {
std::vector<ragger::SummaryImport> items;
const std::string jsonl = opts["jsonl"].as<std::string>();
if (!jsonl.empty()) {
items = ragger::load_summary_jsonl(ragger::expand_path(jsonl));
} else if (args.size() >= 2) {
std::vector<std::string> files(args.begin() + 1, args.end());
for (auto& p : files) p = ragger::expand_path(p);
items = ragger::load_summary_files(files);
} else {
Diskerror::Logger::error(
"import-conversations summaries: provide files or --jsonl=FILE");
return 1;
}
if (items.empty()) {
std::println("Nothing to import.");
return 0;
}
ragger::RaggerMemory memory(db_path);
int n = 0, n_skip = 0;
for (const auto& s : items) {
std::string ts = to_db_ts(s.timestamp);
if (!ts.empty() && memory.note_exists_exact(s.text, ts)) {
++n_skip;
continue;
}
memory.store_note(s.text, s.tags, ts);
++n;
}
std::println("Imported {} notes ({} duplicates skipped).", n, n_skip);
return 0;
}
std::string raw_src = ragger::expand_path(args[0]);
bool all_flag = opts.count("all") > 0;
bool is_dir = fs::is_directory(raw_src);
// Flat Markdown memory files (OpenClaw/nanobot/zeroclaw-style
// daily logs and MEMORY.md snapshots) — plain `#` headings,
// no JSON wrapper, dated by filename prefix or file mtime.
// Handled as its own path, entirely separate from the
// Claude/Telegram JSON formats below: a single .md file needs
// no --all (nothing to pull in alongside it), while a
// directory of them does, same as any other multi-file
// import.
bool looks_like_flat_md_dir = is_dir && !fs::exists(raw_src + "/conversations.json");
if (looks_like_flat_md_dir) {
bool has_md = false;
for (auto& e : fs::directory_iterator(raw_src)) {
if (e.is_regular_file() && e.path().extension() == ".md") { has_md = true; break; }
}
if (has_md && !all_flag) {
Diskerror::Logger::error(
"import-conversations: " + raw_src + " is a directory of Markdown "
"memory files — pass --all to import them all as one unit");
return 1;
}
if (has_md) {
ragger::RaggerMemory memory(db_path);
int n_dec = 0, n_dec_skip = 0, n_sum = 0, n_sum_skip = 0, n_files = 0;
for (auto& e : fs::directory_iterator(raw_src)) {
if (!e.is_regular_file() || e.path().extension() != ".md") continue;
auto chunks = ragger::parse_flat_markdown_memory(e.path().string());
if (chunks.empty()) continue;
++n_files;
for (auto& c : chunks) {
std::string ts = to_db_ts(c.date);
if (c.is_decision_like) {
if (memory.decision_exists_exact(c.text, ts)) { ++n_dec_skip; continue; }
memory.store_decision(c.text, "current", "flat-memory-import", ts);
++n_dec;
} else {
if (memory.note_exists_exact(c.text, ts)) { ++n_sum_skip; continue; }
memory.store_note(c.text, "flat-memory-import", ts);
++n_sum;
}
}
}
std::println(
"Imported {} Markdown memory files: {} notes ({} duplicates "
"skipped), {} decisions ({} duplicates skipped).",
n_files, n_sum, n_sum_skip, n_dec, n_dec_skip);
return 0;
}
// Directory has neither conversations.json nor any .md
// files — fall through to the conversations.json-required
// error path below, which gives the right message for an
// unrecognized directory.
}
if (!is_dir && fs::path(raw_src).extension() == ".md") {
auto chunks = ragger::parse_flat_markdown_memory(raw_src);
if (chunks.empty()) {
std::println("Nothing to import (empty file or recognized as agent scaffolding).");
return 0;
}
ragger::RaggerMemory memory(db_path);
int n_dec = 0, n_dec_skip = 0, n_sum = 0, n_sum_skip = 0;
for (auto& c : chunks) {
std::string ts = to_db_ts(c.date);
if (c.is_decision_like) {
if (memory.decision_exists_exact(c.text, ts)) { ++n_dec_skip; continue; }
memory.store_decision(c.text, "current", "flat-memory-import", ts);
++n_dec;
} else {
if (memory.note_exists_exact(c.text, ts)) { ++n_sum_skip; continue; }
memory.store_note(c.text, "flat-memory-import", ts);
++n_sum;
}
}
std::println(
"Imported {} notes ({} duplicates skipped), "
"{} decisions ({} duplicates skipped).",
n_sum, n_sum_skip, n_dec, n_dec_skip);
return 0;
}
// Special case: the input file itself IS memories.json (not
// conversations.json with a memories.json sibling). This is a
// standalone import of just that one file — no siblings to
// pull in, no "point at conversations.json instead" detour.
// Handle it here and return, before the sibling-detection
// logic below (which is about conversations.json's siblings,
// not about being handed memories.json directly).
if (!is_dir && fs::path(raw_src).filename() == "memories.json") {
bool fdate = opts.count("fdate") > 0;
std::string date_override = opts["date"].as<std::string>();
std::string mem_ts;
if (!date_override.empty()) {
mem_ts = to_db_ts(date_override);
} else if (fdate) {
auto ftime = fs::last_write_time(raw_src);
auto sctp = std::chrono::time_point_cast<std::chrono::system_clock::duration>(
ftime - fs::file_time_type::clock::now() + std::chrono::system_clock::now());
std::time_t tt = std::chrono::system_clock::to_time_t(sctp);
char buf[32];
std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", std::localtime(&tt));
mem_ts = buf;
}
if (mem_ts.empty()) {
Diskerror::Logger::error(
"import-conversations: " + raw_src + " has no derivable date — "
"pass --fdate (use the file's mtime) or --date=DATE, or import it via "
"import-docs instead");
return 1;
}
std::string raw = ragger::read_file_to_string(raw_src);
std::string text = ragger::extract_text_from_json(raw);
if (text.empty()) {
std::println("Nothing to import.");
return 0;
}
ragger::RaggerMemory memory(db_path);
if (memory.decision_exists_exact(text, mem_ts)) {
std::println("memories.json already imported (dated {}) — skipped.", mem_ts);
return 0;
}
// TODO: LLM-driven split into discrete claims. For now,
// store the narrative as one decision row.
memory.store_decision(text, "current", "claude-memory", mem_ts);
std::println("Imported memories.json as 1 decision (dated {}).", mem_ts);
return 0;
}
// Directory input, or a file with export siblings, both need
// --all: it's the single "yes, treat this as one multi-file
// import unit" switch. No implicit default either way.
if (is_dir && !all_flag) {
Diskerror::Logger::error(
"import-conversations: " + raw_src + " is a directory (looks like a "
"multi-file export) — pass --all to import it as one unit");
return 1;
}
// Resolve the actual conversations.json to parse, plus any
// sibling files (memories.json, projects/*.json) --all pulls in.
std::string conv_path;
std::string memories_path;
std::vector<std::string> project_paths;
if (is_dir) {
conv_path = raw_src + "/conversations.json";
if (!fs::exists(conv_path)) {
Diskerror::Logger::error(
"import-conversations: " + raw_src + " has no conversations.json");
return 1;
}
std::string cand_mem = raw_src + "/memories.json";
if (fs::exists(cand_mem)) memories_path = cand_mem;
std::string proj_dir = raw_src + "/projects";
if (fs::is_directory(proj_dir)) {
for (auto& e : fs::directory_iterator(proj_dir)) {
if (e.is_regular_file() && e.path().extension() == ".json")
project_paths.push_back(e.path().string());
}
}
} else {
conv_path = raw_src;
if (all_flag) {
std::string dir = fs::path(raw_src).parent_path().string();
if (dir.empty()) dir = ".";
std::string cand_mem = dir + "/memories.json";
if (fs::exists(cand_mem)) memories_path = cand_mem;
std::string proj_dir = dir + "/projects";
if (fs::is_directory(proj_dir)) {
for (auto& e : fs::directory_iterator(proj_dir)) {
if (e.is_regular_file() && e.path().extension() == ".json")
project_paths.push_back(e.path().string());
}
}
} else {
// Single file, no --all: if it has export siblings
// sitting right next to it, say so rather than
// silently ignoring them.
std::string dir = fs::path(raw_src).parent_path().string();
if (dir.empty()) dir = ".";
bool has_siblings = fs::exists(dir + "/memories.json") ||
fs::is_directory(dir + "/projects");
if (has_siblings) {
Diskerror::Logger::error(
"import-conversations: " + raw_src + " has sibling export files "
"(memories.json / projects/) — pass --all to import them together, "
"or point at just this file to import only conversations");
return 1;
}
}
}
// Auto-detect the conversation file's shape; --format overrides
// when the sniff is wrong or the file is ambiguous.
std::string fmt = opts["format"].as<std::string>();
if (fmt.empty()) {
switch (ragger::detect_conversation_format(conv_path)) {
case ragger::ConversationFormat::ClaudeWeb: fmt = "web"; break;
case ragger::ConversationFormat::ClaudeCode: fmt = "code"; break;
case ragger::ConversationFormat::Telegram: fmt = "telegram"; break;
case ragger::ConversationFormat::ClaudeMemories:
Diskerror::Logger::error(
"import-conversations: " + conv_path + " looks like a Claude "
"memories.json (no per-message timestamps) — point --all at the "
"export directory so dates come from conversations.json, or import "
"it directly with --fdate/--date=DATE, or use import-docs instead");
return 1;
case ragger::ConversationFormat::Unknown:
Diskerror::Logger::error(
"import-conversations: could not detect the format of " + conv_path +
" — pass --format=code|web|telegram to override");
return 1;
}
}
if (fmt != "code" && fmt != "web" && fmt != "telegram") {
Diskerror::Logger::error(
"import-conversations: --format must be code|web|telegram");
return 1;
}
ragger::TurnFilter f;
f.session = opts["session"].as<std::string>();
f.since = opts["since"].as<std::string>();
f.until = opts["until"].as<std::string>();
std::vector<ragger::ImportTurn> turns;
if (fmt == "code") {
turns = ragger::parse_claude_code(conv_path);
} else if (fmt == "web") {
turns = ragger::parse_claude_web(conv_path);
} else { // telegram
std::string self_name = opts["self"].as<std::string>();
if (self_name.empty()) {
Diskerror::Logger::error(
"import-conversations --format=telegram: --self=\"Your Display Name\" is required");
return 1;
}
turns = ragger::parse_telegram(conv_path, self_name);
}
turns = ragger::filter_turns(turns, f);
if (turns.empty() && memories_path.empty() && project_paths.empty()) {
std::println("No turns matched.");
return 0;
}
ragger::RaggerMemory memory(db_path);
int n = 0, n_skip = 0, n_merged = 0;
std::vector<std::pair<int, std::string>> inserted; // telegram backfill scope
bool is_telegram = (fmt == "telegram");
for (const auto& t : turns) {
std::string ts = to_db_ts(t.timestamp);
if (!ts.empty() && !t.user_text.empty() &&
memory.turn_exists_fuzzy(t.user_text, ts, 90)) {
++n_skip;
continue;
}
if (!is_telegram && !t.user_text.empty()) {