foreign: adopt a claude, hermes or opencode session as a splinter session

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/<slug>/<id>.jsonl, <root>/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 <id> --resume in a shell, and -c finds it in the directory the
conversation actually ran in. The marker foreign=<source>:<id> 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.
This commit is contained in:
lotherk committed 2026-11-21 21:26:43 +00:00
1 parent 87f5987a46
commit fa16bfd0a9
18 files changed
+3962 -17

No files matched your search

+9 -2
View File
@@ -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)
+58
View File
@@ -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 <text>` 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 `<session>.agent`, so a session left in plan resumes
in plan; the model it was left on is in `<session>.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/<slug>/<id>.jsonl` (Claude Code) |
| `hermes` | `<root>/state.db` and `<root>/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 <new id>`
continues it in the chat and `--session-id <new 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=<source>:<id>` — 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
+54
View File
@@ -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
`<session dir>/<id>.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 `<embed_endpoint>/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 `<session_dir>/emb/<session-id>.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) —
+19
View File
@@ -191,6 +191,25 @@ with no network at all.
.It Pa ~/.splinter/<id>.jsonl
Append-only session log, one JSON object per line.
A crash can only truncate the tail.
.It Pa ~/.splinter/emb/<id>.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/<id>.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
File diff suppressed because it is too large. Load diff
+41
View File
@@ -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
}
+2 -1
View File
@@ -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
+2 -1
View File
@@ -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=
+2 -1
View File
@@ -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=
+2 -1
View File
@@ -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() {
+2 -1
View File
@@ -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
+2 -1
View File
@@ -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; }
+2 -1
View File
@@ -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
+579
View File
@@ -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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#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(&reg, 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(&reg, &ag, &cur);
CHECK(host != NULL);
CHECK(sp_plugin_load(host, "plugins/foreign/foreign.so", &err) == 0);
t_list = sp_registry_find(&reg, "foreign_list");
t_search = sp_registry_find(&reg, "foreign_search");
t_read = sp_registry_find(&reg, "foreign_read");
t_import = sp_registry_find(&reg, "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(&reg);
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;
}
+20 -5
View File
@@ -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))
+2 -1
View File
@@ -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; }
+2 -1
View File
@@ -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=
+2 -1
View File
@@ -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 \