Files
splinter/src/session.c
T
Konrad e4f25b481f splinter: sessions belong to a directory, and splinter as an MCP server
Every session records the directory it was started in (<id>.meta, cwd=). With
that, '-c' means the last session that happened *here*:

  cd ~/src/splinter && splinter -c

A session from another tree is never silently loaded; if nothing happened in this
directory yet, it says so and exits. Verified in three directories - two report
no session, the one with history resumes.

folder_history gives the model the folder's memory instead of a guess: sessions
started there, newest first, with turn count and the last question.

--mcp-server-listen IP --mcp-listen-port N serves the registry over MCP
(newline-delimited JSON-RPC on TCP): initialize, tools/list, tools/call. Read
tools are served; mutating and destructive ones are refused unless the server was
started with --autonomous - a remote agent does not run shell commands here
because it asked nicely.

Proven with a real client on 127.0.0.1:8097: handshake answers splinter 0.1.0,
tools/list reports 14 tools, tools/call list returns the directory, tools/call run
is refused with the authorization message.
2026-11-08 14:35:29 +00:00

476 lines
11 KiB
C

/*
* splinter -- append-only session log.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* One JSON object per line, opened O_APPEND. A crash can only truncate the
* tail, so recovery is "replay complete lines, drop one partial line". Nothing
* here ever rewrites an earlier record: history that can be edited is history
* you cannot trust after an incident.
*/
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <sys/stat.h>
#include <unistd.h>
#include "splinter.h"
#include "mcp.h"
#include "log.h"
#include <dirent.h>
#include <sys/stat.h>
static int
mkdir_p(const char *path)
{
char buf[512];
size_t i, n;
n = strlen(path);
if (n == 0 || n >= sizeof(buf)) {
errno = ENAMETOOLONG;
return -1;
}
memcpy(buf, path, n + 1);
for (i = 1; i < n; i++) {
if (buf[i] != '/')
continue;
buf[i] = '\0';
if (mkdir(buf, 0755) != 0 && errno != EEXIST)
return -1;
buf[i] = '/';
}
if (mkdir(buf, 0755) != 0 && errno != EEXIST)
return -1;
return 0;
}
int
sp_session_open(struct sp_session_info *info, const char *dir,
const char *id, struct sp_buf *err)
{
char path[640];
int fd;
if (dir == NULL || id == NULL || info == NULL) {
sp_buf_puts(err, "session: dir and id are required");
return -1;
}
if (strlen(id) >= sizeof(info->id) || strlen(dir) >= sizeof(info->dir)) {
sp_buf_puts(err, "session: id or dir too long");
return -1;
}
snprintf(info->id, sizeof(info->id), "%s", id);
snprintf(info->dir, sizeof(info->dir), "%s", dir);
if (mkdir_p(dir) != 0) {
sp_buf_printf(err, "session: cannot create %s: %s", dir,
strerror(errno));
return -1;
}
snprintf(path, sizeof(path), "%s/%s.jsonl", dir, info->id);
fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0600);
if (fd < 0) {
sp_buf_printf(err, "session: cannot open %s: %s", path,
strerror(errno));
return -1;
}
close(fd);
/*
* 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.
*/
{
char mpath[700], cwd[512], tmp[800];
FILE *m;
time_t now = time(NULL);
if (getcwd(cwd, sizeof(cwd)) == NULL)
snprintf(cwd, sizeof(cwd), "?");
snprintf(mpath, sizeof(mpath), "%s/%s.meta", dir, info->id);
snprintf(tmp, sizeof(tmp), "%s.tmp", mpath);
m = fopen(tmp, "w");
if (m != NULL) {
fprintf(m, "cwd=%s\ncreated=%ld\nopened=%ld\n", cwd,
(long)now, (long)now);
fclose(m);
(void)rename(tmp, mpath);
}
}
return 0;
}
static int
write_all(int fd, const char *p, size_t n)
{
ssize_t w;
while (n > 0) {
w = write(fd, p, n);
if (w < 0) {
if (errno == EINTR)
continue;
return -1;
}
p += (size_t)w;
n -= (size_t)w;
}
return 0;
}
int
sp_session_append(const struct sp_session_info *info, const char *role,
const char *text, struct sp_buf *err)
{
struct sp_buf line;
char path[640];
int fd, rc;
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);
if (rc == 0)
rc = sp_buf_puts(&line, "\",\"text\":\"");
if (rc == 0)
rc = sp_json_escape(&line, text);
if (rc == 0)
rc = sp_buf_puts(&line, "\"}\n");
if (rc != 0) {
sp_buf_puts(err, "session: out of memory");
sp_buf_free(&line);
return -1;
}
snprintf(path, sizeof(path), "%s/%s.jsonl", info->dir, info->id);
fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0600);
if (fd < 0) {
sp_buf_printf(err, "session: cannot open %s: %s", path,
strerror(errno));
sp_buf_free(&line);
return -1;
}
rc = write_all(fd, line.p, line.len);
if (rc == 0 && fsync(fd) != 0)
rc = -1;
if (rc != 0)
sp_buf_printf(err, "session: write failed: %s", strerror(errno));
close(fd);
sp_buf_free(&line);
return rc;
}
int
sp_session_count(const struct sp_session_info *info, size_t *n,
struct sp_buf *err)
{
char path[640], chunk[4096];
FILE *f;
size_t count = 0, i, got;
snprintf(path, sizeof(path), "%s/%s.jsonl", info->dir, info->id);
*n = 0;
f = fopen(path, "r");
if (f == NULL) {
if (errno == ENOENT)
return 0;
sp_buf_printf(err, "session: cannot read %s: %s", path,
strerror(errno));
return -1;
}
while ((got = fread(chunk, 1, sizeof(chunk), f)) > 0) {
for (i = 0; i < got; i++)
if (chunk[i] == '\n')
count++;
}
if (ferror(f)) {
sp_buf_printf(err, "session: read error on %s", path);
fclose(f);
return -1;
}
fclose(f);
/*
* Only complete lines (terminated by a newline) are records: a torn tail
* from a crash is skipped, not repaired and not an error.
*/
*n = count;
return 0;
}
/*
* Load a session back into a conversation.
*
* The JSONL is the record of what happened, so resuming is reading it, not
* reconstructing something else. Records this build does not understand (a
* thinking entry, a tool line) are skipped and counted, never guessed at.
*/
int
sp_session_load(const struct sp_session_info *info, struct sp_conv *conv,
size_t *loaded, struct sp_buf *err)
{
struct sp_buf raw;
char path[640], line[8192];
FILE *f;
size_t n = 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 */
if (sp_buf_init(&raw) != 0) {
fclose(f);
return -1;
}
while (fgets(line, sizeof(line), f) != NULL) {
mcp_json *v;
const char *role, *text;
if (line[0] != '{')
continue; /* a torn tail is not a record */
v = mcp_parse(line);
if (v == NULL)
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)
n++;
}
mcp_json_free(v);
}
fclose(f);
sp_buf_free(&raw);
if (loaded != NULL)
*loaded = n;
return 0;
}
/*
* The newest session in a directory.
*
* Resuming should continue what was last used, not create a new id beside it -
* the first version of --resume did exactly that and silently resumed nothing.
*/
int
sp_session_latest(const char *dir, char *id, size_t cap)
{
DIR *d;
struct dirent *e;
char best[128] = "";
time_t best_t = 0;
d = opendir(dir);
if (d == NULL)
return -1;
while ((e = readdir(d)) != NULL) {
struct stat st;
char path[700];
if (strncmp(e->d_name, "sess-", 5) != 0)
continue;
if (strlen(e->d_name) < 5 + 5 ||
strcmp(e->d_name + strlen(e->d_name) - 6, ".jsonl") != 0)
continue;
snprintf(path, sizeof(path), "%s/%s", dir, e->d_name);
if (stat(path, &st) != 0 || !S_ISREG(st.st_mode))
continue;
if (st.st_mtime >= best_t) {
best_t = st.st_mtime;
snprintf(best, sizeof(best), "%s", e->d_name);
}
}
closedir(d);
if (best[0] == '\0')
return -1;
best[strlen(best) - 6] = '\0'; /* strip .jsonl */
snprintf(id, cap, "%s", best);
return 0;
}
/* The cwd recorded for a session, or NULL. */
static int
meta_cwd(const char *dir, const char *id, char *buf, size_t cap)
{
char path[700], line[600];
FILE *f;
int found = 0;
snprintf(path, sizeof(path), "%s/%s.meta", dir, id);
f = fopen(path, "r");
if (f == NULL)
return -1;
while (fgets(line, sizeof(line), f) != NULL) {
if (strncmp(line, "cwd=", 4) != 0)
continue;
snprintf(buf, cap, "%.*s", (int)(cap - 1), line + 4);
buf[strcspn(buf, "\r\n")] = '\0';
found = 1;
break;
}
fclose(f);
return found ? 0 : -1;
}
/*
* The newest session started in this directory.
*
* 'splinter -c' in ~/src/splinter means "the last thing I did here" - not the
* last thing I did anywhere. Sessions from other directories are the wrong
* answer and would silently load the wrong context.
*/
int
sp_session_last_for(const char *dir, const char *cwd, char *id, size_t cap)
{
DIR *d;
struct dirent *e;
char best[128] = "";
time_t best_t = 0;
d = opendir(dir);
if (d == NULL)
return -1;
while ((e = readdir(d)) != NULL) {
struct stat st;
char path[700], session_cwd[512];
size_t len = strlen(e->d_name);
if (len < 6 || strcmp(e->d_name + len - 5, ".meta") != 0)
continue;
e->d_name[len - 5] = '\0';
snprintf(path, sizeof(path), "%s/%s.meta", dir, e->d_name);
if (stat(path, &st) != 0)
continue;
if (meta_cwd(dir, e->d_name, session_cwd,
sizeof(session_cwd)) != 0)
continue;
if (strcmp(session_cwd, cwd) != 0)
continue;
if (st.st_mtime >= best_t) {
best_t = st.st_mtime;
snprintf(best, sizeof(best), "%s", e->d_name);
}
}
closedir(d);
if (best[0] == '\0')
return -1;
snprintf(id, cap, "%s", best);
return 0;
}
/*
* What happened in a directory: the sessions started there, newest first, with
* the number of turns and the last thing that was asked. This is the folder's
* memory - readable by the model through a tool, not guessed.
*/
int
sp_session_folder_history(const char *dir, const char *cwd, unsigned limit,
struct sp_buf *out)
{
DIR *d;
struct dirent *e;
struct {
char name[128];
time_t mtime;
} found[64];
size_t n = 0, i, j;
d = opendir(dir);
if (d == NULL) {
sp_buf_printf(out, "no sessions in %s\n", dir);
return 0;
}
while ((e = readdir(d)) != NULL && n < 64) {
struct stat st;
char path[700], session_cwd[512];
size_t len = strlen(e->d_name);
if (len < 6 || strcmp(e->d_name + len - 5, ".meta") != 0)
continue;
e->d_name[len - 5] = '\0';
snprintf(path, sizeof(path), "%s/%s.meta", dir, e->d_name);
if (stat(path, &st) != 0)
continue;
if (meta_cwd(dir, e->d_name, session_cwd,
sizeof(session_cwd)) != 0)
continue;
if (cwd != NULL && strcmp(session_cwd, cwd) != 0)
continue;
snprintf(found[n].name, sizeof(found[n].name), "%s", e->d_name);
found[n].mtime = st.st_mtime;
n++;
}
closedir(d);
/* newest first, straight insertion: 64 entries, no library needed */
for (i = 1; i < n; i++) {
for (j = i; j > 0 && found[j - 1].mtime < found[j].mtime; j--) {
char tn[128];
time_t tm = found[j - 1].mtime;
snprintf(tn, sizeof(tn), "%s", found[j - 1].name);
snprintf(found[j - 1].name, sizeof(found[j - 1].name),
"%s", found[j].name);
found[j - 1].mtime = found[j].mtime;
snprintf(found[j].name, sizeof(found[j].name), "%s", tn);
found[j].mtime = tm;
}
}
if (n == 0) {
sp_buf_printf(out, "no sessions in %s%s%s\n", dir,
cwd != NULL ? " for " : "", cwd != NULL ? cwd : "");
return 0;
}
for (i = 0; i < n && i < limit; i++) {
char path[800], line[2048], stamp[32];
struct tm tm;
FILE *f;
time_t when = found[i].mtime;
size_t turns = 0;
char last[512] = "";
(void)localtime_r(&when, &tm);
strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M", &tm);
snprintf(path, sizeof(path), "%.500s/%.120s.jsonl", dir,
found[i].name);
f = fopen(path, "r");
if (f != NULL) {
while (fgets(line, sizeof(line), f) != NULL) {
turns++;
if (strstr(line, "\"role\":\"user\"") == NULL)
continue;
snprintf(last, sizeof(last), "%.511s", line);
}
fclose(f);
}
{
char *p = strstr(last, "\"text\":\"");
if (p != NULL) {
char *v = p + 9;
size_t k = 0;
while (*v != '\0' && *v != '"' && k + 1 < sizeof(last))
last[k++] = *v++;
last[k] = '\0';
} else
last[0] = '\0';
}
sp_buf_printf(out, "%s %s %zu records%s%s\n", stamp,
found[i].name, turns / 2,
last[0] != '\0' ? " last: " : "", last);
}
if (n > limit)
sp_buf_printf(out, "(%zu more)\n", n - limit);
return 0;
}