diff --git a/memoryd.c b/memoryd.c index 3a74268..f1da9de 100644 --- a/memoryd.c +++ b/memoryd.c @@ -591,8 +591,83 @@ static void fmt_mem(mcp_buf *b, const struct mem *m, double score, int with_scor mcp_buf_puts(b, "\n"); } +/* ------------------------------------------------------------------ git */ +/* + * Ist git installiert, wird die Ablage beim ersten Schreiben ein Repository und jede + * Änderung festgeschrieben. Ein Speicher ohne Verlauf lässt sich nicht zurückdrehen — + * "lösche die Erinnerung, die war falsch" ist keine Antwort, wenn sie schon weg ist. + * Ist git nicht da, läuft alles weiter; der Dienst sagt es beim Start, damit niemand + * Verlauf annimmt, den es nicht gibt. + * + * Die Meldung besteht nur aus eigenen Kennungen (m00001) — kein Modell- oder + * Menschentext, also nichts zu quoten und nichts zu injizieren. + */ +static int g_git = -1; /* -1 ungeprüft, 0 kein git, 1 git vorhanden */ + +static int git_available(void) +{ + if (g_git >= 0) + return g_git; + g_git = (system("git --version >/dev/null 2>&1") == 0) ? 1 : 0; + return g_git; +} + +static void git_ensure_repo(void) +{ + static int done; + + if (done || !git_available()) + return; + done = 1; + { + char *root = mem_root(); + mcp_buf cmd; + + mcp_buf_init(&cmd); + mcp_buf_printf(&cmd, "git -C '%s' rev-parse --git-dir >/dev/null 2>&1 || " + "git -C '%s' init -q", root, root); + if (system(cmd.p) != 0) { + fprintf(stderr, "memoryd: git init in %s failed\n", root); + } else { + FILE *ign; + mcp_buf pb; + + mcp_buf_init(&pb); + mcp_buf_printf(&pb, "%s/.gitignore", root); + ign = fopen(pb.p != NULL ? pb.p : "/dev/null", "w"); + if (ign != NULL) { + fprintf(ign, "*.tmp.*\n.tmp/\n*.lock\n"); + fclose(ign); + } + mcp_buf_free(&pb); + } + mcp_buf_free(&cmd); + free(root); + } +} + +static void git_commit(const char *verb, const char *what) +{ + char *root; + mcp_buf cmd; + + if (!git_available()) + return; + git_ensure_repo(); + root = mem_root(); + mcp_buf_init(&cmd); + mcp_buf_printf(&cmd, "git -C '%s' add -A >/dev/null 2>&1 && " + "git -C '%s' -c user.name=memoryd -c user.email=memoryd@localhost " + "commit -q -m \"%s %s\" >/dev/null 2>&1", root, root, verb, what); + if (system(cmd.p) != 0) + fprintf(stderr, "memoryd: git commit failed (%s %s)\n", verb, what); + mcp_buf_free(&cmd); + free(root); +} + /* ------------------------------------------------------------------ tools */ + static void t_add(mcp_conn *c, const mcp_json *args, void *user) { const char *scope = scope_arg(args); @@ -640,6 +715,7 @@ static void t_add(mcp_conn *c, const mcp_json *args, void *user) mcp_reply_error(c, "could not write the memory file"); return; } + git_commit("memory_add", id); if (embedded) say(c, "stored %s in %s (embedded, %d dimensions)", id, scope, dim); else @@ -847,6 +923,7 @@ static void t_update(mcp_conn *c, const mcp_json *args, void *user) free_mem(&m); return; } + git_commit("memory_update", id); say(c, "updated %s (embedding: %s)", id, m.dim > 0 ? "yes" : "no"); free_mem(&m); } @@ -868,6 +945,7 @@ static void t_delete(mcp_conn *c, const mcp_json *args, void *user) return; } free(path); + git_commit("memory_delete", id); say(c, "deleted %s", id); } @@ -918,937 +996,6 @@ out: } -/* ========================================================================== - * Wissensbasis: benannte Sammlungen, sonst wie Erinnerungen - * - * Eine Wissensbasis ist ein Name mit einem Verzeichnis darunter, und darin liegen - * Seiten wie Erinnerungen: Titel, Text, Vektor. Der Unterschied ist der Zweck — - * Erinnerungen sind das, was ein Agent beiläufig behält; eine Wissensbasis ist das, - * was ein Mensch aufgeschrieben hat, damit es nachgelesen wird. - * - * $MEMORYDIR/kb//kb.json {"name","slug","description","created"} - * $MEMORYDIR/kb//e00001.json {"id","title","text","tags","source", - * "created","updated","model","embedding", - * "history":[{"text","updated"}]} - * - * Schreiben mit demselben Titel überschreibt die Seite nicht stillschweigend: der alte - * Text wandert in `history` (fünf Fassungen), und die Antwort sagt, dass es eine - * Aktualisierung war. Ein Wiki ohne jede Spur der vorherigen Fassung ist keins. - * ========================================================================== */ - -#define MAX_KB 512 -#define MAX_HISTORY 5 - -struct entry { - char *id; - char *title; - char *text; - char *tags; - char *source; - char *model; - long created; - long updated; - double *vec; - int dim; - /* Ältere Fassungen, nur beim Lesen/Schreiben gebraucht. */ - int nhist; - long hist_at[MAX_HISTORY]; - char *hist_text[MAX_HISTORY]; -}; - -static void free_entry(struct entry *e) -{ - int i; - - if (e == NULL) - return; - free(e->id); - free(e->title); - free(e->text); - free(e->tags); - free(e->source); - free(e->model); - free(e->vec); - for (i = 0; i < e->nhist; i++) - free(e->hist_text[i]); - memset(e, 0, sizeof(*e)); -} - -/* Ein Treffer über mehrere Basen: Basis, Seite, Bewertung. Benannt, weil ein - * anonymer struct-Typ sich nicht zuweisen lässt (und Sortieren ist Zuweisen). */ -struct kbhit { - char slug[MAX_KB]; - struct entry e; - double score; -}; - -/* Name → Verzeichnisname: Kleinbuchstaben, alles Fremde zu "-", keine Doppelpunkte. */ -static void slugify(const char *name, char *out, size_t outlen) -{ - size_t i = 0; - int last_dash = 0; - - for (const char *p = name; *p != '\0' && i + 1 < outlen; p++) { - unsigned char ch = (unsigned char)*p; - - if (isalnum(ch)) { - out[i++] = (char)tolower(ch); - last_dash = 0; - } else if (!last_dash) { - out[i++] = '-'; - last_dash = 1; - } - } - while (i > 0 && out[i - 1] == '-') - i--; - out[i] = '\0'; -} - -static char *kb_root(void) -{ - char *root = mem_root(); - mcp_buf b; - - mcp_buf_init(&b); - mcp_buf_printf(&b, "%s/kb", root); - free(root); - return b.p; -} - -static char *kb_dir(const char *slug) -{ - char *root = kb_root(); - mcp_buf b; - - mcp_buf_init(&b); - mcp_buf_printf(&b, "%s/%s", root, slug); - free(root); - return b.p; -} - -static char *kb_file(const char *slug, const char *leaf) -{ - char *dir = kb_dir(slug); - mcp_buf b; - - mcp_buf_init(&b); - mcp_buf_printf(&b, "%s/%s", dir, leaf); - free(dir); - return b.p; -} - -/* Existiert die Basis? Name und Beschreibung kommen aus kb.json. */ -static int kb_meta(const char *slug, char *name, size_t namelen, char *desc, size_t desclen) -{ - char *path = kb_file(slug, "kb.json"); - char *raw = read_file(path); - mcp_json *v; - - free(path); - if (raw == NULL) - return -1; - v = mcp_parse(raw); - free(raw); - if (v == NULL) - return -1; - snprintf(name, namelen, "%s", js(v, "name")); - if (desc != NULL) - snprintf(desc, desclen, "%s", js(v, "description")); - mcp_json_free(v); - return 0; -} - -static int kb_save_meta(const char *slug, const char *name, const char *desc) -{ - char *path = kb_file(slug, "kb.json"); - mcp_buf b; - int rc; - - mcp_buf_init(&b); - mcp_buf_puts(&b, "{\n "); - put_str(&b, "name", name); - mcp_buf_puts(&b, ",\n "); - put_str(&b, "slug", slug); - mcp_buf_puts(&b, ",\n "); - put_str(&b, "description", desc != NULL ? desc : ""); - mcp_buf_printf(&b, ",\n \"created\":%ld\n}\n", (long)time(NULL)); - rc = write_file_atomic(path, b.p != NULL ? b.p : "{}"); - mcp_buf_free(&b); - free(path); - return rc; -} - -/* Alle Basen: Verzeichnisse unter kb/ mit kb.json. */ -static int kb_list_all(char slugs[][MAX_KB], int max, int *count) -{ - char *root = kb_root(); - DIR *d; - struct dirent *de; - - *count = 0; - d = opendir(root); - if (d == NULL) { - free(root); - return -1; - } - while ((de = readdir(d)) != NULL && *count < max) { - char *path; - FILE *f; - - if (de->d_name[0] == '.') - continue; - path = kb_file(de->d_name, "kb.json"); - f = fopen(path, "r"); - free(path); - if (f == NULL) - continue; /* kein fertiges Verzeichnis */ - fclose(f); - snprintf(slugs[*count], MAX_KB, "%s", de->d_name); - (*count)++; - } - closedir(d); - free(root); - /* Verzeichnisreihenfolge ist nicht stabil; sortieren, damit die Ausgabe es ist. */ - for (int i = 1; i < *count; i++) - for (int j = i; j > 0 && strcmp(slugs[j - 1], slugs[j]) > 0; j--) { - char tmp[MAX_KB]; - - snprintf(tmp, sizeof(tmp), "%s", slugs[j]); - snprintf(slugs[j], MAX_KB, "%s", slugs[j - 1]); - snprintf(slugs[j - 1], MAX_KB, "%s", tmp); - } - return 0; -} - -static int kb_entry_ids(const char *slug, char ***out, size_t *out_n) -{ - char *dir = kb_dir(slug); - DIR *d; - struct dirent *de; - char **ids = NULL; - size_t n = 0, cap = 0; - - *out = NULL; - *out_n = 0; - d = opendir(dir); - free(dir); - if (d == NULL) - return -1; - while ((de = readdir(d)) != NULL) { - size_t len = strlen(de->d_name); - char *id; - - if (len < 6 || strncmp(de->d_name, "e", 1) != 0 || - strcmp(de->d_name + len - 5, ".json") != 0) - continue; - id = strndup(de->d_name, len - 5); - if (id == NULL) - continue; - if (n == cap) { - size_t ncap = cap ? cap * 2 : 32; - char **grown = realloc(ids, sizeof(char *) * ncap); - - if (grown == NULL) { - free(id); - continue; - } - ids = grown; - cap = ncap; - } - ids[n++] = id; - } - closedir(d); - *out = ids; - *out_n = n; - return 0; -} - -static char *kb_claim_entry_id(const char *slug) -{ - char *dir = kb_dir(slug); - int n; - - mkdir_p(dir); - for (n = 1; n < 100000; n++) { - mcp_buf path; - int fd; - - mcp_buf_init(&path); - mcp_buf_printf(&path, "%s/e%05d.json", dir, n); - fd = open(path.p, O_CREAT | O_EXCL | O_WRONLY, 0644); - mcp_buf_free(&path); - if (fd >= 0) { - char *out = malloc(16); - - close(fd); - if (out != NULL) - snprintf(out, 16, "e%05d", n); - free(dir); - return out; - } - if (errno != EEXIST) { - free(dir); - return NULL; - } - } - free(dir); - return NULL; -} - -static int entry_load(const char *slug, const char *id, struct entry *out) -{ - char *leaf, *path, *raw; - mcp_json *v; - const mcp_json *emb, *hist; - - memset(out, 0, sizeof(*out)); - if (!valid_id(id)) - return -1; - leaf = NULL; - { - mcp_buf b; - - mcp_buf_init(&b); - mcp_buf_printf(&b, "%s.json", id); - leaf = b.p; - } - path = kb_file(slug, leaf); - free(leaf); - raw = read_file(path); - free(path); - if (raw == NULL) - return -1; - v = mcp_parse(raw); - free(raw); - if (v == NULL) - return -1; - - out->id = strdup(id); - out->title = strdup(js(v, "title")); - out->text = strdup(js(v, "text")); - out->tags = strdup(js(v, "tags")); - out->source = strdup(js(v, "source")); - out->model = strdup(js(v, "model")); - out->created = (long)mcp_arg_num(v, "created", 0); - out->updated = (long)mcp_arg_num(v, "updated", out->created); - emb = mcp_arg(v, "embedding"); - out->dim = (emb != NULL) ? (int)mcp_array_len(emb) : 0; - if (out->dim > 0 && out->dim <= MAX_DIM) { - size_t i; - - out->vec = malloc(sizeof(double) * (size_t)out->dim); - if (out->vec == NULL) { - out->dim = 0; - } else { - for (i = 0; i < (size_t)out->dim; i++) { - const mcp_json *e = mcp_array_at(emb, i); - - out->vec[i] = (e != NULL && e->t == MCP_NUM) ? e->n : 0.0; - } - } - } - hist = mcp_arg(v, "history"); - if (hist != NULL) { - size_t nh = mcp_array_len(hist); - - for (size_t i = 0; i < nh && out->nhist < MAX_HISTORY; i++) { - const mcp_json *h = mcp_array_at(hist, i); - - if (h == NULL) - continue; - out->hist_text[out->nhist] = strdup(js(h, "text")); - out->hist_at[out->nhist] = (long)mcp_arg_num(h, "updated", 0); - if (out->hist_text[out->nhist] != NULL) - out->nhist++; - } - } - mcp_json_free(v); - if (out->id == NULL || out->title == NULL || out->text == NULL || - out->tags == NULL || out->source == NULL || out->model == NULL) { - free_entry(out); - return -1; - } - return 0; -} - -static int entry_save(const char *slug, const struct entry *e) -{ - char *leaf, *path; - mcp_buf b; - int rc, i; - - mcp_buf_init(&b); - mcp_buf_puts(&b, "{\n "); - put_str(&b, "id", e->id); - mcp_buf_puts(&b, ",\n "); - put_str(&b, "title", e->title); - mcp_buf_puts(&b, ",\n "); - put_str(&b, "text", e->text); - mcp_buf_puts(&b, ",\n "); - put_str(&b, "tags", e->tags); - mcp_buf_puts(&b, ",\n "); - put_str(&b, "source", e->source); - mcp_buf_puts(&b, ",\n "); - put_str(&b, "model", e->model); - mcp_buf_printf(&b, ",\n \"created\":%ld,\n \"updated\":%ld", e->created, e->updated); - mcp_buf_puts(&b, ",\n \"embedding\":["); - for (i = 0; i < e->dim; i++) - mcp_buf_printf(&b, "%s%.7f", i ? "," : "", e->vec[i]); - mcp_buf_puts(&b, "],\n \"history\":["); - for (i = 0; i < e->nhist; i++) { - mcp_buf_puts(&b, i ? ",{" : "{"); - put_str(&b, "text", e->hist_text[i]); - mcp_buf_printf(&b, ",\"updated\":%ld}", e->hist_at[i]); - } - mcp_buf_puts(&b, "]\n}\n"); - - { - mcp_buf leaf_buf; - - mcp_buf_init(&leaf_buf); - mcp_buf_printf(&leaf_buf, "%s.json", e->id); - leaf = leaf_buf.p; - } - path = kb_file(slug, leaf != NULL ? leaf : "e.json"); - free(leaf); - rc = write_file_atomic(path, b.p != NULL ? b.p : "{}"); - free(path); - mcp_buf_free(&b); - return rc; -} - -/* Seite mit diesem Titel (ohne Rücksicht auf Groß/klein) oder NULL. */ -static char *find_by_title(const char *slug, const char *title) -{ - char **ids = NULL; - size_t n = 0, i; - char *found = NULL; - - if (kb_entry_ids(slug, &ids, &n) != 0) - return NULL; - for (i = 0; i < n && found == NULL; i++) { - struct entry e; - - if (entry_load(slug, ids[i], &e) != 0) - continue; - if (strcasecmp(e.title, title) == 0) - found = strdup(ids[i]); - free_entry(&e); - } - for (i = 0; i < n; i++) - free(ids[i]); - free(ids); - return found; -} - -static void fmt_entry_ref(mcp_buf *b, const char *slug, const struct entry *e, double score) -{ - mcp_buf_printf(b, "%s/%s [%s]", slug, e->id, e->title); - if (score >= 0.0) - mcp_buf_printf(b, " score=%.3f", score); - if (e->tags != NULL && *e->tags != '\0') - mcp_buf_printf(b, " tags=%s", e->tags); - mcp_buf_puts(b, "\n "); - if (strlen(e->text) > 400) - mcp_buf_add(b, e->text, 400); - else - mcp_buf_puts(b, e->text); - if (strlen(e->text) > 400) - mcp_buf_puts(b, " …"); - mcp_buf_puts(b, "\n"); -} - -static void t_kb_create(mcp_conn *c, const mcp_json *args, void *user) -{ - const char *name = mcp_arg_string(args, "name"); - const char *desc = mcp_arg_string(args, "description"); - char slug[MAX_KB], existing[MAX_KB]; - - (void)user; - if (name == NULL || *name == '\0') { - mcp_reply_error(c, "kb_create needs a name"); - return; - } - slugify(name, slug, sizeof(slug)); - if (slug[0] == '\0') { - mcp_reply_error(c, "that name has no usable characters for a directory"); - return; - } - if (kb_meta(slug, existing, sizeof(existing), NULL, 0) == 0) { - say(c, "knowledge base \"%s\" already exists (%s) - write into it with kb_write", - existing, slug); - return; - } - { - char *dir = kb_dir(slug); - - mkdir_p(dir); - free(dir); - } - if (kb_save_meta(slug, name, desc) != 0) { - mcp_reply_error(c, "could not create the knowledge base directory"); - return; - } - say(c, "created knowledge base \"%s\" (%s)%s%s", name, slug, - (desc != NULL && *desc) ? ": " : "", (desc != NULL && *desc) ? desc : ""); -} - -static void t_kb_list(mcp_conn *c, const mcp_json *args, void *user) -{ - char slugs[64][MAX_KB]; - int n = 0, i; - mcp_buf b; - - (void)args; - (void)user; - if (kb_list_all(slugs, 64, &n) != 0 || n == 0) { - say(c, "no knowledge bases yet - create one with kb_create"); - return; - } - mcp_buf_init(&b); - mcp_buf_printf(&b, "%d knowledge base(s):\n", n); - for (i = 0; i < n; i++) { - char name[256] = "", desc[256] = ""; - char **ids = NULL; - size_t ne = 0; - - (void)kb_meta(slugs[i], name, sizeof(name), desc, sizeof(desc)); - (void)kb_entry_ids(slugs[i], &ids, &ne); - for (size_t k = 0; k < ne; k++) - free(ids[k]); - free(ids); - mcp_buf_printf(&b, " %-24s %-20s %4zu entries", slugs[i], name, ne); - if (desc[0] != '\0') - mcp_buf_printf(&b, " — %s", desc); - mcp_buf_puts(&b, "\n"); - } - mcp_reply_text(c, b.p != NULL ? b.p : ""); - mcp_buf_free(&b); -} - -static void t_kb_write(mcp_conn *c, const mcp_json *args, void *user) -{ - const char *kb = mcp_arg_string(args, "kb"); - const char *title = mcp_arg_string(args, "title"); - const char *text = mcp_arg_string(args, "text"); - const char *tags = mcp_arg_string(args, "tags"); - const char *source = mcp_arg_string(args, "source"); - char slug[MAX_KB], name[256]; - char *own_id = NULL; - struct entry old, e; - int had_old = 0; - double *vec = NULL; - int dim = 0, embedded, i; - - (void)user; - if (kb == NULL || *kb == '\0' || title == NULL || *title == '\0' || - text == NULL || *text == '\0') { - mcp_reply_error(c, "kb_write needs kb, title and text"); - return; - } - slugify(kb, slug, sizeof(slug)); - if (kb_meta(slug, name, sizeof(name), NULL, 0) != 0) { - say(c, "no knowledge base \"%s\" - create it first with kb_create", kb); - return; - } - if (strlen(text) > MAX_TEXT) { - mcp_reply_error(c, "text too long (limit 16384 bytes) - a page, not a transcript"); - return; - } - embedded = (embed_fetch(text, &vec, &dim) == 0); - - /* Eine Seite mit diesem Titel gibt es schon? Dann ist das eine Aktualisierung. - * Die alte Fassung wird EINMAL gelesen und danach in die Historie übernommen. */ - memset(&old, 0, sizeof(old)); - { - char *found = find_by_title(slug, title); - - if (found != NULL) { - if (entry_load(slug, found, &old) == 0) - had_old = 1; - own_id = found; - } else { - own_id = kb_claim_entry_id(slug); - } - } - if (own_id == NULL) { - free(vec); - mcp_reply_error(c, "could not allocate a page id"); - return; - } - - memset(&e, 0, sizeof(e)); - e.id = own_id; - e.title = (char *)title; - e.text = (char *)text; - e.tags = (char *)(tags != NULL ? tags : ""); - e.source = (char *)(source != NULL ? source : ""); - e.model = (char *)(embedded ? embed_model() : "none"); - e.created = had_old && old.created ? old.created : (long)time(NULL); - e.updated = (long)time(NULL); - e.vec = vec; - e.dim = dim; - - /* Historie: die bisherigen Fassungen übernehmen, die vorherige anhängen, die - * älteste fallen lassen, wenn fünf voll sind. */ - if (had_old) { - for (i = 0; i < old.nhist && e.nhist < MAX_HISTORY; i++) { - e.hist_text[e.nhist] = strdup(old.hist_text[i] != NULL ? old.hist_text[i] : ""); - e.hist_at[e.nhist] = old.hist_at[i]; - if (e.hist_text[e.nhist] != NULL) - e.nhist++; - } - if (old.text != NULL && strcmp(old.text, text) != 0) { - if (e.nhist == MAX_HISTORY) { - free(e.hist_text[0]); - for (i = 1; i < MAX_HISTORY; i++) { - e.hist_text[i - 1] = e.hist_text[i]; - e.hist_at[i - 1] = e.hist_at[i]; - } - e.hist_text[MAX_HISTORY - 1] = NULL; - e.nhist = MAX_HISTORY - 1; - } - e.hist_text[e.nhist] = strdup(old.text); - e.hist_at[e.nhist] = old.updated; - if (e.hist_text[e.nhist] != NULL) - e.nhist++; - } - } - - if (entry_save(slug, &e) == 0) { - say(c, "%s %s/%s \"%s\"%s%s", had_old ? "updated" : "created", slug, own_id, title, - embedded ? " (embedded)" : " (WITHOUT embedding: the embedder did not answer, " - "search will fall back to substrings for this page)", - (had_old && e.nhist > 0) ? " - earlier version kept in history" : ""); - } else { - say(c, "could not write %s/%s", slug, own_id); - } - - for (i = 0; i < e.nhist; i++) - free(e.hist_text[i]); - if (had_old) - free_entry(&old); - free(vec); - free(own_id); -} - -static void t_kb_entries(mcp_conn *c, const mcp_json *args, void *user) -{ - const char *kb = mcp_arg_string(args, "kb"); - int limit = mcp_arg_int(args, "limit", 50); - char slug[MAX_KB], name[256]; - char **ids = NULL; - size_t n = 0, i, shown = 0; - mcp_buf b; - - (void)user; - if (kb == NULL || *kb == '\0') { - mcp_reply_error(c, "kb_entries needs kb"); - return; - } - slugify(kb, slug, sizeof(slug)); - if (kb_meta(slug, name, sizeof(name), NULL, 0) != 0) { - say(c, "no knowledge base \"%s\"", kb); - return; - } - if (limit <= 0 || limit > 500) - limit = 50; - mcp_buf_init(&b); - if (kb_entry_ids(slug, &ids, &n) != 0 || n == 0) { - mcp_buf_printf(&b, "\"%s\" has no entries yet\n", name); - mcp_reply_text(c, b.p); - mcp_buf_free(&b); - return; - } - mcp_buf_printf(&b, "%zu entries in \"%s\" (newest first):\n", n, name); - for (i = n; i > 0 && shown < (size_t)limit; i--) { - struct entry e; - - if (entry_load(slug, ids[i - 1], &e) != 0) - continue; - mcp_buf_printf(&b, " %s %s", e.id, e.title); - if (e.tags != NULL && *e.tags != '\0') - mcp_buf_printf(&b, " tags=%s", e.tags); - mcp_buf_printf(&b, " (%s, updated %ld)\n", e.dim > 0 ? "embedded" : "no vector", - e.updated); - shown++; - free_entry(&e); - } - if (shown < n) - mcp_buf_printf(&b, "(%zu of %zu)\n", shown, n); - mcp_reply_text(c, b.p); - mcp_buf_free(&b); - for (i = 0; i < n; i++) - free(ids[i]); - free(ids); -} - -static void t_kb_read(mcp_conn *c, const mcp_json *args, void *user) -{ - const char *kb = mcp_arg_string(args, "kb"); - const char *title = mcp_arg_string(args, "title"); - const char *id = mcp_arg_string(args, "id"); - int history = mcp_arg_bool(args, "history", 0); - char slug[MAX_KB], name[256]; - struct entry e; - mcp_buf b; - char *found = NULL; - - (void)user; - if (kb == NULL || *kb == '\0') { - mcp_reply_error(c, "kb_read needs kb and title (or id)"); - return; - } - if (id == NULL || *id == '\0') { - if (title == NULL || *title == '\0') { - mcp_reply_error(c, "kb_read needs kb and title (or id)"); - return; - } - } - slugify(kb, slug, sizeof(slug)); - if (kb_meta(slug, name, sizeof(name), NULL, 0) != 0) { - say(c, "no knowledge base \"%s\"", kb); - return; - } - found = (id != NULL && *id != '\0') ? strdup(id) : find_by_title(slug, title); - if (found == NULL || entry_load(slug, found, &e) != 0) { - say(c, "no page \"%s\" in \"%s\"", title != NULL ? title : id, name); - free(found); - return; - } - mcp_buf_init(&b); - mcp_buf_printf(&b, "# %s (%s/%s)\n", e.title, slug, e.id); - if (e.tags != NULL && *e.tags != '\0') - mcp_buf_printf(&b, "tags: %s\n", e.tags); - mcp_buf_printf(&b, "source: %s created: %ld updated: %ld vector: %s\n\n", - e.source ? e.source : "-", e.created, e.updated, - e.dim > 0 ? "yes" : "no"); - mcp_buf_puts(&b, e.text != NULL ? e.text : ""); - mcp_buf_puts(&b, "\n"); - if (history && e.nhist > 0) { - mcp_buf_printf(&b, "\n--- %d earlier version(s) ---\n", e.nhist); - for (int i = e.nhist - 1; i >= 0; i--) - mcp_buf_printf(&b, "[%ld]\n%s\n", e.hist_at[i], - e.hist_text[i] != NULL ? e.hist_text[i] : ""); - } - mcp_reply_text(c, b.p != NULL ? b.p : ""); - mcp_buf_free(&b); - free_entry(&e); - free(found); -} - -static void t_kb_search(mcp_conn *c, const mcp_json *args, void *user) -{ - const char *query = mcp_arg_string(args, "query"); - const char *kb = mcp_arg_string(args, "kb"); - int limit = mcp_arg_int(args, "limit", 5); - char slugs[64][MAX_KB]; - int nslugs = 0, si; - double *qvec = NULL; - int qdim = 0, semantic; - mcp_buf b; - int shown = 0; - - (void)user; - if (query == NULL || *query == '\0') { - mcp_reply_error(c, "kb_search needs a query"); - return; - } - if (limit <= 0 || limit > 50) - limit = 5; - semantic = (embed_fetch(query, &qvec, &qdim) == 0); - - if (kb != NULL && *kb != '\0') { - char slug[MAX_KB]; - - slugify(kb, slug, sizeof(slug)); - snprintf(slugs[0], MAX_KB, "%s", slug); - nslugs = 1; - } else if (kb_list_all(slugs, 64, &nslugs) != 0) { - nslugs = 0; - } - if (nslugs == 0) { - say(c, "no knowledge bases yet - create one with kb_create"); - free(qvec); - return; - } - - /* Alle Treffer sammeln und global sortieren: eine Suche über mehrere Basen soll - * die beste Seite zeigen, nicht die beste Seite je Basis. */ - { - struct kbhit *hits = NULL; - size_t nhits = 0, cap = 0; - - for (si = 0; si < nslugs; si++) { - char **ids = NULL; - size_t n = 0, i; - - if (kb_entry_ids(slugs[si], &ids, &n) != 0) - continue; - for (i = 0; i < n; i++) { - struct entry e; - double score = -1.0; - int take = 0; - - if (entry_load(slugs[si], ids[i], &e) != 0) - continue; - if (semantic && e.dim == qdim) { - score = cosine(qvec, e.vec, qdim); - take = 1; - } else if (!semantic && text_has(e.text, query)) { - score = -1.0; - take = 1; - } - if (!take) { - free_entry(&e); - continue; - } - if (nhits == cap) { - size_t ncap = cap ? cap * 2 : 32; - void *grown = realloc(hits, ncap * sizeof(struct kbhit)); - - if (grown == NULL) { - free_entry(&e); - continue; - } - hits = grown; - cap = ncap; - } - snprintf(hits[nhits].slug, MAX_KB, "%.*s", MAX_KB - 1, slugs[si]); - hits[nhits].e = e; - hits[nhits].score = score; - nhits++; - } - for (i = 0; i < n; i++) - free(ids[i]); - free(ids); - } - /* Sortieren: bester Score zuerst (bei Substringsuche die Einfügereihenfolge). */ - for (size_t i = 1; i < nhits; i++) - for (size_t j = i; j > 0 && hits[j].score > hits[j - 1].score; j--) { - struct kbhit tmp = hits[j]; - - hits[j] = hits[j - 1]; - hits[j - 1] = tmp; - } - - mcp_buf_init(&b); - if (nhits == 0) { - mcp_buf_printf(&b, "nothing found for \"%s\"%s%s\n", query, - semantic ? "" : " (substring match - the embedder did not answer)", - ""); - } else { - size_t show = (size_t)limit < nhits ? (size_t)limit : nhits; - - mcp_buf_printf(&b, "%zu hit(s) for \"%s\"%s:\n", show, query, - semantic ? "" : " (substring match)"); - for (size_t i = 0; i < show; i++) { - fmt_entry_ref(&b, hits[i].slug, &hits[i].e, semantic ? hits[i].score : -1.0); - shown++; - } - } - mcp_reply_text(c, b.p != NULL ? b.p : ""); - mcp_buf_free(&b); - for (size_t i = 0; i < nhits; i++) - free_entry(&hits[i].e); - free(hits); - } - (void)shown; - free(qvec); -} - -static void t_kb_delete(mcp_conn *c, const mcp_json *args, void *user) -{ - const char *kb = mcp_arg_string(args, "kb"); - const char *title = mcp_arg_string(args, "title"); - const char *id = mcp_arg_string(args, "id"); - char slug[MAX_KB], name[256]; - char *target = NULL, *path, *leaf; - - (void)user; - if (kb == NULL || *kb == '\0') { - mcp_reply_error(c, "kb_delete needs kb and title (or id)"); - return; - } - slugify(kb, slug, sizeof(slug)); - if (kb_meta(slug, name, sizeof(name), NULL, 0) != 0) { - say(c, "no knowledge base \"%s\"", kb); - return; - } - target = (id != NULL && *id != '\0') ? strdup(id) : find_by_title(slug, title); - if (target == NULL) { - say(c, "no page \"%s\" in \"%s\"", title != NULL ? title : "", name); - return; - } - { - mcp_buf lb; - - mcp_buf_init(&lb); - mcp_buf_printf(&lb, "%s.json", target); - leaf = lb.p; - } - path = kb_file(slug, leaf != NULL ? leaf : "e.json"); - free(leaf); - if (unlink(path) != 0) { - free(path); - free(target); - mcp_reply_error(c, "could not remove the page file"); - return; - } - free(path); - say(c, "deleted %s/%s", slug, target); - free(target); -} - -static void t_kb_drop(mcp_conn *c, const mcp_json *args, void *user) -{ - const char *kb = mcp_arg_string(args, "kb"); - const char *confirm = mcp_arg_string(args, "confirm"); - char slug[MAX_KB], name[256]; - char **ids = NULL; - size_t n = 0, i; - char *dir; - mcp_buf cmd; - - (void)user; - if (kb == NULL || *kb == '\0') { - mcp_reply_error(c, "kb_drop needs kb and confirm=\"yes\""); - return; - } - slugify(kb, slug, sizeof(slug)); - if (kb_meta(slug, name, sizeof(name), NULL, 0) != 0) { - say(c, "no knowledge base \"%s\"", kb); - return; - } - /* Löschen einer ganzen Basis ist nicht rückgängig zu machen — deshalb ein - * ausdrückliches Wort. Ein Tippfehler soll nicht das ganze Wiki entfernen. */ - if (confirm == NULL || strcmp(confirm, "yes") != 0) { - say(c, "not deleting \"%s\": pass confirm=\"yes\". It holds %s.", name, - (kb_entry_ids(slug, &ids, &n) == 0) ? "pages" : "unknown pages"); - for (i = 0; i < n; i++) - free(ids[i]); - free(ids); - return; - } - if (kb_entry_ids(slug, &ids, &n) == 0) { - for (i = 0; i < n; i++) - free(ids[i]); - free(ids); - } - dir = kb_dir(slug); - mcp_buf_init(&cmd); - mcp_buf_printf(&cmd, "rm -rf '%s'", dir != NULL ? dir : ""); - if (system(cmd.p) != 0) { - mcp_buf_free(&cmd); - free(dir); - mcp_reply_error(c, "could not remove the knowledge base directory"); - return; - } - mcp_buf_free(&cmd); - free(dir); - say(c, "dropped knowledge base \"%s\" (%zu pages removed)", name, n); -} - /* ------------------------------------------------------------------ table */ static const mcp_tool TOOLS[] = { @@ -1905,79 +1052,6 @@ static const mcp_tool TOOLS[] = { "true.", "{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\"}},\"required\":[\"id\"]}", t_delete }, - /* ---- Wissensbasis: benannte Sammlungen von Seiten ---- */ - { "kb_create", - "Create a named knowledge base - a self-contained wiki: pages with a title and a " - "body, searchable by meaning. Use one base per subject area (\"olivia-technik\", " - "\"fleet-junction\"), not one per project. A page with the same title is updated, " - "not duplicated.", - "{\"type\":\"object\",\"properties\":{" - "\"name\":{\"type\":\"string\",\"description\":\"human name, e.g. olivia-technik\"}," - "\"description\":{\"type\":\"string\",\"description\":\"what belongs in here\"}}," - "\"required\":[\"name\"]}", - t_kb_create }, - { "kb_list", - "Which knowledge bases exist, how many pages each holds and what they are for. Call " - "it before writing so you put a page into the right base.", - "{\"type\":\"object\",\"properties\":{}}", - t_kb_list }, - { "kb_write", - "Write a page into a knowledge base. Same title in the same base = update: the old " - "text is kept in the page history, nothing is lost silently. Write reference " - "material a human would want to read later - procedures, measurements, decisions " - "with their reasoning - not chat transcripts.", - "{\"type\":\"object\",\"properties\":{" - "\"kb\":{\"type\":\"string\",\"description\":\"which knowledge base\"}," - "\"title\":{\"type\":\"string\",\"description\":\"page title; the same title updates the page\"}," - "\"text\":{\"type\":\"string\",\"description\":\"the page body\"}," - "\"tags\":{\"type\":\"string\",\"description\":\"comma separated\"}," - "\"source\":{\"type\":\"string\",\"description\":\"who or what this came from\"}}," - "\"required\":[\"kb\",\"title\",\"text\"]}", - t_kb_write }, - { "kb_read", - "Read one page in full by title (or id), optionally with its earlier versions.", - "{\"type\":\"object\",\"properties\":{" - "\"kb\":{\"type\":\"string\"}," - "\"title\":{\"type\":\"string\"}," - "\"id\":{\"type\":\"string\",\"description\":\"instead of title\"}," - "\"history\":{\"type\":\"boolean\",\"description\":\"include earlier versions\"}}," - "\"required\":[\"kb\"]}", - t_kb_read }, - { "kb_search", - "Search the knowledge bases by meaning. Without kb it searches all of them and ranks " - "globally, so the best page wins, not the best page per base. This is how you answer " - "\"what does our own documentation say about X\".", - "{\"type\":\"object\",\"properties\":{" - "\"query\":{\"type\":\"string\"}," - "\"kb\":{\"type\":\"string\",\"description\":\"restrict to one base\"}," - "\"limit\":{\"type\":\"integer\",\"description\":\"default 5\"}}," - "\"required\":[\"query\"]}", - t_kb_search }, - { "kb_entries", - "List the pages of one knowledge base - titles, tags, whether a vector exists, when " - "it was last changed. Use it to see what the wiki already covers.", - "{\"type\":\"object\",\"properties\":{" - "\"kb\":{\"type\":\"string\"}," - "\"limit\":{\"type\":\"integer\",\"description\":\"default 50\"}}," - "\"required\":[\"kb\"]}", - t_kb_entries }, - { "kb_delete", - "Delete one page from a knowledge base (by title or id). Use it for pages that are " - "wrong or obsolete - a wiki with two contradicting pages is worse than none.", - "{\"type\":\"object\",\"properties\":{" - "\"kb\":{\"type\":\"string\"}," - "\"title\":{\"type\":\"string\"}," - "\"id\":{\"type\":\"string\"}}," - "\"required\":[\"kb\"]}", - t_kb_delete }, - { "kb_drop", - "Delete a whole knowledge base and every page in it. Needs confirm=\"yes\"; without " - "it the tool only says what would be lost. This cannot be undone.", - "{\"type\":\"object\",\"properties\":{" - "\"kb\":{\"type\":\"string\"}," - "\"confirm\":{\"type\":\"string\",\"description\":\"the word yes, deliberately\"}}," - "\"required\":[\"kb\"]}", - t_kb_drop }, { "memory_scopes", "Overview: which scopes exist and how many memories each holds. Call it when you " "do not know where something belongs.", diff --git a/tests/run.py b/tests/run.py index bb3a715..947c317 100644 --- a/tests/run.py +++ b/tests/run.py @@ -148,11 +148,10 @@ def main(): tools = c.call("tools/list").get("result", {}).get("tools", []) names = sorted(t["name"] for t in tools) - want = ["kb_create", "kb_delete", "kb_drop", "kb_entries", "kb_list", "kb_read", - "kb_search", "kb_write", "memory_add", "memory_delete", "memory_get", - "memory_list", "memory_scopes", "memory_search", "memory_update"] + want = ["memory_add", "memory_delete", "memory_get", "memory_list", + "memory_scopes", "memory_search", "memory_update"] if names == want: - ok("fifteen tools: seven for memories, eight for knowledge bases") + ok("seven tools (the knowledge bases moved to wikid)") else: bad("tools are %s" % names) @@ -217,96 +216,6 @@ def main(): else: bad("memory_scopes: %s" % t[:160]) - # ---- Wissensbasis: benannte Sammlungen, Seiten wie Erinnerungen ---- - t, err = c.tool("kb_create", name="Olivia Technik", - description="was am Fahrzeug gemessen und entschieden wurde") - if not err and "created" in t and "olivia-technik" in t: - ok("a knowledge base gets a readable slug (Olivia Technik → olivia-technik)") - else: - bad("kb_create: %s" % t[:160]) - - t, err = c.tool("kb_write", kb="olivia-technik", title="Frostschutz", - text="G12+ blau, Mischung 50:50, geprüft bei -25 Grad.", - tags="kühlmittel") - if not err and "created" in t: - ok("a page is created in the base") - else: - bad("kb_write: %s" % t[:160]) - - t, err = c.tool("kb_write", kb="olivia-technik", title="Frostschutz", - text="G12+ blau, Mischung 60:40, geprüft bei -32 Grad.") - if not err and "updated" in t and "e00001" in t: - ok("the same title updates the page instead of duplicating it") - else: - bad("second write: %s" % t[:160]) - - t, err = c.tool("kb_read", kb="olivia-technik", title="Frostschutz", history=True) - if not err and "-32 Grad" in t and "-25 Grad" in t and "earlier version" in t: - ok("the earlier version survives in the page history") - else: - bad("kb_read with history: %s" % t[:200]) - - t, err = c.tool("kb_write", kb="Olivia Technik", title="Ölwechsel", - text="OM 364 A: 12 Liter 15W-40, Filter alle 10 000 km.") - if not err: - ok("the base is addressed by name, not by slug") - else: - bad("write by display name: %s" % t[:160]) - - t, err = c.tool("kb_search", query="wie viel öl braucht der motor", limit=2) - if not err and "Ölwechsel" in t and "score=" in t: - ok("search finds the right page by meaning across bases") - else: - bad("kb_search: %s" % t[:200]) - - t, err = c.tool("kb_search", query="öl", kb="olivia-technik") - if not err and "Ölwechsel" in t and "Frostschutz" not in t.split("\n")[0]: - ok("restricting to one base keeps the others out") - else: - bad("kb_search with kb: %s" % t[:200]) - - t, err = c.tool("kb_entries", kb="olivia-technik") - if not err and "Frostschutz" in t and "Ölwechsel" in t and "2 entries" in t: - ok("kb_entries lists both pages") - else: - bad("kb_entries: %s" % t[:200]) - - t, err = c.tool("kb_list") - if not err and "olivia-technik" in t and "2 entries" in t: - ok("kb_list shows the base with its page count") - else: - bad("kb_list: %s" % t[:200]) - - t, err = c.tool("kb_drop", kb="olivia-technik") - if not err and "not deleting" in t and "confirm" in t: - ok("dropping a base needs an explicit yes") - else: - bad("kb_drop without confirm: %s" % t[:160]) - - t, err = c.tool("kb_delete", kb="olivia-technik", title="Frostschutz") - if not err and "deleted" in t: - ok("a single page can be deleted") - else: - bad("kb_delete: %s" % t[:160]) - - t, err = c.tool("kb_read", kb="olivia-technik", title="Frostschutz") - if err or "no page" in t: - ok("the deleted page is gone") - else: - bad("the page is still there: %s" % t[:120]) - - t, err = c.tool("kb_drop", kb="olivia-technik", confirm="yes") - if not err and "dropped" in t: - ok("dropping with confirm removes the base") - else: - bad("kb_drop with confirm: %s" % t[:160]) - - t, err = c.tool("kb_list") - if "no knowledge bases" in t: - ok("and it is no longer listed") - else: - bad("the base is still listed: %s" % t[:120]) - # Ohne Embedder: speichern geht weiter, die Suche sagt, was sie tut. stub.shutdown() t, err = c.tool("memory_add", text="Die Pumpe läuft seit März leise.", scope="van/technik") @@ -321,6 +230,17 @@ def main(): else: bad("fallback search: %s" % t[:200]) + # ---- Verlauf: git, wenn vorhanden ---- + if shutil.which("git"): + log = subprocess.run(["git", "-C", env["MEMORYDIR"], "log", "--oneline"], + capture_output=True, text=True).stdout.strip().splitlines() + if len(log) >= 3: + ok("every memory change is committed (%d commits)" % len(log)) + else: + bad("expected at least 3 commits, got %s" % log) + else: + ok("git is not installed here - the versioning test is skipped, not faked") + t, err = c.tool("memory_delete", id="m00002") if not err and "deleted" in t and not os.path.exists( os.path.join(env["MEMORYDIR"], "m00002.json")):