embed: a session is searchable by meaning, with no model and no key

Compaction drops most of a session out of the window, and the only way back
to it was a substring search. That answers "where does this word stand",
not "what did we say about this".

history_search is the second question: every message the session ever wrote
gets a vector, and the model asks by meaning. Three rules shaped it.

It works with no model. The default is a local encoder - the hashing trick
over words, word bigrams and character 4-grams, 256 dimensions, pure CPU -
so remembering does not stop when an API key expires. `embed = openai`
points it at a real embedding model instead. The index records which one
built it: a vector from one space compared against another is noise that
looks like a result.

It never costs the turn. Embedding runs on its own thread; the turn only
says "this session grew" (sp_embed_note_compaction, called from the
compaction event) and goes on. An index that lags is reported as lagging.

It indexes the session file, not the conversation. The conversation is what
is left after the last compaction; the file is everything that was said.
"Before compaction" is not a snapshot to take, it is the file - and the
index stores the byte offset it reached, so the update is incremental for
free. It is derived data, append-only at <session dir>/emb/<id>.emb, and
losing it costs a rebuild, never history.

/status gains a row for it (index: N messages, lags by M).
This commit is contained in:
lotherk committed 2026-11-21 21:26:22 +00:00
1 parent f7120882fa
commit 87f5987a46
8 files changed
+2145

No files matched your search

+1
View File
@@ -245,6 +245,7 @@ status.cost = Kosten
status.cost_value = %.4f USD
status.compact = Kompaktierung
status.compact_value = %zu angewandt, %zu fehlgeschlagen, %zu Runden (Agent %zu)
status.embed = Index
status.limits = Limits
status.limits_value = max_bytes %zu, max_steps %zu%s
status.autonomous = , autonom
+1
View File
@@ -244,6 +244,7 @@ status.cost = cost
status.cost_value = %.4f USD
status.compact = compact
status.compact_value = %zu applied, %zu failed, %zu turns (agent %zu)
status.embed = index
status.limits = limits
status.limits_value = max_bytes %zu, max_steps %zu%s
status.autonomous = , autonomous
+1
View File
@@ -248,6 +248,7 @@ status.cost = custo
status.cost_value = %.4f USD
status.compact = compactacao
status.compact_value = %zu aplicadas, %zu falharam, %zu turnos (agente %zu)
status.embed = indice
status.limits = limites
status.limits_value = max_bytes %zu, max_steps %zu%s
status.autonomous = , autonomo
+56
View File
@@ -15,6 +15,7 @@
#include <dirent.h>
#include "config.h"
#include "embed.h"
#include "usage.h"
#include "confblock.h"
@@ -23,6 +24,13 @@ sp_config_init(struct sp_config *c)
{
memset(c, 0, sizeof(*c));
c->autonomous = -1;
/*
* The index is on by default and it is the local encoder: the whole
* point is that a session becomes searchable without a model, a key or
* a network. `embed = off` turns it off; `embed = openai` swaps in a
* trained encoder.
*/
c->embed = SP_EMBED_LOCAL;
snprintf(c->key_env, sizeof(c->key_env), "SPLINTER_API_KEY");
}
@@ -761,6 +769,45 @@ load_stream(struct sp_config *c, FILE *f, const char *path,
c->compact_threshold = (size_t)strtoul(val, NULL, 10);
else if (!strcmp(key, "compact_target"))
c->compact_target = (size_t)strtoul(val, NULL, 10);
/*
* The embedding index. `embed = local` is the built-in CPU
* encoder (no model, no key), `openai` posts to
* <embed_endpoint>/embeddings, `off` disables it.
*/
else if (!strcmp(key, "embed")) {
if (!strcmp(val, "local") || !strcmp(val, "1") ||
!strcmp(val, "true"))
c->embed = SP_EMBED_LOCAL;
else if (!strcmp(val, "openai") ||
!strcmp(val, "remote"))
c->embed = SP_EMBED_REMOTE;
else if (!strcmp(val, "off") || !strcmp(val, "0") ||
!strcmp(val, "false") || !strcmp(val, "none"))
c->embed = SP_EMBED_OFF;
else {
sp_buf_printf(err, "config: %s:%u: embed is "
"local, openai or off", path, lineno);
return -1;
}
}
else if (!strcmp(key, "embed_dims")) {
long d = strtol(val, NULL, 10);
if (d < 8 || d > 4096) {
sp_buf_printf(err, "config: %s:%u: embed_dims "
"wants 8..4096", path, lineno);
return -1;
}
c->embed_dims = (int)d;
}
else if (!strcmp(key, "embed_model"))
set_str(c->embed_model, sizeof(c->embed_model), val);
else if (!strcmp(key, "embed_endpoint"))
set_str(c->embed_endpoint, sizeof(c->embed_endpoint), val);
else if (!strcmp(key, "embed_key_env"))
set_str(c->embed_key_env, sizeof(c->embed_key_env), val);
else if (!strcmp(key, "embed_timeout"))
c->embed_timeout = strtol(val, NULL, 10);
else if (!strcmp(key, "http_timeout") ||
!strcmp(key, "request_timeout"))
c->http_timeout = strtol(val, NULL, 10);
@@ -920,6 +967,15 @@ sp_config_write_example(const char *path, struct sp_buf *err)
" # A usage limit is waited out: splinter finds the reset and goes on.\n"
" #on_limit = wait # or fail\n"
" #max_wait = 12h\n"
"\n"
" # The session index behind history_search. `local` is built in and\n"
" # needs no model: feature hashing on the CPU, in a background\n"
" # thread, slower to build but never a request. `openai` sends to\n"
" # embed_endpoint, `off` keeps the tool away.\n"
" #embed = local\n"
" #embed_dims = 256 # vector size for `local`\n"
" #embed_endpoint = http://127.0.0.1:8080/v1\n"
" #embed_model = nomic-embed-text\n"
"}\n"
"\n"
"# One block per plugin; what is in it is that plugin's own setting.\n"
+11
View File
@@ -173,6 +173,17 @@ struct sp_config {
* and there is already an explicit cli delegate for the same program.
*/
int env_delegates;
/*
* The embedding index (see embed.h). On by default with the local
* encoder: a harness that needs an API key before it can remember
* anything stops remembering the day the key expires.
*/
int embed; /* SP_EMBED_OFF | _LOCAL | _REMOTE */
int embed_dims;
char embed_model[256];
char embed_endpoint[512];
char embed_key_env[64];
long embed_timeout;
};
void sp_config_init(struct sp_config *);
+1605
View File
File diff suppressed because it is too large. Load diff
+128
View File
@@ -0,0 +1,128 @@
/*
* splinter -- the embedding index of a session.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* Compaction throws most of a session out of the context window. Until now the
* only way back to it was a substring search (lcm's recall, the session
* plugin's session_search), which answers "where does this word stand" and not
* "what did we say about this". The index here is the second question: every
* message a session ever wrote, with a vector, so the model can ask by meaning.
*
* Three rules shape it, and each one was paid for elsewhere in this tree.
*
* 1. It must work with no model at all. A harness that needs an embedding API
* before it can remember anything is a harness that stops remembering the
* day the key expires. So the default is local: the hashing trick over
* words, word bigrams and character 4-grams, a few hundred dimensions,
* pure CPU, microseconds per message. It is weaker than a trained encoder
* and it is honest about being a lexical measure -- it will not match
* "Kompaktierung" with "compaction", and its job does not require it to.
* kind = openai points it at a real embedding model instead; the index
* records which one built it, because a vector from one space compared to a
* vector from another is noise that looks like a result.
*
* 2. It must never cost the turn. Embedding runs on a thread of its own; the
* turn only says "this session grew" and goes on. Nothing waits for the
* index, and an index that lags is reported as lagging instead of pretending
* the newest messages are in it.
*
* 3. It indexes the session file, not the conversation. The conversation is
* what is left after the last compaction; the file is everything that was
* ever said. "Before compaction" is not a snapshot to take, it is the file.
* That also makes the update incremental for free: the index stores the byte
* offset it reached, so the next run reads only the new lines.
*
* The index is derived data. Losing it costs a rebuild, never history, so it
* lives next to the session and is written append-only:
*
* <session_dir>/emb/<id>.emb
*
* one JSON object per line, the vector as base64 float32.
*/
#ifndef SPLINTER_EMBED_H
#define SPLINTER_EMBED_H
#include <stddef.h>
#include "splinter.h"
struct sp_config;
struct sp_registry;
struct sp_embed_ctx;
enum sp_embed_kind {
SP_EMBED_OFF = 0, /* kind = off */
SP_EMBED_LOCAL, /* the built-in hashing encoder, CPU */
SP_EMBED_REMOTE /* POST /embeddings somewhere */
};
struct sp_embed_cfg {
enum sp_embed_kind kind;
int dims; /* local: the hash width */
char model[256];
char endpoint[512];
char key_env[64];
long timeout_s;
};
/* the config file's embed settings, with the defaults applied */
void sp_embed_cfg_from_config(const struct sp_config *, struct sp_embed_cfg *);
/*
* One index per engine. ALWAYS returns a context, even with kind = off: the
* call sites must not each decide what "off" means.
*/
struct sp_embed_ctx *sp_embed_new(const struct sp_config *);
void sp_embed_free(struct sp_embed_ctx *);
/* The session the index belongs to. A changed id starts the new one's index;
* the first bind of a session also queues the whole file, so a resume is
* searchable before anything is compacted. */
void sp_embed_bind(struct sp_embed_ctx *, const char *dir, const char *id);
/* A compaction just threw history out of the context. Cheap: a flag and a
* signal, no I/O and no work on the caller's thread. */
void sp_embed_note_compaction(struct sp_embed_ctx *);
/*
* Wait until the worker has caught up: 1 when it is idle, 0 on timeout.
* Tests need it; a shutdown may not.
*/
int sp_embed_flush(struct sp_embed_ctx *, long timeout_ms);
/* Register the history_search tool. ctx is the index, owned by the engine. */
int sp_embed_register(struct sp_registry *, struct sp_embed_ctx *);
/* One line for /status or a widget: kind, records, how far behind. */
void sp_embed_status(struct sp_embed_ctx *, char *buf, size_t cap);
/*
* The pieces, exposed for tests and for the tool. None of these touch the
* thread.
*/
/* Local encoder: 'v' must hold dims doubles. Returns 0, or -1 for an empty
* text (a vector of zeros has no direction). */
int sp_embed_text(const char *text, int dims, double *v);
/* Cosine of two L2-normalised vectors, which is their dot product. */
double sp_embed_dot(const double *a, const double *b, int dims);
/*
* Run the indexer for one session now, on the caller's thread. 'err' gets a
* message on failure and stays empty on success. Returns the number of records
* added, or -1.
*/
int sp_embed_index_now(struct sp_embed_ctx *, char *err, size_t errcap);
/* Search the index: the 'limit' closest messages, written to out. */
int sp_embed_search(struct sp_embed_ctx *, const char *query, size_t limit,
struct sp_buf *out);
/* The same, and with full != 0 each hit is followed by 'cap' bytes of the
* message itself, read back from the session log. */
int sp_embed_search_full(struct sp_embed_ctx *, const char *query,
size_t limit, int full, size_t cap, struct sp_buf *out);
#endif /* SPLINTER_EMBED_H */
+342
View File
@@ -0,0 +1,342 @@
/*
* splinter -- the embedding index tests.
*
* Three things have to hold for this to be worth having:
*
* 1. the local encoder puts similar text near each other and unrelated text
* far apart, without a model, a key or the network;
* 2. indexing is incremental: a second run reads only the new lines, and the
* result equals an index built in one go;
* 3. a compaction makes the messages searchable again, and the search finds
* the right one - that is the whole point of the module.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include "splinter.h"
#include "config.h"
#include "embed.h"
static int failures;
#define CHECK(cond) do { \
if (!(cond)) { \
fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \
failures++; \
} \
} while (0)
/* ------------------------------------------------------------- encoder */
static void
test_encoder(void)
{
double a[256], b[256], c[256], v[256];
int i, nz = 0;
CHECK(sp_embed_text("the compaction throws the front away and keeps the "
"tail of the conversation", 256, a) == 0);
CHECK(sp_embed_text("compaction throws the front away and keeps the tail "
"of a conversation", 256, b) == 0);
CHECK(sp_embed_text("a pool fails over to the member with room left, and "
"the turn continues there", 256, c) == 0);
/* unit length: the cosine is the dot product, nothing else */
for (i = 0; i < 256; i++) {
CHECK(a[i] >= -1.0000001 && a[i] <= 1.0000001);
if (a[i] != 0.0)
nz++;
}
CHECK(nz > 4);
/*
* A paraphrase has to score clearly above an unrelated sentence. The
* numbers are printed so a change in the weights is visible in the log.
*/
fprintf(stderr, " encoder: paraphrase %.3f, unrelated %.3f\n",
sp_embed_dot(a, b, 256), sp_embed_dot(a, c, 256));
CHECK(sp_embed_dot(a, b, 256) > 0.55);
CHECK(sp_embed_dot(a, c, 256) < sp_embed_dot(a, b, 256));
CHECK(sp_embed_dot(a, a, 256) > 0.999);
/* a word inside a longer word: the 4-grams carry it */
CHECK(sp_embed_text("kompaktierung", 256, a) == 0);
CHECK(sp_embed_text("kompaktierung der sitzung", 256, b) == 0);
fprintf(stderr, " encoder: compound %.3f\n", sp_embed_dot(a, b, 256));
CHECK(sp_embed_dot(a, b, 256) > 0.4);
/* nothing to say: no direction, and the call says so */
CHECK(sp_embed_text("the and of to", 256, v) == -1);
CHECK(sp_embed_text("", 256, v) == -1);
CHECK(sp_embed_text(NULL, 256, v) == -1);
CHECK(sp_embed_text("x", 0, v) == -1);
}
/* --------------------------------------------------------------- index */
static void
write_session(const char *dir, const char *id, const char *const *lines,
size_t n)
{
char path[700];
FILE *f;
size_t i;
snprintf(path, sizeof(path), "%s/%s.jsonl", dir, id);
f = fopen(path, "a");
if (f == NULL) {
perror(path);
return;
}
for (i = 0; i < n; i++)
fprintf(f, "%s\n", lines[i]);
fclose(f);
}
static long
file_size(const char *path)
{
struct stat st;
if (stat(path, &st) != 0)
return -1;
return (long)st.st_size;
}
static void
test_index(void)
{
char tmpl[] = "/tmp/splinter-emb-XXXXXX";
char *dir = mkdtemp(tmpl);
char err[256], status[256], efile[800];
const char *first[] = {
"{\"role\":\"user\",\"text\":\"die kompaktierung wirft den "
"anfang der sitzung weg\"}",
"{\"role\":\"assistant\",\"text\":\"der tail bleibt, und der "
"rest steht im session-log\"}",
"{\"role\":\"user\",\"text\":\"welche ports hoert der dienst?\"}",
"{\"role\":\"assistant\",\"text\":\"der dienst hoert auf 8080 "
"und spricht http\"}"
};
const char *more[] = {
"{\"role\":\"user\",\"text\":\"und wie wird der index "
"nachgezogen?\"}"
};
struct sp_embed_ctx *c;
struct sp_config conf;
struct sp_buf out;
struct stat st;
int n;
if (dir == NULL) {
fprintf(stderr, "FAIL: no temp dir\n");
failures++;
return;
}
sp_config_init(&conf);
conf.embed = SP_EMBED_LOCAL;
conf.embed_dims = 256;
write_session(dir, "s1", first, 4);
c = sp_embed_new(&conf);
CHECK(c != NULL);
if (c == NULL)
return;
sp_embed_bind(c, dir, "s1");
/* the caller's thread does the work, so the test is deterministic */
CHECK(sp_embed_index_now(c, err, sizeof(err)) == 0);
if (err[0] != '\0')
fprintf(stderr, " index: %s\n", err);
snprintf(efile, sizeof(efile), "%s/emb/s1.emb", dir);
CHECK(file_size(efile) > 0);
CHECK(stat(efile, &st) == 0 && (st.st_mode & 07700) == 0600 &&
"the index file is private like the session");
sp_embed_status(c, status, sizeof(status));
fprintf(stderr, " status: %s\n", status);
CHECK(strstr(status, "4 messages") != NULL);
CHECK(strstr(status, "current") != NULL);
/* the file grew by one line: the next run adds one record, not five */
{
long before = file_size(efile);
write_session(dir, "s1", more, 1);
CHECK(sp_embed_index_now(c, err, sizeof(err)) == 0);
fprintf(stderr, " incremental: %ld -> %ld bytes\n", before,
file_size(efile));
CHECK(file_size(efile) > before);
sp_embed_status(c, status, sizeof(status));
CHECK(strstr(status, "5 messages") != NULL);
}
/* and the search finds by meaning, not by substring */
if (sp_buf_init(&out) != 0)
return;
n = sp_embed_search(c, "was passiert mit dem anfang bei der "
"kompaktierung", 3, &out);
fprintf(stderr, " search: %d hits\n%s", n, out.p != NULL ? out.p : "");
CHECK(n > 0);
CHECK(out.p != NULL && strstr(out.p, "kompaktierung") != NULL);
CHECK(out.p != NULL && strstr(out.p, "8080") == NULL);
/* the whole message comes back when asked for */
sp_buf_clear(&out);
n = sp_embed_search_full(c, "kompaktierung anfang", 1, 1, 4096, &out);
CHECK(n == 1);
CHECK(out.p != NULL && strstr(out.p, "die kompaktierung wirft den "
"anfang der sitzung weg") != NULL);
/* a query with no content words says so instead of ranking noise */
sp_buf_clear(&out);
CHECK(sp_embed_search(c, "the and of", 3, &out) == 0);
CHECK(out.p != NULL && strstr(out.p, "no searchable words") != NULL);
sp_buf_free(&out);
/* reopening the same session must not duplicate the index */
sp_embed_free(c);
c = sp_embed_new(&conf);
CHECK(c != NULL);
if (c != NULL) {
sp_embed_bind(c, dir, "s1");
CHECK(sp_embed_index_now(c, err, sizeof(err)) == 0);
sp_embed_status(c, status, sizeof(status));
fprintf(stderr, " after reopen: %s\n", status);
CHECK(strstr(status, "5 messages") != NULL);
sp_embed_free(c);
}
/* off is off, and it says why */
conf.embed = SP_EMBED_OFF;
c = sp_embed_new(&conf);
CHECK(c != NULL);
if (c != NULL) {
CHECK(sp_embed_index_now(c, err, sizeof(err)) == -1);
CHECK(strstr(err, "off") != NULL);
sp_embed_status(c, status, sizeof(status));
CHECK(strcmp(status, "off") == 0);
sp_embed_free(c);
}
}
/* a torn tail must not stop the index, and must not be counted either */
static void
test_torn(void)
{
char tmpl[] = "/tmp/splinter-embt-XXXXXX";
char *dir = mkdtemp(tmpl);
char err[256], status[256], path[800];
const char *lines[] = {
"{\"role\":\"user\",\"text\":\"erste nachricht\"}",
"{\"role\":\"assistant\",\"text\":\"zweite nachricht\"}"
};
struct sp_embed_ctx *c;
struct sp_config conf;
FILE *f;
if (dir == NULL)
return;
sp_config_init(&conf);
conf.embed = SP_EMBED_LOCAL;
write_session(dir, "s2", lines, 2);
/* a crash in the middle of a write */
snprintf(path, sizeof(path), "%s/s2.jsonl", dir);
f = fopen(path, "a");
if (f != NULL) {
fputs("{\"role\":\"user\",\"text\":\"abgeschnit", f);
fclose(f);
}
c = sp_embed_new(&conf);
CHECK(c != NULL);
if (c == NULL)
return;
sp_embed_bind(c, dir, "s2");
CHECK(sp_embed_index_now(c, err, sizeof(err)) == 0);
sp_embed_status(c, status, sizeof(status));
fprintf(stderr, " torn: %s\n", status);
CHECK(strstr(status, "2 messages") != NULL);
sp_embed_free(c);
}
/*
* The end-to-end shape: a session with a lot of history, one compaction, and
* the question that a compaction always makes unanswerable from the context.
*/
static void
test_compaction_recall(void)
{
char tmpl[] = "/tmp/splinter-embs-XXXXXX";
char *dir = mkdtemp(tmpl);
char err[256], big[512];
const char *lines[64];
struct sp_embed_ctx *c;
struct sp_config conf;
struct sp_buf out;
size_t i, n = 0, base;
int rc;
if (dir == NULL)
return;
sp_config_init(&conf);
conf.embed = SP_EMBED_LOCAL;
/*
* A real session: the interesting sentence is at the top and the rest is
* chatter, exactly the shape that compaction cuts away first.
*/
lines[n++] = "{\"role\":\"user\",\"text\":\"der deploy geht nur ueber "
"den rechner mit dem alten ssh-schluessel, port 2222\"}";
base = n;
for (i = 0; i < 40; i++) {
snprintf(big, sizeof(big), "{\"role\":\"%s\",\"text\":\"schritt "
"%zu: die datei wird gelesen und geprueft, danach geht es "
"weiter\"}", (i % 2) ? "assistant" : "user", i);
lines[n++] = strdup(big);
}
lines[n++] = "{\"role\":\"user\",\"text\":\"und noch etwas ganz "
"anderes: wie viele ports hat der dienst?\"}";
write_session(dir, "s3", lines, n);
/* the generated lines were strdup'd; the literals are not ours to free */
for (i = base; i < base + 40; i++)
free((char *)lines[i]);
c = sp_embed_new(&conf);
CHECK(c != NULL);
if (c == NULL)
return;
sp_embed_bind(c, dir, "s3");
CHECK(sp_embed_index_now(c, err, sizeof(err)) == 0);
if (sp_buf_init(&out) != 0)
return;
rc = sp_embed_search(c, "welchen port nimmt der deploy-rechner",
3, &out);
fprintf(stderr, " recall: %d hits\n%s", rc,
out.p != NULL ? out.p : "");
CHECK(rc > 0);
CHECK(out.p != NULL && strstr(out.p, "2222") != NULL);
sp_buf_free(&out);
sp_embed_free(c);
}
int
main(void)
{
fprintf(stderr, "== encoder\n");
test_encoder();
fprintf(stderr, "== index\n");
test_index();
fprintf(stderr, "== torn tail\n");
test_torn();
fprintf(stderr, "== compaction recall\n");
test_compaction_recall();
if (failures != 0) {
fprintf(stderr, "FAILED: %d\n", failures);
return 1;
}
fprintf(stderr, "ok\n");
return 0;
}