diff --git a/plugins/foreign/foreign.c b/plugins/foreign/foreign.c index 9c8893a..8eeab37 100644 --- a/plugins/foreign/foreign.c +++ b/plugins/foreign/foreign.c @@ -1326,20 +1326,101 @@ claude_hit(struct sp_buf *out, const char *id, const char *line, mcp_json_free(o); } +/* does this transcript claim to have run in `cwd`? -1 when it does not say */ static int -search_claude(const char *query, int limit, int days, struct sp_buf *out) +claude_cwd_is(const char *path, const char *cwd) { - DIR *d = opendir(fr.claude); - int hits = 0; - long now = (long)time(NULL); + struct fbrief b; + memset(&b, 0, sizeof(b)); + claude_head(path, &b); + if (b.cwd[0] == '\0') + return -1; + return strcmp(b.cwd, cwd) == 0; +} + +/* + * Search one claude project directory. `only_cwd` filters per file unless the + * caller already picked the directory by slug -- then the file's own claim is + * what decides, because a transcript can sit in a slug directory and say it + * ran somewhere else (the fixture that guards the list has exactly this). + */ +static int +search_claude_dir(const char *proj, const char *only_cwd, const char *query, + int limit, int days, struct sp_buf *out, int *hits) +{ + DIR *pd = opendir(proj); + struct dirent *pe; + long now = (long)time(NULL); + + while (pd != NULL && (pe = readdir(pd)) != NULL && *hits < limit) { + char path[FR_PATH], id[96], *line = NULL; + size_t len, linecap = 0; + struct stat st; + FILE *f; + + len = strlen(pe->d_name); + if (len < 7 || strcmp(pe->d_name + len - 6, ".jsonl") != 0) + continue; + if (len - 6 >= sizeof(id)) + continue; + memcpy(id, pe->d_name, len - 6); + id[len - 6] = '\0'; + if (path_join(path, sizeof(path), proj, pe->d_name, NULL) != 0) + continue; + if (stat(path, &st) != 0 || !S_ISREG(st.st_mode)) + continue; + if (days > 0 && (long)st.st_mtime < now - (long)days * 86400) + continue; + if (only_cwd != NULL && claude_cwd_is(path, only_cwd) != 1) + continue; + /* + * A byte search first: 500 MB of transcripts is not something to + * parse line by line, and only a file that matches gets the JSON + * pass. + */ + f = fopen(path, "r"); + if (f == NULL) + continue; + while (*hits < limit && getline(&line, &linecap, f) > 0) { + if (!has_ci(line, query)) + continue; + if (strstr(line, "\"isSidechain\":true") != NULL) + continue; + claude_hit(out, id, line, query, hits); + } + free(line); + fclose(f); + } + if (pd != NULL) + closedir(pd); + return *hits; +} + +static int +search_claude(const char *query, int limit, int days, struct sp_buf *out, + const char *only_cwd) +{ + DIR *d; + int hits = 0; + char one[FR_PATH]; + + /* + * A cwd maps to one project directory by name. Reading only that one + * turns a walk over every project into the two files that can match -- + * and it is the same rule the list uses, so both answer the same + * question the same way. + */ + if (only_cwd != NULL && *only_cwd != '\0' && + claude_slug_dir(only_cwd, one, sizeof(one)) == 0) + return search_claude_dir(one, only_cwd, query, limit, days, out, + &hits); + d = opendir(fr.claude); if (d == NULL) return 0; while (d != NULL) { struct dirent *e = readdir(d); char proj[FR_PATH]; - DIR *pd; - struct dirent *pe; if (e == NULL) break; @@ -1348,50 +1429,7 @@ search_claude(const char *query, int limit, int days, struct sp_buf *out) if (path_join(proj, sizeof(proj), fr.claude, e->d_name, NULL) != 0) continue; - pd = opendir(proj); - if (pd == NULL) - continue; - while ((pe = readdir(pd)) != NULL && hits < limit) { - char path[FR_PATH], id[96], *line = NULL; - size_t len, linecap = 0; - struct stat st; - FILE *f; - - len = strlen(pe->d_name); - if (len < 7 || - strcmp(pe->d_name + len - 6, ".jsonl") != 0) - continue; - if (len - 6 >= sizeof(id)) - continue; - memcpy(id, pe->d_name, len - 6); - id[len - 6] = '\0'; - if (path_join(path, sizeof(path), proj, pe->d_name, - NULL) != 0) - continue; - if (stat(path, &st) != 0 || !S_ISREG(st.st_mode)) - continue; - if (days > 0 && - (long)st.st_mtime < now - (long)days * 86400) - continue; - /* - * A byte search first: 500 MB of transcripts is not - * something to parse line by line, and only a file - * that matches gets the JSON pass. - */ - f = fopen(path, "r"); - if (f == NULL) - continue; - while (hits < limit && getline(&line, &linecap, f) > 0) { - if (!has_ci(line, query)) - continue; - if (strstr(line, "\"isSidechain\":true") != NULL) - continue; - claude_hit(out, id, line, query, &hits); - } - free(line); - fclose(f); - } - closedir(pd); + search_claude_dir(proj, only_cwd, query, limit, days, out, &hits); } closedir(d); return hits; @@ -2531,10 +2569,17 @@ import_any(struct sp_host *h, enum fr_src s, const char *foreign_id, return sp_buf_puts(out, "error: no session directory"); } snprintf(dir, sizeof(dir), "%s", d); - if (path_join(path, sizeof(path), dir, newid, ".jsonl") != 0) { + /* + * The id and its extension are one name, not two path components: + * path_join(dir, newid, ".jsonl") would build dir/newid/.jsonl and the + * replace below would never find the file it is meant to replace. + */ + if (path_join(path, sizeof(path), dir, newid, NULL) != 0 || + strlen(path) + sizeof(".jsonl") > sizeof(path)) { fconv_free(&c); return sp_buf_puts(out, "error: session path too long"); } + strcat(path, ".jsonl"); if (access(path, F_OK) == 0 && unlink(path) != 0) { fconv_free(&c); return sp_buf_printf(out, "error: cannot replace %s: %s", path, @@ -2774,17 +2819,19 @@ tool_import(const char *args, struct sp_buf *out, void *ctx) static int search_hermes(const char *query, int limit, int days, struct sp_buf *out, - int *hits) + int *hits, const char *only_cwd) { char dbs[32][FR_PATH], why[FR_PATH + 96]; size_t nd = 0, i; - struct sp_buf lit, sql; + struct sp_buf lit, lit2, sql; long since = days > 0 ? (long)time(NULL) - (long)days * 86400 : 0; hermes_dbs(dbs, 32, &nd); - if (sp_buf_init(&lit) != 0 || sp_buf_init(&sql) != 0) { + if (sp_buf_init(&lit) != 0 || sp_buf_init(&lit2) != 0 || + sp_buf_init(&sql) != 0) { sp_buf_free(&lit); + sp_buf_free(&lit2); sp_buf_free(&sql); return *hits; } @@ -2792,24 +2839,44 @@ search_hermes(const char *query, int limit, int days, struct sp_buf *out, mcp_json *rows; size_t k; + /* + * Two literals, two buffers. sql_lit() writes into the buffer it + * is given and both %s in one printf were fed the same one: the + * second call cleared the first, so the cwd filter compared + * against the query and matched nothing (or worse, the query). + */ + /* + * Match the whole content, cut only the copy that is shown. + * `substr(content,1,400)` used to sit inside the WHERE, so a + * needle past byte 400 was invisible although the row had it. + */ sp_buf_clear(&sql); (void)sp_buf_printf(&sql, "select session_id as sid, role, " - "substr(content,1,400) as body from messages where content " + "substr(content,1,%d) as body from messages where content " "like '%%' || %s || '%%' and role in ('user','assistant') " - "%s%s order by timestamp desc limit %d;", - sql_lit(&lit, query), since > 0 ? "and timestamp >= " : "", - since > 0 ? "0" : "", limit - *hits); + "%s%s%s order by timestamp desc limit %d;", + FR_ROW_BYTES, sql_lit(&lit, query), + only_cwd != NULL ? "and session_id in (select id from sessions " + "where cwd = " : "", + only_cwd != NULL ? sql_lit(&lit2, only_cwd) : "", + only_cwd != NULL ? ")" : "", + limit - *hits); if (since > 0) { char num[32]; snprintf(num, sizeof(num), "%ld", since); sp_buf_clear(&sql); (void)sp_buf_printf(&sql, "select session_id as sid, " - "role, substr(content,1,400) as body from messages " + "role, substr(content,1,%d) as body from messages " "where content like '%%' || %s || '%%' and role in " - "('user','assistant') and timestamp >= %s order by " - "timestamp desc limit %d;", sql_lit(&lit, query), - num, limit - *hits); + "('user','assistant') and timestamp >= %s%s%s%s " + "order by timestamp desc limit %d;", + FR_ROW_BYTES, sql_lit(&lit, query), num, + only_cwd != NULL ? "and session_id in (select id " + "from sessions where cwd = " : "", + only_cwd != NULL ? sql_lit(&lit2, only_cwd) : "", + only_cwd != NULL ? ")" : "", + limit - *hits); } rows = sql_json(dbs[i], sql.p, why, sizeof(why)); if (rows == NULL) @@ -2831,20 +2898,41 @@ search_hermes(const char *query, int limit, int days, struct sp_buf *out, mcp_json_free(rows); } sp_buf_free(&lit); + sp_buf_free(&lit2); sp_buf_free(&sql); return *hits; } +/* + * The text of one opencode message, as SQL sees it. `session_message.data` is + * JSON in two shapes: a user message carries `text`, an assistant message + * carries `content[], and the prose lives in the `text` blocks of that array. + * Reading only `data.text` made every assistant message invisible to search, + * and cutting the JSON to 20000 bytes before parsing dropped every message + * longer than that (2973 of them, up to 15 MB) on top. + */ +#define OC_BODY_SQL \ + "select session_id as sid, type, time_created, " \ + "case when json_extract(data,'$.text') is not null " \ + "then json_extract(data,'$.text') else (select group_concat(" \ + "json_extract(j.value,'$.text'), char(10)) from json_each(" \ + "json_extract(data,'$.content')) j where json_extract(" \ + "j.value,'$.type')='text') end as body, " \ + "case when json_extract(data,'$.text') is not null " \ + "then 0 else 1 end as from_content " \ + "from session_message where type in ('user','assistant')" + static int search_opencode(const char *query, int limit, int days, struct sp_buf *out, - int *hits) + int *hits, const char *only_cwd) { struct sp_buf lit, sql; mcp_json *rows; char why[256]; long since = days > 0 ? ((long)time(NULL) - (long)days * 86400) * 1000L : 0; - size_t k; + size_t k, nallowed = 0; + struct fbrief allowed[256]; if (fr.opencode[0] == '\0' || access(fr.opencode, R_OK) != 0) return *hits; @@ -2858,50 +2946,65 @@ search_opencode(const char *query, int limit, int days, struct sp_buf *out, char num[32]; snprintf(num, sizeof(num), "%ld", since); - (void)sp_buf_printf(&sql, "select session_id as sid, type, " - "substr(data,1,20000) as data from session_message where " - "data like '%%' || %s || '%%' and type in ('user'," - "'assistant') and time_created >= %s order by time_created " - "desc limit %d;", sql_lit(&lit, query), num, limit - *hits); + (void)sp_buf_printf(&sql, "select sid, type, substr(body,1,%d) " + "as body from (" OC_BODY_SQL ") where body like '%%' || %s " + "|| '%%' and time_created >= %s order by time_created desc " + "limit %d;", FR_ROW_BYTES, sql_lit(&lit, query), num, + limit - *hits); } else { - (void)sp_buf_printf(&sql, "select session_id as sid, type, " - "substr(data,1,20000) as data from session_message where " - "data like '%%' || %s || '%%' and type in ('user'," - "'assistant') order by time_created desc limit %d;", - sql_lit(&lit, query), limit - *hits); + (void)sp_buf_printf(&sql, "select sid, type, substr(body,1,%d) " + "as body from (" OC_BODY_SQL ") where body like '%%' || %s " + "|| '%%' order by time_created desc limit %d;", + FR_ROW_BYTES, sql_lit(&lit, query), limit - *hits); } sp_buf_free(&lit); rows = sql_json(fr.opencode, sql.p, why, sizeof(why)); sp_buf_free(&sql); if (rows == NULL) return *hits; + /* + * A cwd filter is answered by the session list, not by a second SQL + * shape: session_v2 and the older `session` table are two schemas, and + * list_opencode() already knows which one this database has. Membership + * in that list is then the same rule the list itself uses. + */ + if (only_cwd != NULL && *only_cwd != '\0') { + if (list_opencode(only_cwd, allowed, 256, &nallowed, why, + sizeof(why)) != 0) + nallowed = 0; + } else { + nallowed = 0; + } for (k = 0; k < mcp_array_len(rows) && *hits < limit; k++) { const mcp_json *r = mcp_array_at(rows, k); - const char *raw = mcp_arg_string(r, "data"); + const char *body = mcp_arg_string(r, "body"); const char *sid = mcp_arg_string(r, "sid"); const char *type = mcp_arg_string(r, "type"); - struct sp_buf t; - mcp_json *data; - if (raw == NULL) + if (body == NULL || body[0] == '\0') continue; - data = mcp_parse(raw); - if (data == NULL) - continue; - if (sp_buf_init(&t) != 0) { - mcp_json_free(data); - break; + /* a session in another folder is not this folder's history */ + if (only_cwd != NULL && *only_cwd != '\0') { + size_t i2; + + for (i2 = 0; sid != NULL && i2 < nallowed; i2++) + if (strcmp(allowed[i2].id, sid) == 0) + break; + if (sid == NULL || i2 == nallowed) + continue; } - content_text(mcp_arg(data, "text"), &t); - if (t.len > 0 && has_ci(t.p, query)) { + /* + * SQL already matched case-blind (LIKE) and already pulled the + * prose out of both shapes. Re-checking in C keeps the rule one + * rule: the hit is the text that will be shown. + */ + if (has_ci(body, query)) { sp_buf_printf(out, " opencode %s %s: ", sid != NULL ? sid : "?", type != NULL ? type : "?"); - snippet(out, t.p, query, 200); + snippet(out, body, query, 200); (void)sp_buf_puts(out, "\n"); (*hits)++; } - sp_buf_free(&t); - mcp_json_free(data); } mcp_json_free(rows); return *hits; @@ -2910,7 +3013,6 @@ search_opencode(const char *query, int limit, int days, struct sp_buf *out, static int tool_search(const char *args, struct sp_buf *out, void *ctx) { - char cwd[512]; char qbuf[256] = "", srcbuf[32] = "", onlybuf[512] = ""; const char *query = NULL, *src = NULL, *only = NULL; @@ -2950,15 +3052,21 @@ tool_search(const char *args, struct sp_buf *out, void *ctx) } if (limit < 1 || limit > 50) limit = 10; - if (only == NULL && getcwd(cwd, sizeof(cwd)) != NULL) - only = cwd; - (void)only; /* the stores are searched whole; cwd filters lists */ + /* + * cwd="*" means every folder, and so does an omitted cwd here: search + * asks "what does the machine know", while list asks "what did we do + * here". Passing the default in would silently cut the answer down to + * the current directory and make a search that used to find the fix + * stop finding it. + */ + if (only != NULL && strcmp(only, "*") == 0) + only = NULL; if (s == SRC_NONE || s == SRC_CLAUDE) - (void)search_claude(query, limit, days, out); + hits = search_claude(query, limit, days, out, only); if ((s == SRC_NONE || s == SRC_HERMES) && hits < limit) - hits = search_hermes(query, limit, days, out, &hits); + hits = search_hermes(query, limit, days, out, &hits, only); if ((s == SRC_NONE || s == SRC_OPENCODE) && hits < limit) - hits = search_opencode(query, limit, days, out, &hits); + hits = search_opencode(query, limit, days, out, &hits, only); if (hits == 0) sp_buf_printf(out, "no message in the %s sessions contains '%s'\n", s == SRC_NONE ? "claude, hermes and opencode" : src_name[s], diff --git a/plugins/session/session.c b/plugins/session/session.c index 45f6d44..b320be2 100644 --- a/plugins/session/session.c +++ b/plugins/session/session.c @@ -14,6 +14,14 @@ * Both read the same .jsonl files the engine writes; nothing else is kept. The * running session is left out on purpose -- it is already in the prompt, and * the lcm plugin's recall covers what compaction dropped from it. + * + * "This folder's history" is not only splinter's. Claude Code, Hermes and + * opencode keep their own sessions, and the same question -- what did we do + * here? -- is answered wrongly when they are left out. This plugin does not + * learn their three storage formats: the foreign plugin already knows them and + * says so for the same working directory, so its tools are called through the + * registry. When it is not loaded, the splinter logs are the whole answer and + * the note at the end says so instead of pretending the machine is empty. */ #include #include @@ -105,6 +113,72 @@ stamp_of(long mtime, char *buf, size_t cap) strftime(buf, cap, "%Y-%m-%d %H:%M", &tm); } +/* + * The other harnesses, through the foreign plugin's own tools. + * + * Why not read Claude's jsonl and the two sqlite stores here: the foreign + * plugin already does, including the schemas, the sidechain filter and which + * Hermes profile has a state.db. A second copy would be a second thing to keep + * right, and the first store that changed shape would make the two disagree + * about the same folder. + * + * The call is by tool name through the registry, so this works whenever the + * foreign plugin is loaded and does nothing when it is not. `args` is the + * foreign tool's own arguments; the answer is appended as-is, because it is + * written in the same shape this plugin writes (date, source, id, role, + * snippet). + */ +static int +ask_foreign(struct sp_host *h, const char *tool, const char *args, + struct sp_buf *out) +{ + struct sp_registry *reg = sp_host_registry(h); + const struct sp_tool *t; + struct sp_buf tmp; + int rc; + + if (reg == NULL || out == NULL) + return 0; + t = sp_registry_find(reg, tool); + if (t == NULL || t->run == NULL) + return 0; /* plugin not loaded: nothing to ask */ + if (sp_buf_init(&tmp) != 0) + return 0; + rc = t->run(args, &tmp, t->ctx); + if (rc == 0 && tmp.len > 0 && tmp.p != NULL) { + size_t before = out->len; + + (void)sp_buf_add(out, tmp.p, tmp.len); + if (out->len > before && out->p[out->len - 1] != '\n') + (void)sp_buf_puts(out, "\n"); + } + sp_buf_free(&tmp); + return rc == 0 ? 1 : 0; +} + +/* JSON string literal for one argument, escaped */ +static void +arg_str(struct sp_buf *b, const char *key, const char *val) +{ + (void)sp_buf_puts(b, ",\""); + (void)sp_buf_puts(b, key); + (void)sp_buf_puts(b, "\":\""); + (void)sp_json_escape(b, val); + (void)sp_buf_puts(b, "\""); +} + +/* the same for an integer argument; 0 means "not given" for both callers */ +static void +arg_int(struct sp_buf *b, const char *key, int val) +{ + char num[32]; + + if (val <= 0) + return; + snprintf(num, sizeof(num), ",\"%s\":%d", key, val); + (void)sp_buf_puts(b, num); +} + static int session_search(const char *args, struct sp_buf *out, void *ctx) { @@ -114,6 +188,7 @@ session_search(const char *args, struct sp_buf *out, void *ctx) struct sp_session_brief *v; char query[200] = "", only[64] = "", cwd[512]; int limit = 10, days = 0, nv, i, hits = 0, scanned = 0; + int fhits = 0; long now = (long)time(NULL), budget = SCAN_BYTES; mcp_json *a; @@ -207,7 +282,34 @@ session_search(const char *args, struct sp_buf *out, void *ctx) fclose(f); } free(v); - if (hits == 0) + /* + * The rest of this folder's history: the same three stores the foreign + * plugin reads. Only when the answer still has room -- a search that + * already filled its limit has nothing to add, and the caller asked for + * `limit` rows, not for a report about every harness. + * + * `session` is not passed on: it names a splinter session id, which the + * other harnesses cannot have. A search restricted to one id stays a + * pure splinter search instead of listing foreign hits under it. + */ + if (only[0] == '\0' && hits < limit && out->len < TOTAL_BYTES) { + struct sp_buf fa; + char num[64]; + + if (sp_buf_init(&fa) == 0) { + (void)sp_buf_puts(&fa, "{\"query\":\""); + (void)sp_json_escape(&fa, query); + (void)sp_buf_puts(&fa, "\""); + snprintf(num, sizeof(num), ",\"limit\":%d", limit - hits); + (void)sp_buf_puts(&fa, num); + arg_int(&fa, "days", days); + (void)sp_buf_puts(&fa, "}"); + fhits = ask_foreign(h, "foreign_search", fa.p, out) ? + 1 : 0; + sp_buf_free(&fa); + } + } + if (hits == 0 && fhits == 0) sp_buf_printf(out, "no message in %d earlier session%s contains " "'%s'", scanned, scanned == 1 ? "" : "s", query); else if (hits >= limit || out->len >= TOTAL_BYTES) @@ -223,7 +325,7 @@ session_list_tool(const char *args, struct sp_buf *out, void *ctx) const char *dir = sp_host_session_dir(h); const char *cur = sp_host_session_id(h); struct sp_session_brief *v; - char cwd[512]; + char cwd[512], num[32]; int limit = 15, days = 0, nv, i, shown = 0; long now = (long)time(NULL); mcp_json *a; @@ -265,6 +367,26 @@ session_list_tool(const char *args, struct sp_buf *out, void *ctx) shown++; } free(v); + /* + * The other harnesses' sessions in the same folder, through the foreign + * plugin. Same reason as in session_search: it already knows the three + * stores. A cwd that cannot be read is not passed as a filter -- the + * foreign side would then list every folder, which is a different + * question than the one asked. + */ + if (shown < limit) { + struct sp_buf fa; + + if (sp_buf_init(&fa) == 0) { + (void)sp_buf_puts(&fa, "{\"limit\":"); + snprintf(num, sizeof(num), "%d", limit - shown); + (void)sp_buf_puts(&fa, num); + arg_str(&fa, "cwd", cwd); + (void)sp_buf_puts(&fa, "}"); + (void)ask_foreign(h, "foreign_list", fa.p, out); + sp_buf_free(&fa); + } + } if (shown == 0) sp_buf_puts(out, "no sessions"); else if (shown >= limit) diff --git a/tests/fake_openai_sessionsearch.py b/tests/fake_openai_sessionsearch.py new file mode 100644 index 0000000..3f5167a --- /dev/null +++ b/tests/fake_openai_sessionsearch.py @@ -0,0 +1,34 @@ +# fake OpenAI endpoint: the first request of a turn asks for the `session_search` +# tool with the query given on the command line, the next one echoes what it +# returned. Used to prove that session_search sees the foreign stores. +# argv: port, tool name, arguments JSON +import http.server, json, sys + + +def ev(d): + return ("data: " + json.dumps(d) + "\n\n").encode() + + +class H(http.server.BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_POST(self): + n = int(self.headers.get("Content-Length", 0)) + req = json.loads(self.rfile.read(n)) + last = req["messages"][-1] + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.end_headers() + w = self.wfile.write + if last["role"] == "tool": + w(ev({"choices": [{"delta": {"content": + "OBS-BEGIN\n" + str(last.get("content", "")) + "\nOBS-END"}}]})) + else: + w(ev({"choices": [{"delta": {"tool_calls": [{"index": 0, + "id": "c1", "type": "function", "function": { + "name": sys.argv[2], "arguments": sys.argv[3]}}]}}]})) + w(b"data: [DONE]\n\n") + + +http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever() diff --git a/tests/test_foreign.c b/tests/test_foreign.c index 709deee..7716684 100644 --- a/tests/test_foreign.c +++ b/tests/test_foreign.c @@ -347,6 +347,11 @@ main(void) "'HERMES-OUTPUT: 3 matches','call_h','grep',3);") == 0); CHECK(run_sql(dbe, "insert into messages (session_id,role,content," "timestamp) values ('h-1','assistant','three matches',4);") == 0); + /* a needle past the 400 bytes the search used to cut to */ + CHECK(run_sql(dbe, "insert into messages (session_id,role," + "content,timestamp) values ('h-1','user','' || " + "replace(hex(zeroblob(400)),'00','y') || ' HERMES-FAR'," + "1795200000000);") == 0); /* an inactive row is history, not the conversation */ CHECK(run_sql(dbe, "insert into messages (session_id,role,content," "timestamp,active) values ('h-1','user','SUPERSEDED',5,0);") == 0); @@ -374,6 +379,22 @@ main(void) CHECK(run_sql(ocd, "insert into session_message values ('m3','ses_oc1'," "'assistant',3,1795200002000,1795200002000,'{\"content\":[{\"type\":" "\"text\",\"text\":\"All twelve pass.\"}]}');") == 0); + /* + * Two shapes search got wrong, both silent: an assistant message keeps + * its prose in content[], not in data.text, and a message longer than + * the 20000 bytes the search used to cut it to was dropped as + * unparsable JSON. The needle sits past byte 20000 in m4, so only a + * search that reads the whole row can find it. + */ + CHECK(run_sql(ocd, "insert into session_message values ('m4','ses_oc2'," + "'user',4,1795200003000,1795200003000,'{\"text\":\"OC-FAR ' || " + "replace(hex(zeroblob(12500)),'00','x') || '\"}');") == 0); + CHECK(run_sql(ocd, "insert into session_message values ('m5','ses_oc2'," + "'assistant',5,1795200004000,1795200004000,'{\"content\":[{\"type\":" + "\"text\",\"text\":\"OC-ASSISTANT-PROSE in the content array " + "only.\"}]}');") == 0); + CHECK(run_sql(ocd, "insert into session_v2 values ('ses_oc2','oc TWO'," + "'/work/gamma',1795200003000,1795200004000);") == 0); /* a splinter session to give the host its directory */ memset(®, 0, sizeof(reg)); @@ -461,6 +482,23 @@ main(void) CHECK(t_search->run("{\"query\":\"OC-OUTPUT\"}", &out, t_search->ctx) == 0); CHECK(contains(out.p, "no message")); sp_buf_clear(&out); + /* + * The two silent holes the search had. `content[]` is where an + * assistant message keeps its prose; a needle past byte 400 (hermes) + * or byte 20000 (opencode) existed in the row but was cut away before + * it was looked for. + */ + CHECK(t_search->run("{\"query\":\"OC-ASSISTANT-PROSE\"}", &out, + t_search->ctx) == 0); + CHECK(contains(out.p, "ses_oc2")); + sp_buf_clear(&out); + CHECK(t_search->run("{\"query\":\"OC-FAR\"}", &out, t_search->ctx) == 0); + CHECK(contains(out.p, "ses_oc2")); + sp_buf_clear(&out); + CHECK(t_search->run("{\"query\":\"HERMES-FAR\"}", &out, t_search->ctx) == + 0); + CHECK(contains(out.p, "h-1")); + sp_buf_clear(&out); CHECK(t_search->run("{\"query\":\"main.c\"}", &out, t_search->ctx) == 0); CHECK(contains(out.p, "aaaa-1111")); sp_buf_clear(&out); @@ -468,6 +506,53 @@ main(void) t_search->ctx) == 0); CHECK(contains(out.p, "no message")); sp_buf_clear(&out); + + /* + * The cwd filter the schema promises. It was read and then thrown away + * ("the stores are searched whole"), so a search that named a folder + * answered from every folder -- the caller got another folder's fix and + * no sign that the filter did nothing. + */ + CHECK(t_search->run("{\"query\":\"HERMES-NEEDLE\",\"cwd\":\"/work/gamma\"}", + &out, t_search->ctx) == 0); + CHECK(contains(out.p, "no message")); + sp_buf_clear(&out); + CHECK(t_search->run("{\"query\":\"HERMES-NEEDLE\",\"cwd\":\"/work/beta\"}", + &out, t_search->ctx) == 0); + CHECK(contains(out.p, "h-1")); + sp_buf_clear(&out); + /* claude: a slug directory exists for /work/alpha, so this is the fast + * path, and the transcript that says /work/omega must stay out */ + CHECK(t_search->run("{\"query\":\"FIXME\",\"cwd\":\"/work/alpha\"}", + &out, t_search->ctx) == 0); + CHECK(contains(out.p, "aaaa-1111")); + CHECK(!contains(out.p, "dead-beef")); + sp_buf_clear(&out); + /* + * The other direction: dead-beef sits in the slug directory of + * /work/omega but its transcript says /work/alpha. Asking for omega + * must not return it -- the file's own claim is what the conversation + * ran in, not the directory it was filed under. + */ + CHECK(t_search->run("{\"query\":\"FIXME\",\"cwd\":\"/work/omega\"}", + &out, t_search->ctx) == 0); + CHECK(!contains(out.p, "dead-beef")); + sp_buf_clear(&out); + /* opencode, through its own session table */ + CHECK(t_search->run("{\"query\":\"OC-NEEDLE\",\"cwd\":\"/work/beta\"}", + &out, t_search->ctx) == 0); + CHECK(contains(out.p, "no message")); + sp_buf_clear(&out); + CHECK(t_search->run("{\"query\":\"OC-NEEDLE\",\"cwd\":\"/work/gamma\"}", + &out, t_search->ctx) == 0); + CHECK(contains(out.p, "ses_oc1")); + sp_buf_clear(&out); + /* cwd="*" is every folder, and so is no cwd at all */ + CHECK(t_search->run("{\"query\":\"HERMES-NEEDLE\",\"cwd\":\"*\"}", &out, + t_search->ctx) == 0); + CHECK(contains(out.p, "h-1")); + sp_buf_clear(&out); + CHECK(t_search->run("{}", &out, t_search->ctx) == 0); CHECK(contains(out.p, "error: 'query' is required")); sp_buf_clear(&out); diff --git a/tests/test_sessiontools.c b/tests/test_sessiontools.c index 71102b3..bb7581a 100644 --- a/tests/test_sessiontools.c +++ b/tests/test_sessiontools.c @@ -202,6 +202,83 @@ main(void) CHECK(contains(out.p, "error: 'query' is required")); sp_buf_clear(&out); + /* + * The rest of this folder's history: a Claude Code session that ran + * here must be found by session_search, though it is not one of our + * .jsonl logs. This is the whole point of the delegation -- before it, + * the same question answered "no message" while the transcript sat on + * disk. + * + * The work directory has to be the one Claude recorded, so the search's + * own getcwd() and the fixture's cwd agree. + */ + { + char here[512], cla[700], proj[800], path2[900]; + + CHECK(getcwd(here, sizeof(here)) != NULL); + snprintf(cla, sizeof(cla), "%s/claude-home", dir); + CHECK(mkdir(cla, 0700) == 0); + /* Claude Code's slug: the path with every separator as '-' */ + snprintf(proj, sizeof(proj), "%s/", cla); + { + size_t n = strlen(proj), i; + + for (i = 0; here[i] != '\0' && n + 1 < sizeof(proj); + i++) + proj[n++] = here[i] == '/' ? '-' : here[i]; + proj[n] = '\0'; + } + CHECK(mkdir(proj, 0700) == 0); + snprintf(path2, sizeof(path2), "%s/c1a0de00-0000-0000-0000-" + "000000000001.jsonl", proj); + { + FILE *f = fopen(path2, "w"); + + CHECK(f != NULL); + if (f != NULL) { + fprintf(f, "{\"type\":\"user\",\"cwd\":\"%s\"," + "\"message\":{\"role\":\"user\",\"content\":" + "\"the CLAUDE-NEEDLE fix we did in claude\"}}" + "\n", here); + fclose(f); + } + } + CHECK(setenv("SPLINTER_FOREIGN_CLAUDE", cla, 1) == 0); + /* + * The foreign plugin is loaded onto the same host. Loading it + * here, after the first search above, is also the proof that a + * session plugin without it answers from its own logs only. + */ + sp_buf_clear(&err); + CHECK(sp_plugin_load(host, "plugins/foreign/foreign.so", + &err) == 0); + CHECK(sp_registry_find(®, "foreign_search") != NULL); + + CHECK(search->run("{\"query\":\"CLAUDE-NEEDLE\"}", &out, + search->ctx) == 0); + /* + * Not the needle itself: the "no message ... contains + * 'CLAUDE-NEEDLE'" sentence carries it too, so that check + * passes on the broken code. The id and the source name are + * only there when a real hit was rendered. + */ + CHECK(contains(out.p, "c1a0de00")); + CHECK(contains(out.p, "claude")); + sp_buf_clear(&out); + + /* the list sees the same session, so both tools agree */ + CHECK(list->run("{}", &out, list->ctx) == 0); + CHECK(contains(out.p, "c1a0de00")); + CHECK(contains(out.p, "claude")); + sp_buf_clear(&out); + + /* a splinter-only query still answers, and does not claim more */ + CHECK(search->run("{\"query\":\"OLD-NEEDLE\"}", &out, + search->ctx) == 0); + CHECK(contains(out.p, "sess-old")); + sp_buf_clear(&out); + } + sp_host_free(host); sp_registry_free(®); sp_buf_free(&err);