Commit Graph
238 Commits
Author SHA1 Message Date
lotherk d9bdb2a62f sse: a half-built reply is freed, not handed back
sp_sse_finish() filled *out step by step and returned -1 from the
middle: after strdup(content), after calloc(calls), after strdup of a
call's fields and after strdup(calls_json). The comment one line above
the calloc says the caller does not free a reply it was told failed, and
agent_request() only frees on its own paths - so every one of those
exits leaked the content and every call already strdup'd.

Every failure now goes through one `fail:` label that calls
sp_reply_free(out), which is also what the alloc-failure branch for
out->calls did by hand (and did inconsistently: it freed content only).

Verified: test_sse ok, valgrind on test_sse: no leaks, make check: all
tests passed.
2026-11-23 09:01:39 +00:00
lotherkandClaude Sonnet 5.5 9b83b10804 pkgsrc: distinfo of the archive (tools/ext-dist.sh)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 08:43:17 +00:00
lotherk 68e5b14d10 merge: the pkgsrc import and the race fixes, in one order on every remote 2026-11-23 08:31:44 +00:00
lotherkandClaude Sonnet 5.5 467739ec2b pkgsrc: the recipe for Makronix (misc/splinter), IMPORT
The recipe is copied into pkgsrc/ by Makronix's tools/ext-sync.sh and built
from the archive tools/ext-dist.sh makes of this repository.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 08:30:42 +00:00
lotherk 80f055711d races: five data races fixed, make check-tsan to keep them fixed
Found with ThreadSanitizer over the whole suite, not by reading:

- ack: sp_ack_dir() returned one static buffer. The waiter and the
  answerer (the gateway is both) sprintf'd into each other's path, so an
  approval request could be looked for in the wrong place. One buffer per
  thread now; test_ack asserts the two threads get different addresses.
- mcp: `stopping` was a plain volatile int with no happens-before, so a
  server thread could read 0 after shutdown killed its child and keep
  using buffers that teardown frees. Acquire/release accessors.
- foreign: fr.ready was set before the paths it guards were filled, so a
  second thread returned early and read empty paths; the flag and the host
  handle are now an atomic pair (publish) plus a mutex (the init itself).
- embed: catch_up() read c->path, c->offset and c->id outside the lock. A
  session switch mid-index published the old file's byte offset into the
  new session's index - everything below that offset was never searched
  again. A generation counter makes that run drop its batch, and the
  search path takes its snapshot under the same lock.

Proof, both directions:
- make check-tsan: 45/45 test binaries free of races (new target; the
  tree is rebuilt under TSan and back, like check-asan).
- test_embed's new gated test (a server that holds the batch until the
  session has been switched): without the generation check short.emb ends
  with 4 records, 1 of them leaked from the other session; with it, 1
  and 0. The test is deterministic, so it fails on a plain build too.
- test_ack: reverting to `static char root[]` fails
  "the two threads do not share one buffer".
- make check: all tests passed; make check-asan: 45/45 clean.
2026-11-23 08:30:29 +00:00
lotherk e177475648 races: five data races fixed, make check-tsan to keep them fixed
Found with ThreadSanitizer over the whole suite, not by reading:

- ack: sp_ack_dir() returned one static buffer. The waiter and the
  answerer (the gateway is both) sprintf'd into each other's path, so an
  approval request could be looked for in the wrong place. One buffer per
  thread now; test_ack asserts the two threads get different addresses.
- mcp: `stopping` was a plain volatile int with no happens-before, so a
  server thread could read 0 after shutdown killed its child and keep
  using buffers that teardown frees. Acquire/release accessors.
- foreign: fr.ready was set before the paths it guards were filled, so a
  second thread returned early and read empty paths; the flag and the host
  handle are now an atomic pair (publish) plus a mutex (the init itself).
- embed: catch_up() read c->path, c->offset and c->id outside the lock. A
  session switch mid-index published the old file's byte offset into the
  new session's index - everything below that offset was never searched
  again. A generation counter makes that run drop its batch, and the
  search path takes its snapshot under the same lock.

Proof, both directions:
- make check-tsan: 45/45 test binaries free of races (new target; the
  tree is rebuilt under TSan and back, like check-asan).
- test_embed's new gated test (a server that holds the batch until the
  session has been switched): without the generation check short.emb ends
  with 4 records, 1 of them leaked from the other session; with it, 1
  and 0. The test is deterministic, so it fails on a plain build too.
- test_ack: reverting to `static char root[]` fails
  "the two threads do not share one buffer".
- make check: all tests passed; make check-asan: 45/45 clean.
2026-11-23 08:30:11 +00:00
lotherkandClaude Sonnet 5.5 b61172a4a5 pkgsrc: the recipe for Makronix (misc/splinter), IMPORT
The recipe is copied into pkgsrc/ by Makronix's tools/ext-sync.sh and built
from the archive tools/ext-dist.sh makes of this repository.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 07:02:06 +00:00
lotherk 4cdaf2680b store: a write that cannot finish no longer replaces the good file
jobrec_write(), write_sidecar() and provstate's write_state() wrote into a
temp, ignored the result and renamed it over the live file. A full disk (or
EIO) then left a torn json where a job record or a key's quota state used to
be. For provstate that is the dangerous direction: a truncated state parses as
all zeroes, so "this key is out of quota until 19:00" became "admit it" and the
harness hammered a spent account.

All three now fflush+fsync+fclose, unlink the temp when any step fails, and
only then rename. Test proof, both tests fail on the old code:

  test_provstate.c  RLIMIT_FSIZE=8, write_state fails -> last_status still 429,
                    preflight still waits
  test_jobs.c       RLIMIT_FSIZE=8, delegate_retry cannot write -> the record on
                    disk is still a whole json, no .tmp left behind

make check: all tests passed. tests/check_asan.sh: all 45 binaries clean.
2026-11-23 06:33:12 +00:00
lotherk b1acf1629b builtin: a read error is not the end of the file
`slurp` and `read` treated ferror() as EOF: `edit` then took the truncated
prefix for the whole file and wrote it back, and `read` silently showed
fewer lines. Both now report the error and name the path.

`search` still skips a file it cannot read - it only reports hits, and a
file it cannot open is not a hit - but it no longer claims a clean scan.

Evidence:
  edit /proc/self/mem      -> "error: /proc/self/mem: Input/output error"
                              (before: "is empty")
  read /proc/self/mem      -> "[...: read error after line 0: Input/output error]"
  edit <dir>               -> "Is a directory"
With the three ferror() guards removed, tests/test_builtin.c fails at
lines 221, 227 and the directory cases; with them the test is green.
make check: all tests passed, 21 suites. check_asan: 45 binaries clean.
2026-11-23 01:32:38 +00:00
lotherk d7a61a1bd5 builtin: write and edit can no longer truncate the file they replace
fopen(path, "w") truncates before the new text exists, so a short write
(a full disk - seen in a live session as "No space left on device" - or
RLIMIT_FSIZE) left the operator with an empty file and no copy. The old
code also reported success: the error arrived in fclose(), which was
ignored.

Both tools now share write_atomic(): temp file, fflush, fsync, rename.
A symlink is resolved first, because rename() would otherwise replace the
link instead of writing through it and silently detach a dotfile setup.
The mode of an existing file is kept.

test_builtin makes the short write deterministic with RLIMIT_FSIZE:
without the fix it reports success and the original is gone (FAIL
"error:" and "wichtig"), with it the file is untouched and no .tmp
debris is left. A second case pins the symlink: the link survives, the
target gets the new text (FAIL S_ISLNK and the target content without
resolve_target). make check: all tests passed; check_asan: 45 binaries
clean.
2026-11-23 01:23:25 +00:00
lotherk 0b643ca6d9 servers: a silent client no longer holds the gateway or A2A server
Both HTTP servers answer one connection at a time. A client that sent half a
header and then went quiet held the whole gateway: a second client's complete
request was never answered (measured: recv timed out after 10s, with the lazy
socket open). The A2A server had the same shape with a five minute read
timeout, so one idle socket blocked every other request for five minutes.

Both now bound the read (gateway 60s, A2A 120s) and take the value from
SPLINTER_GATEWAY_READ_TIMEOUT / SPLINTER_A2A_READ_TIMEOUT so a test does not
wait a minute.

Tests: tests/slow_client.py and tests/slow_a2a_client.py open a socket, send
half a request, wait past the timeout, then send a complete one and require a
200. Without the fix both print "the server is still held" and the suite is
red; with it, test_gateway_openai: ok and test_a2a_server: ok. Full suite:
all tests passed. check_asan: all 45 test binaries clean.
2026-11-23 01:11:56 +00:00
lotherk e7e47b7f1d json: a depth limit, so a nested body cannot kill the process
The parser recurses once per container and had no limit. The OpenAI gateway and
the A2A server hand it a caller's body of up to 4 MiB, so a request of 200k
nested arrays was a remote crash: verified against a running gateway, the
process died and the client got an empty reply. 200k arrays are a 400 KB body,
well inside what both servers accept.

J_MAX_DEPTH = 64 is far past any real document (a tool schema nests four or
five deep) and far short of a stack frame budget. A deeper document is now a
parse error, which both servers already answer with 400.

Proof in tests/test_fuzz.c (test_json_depth): 200k nested arrays crash without
the limit and parse as NULL with it; an ordinary document still parses.

make check: all tests passed. make check-asan: all 45 test binaries clean.
2026-11-23 00:56:58 +00:00
lotherk d7ce939966 docs: a remote index is searched by the model that built it 2026-11-23 00:48:06 +00:00
lotherk 98dce53200 embed: a remote index stores the model's vectors, and the query asks the model
Two bugs that made `embed = openai` useless while looking healthy:

1. encode_remote() read every vector element with mcp_arg_num(el, NULL, 0.0).
   mcp_arg_num() looks up a key in an object; on a bare array element it always
   returned the default. Every stored vector was zeros, so the index was
   "built" and no search could ever match.
2. The search encodes the question locally, even when the index was built
   remotely. Two unrelated vector spaces: a query never landed near anything.
   encode_query() now sends the question to the same endpoint that built the
   index.

Proof in tests/test_embed.c (test_remote_vectors_are_the_models): a forked
HTTP server answers /v1/embeddings with a bag-of-words vector that is not the
local hash. Without the fix the stored vector is all 'A' (base64 zeros) and
the search finds nothing; with the fix the stored vector carries 5 non-zero
components and "which port does the deploy machine use" hits the right message
at 0.713.

make check: all tests passed. make check-asan: all 45 test binaries clean.
2026-11-23 00:47:34 +00:00
lotherk 4783705e6b embed: a failed batch frees the vectors it built
catch_up() allocated one vector per record and only commit() ever
freed them: a remote encoder that refused the batch (no endpoint, a
non-2xx, a wrong dimension count) leaked dims doubles per record on
every retry, and the worker retried until it parked.

valgrind on tests/test_embed before the fix: 512 bytes definitely
lost in 4 blocks; after: 0 errors. `make check`: all tests passed.
2026-11-23 00:23:12 +00:00
lotherk 6240f3f72a session: /rm removes the embedding index too
sp_session_delete() unlinked the .jsonl, meta, agent, model and the logs, but
not emb/<id>.emb. The index is derived data, yet it holds a copy of the
conversation text and 42 MB had piled up in ~/.splinter: 41 orphaned files
whose session was long gone. A delete that leaves a searchable copy of the
deleted session behind is also the wrong promise.

tests/test_session.c creates emb/s1.emb, removes the session and checks the
file is gone: red before (access(F_OK) == 0), green after. make check: all
tests passed, rc 0.
2026-11-23 00:13:49 +00:00
lotherk ea772e1851 session: a torn tail no longer swallows the next record
A write that ran out of disk leaves half a JSONL line at the end of the
session file. The next record was appended straight onto it, the two became
one line, and the loader (which drops unterminated lines) lost the NEW
message - seen for real today when /tmp filled up.

The writer now closes a torn line with a newline before appending, so the
damage stays the one record that was never finished. The file is opened
O_RDWR for that: O_WRONLY cannot pread.

tests/test_session.c writes a torn line, appends a turn, and checks the
conversation still loads with the new message: red before the fix
(loaded == 2 was 1), green after. make check: all tests passed, rc 0.
2026-11-23 00:06:21 +00:00
lotherk 30e202eca0 foreign: /foreign search keeps a quote in the text
The command built its JSON request with the operator's words as a plain
%s inside a string, so /foreign search he said "hi" there ended the
value early and was answered with "'query' is required" - the whole
phrase lost. The text (and the source/id pair) goes through
sp_json_escape now.

  before: /foreign search he said "hi" there -> error: 'query' is required
  after:  the same command reaches the stores and answers
  tests/test_foreign: red with the old line (2 failures), green with the fix
  make check: all tests passed, rc=0
2026-11-22 23:57:00 +00:00
lotherk 4507a3c57c i18n: a catalogue text is data, never a printf format
The interview note built its buffer with the translation as the format
string:
  snprintf(note, sizeof(note), sp_td("interview.saved", ...))
A '%' in a translation would be read as a conversion - clformat-security named it. The text goes through "%s" now.

tools/check_i18n.py grew the guard that keeps the shape out: a sp_t()/
sp_td() call may be the format only when arguments follow it; with none
behind it the conversions are unintended.

  clang -Wformat-security: 1 -> no warning at that call
  check_i18n with the bug restored: fires, rc=1
  check_i18n with the fix: ok (229 keys, 3 catalogues)
  make check: all tests passed, rc=0
2026-11-22 23:49:55 +00:00
lotherk cfe0af2688 ui: the picker holds every row the backend lists
The /sessions rows and the /model rows share one list struct, and the list was
sized with SP_MODEL_CHOICES (96) because /model was its first user. The session
side answers with up to 100 rows (FOREIGN_ROW_MAX in foreignopen.c, the v[100]
in sp_session_list's callers), so the source line said "claude (100)" while the
last four rows were dropped by pick_add without a word. SP_PICK_ROWS (128)
sizes the list on its own.

Evidence: tests/test_ui.sh builds a directory with 100 sessions, filters to the
oldest one and expects its row. With SP_PICK_ROWS 96 the check FAILs
("FAIL shows sess-1795000001-1-1"), with 128 it passes. make check: all tests
passed.
2026-11-22 23:39:57 +00:00
lotherk 7634c57872 engine: /open <id> no longer re-imports the newest foreign session
sp_engine_switch() copies the options the run was started with, and a run
started with --claude carries from_foreign. Two branches (a foreign
"claude:<id>" pick and the recovery path back to the session we had) reset
it, the branch for an ordinary session id did not - so a plain /open <id>
in a --claude run ignored the pick and imported the newest claude session
over it. With no plugin loaded that import failed and sp_engine_switch
returned -1 with *ep already NULL, which the caller then dereferenced.

from_foreign is now cleared once, before the branches, and again on the
recovery path (which would otherwise re-import instead of going back).

Evidence: tests/test_engine.c sets from_foreign="claude" on the template and
switches to an ordinary id. Without the fix it FAILs and segfaults (rc=139);
with it the test is green. make check: 21 suites, 0 failures.
tests/check_asan.sh: 45 binaries clean.
2026-11-22 23:19:12 +00:00
lotherk f5d63f6199 sessions: the foreign picker counts and dates what it lists
Three bugs in the /sessions picker, all of them found by review and all of
them visible on the screen:

- sp_engine_sources() hard-set every foreign source's count to 0, so the
  picker offered "claude (0)" while 82 rows were behind it. The count now
  comes from the same listing the picker shows.
- sp_foreign_sessions() hard-set each row's date to 0, so every foreign
  session drew as 1970-01-01. The plugin prints "%Y-%m-%d %H:%M" and the
  row's first column is parsed into epoch seconds.
- The foreign plugin's list tool queried with its configured default
  (limit = 25) no matter what the caller asked for, so asking for 100 rows
  returned 25 and a store with 290 sessions looked like one with 25. The
  caller's limit now reaches the SQL.

Proof: tests/test_foreignopen.c asserts count == 1 and mtime > 1600000000
against a fixture store; reverting either fix makes both checks fail. Live
over the socket, before: [('splinter', 100), ('claude', 0), ('opencode', 0)]
with mtime 0 on every row; after: [('splinter', 100), ('claude', 82),
('opencode', 100)] with mtime 1795387200. sqlite3 counts 290 opencode
sessions and 82 claude files, so the numbers agree with the stores.

make check: 21 suites, 0 failures. check_i18n: 229 keys in 3 catalogues.
2026-11-22 22:52:51 +00:00
lotherk f6211362cb sessions: /sessions is a picker over sources, foreign sessions included
`/sessions` printed a list of ids; the operator then typed the id into
/open. The list was the wrong shape for a thing you pick from, and the
foreign stores (claude, hermes, opencode) were not in it at all - their
sessions were only reachable through the model's import tool.

Now it is a picker in two steps: the sources first (`splinter` and every
foreign store that has something), then the rows of the chosen one. A
foreign row's id is "claude:<id>", which sp_engine_switch() already reads
as an import - so picking it loads and continues that session, exactly
like `/open claude:<id>` typed by hand.

The picker got one shared implementation while it was open: pick_run()
with a value/label list, a configurable title and two hint lines. /model
and /sessions draw the same way now instead of two copies that could
diverge on Esc, resize and the filter. One window is held across both
steps, so a quick double Esc leaves; with a window per step the second Esc
landed in a window that was already gone and the picker stayed open.

Over the socket the same two steps exist: `{"cmd":"sources"}` and
`{"cmd":"sessions","source":"NAME"}`.

Tested: make check, all suites green (test_engine, test_protocol,
test_ui against a real tmux pane, 229 i18n keys in three catalogues).
2026-11-22 21:32:31 +00:00
lotherk 2175263236 engine: /learn mines this folder's sessions for skills, memories and tasks
/learn is an engine command like /self-check, so it works in the TUI, in
-p and over the socket. Without an argument it hands the model this
folder's session list (newest first, with the recap line of each) and the
path of the conversation files, so it can read a session page by page with
read instead of firing dozens of session_search snippets. With an argument
it learns about that topic and the session list is context, not the task.

The prompt names the write tools the engine really has ('one ending in
skill_create, memory_add, page_write, task_create...'), taken from the
registry, because a live run showed the model hunting 'which memoryd' for
tools it was never given. When no write tool is registered it says so and
asks for a suggestion in the answer instead of inventing a call.

Proof: tests/test_engine covers both branches (no argument names a
session of the folder and a registered write tool; a missing write tool
is named as missing). 'make check' passes. Live against junction/beam-free
the model went from '54 session_search snippets, no write' to reading the
session file with read; the run stopped at my 900s timeout, no writes yet
- the prompt hint is in, the end-to-end write is still unproven.
2026-11-22 20:09:47 +00:00
lotherk f568f558d0 test_cli: an own cooldown dir, so a real quota file cannot bench the transport
A cooldown file for "cli" in ~/.splinter/cooldown (left behind by a real
Claude call) made the first 20 checks fail on main, unrelated to any
change: the transport was skipped before it ran. The test now points
SPLINTER_COOLDOWN_DIR at a fresh mkdtemp for the whole run.

Proof: before, tests/test_cli reported 31 failures on a clean main with
that file present; after, 'tests/test_cli: ok' and 'make check' passes.
2026-11-22 20:09:41 +00:00
lotherk bc0b9f22f9 gateway: the retry is announced in the chat, not into a screen queue
The engine's note callback pushes onto the screen event queue. A gateway has
no screen, so the queue was never read: five corrected tries five seconds
apart were twenty-five seconds of silence in Telegram, and the operator saw
nothing until the turn finally answered.

The gateway now installs its own note callback and sends the line into the
chat the turn came from. It is safe on the polling thread because the turn
runs there itself, not on a worker.

The two lines a broken call leaves behind were hardcoded English while the
transport retry was already translated; both keys are now in en/de/pt_BR.

Tests: test_gateway sends "kaputt", the fake answers with a tool call whose
arguments are not JSON, and the chat must carry
"kaputter Tool-Call, neuer Versuch in 0 s (1/5)" and still end with "fertig".
Counter-check: with the engine's own note restored the same run says
"FAIL a broken call is announced in the chat". make check green (273 s),
check_asan green over 45 binaries.
2026-11-22 17:31:36 +00:00
lotherk 082223af96 agent: a step that reports no usage does not empty the ctx meter
The guard was there since 16.11. ("keep the last known prompt size, or the
status bar drops to 0 after every tool call") but nothing tested it, so
t0429 stayed open on the one point that had no evidence.

usage_gap_send reports 1000 prompt tokens on the call that starts the round,
9000 on the next, and nothing at all on the answer. Without the guard
last_in becomes 0 on that answer; with it the meter keeps 9000 and the cache
figure 4000, while tokens_in still sums what was actually reported.

Evidence: make check exit 0 (45 binaries + 20 shell tests), tests/check_asan.sh
all 45 clean. Counter-check: with the old unconditional
`last_in = reply.tokens_in > 0 ? ... : 0`, test_agent fails on
last_in == 9000 and last_cached == 4000.

The other four points of t0429 are covered elsewhere and were verified:
the goal sidecar and /continue in test_session.c and test_engine.c, the
plain sidebar page in test_theme.c (flat light/dark: bg white/black, fg the
opposite, input on the same page), and sysinfo was dropped on purpose in
t0469.
2026-11-22 15:27:54 +00:00
lotherk d714efb16e agent: a broken tool call gets five corrected tries, then words
Konrad saw "agent: model sent malformed tool arguments" on the Telegram
daemon again and again. The retry existed, but it was useless: three
attempts in a single millisecond, each with the identical prompt, so the
model answered with the identical broken call. After the third the turn
died with an error nobody can act on, and the session lost the work.

Now:

- Five tries, five seconds apart (SPLINTER_RETRY_WAIT_MS still shortens
  it for the tests). The wait goes through retry_sleep(), so Ctrl-C does
  not have to sit it out.
- Every retry carries a correction as a user message: what was wrong,
  and what to send instead. A tool result without a call before it is
  refused by the endpoint, so it has to be a user turn.
- A call cut off by the token limit is a different fault from a call the
  model could not write. sp_reply grew a `finish` field ("length",
  "max_tokens"), filled by both the SSE parser and the non-streaming
  reply; the correction then asks for a *smaller* call instead of the
  same one the limit already truncated.
- After the fifth failed try the turn does not die: the model is asked
  for plain words ("say what you wanted to do, step by step"), and
  whatever it sends ends the turn as an answer. A call that arrives
  anyway does not run and is logged whole.
- The log line keeps the whole argument string, not 240 bytes of it -
  "mal gucken" means the operator can read what the model tried.

The tests were only rebuilt when their .c changed, so a new field in
struct sp_reply left them reading a different layout; that failure looks
like a broken test, not a stale object. $(TESTS) now depend on $(HDRS).

Evidence: make check exit 0 (45 binaries + 20 shell tests,
SPLINTER_RETRY_WAIT_MS=0). Counter-checks: with the old single-prompt
retry test_agent fails on bad_args_calls == 6 and on the correction
text; without the finish field cut_off_second carries "not valid JSON"
instead of "cut off by the".
2026-11-22 14:46:08 +00:00
lotherk 1781cdd478 session: session_search and session_list also read claude, opencode and hermes
The session plugin scanned only splinter's own sessions, so "what did we say
about X in this folder" was answered as if no other tool had ever run here.
Both tools now delegate to the foreign plugin's tools through the registry
instead of reading the three stores a second time, and stay usable without it
(fallback to splinter's own sessions).

foreign_search also promises a cwd in its schema and then threw it away
((void)only), so a search always ran over every folder. The filter is applied
for all three sources now.

Two silent losses in the opencode search: substr(data,1,20000) cut the JSON
mid-object, so 2973 messages (up to 15 MB) never parsed and were dropped, and
assistant messages carry their text in data.content[], not data.text, so
73706 of them were skipped even when short. The text is extracted in SQL now
and the whole row is read. Hermes cut its match at 400 bytes in the same way.

Test: tests/test_sessiontools.c writes a claude session into its own working
directory and expects the hit through session_search and session_list; both
fall without the delegation. tests/test_foreign.c covers a long opencode
message, an assistant message via content[], the hermes cut and the cwd
filter; every check was counter-checked against the old code. make check exit
0, check_asan.sh 45/45 clean.
2026-11-22 13:20:45 +00:00
lotherk f19fbf6ac1 cli: splinter -c --claude continues the newest claude session of this folder
The operator's claude ran into its limit mid-work; the session was too full to
continue there. The foreign plugin could already read and import it, but only
through a tool call inside a turn - there was no way in from the command line.

--claude, --opencode, --hermes and --from=NAME make the newest session that
tool ran in this directory the session of the run: it is imported before the
history is loaded, so the first turn already carries it. -c no longer fails in
a folder that has no splinter session yet; it falls back to "no session" and
lets the import decide. An empty placeholder session is removed again, whether
the import worked or not.

Repeating the call continues the same session instead of importing a second
time: sp_session_foreign() reads the foreign= marker back, so the work done in
splinter is kept. A second foreign_import into the same session replaces the
history rather than appending it twice (path_join built "id/.jsonl", so the
replace branch never fired).

Test: tests/test_foreignopen.c builds a claude fixture under its own HOME and
covers import, idempotency, replace-not-append, the empty placeholder and a
folder with no foreign session. make check exit 0, check_asan.sh clean.
2026-11-22 13:20:45 +00:00
lotherk 15d6eb1885 sse: a whole tool call per delta is a call of its own, not a fragment
A bridge that replays a non-streaming message may send one complete call per
delta and no index with it. call_slot() treated every index-less entry as the
next piece of the last call, so three finished argument objects were glued
into one string and the round died with "agent: model sent malformed tool
arguments" - the operator saw that on olivia in telegram, often.

An index-less lone entry now starts a new call when the last slot already
holds a complete argument object. Fragment-by-fragment streaming keeps its
behaviour: a partial object is not complete, so it still lands in the slot it
belongs to.

Test: tests/test_sse.c feeds exactly the three-delta shape from the logs and
expects three calls with their own arguments; without the fix it is 1 call
and the test fails. The indexed two-call case and a call split over three
deltas both still pass. make check exit 0, check_asan.sh 45/45 clean.
2026-11-22 13:20:10 +00:00
lotherk 139f5ae072 compact: judge the local bytes, so a resume can always compact
Automatic compaction was keyed only on stats.last_in, the prompt size the
provider reports with usage. A resumed session starts at 0, and a provider
that reports no usage leaves it at 0 - the session outgrows every endpoint's
window, the first request is refused, no usage arrives, and every later
resume fails the same way. Measured on 2026-11-22: a 9,095,724-byte session,
ctx=2,286,261 at junction, 503 no_endpoint_available on every retry.

The conversation bytes are there before anything is sent; the same four bytes
per token the target already uses are the second trigger.

tests/test_compact_resume.sh: a ~300 kB session, one turn after --resume; the
first request must be compacted. Counter-proof with the old agent.c: 302
messages, 321,087 bytes.
2026-11-22 11:34:21 +00:00
lotherk de1131cdf5 docs: /compact mid-turn is queued, not refused
The steering paragraph still listed /compact among the commands that answer
"not while a turn runs". Since 9e2a2e6 it is remembered and applied when the
turn ends.
2026-11-22 10:26:06 +00:00
lotherk a00534cf6c serve: a second client is told why, not left hanging
`--serve` holds one engine, so one client talks to it at a time - that part is
deliberate. What was not: the second client connected into the listen backlog
and then waited for a greeting that could not come until the first one left.
splinterctl printed nothing and hung; --attach gave up 10 s later with "no
greeting from the backend", which names the wrong cause.

The accept is non-blocking now and a client that arrives while the engine is
taken is answered at once: an error event with the reason, then a shutdown of
the write side. That reads on the other end as "another client is attached:
one conversation runs one turn at a time". Descriptors are drained before the
close, or the RST would eat the message the client has not read yet.

Two smaller ones on the same path:
- --attach reconnects on a broken connection; it now carries the server's error
  text through instead of replacing it with "no greeting".
- a client that reads nothing is not waited for forever: a greeting timeout
  turns a silent server into a message instead of a hang.
2026-11-22 10:26:06 +00:00
lotherk a48a2deec5 foreign: an imported tool call is a JSON array, not a run of objects
The importer collected tool calls by concatenating the objects it found, so a
source that recorded two calls handed the model "{} {}" where the API expects
"[{}, {}]". One call per assistant message is the common case and hid it.

The calls are now kept as the array they were read as, and their results are
kept with the same call ids, so the call/result pairing a provider insists on
survives the import.
2026-11-22 10:26:06 +00:00
lotherk 5ad5768e6a prompt: the input line has a cursor (Ctrl-A/E, Left/Right, Delete)
The prompt only appended: Ctrl-A, Ctrl-E, Left and Right fell through the
printable-key path and vanished, and fixing the first word of a sentence
meant retyping it. One struct editline now holds buf/cap/len/cur (bytes,
always on a UTF-8 boundary) and both prompts edit with the same keys.

Two bugs surfaced with it:
- draw_prompt_cur guarded the caret with 'caret > 0', so caret == 0 (the
  start of the line) was drawn as the end of the text.
- the swarm block reset ed.cur to ed.len on every loop tick, which undid
  every cursor move right after the key that made it.

The steer line of a running turn gets the same editor and a window that
follows its caret, instead of cutting the text at the right edge.
2026-11-22 10:26:06 +00:00
lotherk ca81d297c2 interview: the "never do this" example no longer says to skip commits
The hint under interview.q.never read "e.g. no commits without a request".
Every new profile was nudged to carry the old rule that 2026-11-22 replaced:
finished, tested work is committed and pushed without being asked. The
example now names something that stays true ("never write to /home/carol,
no secrets in logs") instead of a rule that was retired.
2026-11-22 08:31:24 +00:00
lotherk 6358fcf42a openai: every streamed turn asks for usage, so compaction can fire
openai_stream passed the request options only when c->have_gen was set,
and only openai_server.c (splinter as a server, relaying a client's
request) ever set it. A normal turn therefore sent no
stream_options.include_usage, a provider that follows the OpenAI
contract returned no usage, reply.tokens_in stayed 0, last_in stayed 0,
and compact_threshold could never fire - a session grew monotonically to
250k tokens with the threshold at 128000.

The transport now always asks, with a local option block; the gateway
path keeps its caller's settings. Verified against a strict endpoint
that sends usage only when asked: before the fix two turns went 82->86
messages with no compaction, after it the second turn is 8 messages and
21 KB.

tests/test_usage_request.sh starts that strict endpoint (its usage is
emitted only when the request opts in) and asserts the request carries
the option and that the second turn is compacted. It fails without the
transport change.
2026-11-22 08:25:42 +00:00
lotherk 9e2a2e6156 compact: a /compact typed mid-turn is queued, not refused
sp_engine_input answered ui.command_busy for every command while a turn
ran, and /compact was one of them. That is the worst moment to refuse it:
a turn is what makes you look at the context size. Measured on a session
whose operator had typed /compact three times against a 253 KB request
and never saw it run - the refusal reads as "already done" and nobody
repeats the line once the turn is over.

The conversation belongs to the turn worker, so compacting inline would
race its appends. Keep the token target instead and apply it in
turn_thread after the pending model switch, before the engine goes idle;
a foreign turn (the Telegram daemon's) gets the same at
sp_engine_turn_end. The new keys ui.compact_nohost and
ui.compact_pending are in the .msg sources, which is what catalogs.c is
generated from.

tests/test_engine.c runs a real turn and types /compact while it runs;
without the turn-end call it fails at `applied`.
2026-11-22 08:25:36 +00:00
lotherk 678e2814e6 engine: the plugin host exists even when no plugin is configured
The host is what carries the registry to the core compactor. A plugin-less
run had none, so a conversation over max_bytes was refused instead of
compacted - the compaction that would have saved it could not be reached.
The fix landed in f712088; this is the check that keeps it.
2026-11-21 21:27:25 +00:00
lotherk fa16bfd0a9 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.
2026-11-21 21:26:43 +00:00
lotherk 87f5987a46 embed: a session is searchable by meaning, with no model and no key
Compaction drops most of a session out of the window, and the only way back
to it was a substring search. That answers "where does this word stand",
not "what did we say about this".

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

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

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

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

/status gains a row for it (index: N messages, lags by M).
2026-11-21 21:26:22 +00:00
lotherk f7120882fa sessions: a resumed session is the whole transcript, not a chat log
A session file was written as if it were a chat: role and text, nothing
else. Reading it back kept "user" and "assistant" and dropped everything
else - and nearly every line of an agent transcript is an observation.
Measured on three real sessions: 21 of 1507 messages came back, 8 of 1356,
3 of 317. --resume then sent 1% of the conversation and the model had no
idea what it was continuing.

Three writers had to change with the loader:

  - A turn that asked for tools wrote no line at all (agent.c only wrote
    when ncalls == 0). It now goes out with its tool_calls, and each result
    with the name of its tool and its call id; a provider rejects a tool
    message without them.
  - {"role":"user","text":""} came from the steer path and showed the model
    a blank human turn it answered. sp_session_append_rec writes nothing
    when text and calls are both empty.
  - A record from the old format has no name and no call id. It is paired
    with the next unanswered call of its pending assistant turn, or given a
    synthetic one (recovered-N). Dropping it is what emptied every resume;
    keeping it unpaired is what a provider answers with 400.

The same pass gives the core its own compactor (compact.c): a thread digest
- one line per dropped message, OPERATOR: 800 chars, assistant: 300, tool
result 160 - so the model keeps the story, not a count. lcm stays a plugin
that runs after it; sp_core_compactor() is the fallback only when no plugin
registered one, because running both eats the conversation before lcm sees
work to do.

Two bugs fell out of the same area:

  - The plugin host was only built when a plugin was configured, so a
    plugin-less run had no compactor at all: over max_bytes the turn was
    refused instead of compacted (90 KB session, budget 8000, "nothing
    sent").
  - lcm walked *forward* past tool results at the tail boundary, which
    silently shrank the tail: a turn with two results kept four messages
    where keep_tail says six. Walking back to the assistant that carries
    the call keeps six and no orphan.

And the .meta sidecar is shared now: the core rewrote it with only the keys
it knew, so anything a plugin put there was gone on the next open. It
carries unknown lines through (extra[8][160]), which is what lets a plugin
mark a session in the core's own file.

Tests: tests/test_corecompact.c (10 checks, no plugin), the resume cases in
tests/test_session.c, and the tail-size check in tests/test_compactor.c.
Each was seen red on the old code before it was green on the new.
2026-11-21 21:25:51 +00:00
Konrad Lother 226fff3461 interview: the model opens the conversation; light is the default
--interview opened the chat and then waited: the system prompt told the model
to interview the operator, but nobody sent a turn. The UI now sends the same
kickoff the Telegram daemon sends, and with piped input --interview runs that
one turn instead of waiting for a profile.

The default theme is the flat light one, and the language is English unless a
config or SPLINTER_LOCALE says otherwise - the desktop's LANG no longer
decides what the tool speaks.
2026-11-20 16:45:36 +00:00
Konrad Lother 602c8fbf6c transport: the Accept header follows the mode
junction reads an Accept naming text/event-stream as a request to stream, so
a non-streaming call got "data: {...}" back and failed with "reply is not
JSON" on models whose answer goes through its review path. Ask for a stream
only when this call is one.
2026-11-20 16:45:36 +00:00
Konrad Lother fb877e263f sessions: state root vs session root, sessions under ~/.splinter/sessions
Add state_dir (config/token/commands/USER.txt, default ~/.splinter) and
default session_dir to <state>/sessions.  Telegram uses
<session>/telegram, so CLI and gateway sessions are separate trees.
Keep --session and the old configs working.  Also carries the pending
apply_selection model-pointer fix from the n95 tree.
2026-11-20 15:07:36 +00:00
Konrad Lother 9a6b282388 telegram: restore SPLINTER_TG_MARKDOWN after a status notify 2026-11-20 10:02:11 +00:00
Konrad Lother 6b51f48335 telegram: own session tree and a status channel
The daemon writes its sessions under <state>/telegram, so a CLI -c in
the same directory never picks a gateway conversation and /new in the
chat never creates a file a CLI would resume.  Command scripts and
USER.txt stay in the base state dir; only the session files move.

Add --notify TEXT ("-" reads stdin) and telegram { status_chat = ID }
to send status and cron messages to the status chat.  The daemon
announces its start there, and the cron bridge can use the same path.
2026-11-20 09:59:40 +00:00
Konrad Lother 5fd8f76870 providers: models= keeps a provider's served list to the local models
A provider block may name the only models it offers (a bracket list in
the block syntax). sp_provider_served() then filters the endpoint's
/v1/models, so --model-list and /model's probe show only those ids.
The n95 junction provider uses it for qwen3.6-35b-checked,
qwen3.6-35b and qwen3.8-27b, not the cloud models junction also serves.
2026-11-20 06:57:11 +00:00
lotherk 37d038f716 telegram: /status and an inline menu with /model
The command menu now carries /status and /menu; /model was already there. The
inline keyboard under /menu, /status, /help and /start has Status, Model, New
and Help. Status shows the TUI's facts (session, model, endpoint, agent,
tokens, steps, limits, compaction, meter); Model opens the provider picker,
which now has a Status button back. The bot menu button is forced to the
command list, so the commands show even if an older bot had another button.

The live config lists the local models (main/checked, plain, bench35, bench4b,
bench9b) so /model has more than one button; the last two need their
containers running.

tests/test_gateway.sh: /status, the /menu callback, the buttons and the
command list. tests/fake_telegram.py: the status callback and
setChatMenuButton. make check: all tests passed. check-asan: 41/41 clean.
2026-11-19 15:20:20 +00:00