From fa16bfd0a9221cb2f0772977352f023d50d7af58 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sat, 21 Nov 2026 21:26:43 +0000 Subject: [PATCH] foreign: adopt a claude, hermes or opencode session as a splinter session MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Another harness's conversation is not a session until splinter can resume it. plugins/foreign reads the three stores that already exist on the machine - ~/.claude/projects//.jsonl, /state.db (and profiles/*/state.db) and opencode.db's session_v2/session_message - and offers four tools plus /foreign: list, search TEXT, read SOURCE ID, import SOURCE ID The stores are read with sqlite3 -readonly: an import copies, it never moves. Reasoning blocks are dropped on the way in, because a provider does not accept another model's thinking as evidence. Tool calls arrive with their results in place, which is what makes the imported session worth resuming instead of retyping. import writes a real splinter session: the conversation as a replayable jsonl, and a .meta with the source's title, its start time and *its* working directory. So /open continues it in the chat, --session-id --resume in a shell, and -c finds it in the directory the conversation actually ran in. The marker foreign=: survives every later reopen, which needed the core's .meta sidecar to carry keys it does not own. Building this found nine bugs, each one seen red before it was green: - four use-after-frees: mcp_arg_string returns a pointer *into* the parse tree, read after mcp_json_free. That garbage in `only`/`src` was why a list of three stores answered "no sessions" and named AÃ_Â¥U. - sql_json took "no rows" for a failure (NULL), so every empty answer looked like a broken database. - args_split never terminated its buffers: /foreign list became "unknown subcommand 'list('". - path_join(dir, id, ".meta") built dir/id/.meta, so the sidecar landed in a subdirectory. - claude_slug_dir had the sign inverted and returned -1 for every non-empty cwd, so the project directory was never found. - sp_session_open overwrote cwd with getcwd() on *every* open, though the comment beside it promised the opposite: imports claimed the directory they were imported from and -c then picked the wrong session. - hermes_text ran strncmp(p, "\x00json:", 6) on an empty content, a one-byte allocation - heap-buffer-overflow, found by ASAN. The marker is stripped in SQL anyway. - hermes_calls never freed the root node on the object path (5456 bytes over 42 allocations). - list_any reported strerror(errno) with errno never set: a real file with the wrong schema read as "No such file or directory". The SQL reason is passed through now. Checked end to end against the stores on this machine: claude 64 sessions, opencode 25, hermes 0 (both hermes databases here are empty, count(*) = 0). A real opencode session of 150 messages reads back with its tool output; one of 75 imports with the right cwd and title, --resume sends its history, and -c from the source directory opens it. tests/sh/port.sh comes along: the shell tests guessed a port with 20000 + $$ % 30000 and on 2026-11-21 landed on one dtsession held. The fake died, curl got an answer from dtsession, and twenty checks blamed the gateway. They ask the kernel for a free port now. --- Makefile | 11 +- README.md | 58 + docs/CONFIG.md | 54 + docs/splinter.1 | 19 + plugins/foreign/foreign.c | 3162 +++++++++++++++++++++++++++++++++++++ tests/sh/port.sh | 41 + tests/test_a2a.sh | 3 +- tests/test_a2a_input.sh | 3 +- tests/test_a2a_server.sh | 3 +- tests/test_a2a_ui.sh | 3 +- tests/test_agents_ui.sh | 3 +- tests/test_anthropic.sh | 3 +- tests/test_attach.sh | 3 +- tests/test_foreign.c | 579 +++++++ tests/test_gateway.sh | 25 +- tests/test_limit_wait.sh | 3 +- tests/test_reconnect.sh | 3 +- tests/test_ui.sh | 3 +- 18 files changed, 3962 insertions(+), 17 deletions(-) create mode 100644 plugins/foreign/foreign.c create mode 100644 tests/sh/port.sh create mode 100644 tests/test_foreign.c diff --git a/Makefile b/Makefile index 638e9d1..f8b1115 100644 --- a/Makefile +++ b/Makefile @@ -45,11 +45,12 @@ PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \ plugins/junction/junction.so \ plugins/self/self.so \ plugins/cache/cache.so \ - plugins/session/session.so + plugins/session/session.so \ + plugins/foreign/foreign.so TESTS = tests/test_buf tests/test_tool tests/test_session tests/test_conv \ tests/test_transport tests/test_agent tests/test_openai \ tests/test_theme tests/test_plugin tests/test_skills tests/test_telegram tests/test_delegate tests/test_builtin tests/test_ascii tests/test_ack tests/test_i18n tests/test_config tests/test_focus tests/test_sse tests/test_anthropic tests/test_cli tests/test_compactor tests/test_corecompact tests/test_secrets tests/test_mcpclient tests/test_kids tests/test_lifecycle tests/test_md tests/test_tgmd tests/test_providers tests/test_b64 tests/test_pause tests/test_swarm tests/test_provstate tests/test_usage tests/test_agents tests/test_confblock tests/test_jobs tests/test_engine tests/test_self tests/test_fuzz \ - tests/test_sessiontools tests/test_embed + tests/test_sessiontools tests/test_embed tests/test_foreign RPATH = -Wl,-rpath,'$$ORIGIN' PLUGIN_RPATH = -Wl,-rpath,'$$ORIGIN/../..' @@ -109,6 +110,10 @@ plugins/session/session.so: plugins/session/session.c $(LIB) $(CC) $(CFLAGS) -shared -o $@ plugins/session/session.c -L. -lsplinter \ $(PLUGIN_RPATH) $(LIBS) +plugins/foreign/foreign.so: plugins/foreign/foreign.c $(LIB) + $(CC) $(CFLAGS) -shared -o $@ plugins/foreign/foreign.c -L. -lsplinter \ + $(PLUGIN_RPATH) $(LIBS) + plugins/cli/cli.so: plugins/cli/cli.c $(LIB) $(CC) $(CFLAGS) -shared -o $@ plugins/cli/cli.c -L. -lsplinter \ $(PLUGIN_RPATH) $(LIBS) @@ -269,6 +274,8 @@ tests/test_fuzz: tests/test_fuzz.c $(LIB) tests/test_sessiontools: tests/test_sessiontools.c $(LIB) plugins/session/session.so $(CC) $(CFLAGS) -o $@ tests/test_sessiontools.c -L. -lsplinter $(TEST_RPATH) $(LIBS) +tests/test_foreign: tests/test_foreign.c $(LIB) plugins/foreign/foreign.so + $(CC) $(CFLAGS) -o $@ tests/test_foreign.c -L. -lsplinter $(TEST_RPATH) $(LIBS) tests/test_usage: tests/test_usage.c $(LIB) $(CC) $(CFLAGS) -o $@ tests/test_usage.c -L. -lsplinter $(TEST_RPATH) $(LIBS) diff --git a/README.md b/README.md index d3bf6f4..c7f11a1 100644 --- a/README.md +++ b/README.md @@ -479,6 +479,21 @@ comes from the parser (`sp_sse_kind`). ## Compaction +When the conversation outgrows the window, the core compactor replaces the older +part with a digest: each operator message keeps its opening, each assistant turn +what it claimed to be doing, each tool result enough to recognise it — in order, +because the thread is the point. The newest messages stay verbatim, and the last +real user message is pinned so a long tool loop cannot push the task out. A +plugin that compacts too runs first; the core one is the backstop. + +What it drops is not gone. The digest opens with a line saying where it went, +and the model has `history_search`, which searches the whole session by meaning +— not just what is quoted in the digest. The index is built by a background +thread, never inside the turn, so the turn does not pay for it (28 ms on a +937 KB session). `core { embed = local }` is the default: a built-in CPU +encoder, no model, no key. `embed = openai` points it at a real embedding model +instead, `off` takes the tool away. See `docs/CONFIG.md`. + `focus` keeps a short recap of the session's goal in front of the model every seven turns — one inserted system message, never twice in a turn, nothing until a goal is set. `/goal ` sets the goal and starts that recap turn; the @@ -787,6 +802,49 @@ like a resume and was none. The agent profile comes back too: the engine keeps the session's profile in `.agent`, so a session left in plan resumes in plan; the model it was left on is in `.model` and comes back too. +## Foreign sessions: claude, hermes, opencode + +`splinter --plugin plugins/foreign/foreign.so` reads the three session stores +that already exist on the machine and can adopt one of their conversations: + +| source | what it reads | +|------------|--------------------------------------------------------| +| `claude` | `~/.claude/projects//.jsonl` (Claude Code) | +| `hermes` | `/state.db` and `/profiles/*/state.db` | +| `opencode` | `~/.local/share/opencode/opencode.db` (`session_v2`) | + +The roots are `SPLINTER_FOREIGN_CLAUDE`, `SPLINTER_FOREIGN_HERMES` (a comma +list, one root per store) and `SPLINTER_FOREIGN_OPENCODE` (the database file +itself), or the plugin's own block in the config, which also loads it: + + plugin foreign { + claude = ~/.claude/projects + hermes = ~/.hermes, ~/.hermes-work + opencode = ~/.local/share/opencode/opencode.db + } + +Four tools — `foreign_list`, `foreign_search`, `foreign_read`, `foreign_import` +— and the `/foreign` command: + + /foreign list what is there, per store + /foreign search TEXT full text, with role and session id + /foreign read SOURCE ID one transcript, tool calls in place + /foreign import SOURCE ID adopt it as a splinter session + +`import` writes a real splinter session and says so: the conversation as a +replayable `.jsonl`, and a `.meta` with the source's title, its start time and +**its** working directory, not the one you imported from. So `/open ` +continues it in the chat and `--session-id --resume` in a shell; `-c` +finds it in the directory the conversation actually ran in. The new id carries the origin (`fcl-`, `fhm-`, +`foc-`), and the sidecar keeps `foreign=:` — a key the core does not +own, so it is carried through every later reopen. + +Three limits worth knowing. The stores are read with `sqlite3 -readonly`, so +splinter never writes into them — an import copies, it does not move. Reasoning +blocks are dropped on the way in: a provider does not accept another model's +thinking as evidence. And the tool calls arrive with their results in place, +which is what makes the imported session worth resuming instead of retyping. + ## MCP `plugins/mcp/mcp.so` speaks MCP to a server and registers its tools. The config diff --git a/docs/CONFIG.md b/docs/CONFIG.md index 1cd99c7..f80ddaa 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -221,6 +221,16 @@ starts a turn that writes a short recap; the recap is injected every seventh turn. The goal itself is stored in the session's `.meta`, so `/continue` and a resumed session find it. It belongs to the conversation in front of you. +## The `.meta` sidecar is shared + +`/.meta` is one `key=value` per line. The core owns `cwd`, +`created`, `opened`, `title`, `goal` and `goal_state` and rewrites the file on +every open, rename and `/goal`. Any other key is kept verbatim, so a plugin can +mark a session in the same file — `plugins/foreign` records `foreign=hermes:h-1` +there to say where an imported conversation came from, and the marker survives +the reopen that `-c` or `/open` causes. Unknown keys are carried through +unchanged, up to eight of them; a `key=value` longer than 159 bytes is cut. + ## Precedence Command line, then the file, then the built-in default. An unknown key is an @@ -245,6 +255,12 @@ lies about what it does. | `max_bytes` | conversation budget in bytes, `0` = no limit | | `compact_threshold` | context tokens past which the next request is compacted (`0` = off) | | `compact_target` | the size compaction aims for, in tokens; `/compact [tokens]` forces it now | +| `embed` | the session's search index: `local` (default, built-in CPU encoder, no model and no key), `openai` (posts to `embed_endpoint`), `off` | +| `embed_dims` | vector size, 8..4096, default 256; only meaningful for `local`, and `openai` must match what the model returns | +| `embed_model` | model name for `embed = openai`, e.g. `nomic-embed-text` | +| `embed_endpoint` | base URL for `embed = openai`, e.g. `http://127.0.0.1:11434/v1` | +| `embed_key_env` | env var holding the key for `embed_endpoint` | +| `embed_timeout` | seconds one embedding request may take | | `session_dir` | where session logs go (default `~/.splinter`); `SPLINTER_SESSION_DIR` overrides it, which is how `make check` keeps its test sessions out of yours | | `system_prompt` | sent once at the start of a conversation | | `telegram_allow` | user ids the gateway answers, comma-separated; empty means nobody | @@ -500,6 +516,44 @@ or pass the prompt via a flag your CLI supports. With both `endpoint` and `transport` set, `transport` wins — it is the more specific instruction. +## Searching the session: `embed` + +Compaction drops messages from the conversation to fit the window. They stay in +the session file, and the model gets a `history_search` tool to find them again +by meaning. The digest that replaces them names the tool — but only when it is +really registered, since a prompt pointing at a missing tool teaches the model +to call nothing. + +``` +core { + embed = local # default + embed_dims = 256 +} +``` + +`embed = local` is the built-in encoder: no model, no key, no network. It hashes +words, four-character prefixes and bigrams into a signed vector on the CPU. It +is weaker than a real embedding model (measured: paraphrase 0.92, unrelated +0.01) and it is enough to tell "the deploy machine" from "the frontend build". + +`embed = openai` sends the text to `/embeddings` with +`embed_model`; `embed_dims` must match what the model returns. `embed = off` +keeps the tool out entirely. + +Two things it does **not** do: it never runs inside the turn, and it never +delays an answer. The indexer is its own thread; a 937 KB session costs the turn +28 ms. The index lives in `/emb/.emb`, next to the +session log, and grows with it — a resumed session becomes searchable in the +background without anything having been compacted. + +`/status` shows what the indexer is doing (`status.embed`). + +The tool says what it found, or why it found nothing: `the index is still +filling; ask again in a moment` while the thread catches up on a session that +just grew, `the index is empty: nothing in this session has been indexed yet` +when there is nothing to search, and `the query has no searchable words` when +the question was all stopwords. All three are answers, not errors. + ## Adding a provider from the chat `/connect` — in the Telegram gateway and in the TUI (one answer per line) — diff --git a/docs/splinter.1 b/docs/splinter.1 index 4571cff..2fb8845 100644 --- a/docs/splinter.1 +++ b/docs/splinter.1 @@ -191,6 +191,25 @@ with no network at all. .It Pa ~/.splinter/.jsonl Append-only session log, one JSON object per line. A crash can only truncate the tail. +.It Pa ~/.splinter/emb/.emb +The session's search index, one record per line. +It is written by a background thread, so it lags the session log by a moment +and is rebuilt by reading the log again if it is missing. +.It Pa ~/.splinter/.meta +The session's sidecar, one +.Sq key=value +per line: cwd, created, opened, title, goal, goal_state. +A key the core does not own is carried through unchanged, so a plugin can mark +a session in the same file +.Pq Pa plugins/foreign No writes Sy foreign Ns = Ns Ar source : Ns Ar id . +.It Pa ~/.splinter/splinter.conf +The configuration. +.Fl -init-config +writes it as +.Pa splinter.conf.example +when one is already there, so it never overwrites a file in use. +See +.Pa docs/CONFIG.md . .El .Sh EXIT STATUS .Bl -tag -width Ds -compact diff --git a/plugins/foreign/foreign.c b/plugins/foreign/foreign.c new file mode 100644 index 0000000..7f2cad4 --- /dev/null +++ b/plugins/foreign/foreign.c @@ -0,0 +1,3162 @@ +/* + * splinter -- foreign sessions: Claude Code, Hermes and opencode, read natively. + * + * Copyright (c) 2026 Konrad Lother + * SPDX-License-Identifier: BSD-3-Clause + * + * Three harnesses keep their conversations on this machine, each in its own + * shape: + * + * claude ~/.claude/projects//.jsonl + * one JSON object per line, type user|assistant, content an array + * of text / thinking / tool_use / tool_result blocks, and one + * assistant message split over several lines (one per block, same + * message id, chained by parentUuid). + * hermes /state.db, and /profiles//state.db + * SQLite: sessions(id,title,cwd,started_at) and + * messages(session_id,role,content,tool_call_id,tool_calls, + * tool_name,...), in OpenAI's shape. + * opencode ~/.local/share/opencode/opencode.db + * SQLite: session_v2 for the list and session_message + * (type user|assistant|system|compaction, data JSON) for the + * transcript; older databases keep message + part instead, older + * roots only the table 'session'. + * + * None of them is a splinter session, and asking a model to "remember" + * another harness's conversation is not the same as having it: resume, /open, + * compaction and the session tools work on splinter's own append-only JSONL. + * + * So this plugin does two things and nothing else: + * + * read list, search and print the foreign sessions (four tools and + * /foreign). Read-only, SP_AUTH_READ. + * import write one of them into the session directory as a splinter + * session - the same records splinter writes itself, every tool call + * paired with its observation - so --session-id --resume, + * -c and the name in the sidecar + * continue that conversation natively afterwards. + * + * The import keeps the foreign session's working directory and start time in + * the .meta sidecar, so the imported session appears under the folder it + * happened in and `-c` finds it there. That is the one place the plugin writes + * a file splinter defines (session.c's key=value sidecar); it merges the keys + * it owns into whatever is already there and keeps the rest. + * + * SQLite is read through the sqlite3(1) CLI in read-only mode, exec'd directly + * (never through a shell, so a session id cannot become an argument): the + * harness has no SQLite dependency and this plugin does not add one. A missing + * sqlite3 says so instead of pretending the store is empty. + * + * Configuration, all optional; the standard paths are the default: + * + * plugin foreign { + * claude = ~/.claude/projects + * hermes = ~/.hermes, ~/.hermes-personal + * opencode = ~/.local/share/opencode/opencode.db + * max_bytes = 33554432 # per transcript, then truncated + * limit = 25 # rows and hits per answer + * } + * + * SPLINTER_FOREIGN_CLAUDE / _HERMES / _OPENCODE override the paths for one run + * (the test uses them; so does a disk mounted somewhere else). + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "splinter.h" +#include "splinter_plugin.h" +#include "mcp.h" + +/* anthropic.c and openai.c declare this locally; libsplinter exports it */ +int sp_json_emit(struct sp_buf *, const mcp_json *); + +#define FR_PATHS 8 /* hermes roots */ +#define FR_PATH 700 +#define FR_TITLE 110 +#define FR_MAX_MSG 4000 /* records per imported transcript */ +#define FR_MAX_BYTES (32u * 1024 * 1024) +#define FR_MAX_LINE (16u * 1024 * 1024) +#define FR_ROW_BYTES 262144 /* one SQL row, so 500 of them stay bounded */ +#define FR_SQL_BYTES (48u * 1024 * 1024) +#define FR_SQL_ROWS 400 +#define FR_SQL_TIMEOUT 30 /* seconds per sqlite3 call */ +#define FR_HEAD_BYTES (192u * 1024) /* how much of a claude file a title reads */ + +enum fr_src { SRC_CLAUDE = 0, SRC_HERMES, SRC_OPENCODE, SRC_NONE }; + +static const char *const src_name[] = { "claude", "hermes", "opencode" }; +static const char *const src_tag[] = { "fcl-", "fhm-", "foc-" }; + +/* ------------------------------------------------------------------ config */ + +static struct { + struct sp_host *host; + char claude[FR_PATH]; + char hermes[FR_PATHS][FR_PATH]; + size_t nhermes; + char opencode[FR_PATH]; + size_t max_bytes; + int limit; + int ready; +} fr = { NULL, "", { { "" } }, 0, "", FR_MAX_BYTES, 25, 0 }; + +/* ~ at the front of a configured path; a trailing slash is dropped */ +static int +path_expand(const char *in, char *out, size_t cap) +{ + const char *home = getenv("HOME"); + size_t n; + + if (in == NULL || out == NULL || cap == 0) + return -1; + if (in[0] == '~' && (in[1] == '/' || in[1] == '\0')) { + if (home == NULL) + return -1; + if ((size_t)snprintf(out, cap, "%s%s", home, in + 1) >= cap) + return -1; + } else if ((size_t)snprintf(out, cap, "%s", in) >= cap) { + return -1; + } + while ((n = strlen(out)) > 1 && out[n - 1] == '/') + out[n - 1] = '\0'; + return 0; +} + +/* a + "/" + b (+ c): -1 instead of a silently cut path */ +static int +path_join(char *out, size_t cap, const char *a, const char *b, const char *c) +{ + size_t n = 0; + const char *parts[3]; + size_t i; + + parts[0] = a; + parts[1] = b; + parts[2] = c; + for (i = 0; i < 3; i++) { + const char *p = parts[i]; + + if (p == NULL || *p == '\0') + continue; + if (n > 0 && out[n - 1] != '/') { + if (n + 1 >= cap) + return -1; + out[n++] = '/'; + } + while (*p != '\0') { + if (n + 1 >= cap) + return -1; + out[n++] = *p++; + } + } + if (cap == 0) + return -1; + out[n] = '\0'; + return 0; +} + +static void +hermes_add(const char *path) +{ + char buf[FR_PATH]; + size_t i; + + if (path == NULL || *path == '\0' || fr.nhermes == FR_PATHS) + return; + if (path_expand(path, buf, sizeof(buf)) != 0) + return; + for (i = 0; i < fr.nhermes; i++) + if (strcmp(fr.hermes[i], buf) == 0) + return; + snprintf(fr.hermes[fr.nhermes++], FR_PATH, "%s", buf); +} + +/* a configured value that is a list "a, b" or a single path */ +static void +hermes_list(const char *val) +{ + char *copy, *p, *save = NULL; + + if (val == NULL) + return; + copy = strdup(val); + if (copy == NULL) + return; + for (p = strtok_r(copy, ",", &save); p != NULL; + p = strtok_r(NULL, ",", &save)) { + while (*p == ' ' || *p == '\t') + p++; + hermes_add(p); + } + free(copy); +} + +static const char * +conf(const char *key) +{ + return fr.host != NULL ? sp_host_plugin_config(fr.host, "foreign", key) : + NULL; +} + +static void +resolve_paths(void) +{ + const char *v; + char home[FR_PATH]; + + if (fr.ready) + return; + fr.ready = 1; + snprintf(home, sizeof(home), "%s", + getenv("HOME") != NULL ? getenv("HOME") : ""); + + v = conf("claude"); + if (v == NULL) + v = getenv("SPLINTER_FOREIGN_CLAUDE"); + if (v != NULL && *v != '\0') { + (void)path_expand(v, fr.claude, sizeof(fr.claude)); + } else if (home[0] != '\0') { + (void)path_join(fr.claude, sizeof(fr.claude), home, + ".claude", "projects"); + } + + v = conf("hermes"); + if (v != NULL) { + hermes_list(v); + } else if ((v = getenv("SPLINTER_FOREIGN_HERMES")) != NULL) { + hermes_list(v); + } else if (home[0] != '\0') { + DIR *d; + struct dirent *e; + + hermes_add("~/.hermes"); + /* profiles and stubs sit next to it as ~/.hermes-NAME */ + d = opendir(home); + while (d != NULL && (e = readdir(d)) != NULL) { + char cand[FR_PATH]; + + if (strncmp(e->d_name, ".hermes-", 8) != 0) + continue; + if (path_join(cand, sizeof(cand), home, e->d_name, + NULL) == 0) + hermes_add(cand); + } + if (d != NULL) + closedir(d); + } + + v = conf("opencode"); + if (v == NULL) + v = getenv("SPLINTER_FOREIGN_OPENCODE"); + if (v != NULL && *v != '\0') { + (void)path_expand(v, fr.opencode, sizeof(fr.opencode)); + } else { + const char *xdg = getenv("XDG_DATA_HOME"); + + if (xdg != NULL && *xdg != '\0') + (void)path_join(fr.opencode, sizeof(fr.opencode), xdg, + "opencode", "opencode.db"); + else if (home[0] != '\0') + (void)path_join(fr.opencode, sizeof(fr.opencode), home, + ".local/share/opencode", "opencode.db"); + } + + if (conf("max_bytes") != NULL) { + unsigned long mb = strtoul(conf("max_bytes"), NULL, 10); + + if (mb >= 65536) + fr.max_bytes = (size_t)mb; + } + if (conf("limit") != NULL) + fr.limit = atoi(conf("limit")); + if (fr.limit < 1 || fr.limit > 200) + fr.limit = 25; +} + +static enum fr_src +src_of(const char *s) +{ + if (s == NULL) + return SRC_NONE; + if (strcmp(s, "claude") == 0 || strcmp(s, "claude-code") == 0) + return SRC_CLAUDE; + if (strcmp(s, "hermes") == 0) + return SRC_HERMES; + if (strcmp(s, "opencode") == 0 || strcmp(s, "opencode-go") == 0 || + strcmp(s, "oc") == 0) + return SRC_OPENCODE; + return SRC_NONE; +} + +/* ------------------------------------------------------------------- child */ + +/* + * Run a program with an argument vector and capture stdout. No shell: a + * session id from a tool call must not be able to become an argument, let + * alone a command. The child only does dup2/execv/_exit, which is safe after + * fork() in a process that has threads. + */ +static int +run_argv(char *const argv[], struct sp_buf *out, char *err, size_t errcap, + int timeout_s, size_t cap_bytes) +{ + int op[2], ep[2], status = 0, rc = -1, dead = 0, over = 0; + pid_t child; + time_t deadline; + + if (err != NULL && errcap > 0) + err[0] = '\0'; + if (pipe(op) != 0) + return -1; + if (pipe(ep) != 0) { + close(op[0]); + close(op[1]); + return -1; + } + child = fork(); + if (child < 0) { + close(op[0]); + close(op[1]); + close(ep[0]); + close(ep[1]); + return -1; + } + if (child == 0) { + (void)setpgid(0, 0); + close(op[0]); + close(ep[0]); + if (dup2(op[1], STDOUT_FILENO) < 0 || + dup2(ep[1], STDERR_FILENO) < 0) + _exit(127); + close(op[1]); + close(ep[1]); + execv(argv[0], argv); + _exit(127); + } + (void)setpgid(child, child); + close(op[1]); + close(ep[1]); + deadline = time(NULL) + (timeout_s > 0 ? timeout_s : FR_SQL_TIMEOUT); + while (!dead && !over) { + struct pollfd pfd[2]; + int pr; + + if (time(NULL) > deadline) { + (void)kill(-child, SIGKILL); + if (err != NULL) + snprintf(err, errcap, "timed out after %d s", + timeout_s > 0 ? timeout_s : FR_SQL_TIMEOUT); + over = 1; + break; + } + pfd[0].fd = op[0]; + pfd[0].events = POLLIN; + pfd[0].revents = 0; + pfd[1].fd = ep[0]; + pfd[1].events = POLLIN; + pfd[1].revents = 0; + pr = poll(pfd, 2, 200); + if (pr < 0) { + if (errno == EINTR) + continue; + break; + } + if (pr == 0) + continue; + if ((pfd[0].revents & (POLLIN | POLLHUP)) != 0) { + char chunk[8192]; + ssize_t got = read(op[0], chunk, sizeof(chunk)); + + if (got < 0 && errno != EINTR) + break; + if (got == 0) { + close(op[0]); + op[0] = -1; + } else if (out != NULL && out->len + (size_t)got <= + cap_bytes) { + if (sp_buf_add(out, chunk, (size_t)got) != 0) + break; + } else { + (void)kill(-child, SIGKILL); + if (err != NULL) + snprintf(err, errcap, "output larger than " + "%zu bytes", cap_bytes); + over = 1; + break; + } + } + if ((pfd[1].revents & (POLLIN | POLLHUP)) != 0) { + char chunk[2048]; + ssize_t got = read(ep[0], chunk, sizeof(chunk)); + + if (got > 0 && err != NULL && errcap > 0) { + size_t have = strlen(err); + + if (have + (size_t)got < errcap - 1) + memcpy(err + have, chunk, (size_t)got); + } else if (got == 0) { + close(ep[0]); + ep[0] = -1; + } + } + if (op[0] < 0 && ep[0] < 0) + dead = 1; + } + if (op[0] >= 0) + close(op[0]); + if (ep[0] >= 0) + close(ep[0]); + while (waitpid(child, &status, 0) < 0 && errno == EINTR) + ; + if (!over && WIFEXITED(status) && WEXITSTATUS(status) == 0) + rc = 0; + else if (!over && err != NULL && err[0] == '\0') + snprintf(err, errcap, "exit status %d", + WIFEXITED(status) ? WEXITSTATUS(status) : -1); + return rc; +} + +/* where the sqlite3 CLI is, resolved before fork so the child only execs */ +static const char * +sqlite3_bin(void) +{ + static const char *cand[] = { + "/usr/bin/sqlite3", "/usr/local/bin/sqlite3", "/bin/sqlite3", + "/opt/homebrew/bin/sqlite3", NULL + }; + const char *env = getenv("SPLINTER_SQLITE3"); + size_t i; + + if (env != NULL && *env != '\0' && access(env, X_OK) == 0) + return env; + for (i = 0; cand[i] != NULL; i++) + if (access(cand[i], X_OK) == 0) + return cand[i]; + return NULL; +} + +/* + * One read-only query, answered as a JSON array. -batch keeps the CLI from + * drawing a prompt or a table and -json makes it parseable with the same + * parser the rest of the harness uses; the .timeout waits out a writer + * instead of failing on a busy WAL. + */ +static mcp_json * +sql_json(const char *db, const char *sql, char *err, size_t errcap) +{ + struct sp_buf out; + char *argv[9]; + const char *bin = sqlite3_bin(); + mcp_json *v = NULL; + int rc_ok = 0; + + if (bin == NULL) { + if (err != NULL) + snprintf(err, errcap, "sqlite3 not found (set " + "SPLINTER_SQLITE3)"); + return NULL; + } + if (sp_buf_init(&out) != 0) + return NULL; + argv[0] = (char *)bin; + argv[1] = (char *)"-readonly"; + argv[2] = (char *)"-batch"; + argv[3] = (char *)"-json"; + argv[4] = (char *)"-cmd"; + argv[5] = (char *)".timeout 3000"; + argv[6] = (char *)db; + argv[7] = (char *)sql; + argv[8] = NULL; + if (run_argv(argv, &out, err, errcap, FR_SQL_TIMEOUT, FR_SQL_BYTES) != 0) { + sp_buf_free(&out); + return NULL; + } + rc_ok = 1; + if (out.p != NULL && out.len > 0) { + v = mcp_parse(out.p); + if (v == NULL && err != NULL) + snprintf(err, errcap, "unparsable sqlite output: %.100s", + out.p); + } else if (rc_ok) { + /* + * sqlite3 -json prints nothing when the query matched no row. + * That is an empty answer, not a failure: returning NULL made + * every caller take its "query failed" branch, so a session + * whose rows had already been read once (or a count that was + * zero) looked like a broken database. + */ + v = mcp_parse("[]"); + } + sp_buf_free(&out); + return v; +} + +/* a string literal for SQL; the caller passes text, never SQL */ +static const char * +sql_lit(struct sp_buf *b, const char *s) +{ + const char *p; + + sp_buf_clear(b); + if (sp_buf_puts(b, "'") != 0) + return "''"; + for (p = s; *p != '\0'; p++) { + if (*p == '\'') { + if (sp_buf_puts(b, "''") != 0) + return "''"; + } else if (sp_buf_add(b, p, 1) != 0) { + return "''"; + } + } + if (sp_buf_puts(b, "'") != 0) + return "''"; + return b->p != NULL ? b->p : "''"; +} + +/* ------------------------------------------------------------- transcript */ + +struct frec { + char *role; + char *text; + char *name; + char *call_id; + char *calls; /* raw JSON array, OpenAI shape */ +}; + +struct fconv { + struct frec *v; + size_t n; + size_t cap; + size_t bytes; + int truncated; +}; + +static void +frec_free(struct frec *r) +{ + free(r->role); + free(r->text); + free(r->name); + free(r->call_id); + free(r->calls); + memset(r, 0, sizeof(*r)); +} + +static void +fconv_free(struct fconv *c) +{ + size_t i; + + if (c == NULL) + return; + for (i = 0; i < c->n; i++) + frec_free(&c->v[i]); + free(c->v); + memset(c, 0, sizeof(*c)); +} + +static size_t +str_cap(size_t n, size_t max) +{ + return n > max ? max : n; +} + +static struct frec * +fconv_add(struct fconv *c, const char *role, const char *text, const char *name, + const char *call_id, const char *calls) +{ + struct frec *r; + size_t n = str_cap(text != NULL ? strlen(text) : 0, + 4u * 1024 * 1024); + + if (c->n >= FR_MAX_MSG || c->bytes >= fr.max_bytes) { + c->truncated = 1; + return NULL; + } + if (c->n == c->cap) { + size_t ncap = c->cap == 0 ? 16 : c->cap * 2; + struct frec *nv = realloc(c->v, ncap * sizeof(*nv)); + + if (nv == NULL) + return NULL; + c->v = nv; + c->cap = ncap; + } + r = &c->v[c->n]; + memset(r, 0, sizeof(*r)); + r->role = strdup(role != NULL ? role : "user"); + r->text = calloc(1, n + 1); + if (r->text != NULL && text != NULL) + memcpy(r->text, text, n); + if (r->role == NULL || r->text == NULL || + (name != NULL && (r->name = strdup(name)) == NULL) || + (call_id != NULL && (r->call_id = strdup(call_id)) == NULL) || + (calls != NULL && (r->calls = strdup(calls)) == NULL)) { + frec_free(r); + return NULL; + } + c->n++; + c->bytes += n + 24; + return r; +} + +/* Every tool call needs its observation and every observation its call: a + * provider rejects a transcript where one side is missing (OpenAI: tool_calls + * must be followed by tool messages; Anthropic: a tool_result without a + * tool_use). Foreign transcripts are usually paired, a truncated import or a + * compacted log is not - so the pairing is enforced here, once, instead of + * leaving a session that fails on its first resumed request. */ +static int +has_str(char **v, size_t n, const char *s) +{ + size_t i; + + for (i = 0; i < n; i++) + if (strcmp(v[i], s) == 0) + return 1; + return 0; +} + +static void +calls_keep(struct frec *r, char **answered, size_t nans, char ***kept, + size_t *nkept) +{ + mcp_json *arr = mcp_parse(r->calls); + struct sp_buf b; + size_t k; + int any = 0; + + free(r->calls); + r->calls = NULL; + if (arr == NULL || arr->t != MCP_ARR) { + mcp_json_free(arr); + return; + } + if (sp_buf_init(&b) != 0) { + mcp_json_free(arr); + return; + } + for (k = 0; k < mcp_array_len(arr); k++) { + const mcp_json *one = mcp_array_at(arr, k); + const char *id = mcp_arg_string(one, "id"); + struct sp_buf one_buf; + + if (id == NULL || !has_str(answered, nans, id)) + continue; + if (sp_buf_init(&one_buf) != 0) + break; + if (sp_json_emit(&one_buf, one) == 0 && one_buf.p != NULL) { + if ((any && sp_buf_puts(&b, ",") != 0) || + sp_buf_puts(&b, one_buf.p) != 0) { + sp_buf_free(&one_buf); + break; + } + any = 1; + if (!has_str(*kept, *nkept, id)) { + char **nv = realloc(*kept, (*nkept + 1) * + sizeof(**kept)); + + if (nv != NULL) { + *kept = nv; + (*kept)[*nkept] = strdup(id); + if ((*kept)[*nkept] != NULL) + (*nkept)++; + } + } + } + sp_buf_free(&one_buf); + } + mcp_json_free(arr); + if (any && b.len > 0 && + sp_buf_printf(&(struct sp_buf){ 0 }, "") == 0) { + struct sp_buf full; + + if (sp_buf_init(&full) == 0) { + if (sp_buf_puts(&full, "[") == 0 && + sp_buf_puts(&full, b.p) == 0 && + sp_buf_puts(&full, "]") == 0) + r->calls = strdup(full.p); + sp_buf_free(&full); + } + } + sp_buf_free(&b); +} + +static void +fconv_pair(struct fconv *c) +{ + char **answered = NULL, **kept = NULL; + size_t nans = 0, nkept = 0, i, out = 0; + + answered = calloc(c->n + 1, sizeof(*answered)); + if (answered == NULL) + return; + /* an observation that says nothing still answers its call */ + for (i = 0; i < c->n; i++) { + struct frec *r = &c->v[i]; + + if (strcmp(r->role, "tool") != 0) + continue; + if (r->text[0] == '\0') { + free(r->text); + r->text = strdup("(no output)"); + if (r->text == NULL) + r->text = strdup(""); + } + if (r->call_id != NULL) { + answered[nans] = strdup(r->call_id); + if (answered[nans] != NULL) + nans++; + } + } + for (i = 0; i < c->n; i++) + if (strcmp(c->v[i].role, "assistant") == 0 && + c->v[i].calls != NULL && c->v[i].calls[0] != '\0') + calls_keep(&c->v[i], answered, nans, &kept, &nkept); + /* drop observations whose call did not survive, and empty records */ + for (i = 0; i < c->n; i++) { + struct frec *r = &c->v[i]; + int keep = 1; + + if (strcmp(r->role, "tool") == 0 && + (r->call_id == NULL || !has_str(kept, nkept, r->call_id))) + keep = 0; + if ((r->text == NULL || r->text[0] == '\0') && + (r->calls == NULL || r->calls[0] == '\0')) + keep = 0; + if (!keep) { + frec_free(r); + continue; + } + c->v[out++] = *r; + } + c->n = out; + for (i = 0; i < nans; i++) + free(answered[i]); + free(answered); + for (i = 0; i < nkept; i++) + free(kept[i]); + free(kept); +} + +/* one line, no control bytes, at most cap-1 bytes of UTF-8 */ +static void +one_line(const char *text, char *out, size_t cap) +{ + const char *p = text != NULL ? text : ""; + size_t n = 0; + + if (cap == 0) + return; + while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') + p++; + while (*p != '\0' && *p != '\n' && *p != '\r' && n + 1 < cap) { + unsigned char ch = (unsigned char)*p; + + out[n++] = (ch < 0x20 || ch == 0x7f) ? ' ' : (char)ch; + p++; + } + while (n > 0 && out[n - 1] == ' ') + n--; + /* + * A cut in the middle of a UTF-8 sequence leaves a lead byte without + * enough continuation bytes; drop the whole character. + */ + while (n > 0) { + size_t start = n, need; + unsigned char ch; + + while (start > 0 && ((unsigned char)out[start - 1] & 0xC0) == 0x80) + start--; + if (start == 0) + break; + ch = (unsigned char)out[start - 1]; + need = (ch & 0x80) == 0 ? 1 : (ch & 0xE0) == 0xC0 ? 2 : + (ch & 0xF0) == 0xE0 ? 3 : (ch & 0xF8) == 0xF0 ? 4 : 0; + if (need == 0 || n - (start - 1) < need) + n = start - 1; + else + break; + } + out[n] = '\0'; +} + +/* case-blind substring, and where it is */ +static int +has_ci(const char *hay, const char *needle) +{ + size_t i, n = strlen(needle); + const char *p; + + if (n == 0) + return 1; + for (p = hay; *p != '\0'; p++) { + for (i = 0; i < n && p[i] != '\0'; i++) + if (tolower((unsigned char)p[i]) != + tolower((unsigned char)needle[i])) + break; + if (i == n) + return 1; + } + return 0; +} + +static long +find_ci(const char *hay, const char *needle) +{ + size_t i, n = strlen(needle); + const char *p; + + for (p = hay; *p != '\0'; p++) { + for (i = 0; i < n && p[i] != '\0'; i++) + if (tolower((unsigned char)p[i]) != + tolower((unsigned char)needle[i])) + break; + if (i == n) + return (long)(p - hay); + } + return -1; +} + +static void +snippet(struct sp_buf *b, const char *text, const char *query, size_t cap) +{ + long at = find_ci(text, query); + size_t len = strlen(text), from = 0, n, i; + + if (at > 60) + from = (size_t)at - 60; + n = len - from; + if (n > cap) + n = cap; + if (from > 0) + sp_buf_puts(b, "..."); + for (i = 0; i < n; i++) { + char ch = text[from + i]; + + if ((unsigned char)ch < 0x20 || (unsigned char)ch == 0x7f) + ch = ' '; + (void)sp_buf_add(b, &ch, 1); + } + if (from + n < len) + sp_buf_puts(b, "..."); +} + +static void +stamp_of(long secs, char *buf, size_t cap) +{ + struct tm tm; + + if (secs <= 0 || localtime_r(&(time_t){ secs }, &tm) == NULL) { + snprintf(buf, cap, "?"); + return; + } + strftime(buf, cap, "%Y-%m-%d %H:%M", &tm); +} + +/* a content value as text: a string, or the text blocks of an array */ +static void +content_text(const mcp_json *content, struct sp_buf *out) +{ + size_t i; + + if (content == NULL) + return; + if (content->t == MCP_STR) { + const char *p = mcp_json_string(content); + + if (p != NULL) + (void)sp_buf_puts(out, p); + return; + } + if (content->t != MCP_ARR) + return; + for (i = 0; i < mcp_array_len(content); i++) { + const mcp_json *blk = mcp_array_at(content, i); + const char *type = mcp_arg_string(blk, "type"); + const char *text; + + if (type == NULL) + continue; + text = mcp_arg_string(blk, "text"); + if (text != NULL && strcmp(type, "text") == 0) { + if (out->len > 0) + (void)sp_buf_puts(out, "\n"); + (void)sp_buf_puts(out, text); + } else if (strcmp(type, "image") == 0) { + if (out->len > 0) + (void)sp_buf_puts(out, "\n"); + (void)sp_buf_puts(out, "[image omitted]"); + } + } +} + +/* the arguments of a call, as the JSON text OpenAI's shape wants */ +static void +args_text(const mcp_json *input, struct sp_buf *out) +{ + sp_buf_clear(out); + if (input == NULL || input->t == MCP_NULL) { + (void)sp_buf_puts(out, "{}"); + return; + } + if (sp_json_emit(out, input) != 0 || out->len == 0) { + sp_buf_clear(out); + (void)sp_buf_puts(out, "{}"); + } +} + +static void +calls_append(struct sp_buf *b, const char *id, const char *name, + const char *args) +{ + int first = b->len == 0; + + if (sp_buf_printf(b, "%s{\"id\":\"", first ? "" : ",") != 0 || + sp_json_escape(b, id != NULL ? id : "call") != 0 || + sp_buf_puts(b, "\",\"type\":\"function\",\"function\":{\"name\":\"") != + 0 || + sp_json_escape(b, name != NULL ? name : "tool") != 0 || + sp_buf_puts(b, "\",\"arguments\":\"") != 0 || + sp_json_escape(b, args != NULL ? args : "{}") != 0) + return; + (void)sp_buf_puts(b, "\"}}"); +} + +/* ------------------------------------------------------------------- ids */ + +static int +valid_id(const char *id) +{ + size_t i, n; + + if (id == NULL || *id == '\0') + return 0; + n = strlen(id); + if (n >= 64) + return 0; + for (i = 0; i < n; i++) + if (!((id[i] >= 'a' && id[i] <= 'z') || + (id[i] >= 'A' && id[i] <= 'Z') || + (id[i] >= '0' && id[i] <= '9') || + id[i] == '-' || id[i] == '_' || id[i] == '.')) + return 0; + return strstr(id, "..") == NULL; +} + +/* a foreign id, made into one splinter's session file names accept */ +static void +import_id(enum fr_src s, const char *foreign, char *out, size_t cap) +{ + size_t i, n; + + snprintf(out, cap, "%s", src_tag[s]); + n = strlen(out); + for (i = 0; foreign[i] != '\0' && n + 1 < cap && n < 60; i++) { + unsigned char ch = (unsigned char)foreign[i]; + + if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || + (ch >= '0' && ch <= '9') || ch == '-' || ch == '_' || + ch == '.') + out[n++] = (char)ch; + else + out[n++] = '-'; + } + out[n] = '\0'; + while (n > 0 && out[n - 1] == '.') + out[--n] = '\0'; + { + char *dot; + + while (n > 0 && (dot = strstr(out, "..")) != NULL) + dot[1] = '-'; + } +} + +/* ------------------------------------------------------------------ claude */ + +/* //.jsonl across every project directory */ +static int +claude_find(const char *id, char *out, size_t cap) +{ + DIR *d; + struct dirent *e; + int found = -1; + + d = opendir(fr.claude); + if (d == NULL) + return -1; + while ((e = readdir(d)) != NULL) { + char path[FR_PATH]; + + if (e->d_name[0] == '.') + continue; + if (path_join(path, sizeof(path), fr.claude, e->d_name, id) + != 0) + continue; + { + size_t pl = strlen(path); + + if (pl + 7 >= sizeof(path)) + continue; + memcpy(path + pl, ".jsonl", 7); + } + if (access(path, R_OK) == 0) { + snprintf(out, cap, "%s", path); + found = 0; + break; + } + } + closedir(d); + return found; +} + +struct fbrief { + char id[96]; + char title[FR_TITLE]; + char cwd[512]; + long mtime; + size_t bytes; +}; + +static int +brief_cmp(const void *a, const void *b) +{ + const struct fbrief *x = a, *y = b; + + if (x->mtime != y->mtime) + return x->mtime < y->mtime ? 1 : -1; + return strcmp(x->id, y->id); +} + +/* + * A claude file's title and directory without reading all of it: cwd rides on + * every line, the title is an ai-title line, and the first real user text is + * the fallback splinter itself uses for an untitled session. + */ +static void +claude_head(const char *path, struct fbrief *b) +{ + char *line = NULL; + size_t linecap = 0, read = 0; + FILE *f = fopen(path, "r"); + + b->title[0] = '\0'; + b->cwd[0] = '\0'; + if (f == NULL) + return; + while (read < FR_HEAD_BYTES && getline(&line, &linecap, f) > 0) { + mcp_json *o; + + read += strlen(line); + if (line[0] != '{') + continue; + o = mcp_parse(line); + if (o == NULL) + continue; + if (b->cwd[0] == '\0') { + const char *cwd = mcp_arg_string(o, "cwd"); + + if (cwd != NULL) + snprintf(b->cwd, sizeof(b->cwd), "%s", cwd); + } + if (b->title[0] == '\0' && + strstr(line, "\"type\":\"ai-title\"") != NULL) { + const char *t = mcp_arg_string(o, "aiTitle"); + + if (t != NULL) + one_line(t, b->title, sizeof(b->title)); + } + if (b->title[0] == '\0' && + strstr(line, "\"type\":\"user\"") != NULL && + strstr(line, "\"tool_result\"") == NULL && + strstr(line, "\"isSidechain\":true") == NULL) { + const mcp_json *m = mcp_arg(o, "message"); + struct sp_buf text; + + if (sp_buf_init(&text) == 0) { + content_text(m != NULL ? mcp_arg(m, "content") : + NULL, &text); + if (text.len > 0) + one_line(text.p, b->title, + sizeof(b->title)); + sp_buf_free(&text); + } + } + mcp_json_free(o); + if (b->title[0] != '\0' && b->cwd[0] != '\0') + break; + } + free(line); + fclose(f); + /* a checkpoint prefix is not a title */ + while (b->title[0] == '<') + memmove(b->title, b->title + 1, strlen(b->title)); + if (b->title[0] == '\0') + snprintf(b->title, sizeof(b->title), "(untitled)"); +} + +/* the project directory Claude Code uses for a working directory: the path + * with every separator as '-', under / */ +static int +claude_slug_dir(const char *cwd, char *out, size_t cap) +{ + char full[FR_PATH]; + size_t i, n = 0; + + /* '~'-free absolute path or nothing; the check used to be inverted, so + * every real directory looked unusable and the slug lookup never ran */ + if (cwd == NULL || cwd[0] == '\0') + return -1; + { + size_t need = strlen(cwd) + strlen(fr.claude) + 2; + + if (need > sizeof(full)) + return -1; + } + n = (size_t)snprintf(full, sizeof(full), "%s/", fr.claude); + for (i = 0; cwd[i] != '\0' && n + 1 < sizeof(full); i++) + full[n++] = cwd[i] == '/' ? '-' : cwd[i]; + full[n] = '\0'; + if (access(full, R_OK) != 0) + return -1; + snprintf(out, cap, "%s", full); + return 0; +} + +/* one claude project directory's sessions */ +static void +claude_dir(const char *proj, const char *only_cwd, struct fbrief *v, size_t max, + size_t *n) +{ + DIR *pd = opendir(proj); + struct dirent *pe; + + while (pd != NULL && (pe = readdir(pd)) != NULL && *n < max) { + char path[FR_PATH]; + struct stat st; + size_t len; + struct fbrief *b; + + len = strlen(pe->d_name); + if (len < 7 || strcmp(pe->d_name + len - 6, ".jsonl") != 0) + continue; + if (len - 6 >= sizeof(v[0].id)) + continue; + snprintf(path, sizeof(path), "%s/%s", proj, pe->d_name); + if (stat(path, &st) != 0 || !S_ISREG(st.st_mode)) + continue; + b = &v[*n]; + memset(b, 0, sizeof(*b)); + memcpy(b->id, pe->d_name, len - 6); + b->id[len - 6] = '\0'; + b->mtime = (long)st.st_mtime; + b->bytes = (size_t)st.st_size; + claude_head(path, b); + if (only_cwd != NULL && *only_cwd != '\0' && + strcmp(b->cwd, only_cwd) != 0) + continue; + (*n)++; + } + if (pd != NULL) + closedir(pd); +} + +static int +list_claude(const char *only_cwd, struct fbrief *v, size_t max, size_t *n, + char *err, size_t errcap) +{ + char one[FR_PATH] = ""; + DIR *d; + + *n = 0; + /* + * A working directory maps to one project directory by name, so the + * common case reads 2 files instead of 143. A cwd that does not map + * (no such slug) still gets the fallback below: the slug is Claude + * Code's convention, not a promise about this tree. + */ + if (only_cwd != NULL && *only_cwd != '\0' && + claude_slug_dir(only_cwd, one, sizeof(one)) == 0) { + claude_dir(one, only_cwd, v, max, n); + qsort(v, *n, sizeof(*v), brief_cmp); + return 0; + } + d = opendir(fr.claude); + if (d == NULL) { + snprintf(err, errcap, "%s: %s", + fr.claude[0] != '\0' ? fr.claude : "(unset)", + strerror(errno)); + return -1; + } + while (d != NULL) { + struct dirent *e = readdir(d); + char proj[FR_PATH]; + + if (e == NULL) + break; + if (e->d_name[0] == '.') + continue; + if (path_join(proj, sizeof(proj), fr.claude, e->d_name, + NULL) != 0) + continue; + claude_dir(proj, only_cwd, v, max, n); + } + closedir(d); + qsort(v, *n, sizeof(*v), brief_cmp); + return 0; +} + +static int +count_claude(void) +{ + DIR *d = opendir(fr.claude); + int n = 0; + + while (d != NULL) { + struct dirent *e = readdir(d); + char proj[FR_PATH]; + DIR *pd; + struct dirent *pe; + + if (e == NULL) + break; + if (e->d_name[0] == '.') + continue; + 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) { + size_t len = strlen(pe->d_name); + + if (len > 6 && strcmp(pe->d_name + len - 6, ".jsonl") == 0) + n++; + } + closedir(pd); + } + if (d != NULL) + closedir(d); + return n; +} + +/* + * One claude line as a hit: the text blocks of the message it carries, with + * the query as the anchor. The raw line is JSON-escaped, so it is parsed + * instead of sliced. + */ +static void +claude_hit(struct sp_buf *out, const char *id, const char *line, + const char *query, int *hits) +{ + mcp_json *o = mcp_parse(line); + const char *type; + const mcp_json *m, *content; + struct sp_buf text; + + if (o == NULL) + return; + type = mcp_arg_string(o, "type"); + m = mcp_arg(o, "message"); + content = m != NULL ? mcp_arg(m, "content") : NULL; + if (type == NULL || content == NULL) { + mcp_json_free(o); + return; + } + if (sp_buf_init(&text) != 0) { + mcp_json_free(o); + return; + } + content_text(content, &text); + if (text.len > 0 && has_ci(text.p, query)) { + sp_buf_printf(out, " claude %s %s: ", id, type); + snippet(out, text.p, query, 200); + (void)sp_buf_puts(out, "\n"); + (*hits)++; + } else if (has_ci(line, query)) { + /* the hit is in an argument, not in the text: say so */ + sp_buf_printf(out, " claude %s %s: ", id, type); + snippet(out, line, query, 160); + (void)sp_buf_puts(out, "\n"); + (*hits)++; + } + sp_buf_free(&text); + mcp_json_free(o); +} + +static int +search_claude(const char *query, int limit, int days, struct sp_buf *out) +{ + DIR *d = opendir(fr.claude); + int hits = 0; + long now = (long)time(NULL); + + 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; + if (e->d_name[0] == '.') + continue; + 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); + } + closedir(d); + return hits; +} + +static int +load_claude(const char *id, struct fconv *conv, char *err, size_t errcap) +{ + char path[FR_PATH], *line = NULL; + size_t linecap = 0; + FILE *f; + /* the assistant message being assembled: one per message id */ + struct { + char id[80]; + int used; + struct sp_buf text; + struct sp_buf calls; + } p; + struct { + char id[80]; + char name[80]; + } names[256]; + size_t nnames = 0; + + if (claude_find(id, path, sizeof(path)) != 0) { + snprintf(err, errcap, "no claude session '%s'", id); + return -1; + } + f = fopen(path, "r"); + if (f == NULL) { + snprintf(err, errcap, "cannot read the claude session: %s", + strerror(errno)); + return -1; + } + memset(&p, 0, sizeof(p)); + (void)sp_buf_init(&p.text); + (void)sp_buf_init(&p.calls); + while (getline(&line, &linecap, f) > 0) { + mcp_json *o; + const char *type; + const mcp_json *m, *content; + size_t i; + + if (line[0] != '{' || strlen(line) > FR_MAX_LINE) + continue; + o = mcp_parse(line); + if (o == NULL) + continue; + type = mcp_arg_string(o, "type"); + if (type == NULL || (strcmp(type, "user") != 0 && + strcmp(type, "assistant") != 0)) { + mcp_json_free(o); + continue; + } + /* a subagent's sidechain is a different conversation */ + if (mcp_arg_bool(o, "isSidechain", 0)) { + mcp_json_free(o); + continue; + } + m = mcp_arg(o, "message"); + content = m != NULL ? mcp_arg(m, "content") : NULL; + if (content == NULL) { + mcp_json_free(o); + continue; + } + if (strcmp(type, "assistant") == 0) { + const char *mid = mcp_arg_string(m, "id"); + + /* one message can arrive as several lines */ + if (!p.used || (mid != NULL && p.id[0] != '\0' && + strcmp(mid, p.id) != 0)) { + if (p.used) + (void)fconv_add(conv, "assistant", + p.text.p, NULL, NULL, + p.calls.len > 0 ? p.calls.p : NULL); + p.used = 1; + p.id[0] = '\0'; + sp_buf_clear(&p.text); + sp_buf_clear(&p.calls); + snprintf(p.id, sizeof(p.id), "%s", + mid != NULL ? mid : ""); + } + for (i = 0; content->t == MCP_ARR && + i < mcp_array_len(content); i++) { + const mcp_json *blk = mcp_array_at(content, i); + const char *bt = mcp_arg_string(blk, "type"); + const char *t; + + if (bt == NULL) + continue; + t = mcp_arg_string(blk, "text"); + if (strcmp(bt, "text") == 0 && t != NULL) { + if (p.text.len > 0) + (void)sp_buf_puts(&p.text, "\n"); + (void)sp_buf_puts(&p.text, t); + } else if (strcmp(bt, "tool_use") == 0) { + const char *cid = mcp_arg_string(blk, + "id"); + const char *name = mcp_arg_string(blk, + "name"); + struct sp_buf args; + + if (sp_buf_init(&args) != 0) + continue; + args_text(mcp_arg(blk, "input"), &args); + calls_append(&p.calls, cid, name, + args.p); + if (cid != NULL && name != NULL && + nnames < 256) { + snprintf(names[nnames].id, + sizeof(names[0].id), "%s", + cid); + snprintf(names[nnames].name, + sizeof(names[0].name), "%s", + name); + nnames++; + } + sp_buf_free(&args); + } + /* thinking is not a message */ + } + mcp_json_free(o); + continue; + } + /* user: tool results answer the open calls, text is the turn */ + if (p.used) { + (void)fconv_add(conv, "assistant", p.text.p, NULL, NULL, + p.calls.len > 0 ? p.calls.p : NULL); + p.used = 0; + p.id[0] = '\0'; + sp_buf_clear(&p.text); + sp_buf_clear(&p.calls); + } + for (i = 0; content->t == MCP_ARR && + i < mcp_array_len(content); i++) { + const mcp_json *blk = mcp_array_at(content, i); + const char *bt = mcp_arg_string(blk, "type"); + const char *t = mcp_arg_string(blk, "text"); + + if (bt == NULL) + continue; + if (strcmp(bt, "tool_result") == 0) { + const char *cid = mcp_arg_string(blk, + "tool_use_id"); + const char *name = "tool"; + struct sp_buf text; + size_t k; + + if (sp_buf_init(&text) != 0) + continue; + content_text(mcp_arg(blk, "content"), &text); + for (k = 0; k < nnames; k++) + if (cid != NULL && + strcmp(names[k].id, cid) == 0) { + name = names[k].name; + break; + } + (void)fconv_add(conv, "tool", text.p, name, cid, + NULL); + sp_buf_free(&text); + } else if (strcmp(bt, "text") == 0 && t != NULL) { + (void)fconv_add(conv, "user", t, NULL, NULL, + NULL); + } + } + if (content->t == MCP_STR) { + const char *s = mcp_json_string(content); + + if (s != NULL) + (void)fconv_add(conv, "user", s, NULL, NULL, + NULL); + } + mcp_json_free(o); + } + if (p.used) + (void)fconv_add(conv, "assistant", p.text.p, NULL, NULL, + p.calls.len > 0 ? p.calls.p : NULL); + sp_buf_free(&p.text); + sp_buf_free(&p.calls); + free(line); + fclose(f); + if (conv->n == 0) { + snprintf(err, errcap, "claude session '%s' has no messages", id); + return -1; + } + return 0; +} + +/* ------------------------------------------------------------------ hermes */ + +static void +hermes_dbs(char dbs[][FR_PATH], size_t max, size_t *n) +{ + size_t i; + + *n = 0; + for (i = 0; i < fr.nhermes && *n < max; i++) { + char path[FR_PATH], pdir[FR_PATH]; + struct stat st; + DIR *d; + struct dirent *e; + + snprintf(path, sizeof(path), "%s/state.db", fr.hermes[i]); + if (stat(path, &st) == 0 && S_ISREG(st.st_mode)) + snprintf(dbs[(*n)++], FR_PATH, "%s", path); + /* profiles under one root, each with its own state.db */ + snprintf(pdir, sizeof(pdir), "%s/profiles", fr.hermes[i]); + d = opendir(pdir); + while (d != NULL && (e = readdir(d)) != NULL && *n < max) { + if (e->d_name[0] == '.') + continue; + if (path_join(path, sizeof(path), pdir, e->d_name, + "state.db") != 0) + continue; + if (stat(path, &st) == 0 && S_ISREG(st.st_mode)) + snprintf(dbs[(*n)++], FR_PATH, "%s", path); + } + if (d != NULL) + closedir(d); + } +} + +static int +list_hermes(const char *only_cwd, struct fbrief *v, size_t max, size_t *n) +{ + char dbs[32][FR_PATH], why[FR_PATH + 96]; + size_t nd = 0, i; + struct sp_buf lit, sql; + + *n = 0; + hermes_dbs(dbs, 32, &nd); + if (nd == 0) + return -1; + if (sp_buf_init(&lit) != 0 || sp_buf_init(&sql) != 0) { + sp_buf_free(&lit); + sp_buf_free(&sql); + return -1; + } + for (i = 0; i < nd && *n < max; i++) { + mcp_json *rows; + size_t k; + + sp_buf_clear(&sql); + if (only_cwd != NULL && *only_cwd != '\0') { + (void)sp_buf_printf(&sql, "select id, coalesce(title,'') " + "as title, coalesce(cwd,'') as cwd, " + "cast(started_at as integer) as ts from sessions " + "where cwd = %s order by ts desc limit %d;", + sql_lit(&lit, only_cwd), fr.limit); + } else { + (void)sp_buf_printf(&sql, "select id, coalesce(title,'') " + "as title, coalesce(cwd,'') as cwd, " + "cast(started_at as integer) as ts from sessions " + "order by ts desc limit %d;", fr.limit); + } + /* a store that answers nothing is not an error worth stopping */ + rows = sql_json(dbs[i], sql.p, why, sizeof(why)); + if (rows == NULL) + continue; + for (k = 0; k < mcp_array_len(rows) && *n < max; k++) { + const mcp_json *r = mcp_array_at(rows, k); + const char *id = mcp_arg_string(r, "id"); + const char *title = mcp_arg_string(r, "title"); + const char *cwd = mcp_arg_string(r, "cwd"); + struct fbrief *b; + + if (id == NULL || strlen(id) >= sizeof(v[0].id)) + continue; + b = &v[(*n)++]; + memset(b, 0, sizeof(*b)); + snprintf(b->id, sizeof(b->id), "%s", id); + if (title != NULL) + one_line(title, b->title, sizeof(b->title)); + if (b->title[0] == '\0') + snprintf(b->title, sizeof(b->title), + "(untitled)"); + if (cwd != NULL) + snprintf(b->cwd, sizeof(b->cwd), "%s", cwd); + b->mtime = (long)mcp_arg_int(r, "ts", 0); + } + mcp_json_free(rows); + } + sp_buf_free(&lit); + sp_buf_free(&sql); + qsort(v, *n, sizeof(*v), brief_cmp); + return 0; +} + +static int +count_hermes(void) +{ + char dbs[32][FR_PATH], why[FR_PATH + 96]; + size_t nd = 0, i; + int total = 0; + + hermes_dbs(dbs, 32, &nd); + for (i = 0; i < nd; i++) { + mcp_json *rows = sql_json(dbs[i], + "select count(*) as n from sessions;", why, sizeof(why)); + + if (rows == NULL) + continue; + total += mcp_arg_int(mcp_array_at(rows, 0), "n", 0); + mcp_json_free(rows); + } + return total; +} + +static int +hermes_db_for(const char *id, char *db, size_t cap, char *err, size_t errcap) +{ + char dbs[32][FR_PATH], why[FR_PATH + 96]; + size_t nd = 0, i; + struct sp_buf lit, sql; + + hermes_dbs(dbs, 32, &nd); + if (nd == 0) { + snprintf(err, errcap, "no hermes state.db under %zu root%s", + fr.nhermes, fr.nhermes == 1 ? "" : "s"); + return -1; + } + if (sp_buf_init(&lit) != 0 || sp_buf_init(&sql) != 0) { + sp_buf_free(&lit); + sp_buf_free(&sql); + snprintf(err, errcap, "out of memory"); + return -1; + } + for (i = 0; i < nd; i++) { + mcp_json *rows; + int n = 0; + + sp_buf_clear(&sql); + (void)sp_buf_printf(&sql, "select count(*) as n from sessions " + "where id = %s;", sql_lit(&lit, id)); + rows = sql_json(dbs[i], sql.p, why, sizeof(why)); + if (rows != NULL) { + n = mcp_arg_int(mcp_array_at(rows, 0), "n", 0); + mcp_json_free(rows); + } + if (n > 0) { + if ((size_t)snprintf(db, cap, "%s", dbs[i]) >= cap) { + sp_buf_free(&lit); + sp_buf_free(&sql); + snprintf(err, errcap, "state.db path too long"); + return -1; + } + sp_buf_free(&lit); + sp_buf_free(&sql); + return 0; + } + } + sp_buf_free(&lit); + sp_buf_free(&sql); + snprintf(err, errcap, "no hermes session '%s' in %zu state.db file%s", + id, nd, nd == 1 ? "" : "s"); + return -1; +} + +/* the stored tool_calls of a hermes row, in OpenAI's shape, rebuilt */ +static void +hermes_calls(const char *raw, struct sp_buf *out) +{ + mcp_json *root, *arr; + size_t i; + + sp_buf_clear(out); + if (raw == NULL || raw[0] == '\0') + return; + root = mcp_parse(raw); + if (root == NULL) + return; + arr = root; + if (root->t == MCP_OBJ) { + const mcp_json *t = mcp_arg(root, "tool_calls"); + + if (t == NULL || t->t != MCP_ARR) { + mcp_json_free(root); + return; + } + arr = (mcp_json *)t; /* borrowed from root, freed below */ + } + for (i = 0; i < mcp_array_len(arr); i++) { + const mcp_json *c = mcp_array_at(arr, i); + const mcp_json *fn = mcp_arg(c, "function"); + const char *id = mcp_arg_string(c, "id"); + const char *name = fn != NULL ? mcp_arg_string(fn, "name") : + mcp_arg_string(c, "name"); + const char *a = fn != NULL ? + mcp_arg_string(fn, "arguments") : NULL; + struct sp_buf args; + + if (name == NULL) + continue; + if (sp_buf_init(&args) != 0) + break; + if (a != NULL) { + if (sp_buf_puts(&args, a) != 0) { + sp_buf_free(&args); + break; + } + } else { + args_text(mcp_arg(c, "input"), &args); + } + calls_append(out, id, name, args.p); + sp_buf_free(&args); + } + mcp_json_free(root); +} + +/* hermes stores structured content with a NUL-prefixed JSON marker */ +static void +hermes_text(const char *content, struct sp_buf *out) +{ + const char *p = content; + + sp_buf_clear(out); + if (content == NULL) + return; + /* + * The NUL-prefixed 'json:' marker is stripped in SQL (substr(content,7)), + * not here: a content of "" is a one-byte allocation, so any strncmp + * against "\x00json:" reads past its end. + */ + if (p[0] == '{' || p[0] == '[') { + mcp_json *v = mcp_parse(p); + + if (v != NULL) { + content_text(v, out); + if (out->len == 0) { + const char *t = mcp_arg_string(v, "text"); + const char *c = mcp_arg_string(v, "content"); + + if (t != NULL) + (void)sp_buf_puts(out, t); + else if (c != NULL) + (void)sp_buf_puts(out, c); + } + mcp_json_free(v); + if (out->len > 0) + return; + } + } + (void)sp_buf_puts(out, p); +} + +static int +load_hermes(const char *id, struct fconv *conv, char *err, size_t errcap) +{ + char db[FR_PATH], why[FR_PATH + 96]; + struct sp_buf lit, sql; + size_t offset = 0; + + if (hermes_db_for(id, db, sizeof(db), err, errcap) != 0) + return -1; + if (sp_buf_init(&lit) != 0 || sp_buf_init(&sql) != 0) { + sp_buf_free(&lit); + sp_buf_free(&sql); + snprintf(err, errcap, "out of memory"); + return -1; + } + for (;;) { + mcp_json *rows; + size_t i; + + sp_buf_clear(&sql); + (void)sp_buf_printf(&sql, "select role, " + "case when substr(content,1,6) = char(0)||'json:' then " + "substr(content,7) else substr(content,1,%d) end as body, " + "tool_call_id, tool_calls, tool_name from messages where " + "session_id = %s and active = 1 and compacted = 0 and role " + "in ('user','assistant','tool','system') order by timestamp, " + "id limit %d offset %zu;", FR_ROW_BYTES, + sql_lit(&lit, id), FR_SQL_ROWS, offset); + rows = sql_json(db, sql.p, why, sizeof(why)); + if (rows == NULL) { + snprintf(err, errcap, "%s", + why[0] != '\0' ? why : "hermes query failed"); + sp_buf_free(&lit); + sp_buf_free(&sql); + return -1; + } + if (mcp_array_len(rows) == 0) { + mcp_json_free(rows); + break; + } + for (i = 0; i < mcp_array_len(rows); i++) { + const mcp_json *r = mcp_array_at(rows, i); + const char *role = mcp_arg_string(r, "role"); + const char *cid = mcp_arg_string(r, "tool_call_id"); + const char *name = mcp_arg_string(r, "tool_name"); + struct sp_buf text, calls; + int istool; + + if (role == NULL) + continue; + istool = strcmp(role, "tool") == 0; + if (sp_buf_init(&text) != 0 || sp_buf_init(&calls) != 0) { + sp_buf_free(&text); + sp_buf_free(&calls); + break; + } + hermes_text(mcp_arg_string(r, "body"), &text); + if (strcmp(role, "assistant") == 0) + hermes_calls(mcp_arg_string(r, "tool_calls"), + &calls); + (void)fconv_add(conv, role, text.p, istool ? name : NULL, + istool ? cid : NULL, + calls.len > 0 ? calls.p : NULL); + sp_buf_free(&text); + sp_buf_free(&calls); + } + offset += mcp_array_len(rows); + mcp_json_free(rows); + if (conv->truncated) + break; + } + sp_buf_free(&lit); + sp_buf_free(&sql); + if (conv->n == 0) { + snprintf(err, errcap, "hermes session '%s' has no active " + "messages", id); + return -1; + } + return 0; +} + +/* ---------------------------------------------------------------- opencode */ + +static int +list_opencode(const char *only_cwd, struct fbrief *v, size_t max, size_t *n, + char *err, size_t errcap) +{ + struct sp_buf lit, sql; + mcp_json *rows; + char why[FR_PATH + 96] = ""; + size_t i; + + *n = 0; + if (fr.opencode[0] == '\0') { + snprintf(err, errcap, "no opencode database configured " + "(set opencode in the plugin config or " + "SPLINTER_FOREIGN_OPENCODE)"); + return -1; + } + if (access(fr.opencode, R_OK) != 0) { + snprintf(err, errcap, "%s: %s", fr.opencode, + strerror(errno)); + return -1; + } + if (sp_buf_init(&lit) != 0 || sp_buf_init(&sql) != 0) { + sp_buf_free(&lit); + sp_buf_free(&sql); + return -1; + } + /* session_v2 is current; older databases only have 'session' */ + if (only_cwd != NULL && *only_cwd != '\0') { + (void)sp_buf_printf(&sql, "select id, coalesce(title,'') as " + "title, directory, cast(time_updated as integer) as updated " + "from session_v2 where directory = %s order by updated desc " + "limit %d;", sql_lit(&lit, only_cwd), fr.limit); + } else { + (void)sp_buf_printf(&sql, "select id, coalesce(title,'') as " + "title, directory, cast(time_updated as integer) as updated " + "from session_v2 order by updated desc limit %d;", + fr.limit); + } + rows = sql_json(fr.opencode, sql.p, why, sizeof(why)); + if (rows == NULL) { + sp_buf_clear(&sql); + if (only_cwd != NULL && *only_cwd != '\0') { + (void)sp_buf_printf(&sql, "select id, coalesce(title,'') " + "as title, directory, cast(time_updated as integer) " + "as updated from session where directory = %s order " + "by updated desc limit %d;", + sql_lit(&lit, only_cwd), fr.limit); + } else { + (void)sp_buf_printf(&sql, "select id, coalesce(title,'') " + "as title, directory, cast(time_updated as integer) " + "as updated from session order by updated desc " + "limit %d;", fr.limit); + } + rows = sql_json(fr.opencode, sql.p, why, sizeof(why)); + } + sp_buf_free(&lit); + sp_buf_free(&sql); + if (rows == NULL) { + snprintf(err, errcap, "%s", why[0] != '\0' ? why : + "query failed"); + return -1; + } + for (i = 0; i < mcp_array_len(rows) && *n < max; i++) { + const mcp_json *r = mcp_array_at(rows, i); + const char *id = mcp_arg_string(r, "id"); + const char *title = mcp_arg_string(r, "title"); + const char *directory = mcp_arg_string(r, "directory"); + struct fbrief *b; + + if (id == NULL || strlen(id) >= sizeof(v[0].id)) + continue; + b = &v[(*n)++]; + memset(b, 0, sizeof(*b)); + snprintf(b->id, sizeof(b->id), "%s", id); + if (title != NULL) + one_line(title, b->title, sizeof(b->title)); + if (b->title[0] == '\0') + snprintf(b->title, sizeof(b->title), "(untitled)"); + if (directory != NULL) + snprintf(b->cwd, sizeof(b->cwd), "%s", directory); + /* milliseconds since the epoch, like every opencode time */ + b->mtime = (long)(mcp_arg_num(r, "updated", 0) / 1000.0); + } + mcp_json_free(rows); + return 0; +} + +static int +count_opencode(void) +{ + char why[FR_PATH + 96]; + mcp_json *rows; + int n = 0; + + if (fr.opencode[0] == '\0' || access(fr.opencode, R_OK) != 0) + return 0; + rows = sql_json(fr.opencode, "select count(*) as n from session_v2;", + why, sizeof(why)); + if (rows == NULL) + rows = sql_json(fr.opencode, "select count(*) as n from session;", + why, sizeof(why)); + if (rows == NULL) + return 0; + n = mcp_arg_int(mcp_array_at(rows, 0), "n", 0); + mcp_json_free(rows); + return n; +} + +static void +oc_tool_output(const mcp_json *tool, struct sp_buf *out) +{ + const mcp_json *state = mcp_arg(tool, "state"); + const mcp_json *content = state != NULL ? mcp_arg(state, "content") : + NULL; + const mcp_json *meta = state != NULL ? mcp_arg(state, "metadata") : NULL; + const char *status = state != NULL ? mcp_arg_string(state, "status") : + NULL; + + sp_buf_clear(out); + content_text(content, out); + if (out->len == 0 && meta != NULL) { + const char *o = mcp_arg_string(meta, "output"); + const char *e = mcp_arg_string(meta, "error"); + + if (o != NULL) + (void)sp_buf_puts(out, o); + else if (e != NULL) + (void)sp_buf_puts(out, e); + } + if (out->len == 0 && status != NULL) + (void)sp_buf_printf(out, "[%s]", status); +} + +/* one assistant record: its text, then its calls, then their observations */ +static void +oc_assistant(struct fconv *conv, const mcp_json *data) +{ + const mcp_json *content = mcp_arg(data, "content"); + struct sp_buf text, calls, args, out; + size_t i; + + if (sp_buf_init(&text) != 0 || sp_buf_init(&calls) != 0 || + sp_buf_init(&args) != 0 || sp_buf_init(&out) != 0) { + sp_buf_free(&text); + sp_buf_free(&calls); + sp_buf_free(&args); + sp_buf_free(&out); + return; + } + for (i = 0; i < mcp_array_len(content); i++) { + const mcp_json *blk = mcp_array_at(content, i); + const char *bt = mcp_arg_string(blk, "type"); + const char *t; + + if (bt == NULL || strcmp(bt, "text") != 0) + continue; /* reasoning is not a message */ + t = mcp_arg_string(blk, "text"); + if (t == NULL || t[0] == '\0') + continue; + if (text.len > 0) + (void)sp_buf_puts(&text, "\n"); + (void)sp_buf_puts(&text, t); + } + for (i = 0; i < mcp_array_len(content); i++) { + const mcp_json *blk = mcp_array_at(content, i); + const char *bt = mcp_arg_string(blk, "type"); + const mcp_json *state; + + if (bt == NULL || strcmp(bt, "tool") != 0) + continue; + state = mcp_arg(blk, "state"); + args_text(state != NULL ? mcp_arg(state, "input") : NULL, &args); + calls_append(&calls, mcp_arg_string(blk, "id"), + mcp_arg_string(blk, "name"), args.p); + } + /* + * The call record goes before its observations, because a provider + * pairs them in that order; the text of the same turn rides on it. + */ + if (text.len > 0 || calls.len > 0) + (void)fconv_add(conv, "assistant", text.p, NULL, NULL, + calls.len > 0 ? calls.p : NULL); + for (i = 0; i < mcp_array_len(content); i++) { + const mcp_json *blk = mcp_array_at(content, i); + const char *bt = mcp_arg_string(blk, "type"); + + if (bt == NULL || strcmp(bt, "tool") != 0) + continue; + oc_tool_output(blk, &out); + (void)fconv_add(conv, "tool", out.p, mcp_arg_string(blk, "name"), + mcp_arg_string(blk, "id"), NULL); + } + sp_buf_free(&text); + sp_buf_free(&calls); + sp_buf_free(&args); + sp_buf_free(&out); +} + +static int +oc_load_v2(const char *id, struct fconv *conv, char *why, size_t whycap) +{ + struct sp_buf lit, sql; + size_t offset = 0; + + for (;;) { + mcp_json *rows; + size_t i; + + if (sp_buf_init(&lit) != 0 || sp_buf_init(&sql) != 0) { + sp_buf_free(&lit); + sp_buf_free(&sql); + return -1; + } + (void)sp_buf_printf(&sql, "select type, substr(data,1,%d) as data " + "from session_message where session_id = %s and type in " + "('user','assistant','system','compaction') order by seq " + "limit %d offset %zu;", FR_ROW_BYTES, sql_lit(&lit, id), + FR_SQL_ROWS, offset); + rows = sql_json(fr.opencode, sql.p, why, whycap); + sp_buf_free(&lit); + sp_buf_free(&sql); + if (rows == NULL) + return -1; + if (mcp_array_len(rows) == 0) { + mcp_json_free(rows); + return 0; + } + for (i = 0; i < mcp_array_len(rows); i++) { + const mcp_json *r = mcp_array_at(rows, i); + const char *type = mcp_arg_string(r, "type"); + const char *raw = mcp_arg_string(r, "data"); + mcp_json *data; + + if (type == NULL || raw == NULL) + continue; + data = mcp_parse(raw); + if (data == NULL) + continue; + if (strcmp(type, "user") == 0) { + struct sp_buf t; + + if (sp_buf_init(&t) == 0) { + content_text(mcp_arg(data, "text"), &t); + if (t.len > 0) + (void)fconv_add(conv, "user", t.p, + NULL, NULL, NULL); + sp_buf_free(&t); + } + } else if (strcmp(type, "assistant") == 0) { + oc_assistant(conv, data); + } else if (strcmp(type, "compaction") == 0) { + const char *sum = mcp_arg_string(data, "summary"); + + if (sum != NULL && sum[0] != '\0') + (void)fconv_add(conv, "system", sum, + NULL, NULL, NULL); + } else if (strcmp(type, "system") == 0) { + const char *t = mcp_arg_string(data, "text"); + + if (t != NULL && t[0] != '\0') + (void)fconv_add(conv, "system", t, NULL, + NULL, NULL); + } + mcp_json_free(data); + } + offset += mcp_array_len(rows); + mcp_json_free(rows); + if (conv->truncated) + return 0; + } +} + +/* the pre-session_message layout: message rows plus part rows */ +static int +oc_load_legacy(const char *id, struct fconv *conv, char *why, size_t whycap) +{ + struct sp_buf lit, sql; + size_t offset = 0; + + for (;;) { + mcp_json *rows; + size_t i; + + if (sp_buf_init(&lit) != 0 || sp_buf_init(&sql) != 0) { + sp_buf_free(&lit); + sp_buf_free(&sql); + return -1; + } + (void)sp_buf_printf(&sql, "select m.data as mdata, " + "substr(p.data,1,%d) as pdata from message m join part p on " + "p.message_id = m.id where m.session_id = %s order by " + "m.time_created, p.id limit %d offset %zu;", FR_ROW_BYTES, + sql_lit(&lit, id), FR_SQL_ROWS, offset); + rows = sql_json(fr.opencode, sql.p, why, whycap); + sp_buf_free(&lit); + sp_buf_free(&sql); + if (rows == NULL) + return -1; + if (mcp_array_len(rows) == 0) { + mcp_json_free(rows); + return 0; + } + for (i = 0; i < mcp_array_len(rows); i++) { + const mcp_json *r = mcp_array_at(rows, i); + mcp_json *md = mcp_parse(mcp_arg_string(r, "mdata")); + mcp_json *pd = mcp_parse(mcp_arg_string(r, "pdata")); + const char *role = md != NULL ? + mcp_arg_string(md, "role") : NULL; + const char *ptype = pd != NULL ? + mcp_arg_string(pd, "type") : NULL; + + if (role == NULL || ptype == NULL) { + mcp_json_free(md); + mcp_json_free(pd); + continue; + } + if (strcmp(role, "user") == 0 && strcmp(ptype, "text") == + 0) { + const char *t = mcp_arg_string(pd, "text"); + + if (t != NULL && t[0] != '\0') + (void)fconv_add(conv, "user", t, NULL, + NULL, NULL); + } else if (strcmp(role, "assistant") == 0 && + strcmp(ptype, "text") == 0) { + const char *t = mcp_arg_string(pd, "text"); + + if (t != NULL && t[0] != '\0') + (void)fconv_add(conv, "assistant", t, + NULL, NULL, NULL); + } else if (strcmp(role, "assistant") == 0 && + strcmp(ptype, "tool") == 0) { + const char *name = mcp_arg_string(pd, "tool"); + const char *cid = mcp_arg_string(pd, "callID"); + const mcp_json *state = mcp_arg(pd, "state"); + struct sp_buf args, calls, out; + + if (sp_buf_init(&args) != 0 || + sp_buf_init(&calls) != 0) { + sp_buf_free(&args); + sp_buf_free(&calls); + mcp_json_free(md); + mcp_json_free(pd); + continue; + } + if (sp_buf_init(&out) != 0) { + sp_buf_free(&args); + sp_buf_free(&calls); + mcp_json_free(md); + mcp_json_free(pd); + continue; + } + args_text(state != NULL ? + mcp_arg(state, "input") : NULL, &args); + calls_append(&calls, cid, name, args.p); + (void)fconv_add(conv, "assistant", "", NULL, + NULL, calls.p); + oc_tool_output(pd, &out); + (void)fconv_add(conv, "tool", out.p, name, cid, + NULL); + sp_buf_free(&args); + sp_buf_free(&calls); + sp_buf_free(&out); + } + mcp_json_free(md); + mcp_json_free(pd); + } + offset += mcp_array_len(rows); + mcp_json_free(rows); + if (conv->truncated) + return 0; + } +} + +static int +load_opencode(const char *id, struct fconv *conv, char *err, size_t errcap) +{ + char why[FR_PATH + 96] = ""; + + if (fr.opencode[0] == '\0') { + snprintf(err, errcap, "no opencode database configured"); + return -1; + } + if (access(fr.opencode, R_OK) != 0) { + snprintf(err, errcap, "cannot read %s: %s", fr.opencode, + strerror(errno)); + return -1; + } + if (oc_load_v2(id, conv, why, sizeof(why)) != 0) { + fconv_free(conv); + if (oc_load_legacy(id, conv, why, sizeof(why)) != 0) { + snprintf(err, errcap, "%s", + why[0] != '\0' ? why : "opencode query failed"); + return -1; + } + } + if (conv->n == 0) { + snprintf(err, errcap, "opencode session '%s' has no messages", + id); + return -1; + } + return 0; +} + +/* ---------------------------------------------------------------- sources */ + +static int +load_any(enum fr_src s, const char *id, struct fconv *conv, char *err, + size_t errcap) +{ + memset(conv, 0, sizeof(*conv)); + resolve_paths(); + if (!valid_id(id)) { + snprintf(err, errcap, "not a session id: '%s'", + id != NULL ? id : ""); + return -1; + } + switch (s) { + case SRC_CLAUDE: + return load_claude(id, conv, err, errcap); + case SRC_HERMES: + return load_hermes(id, conv, err, errcap); + case SRC_OPENCODE: + return load_opencode(id, conv, err, errcap); + default: + snprintf(err, errcap, "unknown source"); + return -1; + } +} + +static int +list_any(enum fr_src s, const char *cwd, struct fbrief *v, size_t max, + size_t *n, char *err, size_t errcap) +{ + resolve_paths(); + *n = 0; + switch (s) { + case SRC_CLAUDE: + return list_claude(cwd, v, max, n, err, errcap) == 0 ? 0 : -1; + case SRC_HERMES: + if (list_hermes(cwd, v, max, n) != 0) { + snprintf(err, errcap, "no hermes state.db under %zu " + "root%s", fr.nhermes, fr.nhermes == 1 ? "" : "s"); + return -1; + } + return 0; + case SRC_OPENCODE: + return list_opencode(cwd, v, max, n, err, errcap) == 0 ? 0 : -1; + default: + snprintf(err, errcap, "unknown source"); + return -1; + } +} + +/* ------------------------------------------------------------------ render */ + +static void +render_conv(struct fconv *c, struct sp_buf *out, size_t limit) +{ + size_t i; + + for (i = 0; i < c->n && out->len < limit; i++) { + struct frec *r = &c->v[i]; + + if (strcmp(r->role, "assistant") == 0) + (void)sp_buf_puts(out, "\n[assistant]\n"); + else if (strcmp(r->role, "tool") == 0) + (void)sp_buf_printf(out, "\n[tool %s]\n", + r->name != NULL ? r->name : ""); + else + (void)sp_buf_printf(out, "\n[%s]\n", r->role); + if (r->text != NULL && r->text[0] != '\0') + (void)sp_buf_puts(out, r->text); + (void)sp_buf_puts(out, "\n"); + } + if (i < c->n) + (void)sp_buf_puts(out, "... (transcript truncated; import it or " + "read with a larger bytes value)\n"); +} + +/* ------------------------------------------------------------------ import */ + +/* + * /.meta, merged: the keys this plugin owns are replaced, the rest + * survives. session.c drops unknown keys on its next write, so a later /rename + * simply forgets the foreign tag - the id prefix still says where the session + * came from. + */ +static int +meta_merge(const char *dir, const char *id, const char *cwd, long created, + const char *title, const char *foreign) +{ + char path[FR_PATH], tmp[FR_PATH + 8], *line = NULL; + size_t cap = 0, n = 0; + FILE *f, *o; + char **keep = NULL; + size_t nkeep = 0; + int rc = -1; + + /* dir/id.meta, not dir/id/.meta: path_join puts a slash between parts */ + if ((size_t)snprintf(path, sizeof(path), "%s/%s.meta", dir, id) >= + sizeof(path)) + return -1; + if ((size_t)snprintf(tmp, sizeof(tmp), "%s.tmp", path) >= sizeof(tmp)) + return -1; + keep = calloc(256, sizeof(*keep)); + if (keep == NULL) + return -1; + f = fopen(path, "r"); + while (f != NULL && nkeep < 256 && getline(&line, &cap, f) > 0) { + if (strncmp(line, "cwd=", 4) == 0 || + strncmp(line, "created=", 8) == 0 || + strncmp(line, "opened=", 7) == 0 || + strncmp(line, "title=", 6) == 0 || + strncmp(line, "foreign=", 8) == 0) + continue; + keep[nkeep++] = strdup(line); + } + if (f != NULL) + fclose(f); + free(line); + o = fopen(tmp, "w"); + if (o == NULL) + goto out; + fprintf(o, "cwd=%s\ncreated=%ld\nopened=%ld\n", cwd, created, + (long)time(NULL)); + if (title != NULL && title[0] != '\0') + fprintf(o, "title=%s\n", title); + if (foreign != NULL && foreign[0] != '\0') + fprintf(o, "foreign=%s\n", foreign); + while (n < nkeep) { + fputs(keep[n], o); + free(keep[n]); + n++; + } + if (fclose(o) != 0) { + (void)unlink(tmp); + goto out; + } + rc = rename(tmp, path) == 0 ? 0 : -1; + if (rc != 0) + (void)unlink(tmp); +out: + while (n < nkeep) + free(keep[n++]); + free(keep); + return rc; +} + +/* the source's own title, directory and start time, for the import */ +static void +import_meta_fields(enum fr_src s, const char *foreign_id, char *title, + size_t tcap, char *cwd, size_t ccap, long *created) +{ + char err[FR_PATH + 96]; + size_t i, n = 0, max = 200; + struct fbrief *v = calloc(max, sizeof(*v)); + + if (v == NULL) + return; + if (list_any(s, NULL, v, max, &n, err, sizeof(err)) == 0) + for (i = 0; i < n; i++) + if (strcmp(v[i].id, foreign_id) == 0) { + if (v[i].title[0] != '\0' && + strcmp(v[i].title, "(untitled)") != 0) + snprintf(title, tcap, "%s", v[i].title); + if (v[i].cwd[0] != '\0') + snprintf(cwd, ccap, "%s", v[i].cwd); + if (v[i].mtime > 0) + *created = v[i].mtime; + break; + } + free(v); +} + +static int +import_any(struct sp_host *h, enum fr_src s, const char *foreign_id, + struct sp_buf *out) +{ + struct fconv c; + char err[FR_PATH + 96], newid[80], dir[FR_PATH], path[FR_PATH]; + char tag[96], title[FR_TITLE], cwd[512] = ""; + struct sp_session_info si; + struct sp_buf serr; + size_t i; + long created = 0; + const char *d; + + resolve_paths(); + if (!valid_id(foreign_id)) + return sp_buf_puts(out, "error: 'id' is not a session id"); + fr.host = h; + if (load_any(s, foreign_id, &c, err, sizeof(err)) != 0) + return sp_buf_printf(out, "error: %s", err); + fconv_pair(&c); + if (c.n == 0) { + fconv_free(&c); + return sp_buf_printf(out, "error: '%s' has nothing to import " + "(every record was empty or had no counterpart)", foreign_id); + } + import_id(s, foreign_id, newid, sizeof(newid)); + d = h != NULL ? sp_host_session_dir(h) : NULL; + if (d == NULL || *d == '\0') { + fconv_free(&c); + 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) { + fconv_free(&c); + return sp_buf_puts(out, "error: session path too long"); + } + if (access(path, F_OK) == 0 && unlink(path) != 0) { + fconv_free(&c); + return sp_buf_printf(out, "error: cannot replace %s: %s", path, + strerror(errno)); + } + if (sp_buf_init(&serr) != 0) { + fconv_free(&c); + return sp_buf_puts(out, "error: out of memory"); + } + if (sp_session_open(&si, dir, newid, &serr) != 0) { + sp_buf_printf(out, "error: %s", serr.p != NULL ? serr.p : "?"); + sp_buf_free(&serr); + fconv_free(&c); + return -1; + } + for (i = 0; i < c.n; i++) { + struct sp_sess_rec rec; + + memset(&rec, 0, sizeof(rec)); + rec.role = c.v[i].role; + rec.text = c.v[i].text; + rec.name = c.v[i].name; + rec.call_id = c.v[i].call_id; + rec.calls = c.v[i].calls; + sp_buf_clear(&serr); + if (sp_session_append_rec(&si, &rec, &serr) != 0) { + sp_buf_printf(out, "error: writing %s: %s", path, + serr.p != NULL ? serr.p : "?"); + sp_buf_free(&serr); + fconv_free(&c); + return -1; + } + } + sp_buf_free(&serr); + /* + * The source's own title is the better one; the first user message is + * only the fallback when the store has none. Asking the list first + * also fills cwd and created, which is what makes an imported session + * show up under the directory it ran in instead of this one. + */ + title[0] = '\0'; + import_meta_fields(s, foreign_id, title, sizeof(title), cwd, + sizeof(cwd), &created); + if (title[0] == '\0') + for (i = 0; i < c.n; i++) + if (strcmp(c.v[i].role, "user") == 0 && + c.v[i].text != NULL && c.v[i].text[0] != '\0') { + one_line(c.v[i].text, title, sizeof(title)); + break; + } + if (title[0] == '\0') + snprintf(title, sizeof(title), "imported %s session", + src_name[s]); + if (cwd[0] == '\0' && getcwd(cwd, sizeof(cwd)) == NULL) + snprintf(cwd, sizeof(cwd), "?"); + if (created == 0) + created = (long)time(NULL); + snprintf(tag, sizeof(tag), "%s:%s", src_name[s], foreign_id); + (void)meta_merge(dir, newid, cwd, created, title, tag); + sp_buf_printf(out, "imported %s session %s as %s (%zu messages%s)\n", + src_name[s], foreign_id, newid, c.n, + c.truncated ? ", truncated at the message or byte cap" : ""); + /* + * Two ways, because they belong to two places: /open is the TUI's + * command, --session-id is what a shell has (a one-shot run has no + * /commands beyond the plugins, so /open there answers "unknown + * command" and looks like a broken import). + */ + sp_buf_printf(out, "continue it with: /open %s (in the chat) or " + "splinter --session-id %s --resume\n", newid, newid); + sp_buf_printf(out, "it is listed under %s\n", cwd); + fconv_free(&c); + return 0; +} + +/* ------------------------------------------------------------------- tools */ + +static int +tool_list(const char *args, struct sp_buf *out, void *ctx) +{ + char err[FR_PATH + 96], cwd[512]; + char srcbuf[32] = "", onlybuf[512] = ""; + const char *src = NULL, *only = NULL; + struct fbrief *v; + size_t max = 200, n = 0, i, k, shown = 0; + int limit = fr.limit, all_cwd = 0; + enum fr_src want = SRC_NONE; + mcp_json *a; + + (void)ctx; + resolve_paths(); + /* + * The argument strings live inside the parsed JSON and are gone once + * it is freed. Copy them out first: reading them afterwards handed + * the caller freed memory (a cwd filter that matched nothing, and a + * garbage string in the "no sessions" line). + */ + if (args != NULL && args[0] == '{' && (a = mcp_parse(args)) != NULL) { + const char *s = mcp_arg_string(a, "source"); + const char *o = mcp_arg_string(a, "cwd"); + + if (s != NULL) + snprintf(srcbuf, sizeof(srcbuf), "%s", s); + if (o != NULL) + snprintf(onlybuf, sizeof(onlybuf), "%s", o); + limit = mcp_arg_int(a, "limit", fr.limit); + mcp_json_free(a); + src = srcbuf[0] != '\0' ? srcbuf : NULL; + only = onlybuf[0] != '\0' ? onlybuf : NULL; + } + if (src != NULL && src_of(src) == SRC_NONE) + return sp_buf_puts(out, "error: 'source' must be claude, hermes or " + "opencode"); + want = src_of(src); + if (limit < 1 || limit > 100) + limit = fr.limit; + /* + * cwd="*" means every directory. It has to be remembered as a + * decision: setting 'only' to NULL and then falling back to getcwd() + * below made the wildcard filter by the current directory like an + * omitted argument, so "list everything" listed nothing here. + */ + if (only != NULL && strcmp(only, "*") == 0) { + only = NULL; + all_cwd = 1; + } + if (only == NULL && !all_cwd && getcwd(cwd, sizeof(cwd)) != NULL) + only = cwd; + v = calloc(max, sizeof(*v)); + if (v == NULL) + return sp_buf_puts(out, "error: out of memory"); + for (i = 0; i < 3 && shown < (size_t)limit; i++) { + if (want != SRC_NONE && want != (enum fr_src)i) + continue; + if (list_any((enum fr_src)i, only, v, max, &n, err, + sizeof(err)) != 0) { + sp_buf_printf(out, "%s: %s\n", src_name[i], err); + continue; + } + for (k = 0; k < n && shown < (size_t)limit; k++) { + char stamp[32]; + + stamp_of(v[k].mtime, stamp, sizeof(stamp)); + sp_buf_printf(out, "%s %-8s %-42s %s %s\n", stamp, + src_name[i], v[k].id, v[k].title, + v[k].cwd[0] != '\0' ? v[k].cwd : ""); + shown++; + } + } + free(v); + if (shown == 0) + sp_buf_printf(out, "no foreign sessions%s%s%s\n", + only != NULL ? " in " : "", only != NULL ? only : "", + want != SRC_NONE ? " for that source" : ""); + else if (shown >= (size_t)limit) + (void)sp_buf_puts(out, "... (limit reached; cwd=\"*\" or a " + "higher limit lists more)\n"); + return 0; +} + +static int +tool_read(const char *args, struct sp_buf *out, void *ctx) +{ + struct fconv c; + char err[FR_PATH + 96]; + char srcbuf[32] = "", idbuf[256] = ""; + const char *src = NULL, *id = NULL; + enum fr_src s; + int limit = 40000; + mcp_json *a; + + (void)ctx; + if (args != NULL && args[0] == '{' && (a = mcp_parse(args)) != NULL) { + const char *sv = mcp_arg_string(a, "source"); + const char *iv = mcp_arg_string(a, "id"); + + if (sv != NULL) + snprintf(srcbuf, sizeof(srcbuf), "%s", sv); + if (iv != NULL) + snprintf(idbuf, sizeof(idbuf), "%s", iv); + limit = mcp_arg_int(a, "bytes", 40000); + mcp_json_free(a); + src = srcbuf[0] != '\0' ? srcbuf : NULL; + id = idbuf[0] != '\0' ? idbuf : NULL; + } + s = src_of(src); + if (s == SRC_NONE) + return sp_buf_puts(out, "error: 'source' must be claude, hermes " + "or opencode"); + if (id == NULL || *id == '\0') + return sp_buf_puts(out, "error: 'id' is required"); + if (limit < 1000) + limit = 1000; + if (limit > 400000) + limit = 400000; + if (load_any(s, id, &c, err, sizeof(err)) != 0) + return sp_buf_printf(out, "error: %s", err); + sp_buf_printf(out, "%s %s: %zu messages%s\n", src_name[s], id, c.n, + c.truncated ? " (truncated)" : ""); + render_conv(&c, out, (size_t)limit); + fconv_free(&c); + return 0; +} + +static int +tool_import(const char *args, struct sp_buf *out, void *ctx) +{ + char srcbuf[32] = "", idbuf[256] = ""; + const char *src = NULL, *id = NULL; + enum fr_src s; + mcp_json *a; + int rc; + + if (args != NULL && args[0] == '{' && (a = mcp_parse(args)) != NULL) { + const char *sv = mcp_arg_string(a, "source"); + const char *iv = mcp_arg_string(a, "id"); + + if (sv != NULL) + snprintf(srcbuf, sizeof(srcbuf), "%s", sv); + if (iv != NULL) + snprintf(idbuf, sizeof(idbuf), "%s", iv); + mcp_json_free(a); + src = srcbuf[0] != '\0' ? srcbuf : NULL; + id = idbuf[0] != '\0' ? idbuf : NULL; + } + s = src_of(src); + if (s == SRC_NONE) + return sp_buf_puts(out, "error: 'source' must be claude, hermes " + "or opencode"); + if (id == NULL || *id == '\0') + return sp_buf_puts(out, "error: 'id' is required"); + rc = import_any(ctx, s, id, out); + if (rc == 0) + (void)sp_host_note(ctx, "foreign session imported"); + return rc; +} + +static int +search_hermes(const char *query, int limit, int days, struct sp_buf *out, + int *hits) +{ + char dbs[32][FR_PATH], why[FR_PATH + 96]; + size_t nd = 0, i; + struct sp_buf lit, 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) { + sp_buf_free(&lit); + sp_buf_free(&sql); + return *hits; + } + for (i = 0; i < nd && *hits < limit; i++) { + mcp_json *rows; + size_t k; + + 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 " + "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); + 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 " + "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); + } + rows = sql_json(dbs[i], sql.p, why, sizeof(why)); + if (rows == NULL) + continue; + for (k = 0; k < mcp_array_len(rows) && *hits < limit; k++) { + const mcp_json *r = mcp_array_at(rows, k); + const char *sid = mcp_arg_string(r, "sid"); + const char *role = mcp_arg_string(r, "role"); + const char *txt = mcp_arg_string(r, "body"); + + if (txt == NULL || !has_ci(txt, query)) + continue; + sp_buf_printf(out, " hermes %s %s: ", + sid != NULL ? sid : "?", role != NULL ? role : "?"); + snippet(out, txt, query, 200); + (void)sp_buf_puts(out, "\n"); + (*hits)++; + } + mcp_json_free(rows); + } + sp_buf_free(&lit); + sp_buf_free(&sql); + return *hits; +} + +static int +search_opencode(const char *query, int limit, int days, struct sp_buf *out, + int *hits) +{ + 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; + + if (fr.opencode[0] == '\0' || access(fr.opencode, R_OK) != 0) + return *hits; + if (sp_buf_init(&lit) != 0 || sp_buf_init(&sql) != 0) { + sp_buf_free(&lit); + sp_buf_free(&sql); + return *hits; + } + sp_buf_clear(&sql); + if (since > 0) { + 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); + } 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); + } + sp_buf_free(&lit); + rows = sql_json(fr.opencode, sql.p, why, sizeof(why)); + sp_buf_free(&sql); + if (rows == NULL) + return *hits; + 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 *sid = mcp_arg_string(r, "sid"); + const char *type = mcp_arg_string(r, "type"); + struct sp_buf t; + mcp_json *data; + + if (raw == NULL) + continue; + data = mcp_parse(raw); + if (data == NULL) + continue; + if (sp_buf_init(&t) != 0) { + mcp_json_free(data); + break; + } + content_text(mcp_arg(data, "text"), &t); + if (t.len > 0 && has_ci(t.p, query)) { + sp_buf_printf(out, " opencode %s %s: ", + sid != NULL ? sid : "?", type != NULL ? type : "?"); + snippet(out, t.p, query, 200); + (void)sp_buf_puts(out, "\n"); + (*hits)++; + } + sp_buf_free(&t); + mcp_json_free(data); + } + mcp_json_free(rows); + return *hits; +} + +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; + int limit = 10, days = 0, hits = 0; + enum fr_src s = SRC_NONE; + mcp_json *a; + + (void)ctx; + resolve_paths(); + if (args != NULL && args[0] == '{' && (a = mcp_parse(args)) != NULL) { + const char *q = mcp_arg_string(a, "query"); + const char *sv = mcp_arg_string(a, "source"); + const char *o = mcp_arg_string(a, "cwd"); + + if (q != NULL) + snprintf(qbuf, sizeof(qbuf), "%s", q); + if (sv != NULL) + snprintf(srcbuf, sizeof(srcbuf), "%s", sv); + if (o != NULL) + snprintf(onlybuf, sizeof(onlybuf), "%s", o); + limit = mcp_arg_int(a, "limit", 10); + days = mcp_arg_int(a, "days", 0); + mcp_json_free(a); + query = qbuf[0] != '\0' ? qbuf : NULL; + src = srcbuf[0] != '\0' ? srcbuf : NULL; + only = onlybuf[0] != '\0' ? onlybuf : NULL; + } + if (query == NULL || *query == '\0') + return sp_buf_puts(out, "error: 'query' is required"); + if (strlen(query) > 200) + return sp_buf_puts(out, "error: 'query' is too long"); + if (src != NULL) { + s = src_of(src); + if (s == SRC_NONE) + return sp_buf_puts(out, "error: 'source' must be claude, " + "hermes or opencode"); + } + 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 */ + if (s == SRC_NONE || s == SRC_CLAUDE) + (void)search_claude(query, limit, days, out); + if ((s == SRC_NONE || s == SRC_HERMES) && hits < limit) + hits = search_hermes(query, limit, days, out, &hits); + if ((s == SRC_NONE || s == SRC_OPENCODE) && hits < limit) + hits = search_opencode(query, limit, days, out, &hits); + 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], + query); + else if (hits >= limit) + (void)sp_buf_puts(out, "... (limit reached; narrow the query or " + "raise limit)\n"); + return 0; +} + +/* ---------------------------------------------------------------- command */ + +static void +args_split(const char *args, char *sub, size_t scap, char *a1, size_t a1cap, + char *a2, size_t a2cap) +{ + const char *p = args != NULL ? args : ""; + size_t n; + + sub[0] = a1[0] = a2[0] = '\0'; + while (*p == ' ' || *p == '\t') + p++; + for (n = 0; *p != '\0' && *p != ' ' && n + 1 < scap; n++) + sub[n] = *p++; + sub[n] = '\0'; + while (*p == ' ' || *p == '\t') + p++; + for (n = 0; *p != '\0' && *p != ' ' && n + 1 < a1cap; n++) + a1[n] = *p++; + a1[n] = '\0'; + while (*p == ' ' || *p == '\t') + p++; + for (n = 0; *p != '\0' && n + 1 < a2cap; n++) + a2[n] = *p++; + a2[n] = '\0'; +} + +static int +cmd_foreign(struct sp_host *h, const char *args, struct sp_buf *out, void *ctx) +{ + char sub[32], a1[128], a2[512]; + char err[FR_PATH + 96]; + size_t i, n = 0; + struct sp_buf j; + int rc; + + (void)ctx; + fr.host = h; + resolve_paths(); + args_split(args, sub, sizeof(sub), a1, sizeof(a1), a2, sizeof(a2)); + + if (sub[0] == '\0' || strcmp(sub, "list") == 0 || + strcmp(sub, "sources") == 0) { + struct fbrief *v = calloc(64, sizeof(*v)); + + if (v == NULL) + return sp_buf_puts(out, "error: out of memory"); + sp_buf_puts(out, "foreign session stores:\n"); + sp_buf_printf(out, " claude %s\n", + fr.claude[0] != '\0' ? fr.claude : "(unset)"); + for (i = 0; i < fr.nhermes; i++) + sp_buf_printf(out, " hermes %s\n", fr.hermes[i]); + if (fr.nhermes == 0) + sp_buf_puts(out, " hermes (unset)\n"); + sp_buf_printf(out, " opencode %s\n", + fr.opencode[0] != '\0' ? fr.opencode : "(unset)"); + for (i = 0; i < 3; i++) { + if (list_any((enum fr_src)i, NULL, v, 64, &n, err, + sizeof(err)) != 0) { + sp_buf_printf(out, " %-8s %s\n", src_name[i], + err); + continue; + } + sp_buf_printf(out, " %-8s %zu listed\n", src_name[i], n); + } + free(v); + sp_buf_puts(out, "\n/foreign list|read SOURCE ID|search TEXT|" + "import SOURCE ID\n"); + sp_buf_puts(out, "import writes a splinter session; /open continues it in the chat, splinter --session-id --resume in a shell.\n"); + return 0; + } + if (strcmp(sub, "read") == 0) { + if (src_of(a1) == SRC_NONE || a2[0] == '\0') + return sp_buf_puts(out, "usage: /foreign read SOURCE ID"); + } else if (strcmp(sub, "import") == 0) { + if (src_of(a1) == SRC_NONE || a2[0] == '\0') + return sp_buf_puts(out, "usage: /foreign import SOURCE ID"); + } else if (strcmp(sub, "search") == 0) { + if (a1[0] == '\0') + return sp_buf_puts(out, "usage: /foreign search TEXT"); + } else { + sp_buf_printf(out, "unknown /foreign subcommand '%s'\n", sub); + return sp_buf_puts(out, "usage: /foreign [list|read SOURCE ID|" + "search TEXT|import SOURCE ID]"); + } + if (sp_buf_init(&j) != 0) + return sp_buf_puts(out, "error: out of memory"); + if (strcmp(sub, "search") == 0) { + (void)sp_buf_printf(&j, "{\"query\":\"%s%s%s\"}", a1, + a2[0] != '\0' ? " " : "", a2); + rc = tool_search(j.p, out, h); + } else { + (void)sp_buf_printf(&j, "{\"source\":\"%s\",\"id\":\"%s\"}", + a1, a2); + rc = strcmp(sub, "import") == 0 ? import_any(h, src_of(a1), a2, + out) : tool_read(j.p, out, h); + } + sp_buf_free(&j); + return rc; +} + +/* ----------------------------------------------------------------- widget */ + +static int +foreign_tick(struct sp_host *h, const char *name, void *ctx) +{ + char text[128]; + + (void)ctx; + fr.host = h; + resolve_paths(); + snprintf(text, sizeof(text), "claude %d hermes %d oc %d", + count_claude(), count_hermes(), count_opencode()); + return sp_host_widget_text(h, name, text); +} + +/* ------------------------------------------------------------------- init */ + +static int +foreign_init(struct sp_host *h) +{ + static struct sp_tool t[4]; + static const struct sp_widget w = { + "foreign", foreign_tick, NULL, NULL, 0 + }; + size_t i; + + memset(t, 0, sizeof(t)); + fr.host = h; + resolve_paths(); + + t[0].name = "foreign_list"; + t[0].description = "List the sessions of the other harnesses on this " + "machine -- Claude Code, Hermes and opencode -- with date, id, " + "title and the directory each conversation ran in. Defaults to the " + "current working directory; cwd:\"*\" lists every folder. Use it " + "before asking what an earlier Claude or opencode session did, and " + "foreign_import to continue one here."; + t[0].params = "{\"type\":\"object\",\"properties\":{" + "\"source\":{\"type\":\"string\",\"enum\":[\"claude\",\"hermes\"," + "\"opencode\"],\"description\":\"omit for all three\"}," + "\"cwd\":{\"type\":\"string\",\"description\":\"only sessions that " + "ran in this directory; \\\"*\\\" for every one (default: the " + "current directory)\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"max rows, " + "default 25\"}}}"; + t[0].auth = SP_AUTH_READ; + t[0].run = tool_list; + t[0].ctx = h; + + t[1].name = "foreign_search"; + t[1].description = "Search inside the Claude Code, Hermes and opencode " + "sessions (case-blind): what was asked and answered, with the " + "session id needed to read or import it. Cheaper than reading a " + "whole transcript and the way to find the session that already " + "solved something."; + t[1].params = "{\"type\":\"object\",\"properties\":{" + "\"query\":{\"type\":\"string\",\"description\":\"text to find\"}," + "\"source\":{\"type\":\"string\",\"enum\":[\"claude\",\"hermes\"," + "\"opencode\"],\"description\":\"omit for all\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"max hits, " + "default 10, max 50\"}," + "\"days\":{\"type\":\"integer\",\"description\":\"only sessions " + "changed in the last N days\"}}," + "\"required\":[\"query\"]}"; + t[1].auth = SP_AUTH_READ; + t[1].run = tool_search; + t[1].ctx = h; + + t[2].name = "foreign_read"; + t[2].description = "Read one Claude Code, Hermes or opencode session as " + "a transcript: role, text, and the tool calls with their results " + "in place. Read-only; to give splinter the conversation, use " + "foreign_import instead."; + t[2].params = "{\"type\":\"object\",\"properties\":{" + "\"source\":{\"type\":\"string\",\"enum\":[\"claude\",\"hermes\"," + "\"opencode\"]}," + "\"id\":{\"type\":\"string\",\"description\":\"the session id from " + "foreign_list\"}," + "\"bytes\":{\"type\":\"integer\",\"description\":\"how much of the " + "transcript to print, default 40000\"}}," + "\"required\":[\"source\",\"id\"]}"; + t[2].auth = SP_AUTH_READ; + t[2].run = tool_read; + t[2].ctx = h; + + t[3].name = "foreign_import"; + t[3].description = "Import one Claude Code, Hermes or opencode session " + "into splinter as a splinter session, so /open (in the " + "chat), --session-id --resume (in a shell) and -c continue " + "that conversation here with its history, its tool calls and its " + "working directory. Prints the new session id."; + t[3].params = "{\"type\":\"object\",\"properties\":{" + "\"source\":{\"type\":\"string\",\"enum\":[\"claude\",\"hermes\"," + "\"opencode\"]}," + "\"id\":{\"type\":\"string\",\"description\":\"the session id from " + "foreign_list\"}}," + "\"required\":[\"source\",\"id\"]}"; + t[3].auth = SP_AUTH_MUTATE; /* it writes a session file */ + t[3].run = tool_import; + t[3].ctx = h; + + for (i = 0; i < 4; i++) + if (sp_host_add_tool(h, &t[i]) != 0) + return -1; + if (sp_host_add_widget(h, &w) != 0) + return -1; + if (sp_host_add_command(h, "foreign", cmd_foreign, NULL) != 0) + return -1; + return 0; +} + +static const struct sp_plugin foreign_plugin = { + SP_PLUGIN_ABI, "foreign", "1.0.0", foreign_init, NULL, NULL +}; + +const struct sp_plugin * +sp_plugin_describe(void) +{ + return &foreign_plugin; +} diff --git a/tests/sh/port.sh b/tests/sh/port.sh new file mode 100644 index 0000000..6ce39b7 --- /dev/null +++ b/tests/sh/port.sh @@ -0,0 +1,41 @@ +# A port this process can really bind, and a wait that tells "my fake started" +# apart from "something else already answers here". +# +# The shell tests used to pick a port with 20000 + $$ % 30000. That is a guess: +# on 2026-11-21 it landed on 36343, which dtsession (the CDE desktop) held. +# The fake telegram died with "Address already in use" while the test went on, +# because curl got an answer from dtsession - a server that knows nothing about +# the test - and every check after it failed. Twenty failures pointing at the +# gateway, none at the port. +# +# Source this file and use free_port / wait_listen: +# +# . "$(dirname "$0")/sh/port.sh" +# P=$(free_port) +# python3 -I tests/fake_x.py "$P" ... & +# S=$! +# wait_listen "$P" "$S" || fail "fake did not start" + +# Ask the kernel for a port nobody holds. Between the bind and the fake's own +# bind another process could take it - rare, and much better than a number that +# collides by construction. +free_port() { + python3 -c 'import socket +s = socket.socket(); s.bind(("127.0.0.1", 0)) +print(s.getsockname()[1]); s.close()' +} + +# $1 = port, $2 = pid of the server we started. +# 0 when that process is alive AND accepting connections. +wait_listen() { + _p="$1" + _pid="$2" + _i=0 + while [ "$_i" -lt 100 ]; do + kill -0 "$_pid" 2>/dev/null || return 1 + curl -s -o /dev/null "http://127.0.0.1:$_p/x" && return 0 + sleep 0.2 + _i=$((_i + 1)) + done + return 1 +} diff --git a/tests/test_a2a.sh b/tests/test_a2a.sh index 99c100a..4f0c693 100755 --- a/tests/test_a2a.sh +++ b/tests/test_a2a.sh @@ -7,9 +7,10 @@ # a JSON-RPC error that must fail the turn instead of becoming an empty answer. set -u cd "$(dirname "$0")/.." || exit 1 +. "$(dirname "$0")/sh/port.sh" D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-a2a-XXXXXX") || exit 1 SPLINTER_SESSION_DIR="$D/home/.splinter"; export SPLINTER_SESSION_DIR -P=$((20000 + ($$ % 20000))) +P=$(free_port) F= cleanup() { [ -n "$F" ] && kill "$F" 2>/dev/null; rm -rf "$D"; } trap cleanup EXIT diff --git a/tests/test_a2a_input.sh b/tests/test_a2a_input.sh index b29ba0e..e86d3fe 100755 --- a/tests/test_a2a_input.sh +++ b/tests/test_a2a_input.sh @@ -8,8 +8,9 @@ # without writing. set -u cd "$(dirname "$0")/.." || exit 1 +. "$(dirname "$0")/sh/port.sh" D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-a2a-ir-XXXXXX") || exit 1 -P=$((20000 + ($$ % 20000))) +P=$(free_port) P2=$((P + 1)) P3=$((P + 2)) S1= diff --git a/tests/test_a2a_server.sh b/tests/test_a2a_server.sh index 4d25766..beb9f98 100755 --- a/tests/test_a2a_server.sh +++ b/tests/test_a2a_server.sh @@ -6,9 +6,10 @@ # bearer token that is required beyond loopback (or when configured). set -u cd "$(dirname "$0")/.." || exit 1 +. "$(dirname "$0")/sh/port.sh" D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-a2a-srv-XXXXXX") || exit 1 SPLINTER_SESSION_DIR="$D/home/.splinter"; export SPLINTER_SESSION_DIR -P=$((20000 + ($$ % 20000))) +P=$(free_port) P2=$((P + 1)) P3=$((P + 2)) S1= diff --git a/tests/test_a2a_ui.sh b/tests/test_a2a_ui.sh index 8417092..6548f05 100755 --- a/tests/test_a2a_ui.sh +++ b/tests/test_a2a_ui.sh @@ -7,6 +7,7 @@ # answer is the final status message still produces text. set -u cd "$(dirname "$0")/.." || exit 1 +. "$(dirname "$0")/sh/port.sh" if ! command -v tmux >/dev/null 2>&1; then echo "test_a2a_ui: skipped (no tmux)" exit 0 @@ -23,7 +24,7 @@ own_server() { fi } S=splinter-a2a-ui-$$ -P=$((20000 + ($$ % 20000))) +P=$(free_port) F= fails=0 cleanup() { diff --git a/tests/test_agents_ui.sh b/tests/test_agents_ui.sh index 8e03a2f..a4a0cdb 100644 --- a/tests/test_agents_ui.sh +++ b/tests/test_agents_ui.sh @@ -3,6 +3,7 @@ # splinter -- Tab switches the agent profile; plan cannot run commands. set -u cd "$(dirname "$0")/.." || exit 1 +. "$(dirname "$0")/sh/port.sh" command -v tmux >/dev/null 2>&1 || { echo "test_agents_ui: skipped (no tmux)"; exit 0; } D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-ag-XXXXXX") || exit 1 SPLINTER_SESSION_DIR="$D/home/.splinter"; export SPLINTER_SESSION_DIR @@ -19,7 +20,7 @@ own_server() { fi } killserver() { own_server; tmux kill-server 2>/dev/null; } -P=$((20000 + $$ % 30000)) +P=$(free_port) S=sp-agents-$$ F= trap 'killserver; kill $F 2>/dev/null; rm -rf "$D"' EXIT diff --git a/tests/test_anthropic.sh b/tests/test_anthropic.sh index b459f22..5a53028 100644 --- a/tests/test_anthropic.sh +++ b/tests/test_anthropic.sh @@ -12,8 +12,9 @@ # the provider's own message (instead of "no answer"), and -m picks the pool. set -u cd "$(dirname "$0")/.." || exit 1 +. "$(dirname "$0")/sh/port.sh" D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-as-XXXXXX") || exit 1 -P=$((22000 + $$ % 20000)) +P=$(free_port) trap 'kill $FP 2>/dev/null; rm -rf "$D"' EXIT fails=0 check() { d=$1; shift; if "$@"; then :; else echo "FAIL $d"; fails=$((fails + 1)); fi; } diff --git a/tests/test_attach.sh b/tests/test_attach.sh index aa20e08..5df5653 100755 --- a/tests/test_attach.sh +++ b/tests/test_attach.sh @@ -8,6 +8,7 @@ # agent profile, and Ctrl-D ends the client while the server keeps serving. set -u cd "$(dirname "$0")/.." || exit 1 +. "$(dirname "$0")/sh/port.sh" if ! command -v tmux >/dev/null 2>&1; then echo "test_attach: skipped (no tmux)" exit 0 @@ -23,7 +24,7 @@ own_server() { } killserver() { own_server; tmux kill-server 2>/dev/null; } S=splinter-attach-$$ -P=$((20000 + ($$ + 7) % 30000)) +P=$(free_port) F= G= fails=0 diff --git a/tests/test_foreign.c b/tests/test_foreign.c new file mode 100644 index 0000000..42fe0dc --- /dev/null +++ b/tests/test_foreign.c @@ -0,0 +1,579 @@ +/* + * splinter -- the foreign plugin: claude, hermes and opencode sessions. + * + * Copyright (c) 2026 Konrad Lother + * SPDX-License-Identifier: BSD-3-Clause + * + * What it guards, against fixtures it writes itself (the machine's real stores + * are not a test): + * + * - every source lists its sessions with title, date and the directory the + * conversation ran in, and a cwd filter really filters; + * - reading returns the conversation in order, with the tool call before its + * result, and no thinking block; + * - an import writes a splinter session that sp_session_load() reads back as + * a conversation a provider accepts: every tool_calls is followed by its + * observation, every observation has a call, no blank turn; + * - the import lands in the directory the foreign session ran in, so -c and + * /sessions find it where it happened; + * - an unknown id is an error, not an empty answer, and a title is one line. + * + * The three stores are the fixture's own: SPLINTER_FOREIGN_CLAUDE/_HERMES/ + * _OPENCODE point the plugin at them. + */ +#include +#include +#include +#include +#include +#include + +#include "mcp.h" +#include "splinter.h" +#include "splinter_plugin.h" + +static int failures; + +#define CHECK(cond) do { \ + if (!(cond)) { \ + fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, \ + #cond); \ + failures++; \ + } \ +} while (0) + +static int +contains(const char *hay, const char *needle) +{ + return hay != NULL && strstr(hay, needle) != NULL; +} + +static void +write_file(const char *path, const char *text) +{ + FILE *f = fopen(path, "w"); + + CHECK(f != NULL); + if (f == NULL) + return; + fputs(text, f); + fclose(f); +} + +static void +mkdir_p(const char *path) +{ + char buf[800]; + size_t i, n = strlen(path); + + CHECK(n < sizeof(buf)); + if (n >= sizeof(buf)) + return; + memcpy(buf, path, n + 1); + for (i = 1; i < n; i++) { + if (buf[i] != '/') + continue; + buf[i] = '\0'; + (void)mkdir(buf, 0700); + buf[i] = '/'; + } + CHECK(mkdir(buf, 0700) == 0 || 1); +} + +static int +run_sql(const char *db, const char *sql) +{ + char cmd[4096 + 64], path[256]; + FILE *f; + int rc; + + /* + * The SQL goes through a file, not through the shell. Passing it as a + * quoted argument looked fine until the JSON fixtures arrived: they + * contain double quotes, so '{"text":"OC-NEEDLE"}' ended the shell's + * quoting in the middle of the statement and sqlite3 saw a fragment + * ("unrecognized token"). A file has no quoting to get wrong. + */ + snprintf(path, sizeof(path), "/tmp/splinter-foreign-sql-%ld.sql", + (long)getpid()); + f = fopen(path, "w"); + if (f == NULL) + return -1; + fputs(sql, f); + fclose(f); + snprintf(cmd, sizeof(cmd), "sqlite3 -batch '%s' < '%s'", db, path); + rc = system(cmd); + unlink(path); + return rc == 0 ? 0 : -1; +} + +/* the conversation a provider would accept, out of a session file */ +static int +conversation_ok(const char *dir, const char *id, struct sp_buf *why) +{ + struct sp_session_info si; + struct sp_conv conv; + struct sp_buf err; + size_t loaded = 0, i; + char open_calls[64][80]; + size_t nopen = 0; + int rc = 0; + + memset(&si, 0, sizeof(si)); + if (sp_session_open(&si, dir, id, why) != 0) + return -1; + sp_conv_init(&conv); + sp_buf_init(&err); + if (sp_session_load(&si, &conv, &loaded, &err) != 0) { + sp_buf_printf(why, "load failed: %s", err.p != NULL ? err.p : "?"); + sp_conv_free(&conv); + sp_buf_free(&err); + return -1; + } + for (i = 0; i < conv.n && rc == 0; i++) { + struct sp_msg *m = &conv.v[i]; + + if (m->role == NULL) { + sp_buf_printf(why, "message %zu has no role", i); + rc = -1; + } else if (strcmp(m->role, "assistant") == 0) { + /* every call must be answered by the next tool turns */ + nopen = 0; + if (m->calls != NULL && m->calls[0] != '\0') { + mcp_json *a = mcp_parse(m->calls); + size_t k; + + if (a == NULL || a->t != MCP_ARR) { + sp_buf_printf(why, "message %zu: calls " + "not a JSON array", i); + rc = -1; + } else { + for (k = 0; k < mcp_array_len(a) && + nopen < 64; k++) { + const char *cid = + mcp_arg_string( + mcp_array_at(a, k), "id"); + const mcp_json *fn = + mcp_arg(mcp_array_at(a, k), + "function"); + + if (cid == NULL || fn == NULL) { + sp_buf_printf(why, + "message %zu: a call " + "has no id or no " + "function", i); + rc = -1; + break; + } + snprintf(open_calls[nopen++], + sizeof(open_calls[0]), "%s", + cid); + } + } + mcp_json_free(a); + } + if ((m->content == NULL || m->content[0] == '\0') && + (m->calls == NULL || m->calls[0] == '\0')) { + sp_buf_printf(why, "message %zu: empty assistant " + "turn", i); + rc = -1; + } + } else if (strcmp(m->role, "tool") == 0) { + if (m->call_id == NULL || m->call_id[0] == '\0') { + sp_buf_printf(why, "message %zu: tool without a " + "call id", i); + rc = -1; + } else if (nopen == 0) { + sp_buf_printf(why, "message %zu: tool result %s " + "with no call before it", i, m->call_id); + rc = -1; + } + } else if (strcmp(m->role, "user") == 0) { + nopen = 0; + } + } + if (rc == 0 && loaded == 0) { + sp_buf_printf(why, "loaded 0 messages"); + rc = -1; + } + sp_conv_free(&conv); + sp_buf_free(&err); + return rc; +} + +static const char *claude_jsonl = + "{\"type\":\"queue-operation\",\"operation\":\"enqueue\"}\n" + "{\"type\":\"user\",\"cwd\":\"/work/alpha\",\"isSidechain\":false," + "\"message\":{\"role\":\"user\",\"content\":\"fix the FIXME in " + "main.c\"}}\n" + "{\"type\":\"assistant\",\"cwd\":\"/work/alpha\",\"message\":{\"id\":" + "\"msg_1\",\"role\":\"assistant\",\"content\":[{\"type\":\"thinking\"," + "\"thinking\":\"THE-THINKING should never surface\"}]}}\n" + "{\"type\":\"assistant\",\"cwd\":\"/work/alpha\",\"message\":{\"id\":" + "\"msg_1\",\"role\":\"assistant\",\"content\":[{\"type\":\"text\"," + "\"text\":\"I will read main.c.\"}]}}\n" + "{\"type\":\"assistant\",\"cwd\":\"/work/alpha\",\"message\":{\"id\":" + "\"msg_1\",\"role\":\"assistant\",\"content\":[{\"type\":\"tool_use\"," + "\"id\":\"toolu_a\",\"name\":\"read\",\"input\":{\"path\":\"main.c\"}}]}}\n" + "{\"type\":\"user\",\"cwd\":\"/work/alpha\",\"message\":{\"role\":" + "\"user\",\"content\":[{\"type\":\"tool_result\",\"tool_use_id\":" + "\"toolu_a\",\"content\":[{\"type\":\"text\",\"text\":\"int main(){} " + "// FIXME\"}]}]}}\n" + "{\"type\":\"assistant\",\"cwd\":\"/work/alpha\",\"message\":{\"id\":" + "\"msg_2\",\"role\":\"assistant\",\"content\":[{\"type\":\"text\"," + "\"text\":\"The FIXME is gone now.\"}]}}\n" + /* a subagent's own conversation: not part of this one */ + "{\"type\":\"assistant\",\"isSidechain\":true,\"message\":{\"id\":" + "\"msg_side\",\"role\":\"assistant\",\"content\":[{\"type\":\"text\"," + "\"text\":\"SIDECHAIN-NOISE\"}]}}\n"; + +int +main(void) +{ + char tmpl[] = "/tmp/splinter-foreign-XXXXXX"; + char *base, cla[900], her[900], ocd[900], sessions[900]; + char path[1000], outbuf[8000]; + struct sp_registry reg; + struct sp_agent ag; + struct sp_session_info cur; + struct sp_host *host; + struct sp_buf err, out; + const struct sp_tool *t_list, *t_search, *t_read, *t_import; + struct sp_session_brief v[200]; + int n; + + base = mkdtemp(tmpl); + CHECK(base != NULL); + if (base == NULL) + return 1; + snprintf(cla, sizeof(cla), "%s/claude", base); + snprintf(her, sizeof(her), "%s/hermes", base); + snprintf(ocd, sizeof(ocd), "%s/oc.db", base); + snprintf(sessions, sizeof(sessions), "%s/sessions", base); + + mkdir_p(cla); + mkdir_p(her); + mkdir_p(sessions); + CHECK(setenv("SPLINTER_FOREIGN_CLAUDE", cla, 1) == 0); + CHECK(setenv("SPLINTER_FOREIGN_HERMES", her, 1) == 0); + CHECK(setenv("SPLINTER_FOREIGN_OPENCODE", ocd, 1) == 0); + + /* --- claude: a project directory and one session with a tool call --- */ + { + char proj[950]; + + snprintf(proj, sizeof(proj), "%s/-work-alpha", cla); + mkdir_p(proj); + snprintf(path, sizeof(path), "%s/aaaa-1111.jsonl", proj); + write_file(path, claude_jsonl); + } + + /* --- hermes: state.db with one session and a tool round --- */ + { + char dbe[950]; + + snprintf(dbe, sizeof(dbe), "%s/state.db", her); + CHECK(run_sql(dbe, "create table sessions (id text primary key, " + "title text, cwd text, started_at real, message_count int);") == 0); + CHECK(run_sql(dbe, "create table messages (id integer primary key " + "autoincrement, session_id text, role text, content text, " + "tool_call_id text, tool_calls text, tool_name text, " + "timestamp real, active int default 1, compacted int default " + "0);") == 0); + CHECK(run_sql(dbe, "insert into sessions values ('h-1','hermes " + "H ITLE','/work/beta',1795200000,4);") == 0); + CHECK(run_sql(dbe, "insert into messages (session_id,role,content," + "timestamp) values ('h-1','user','HERMES-NEEDLE what does it " + "do',1);") == 0); + CHECK(run_sql(dbe, "insert into messages (session_id,role,content," + "tool_calls,timestamp) values ('h-1','assistant',''," + "'[{\"id\":\"call_h\",\"type\":\"function\",\"function\":" + "{\"name\":\"grep\",\"arguments\":\"{\\\"q\\\":\\\"x\\\"}\"}}]'," + "2);") == 0); + CHECK(run_sql(dbe, "insert into messages (session_id,role,content," + "tool_call_id,tool_name,timestamp) values ('h-1','tool'," + "'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); + /* 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); + } + + /* --- opencode: session_v2 + session_message, one tool round --- */ + CHECK(run_sql(ocd, "create table session_v2 (id text primary key, title " + "text, directory text, time_created integer, time_updated integer);") + == 0); + CHECK(run_sql(ocd, "create table session_message (id text primary key, " + "session_id text, type text, seq integer, time_created integer, " + "time_updated integer, data text);") == 0); + CHECK(run_sql(ocd, "insert into session_v2 values ('ses_oc1','oc TITLE'," + "'/work/gamma',1795200000000,1795200100000);") == 0); + CHECK(run_sql(ocd, "insert into session_message values ('m1','ses_oc1'," + "'user',1,1795200000000,1795200000000,'{\"text\":\"OC-NEEDLE " + "run the tests\"}');") == 0); + CHECK(run_sql(ocd, "insert into session_message values ('m2','ses_oc1'," + "'assistant',2,1795200001000,1795200001000,'{\"content\":[{\"type\":" + "\"reasoning\",\"text\":\"OC-REASONING must not surface\"}," + "{\"type\":\"text\",\"text\":\"Running them.\"},{\"type\":\"tool\"," + "\"id\":\"call_oc\",\"name\":\"shell\",\"state\":{\"status\":" + "\"completed\",\"input\":{\"command\":\"make test\"},\"content\":" + "[{\"type\":\"text\",\"text\":\"OC-OUTPUT 12 passed\"}]}}]}');") == 0); + CHECK(run_sql(ocd, "insert into session_message values ('m3','ses_oc1'," + "'assistant',3,1795200002000,1795200002000,'{\"content\":[{\"type\":" + "\"text\",\"text\":\"All twelve pass.\"}]}');") == 0); + + /* a splinter session to give the host its directory */ + memset(®, 0, sizeof(reg)); + memset(&ag, 0, sizeof(ag)); + memset(&cur, 0, sizeof(cur)); + sp_buf_init(&err); + sp_buf_init(&out); + CHECK(sp_session_open(&cur, sessions, "sess-cur", &err) == 0); + sp_buf_clear(&err); + host = sp_host_new(®, &ag, &cur); + CHECK(host != NULL); + CHECK(sp_plugin_load(host, "plugins/foreign/foreign.so", &err) == 0); + + t_list = sp_registry_find(®, "foreign_list"); + t_search = sp_registry_find(®, "foreign_search"); + t_read = sp_registry_find(®, "foreign_read"); + t_import = sp_registry_find(®, "foreign_import"); + CHECK(t_list != NULL && t_search != NULL && t_read != NULL && + t_import != NULL); + if (t_list == NULL || t_search == NULL || t_read == NULL || + t_import == NULL) { + fprintf(stderr, "plugin not loaded: %s\n", + err.p != NULL ? err.p : "?"); + goto out; + } + /* an import writes a session: it must not be a read tool */ + CHECK(t_import->auth == SP_AUTH_MUTATE); + CHECK(t_list->auth == SP_AUTH_READ && t_search->auth == SP_AUTH_READ && + t_read->auth == SP_AUTH_READ); + + /* --- list: all three stores, cwd filters really filter --- */ + CHECK(t_list->run("{\"cwd\":\"*\"}", &out, t_list->ctx) == 0); + CHECK(contains(out.p, "aaaa-1111")); + CHECK(contains(out.p, "h-1")); + CHECK(contains(out.p, "ses_oc1")); + CHECK(contains(out.p, "/work/alpha") && contains(out.p, "/work/beta") && + contains(out.p, "/work/gamma")); + sp_buf_clear(&out); + + CHECK(t_list->run("{\"cwd\":\"/work/beta\"}", &out, t_list->ctx) == 0); + CHECK(contains(out.p, "h-1")); + CHECK(!contains(out.p, "ses_oc1")); + CHECK(!contains(out.p, "aaaa-1111")); + sp_buf_clear(&out); + + /* + * A cwd whose slug directory exists: the list must read that one + * directory and not walk everything. The second project below holds a + * session that claims /work/alpha too - a directory walk would list it, + * the slug lookup must not. claude_slug_dir used to answer -1 for every + * non-empty path (inverted check), so the fast path was dead and the + * walk decided. + */ + { + char proj[950], other[950]; + + snprintf(proj, sizeof(proj), "%s/-work-alpha", cla); + mkdir_p(proj); + snprintf(other, sizeof(other), "%s/-work-omega", cla); + mkdir_p(other); + snprintf(path, sizeof(path), "%s/dead-beef.jsonl", other); + write_file(path, claude_jsonl); + } + CHECK(t_list->run("{\"source\":\"claude\",\"cwd\":\"/work/alpha\"}", + &out, t_list->ctx) == 0); + CHECK(contains(out.p, "aaaa-1111")); + CHECK(!contains(out.p, "dead-beef")); + sp_buf_clear(&out); + + CHECK(t_list->run("{\"source\":\"opencode\",\"cwd\":\"*\"}", &out, + t_list->ctx) == 0); + CHECK(contains(out.p, "ses_oc1")); + CHECK(!contains(out.p, "h-1")); + sp_buf_clear(&out); + + CHECK(t_list->run("{\"cwd\":\"/nowhere\"}", &out, t_list->ctx) == 0); + CHECK(contains(out.p, "no foreign sessions")); + sp_buf_clear(&out); + + /* --- search: case-blind, hits name the session, the answer is not a hit */ + CHECK(t_search->run("{\"query\":\"hermes-needle\"}", &out, + t_search->ctx) == 0); + CHECK(contains(out.p, "h-1")); + sp_buf_clear(&out); + CHECK(t_search->run("{\"query\":\"OC-OUTPUT\"}", &out, t_search->ctx) == 0); + CHECK(contains(out.p, "no message")); + 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); + CHECK(t_search->run("{\"query\":\"NOT-ANYWHERE-AT-ALL\"}", &out, + t_search->ctx) == 0); + CHECK(contains(out.p, "no message")); + 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); + + /* --- read: order, the call before its result, no thinking/reasoning --- */ + CHECK(t_read->run("{\"source\":\"claude\",\"id\":\"aaaa-1111\"}", &out, + t_read->ctx) == 0); + snprintf(outbuf, sizeof(outbuf), "%s", out.p != NULL ? out.p : ""); + CHECK(contains(outbuf, "fix the FIXME")); + CHECK(contains(outbuf, "I will read main.c.")); + CHECK(contains(outbuf, "[tool read]")); + CHECK(contains(outbuf, "int main(){} // FIXME")); + CHECK(contains(outbuf, "The FIXME is gone now.")); + CHECK(!contains(outbuf, "THE-THINKING")); + CHECK(!contains(outbuf, "SIDECHAIN-NOISE")); + CHECK(strstr(outbuf, "I will read main.c.") < + strstr(outbuf, "[tool read]")); + sp_buf_clear(&out); + + CHECK(t_read->run("{\"source\":\"hermes\",\"id\":\"h-1\"}", &out, + t_read->ctx) == 0); + CHECK(contains(out.p, "HERMES-NEEDLE")); + CHECK(contains(out.p, "[tool grep]")); + CHECK(contains(out.p, "HERMES-OUTPUT")); + CHECK(contains(out.p, "three matches")); + CHECK(!contains(out.p, "SUPERSEDED")); + sp_buf_clear(&out); + + CHECK(t_read->run("{\"source\":\"opencode\",\"id\":\"ses_oc1\"}", &out, + t_read->ctx) == 0); + CHECK(contains(out.p, "OC-NEEDLE")); + CHECK(contains(out.p, "[tool shell]")); + CHECK(contains(out.p, "OC-OUTPUT")); + CHECK(contains(out.p, "All twelve pass.")); + CHECK(!contains(out.p, "OC-REASONING")); + CHECK(strstr(out.p, "[assistant]") < strstr(out.p, "[tool shell]")); + sp_buf_clear(&out); + + /* --- errors are sentences, not silence --- */ + CHECK(t_read->run("{\"source\":\"claude\",\"id\":\"nope\"}", &out, + t_read->ctx) == 0); + CHECK(contains(out.p, "error:")); + CHECK(contains(out.p, "no claude session")); + sp_buf_clear(&out); + CHECK(t_read->run("{\"id\":\"x\"}", &out, t_read->ctx) == 0); + CHECK(contains(out.p, "error:")); + sp_buf_clear(&out); + CHECK(t_read->run("{\"source\":\"claude\",\"id\":\"../etc/passwd\"}", &out, + t_read->ctx) == 0); + CHECK(contains(out.p, "not a session id")); + sp_buf_clear(&out); + + /* --- import: a session splinter can read back and resume --- */ + CHECK(t_import->run("{\"source\":\"claude\",\"id\":\"aaaa-1111\"}", &out, + t_import->ctx) == 0); + CHECK(contains(out.p, "imported claude session aaaa-1111 as fcl-aaaa-1111")); + sp_buf_clear(&out); + CHECK(conversation_ok(sessions, "fcl-aaaa-1111", &err) == 0); + if (err.len > 0) + fprintf(stderr, "claude import: %s\n", err.p); + sp_buf_clear(&err); + + CHECK(t_import->run("{\"source\":\"hermes\",\"id\":\"h-1\"}", &out, + t_import->ctx) == 0); + sp_buf_clear(&out); + CHECK(conversation_ok(sessions, "fhm-h-1", &err) == 0); + if (err.len > 0) + fprintf(stderr, "hermes import: %s\n", err.p); + sp_buf_clear(&err); + + CHECK(t_import->run("{\"source\":\"opencode\",\"id\":\"ses_oc1\"}", &out, + t_import->ctx) == 0); + sp_buf_clear(&out); + CHECK(conversation_ok(sessions, "foc-ses_oc1", &err) == 0); + if (err.len > 0) + fprintf(stderr, "opencode import: %s\n", err.p); + sp_buf_clear(&err); + + /* the import is in the directory the conversation ran in */ + CHECK(sp_session_cwd(sessions, "fcl-aaaa-1111", path, sizeof(path)) == 0); + CHECK(strcmp(path, "/work/alpha") == 0); + CHECK(sp_session_cwd(sessions, "fhm-h-1", path, sizeof(path)) == 0); + CHECK(strcmp(path, "/work/beta") == 0); + CHECK(sp_session_cwd(sessions, "foc-ses_oc1", path, sizeof(path)) == 0); + CHECK(strcmp(path, "/work/gamma") == 0); + + /* and it has the source's title, on one line */ + n = sp_session_list(sessions, v, 200); + CHECK(n >= 3); + { + int i, found = 0; + + for (i = 0; i < n; i++) + if (strcmp(v[i].id, "fhm-h-1") == 0) { + CHECK(strcmp(v[i].title, "hermes H ITLE") == 0); + found = 1; + } + CHECK(found); + } + + /* the imported session grows like any other: a turn is appended */ + { + struct sp_session_info si; + struct sp_buf serr; + + sp_buf_init(&serr); + CHECK(sp_session_open(&si, sessions, "fcl-aaaa-1111", &serr) == 0); + CHECK(sp_session_append(&si, "user", "and now?", &serr) == 0); + sp_buf_free(&serr); + } + CHECK(conversation_ok(sessions, "fcl-aaaa-1111", &err) == 0); + sp_buf_clear(&err); + + /* an import of something unknown fails and writes nothing */ + CHECK(t_import->run("{\"source\":\"opencode\",\"id\":\"ses_none\"}", &out, + t_import->ctx) == 0); + CHECK(contains(out.p, "error:")); + sp_buf_clear(&out); + snprintf(path, sizeof(path), "%s/foc-ses_none.jsonl", sessions); + CHECK(access(path, F_OK) != 0); + + /* the command reports the stores and their counts */ + CHECK(sp_host_command(host, "foreign", "list", &out) == 0); + CHECK(contains(out.p, "claude")); + CHECK(contains(out.p, "hermes")); + CHECK(contains(out.p, "opencode")); + CHECK(contains(out.p, cla)); + sp_buf_clear(&out); + + /* + * A store that cannot be read says why. The message used to be built + * from errno, which nothing on the path had set: a database with the + * wrong schema was reported as "No such file or directory" while the + * file was right there. This drops the tables from the store the plugin + * resolved and asks again. + */ + CHECK(run_sql(ocd, "drop table session_v2;") == 0); + CHECK(t_list->run("{\"source\":\"opencode\",\"cwd\":\"*\"}", &out, + t_list->ctx) == 0); + CHECK(contains(out.p, "no such table")); + CHECK(!contains(out.p, "No such file")); + sp_buf_clear(&out); + +out: + sp_host_free(host); + sp_registry_free(®); + sp_buf_free(&err); + sp_buf_free(&out); + { + char cmd[1100]; + + if (getenv("KEEP_FOREIGN") == NULL) { + snprintf(cmd, sizeof(cmd), "rm -rf '%s'", base); + (void)system(cmd); + } else + fprintf(stderr, "kept: %s\n", base); + } + if (failures == 0) + printf("test_foreign: ok\n"); + return failures == 0 ? 0 : 1; +} diff --git a/tests/test_gateway.sh b/tests/test_gateway.sh index 39ebba6..e029362 100755 --- a/tests/test_gateway.sh +++ b/tests/test_gateway.sh @@ -13,16 +13,31 @@ SPLINTER_SESSION_DIR="$D/home/.splinter"; export SPLINTER_SESSION_DIR trap 'rm -rf "$D"' EXIT fails=0 -wait_fake() { # $1 = port; 0 when something accepts a connection +wait_fake() { # $1 = port, $2 = pid; 0 when THAT process accepts a connection + # + # Check the pid first. Without it a port that some other program already + # holds looks like a fake that started: curl answers, the test goes on, + # and the failures show up far from the cause. Seen on 2026-11-21 with + # dtsession (the CDE desktop) holding 36343, a port the old formula + # picked; twenty-odd gateway checks failed for it. for i in $(seq 1 100); do + kill -0 "$2" 2>/dev/null || return 1 curl -s -o /dev/null "http://127.0.0.1:$1/x" && return 0 sleep 0.2 done return 1 } +# A port this process can really bind. The old formula, 20000 + $$ % 30000, +# is a guess and collided with whatever else the machine runs. +free_port() { + python3 -c 'import socket +s = socket.socket(); s.bind(("127.0.0.1", 0)) +print(s.getsockname()[1]); s.close()' +} + run() { # $1 = answer word; leaves $D/sent.log and maybe $D/out.txt - P=$((20000 + ($$ + ${2:-0}) % 30000)) + P=$(free_port) rm -rf "$D/home" "$D/out.txt" "$D/sent.log" mkdir -p "$D/home/.splinter/commands" printf '#!/bin/sh\necho hallo\n' > "$D/home/.splinter/commands/hello" @@ -32,7 +47,7 @@ run() { # $1 = answer word; leaves $D/sent.log and maybe $D/out.txt python3 -I tests/fake_telegram.py "$P" "$D/out.txt" "$D/sent.log" "$1" \ > "$D/fake.out" 2>&1 & S=$! - if ! wait_fake "$P" || ! kill -0 "$S" 2>/dev/null; then + if ! wait_fake "$P" "$S"; then echo "FAIL fake telegram did not start on $P" cat "$D/fake.out" 2>/dev/null fails=$((fails + 1)) @@ -80,7 +95,7 @@ check "the tool did not run after the no" test ! -e "$D/out.txt" # a program in commands/ answers in the chat, without a model turn run_text() { # $1 = first message, $2 = line to wait for, $3 = port offset, # $4 = a line that must appear too before the fake is killed - P=$((20000 + ($$ + ${3:-0}) % 30000)) + P=$(free_port) rm -rf "$D/home" "$D/out.txt" "$D/sent.log" mkdir -p "$D/home/.splinter/commands" printf '#!/bin/sh\necho "script sagt hallo"\n' \ @@ -91,7 +106,7 @@ run_text() { # $1 = first message, $2 = line to wait for, $3 = port offset, python3 -I tests/fake_telegram.py "$P" "$D/out.txt" "$D/sent.log" ok "$1" \ > "$D/fake.out" 2>&1 & S=$! - if ! wait_fake "$P" || ! kill -0 "$S" 2>/dev/null; then + if ! wait_fake "$P" "$S"; then echo "FAIL fake telegram did not start on $P" cat "$D/fake.out" 2>/dev/null fails=$((fails + 1)) diff --git a/tests/test_limit_wait.sh b/tests/test_limit_wait.sh index 5464a61..eae45e0 100644 --- a/tests/test_limit_wait.sh +++ b/tests/test_limit_wait.sh @@ -7,8 +7,9 @@ # on_limit = fail it must fail instead. set -u cd "$(dirname "$0")/.." || exit 1 +. "$(dirname "$0")/sh/port.sh" D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-lw-XXXXXX") || exit 1 -P=$((20000 + $$ % 30000)) +P=$(free_port) trap 'kill $F 2>/dev/null; rm -rf "$D"' EXIT fails=0 check() { d=$1; shift; if "$@"; then :; else echo "FAIL $d"; fails=$((fails + 1)); fi; } diff --git a/tests/test_reconnect.sh b/tests/test_reconnect.sh index 64eda6b..90801e4 100755 --- a/tests/test_reconnect.sh +++ b/tests/test_reconnect.sh @@ -7,6 +7,7 @@ # on is asked for by id, its history comes back and a new turn works. set -u cd "$(dirname "$0")/.." || exit 1 +. "$(dirname "$0")/sh/port.sh" if ! command -v tmux >/dev/null 2>&1; then echo "test_reconnect: skipped (no tmux)" exit 0 @@ -24,7 +25,7 @@ own_server() { } killserver() { own_server; tmux kill-server 2>/dev/null; } S=splinter-reconnect-$$ -P=$((20000 + ($$ + 11) % 30000)) +P=$(free_port) F= G1= G2= diff --git a/tests/test_ui.sh b/tests/test_ui.sh index 50620e2..af52471 100755 --- a/tests/test_ui.sh +++ b/tests/test_ui.sh @@ -10,6 +10,7 @@ # Skipped, and says so, where tmux is not installed. set -u cd "$(dirname "$0")/.." || exit 1 +. "$(dirname "$0")/sh/port.sh" if ! command -v tmux >/dev/null 2>&1; then echo "test_ui: skipped (no tmux)" exit 0 @@ -66,7 +67,7 @@ done_turn() { # wait until the turn label is gone start() { # a fresh fake model and a fresh UI ($2: retry wait in ms) [ -n "$F" ] && kill "$F" 2>/dev/null killserver - P=$((20000 + ($$ + $1) % 30000)) + P=$(free_port) rm -rf "$D/home" "$D/out.txt" "$D/rc" mkdir -p "$D/home" python3 -I tests/fake_telegram.py "$P" "$D/out.txt" "$D/sent.log" ok \