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.
This commit is contained in:
lotherk committed 2026-11-21 21:25:51 +00:00
1 parent 226fff3461
commit f7120882fa
15 files changed
+1753 -35

No files matched your search

+9 -4
View File
@@ -24,10 +24,10 @@ CURSES_A = $(CURSES_DIR)/libcurses/libcurses.a \
$(CURSES_DIR)/libterminfo/libterminfo.a
LIB = libsplinter.so
LIBOBJ = src/backend/buf.o src/backend/tool.o src/backend/session.o src/backend/conv.o src/backend/transport.o \
LIBOBJ = src/backend/buf.o src/backend/tool.o src/backend/session.o src/backend/conv.o src/backend/compact.o src/backend/transport.o \
src/backend/json.o src/backend/sse.o src/backend/openai.o src/backend/transport_openai.o \
src/backend/anthropic.o src/backend/transport_anthropic.o src/backend/builtin.o \
src/backend/agent.o src/backend/theme.o src/backend/palettes.o src/backend/decomp.o src/backend/i18n.o src/backend/delegate.o src/backend/telegram.o src/backend/log.o src/backend/cmdscript.o src/backend/folder.o src/backend/interview.o src/backend/ack.o src/backend/mcpserver.o src/backend/mcpsession.o src/backend/skills.o src/backend/user.o src/backend/prompt.o src/backend/config.o src/backend/plugin.o src/backend/curl.o src/backend/swarm.o src/backend/provstate.o src/backend/md.o src/backend/tgmd.o src/backend/b64.o src/backend/a2aserver.o src/backend/providers.o src/backend/usage.o src/backend/confblock.o src/backend/agents.o src/backend/engine.o src/backend/http.o src/backend/openai_server.o src/backend/catalogs.o
src/backend/agent.o src/backend/theme.o src/backend/palettes.o src/backend/decomp.o src/backend/i18n.o src/backend/delegate.o src/backend/telegram.o src/backend/log.o src/backend/cmdscript.o src/backend/folder.o src/backend/interview.o src/backend/ack.o src/backend/mcpserver.o src/backend/mcpsession.o src/backend/skills.o src/backend/user.o src/backend/prompt.o src/backend/config.o src/backend/plugin.o src/backend/curl.o src/backend/swarm.o src/backend/provstate.o src/backend/md.o src/backend/tgmd.o src/backend/b64.o src/backend/a2aserver.o src/backend/providers.o src/backend/usage.o src/backend/confblock.o src/backend/embed.o src/backend/agents.o src/backend/engine.o src/backend/http.o src/backend/openai_server.o src/backend/catalogs.o
# buildinfo.o is separate: buildinfo.c is generated from the objects below.
LIBOBJ_ALL = $(LIBOBJ) src/backend/buildinfo.o
BIN = splinter
@@ -48,8 +48,8 @@ PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \
plugins/session/session.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_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_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
RPATH = -Wl,-rpath,'$$ORIGIN'
PLUGIN_RPATH = -Wl,-rpath,'$$ORIGIN/../..'
@@ -285,12 +285,17 @@ tests/test_cli: tests/test_cli.c $(LIB) $(PLUGIN)
tests/test_compactor: tests/test_compactor.c $(LIB) $(PLUGIN)
$(CC) $(CFLAGS) -o $@ tests/test_compactor.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_corecompact: tests/test_corecompact.c $(LIB)
$(CC) $(CFLAGS) -o $@ tests/test_corecompact.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_secrets: tests/test_secrets.c $(LIB) $(PLUGIN)
$(CC) $(CFLAGS) -o $@ tests/test_secrets.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_mcpclient: tests/test_mcpclient.c $(LIB) $(PLUGIN)
$(CC) $(CFLAGS) -o $@ tests/test_mcpclient.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_kids: tests/test_kids.c $(LIB) $(PLUGIN)
$(CC) $(CFLAGS) -o $@ tests/test_kids.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_embed: tests/test_embed.c $(LIB) $(HDRS)
$(CC) $(CFLAGS) -o $@ tests/test_embed.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/plugin_lifecycle.so: tests/plugin_lifecycle.c $(LIB) $(HDRS)
$(CC) $(CFLAGS) -shared -o $@ tests/plugin_lifecycle.c -L. -lsplinter \
$(TEST_RPATH) $(LIBS)
+18
View File
@@ -260,6 +260,24 @@ int sp_session_open(struct sp_session_info *, const char *dir,
const char *id, struct sp_buf *err);
int sp_session_append(const struct sp_session_info *, const char *role,
const char *text, struct sp_buf *err);
/*
* A full record. The short form above writes a role and a text; that was enough
* to read a session back as a chat log and not enough to resume one: a tool
* result without the name of its tool, and an assistant turn without its
* tool_calls, cannot be sent to a provider at all. An empty text writes
* nothing - a record with no content is not a message, it is noise in the file
* that made every resumed session carry blank user turns.
*/
struct sp_sess_rec {
const char *role;
const char *text;
const char *name; /* tool name, when role is "tool" */
const char *call_id; /* tool_call id */
const char *calls; /* raw tool_calls JSON of an assistant turn */
};
int sp_session_append_rec(const struct sp_session_info *,
const struct sp_sess_rec *, struct sp_buf *err);
int sp_session_count(const struct sp_session_info *, size_t *n,
struct sp_buf *err);
int sp_session_latest(const char *dir, char *id, size_t cap);
+20
View File
@@ -150,6 +150,26 @@ int sp_host_note(struct sp_host *, const char *text);
int sp_host_status_msg(struct sp_host *, const char *text);
int sp_host_status_take(struct sp_host *, char *buf, size_t len);
int sp_host_add_compactor(struct sp_host *, const struct sp_compactor *);
/*
* The compactor the core registers itself, before any plugin. It is what
* compact_threshold and compact_target drive; a plugin that compacts too runs
* after it.
*/
const struct sp_compactor *sp_core_compactor(void);
/*
* "Leave this conversation alone for this round."
*
* A compactor that works asynchronously - it copies the conversation, hands it
* to a worker and applies the plan on its next call - cannot survive the core
* cutting the conversation between the snapshot and the apply: the plan is
* made for a conversation that no longer exists, the size check fails, and the
* work is thrown away every round while the conversation keeps growing.
*
* So a plugin in that state calls this before returning 0. The host then keeps
* the core compactor out of this one call and asks again next time, which is
* when the plan lands. The flag lasts one call and is not remembered.
*/
void sp_host_compactor_hold(struct sp_host *);
int sp_host_add_gate(struct sp_host *, const struct sp_gate *);
int sp_host_add_status(struct sp_host *, const struct sp_status *);
const struct sp_meter *sp_host_meter(struct sp_host *);
+6
View File
@@ -138,6 +138,12 @@ cps_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
if (sp_conv_bytes(conv) <= budget)
return 0; /* fits: no plan needed */
copy_snapshot(conv, budget);
/*
* The worker is making a plan for exactly this conversation. The
* core compactor must not cut it in the meantime, or the plan is
* invalid before it lands and every round throws it away.
*/
sp_host_compactor_hold(h);
return 0; /* plan is being prepared */
}
+9 -2
View File
@@ -186,9 +186,16 @@ lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
* The tail must not start with a tool result: its assistant turn, the
* one carrying the tool_call, would be gone, and a provider answers an
* orphaned tool message with a 400. Such results go with their call.
*
* Walk BACK to that assistant, not forward past the results. Forward
* was the first try and it silently shrank the tail: a turn with two
* results at the boundary kept four messages where keep_tail says six.
* Measured 2026-11-21 on system + user + [assistant, tool, tool] x4 +
* user: fifteen messages, tail of six, result was a tail of four.
*/
while (keep_from < conv->n && is_role(&conv->v[keep_from], "tool"))
keep_from++;
while (keep_from < conv->n && keep_from > first &&
is_role(&conv->v[keep_from], "tool"))
keep_from--;
if (keep_from >= conv->n || keep_from <= first)
return 0;
/*
+40 -5
View File
@@ -332,9 +332,17 @@ run_one(struct sp_agent *a, struct sp_conv *conv,
sp_buf_puts(err, "agent: out of memory");
return -1;
}
if (a->sess != NULL &&
sp_session_append(a->sess, "observation", obs->p, err) != 0)
return -1;
if (a->sess != NULL) {
struct sp_sess_rec rec;
memset(&rec, 0, sizeof(rec));
rec.role = "tool";
rec.text = obs->p;
rec.name = call->name;
rec.call_id = call->id;
if (sp_session_append_rec(a->sess, &rec, err) != 0)
return -1;
}
return 0;
}
@@ -788,9 +796,10 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision,
sp_buf_free(&steer);
}
/* compaction happens before the budget is judged, never after */
if (a->host != NULL) {
{
size_t cb = sp_conv_bytes(conv), cn = conv->n;
size_t cbudget = a->cfg->max_bytes;
int changed = 0;
/*
* The token threshold is the automatic compaction: past
@@ -801,7 +810,14 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision,
a->cfg->compact_target > 0 &&
a->stats.last_in > a->cfg->compact_threshold)
cbudget = a->cfg->compact_target * 4;
if (sp_host_compact(a->host, conv, cbudget) > 0) {
/*
* The engine always builds the host, plugins or not:
* it is how the compactor learns whether the tools
* exist. A fallback here would compact without that
* knowledge and lose the hint.
*/
changed = sp_host_compact(a->host, conv, cbudget);
if (changed > 0) {
a->stats.compactions++;
if (a->cfg != NULL && a->cfg->on_compact != NULL)
a->cfg->on_compact(a->cfg->on_compact_ctx,
@@ -957,6 +973,25 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision,
sp_reply_free(&reply);
goto oom;
}
/*
* A turn that asks for tools used to leave no line at
* all, so a resumed session had answers with no calls
* and results with no name. Write the turn with its
* tool_calls; the results follow as they run.
*/
if (a->sess != NULL) {
struct sp_sess_rec rec;
memset(&rec, 0, sizeof(rec));
rec.role = "assistant";
rec.text = reply.content;
rec.calls = reply.calls_json;
if (sp_session_append_rec(a->sess, &rec,
err) != 0) {
sp_reply_free(&reply);
goto out;
}
}
}
for (i = 0; i < reply.ncalls; i++) {
int r = run_one(a, conv, &reply.calls[i], 0, 0, &obs,
+540
View File
@@ -0,0 +1,540 @@
/*
* splinter -- compact: the compactor the core owns.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* Compaction used to live only in the lcm plugin, which made `compact_threshold`
* and `compact_target` dead settings: the agent read them, built a budget from
* them, and handed it to a compactor list that was empty unless a plugin had
* been loaded. A harness whose own configuration does nothing is worse than one
* that has no such configuration, because the operator believes it is working.
*
* So the core carries a compactor of its own, and it runs when no plugin does.
*
* Two things were learned the hard way, and they shape everything below.
*
* 1. A cut that leaves only a statistic line loses the thread. lcm replaced the
* dropped range with "[lcm] 42 messages compacted out (user 12, ...)" and
* quoted 120 characters of the oldest one. The model then no longer knew what
* the work was, re-asked, and the operator called it "losing the fade" - a
* correct complaint. What has to survive is not a count, it is the story:
* who asked what, in order.
*
* 2. Tool output is where the bytes are, and the head of an observation is the
* part that matters. Trimming bodies saves most of the budget before any
* message has to go.
*
* So the order of work is:
*
* 1. trim every tool body outside the verbatim tail
* 2. still over budget: build a THREAD DIGEST of the dropped range. Every user
* message survives nearly whole; every assistant turn keeps its opening;
* every observation is reduced to a line. The digest is one system message.
* 3. the newest real user message is pinned after the digest, so the question
* being answered is never something the model has to infer.
* 4. if the digest plus the tail still exceeds the budget, the caps shrink
* step by step, cheapest role first. The digest is never dropped whole.
*
* Nothing here calls a second model: a summary that costs a request and makes a
* run unreproducible is a different feature, not a flag on this one.
*
* The tail boundary never lands on a "tool" message: its assistant turn carries
* the tool_call, and a provider rejects an orphaned tool result with a 400.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "splinter.h"
#include "splinter_plugin.h"
#define COMPACT_KEEP_TAIL 6 /* messages always kept verbatim */
#define COMPACT_KEEP_HEAD 8 /* leading system messages never digested */
#define COMPACT_TOOL_TRIM 2048 /* a tool body outside the tail */
/* Per-role caps inside the digest. User text is the thread: keep it nearly
* whole. An assistant turn is mostly restating its tool call, so its opening
* is enough. An observation is already trimmed by then. */
#define CAP_USER 800
#define CAP_ASSISTANT 300
#define CAP_TOOL 160
#define CAP_MIN_USER 120
#define CAP_MIN_ASSISTANT 40
#define CAP_MIN_TOOL 0
struct caps {
size_t user;
size_t assistant;
size_t tool;
};
static size_t
msg_bytes(const struct sp_msg *m)
{
size_t n = 16; /* JSON scaffolding, estimated */
n += m->role != NULL ? strlen(m->role) : 0;
n += m->name != NULL ? strlen(m->name) : 0;
n += m->content != NULL ? strlen(m->content) : 0;
n += m->calls != NULL ? strlen(m->calls) : 0;
return n;
}
static int
is_role(const struct sp_msg *m, const char *role)
{
return m->role != NULL && strcmp(m->role, role) == 0;
}
/*
* The engine's own continuation prompt ("Continue with the task ...") arrives as
* a user message but is not the question. Pinning it keeps the keystroke and
* loses the task it was meant to continue - measured on a session resumed after
* a rate limit, which woke up with the prompt, one tool call and no task.
*/
static int
is_continuation(const struct sp_msg *m)
{
static const char *prefix[] = {
"Continue with the task",
"Setze die Aufgabe",
NULL
};
size_t i;
if (m->content == NULL)
return 0;
for (i = 0; prefix[i] != NULL; i++)
if (strncmp(m->content, prefix[i], strlen(prefix[i])) == 0)
return 1;
return 0;
}
/*
* Cut long tool outputs in [from, to). The head of an observation is the part
* worth keeping: a tool prints its answer, then a stack of context. The marker
* says the cut happened, so a model does not read a trimmed result as complete.
*/
static int
trim_tools(struct sp_conv *conv, size_t from, size_t to, size_t limit)
{
size_t i;
int trimmed = 0;
for (i = from; i < to; i++) {
struct sp_msg *m = &conv->v[i];
size_t len;
char *cut;
if (!is_role(m, "tool") || m->content == NULL)
continue;
len = strlen(m->content);
if (len <= limit)
continue;
cut = malloc(limit + 96);
if (cut == NULL)
return trimmed;
memcpy(cut, m->content, limit);
snprintf(cut + limit, 96, "\n[... %zu bytes trimmed by compaction]",
len - limit);
free(m->content);
m->content = cut;
trimmed++;
}
return trimmed;
}
/* Append text with newlines flattened to spaces: the digest is a transcript of
* one message, not a document with its own layout. */
static void
append_flat(struct sp_buf *b, const char *s, size_t cap)
{
size_t i;
if (s == NULL)
return;
for (i = 0; i < cap && s[i] != '\0'; i++) {
char c = s[i];
if (c == '\n' || c == '\r' || c == '\t')
c = ' ';
sp_buf_add(b, &c, 1);
}
if (s[i] != '\0')
sp_buf_puts(b, "...");
}
/*
* The thread: one line per dropped message, in order. A user turn gets its
* opening nearly whole - that is the task and the corrections to it. An
* assistant turn gets its opening, which is what it claimed to be doing. An
* observation gets enough to recognise it.
*/
/*
* Does the registry offer history_search? Passed in rather than looked up here,
* because build_digest runs inside the shrink loop and the answer never changes.
*/
static int
build_digest(struct sp_conv *conv, size_t from, size_t to, struct caps caps,
int searchable, struct sp_buf *out)
{
size_t i;
size_t users = 0, assistants = 0, tools = 0, other = 0;
if (sp_buf_init(out) != 0)
return -1;
for (i = from; i < to; i++) {
if (is_role(&conv->v[i], "user"))
users++;
else if (is_role(&conv->v[i], "assistant"))
assistants++;
else if (is_role(&conv->v[i], "tool"))
tools++;
else
other++;
}
sp_buf_puts(out, "[thread so far - compacted] ");
sp_buf_printf(out, "%zu earlier messages: %zu from the operator, %zu "
"assistant turns, %zu tool results", to - from, users, assistants,
tools);
if (other > 0)
sp_buf_printf(out, ", %zu other", other);
sp_buf_puts(out, ". In order:\n");
/*
* Say where the rest went. Without this line the model reads a summary
* that stops mid-thought and believes that is all there ever was: it
* re-asks the operator what the operator already answered, which is the
* exact complaint ("losing the fade") this digest exists to fix. The
* tool is named only when it is really registered - a prompt pointing at
* a missing tool teaches the model to call nothing.
*/
if (searchable)
sp_buf_puts(out, "\n[The full transcript is still on disk. "
"Call history_search with the words of what you are looking "
"for to get it back: it searches this whole session by "
"meaning, not just what is quoted here.]\n");
for (i = from; i < to; i++) {
struct sp_msg *m = &conv->v[i];
if (is_role(m, "user")) {
sp_buf_puts(out, "\nOPERATOR: ");
append_flat(out, m->content, caps.user);
} else if (is_role(m, "assistant")) {
if (m->content == NULL && m->calls != NULL)
continue; /* a bare tool call says nothing yet */
sp_buf_puts(out, "\n assistant: ");
append_flat(out, m->content, caps.assistant);
} else if (is_role(m, "tool")) {
if (caps.tool == 0)
continue;
sp_buf_puts(out, "\n ");
if (m->name != NULL) {
sp_buf_puts(out, m->name);
sp_buf_puts(out, " -> ");
} else
sp_buf_puts(out, "tool -> ");
append_flat(out, m->content, caps.tool);
}
}
return 0;
}
/* Free the strings of [from, to) and close the gap. The vector, not the count. */
static void
drop_range(struct sp_conv *conv, size_t from, size_t to)
{
size_t i;
for (i = from; i < to; i++) {
free(conv->v[i].role);
free(conv->v[i].name);
free(conv->v[i].call_id);
free(conv->v[i].content);
free(conv->v[i].calls);
}
memmove(&conv->v[from], &conv->v[to],
(conv->n - to) * sizeof(*conv->v));
conv->n = from + (conv->n - to);
}
/* Bytes that [from, to) currently costs. */
static size_t
range_bytes(struct sp_conv *conv, size_t from, size_t to)
{
size_t i, total = 0;
for (i = from; i < to; i++)
total += msg_bytes(&conv->v[i]);
return total;
}
static int
core_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
unsigned turn)
{
struct sp_buf digest;
struct sp_registry *reg;
int searchable;
struct caps caps;
size_t bytes, drop_bytes, tail_bytes;
char *best_p = NULL;
size_t best_len = 0;
size_t first, keep_from;
long pin_at = -1;
char *pin_content = NULL;
char *pin_name = NULL;
size_t pin_extra = 0;
int trimmed, pinned = 0;
int attempt;
(void)turn;
/*
* Whether the escape hatch exists decides whether the digest advertises
* it. The embedding index is on by default, but `embed = off` is a
* supported choice and the prompt must not lie about it.
*/
reg = h != NULL ? sp_host_registry(h) : NULL;
searchable = reg != NULL && sp_registry_find(reg, "history_search") != NULL;
if (conv == NULL || conv->n == 0 || budget == 0)
return 0;
bytes = sp_conv_bytes(conv);
if (bytes <= budget)
return 0; /* fits: nothing to do */
if (conv->n <= COMPACT_KEEP_TAIL + 1)
return 0; /* too short to cut anything meaningful */
/*
* The leading system messages stay. Plural, because a compactor plugin
* that ran before this one put its own summary there - lcm's "[lcm] 42
* messages compacted out", cps' plan. That message is the result of work
* somebody already paid for, and digesting it away would replace the
* plugin's summary with a worse one. The cap keeps a pathological lead of
* system messages from eating the whole budget.
*/
for (first = 0; first < conv->n && first < COMPACT_KEEP_HEAD &&
is_role(&conv->v[first], "system"); first++)
;
keep_from = conv->n - COMPACT_KEEP_TAIL;
/*
* The tail must not begin with a tool result: its assistant turn, the
* one carrying the tool_call, would be cut away and a provider answers
* an orphaned tool message with a 400. Walk BACK to that assistant
* rather than forward past the results.
*
* Forward was the first try and it quietly broke the promise this
* constant makes: a turn with two tool results in the tail boundary
* kept four messages instead of six, because each result pushed the
* start further in. Measured on system + user + [assistant, tool, tool]
* x4 + user: 15 messages, tail of six, result was a tail of four. Going
* back costs the bytes of one call record and keeps the size.
*/
while (keep_from < conv->n && keep_from > first &&
is_role(&conv->v[keep_from], "tool"))
keep_from--;
if (keep_from >= conv->n || keep_from <= first)
return 0;
/* 1. trim every tool body outside the verbatim tail */
trimmed = trim_tools(conv, first, conv->n, COMPACT_TOOL_TRIM);
bytes = sp_conv_bytes(conv);
if (bytes <= budget)
return trimmed > 0 ? 1 : 0;
/* 2. the question being answered, pinned after the digest */
{
size_t i;
for (i = conv->n; i > first; i--) {
if (!is_role(&conv->v[i - 1], "user"))
continue;
if (is_continuation(&conv->v[i - 1]))
continue;
pin_at = (long)(i - 1);
break;
}
}
if (pin_at >= 0 && (size_t)pin_at >= keep_from) {
/* it is already in the verbatim tail: nothing to pin */
pin_at = -1;
}
if (pin_at >= 0) {
pin_content = strdup(conv->v[pin_at].content != NULL ?
conv->v[pin_at].content : "");
if (conv->v[pin_at].name != NULL)
pin_name = strdup(conv->v[pin_at].name);
pinned = pin_content != NULL;
if (pinned)
pin_extra = strlen(pin_content) +
(pin_name != NULL ? strlen(pin_name) : 0) + 20;
}
caps.user = CAP_USER;
caps.assistant = CAP_ASSISTANT;
caps.tool = CAP_TOOL;
/*
* What the digest has to beat is not the budget - it is what it replaces.
* If it costs more than the range it stands in for, the rewrite makes the
* conversation bigger and the next request pays for nothing. Shrink the
* caps until the digest is smaller than the range, user text last: that is
* the thread.
*
* The digest may also take at most its share of the budget, unless the
* verbatim tail alone already leaves less room than that.
*/
/*
* The digest has two hard limits, and it must satisfy both:
*
* a) smaller than the range it replaces, or the rewrite grows the
* conversation and the next request pays for nothing
* b) small enough that the digest plus the verbatim tail fits the
* budget, or the turn is refused for exceeding it anyway
*
* (b) is the one that was missing: with a budget of 900 and a tail of
* 1000 the digest could satisfy (a) all day and the request still went
* out at 3776 bytes. When the tail alone already exceeds the budget,
* (b) has no answer and (a) is the only rule left.
*
* Beyond those, the caps decide how much of the thread survives.
* Shrinking them is a last resort: the thread IS the point, and a digest
* that fits but says nothing is the failure this file exists to avoid.
*/
drop_bytes = range_bytes(conv, first, keep_from);
tail_bytes = range_bytes(conv, keep_from, conv->n);
{
size_t room = drop_bytes > pin_extra + 64 ?
drop_bytes - pin_extra - 64 : 0;
size_t fit = budget > tail_bytes + pin_extra ?
budget - tail_bytes - pin_extra : 0;
if (fit > 0 && fit < room)
room = fit;
/*
* Shrink until it fits, but keep the best attempt: when even the
* smallest caps overshoot, the smallest digest is still worth more
* than no thread at all. The best one is copied out as a plain
* buffer, so ownership stays in one place.
*/
best_p = NULL;
best_len = 0;
for (attempt = 0; attempt < 16; attempt++) {
if (build_digest(conv, first, keep_from, caps,
searchable, &digest) != 0) {
free(best_p);
free(pin_content);
free(pin_name);
return -1;
}
if (digest.len == 0) {
sp_buf_free(&digest);
break;
}
if (best_p == NULL || digest.len < best_len) {
char *copy = malloc(digest.len + 1);
if (copy != NULL) {
memcpy(copy, digest.p, digest.len + 1);
free(best_p);
best_p = copy;
best_len = digest.len;
}
}
if (digest.len <= room) {
sp_buf_free(&digest);
break;
}
sp_buf_free(&digest);
if (caps.tool > CAP_MIN_TOOL) {
caps.tool = caps.tool / 2;
continue;
}
if (caps.assistant > CAP_MIN_ASSISTANT) {
caps.assistant = caps.assistant / 2;
continue;
}
if (caps.user > CAP_MIN_USER) {
caps.user = caps.user * 3 / 4;
continue;
}
break; /* nothing left to shrink */
}
if (best_p == NULL) {
free(pin_content);
free(pin_name);
return trimmed > 0 ? 1 : 0;
}
/*
* Rule (a), enforced rather than merely computed. The shrink loop
* stops at the minimum caps and keeps the smallest attempt even
* when that attempt is still too big - and then the rewrite went
* out anyway, replacing a short range with a longer digest plus a
* pinned question. Measured on the case /resume produced: 317
* bytes in, 476 bytes out, on a budget of 217. A compactor that
* grows the conversation is worse than none, because the next
* request pays for it and the turn is refused for size.
*
* There is nothing else to try at this point, so the honest
* answer is "I could not help": the tool bodies were already
* trimmed above, which is where the easy bytes were.
*/
if (best_len + pin_extra >= drop_bytes) {
free(best_p);
free(pin_content);
free(pin_name);
return trimmed > 0 ? 1 : 0;
}
if (sp_buf_init(&digest) != 0) {
free(best_p);
free(pin_content);
free(pin_name);
return -1;
}
sp_buf_add(&digest, best_p, best_len);
free(best_p);
}
drop_range(conv, first, keep_from);
{
struct sp_msg m;
memset(&m, 0, sizeof(m));
m.role = "system";
m.content = digest.p;
if (sp_conv_insert(conv, first, &m) != 0) {
sp_buf_free(&digest);
free(pin_content);
free(pin_name);
return -1;
}
}
if (pinned && pin_content != NULL && pin_content[0] != '\0') {
struct sp_msg m;
memset(&m, 0, sizeof(m));
m.role = "user";
m.name = pin_name;
m.content = pin_content;
if (sp_conv_insert(conv, first + 1, &m) != 0) {
sp_buf_free(&digest);
free(pin_content);
free(pin_name);
return -1;
}
}
sp_buf_free(&digest);
free(pin_content);
free(pin_name);
return 1;
}
static const struct sp_compactor compact = { "compact", core_compact };
const struct sp_compactor *
sp_core_compactor(void)
{
return &compact;
}
+40 -2
View File
@@ -34,6 +34,7 @@
#include "config.h"
#include "folder.h"
#include "i18n.h"
#include "embed.h"
#include "log.h"
#include "mcp.h"
#include "prompt.h"
@@ -79,6 +80,8 @@ struct sp_engine {
struct sp_session_info sess;
struct sp_conv conv;
struct sp_host *host;
/* the session's embedding index: background thread, never on the turn */
struct sp_embed_ctx *emb;
struct sp_mock mock;
int have_mock;
@@ -1146,6 +1149,12 @@ engine_compact(void *ctx, size_t before, size_t after, size_t mb, size_t ma)
snprintf(msg, sizeof(msg), sp_t("ui.compacted"), mb, ma, t1, t2, b1,
b2);
ev_push(e, SP_EV_ENTRY, 0, "splinter", msg);
/*
* What compaction just dropped stays in the session file, and this is
* the moment it becomes worth finding again. The call only raises a
* flag; the embedding runs on its own thread.
*/
sp_embed_note_compaction(e->emb);
}
/* ----------------------------------------------------------------- turns */
@@ -2254,6 +2263,8 @@ cmd_new(struct sp_engine *e, struct sp_buf *out)
&e->agents.v[e->agent_cur], base, &e->policy);
(void)sp_log_open(e->sess.dir, e->sess.id);
sp_logf("session", "started: %s", e->sess.id);
/* the new session gets its own index; the old one stays on disk */
sp_embed_bind(e->emb, e->sess.dir, e->sess.id);
profile_save(e);
{
char sel[320];
@@ -2406,6 +2417,14 @@ cmd_status(struct sp_engine *e, struct sp_buf *out)
sp_buf_printf(out, sp_t("status.compact_value"), comp, failed, turns,
e->snapshot.compactions);
sp_buf_puts(out, "\n");
sp_buf_printf(out, " %-8s ", sp_t("status.embed"));
{
char etex[256];
sp_embed_status(e->emb, etex, sizeof(etex));
sp_buf_puts(out, etex);
}
sp_buf_puts(out, "\n");
sp_buf_printf(out, " %-8s ", sp_t("status.limits"));
sp_buf_printf(out, sp_t("status.limits_value"), e->base.max_bytes,
e->base.max_steps, e->base.autonomous ?
@@ -3076,8 +3095,13 @@ load_plugins(struct sp_engine *e, const struct sp_engine_opts *o,
struct sp_host *host;
size_t k;
if (o->nplugins == 0)
return 0;
/*
* The host is created even without a single plugin: it is what carries
* the registry to the core compactor and the gate to the tools. Skiping
* it here left a plugin-less run with no compactor at all, so max_bytes
* killed every turn whose conversation was over the ceiling - the
* compaction that was supposed to save it could not be reached.
*/
host = sp_host_new(&e->reg, &e->ag, &e->sess);
if (host == NULL) {
sp_buf_puts(err, "cannot create plugin host");
@@ -3336,6 +3360,14 @@ sp_engine_open(struct sp_engine **out, const struct sp_engine_opts *o,
}
if (open_session(e, o, err, &code) != 0)
goto fail;
/*
* The index belongs to the session, so it is created with it. It starts
* its own thread and begins reading the file in the background: a
* resumed session is searchable without anything having been compacted.
*/
e->emb = sp_embed_new(e->conf);
if (e->emb != NULL)
sp_embed_bind(e->emb, e->sess.dir, e->sess.id);
if (session_model_read(e, saved, sizeof(saved)) == 0) {
struct sp_choice ch;
@@ -3381,6 +3413,11 @@ sp_engine_open(struct sp_engine **out, const struct sp_engine_opts *o,
sp_buf_puts(err, "cannot register folder_history or delegate");
goto fail;
}
/* history_search: the way back into what compaction dropped */
if (e->emb != NULL && sp_embed_register(&e->reg, e->emb) != 0) {
sp_buf_puts(err, "cannot register history_search");
goto fail;
}
if (pick_transport(e, o, err) != 0) {
code = -2; /* a configuration the user can fix */
goto fail;
@@ -3514,6 +3551,7 @@ sp_engine_close(struct sp_engine *e)
free(e->turn_text);
sp_agents_free(&e->agents);
sp_conv_free(&e->conv);
sp_embed_free(e->emb);
sp_host_free(e->host);
sp_registry_free(&e->reg);
if (e->have_mock)
+47
View File
@@ -60,6 +60,8 @@ struct sp_host {
size_t msg_head, msg_n;
const struct sp_compactor *compact[MAX_COMPACTORS];
size_t ncompact;
/* set by a plugin that is preparing a plan; lasts one call */
int compact_hold;
const struct sp_gate *gate[MAX_COMPACTORS];
size_t ngate;
const struct sp_status *status[MAX_STATUS];
@@ -468,6 +470,27 @@ sp_host_compact(struct sp_host *h, struct sp_conv *conv, size_t budget)
if (h == NULL || conv == NULL)
return 0;
/*
* The plugins get their turn first, and the core is the backstop.
*
* The old rule was "any plugin compactor means the core stays out", and
* it was wrong twice over. compact_threshold and compact_target are core
* settings, so a configuration whose plugins happened to register one
* made them dead - the operator set a limit and the conversation grew
* past the window until the provider cut it (254k of 131k, 2026-11-21).
* And most plugin "compactors" do not compact at all: focus and reminder
* insert one message and return 0 or 1. A plugin that inserts a goal
* reminder must not be the reason an oversized request goes out whole.
*
* So the core always gets a look, and decides for itself: core_compact()
* returns 0 without touching anything when the conversation already fits
* the budget. That is the check that separates "focus inserted a
* reminder into a small conversation" (616 bytes under a 1-byte budget
* in a test, every real turn under its real budget) from "lcm cut the
* transcript in half". Only the second kind of turn gets a digest, and
* then it comes after the plugin's own work, so that work is what
* survives where it did something.
*/
for (i = 0; i < h->ncompact; i++) {
rc = h->compact[i]->compact(h, conv, budget,
(unsigned)h->turns);
@@ -478,9 +501,33 @@ sp_host_compact(struct sp_host *h, struct sp_conv *conv, size_t budget)
h->failed++;
}
}
/*
* A plugin that answered "not yet, my plan is still being prepared" asked
* for one round of room. Its next call applies the plan. Cutting the
* conversation in between would invalidate that plan, which is the bug
* this flag exists to prevent.
*/
if (h->compact_hold) {
h->compact_hold = 0;
return changed;
}
rc = sp_core_compactor()->compact(h, conv, budget, (unsigned)h->turns);
if (rc > 0) {
changed = 1;
h->compactions++;
} else if (rc < 0) {
h->failed++;
}
return changed;
}
void
sp_host_compactor_hold(struct sp_host *h)
{
if (h != NULL)
h->compact_hold = 1;
}
size_t
sp_host_compaction_stats(struct sp_host *h, size_t *compactions,
size_t *failed, unsigned *turns)
+362 -13
View File
@@ -57,6 +57,15 @@ struct session_meta {
char title[96];
char goal[1001]; /* the session's /goal, one line */
char goal_state[16]; /* open | succeeded: the model said GOAL_COMPLETE */
/*
* Lines the core does not own. A plugin that marks a session (foreign=
* hermes:h-1 names where an imported conversation came from) writes into
* the same file, and every reopen, rename or /goal rewrites it: without
* carrying them through, the plugin's own marker was gone the first time
* the session was opened again.
*/
char extra[8][160];
size_t nextra;
};
/* a title is one line, no control bytes, at most 95 bytes of UTF-8 */
@@ -144,6 +153,17 @@ meta_read(const char *dir, const char *id, struct session_meta *m)
snprintf(m->goal, sizeof(m->goal), "%s", v);
else if (strcmp(line, "goal_state") == 0)
snprintf(m->goal_state, sizeof(m->goal_state), "%s", v);
else if (m->nextra < sizeof(m->extra) / sizeof(m->extra[0])) {
size_t cap = sizeof(m->extra[0]);
size_t lk = strlen(line), lv = strlen(v), use, kv;
kv = lk < cap - 2 ? lk : cap - 2;
use = cap - 1 - kv - 1;
if (lv > use)
lv = use;
snprintf(m->extra[m->nextra++], cap, "%.*s=%.*s",
(int)kv, line, (int)lv, v);
}
}
fclose(f);
return 0;
@@ -154,6 +174,7 @@ meta_write(const char *dir, const char *id, const struct session_meta *m)
{
char path[700], tmp[800];
FILE *f;
size_t i;
snprintf(path, sizeof(path), "%s/%s.meta", dir, id);
snprintf(tmp, sizeof(tmp), "%s.tmp", path);
@@ -168,6 +189,8 @@ meta_write(const char *dir, const char *id, const struct session_meta *m)
fprintf(f, "goal=%s\n", m->goal);
if (m->goal_state[0] != '\0')
fprintf(f, "goal_state=%s\n", m->goal_state);
for (i = 0; i < m->nextra; i++)
fprintf(f, "%s\n", m->extra[i]);
if (fclose(f) != 0) {
(void)unlink(tmp);
return -1;
@@ -300,6 +323,13 @@ sp_session_open(struct sp_session_info *info, const char *dir,
* A session belongs to the directory it was started in. That is what '-c'
* needs: the last session that happened *here*, not the last one anywhere.
* The title and the original creation time survive a reopen.
*
* The cwd is only filled in when it is still empty, i.e. for a new
* session. Taking getcwd() unconditionally looked right for a new one
* and rewrote the field for an existing one: /open from another
* directory, and every import (which sets the source's directory),
* then claimed this directory instead of the one the conversation ran
* in - and '-c' picked that session up from the wrong place.
*/
{
struct session_meta m;
@@ -309,7 +339,7 @@ sp_session_open(struct sp_session_info *info, const char *dir,
memset(&m, 0, sizeof(m));
m.created = (long)now;
}
if (getcwd(m.cwd, sizeof(m.cwd)) == NULL)
if (m.cwd[0] == '\0' && getcwd(m.cwd, sizeof(m.cwd)) == NULL)
snprintf(m.cwd, sizeof(m.cwd), "?");
if (m.created == 0)
m.created = (long)now;
@@ -395,27 +425,71 @@ sp_session_list(const char *dir, struct sp_session_brief *v, size_t max)
return (int)n;
}
/*
* The record writer. Everything the conversation needs to be sent again is
* written here: role, the text, and for a tool result the name of the tool and
* the call it answers, and for an assistant turn its tool_calls. Without those
* three a resumed session cannot be replayed to a provider - the provider
* rejects a "tool" message with no matching tool_call, so the old loader simply
* dropped every observation instead.
*/
int
sp_session_append(const struct sp_session_info *info, const char *role,
const char *text, struct sp_buf *err)
sp_session_append_rec(const struct sp_session_info *info,
const struct sp_sess_rec *rec, struct sp_buf *err)
{
struct sp_buf line;
char path[640];
int fd, rc;
if (info == NULL || rec == NULL || rec->role == NULL) {
sp_buf_puts(err, "session: no record");
return -1;
}
/*
* A record with neither text nor calls says nothing. Writing it put
* {"role":"user","text":""} into the file and every resume showed the
* model a blank human turn - which it then answered. Drop it here, at the
* one place that writes.
*/
if ((rec->text == NULL || rec->text[0] == '\0') &&
(rec->calls == NULL || rec->calls[0] == '\0'))
return 0;
if (sp_buf_init(&line) != 0) {
sp_buf_puts(err, "session: out of memory");
return -1;
}
rc = sp_buf_puts(&line, "{\"role\":\"");
if (rc == 0)
rc = sp_json_escape(&line, role);
rc = sp_json_escape(&line, rec->role);
if (rc == 0)
rc = sp_buf_puts(&line, "\",\"text\":\"");
if (rc == 0)
rc = sp_json_escape(&line, text);
rc = sp_json_escape(&line, rec->text != NULL ? rec->text : "");
if (rc == 0)
rc = sp_buf_puts(&line, "\"}\n");
rc = sp_buf_puts(&line, "\"");
if (rc == 0 && rec->name != NULL && rec->name[0] != '\0') {
rc = sp_buf_puts(&line, ",\"name\":\"");
if (rc == 0)
rc = sp_json_escape(&line, rec->name);
if (rc == 0)
rc = sp_buf_puts(&line, "\"");
}
if (rc == 0 && rec->call_id != NULL && rec->call_id[0] != '\0') {
rc = sp_buf_puts(&line, ",\"call_id\":\"");
if (rc == 0)
rc = sp_json_escape(&line, rec->call_id);
if (rc == 0)
rc = sp_buf_puts(&line, "\"");
}
if (rc == 0 && rec->calls != NULL && rec->calls[0] != '\0') {
/* raw JSON array: written verbatim, never re-escaped */
rc = sp_buf_puts(&line, ",\"calls\":");
if (rc == 0)
rc = sp_buf_puts(&line, rec->calls);
}
if (rc == 0)
rc = sp_buf_puts(&line, "}\n");
if (rc != 0) {
sp_buf_puts(err, "session: out of memory");
sp_buf_free(&line);
@@ -442,12 +516,13 @@ sp_session_append(const struct sp_session_info *info, const char *role,
* otherwise. Written once, so a long conversation does not rewrite the
* sidecar on every turn.
*/
if (rc == 0 && role != NULL && strcmp(role, "user") == 0) {
if (rc == 0 && strcmp(rec->role, "user") == 0 && rec->text != NULL &&
rec->text[0] != '\0') {
struct session_meta m;
if (meta_read(info->dir, info->id, &m) == 0 &&
m.title[0] == '\0') {
title_from_text(text, m.title, sizeof(m.title));
title_from_text(rec->text, m.title, sizeof(m.title));
if (m.title[0] != '\0')
(void)meta_write(info->dir, info->id, &m);
}
@@ -455,6 +530,18 @@ sp_session_append(const struct sp_session_info *info, const char *role,
return rc;
}
int
sp_session_append(const struct sp_session_info *info, const char *role,
const char *text, struct sp_buf *err)
{
struct sp_sess_rec rec;
memset(&rec, 0, sizeof(rec));
rec.role = role;
rec.text = text;
return sp_session_append_rec(info, &rec, err);
}
int
sp_session_count(const struct sp_session_info *info, size_t *n,
struct sp_buf *err)
@@ -499,27 +586,188 @@ sp_session_count(const struct sp_session_info *info, size_t *n,
* reconstructing something else. Records this build does not understand (a
* thinking entry, a tool line) are skipped and counted, never guessed at.
*/
/*
* Serialize a parsed JSON value back to text.
*
* The loader needs this because a record's "calls" is a JSON value inside a
* JSON line: the raw text cannot be sliced out with strstr, since an argument
* may itself contain the characters that delimit it. Slicing until the first
* newline worked only while every argument was single-line; the first tool
* result with a \n in its content produced a request the provider could not
* parse (measured: json.decoder.JSONDecodeError at char 2309).
*/
static void
json_write(struct sp_buf *out, const mcp_json *v)
{
size_t i;
if (v == NULL) {
sp_buf_puts(out, "null");
return;
}
switch (v->t) {
case MCP_NULL:
sp_buf_puts(out, "null");
break;
case MCP_BOOL:
sp_buf_puts(out, v->b ? "true" : "false");
break;
case MCP_NUM:
if (v->n == (double)(long)v->n)
sp_buf_printf(out, "%ld", (long)v->n);
else
sp_buf_printf(out, "%.17g", v->n);
break;
case MCP_STR:
sp_buf_puts(out, "\"");
sp_json_escape(out, v->s != NULL ? v->s : "");
sp_buf_puts(out, "\"");
break;
case MCP_ARR:
sp_buf_puts(out, "[");
for (i = 0; i < v->count; i++) {
if (i > 0)
sp_buf_puts(out, ",");
json_write(out, v->items[i]);
}
sp_buf_puts(out, "]");
break;
case MCP_OBJ:
sp_buf_puts(out, "{");
for (i = 0; i < v->count; i++) {
if (i > 0)
sp_buf_puts(out, ",");
sp_buf_puts(out, "\"");
sp_json_escape(out, v->keys[i]);
sp_buf_puts(out, "\":");
json_write(out, v->items[i]);
}
sp_buf_puts(out, "}");
break;
}
}
/*
* Collect the "id" of every call in a tool_calls array, in order. The raw JSON
* is parsed rather than pattern-matched: a tool name may contain the word id,
* an argument may contain an id, and taking the wrong one pairs a result with
* the wrong call - which a provider accepts and the model then reads as a lie.
*/
/* The id of the synthetic call the loader had to invent, so the next
* observation can reuse the same assistant turn while it is still last. */
static char last_synth_id[32];
static size_t synth_seq;
/*
* Insert an assistant turn that carries one tool call, so the result that
* follows has a call to answer. Used only when reading a file that predates the
* format - a replay of an old session must not cost the model its evidence.
*/
static int
synth_call(struct sp_conv *conv, const char *name)
{
struct sp_msg am;
char calls[512];
struct sp_buf id;
if (sp_buf_init(&id) != 0)
return 0;
sp_buf_printf(&id, "recovered-%zu", ++synth_seq);
snprintf(calls, sizeof(calls),
"[{\"id\":\"%s\",\"type\":\"function\",\"function\":"
"{\"name\":\"%s\",\"arguments\":\"{}\"}}]", id.p, name);
memset(&am, 0, sizeof(am));
am.role = (char *)"assistant";
am.content = (char *)"";
am.calls = calls;
snprintf(last_synth_id, sizeof(last_synth_id), "%s", id.p);
sp_buf_free(&id);
return sp_conv_add(conv, &am) == 0;
}
static size_t
sp_session_ids(const char *calls_json, char **out, size_t max)
{
mcp_json *v;
const mcp_json *arr;
size_t i, n = 0;
if (calls_json == NULL || out == NULL || max == 0)
return 0;
v = mcp_parse(calls_json);
if (v == NULL)
return 0;
arr = v;
if (v->t == MCP_OBJ) {
const mcp_json *t = mcp_arg(v, "tool_calls");
if (t != NULL)
arr = t;
}
for (i = 0; i < mcp_array_len(arr) && n < max; i++) {
const mcp_json *one = mcp_array_at(arr, i);
const char *id = mcp_arg_string(one, "id");
if (id == NULL || id[0] == '\0')
continue;
out[n] = strdup(id);
if (out[n] == NULL)
break;
n++;
}
mcp_json_free(v);
return n;
}
/*
* Read a session back as a conversation a provider will accept.
*
* The first version kept only "user" and "assistant" lines, because the file
* was read as a chat log. It is not a chat log: it is the transcript of an
* agent run, and 99% of its lines are observations. Resuming then handed the
* model a handful of questions with no answers and no evidence between them
* (measured on a real session: 21 of 1507 lines), so it re-did work it had
* already done or asked what the task was.
*
* Two rules make the replay valid:
*
* - A "tool" message needs the name of its tool and the id of the call it
* answers. Records written before this format carry neither; such a line is
* paired with the nearest preceding assistant turn that has calls and no
* answer yet, and the missing id is taken from that call. A tool result
* with no call to answer is dropped - a provider rejects it with a 400, so
* keeping it would break the whole resume.
* - An assistant turn carries its raw tool_calls. Without them the calls are
* gone and their results become orphans.
*/
int
sp_session_load(const struct sp_session_info *info, struct sp_conv *conv,
size_t *loaded, struct sp_buf *err)
{
char path[640];
(void)err;
char *line = NULL;
size_t linecap = 0, n = 0;
ssize_t len;
FILE *f;
/* the calls of the last assistant turn, still waiting for results */
char *pending_calls = NULL; /* raw JSON of that turn */
char *pending_ids[64];
size_t pending_n = 0;
size_t pending_used = 0;
(void)err;
if (loaded != NULL)
*loaded = 0;
snprintf(path, sizeof(path), "%s/%s.jsonl", info->dir, info->id);
f = fopen(path, "r");
if (f == NULL)
return 0; /* nothing to resume from */
/* whole lines, however long: a fixed buffer split big records */
while ((len = getline(&line, &linecap, f)) > 0) {
mcp_json *v;
const char *role, *text;
const char *role, *text, *name, *call_id;
const mcp_json *calls;
/*
* A record is a complete, newline-terminated JSON object. An
@@ -533,13 +781,114 @@ sp_session_load(const struct sp_session_info *info, struct sp_conv *conv,
continue;
role = mcp_arg_string(v, "role");
text = mcp_arg_string(v, "text");
if (role != NULL && text != NULL &&
(strcmp(role, "user") == 0 || strcmp(role, "assistant") == 0)) {
if (sp_conv_push(conv, role, NULL, text) == 0)
name = mcp_arg_string(v, "name");
call_id = mcp_arg_string(v, "call_id");
calls = mcp_arg(v, "calls");
if (role == NULL || text == NULL) {
mcp_json_free(v);
continue;
}
if (strcmp(role, "user") == 0 || strcmp(role, "system") == 0) {
/*
* A blank user line is noise from an older writer; a
* provider answers it by asking what was meant.
*/
if (text[0] != '\0') {
if (sp_conv_push(conv, role, NULL, text) == 0)
n++;
}
} else if (strcmp(role, "assistant") == 0) {
/* free whatever the previous turn left unclaimed */
free(pending_calls);
pending_calls = NULL;
{
size_t i;
for (i = 0; i < pending_n; i++)
free(pending_ids[i]);
}
pending_n = pending_used = 0;
{
struct sp_msg am;
memset(&am, 0, sizeof(am));
am.role = (char *)"assistant";
am.content = (char *)text;
am.calls = NULL;
if (calls != NULL) {
/*
* Re-serialize the value, never slice
* the line: an argument may contain
* the delimiters of its own record.
*/
struct sp_buf cb;
if (sp_buf_init(&cb) == 0) {
json_write(&cb, calls);
pending_calls = cb.p;
am.calls = pending_calls;
pending_n = sp_session_ids(
pending_calls, pending_ids, 64);
}
}
if (sp_conv_add(conv, &am) == 0)
n++;
pending_used = 0;
}
} else if (strcmp(role, "tool") == 0 ||
strcmp(role, "observation") == 0) {
struct sp_msg tm;
const char *use_id = call_id;
/*
* An old record has no name and no id. Take the next
* unanswered call of the pending assistant turn.
*
* An observation with no call to answer is the common
* case in files written before this format: the writer
* never stored the assistant turn's tool_calls, so there
* is nothing to pair with. Dropping the line is what made
* a resumed session 99% empty, and keeping it unpaired is
* what a provider rejects with 400. So the pair is built
* here: a synthetic assistant turn carrying exactly the
* calls these results answer, inserted before them.
*/
if (use_id == NULL && pending_n > 0 &&
pending_used < pending_n)
use_id = pending_ids[pending_used];
if (use_id == NULL || use_id[0] == '\0') {
if (!synth_call(conv, (name != NULL && name[0] != '\0') ?
name : "tool"))
continue;
use_id = last_synth_id;
}
if (pending_n > 0 && pending_used < pending_n)
pending_used++;
memset(&tm, 0, sizeof(tm));
tm.role = "tool";
tm.name = (char *)((name != NULL && name[0] != '\0') ? name :
"tool");
tm.call_id = (char *)use_id;
tm.content = (char *)text;
if (sp_conv_add(conv, &tm) == 0)
n++;
}
mcp_json_free(v);
}
/*
* The ids were strdup'd for the tool results that follow; once the file
* is read they have no owner left. The conversation keeps the call_id
* strings of the messages it was given, not these.
*/
{
size_t i;
/* every id, used or not: an unanswered call leaks too */
for (i = 0; i < pending_n; i++)
free(pending_ids[i]);
}
free(pending_calls);
free(line);
fclose(f);
if (loaded != NULL)
+57
View File
@@ -11,6 +11,7 @@
#include <unistd.h>
#include "splinter.h"
#include "splinter_plugin.h"
static int failures;
@@ -549,6 +550,62 @@ main(void)
sp_registry_free(&r2);
}
/*
* 13. A conversation over max_bytes is compacted, not refused. The core
* compactor lives behind the host; before this test the engine built
* the host only when a plugin was configured, so a plugin-less run
* had no compactor and every long conversation died on the ceiling
* with "budget exceeded". Long input, small budget, the turn must go
* through and the conversation must come out smaller.
*/
{
struct sp_agent a;
struct sp_agent_config cfg;
struct sp_transport tr;
struct sp_conv c;
struct sp_host *h;
struct sp_registry r3;
size_t i, before, after;
memset(&r3, 0, sizeof(r3));
setup(&r3);
CHECK(sp_mock_init(&m) == 0);
for (i = 0; i < 6; i++)
CHECK(sp_mock_push(&m, 200, "answer ack") == 0);
h = sp_host_new(&r3, NULL, NULL);
CHECK(h != NULL);
sp_conv_init(&c);
for (i = 0; i < 24; i++)
CHECK(sp_conv_push(&c, i % 2 ? "assistant" : "user",
NULL, "a piece of the conversation that costs bytes, "
"long enough to matter once there are a few of them")
== 0);
memset(&a, 0, sizeof(a));
memset(&cfg, 0, sizeof(cfg));
memset(&tr, 0, sizeof(tr));
cfg.max_steps = 8;
cfg.autonomous = 1;
cfg.max_bytes = 2400;
tr = sp_mock_transport(&m);
a.reg = &r3;
a.cfg = &cfg;
a.tr = tr;
a.conv = &c;
a.host = h;
before = sp_conv_bytes(&c);
CHECK(before > cfg.max_bytes);
sp_buf_clear(&answer);
sp_buf_clear(&err);
CHECK(sp_agent_run(&a, "go on", &answer, &err) == 0);
after = sp_conv_bytes(&c);
CHECK(after < before);
CHECK(a.stats.compactions > 0);
sp_conv_free(&c);
sp_host_free(h);
sp_registry_free(&r3);
sp_mock_free(&m);
}
sp_buf_free(&answer);
sp_buf_free(&err);
sp_registry_free(&r);
+9
View File
@@ -582,6 +582,15 @@ main(void)
CHECK(strcmp(tc.v[0].role, "system") == 0);
CHECK(strstr(tc.v[1].content, "[lcm]") != NULL);
CHECK(strcmp(tc.v[tc.n - 1].content, "and now?") == 0);
/*
* The tail keeps its promised size. Walking forward past the
* tool results left four messages of the six the constant
* names; walking back to the assistant that carries the call
* keeps all six, because the call record is what those results
* belong to. Four still has no orphan, which is why the check
* above alone did not notice.
*/
CHECK(tc.n == 9); /* 2 leading + 6 verbatim, no orphan */
sp_conv_free(&tc);
}
+430
View File
@@ -0,0 +1,430 @@
/*
* splinter -- the core compactor, without any plugin.
*
* The failure this guards against was silent: compact_threshold and
* compact_target were read, a budget was computed from them, and the compactor
* list was empty unless `plugin lcm` had been loaded. The conversation then grew
* until the provider cut it. This test registers NOTHING but the host, so every
* assertion below fails on the old code.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "splinter.h"
#include "splinter_plugin.h"
#include "config.h"
#include "embed.h"
static int failures;
#define CHECK(cond) do { \
if (!(cond)) { \
fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \
failures++; \
} \
} while (0)
static void
fill(struct sp_conv *c, int n, size_t pad)
{
int i;
char *big = malloc(pad + 64);
if (big == NULL)
return;
memset(big, 'x', pad);
big[pad] = '\0';
sp_conv_init(c);
sp_conv_push(c, "system", NULL, "you are a harness");
for (i = 0; i < n; i++) {
char text[256];
if (i % 5 == 4)
sp_conv_push(c, "tool", "run", big);
else {
snprintf(text, sizeof(text), "message %d %s", i, big);
sp_conv_push(c, (i % 2) ? "assistant" : "user", NULL,
text);
}
}
free(big);
}
/* --- 1. a conversation that fits is not touched ------------------------- */
static void
test_fits(void)
{
struct sp_conv c;
size_t before, n;
fill(&c, 4, 32);
before = sp_conv_bytes(&c);
n = c.n;
CHECK(sp_host_compact(NULL, &c, 1000000) == 0);
CHECK(sp_conv_bytes(&c) == before);
CHECK(c.n == n);
sp_conv_free(&c);
printf("ok 1 - a conversation under budget is untouched\n");
}
/* --- 2. the host carries a compactor with no plugin loaded -------------- */
static void
test_core_registered(void)
{
struct sp_host *h;
struct sp_conv c;
size_t before;
h = sp_host_new(NULL, NULL, NULL);
CHECK(h != NULL);
if (h == NULL)
return;
fill(&c, 40, 400);
before = sp_conv_bytes(&c);
CHECK(before > 4000);
CHECK(sp_host_compact(h, &c, 4000) == 1);
CHECK(sp_conv_bytes(&c) < before);
sp_conv_free(&c);
sp_host_free(h);
printf("ok 2 - the core compactor runs with no plugin loaded\n");
}
/* --- 3. the tail survives, the front goes ------------------------------- */
static void
test_tail_kept(void)
{
struct sp_host *h;
struct sp_conv c;
size_t i;
int found_last = 0;
h = sp_host_new(NULL, NULL, NULL);
fill(&c, 40, 400);
sp_conv_push(&c, "user", NULL, "THE QUESTION THAT MUST SURVIVE");
(void)sp_host_compact(h, &c, 4000);
for (i = 0; i < c.n; i++)
if (c.v[i].content != NULL &&
strstr(c.v[i].content, "MUST SURVIVE") != NULL)
found_last = 1;
CHECK(found_last);
sp_conv_free(&c);
sp_host_free(h);
printf("ok 3 - the newest question survives compaction\n");
}
/* --- 4. the cut is announced, never silent ------------------------------ */
static void
test_summary_present(void)
{
struct sp_host *h;
struct sp_conv c;
size_t i;
int note = 0;
h = sp_host_new(NULL, NULL, NULL);
fill(&c, 40, 400);
(void)sp_host_compact(h, &c, 4000);
for (i = 0; i < c.n; i++)
if (c.v[i].role != NULL && strcmp(c.v[i].role, "system") == 0 &&
c.v[i].content != NULL &&
strstr(c.v[i].content, "[thread so far - compacted]") != NULL)
note = 1;
CHECK(note);
CHECK(c.v[0].content != NULL &&
strcmp(c.v[0].content, "you are a harness") == 0);
sp_conv_free(&c);
sp_host_free(h);
printf("ok 4 - a system note says what was removed, original prompt stays\n");
}
/* --- 5. the tail never starts on a tool result -------------------------- */
static void
test_no_orphan_tool(void)
{
struct sp_host *h;
struct sp_conv c;
size_t i;
h = sp_host_new(NULL, NULL, NULL);
fill(&c, 40, 400);
(void)sp_host_compact(h, &c, 3000);
/*
* Walk from the note forward: the first message after the compaction
* seam must not be a tool result whose assistant turn is gone.
*/
for (i = 1; i < c.n; i++) {
if (c.v[i].role != NULL && strcmp(c.v[i].role, "tool") == 0) {
size_t j = i;
while (j > 0) {
j--;
if (c.v[j].role == NULL)
break;
if (strcmp(c.v[j].role, "assistant") == 0)
break;
if (strcmp(c.v[j].role, "system") == 0 &&
c.v[j].content != NULL &&
strstr(c.v[j].content,
"[thread so far - compacted]") != NULL)
break;
}
CHECK(j > 0 && c.v[j].role != NULL &&
strcmp(c.v[j].role, "assistant") == 0);
}
}
sp_conv_free(&c);
sp_host_free(h);
printf("ok 5 - no tool result is orphaned from its assistant turn\n");
}
/* --- 6. compaction actually shrinks, and is idempotent ------------------ */
static void
test_shrinks_and_settles(void)
{
struct sp_host *h;
struct sp_conv c;
size_t a, b, c2;
int r2;
h = sp_host_new(NULL, NULL, NULL);
fill(&c, 60, 500);
a = sp_conv_bytes(&c);
CHECK(sp_host_compact(h, &c, 6000) == 1);
b = sp_conv_bytes(&c);
CHECK(b < a);
r2 = sp_host_compact(h, &c, 6000);
c2 = sp_conv_bytes(&c);
if (r2 == 1)
CHECK(c2 < b); /* a second cut may happen, but shrinks */
else
CHECK(c2 == b);
sp_conv_free(&c);
sp_host_free(h);
printf("ok 6 - compaction shrinks the conversation (%zu -> %zu)\n", a, b);
}
/* --- 7. a budget of 0 means "no compaction", not "compact to nothing" --- */
static void
test_zero_budget(void)
{
struct sp_conv c;
size_t before;
fill(&c, 20, 200);
before = sp_conv_bytes(&c);
CHECK(sp_host_compact(NULL, &c, 0) == 0);
CHECK(sp_conv_bytes(&c) == before);
sp_conv_free(&c);
printf("ok 7 - a zero budget compacts nothing\n");
}
/* --- 8. trimming is preferred over deleting ----------------------------- */
static void
test_trim_before_drop(void)
{
struct sp_host *h;
struct sp_conv c;
size_t before_n, trimmed_found = 0, i;
h = sp_host_new(NULL, NULL, NULL);
sp_conv_init(&c);
sp_conv_push(&c, "system", NULL, "sys");
for (i = 0; i < 30; i++) {
char *big = malloc(8192);
if (big == NULL)
break;
memset(big, 'y', 8191);
big[8191] = '\0';
sp_conv_push(&c, (i % 2) ? "assistant" : "user", NULL, "short");
sp_conv_push(&c, "tool", "run", big);
free(big);
}
before_n = c.n;
CHECK(sp_host_compact(h, &c, 12000) == 1);
for (i = 0; i < c.n; i++)
if (c.v[i].content != NULL &&
strstr(c.v[i].content, "trimmed by compaction") != NULL)
trimmed_found++;
CHECK(trimmed_found > 0);
CHECK(c.n <= before_n + 2);
sp_conv_free(&c);
sp_host_free(h);
printf("ok 8 - long tool output is trimmed rather than deleted (%zu bodies)\n",
trimmed_found);
}
/* --- 9. the thread survives: who asked what, in order -------------------- */
static void
test_thread_survives(void)
{
struct sp_host *h;
struct sp_conv c;
size_t i;
int first_task = 0, correction = 0, order_ok = 0;
size_t pos_task = 0, pos_fix = 0;
h = sp_host_new(NULL, NULL, NULL);
sp_conv_init(&c);
sp_conv_push(&c, "system", NULL, "you are a harness");
sp_conv_push(&c, "user", NULL,
"BAUE EINE MCP-BRUECKE fuer den ESP32, Ziel: deauth erkennen");
sp_conv_push(&c, "assistant", NULL, "Ich lese zuerst das Repo.");
sp_conv_push(&c, "user", NULL,
"nein, nimm das ANDERE repo, nicht ARTEX sondern apex-twin");
sp_conv_push(&c, "assistant", NULL, "Verstanden, apex-twin.");
for (i = 0; i < 20; i++) {
char t[300];
snprintf(t, sizeof(t), "fuell nachricht %zu ......", i);
sp_conv_push(&c, (i % 2) ? "assistant" : "user", NULL, t);
}
sp_conv_push(&c, "user", NULL, "DIE AKTUELLE FRAGE");
/* 0 is fine: at this budget it may already settle after the trim. What
* matters is the thread below, not the return code. */
(void)sp_host_compact(h, &c, 2200);
for (i = 0; i < c.n; i++) {
if (c.v[i].content == NULL)
continue;
if (strstr(c.v[i].content, "BAUE EINE MCP-BRUECKE") != NULL) {
first_task = 1;
pos_task = i;
}
if (strstr(c.v[i].content, "das ANDERE repo") != NULL) {
correction = 1;
pos_fix = i;
}
}
CHECK(first_task);
CHECK(correction);
/*
* The correction came after the task, so it must stay after it in the
* digest. This is the property lcm broke: the model forgot that the
* operator had changed direction and redid the first plan.
*/
order_ok = first_task && correction && pos_fix >= pos_task;
CHECK(order_ok);
printf("ok 9 - the thread survives in order (task at %zu, correction at %zu)\n",
pos_task, pos_fix);
sp_conv_free(&c);
sp_host_free(h);
}
/* --- 10. a bigger budget keeps more of the thread, not less ------------- */
static void
test_budget_scales_thread(void)
{
struct sp_host *h;
struct sp_conv c1, c2;
size_t i;
size_t small, large;
h = sp_host_new(NULL, NULL, NULL);
for (i = 0; i < 2; i++) {
struct sp_conv *c = i == 0 ? &c1 : &c2;
size_t k;
sp_conv_init(c);
sp_conv_push(c, "system", NULL, "sys");
for (k = 0; k < 40; k++) {
char t[600];
snprintf(t, sizeof(t), "message %zu %s", k,
"padding padding padding padding padding padding "
"padding padding padding padding padding padding "
"padding padding padding padding padding padding");
sp_conv_push(c, (k % 2) ? "assistant" : "user", NULL, t);
}
}
(void)sp_host_compact(h, &c1, 4000);
(void)sp_host_compact(h, &c2, 12000);
small = sp_conv_bytes(&c1);
large = sp_conv_bytes(&c2);
CHECK(large >= small);
printf("ok 10 - a larger budget keeps more (%zu vs %zu bytes)\n", small,
large);
sp_conv_free(&c1);
sp_conv_free(&c2);
sp_host_free(h);
}
/* --- 11. the digest points at history_search, but only if it exists ------ */
/*
* The digest is a lossy summary. If the index is off, the model must not be
* told about a tool that is not registered - a prompt naming a missing tool
* teaches it to call nothing. Both halves are checked against the real
* registry, because "embed = off" is a supported configuration.
*/
static void
test_search_hint(void)
{
struct sp_registry reg;
struct sp_config conf;
struct sp_embed_ctx *emb;
struct sp_host *h;
struct sp_conv c;
size_t i;
int hinted = 0;
memset(&reg, 0, sizeof(reg));
sp_config_init(&conf);
conf.embed = SP_EMBED_OFF; /* no index: no tool */
h = sp_host_new(&reg, NULL, NULL);
fill(&c, 40, 400);
(void)sp_host_compact(h, &c, 4000);
for (i = 0; i < c.n; i++)
if (c.v[i].content != NULL &&
strstr(c.v[i].content, "history_search") != NULL)
hinted = 1;
CHECK(!hinted);
sp_conv_free(&c);
sp_host_free(h);
/* now with the tool really registered, as the engine does it */
memset(&reg, 0, sizeof(reg));
sp_config_init(&conf);
conf.embed = SP_EMBED_LOCAL;
emb = sp_embed_new(&conf);
CHECK(emb != NULL);
h = sp_host_new(&reg, NULL, NULL);
CHECK(h != NULL);
CHECK(sp_embed_register(sp_host_registry(h), emb) == 0);
fill(&c, 40, 400);
(void)sp_host_compact(h, &c, 4000);
hinted = 0;
for (i = 0; i < c.n; i++)
if (c.v[i].content != NULL &&
strstr(c.v[i].content, "history_search") != NULL)
hinted = 1;
CHECK(hinted);
sp_conv_free(&c);
sp_host_free(h);
sp_embed_free(emb);
sp_registry_free(&reg);
printf("ok 11 - the digest names history_search only when it exists\n");
}
int
main(void)
{
test_fits();
test_core_registered();
test_tail_kept();
test_summary_present();
test_no_orphan_tool();
test_shrinks_and_settles();
test_zero_budget();
test_trim_before_drop();
test_thread_survives();
test_budget_scales_thread();
test_search_hint();
if (failures > 0) {
fprintf(stderr, "%d check(s) failed\n", failures);
return 1;
}
printf("all compact checks passed\n");
return 0;
}
+18 -9
View File
@@ -24,6 +24,15 @@ static int failures;
} \
} while (0)
/*
* The focus plugin ignores the budget, but the core compactor does not: it
* trims and digests whenever the conversation does not fit. This file tests
* reminders, so it hands over a budget nothing can exceed. The old "1" meant
* "one byte" the moment the core started reading it, and the core then ate the
* reminders the test was looking for.
*/
#define NO_PRESSURE ((size_t)-1)
static int
count_focus(const struct sp_conv *c)
{
@@ -101,7 +110,7 @@ main(void)
/* turn 2: the reminder appears, once, and says so */
CHECK(sp_conv_push(&conv, "user", NULL, "zweiter turn") == 0);
sp_host_turn(host);
CHECK(sp_host_compact(host, &conv, 1) == 1);
CHECK(sp_host_compact(host, &conv, NO_PRESSURE) == 1);
CHECK(count_focus(&conv) == 2);
{
char msg[256], snap[1024];
@@ -127,19 +136,19 @@ main(void)
strstr(conv.v[2].content, "Ship the config file") != NULL);
/* compacting again in the same turn must not add a second one */
CHECK(sp_host_compact(host, &conv, 1) == 0);
CHECK(sp_host_compact(host, &conv, NO_PRESSURE) == 0);
CHECK(count_focus(&conv) == 2);
/* turn 3: silent */
CHECK(sp_conv_push(&conv, "user", NULL, "dritter turn") == 0);
sp_host_turn(host);
CHECK(sp_host_compact(host, &conv, 1) == 0);
CHECK(sp_host_compact(host, &conv, NO_PRESSURE) == 0);
CHECK(count_focus(&conv) == 2);
/* turn 4: second reminder, with the completion rule in it */
CHECK(sp_conv_push(&conv, "user", NULL, "vierter turn") == 0);
sp_host_turn(host);
CHECK(sp_host_compact(host, &conv, 1) == 1);
CHECK(sp_host_compact(host, &conv, NO_PRESSURE) == 1);
CHECK(count_focus(&conv) == 3);
CHECK(strstr(conv.v[conv.n - 2].content, "GOAL_COMPLETE") != NULL);
@@ -167,14 +176,14 @@ main(void)
CHECK(sp_conv_push(&conv, "user", NULL,
"Goal: neues ziel. Write a short recap.") == 0);
sp_host_turn(host);
CHECK(sp_host_compact(host, &conv, 1) == 0);
CHECK(sp_host_compact(host, &conv, NO_PRESSURE) == 0);
/* the answer is the recap; the next turn injects it */
CHECK(sp_conv_push(&conv, "assistant", NULL,
"KURZ: neues ziel, erster Schritt") == 0);
CHECK(sp_conv_push(&conv, "user", NULL, "weiter") == 0);
sp_host_turn(host);
CHECK(sp_host_compact(host, &conv, 1) == 1);
CHECK(sp_host_compact(host, &conv, NO_PRESSURE) == 1);
CHECK(count_focus(&conv) == 1);
for (i = 0; i < conv.n; i++)
if (conv.v[i].content != NULL &&
@@ -207,7 +216,7 @@ main(void)
int before = count_focus(&conv);
char snap[1024];
CHECK(sp_host_compact(host, &conv, 1) == 0);
CHECK(sp_host_compact(host, &conv, NO_PRESSURE) == 0);
CHECK(count_focus(&conv) == before);
snap[0] = '\0';
sp_host_widget_snapshot(host, snap, sizeof(snap));
@@ -224,14 +233,14 @@ main(void)
CHECK(strstr(out.p, "succeeded") != NULL);
CHECK(sp_conv_push(&conv, "user", NULL, "noch ein turn") == 0);
sp_host_turn(host);
CHECK(sp_host_compact(host, &conv, 1) == 0);
CHECK(sp_host_compact(host, &conv, NO_PRESSURE) == 0);
/* a new goal opens a new one, and is announced again */
sp_buf_clear(&out);
CHECK(sp_host_command(host, "goal", "zweites ziel", &out) == 0);
CHECK(sp_conv_push(&conv, "user", NULL, "los") == 0);
sp_host_turn(host);
CHECK(sp_host_compact(host, &conv, 1) == 1);
CHECK(sp_host_compact(host, &conv, NO_PRESSURE) == 1);
{
char snap[1024];
+148
View File
@@ -117,6 +117,42 @@ main(void)
CHECK(strcmp(v[0].title, "Ein Titel") == 0);
}
/*
* A key the core does not own survives every rewrite. A plugin that
* marks a session in the same sidecar (workspace/foreign.c records
* foreign=hermes:h-1 there) lost its marker on the first reopen,
* because meta_write only ever wrote the keys it knew.
*/
{
char mpath[700], line[200], extra[200];
FILE *mf;
int found = 0;
snprintf(mpath, sizeof(mpath), "%s/s1.meta", dir);
mf = fopen(mpath, "a");
CHECK(mf != NULL);
if (mf != NULL) {
fputs("foreign=hermes:h-1\n", mf);
fclose(mf);
}
/* reopen, rename and /goal each rewrite the file */
CHECK(sp_session_open(&s, dir, "s1", &err) == 0);
CHECK(sp_session_set_title(dir, "s1", "Noch ein Titel",
&err) == 0);
CHECK(sp_session_set_goal(dir, "s1", "Ship it", &err) == 0);
mf = fopen(mpath, "r");
CHECK(mf != NULL);
while (mf != NULL && fgets(line, sizeof(line), mf) != NULL) {
line[strcspn(line, "\r\n")] = '\0';
if (strcmp(line, "foreign=hermes:h-1") == 0)
found = 1;
}
if (mf != NULL)
fclose(mf);
snprintf(extra, sizeof(extra), "%s", found ? "kept" : "lost");
CHECK(strcmp(extra, "kept") == 0);
}
/* reopening an existing session appends, it never truncates */
CHECK(sp_session_open(&s, dir, "s1", &err) == 0);
CHECK(sp_session_append(&s, "user", "again", &err) == 0);
@@ -218,6 +254,118 @@ main(void)
}
}
/*
* A session is an agent transcript, not a chat log: almost every line is
* an observation. The first loader kept only user and assistant, which
* handed a resumed run 21 of 1507 lines - questions with no answers and
* no evidence between them. Everything below must come back.
*/
{
struct sp_conv c;
struct sp_sess_rec r;
size_t loaded = 0;
CHECK(sp_session_open(&s, dir, "full", &err) == 0);
memset(&r, 0, sizeof(r));
r.role = "user";
r.text = "BAUE EINE BRUECKE";
CHECK(sp_session_append_rec(&s, &r, &err) == 0);
r.role = "assistant";
r.text = "";
r.calls = "[{\"id\":\"c1\",\"type\":\"function\","
"\"function\":{\"name\":\"run\",\"arguments\":\"{}\"}}]";
CHECK(sp_session_append_rec(&s, &r, &err) == 0);
memset(&r, 0, sizeof(r));
r.role = "tool";
r.text = "DIE BEOBACHTUNG";
r.name = "run";
r.call_id = "c1";
CHECK(sp_session_append_rec(&s, &r, &err) == 0);
r.role = "assistant";
r.text = "Fertig.";
r.name = NULL;
r.call_id = NULL;
CHECK(sp_session_append_rec(&s, &r, &err) == 0);
sp_conv_init(&c);
CHECK(sp_session_load(&s, &c, &loaded, &err) == 0);
CHECK(loaded == 4);
CHECK(c.n == 4);
if (c.n == 4) {
CHECK(strcmp(c.v[0].role, "user") == 0);
CHECK(strcmp(c.v[1].role, "assistant") == 0);
CHECK(c.v[1].calls != NULL);
CHECK(strcmp(c.v[2].role, "tool") == 0);
CHECK(c.v[2].name != NULL &&
strcmp(c.v[2].name, "run") == 0);
CHECK(c.v[2].call_id != NULL &&
strcmp(c.v[2].call_id, "c1") == 0);
CHECK(strcmp(c.v[2].content, "DIE BEOBACHTUNG") == 0);
}
sp_conv_free(&c);
CHECK(sp_session_delete(dir, "full", &err) == 0);
}
/* empty text is not a message: it must not reach the file */
{
struct sp_conv c;
size_t loaded = 0;
char line[800];
FILE *g;
int has_blank = 0;
CHECK(sp_session_open(&s, dir, "blank", &err) == 0);
CHECK(sp_session_append(&s, "user", "", &err) == 0);
CHECK(sp_session_append(&s, "user", "ECHT", &err) == 0);
snprintf(path, sizeof(path), "%s/blank.jsonl", dir);
g = fopen(path, "r");
CHECK(g != NULL);
if (g != NULL) {
while (fgets(line, sizeof(line), g) != NULL)
if (strstr(line, "\"text\":\"\"") != NULL)
has_blank = 1;
fclose(g);
}
CHECK(!has_blank);
sp_conv_init(&c);
CHECK(sp_session_load(&s, &c, &loaded, &err) == 0);
CHECK(loaded == 1);
sp_conv_free(&c);
CHECK(sp_session_delete(dir, "blank", &err) == 0);
}
/*
* A file written before the format: an observation with no name, no
* call_id and no assistant turn carrying calls. It must still come back;
* dropping it is what emptied every resumed session.
*/
{
struct sp_conv c;
size_t loaded = 0;
int found = 0;
snprintf(path, sizeof(path), "%s/old.jsonl", dir);
f = fopen(path, "w");
CHECK(f != NULL);
if (f != NULL) {
fputs("{\"role\":\"user\",\"text\":\"AUFGABE\"}\n", f);
fputs("{\"role\":\"observation\",\"text\":\"ALTEBEFUND\"}\n",
f);
fclose(f);
}
CHECK(sp_session_open(&s, dir, "old", &err) == 0);
sp_conv_init(&c);
CHECK(sp_session_load(&s, &c, &loaded, &err) == 0);
for (size_t k = 0; k < c.n; k++)
if (c.v[k].content != NULL &&
strstr(c.v[k].content, "ALTEBEFUND") != NULL)
found = 1;
CHECK(found);
sp_conv_free(&c);
CHECK(sp_session_delete(dir, "old", &err) == 0);
}
sp_buf_free(&err);
printf("test_session: ok (%s)\n", dir);
return failures == 0 ? 0 : 1;