Repository navigation
Expand file tree
/
Copy pathserver.cpp
More file actions
1860 lines (1705 loc) · 87.7 KB
/
Copy pathserver.cpp
File metadata and controls
1860 lines (1705 loc) · 87.7 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
/**
* HTTP server for Ragger Memory implementation
*/
#include "build_info.h"
#include "server.h"
#include "memory.h"
#include "agent_parse.h"
#include "user_store.h"
#include "sqlite/backend.h"
#include "lang.h"
#include "Logger.h"
#include "auth.h"
#include "config.h"
#include "config_access.h"
#include "embedder.h"
#include "util/fs.h"
#include "util/parse.h"
#include "inference.h"
#include <curl/curl.h>
#include "summarizer.h"
#include "summarizer_service.h"
#include "nlohmann_json.hpp"
#include "httplib.h"
// Dashboard HTML/JS, embedded at build time (web/dashboard.html -> generated
// dashboard_html.inc). Provides `static const char* DASHBOARD_HTML`.
#include "dashboard_html.inc"
#include <chrono>
#include <condition_variable>
#include <filesystem>
#include <fstream>
#include <set>
#include <mutex>
#include <iostream>
#include <optional>
#include <pwd.h>
#include <format>
#include <sstream>
#include <thread>
#include <unordered_map>
#include <atomic>
#include <signal.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
namespace ragger {
namespace fs = std::filesystem;
using json = nlohmann::json;
// Global signal flags (async-signal-safe)
static std::atomic<bool> g_housekeeping_requested{false};
static std::atomic<bool> g_config_reload_requested{false};
static std::atomic<bool> g_shutdown_requested{false};
// Set by POST /restart: like shutdown, but main() re-execs the daemon in
// place afterward (rebinding listeners — the only way a port change takes).
static std::atomic<bool> g_restart_requested{false};
static void sigusr1_handler(int) {
g_housekeeping_requested.store(true, std::memory_order_relaxed);
}
static void sighup_handler(int) {
g_config_reload_requested.store(true, std::memory_order_relaxed);
}
static void sigterm_handler(int) {
g_shutdown_requested.store(true, std::memory_order_relaxed);
}
// Serializes a json body with the "application/json" content-type and an
// optional non-200 status, replacing the repeated
// res.set_content(json{...}.dump(), "application/json") pattern used
// throughout this file's handlers.
static void respond_json(httplib::Response& res, const json& body, int status = 200) {
res.status = status;
res.set_content(body.dump(), "application/json");
}
// Serialise a vector of SearchResults to a JSON array.
// score is always included (0.0 for metadata-only searches).
static json search_results_to_json(const std::vector<SearchResult>& results) {
json arr = json::array();
for (const auto& r : results)
arr.push_back({{"id", r.id}, {"text", r.text}, {"score", r.score},
{"metadata", r.metadata}, {"timestamp", r.timestamp}});
return arr;
}
struct Server::Impl {
// Two listener instances so we can bind AF_UNIX and AF_INET at the same
// time. cpp-httplib::Server::listen() blocks the calling thread and binds
// exactly one socket, so each listener gets its own Server and its own
// thread. Routes are registered on both via setup_routes(httplib::Server&).
//
// tcp_svr is a pointer because it's either a plain httplib::Server or an
// httplib::SSLServer, decided once at construction time from [server]
// cert/key. httplib::SSLServer derives from Server (virtual dtor), so a
// base-class pointer works for both; setup_routes()/listen()/stop() are
// all virtual or take the base type.
httplib::Server unix_svr;
std::unique_ptr<httplib::Server> tcp_svr;
bool tls_enabled_ = false;
RaggerMemory& memory;
UserStore users_;
std::string host;
int port;
std::string server_token_;
std::optional<UserInfo> default_user_;
std::shared_ptr<InferenceClient> inference_;
mutable std::mutex inference_mu_; // guards inference_ (C §1.3)
std::unique_ptr<SummarizerService> summarizer_;
/// Snapshot accessor: callers hold the returned shared_ptr for as long
/// as they need the client, independent of any concurrent reload.
std::shared_ptr<InferenceClient> inference() const {
std::lock_guard<std::mutex> lk(inference_mu_);
return inference_;
}
void set_inference(std::shared_ptr<InferenceClient> c) {
std::lock_guard<std::mutex> lk(inference_mu_);
inference_ = std::move(c);
}
// Per-user memory cache (username → RaggerMemory)
std::unordered_map<std::string, std::unique_ptr<RaggerMemory>> user_memories_;
std::mutex user_memories_mutex_;
// SSE activity-log tailing: byte offset already streamed to /events.
std::uintmax_t activity_log_offset_ = 0;
// Housekeeping timer
std::atomic<bool> timer_running_{false};
std::thread timer_thread_;
std::atomic<bool> poller_running_{false};
std::thread poller_thread_;
std::string pid_file_;
Impl(RaggerMemory& mem, const std::string& h, int p)
: memory(mem), users_(config().resolved_db_path()), host(h), port(p)
{
bootstrap_auth();
init_inference();
tcp_svr = make_tcp_server();
if (!config().server_name.empty()) {
httplib::Headers server_header{{"Server", config().server_name}};
unix_svr.set_default_headers(server_header);
tcp_svr->set_default_headers(server_header);
}
setup_routes(unix_svr);
setup_routes(*tcp_svr);
warmup();
}
/// Build the TCP listener — plain httplib::Server, or an SSLServer when
/// [server] cert + key are both configured and load successfully. Any
/// TLS problem (partial config, unloadable cert/key, construction
/// failure) is logged as a warning (stderr + activity.log) and the
/// daemon falls back to plain HTTP rather than refusing to start — a
/// working insecure daemon beats a daemon that won't come up at all.
std::unique_ptr<httplib::Server> make_tcp_server() {
const auto& cfg = config();
const bool have_cert = !cfg.tls_cert.empty();
const bool have_key = !cfg.tls_key.empty();
if (have_cert != have_key) {
// Only one of cert/key set — misconfiguration. Warn and fall
// back to plain HTTP; enforcing TLS on a half-configured pair
// isn't possible.
std::string msg = std::format(lang::WARN_TLS_PARTIAL_CONFIG,
have_cert ? "cert" : "key");
Diskerror::Logger::warn(msg);
std::cerr << msg << "\n";
return std::make_unique<httplib::Server>();
}
if (!have_cert && !have_key) {
return std::make_unique<httplib::Server>();
}
try {
auto svr = std::make_unique<httplib::SSLServer>(
cfg.tls_cert.c_str(), cfg.tls_key.c_str());
if (!svr->is_valid()) {
std::string msg = std::format(lang::WARN_TLS_INVALID_CERT,
cfg.tls_cert, cfg.tls_key);
Diskerror::Logger::warn(msg);
std::cerr << msg << "\n";
return std::make_unique<httplib::Server>();
}
tls_enabled_ = true;
Diskerror::Logger::info(std::format(lang::MSG_TLS_ENABLED, cfg.tls_cert));
return svr;
} catch (const std::exception& e) {
std::string msg = std::format(lang::WARN_TLS_SETUP_FAILED, e.what());
Diskerror::Logger::warn(msg);
std::cerr << msg << "\n";
return std::make_unique<httplib::Server>();
}
}
void warmup() {
// Pre-load embedding cache so first request isn't slow
try {
auto result = memory.search("warmup", 1, 0.0f);
Diskerror::Logger::info(std::format(lang::MSG_WARMUP_EMBEDDING_CACHE, memory.count()));
} catch (const std::exception& e) {
Diskerror::Logger::info(std::format(lang::MSG_WARMUP_ERROR, e.what()));
}
// Preload default model on local inference engines
if (auto inf = inference()) {
preload_local_model(inf, inf->model);
}
}
/// Preload a model if its endpoint is local (non-commercial).
/// Runs in background thread to avoid blocking startup. Takes the
/// client by shared_ptr copy — the detached thread must not capture
/// `this` and race a reload/teardown (C §1.3).
void preload_local_model(std::shared_ptr<InferenceClient> inf,
const std::string& model_name) {
if (model_name.empty() || !inf) return;
try {
auto& ep = inf->resolve_endpoint(model_name);
if (!ep.is_local()) return;
} catch (...) {
return;
}
std::thread([inf, model_name]() {
auto err = inf->ensure_model_loaded(model_name);
if (err.empty()) {
Diskerror::Logger::info(std::format(lang::MSG_PRELOADED_MODEL, model_name));
} else {
// WARN, not info — preload is best-effort but a misconfigured or
// unreachable management endpoint is the kind of thing the user
// wants to see (issue #47). The err string already carries the
// tried URL via ERR_ENGINE_UNREACHABLE / ERR_MODEL_LOAD_*.
Diskerror::Logger::warn(std::format(lang::MSG_MODEL_PRELOAD_SKIPPED, err));
}
}).detach();
}
/// Run one housekeeping pass: purge old turns, catch up missing
/// summaries, and backfill any NULL embeddings.
void run_housekeeping() {
const auto& cfg = config();
float max_age_hours = cfg.cleanup_max_age_hours;
// 1. Purge old conversation entries — use the main memory backend,
// not a separate sqlite::Backend. Opening a second connection to the
// same file while the main backend holds it can produce SQLite
// BUSY/LOCKED contention that silently prevents the backfill UPDATE
// in step 3 from committing.
if (max_age_hours > 0) {
try {
int deleted = memory.cleanup_old_conversations(max_age_hours);
if (deleted > 0) {
Diskerror::Logger::info(std::format(
lang::MSG_HOUSEKEEPING_EXPIRED, 0, deleted));
}
} catch (const std::exception& e) {
Diskerror::Logger::critical(std::format(lang::ERR_CLEANUP_DB, e.what()));
}
}
// 2. Catch up unsummarized turns.
if (summarizer_) {
summarizer_->enqueue_catch_up();
}
// 3. Backfill NULL embeddings (deferred stores, partial rebuilds).
// If embeddings are degraded, try to recover first — a rebuild may
// have fixed the drift since the last housekeeping tick.
if (memory.embeddings_degraded()) {
memory.try_recover_embeddings();
}
if (!memory.embeddings_degraded()) {
try {
// Finish an interrupted re-embed before the ordinary backfill.
// This resumes the remaining rows with the promoted identity;
// the plain backfill below then handles deferred stores.
memory.resume_interrupted_reembed();
int filled = memory.backfill_embeddings();
if (filled > 0) {
Diskerror::Logger::info(std::format(
lang::MSG_BACKFILLED_EMBEDDINGS, filled));
}
} catch (const std::exception& e) {
Diskerror::Logger::warn(std::format(lang::ERR_CLEANUP_DB, e.what()));
}
}
// 4. (Reindex housekeeping removed in Step 10 — the custom text index
// is maintained incrementally by the write path; use
// `ragger reindex [table|all]` for manual rebuilds.)
}
// Per-user housekeeping locks: username → fd
std::unordered_map<std::string, int> housekeeping_locks_;
std::mutex housekeeping_locks_mutex_;
/// Try to acquire housekeeping lock for a specific user.
/// Lock file: /tmp/ragger/housekeeping-{username}.lock
/// Returns true if this instance now owns housekeeping for that user.
bool acquire_user_housekeeping_lock(const std::string& username) {
std::lock_guard<std::mutex> lock(housekeeping_locks_mutex_);
if (housekeeping_locks_.count(username)) return true; // already own it
fs::create_directories("/tmp/ragger");
std::string lock_path = "/tmp/ragger/housekeeping-" + username + ".lock";
int fd = open(lock_path.c_str(), O_WRONLY | O_CREAT, 0644);
if (fd < 0) return false;
if (flock(fd, LOCK_EX | LOCK_NB) != 0) {
::close(fd);
return false; // another instance owns it
}
// Write our PID
ftruncate(fd, 0);
auto pid_str = std::to_string(getpid());
(void)write(fd, pid_str.c_str(), pid_str.size());
housekeeping_locks_[username] = fd;
Diskerror::Logger::info(std::format(lang::MSG_HOUSEKEEPING_OWNER, username));
return true;
}
/// Start background timer for periodic housekeeping.
/// Housekeeping only acts on users whose locks we hold.
void start_background_threads() {
start_signal_poller();
start_housekeeping_timer();
}
/// Signal handling thread — ALWAYS started, even with
/// housekeeping_interval == 0 (C §1.5): shutdown, restart, and SIGHUP
/// reload must not depend on the housekeeping thread existing. With
/// SA_RESTART, accept() resumes after a signal, so without this poller
/// SIGTERM was swallowed and POST /restart answered "restarting" but
/// nothing happened.
void start_signal_poller() {
poller_running_ = true;
poller_thread_ = std::thread([this]() {
while (poller_running_) {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
// (1) shutdown / restart — stop the listeners exactly as the
// old housekeeping-thread block did; main() re-execs on
// restart after the listeners return.
if (g_shutdown_requested.load(std::memory_order_relaxed) ||
g_restart_requested.load(std::memory_order_relaxed)) {
Diskerror::Logger::info(
g_restart_requested.load(std::memory_order_relaxed)
? "Restart signal received; stopping listeners to re-exec"
: "Shutdown signal received; stopping listeners");
if (unix_svr.is_running()) unix_svr.stop();
if (tcp_svr && tcp_svr->is_running()) tcp_svr->stop();
return;
}
// (2) Reload (SIGHUP): config, plus the search caches — the
// DB file may have been changed by another process (CLI
// import/delete, a hand edit). SIGHUP, not a new signal, so
// a newer CLI can never kill an older daemon. Lives here so
// reload works with housekeeping disabled (every CLI write
// sends SIGHUP).
if (g_config_reload_requested.exchange(false)) {
memory.backend()->invalidate_all_caches();
Diskerror::Logger::info(lang::MSG_CACHE_RELOADED);
int n = reload_config();
if (n > 0) {
Diskerror::Logger::info(std::format(ragger::lang::MSG_CONFIG_RELOADED_N, n));
// Re-initialize inference client if endpoints changed
try {
auto fresh = std::make_shared<InferenceClient>(
InferenceClient::from_config(config()));
set_inference(std::move(fresh));
Diskerror::Logger::info(lang::MSG_INFERENCE_CLIENT_OK);
} catch (const std::exception& e) {
Diskerror::Logger::critical(std::format(lang::ERR_INFERENCE_CLIENT_FAIL, e.what()));
}
} else {
Diskerror::Logger::info(lang::MSG_CONFIG_RELOADED_NONE);
}
}
}
});
}
/// Periodic housekeeping only. The interval is re-read every iteration
/// so a changed setting takes effect without a restart; 0 still means
/// the thread is not started at all.
void start_housekeeping_timer() {
if (config().housekeeping_interval == 0) {
Diskerror::Logger::info(lang::MSG_HOUSEKEEPING_DISABLED);
return;
}
timer_running_ = true;
timer_thread_ = std::thread([this]() {
while (timer_running_) {
const int interval = config().housekeeping_interval; // live
if (interval <= 0) {
std::this_thread::sleep_for(std::chrono::seconds(1));
continue;
}
for (int i = 0; i < interval && timer_running_; ++i) {
std::this_thread::sleep_for(std::chrono::seconds(1));
// Check for signal-triggered housekeeping
if (g_housekeeping_requested.exchange(false)) {
Diskerror::Logger::info(lang::MSG_HOUSEKEEPING_SIGNAL);
run_housekeeping();
}
}
if (timer_running_) {
run_housekeeping();
}
}
});
}
void stop_background_threads() {
timer_running_ = false;
poller_running_ = false;
if (timer_thread_.joinable()) {
timer_thread_.join();
}
if (poller_thread_.joinable()) {
poller_thread_.join();
}
// Release all user housekeeping locks
std::lock_guard<std::mutex> lock(housekeeping_locks_mutex_);
for (auto& [username, fd] : housekeeping_locks_) {
flock(fd, LOCK_UN);
::close(fd);
}
housekeeping_locks_.clear();
}
void init_inference() {
const auto& cfg = config();
auto client = InferenceClient::from_config(cfg);
if (!client.endpoints.empty()) {
auto n = client.endpoints.size();
set_inference(std::make_shared<InferenceClient>(std::move(client)));
Diskerror::Logger::info(std::format(lang::MSG_INFERENCE_ENABLED, n));
}
}
void bootstrap_auth() {
// Single-user mode: ensure token exists
server_token_ = ensure_token();
if (!server_token_.empty()) {
std::string token_hash = hash_token(server_token_);
auto user = users_.get_user_by_token_hash(token_hash);
if (!user) {
// Auto-create the single user
std::string username = "default";
struct passwd* pw = getpwuid(getuid());
if (pw) username = pw->pw_name;
int user_id = users_.create_user(username, token_hash);
user = UserInfo{user_id, username, token_hash};
Diskerror::Logger::info(std::format(lang::MSG_CREATED_USER, username, user_id));
}
default_user_ = user;
}
Diskerror::Logger::info(lang::MSG_SINGLE_USER_MODE);
}
/// True if this request must present a valid token. False for requests
/// arriving on the unix socket (empty remote_addr) or from localhost.
bool request_requires_auth(const httplib::Request& req) const {
if (req.remote_addr.empty()) return false; // unix socket
if (req.remote_addr == "127.0.0.1" || req.remote_addr == "::1") {
return false;
}
return true;
}
std::optional<UserInfo> _check_auth(const httplib::Request& req) {
const auto& cfg = config();
// Auth bypass: unix socket and localhost requests are pre-authenticated
// as the default (single) user.
if (!request_requires_auth(req) && default_user_) {
return default_user_;
}
// Parse "Bearer <token>" from the Authorization header.
auto auth_header = req.get_header_value("Authorization");
const std::string bearer_prefix = "Bearer ";
std::string token;
if (auth_header.substr(0, bearer_prefix.size()) == bearer_prefix) {
token = auth_header.substr(bearer_prefix.size());
} else if (req.has_param("token")) {
// Browser navigation / EventSource can't set headers — accept the
// token as a query parameter (?token=...) for the dashboard and
// its SSE stream. Same trust model: holding the token = authorized.
token = req.get_param_value("token");
} else {
return std::nullopt;
}
// Hash and lookup in database
std::string token_hash = hash_token(token);
auto user = users_.get_user_by_token_hash(token_hash);
if (user) {
return user;
}
// Fallback: direct comparison with server token
if (token == server_token_ && default_user_) {
return default_user_;
}
return std::nullopt;
}
/// Get per-user memory (or fallback to common).
/// In single-user mode, always returns the main memory instance.
RaggerMemory& _get_memory(const std::string& /*username*/) {
// Single-user mode: always return the main memory
return memory;
}
// ---- Route handlers (named for navigability) ---------------------------
void handle_store(const UserInfo& user, const httplib::Request& req,
httplib::Response& res) {
auto body = json::parse(req.body);
std::string text = body.value("text", "");
json metadata = body.value("metadata", json::object());
if (text.empty()) {
Diskerror::Logger::debug("POST /store 400");
res.status = 400;
res.set_content(lang::HTTP_MISSING_TEXT, "text/plain");
return;
}
if (!metadata.contains("collection") || metadata["collection"].get<std::string>().empty())
metadata["collection"] = "memory";
if (!metadata.contains("source") || metadata["source"].get<std::string>().empty())
metadata["source"] = user.username;
auto& mem = _get_memory(user.username);
// Route curated decisions to knowledge(kind='decision'); everything
// else (fact/preference/lesson/unspecified) lands in
// knowledge(kind='note') via store().
std::string category = metadata.value("category", "");
if (category == "decision") {
std::string tags = metadata.value("tags", "");
// Default "current" (the only status the recall pipeline
// surfaces). Callers can pass metadata.status="roadmap" for
// planned/future work that shouldn't clutter every session's
// recall until it's actually done.
std::string status = metadata.value("status", "current");
int did = mem.store_decision(text, status, tags);
Diskerror::Logger::debug("POST /store 200 (decision)");
respond_json(res, json{{"id", std::to_string(did)},
{"status", "stored"},
{"kind", "decision"}});
return;
}
std::string id = mem.store(text, metadata);
Diskerror::Logger::debug("POST /store 200");
respond_json(res, json{{"id", id}, {"status", "stored"}});
}
// POST /decision -- structured decision (agent API Phase 1, db 0.17).
// Body: {text, trigger, rationale?, scope?, tags?, status?, supersedes?,
// session?, evidence?: [turn_summary_id,...]}
// tags may be a string ("a,b") or an array of strings.
// Validation failures are 400 with the message; they are caller errors,
// not server faults, so they must not fall through to guarded()'s 500.
void handle_decision(const UserInfo& user, const httplib::Request& req,
httplib::Response& res) {
auto body = json::parse(req.body);
auto& mem = _get_memory(user.username);
// Project (Phase 3): explicit name/path wins; otherwise infer from
// cwd (longest-prefix match). No match leaves it empty — not an
// error. Shared with the MCP surface via parse_decision_input.
KnowledgeInput in = parse_decision_input(body);
try {
auto r = mem.store_knowledge(in);
Diskerror::Logger::debug("POST /decision 200");
respond_json(res, json{
{"id", r.id},
{"kind", r.kind},
{"status", "stored"},
{"superseded", r.superseded ? json(*r.superseded) : json(nullptr)},
{"possible_supersedes", supersedes_json(r.possible_supersedes)}});
} catch (const std::invalid_argument& e) {
Diskerror::Logger::debug("POST /decision 400");
res.status = 400;
res.set_content(std::string("ERROR: ") + e.what(), "text/plain");
}
}
// POST /memory/note — agent note (agent API Phase 3).
// Body: {text, tags?, evidence?}. Stores via store(), so the row lands
// where ragger_store notes land (knowledge kind='note'). The response carries
// possible_supersedes exactly like /decision — compared against current
// decisions, hint only, nothing is changed.
// Phase 5 step 6: `evidence: [turn_summary_id]` routes the write to
// store_knowledge(kind="insight") instead — a synthesized insight linked
// to its sources, and the response carries "kind":"insight". Without evidence nothing
// changes.
void handle_memory_note(const UserInfo& user, const httplib::Request& req,
httplib::Response& res) {
auto body = json::parse(req.body);
std::string text = body.value("text", "");
if (text.empty()) {
Diskerror::Logger::debug("POST /memory/note 400");
res.status = 400;
res.set_content(lang::HTTP_MISSING_TEXT, "text/plain");
return;
}
json metadata = json::object();
metadata["source"] = user.username;
if (body.contains("tags"))
metadata["tags"] = body["tags"];
auto& mem = _get_memory(user.username);
// ---- insight routing (Phase 5; PHASE7 kind="insight") -----------
if (body.contains("evidence") && body["evidence"].is_array()) {
KnowledgeInput in = parse_note_insight(body, text);
try {
auto r = mem.store_knowledge(in);
Diskerror::Logger::debug("POST /memory/note 200 (insight)");
respond_json(res, json{
{"id", r.id},
{"kind", r.kind},
{"status", "stored"},
{"superseded", r.superseded ? json(*r.superseded) : json(nullptr)},
{"possible_supersedes", supersedes_json(r.possible_supersedes)}});
} catch (const std::invalid_argument& e) {
Diskerror::Logger::debug("POST /memory/note 400 (insight)");
res.status = 400;
res.set_content(std::string("ERROR: ") + e.what(), "text/plain");
}
return;
}
try {
std::string id = mem.store(text, metadata);
Diskerror::Logger::debug("POST /memory/note 200");
respond_json(res, json{
{"id", id},
{"status", "stored"},
{"possible_supersedes", supersedes_json(mem.possible_supersedes_for_text(text))}});
} catch (const std::invalid_argument& e) {
Diskerror::Logger::debug("POST /memory/note 400");
res.status = 400;
res.set_content(std::string("ERROR: ") + e.what(), "text/plain");
}
}
// POST /memory/timeline — deterministic newest-first range scan
// (agent API Phase 4). Body: {session?, since?, until?,
// granularity?, limit?, cursor?}. Returns {items, next_cursor}.
void handle_memory_timeline(const UserInfo& user, const httplib::Request& req,
httplib::Response& res) {
auto body = json::parse(req.body);
auto& mem = _get_memory(user.username);
TimelineQuery q = parse_timeline_query(body);
try {
Diskerror::Logger::debug("POST /memory/timeline 200");
respond_json(res, mem.agent_timeline(q));
} catch (const std::invalid_argument& e) {
Diskerror::Logger::debug("POST /memory/timeline 400");
res.status = 400;
res.set_content(std::string("ERROR: ") + e.what(), "text/plain");
}
}
// POST /memory/update — metadata-only curation (agent API Phase 4).
// Body: {id, status?, tags?, text?}. `text` present is always
// rejected: text changes go through a new decision/note with supersedes.
void handle_memory_update(const UserInfo& user, const httplib::Request& req,
httplib::Response& res) {
auto body = json::parse(req.body);
UpdateRequest u = parse_update_request(body);
auto& mem = _get_memory(user.username);
try {
Diskerror::Logger::debug("POST /memory/update 200");
respond_json(res, mem.agent_update(u));
} catch (const std::invalid_argument& e) {
Diskerror::Logger::debug("POST /memory/update 400");
res.status = 400;
res.set_content(std::string("ERROR: ") + e.what(), "text/plain");
}
}
// POST /memory/review — pending-decision queue (agent API Phase 4).
// Body: {action: list|approve|reject, ids?: [handles]}.
void handle_memory_review(const UserInfo& user, const httplib::Request& req,
httplib::Response& res) {
auto body = json::parse(req.body);
const std::string action = body.value("action", "");
std::vector<std::string> ids;
if (body.contains("ids"))
ids = body["ids"].get<std::vector<std::string>>();
auto& mem = _get_memory(user.username);
try {
Diskerror::Logger::debug("POST /memory/review 200");
respond_json(res, mem.agent_review(action, ids));
} catch (const std::invalid_argument& e) {
Diskerror::Logger::debug("POST /memory/review 400");
res.status = 400;
res.set_content(std::string("ERROR: ") + e.what(), "text/plain");
}
}
// POST /memory/search — layered agent search (agent API Phase 2).
// Body = AgentSearchQuery fields: {query, layers?: [..], since?, until?,
// status?, session?, exclude_session?, limit?, max_tokens?}.
// Returns {"results":[AgentHit...]}. Validation failures are 400.
void handle_memory_search(const UserInfo& user, const httplib::Request& req,
httplib::Response& res) {
auto body = json::parse(req.body);
// Shared with the MCP surface via parse_agent_search_query.
auto& mem = _get_memory(user.username);
AgentSearchQuery q = parse_agent_search_query(body);
try {
auto hits = mem.agent_search(q);
json arr = json::array();
for (const auto& h : hits) {
arr.push_back({{"id", h.id}, {"layer", h.layer},
{"score", h.score}, {"matched_by", h.matched_by},
{"created", h.created}, {"snippet", h.snippet},
{"extra", h.extra}});
}
Diskerror::Logger::debug("POST /memory/search 200");
respond_json(res, json{{"results", std::move(arr)}});
} catch (const std::invalid_argument& e) {
Diskerror::Logger::debug("POST /memory/search 400");
res.status = 400;
res.set_content(std::string("ERROR: ") + e.what(), "text/plain");
}
}
// POST /memory/get — agent row reads (agent API Phase 2).
// Body = AgentGetQuery fields: {ids?: [handles], expand?, session?,
// after_turn?, before_turn?, limit?}. Exactly one mode per call.
void handle_memory_get(const UserInfo& user, const httplib::Request& req,
httplib::Response& res) {
auto body = json::parse(req.body);
AgentGetQuery q = parse_agent_get_query(body);
auto& mem = _get_memory(user.username);
try {
Diskerror::Logger::debug("POST /memory/get 200");
respond_json(res, mem.agent_get(q));
} catch (const std::invalid_argument& e) {
Diskerror::Logger::debug("POST /memory/get 400");
res.status = 400;
res.set_content(std::string("ERROR: ") + e.what(), "text/plain");
}
}
void handle_search(const UserInfo& user, const httplib::Request& req,
httplib::Response& res) {
auto body = json::parse(req.body);
std::string query = body.value("query", "");
if (query.empty()) {
Diskerror::Logger::debug("POST /search 400");
res.status = 400; res.set_content(lang::HTTP_MISSING_QUERY, "text/plain"); return;
}
int limit = body.value("limit", config().default_search_limit);
float min_score = body.value("min_score", config().default_min_score);
auto collections = body.value("collections", std::vector<std::string>{});
auto t0 = std::chrono::high_resolution_clock::now();
auto& mem = _get_memory(user.username);
auto sr = mem.search(query, limit, min_score, collections);
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - t0).count();
json timing = sr.timing;
timing["total_ms"] = ms;
Diskerror::Logger::trace(std::format(lang::DBG_QUERY_LOG, query, sr.results.size(), ms));
Diskerror::Logger::debug(std::format(lang::DBG_HTTP, "POST", "/search", "200"));
respond_json(res, json{{"results", search_results_to_json(sr.results)},
{"timing", timing}});
}
// POST /turn: ingest one agent-pushed conversation turn for background
// summarization. No-op unless [server] capture_turns is true.
void handle_turn(const UserInfo& user, const httplib::Request& req,
httplib::Response& res) {
auto body = json::parse(req.body);
std::string user_text = body.value("user", "");
std::string assistant = body.value("assistant", "");
std::string model = body.value("model", "");
std::string session_id = body.value("session_id", "");
std::string session_name = body.value("session_name", "");
std::string name_source = body.value("name_source", "");
if (user_text.empty()) {
Diskerror::Logger::debug("POST /turn 400");
respond_json(res, json{{"error", "missing required field: user"}}, 400);
return;
}
auto& mem = _get_memory(user.username);
auto result = capture_turn(mem, user_text, assistant, model, session_id,
session_name, name_source);
// PHASE6 2.2: hand the fresh turn straight to the summarizer so L2
// runs as soon as the single worker is free (the periodic tick is
// the safety net, not the primary path). Non-blocking: enqueue only,
// the request never waits for inference. summarizer_ is assigned in
// serve() before the listeners start, so every request thread sees a
// fully-constructed pointer without locking. MCP capture (no daemon
// summarizer in-process) is unchanged: the daemon's tick finds those.
if (result.captured && !assistant.empty() && summarizer_)
summarizer_->enqueue_turn(result.turn_id, result.clean_user, assistant,
model, session_id, /*source_timestamp=*/"");
Diskerror::Logger::debug(std::format(lang::DBG_HTTP, "POST", "/turn", "200"));
respond_json(res, json{{"status", result.captured ? "captured" : "disabled"},
{"turn_id", result.turn_id}});
}
// GET /session/<guid>[?recipe=name]: assemble a recipe-shaped context payload.
void handle_session(const UserInfo& user, const httplib::Request& req,
httplib::Response& res) {
std::string sid = req.matches[1];
std::string recipe_name = req.get_param_value("recipe");
auto& mem = _get_memory(user.username);
auto ctx = build_context(mem, sid, recipe_name);
if (!ctx.enabled) {
respond_json(res, json{{"status", "disabled"}});
return;
}
json chunks = json::array();
for (const auto& c : ctx.chunks)
chunks.push_back({{"kind", c.kind}, {"text", c.text}, {"timestamp", c.timestamp}});
Diskerror::Logger::debug(std::format(lang::DBG_HTTP, "GET", "/session", "200"));
respond_json(res, json{{"status", "ok"},
{"session_id", sid},
{"recipe", ctx.recipe_name},
{"chunks", chunks}});
}
void handle_delete_memory(const UserInfo& user, const httplib::Request& req,
httplib::Response& res) {
int id = 0;
if (!util::parse_positive_int(std::string(req.matches[1]), id))
throw std::invalid_argument("memory id must be a positive integer");
auto& mem = _get_memory(user.username);
if (mem.delete_memory(id)) {
Diskerror::Logger::debug("DELETE /memory 200");
respond_json(res, json{{"id", id}, {"status", "deleted"}});
} else {
Diskerror::Logger::debug("DELETE /memory 404");
res.status = 404; res.set_content(lang::HTTP_MEMORY_NOT_FOUND, "text/plain");
}
}
void handle_delete_batch(const UserInfo& user, const httplib::Request& req,
httplib::Response& res) {
auto body = json::parse(req.body);
if (!body.contains("ids") || !body["ids"].is_array()) {
Diskerror::Logger::debug("POST /delete_batch 400");
res.status = 400; res.set_content(lang::HTTP_MISSING_IDS, "text/plain"); return;
}
auto ids = body["ids"].get<std::vector<int>>();
auto& mem = _get_memory(user.username);
int deleted = mem.delete_batch(ids);
Diskerror::Logger::debug("POST /delete_batch 200");
respond_json(res, json{{"deleted", deleted}});
}
void handle_search_by_metadata(const UserInfo& user, const httplib::Request& req,
httplib::Response& res) {
auto body = json::parse(req.body);
if (!body.contains("metadata") || !body["metadata"].is_object()) {
Diskerror::Logger::debug("POST /search_by_metadata 400");
res.status = 400; res.set_content(lang::HTTP_MISSING_METADATA, "text/plain"); return;
}
auto results = _get_memory(user.username).search_by_metadata(
body["metadata"], body.value("limit", 0),
body.value("after", ""), body.value("before", ""));
Diskerror::Logger::debug("POST /search_by_metadata 200");
respond_json(res, json{{"results", search_results_to_json(results)},
{"count", results.size()}});
}
// ---- Route registration -----------------------------------------------
void setup_routes(httplib::Server& svr) {
// GET /health — no auth required
svr.Get("/health", [this](const httplib::Request&, httplib::Response& res) {
respond_json(res, json{{"status", "ok"},
{"version", RAGGER_VERSION},
{"commit", RAGGER_COMMIT},
{"built", RAGGER_BUILD_DATE},
{"memories", memory.count()},
{"embeddable_rows", memory.count_embeddable_rows()},
{"degraded", memory.embeddings_degraded()}});
Diskerror::Logger::debug("GET /health 200");
});
// Wrap a handler with bearer auth + uniform error handling.
auto guarded = [this](auto handler) {
return [this, handler](const httplib::Request& req, httplib::Response& res) {
auto user = _check_auth(req);
if (!user) {
Diskerror::Logger::debug(std::format("{} {} 401", req.method, req.path));
res.status = 401;
res.set_content(lang::HTTP_UNAUTHORIZED, "text/plain");
return;
}
// Cross-origin write guard (C §1.8): after auth, before the
// handler. A browser sends Origin on cross-site writes; the
// authority must match Host. GET/HEAD/OPTIONS and requests
// with no Origin (curl, CLI, plugin, MCP) pass through.
if (!request_origin_allowed(req.method,
req.get_header_value("Origin"),
req.get_header_value("Host"))) {
Diskerror::Logger::debug(std::format("{} {} 403 (origin)", req.method, req.path));
res.status = 403;
res.set_content("ERROR: cross-origin request refused", "text/plain");
return;
}
try {
handler(*user, req, res);
} catch (const json::exception& e) {
Diskerror::Logger::debug(std::format("{} {} 400", req.method, req.path));
res.status = 400;
res.set_content(std::format(lang::HTTP_JSON_ERROR, e.what()), "text/plain");
} catch (const std::invalid_argument& e) {
// Malformed inputs (bad ids, bad ports, validation failures)
// are client errors, not server faults (C §1.10).
Diskerror::Logger::debug(std::format("{} {} 400", req.method, req.path));
res.status = 400;
res.set_content(std::string("ERROR: ") + e.what(), "text/plain");
} catch (const std::exception& e) {
Diskerror::Logger::critical(std::format(lang::ERR_ROUTE_FAILED, req.method, req.path, e.what()));
res.status = 500;
res.set_content(std::string("ERROR: ") + e.what(), "text/plain");
}
};
};
svr.Get("/count", guarded([this](const UserInfo& user, const httplib::Request&,
httplib::Response& res) {
respond_json(res, json{{"count", _get_memory(user.username).count()}});
Diskerror::Logger::debug("GET /count 200");
}));
svr.Post("/store", guarded([this](const UserInfo& u, const httplib::Request& req, httplib::Response& res) { handle_store(u, req, res); }));
svr.Post("/decision", guarded([this](const UserInfo& u, const httplib::Request& req, httplib::Response& res) { handle_decision(u, req, res); }));
svr.Post("/search", guarded([this](const UserInfo& u, const httplib::Request& req, httplib::Response& res) { handle_search(u, req, res); }));
svr.Post("/memory/search", guarded([this](const UserInfo& u, const httplib::Request& req, httplib::Response& res) { handle_memory_search(u, req, res); }));
svr.Post("/memory/get", guarded([this](const UserInfo& u, const httplib::Request& req, httplib::Response& res) { handle_memory_get(u, req, res); }));
svr.Post("/memory/note", guarded([this](const UserInfo& u, const httplib::Request& req, httplib::Response& res) { handle_memory_note(u, req, res); }));
svr.Post("/memory/timeline", guarded([this](const UserInfo& u, const httplib::Request& req, httplib::Response& res) { handle_memory_timeline(u, req, res); }));
svr.Post("/memory/update", guarded([this](const UserInfo& u, const httplib::Request& req, httplib::Response& res) { handle_memory_update(u, req, res); }));
svr.Post("/memory/review", guarded([this](const UserInfo& u, const httplib::Request& req, httplib::Response& res) { handle_memory_review(u, req, res); }));
svr.Post("/turn", guarded([this](const UserInfo& u, const httplib::Request& req, httplib::Response& res) { handle_turn(u, req, res); }));
svr.Get(R"(/session/([^/]+))", guarded([this](const UserInfo& u, const httplib::Request& req, httplib::Response& res) { handle_session(u, req, res); }));
svr.Delete(R"(/memory/(\d+))", guarded([this](const UserInfo& u, const httplib::Request& req, httplib::Response& res) { handle_delete_memory(u, req, res); }));
svr.Post("/delete_batch", guarded([this](const UserInfo& u, const httplib::Request& req, httplib::Response& res) { handle_delete_batch(u, req, res); }));
svr.Post("/search_by_metadata", guarded([this](const UserInfo& u, const httplib::Request& req, httplib::Response& res) { handle_search_by_metadata(u, req, res); }));
svr.Get("/user/token", guarded([this](const UserInfo& user, const httplib::Request&,
httplib::Response& res) {
struct passwd* pw = getpwnam(user.username.c_str());
if (!pw) { res.status = 404; res.set_content(std::format(R"({{"error":"{}"}})", lang::HTTP_SYSTEM_USER_NOT_FOUND), "application/json"); return; }
std::string token_file = std::string(pw->pw_dir) + "/.ragger/token";
std::ifstream f(token_file);
if (!f) { res.status = 404; res.set_content(std::format(R"({{"error":"{}"}})", lang::HTTP_NO_TOKEN_FILE), "application/json"); return; }
std::string token;
std::getline(f, token);
size_t s = token.find_first_not_of(" \t\r\n");
size_t e = token.find_last_not_of(" \t\r\n");
if (s != std::string::npos) token = token.substr(s, e - s + 1);
Diskerror::Logger::debug("GET /user/token 200");
respond_json(res, json{{"token", token}, {"username", user.username}});
}));
// ---- Dashboard (embedded HTML/JS) --------------------------------
// GET /dashboard[?token=...] -> the single-page control panel. The
// page then talks to /config and /events with the same token.
svr.Get("/dashboard", guarded([this](const UserInfo&, const httplib::Request&,
httplib::Response& res) {
res.set_content(DASHBOARD_HTML, "text/html; charset=utf-8");
Diskerror::Logger::debug("GET /dashboard 200");
}));
// ---- Config API (dashboard + programmatic) -----------------------
// GET /config -> all settings as {key: {value, ...schema}}
// GET /config/<key> -> one setting