Commit Graph
267 Commits
Author SHA1 Message Date
lotherk df6bfa9cfb telegram: /cancel ends an open ask question instead of answering it
The hint under the question promised "/cancel cancels the turn", but the
gateway knew the command nowhere -- a /cancel was handed to the model as the
operator's answer and the turn went on with that as its decision. The gateway
runs its turns on sp_agent, so there was no cancel flag the chat could set.

tg_ask now takes /cancel (and "cancel", case-blind) as the way out: it sets
tg_cancelled, says so in the chat (new key ask.cancelled, de/en/pt_BR) and
returns -2, which the tool reports as "no answer: the operator cancelled".
gcfg.cancel points at that flag -- the agent already reads cfg->cancel
between steps -- and it is cleared at the start of every turn so a cancel
ends the turn it was meant for.

Test evidence: tests/test_gateway.sh grew a case where the fake operator
replies /cancel to the question. Proven red against the old code (2 FAILs:
"/cancel is acknowledged in the chat", "/cancel does not reach the model as
the answer") and green on the fix. The existing gateway case is unchanged
(FAKE_ANSWER defaults to ok). test_gateway: ok, make check green (336 s).
2026-11-24 09:00:59 +00:00
lotherk 6debe213c3 ask: the wait for an answer is the operator's to set, and a late answer is refused
The 900 s wait was not the defect -- a person reads and thinks. Being hard
coded was: a run with no operator attached (an older protocol client that
does not know SP_EV_ASK, a script) lost the turn for fifteen minutes and
nobody could shorten it. Measured before the change: a client that ignores
the event saw the question and then no turn for 10 s.

sp_ask_wait_s() reads $SPLINTER_ASK_TIMEOUT, then ask_timeout from the
config, then SP_ASK_WAIT_S = 900. No upper bound: how long a turn may wait
is the operator's call. Consumers: engine_ask, tg_ask.

protocol.c also dropped sp_engine_answer's return value, so an answer that
arrived after the question was gone (wait expired, turn cancelled) looked
accepted. It now reports "no question is pending", as steer already did.

Test evidence:
- tests/test_ask_timeout.sh (new, wired into make check): with
  SPLINTER_ASK_TIMEOUT=3 the turn returns in 3 s with the "no answer"
  observation instead of parking. Proven red against the old code (env
  ignored: 5 FAILs, the client got no turn at all) and green on the fix.
- ask_timeout in the config file takes effect too: measured 3.1 s against a
  running --serve, so the docs line is not a claim.
- sp_ask_wait_s() edge cases: unset/0/-5/abc -> 900, 1 -> 1, 42 -> 42,
  999999999999 -> clamped.
- make check green (336 s), make check-asan and check-tsan clean (46
  binaries each).
2026-11-24 09:00:49 +00:00
lotherk 181b2c0638 ask: the model can put a question to the operator, in every front end
The `ask` tool asks and the answer -- or "nobody answered" -- becomes the
observation. Read class: it changes nothing on the machine, and the authority
is the operator, not a gate.

Front ends: the chat draws a dialog (options to pick, typed words still count),
the protocol carries it as an `ask` event and an `answer` command, MCP returns
it from splinter_say and resumes with splinter_answer, the Telegram gateway
sends it as a message and takes the next message from an allowed user.

What the review of the WIP found, and what this fixes:

- -p hung for the full 900 s ask wait: sp_engine_prompt installed engine_ask,
  but nobody polls events on the synchronous path. cfg.ask now stays NULL
  there, so the tool answers at once with "nobody can be asked here".
  Measured: 3 s instead of 900 s (was rc=124 after 20 s).
- splinter_say over MCP hung the same way, because tool_say only looked at
  st.waiting. It now looks at st.asking and returns the question; the client
  timed out at 15 s before, and the turn was lost.
- protocol.c read the question buffer uninitialized when sp_engine_ask
  returned 0.
- turn_ask answered nothing when the window could not be opened, which parked
  the turn for the full wait.
- pick_run computed the list height without the question's rows, so the
  highlighted row scrolled out of the window (reproduced: after nine Downs no
  ">" row was on the screen). pick_draw and pick_run now share pick_listtop().
- the Telegram gateway was dead for this tool: it runs its turns on a copy of
  e->base, where ask was never set, so the model was told "nobody can be
  asked" while the operator sat in the chat. New tg_ask, verified against a
  running daemon and covered in test_gateway.sh.
- tests/test_ask_ui.sh was untracked and not in make check, so it never ran.

A2A keeps no ask channel on purpose: there an approval pauses the task into
INPUT_REQUIRED, and the ask signature cannot express a pause -- saying
"nobody can be asked" is the honest answer there.

Tests: make check green (327 s), including the new test_ask_mcp.sh and
test_ask_ui.sh, both wired into make check. test_ask_mcp.sh was verified to
fail against the unfixed code (client times out, no result written).
make check-asan: 46 binaries clean. make check-tsan: 46 binaries, no races.
2026-11-24 07:57:35 +00:00
lotherk 00bedb4e32 swarm: the socket exists only with --swarm, and only while a member runs
Two things were wrong with .splinter-swarm.sock. Every chat bound it, wanted
or not, so a shared working directory collected a leftover from every session
and the next start that found one sat on "[swarm locked]" because nobody
answered on it. And the master removed the file on its way out even when a
member was still running, which left that member on a path that was gone.

Now the fleet is opt-in. Without --swarm nothing binds or joins the file;
with it, the file lives exactly as long as the fleet does, whatever order the
members leave in.

- main.c: --swarm is a flag; eo.swarm requires it (plus --chat, no --serve,
  no --daemon, no A2A/MCP/delegate).
- swarm.c: join_or_bind() is the one place that decides master or slave, used
  at startup and again on takeover. A slave whose master says "bye" or whose
  connection just ends (SIGKILL) takes the fleet over: bind, or join whoever
  was faster. A leftover file with no listener is removed there and rebound,
  because a refused connect is proof nobody answers.
- master_close() removes the file only when it is the last member. The peer
  check reads the sockets instead of trusting the cached flag: a peer that
  exited is only visible as EOF on read.
- swarm_emergency_unlink() (SIGTERM/SIGHUP) keeps the file while a peer is
  live. A handler may not walk the peer table, so the master keeps a
  sig_atomic_t count of live peers for it.

Tests, all against the real binary and the real signal path:
- test_swarm.c: master leaves first, survivor takes over and the file stays;
  hard-killed master (EOF, no bye), survivor cleans the leftover up; the
  signal cleanup alone leaves the file for a live member; an unowned file is
  still never deleted. Mutation-checked: forcing master_close to always
  unlink, and dropping the peer count from swarm_emergency_unlink, each turn
  the suite red.
- test_swarm_socket.sh (new, in make check): through tmux, --chat without
  --swarm creates no file at all; --chat --swarm creates one that accepts a
  member and is gone after Ctrl-D and after SIGTERM; two members share one
  file that outlives the master and goes with the last one; a SIGTERM-killed
  master does not take the fleet from the survivor. Mutation-checked: making
  the fleet unconditional (the old eo.swarm line) turns it red.

make check: all tests passed. check_asan.sh: all 46 test binaries clean.
2026-11-23 20:19:33 +00:00
lotherk 719c436f5c pkgsrc: build from the source tree, no archive
The recipe set DISTFILES and built from a tarball that tools/ext-dist.sh
made, and its distinfo had to be regenerated after every commit.  It now
does what pkgsrc itself does for a package that lives in a tree (net/fetch,
pkgtools/pkg_install): DISTFILES= # empty, do-extract fills WRKSRC.

The copy is made by tools/ext-extract.sh (called from do-extract), not by
cp -R: a work directory is extracted once, so a plain copy would keep the
files of the commit it was extracted from.

Verified: bmake -C pkgsrc/misc/splinter package built splinter-0.1.tgz in
build/packages/All with no distinfo present.
2026-11-23 19:50:20 +00:00
lotherk 4fc7614cc5 builtin: tools_root - the file tools stay inside one directory
The five file tools act with the rights of the process. The authorization
classes say *whether* a tool may run, never *where*: a model with mutate rights
- or a prompt-injected one - could write ~/.ssh/authorized_keys or the config
that names the plugins this harness loads.

core { tools_root = ~/src } closes that. Empty (the default) means no boundary,
so an existing setup is unchanged.

What makes it hold, rather than look like it:
- every path is resolved before it is used, and the resolved path is what the
  tool then opens (realpath for existing paths, resolve_target for one that
  does not exist yet, so a dangling symlink cannot be followed out);
- search resolves every entry it recurses into: stat() follows a directory
  symlink, so guarding only the argument left a door open (found and fixed in
  this change, the test went red without it);
- the root is resolved once at startup, and a root that does not exist is
  refused with the path in the message instead of matching nothing;
- run cannot be fenced (a shell opens any path); it starts in the root, and a
  failed chdir is written into the tool's observation, not the operator's
  terminal.

Verified: an escape by absolute path, by ../.., by a symlink inside, by a
dangling symlink, and through search's recursion are all refused in the live
engine path (scripted model, tool call in the session log); the same tree
inside the root still reads; without tools_root everything behaves as before.
Each guard was removed once to watch the test go red. tests: test_builtin,
test_config, test_secrets ok; make check: all tests passed; check_asan: all 46
binaries clean.
2026-11-23 16:55:49 +00:00
lotherk 6166acfdea config: a leading ~ is the home directory
The shipped --init-config template suggests "session_dir = ~/.splinter" and
"tools_root = ~/src". Nothing expanded "~": no shell is involved in reading
the file, so the first created a directory literally named "~" in the cwd and
the second made the tool fence match nothing.

set_path() now expands a leading "~/" (or a bare "~") for the settings that
name a place on disk: session_dir, state_dir, skills_dir, tools_root. A
"~user" form is left alone rather than half-guessed.

Verified: the template with both lines uncommented starts, writes its sessions
under $HOME and leaves no "~" directory behind; tests/test_config covers the
expansion (3 checks red without it, green with it); make check: all tests
passed.
2026-11-23 16:55:49 +00:00
lotherk 1a17d25659 pkgsrc: PLIST carries the three plugins added since it was written
cache.so, foreign.so and session.so were built into .destdir but not listed,
so the package check stopped with 'these files are not in the PLIST'
(measured 2026-11-23, cross release).  Verified against the PLUGIN variable:
19 files on both sides, diff empty.
2026-11-23 14:10:33 +00:00
lotherk 1c4fdf0a55 make: link the library by file, not through -L
A package build passes -L=/usr/pkg/lib ahead of anything this Makefile can
append, so -lsplinter found the copy installed by the previous release.  A
function added to engine.c the same day was then 'undefined' at link time
(2026-11-23, cross release).  The library is named as a file now, and carries
a SONAME, so the installed binary records libsplinter.so and not a build path.

Test: make install with LDFLAGS=-L/tmp/oldlib (the 22.11 library without
sp_engine_sources) links and runs: 0 undefined references.
2026-11-23 13:42:13 +00:00
lotherk 8f030af8c2 pkgsrc: CURSES_DEP is passed empty, so the vendored tree is not built
The package links the base system's curses (CURSES_LIB), and the Makefile
defaults CURSES_DEP to CURSES_LIB for the vendored tree -- an empty
assignment keeps that default from applying.
2026-11-23 13:31:37 +00:00
lotherk 85556ce889 make: -L. travels with -lsplinter, ahead of a package's -L
A pkgsrc build passes -L=/usr/pkg/lib before -L., so `-lsplinter' found
the libsplinter.so that an earlier package had installed and ignored the
one just built.  On the cross build this stopped `splinter' with
"undefined reference to sp_engine_sources", a function added to engine.c
that morning: /usr/pkg/lib/libsplinter.so was the file of 22.11 22:26
(build/logs/release-2026-11-23l-cross.log:78).  The tree's own build was
never affected, only the package build -- which is the one that ships.

SPLLIB carries -L. and -l together and the binary's link puts it before
$(LDFLAGS).  72 link lines changed; LDFLAGS moved behind the library for
splinter and splinterctl.

Verified: make clean && make -j8 rc=0, ./splinter --version prints the
stamp; with LDFLAGS=-L/tmp (holding a stale libsplinter.so) the build
still links, 0 undefined references.
2026-11-23 13:31:37 +00:00
lotherk 9b2fee66a2 tests: valgrind-clean -- free the registry, NUL where the read stopped
Valgrind over the test binaries found two test-side defects, no
production path:

- test_skills never called sp_registry_free(), so the 448 bytes
  sp_registry_add() copied for the three skill tools were reported as
  "definitely lost" on every run. Freed now.
- test_providers read the /connect drop-in into a 1024-byte stack buffer
  and NUL-ed only the first and last byte, so strstr() walked through
  uninitialised bytes between them ("Conditional jump or move depends on
  uninitialised value"). Terminated at the read length instead.

Both runs are clean: valgrind tests/test_skills -> 0 errors, exit 0;
valgrind tests/test_providers -> 0 errors, exit 0. make check: all tests
passed. tests/check_asan.sh: all 46 test binaries clean.
2026-11-23 13:22:14 +00:00
lotherk 35d4e1bc53 make: CURSES_LIB/CURSES_DEP -- the package build links the base curses
The pkgsrc recipe passes CURSES_LIB=-lcurses -lterminfo and CURSES_DEP=
to get NetBSD's own curses instead of the vendored tree, whose nbperf and
host_tic have to run while building -- a cross build cannot run them
(it compiled nbperf with the target compiler and got 'nbperf/nbperf:
not found', build/logs/release-2026-11-23k-cross.log:91).  The Makefile
ignored both and always built vendor/netbsd-curses.

Verified: default build still builds and links the vendored tree (make
clean && make -j8 rc=0, splinter runs); with CURSES_LIB='-lcurses
-lterminfo' CURSES_DEP='' no GNUmakefile is invoked and
src/frontend/curses.c compiles against NetBSD's curses.h (rc=0).
2026-11-23 13:13:28 +00:00
lotherk f7158d34d2 embed: a failed batch alloc frees the vectors it already made
The remote branch allocates vec[0..n) first, then a texts[] array. When that
calloc failed the function broke out with the vectors still held.

Test: make check (all tests passed), tests/test_embed ok
2026-11-23 13:02:37 +00:00
lotherk 3b0de63e06 protocol: the model list carries its tag too
The listings got a request tag so a late answer could not be read as the
next request's; `models` was left out. A probe that outlived the client's
15 s timeout stayed in the socket and the following plain `models` read it
as its own answer - /model then drew the endpoint's models where the
configuration was asked for, and the picker's second request drew a stale
list.

Test: tests/test_remote_list.c, fake server answers the first models
request twice and never the second. Before the fix the second call
returned 2 rows (FAIL nm == 0), after it 0. Full suite green, ASan clean
on the 46 test binaries.
2026-11-23 12:55:04 +00:00
lotherk 7fecc7d153 curses: le16enc/le32enc only where the libc has none
NetBSD's <sys/endian.h> defines le16dec, le32dec, le16enc and le32enc, and
the vendored replacement redefined them -- "redefinition of 'le16enc'",
which stopped the cross build at tic/tic.o
(build/logs/release-2026-11-23i-cross.log:94).

Test: x86_64--netbsd-gcc -std=gnu11 -I. -I./libterminfo -I build/obj/destdir.amd64/usr/include -c tic/tic.c -> rc=0.
2026-11-23 12:52:10 +00:00
lotherk 4ff2844955 main: a port that is not a port is refused, not guessed
atoi() took anything on --mcp-listen-port, --a2a-listen-port and
--openai-listen-port: "abc" bound port 0 (a random port the operator was
never told) and "-5" bound 65531. Both started a server on a port nobody
chose and said nothing.

port_arg() parses with strtol, requires the whole string, and refuses
anything outside 1..65535, naming the option and the value.

Test: tests/test_args.sh, new, in make check. Six bad values are refused
with the reason; a valid port still starts the gateway and says which one
it took. With the check reverted the test reports 6 failures, with it
"test_args: ok". make check: all tests passed.

docs/splinter.1: the two documented port options say so.
2026-11-23 12:37:42 +00:00
lotherk 0fc81398dc protocol: a late answer cannot answer the next request
The listings were matched to their request by kind alone. A server slower
than the client's 5 s timeout left its answer in the socket, and the next
request of the same kind read it as its own: the /sessions picker drew one
source's sessions under another source's name. Seen live on 2026-11-22
against a --serve instance.

A request may now carry "tag":N, the server echoes it in the event that
answers it, and the client drops an event whose tag is not the one it waits
for. Without a tag both sides behave as before.

Test: tests/test_remote_list.c has the server echo the tag and send the
first sessions answer twice. With the tag check removed it reports
"the unanswered request still drew 2 row(s): erste zweite" and three FAILs,
with it green. make check: all tests passed.

Also in here: pick_match stops at SP_PICK_ROWS like pick_add does (the two
caps are the same constant, the write was only safe because of that).
2026-11-23 12:37:42 +00:00
lotherk d0a3c484ef curses: the vendored fpurge only where the libc has none
NetBSD declares fpurge() in <stdio.h>, so a static definition in the vendored
libcurses contradicts the prototype and -Werror stops the cross build
(static declaration of 'fpurge' follows non-static declaration,
build/logs/release-2026-11-23h-cross.log:21830).  FreeBSD was the only libc
the guard knew about; the four BSDs and macOS all carry the call.

Test: x86_64--netbsd-gcc -std=gnu11 -I. -I./libterminfo -I build/obj/destdir.amd64/usr/include -c libcurses/tty.c -> rc=0, no errors.
2026-11-23 12:35:14 +00:00
lotherk f7c374bcbb embed: <signal.h> for kill/SIGKILL
embed.c calls kill(pid, SIGKILL) to stop a child that outlived its request,
without the header that declares both.  gcc -Werror=implicit-function-declaration
stops the build on the NetBSD target (build/logs/release-2026-11-23b-cross.log:
embed.c:726).  Linux libc pulls signal.h in through another header, so the
build on the build host never saw it.

Test: make against the NetBSD sysroot headers, rc=0
2026-11-23 11:35:58 +00:00
lotherk 91f0136e9d theme: colours as bytes, not as a compound literal in memcpy
NetBSD's ssp/string.h defines memcpy() as a three-argument macro, and the
preprocessor counts the commas inside a braced literal as arguments of the
macro: 'macro "memcpy" passed 5 arguments, but takes just 3'.  That is
what stopped misc/splinter in the cross build of make release
(build/logs/release-2026-11-23.log:21775, src/backend/theme.c:335).

Test: gcc -fsyntax-only -Werror against build/obj/destdir.amd64/usr/include
(NetBSD headers) passes; a clean native make -j8 here builds the binary and
./splinter --version answers.
2026-11-23 11:12:33 +00:00
lotherk 44f457b68d server: no tool child inherits a listening socket
The `run` tool forks /bin/sh with the server's descriptors open. A command
that left something in the background ("nohup sleep 300 &") kept the LISTEN
socket of the A2A server alive after splinter exited: the port stayed bound
and the next start died with "Address already in use".

Found by starting a background child from a tool, killing the server, and
watching the port: `ss -ltn` still listed it, the inode matched the server's
listen socket.

The listening and the accepted sockets now carry FD_CLOEXEC in a2aserver,
mcpserver, openai_server and swarm. protocol.c already did this.

Test: tests/test_a2a_server.sh starts a background child from the run tool,
kills the server, and checks that the port is free and that a second start
does not report "Address already in use". Without the fix both checks fail;
with it, and under ASan (46 test binaries), they pass.
2026-11-23 11:12:04 +00:00
lotherk 15fc06c8bf a2a: the Host header goes into the agent card escaped
The card is built with sp_buf_printf and put the Host header straight into
the url string. A Host of

  127.0.0.1","evil":"x

produced

  "supportedInterfaces":[{"url":"http://127.0.0.1","evil":"x/a2a",...

which is valid JSON with an extra key of the caller's choosing in an object
that ought to hold only the three interface fields. Every other client
value in this file already goes through sp_json_escape (see put_ids); this
one did not.

Test: tests/test_a2a_server.sh asks for the card with that Host and asserts
supportedInterfaces[0] carries exactly url/protocolBinding/protocolVersion
and a url ending in /a2a. Red before (extra key), green after; live curl
against the built binary shows the quote escaped.
2026-11-23 10:37:03 +00:00
lotherk 030f1be0bb leaks and double getenv: typing thread, program_found
typing_thread() returned NULL with url/reply already built when a later
sp_buf_init() failed - a small leak, but on a thread that outlives the turn
and is never reclaimed. It now leaves through one exit that frees all four.

program_found() called getenv("PATH") twice; one read is the whole truth.
2026-11-23 10:23:37 +00:00
lotherk 4f7255548d time: an unrepresentable time is "?", not an uninitialised struct tm
Four places formatted a time with strftime(localtime_r(&tt, &tm)) and
threw the NULL away. When localtime_r cannot represent the value - a
cooldown file can hold anything - tm is untouched and strftime formats
whatever the stack held: the operator read a limit that lifts at
"219250468--1414812756--1414812757", and a NULL deref in the die-hard case.

agent.c, engine.c, session.c and plugins/cli now check the return and fall
back to "?", the answer the foreign plugin already gives for a time it does
not know.

Found by review; the strftime call site is the same shape in all four.
2026-11-23 10:23:29 +00:00
lotherk 407f073ae3 delegate: a reset 292 billion years out is not a reset
"ready_at=9223372036854775807" in a provider's limit text was parsed with
strtol, stored as a cooldown and honoured: choose() then skipped that
delegate on every call and said nothing about it. On machine here that
would have wedged the delegate for good, from one unlucky answer.

A reset beyond LIMIT_MAX_AHEAD (370 days) is not a reset, so sp_limit_parse
drops it and the default one-hour bench applies. sp_cooldown_until does the
same with the file: it is plain text in a directory other runs can write,
so a value that is not a plausible time is not a bench either.

Test: tests/test_delegate.c feeds the absurd ready_at and asserts the bench
stays within two hours, a plausible ready_at is kept exactly, a cooldown
file holding LONG_MAX and a text line reads as no bench, and a real
sp_cooldown_set is still honoured. Red before the fix (until <= now + 2h,
sp_cooldown_until == 0), green after.
2026-11-23 10:23:17 +00:00
lotherk 4b4d822188 tgmd: an "&" with no ";" behind it is text, not the head of an entity
sp_tgmd_next() could return 1 with a piece of zero bytes and the cursor
where it was. The sender runs `while (sp_tgmd_next(...) > 0)`, so that
piece was an endless loop: telegram never sent the answer, never returned
and the turn hung.

The cause is safe_cut(): it walked back from the cut, saw a '&' and moved
the cut in front of it, assuming an entity. An "&" that no ";" follows (a
lone ampersand at a piece boundary) therefore cut at offset 0 every time.

entity_at() now only treats "&" as the head of an entity when a ";" closes
it within the 10 bytes an entity can take, and a cut that would come out
empty sends the entity whole instead of nothing at all.

Test: tests/test_tgmd.c check_no_stall() feeds 13 lone-ampersand shapes at
three limits and asserts each piece either grows the cursor or carries
bytes. Red before the fix (the guard runs out, cur.pos != cur.len), green
after. Fuzz: 20000 random inputs through render+chunk, 0 stalls; ASan/UBSan
clean; valgrind clean on test_tgmd.
2026-11-23 10:23:11 +00:00
lotherk 1b5b4fab27 provstate/providers: a refused write still closes its stream
Both writers chained the close: `fflush() || fsync() || fclose()` in
write_state() and `write_all() || fclose()` in save_dropin(). Short-circuit
evaluation meant a failing first call skipped fclose(), so every refused
write leaked one descriptor. A daemon that answers 429s for hours, or one
on a full disk, reaches EMFILE - which reads like a network failure, not
like a file one.

Measured on the real code path with RLIMIT_FSIZE:
  provstate  8 refused writes: 7 -> 15 open fds (8 lost), now 7 -> 7
  providers  (drop-in padded past one stdio buffer, else the write stays
             in the buffer and only fclose sees the failure) 7 -> 15, now 7 -> 7

Both tests fail without the fix and pass with it; make check all green
(21 suites), check-asan clean over 46 binaries.
2026-11-23 09:33:58 +00:00
lotherk a5665a4dcc attach: a timed-out listing is empty, not the previous one
The picker's two remote calls cleared their counters only when the
answer arrived. A served engine that did not answer within the 5 s
deadline therefore left the last answer in place, and /sessions drew
another folder's - or another source's - rows as the ones that were
asked for. The counters are now cleared before the request is sent.

tests/test_remote_list drives the remote backend against a fake server
that answers the first request of each kind and drops the second one.
Without the fix it prints "the unanswered request still drew 2 row(s):
erste zweite" and fails five checks; with it: ok.

Verified: test_remote_list ok, make check: all tests passed.
2026-11-23 09:01:39 +00:00
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