An open-source, faster Devin alternative
TypeScript
computer: one journal directory per session (work 103, step 4) (#1032)
opencomputer-app[bot]9ea7fdea7b5a
diff --git a/computer/src/api/journal-checkpoint.ts b/computer/src/api/journal-checkpoint.tsindex 5476e0dd..72eba5e6 100644--- a/computer/src/api/journal-checkpoint.ts+++ b/computer/src/api/journal-checkpoint.ts@@ -20,7 +20,8 @@// checkpoint first (Journal.load).import { createHash } from 'node:crypto';-import { closeSync, fchmodSync, openSync, readFileSync, readSync, renameSync, rmSync, writeSync } from 'node:fs';+import { closeSync, fchmodSync, readSync, renameSync, rmSync, writeSync } from 'node:fs';+import { OPEN, openRegular, readRegular } from './journal-dir.js';/** Bumped whenever the header's meaning changes; an older checkpoint is ignored. */const VERSION = 1;@@ -69,7 +70,7 @@ export function lineHash(fd: number, start: number, end: number): string {export function readCheckpoint(journal: string, fd: number, size: number, o: { sessionId?: string; fold: boolean }): { ck?: Checkpoint; offset: number; bytes: number } {let buf: Buffer;try {- buf = readFileSync(checkpointPath(journal));+ buf = readRegular(checkpointPath(journal)); // never through a link (journal-dir.ts)} catch {return { offset: 0, bytes: 0 };}@@ -104,7 +105,7 @@ export function writeCheckpoint(journal: string, h: Omit<CheckpointHeader, 'v'>,const tmp = `${file}.tmp`;const body = `${JSON.stringify({ v: VERSION, ...h })}\n${JSON.stringify(fold ?? null)}\n`;rmSync(tmp, { force: true }); // a temp left by another uid (runner or host): ours instead- const fd = openSync(tmp, 'w', 0o660);+ const fd = openRegular(tmp, OPEN.create);try {// As the journal's own mode: the umask may have masked the group bit (the other writer reads and replaces it).try {diff --git a/computer/src/api/journal-dir.test.ts b/computer/src/api/journal-dir.test.tsnew file mode 100644index 00000000..712c0f76--- /dev/null+++ b/computer/src/api/journal-dir.test.ts@@ -0,0 +1,55 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { mintId } from '../session-ids.js';+import { ensureJournalDir, ensureSessionJournalDir, journalPath } from './journal-dir.js';+import { saveResult } from './subagent-results.js';++let data: string;+let target: string;+beforeEach(() => {+ data = fs.mkdtempSync(path.join(os.tmpdir(), 'jdir-'));+ target = path.join(data, 'host-only');+ fs.mkdirSync(target, { mode: 0o700 });+});+afterEach(() => fs.rmSync(data, { recursive: true, force: true }));++const mode = (p: string) => fs.statSync(p).mode & 0o7777;++describe('journal directories', () => {+ it('a new journals directory is 02750; one that exists keeps the mode provisioning gave it', () => {+ expect(mode(ensureJournalDir(data))).toBe(0o2750);+ fs.chmodSync(path.join(data, 'journals'), 0o2770);+ ensureSessionJournalDir(data, mintId('cs'));+ expect(mode(path.join(data, 'journals'))).toBe(0o2770);+ });++ it('a session directory is 02770 whatever the umask, and made again it stays', () => {+ const id = mintId('cs');+ const before = process.umask(0o077);+ try {+ expect(mode(ensureSessionJournalDir(data, id))).toBe(0o2770);+ } finally {+ process.umask(before);+ }+ expect(mode(ensureSessionJournalDir(data, id))).toBe(0o2770);+ });++ it('a link where a session directory goes is refused before anything is chmodded through it', () => {+ const id = mintId('cs');+ fs.symlinkSync(target, path.join(ensureJournalDir(data), id));+ expect(() => ensureSessionJournalDir(data, id)).toThrow(/not a directory/);+ expect(mode(target)).toBe(0o700);+ });++ it('saveResult refuses a link where the results directory goes, and leaves its target as it was', () => {+ const id = mintId('cs');+ ensureSessionJournalDir(data, id);+ const journal = journalPath(data, id);+ fs.symlinkSync(target, `${journal}.results`);+ expect(() => saveResult(journal, mintId('sa'), 'x')).toThrow(/not a directory/);+ expect(mode(target)).toBe(0o700);+ expect(fs.readdirSync(target)).toEqual([]);+ });+});diff --git a/computer/src/api/journal-dir.ts b/computer/src/api/journal-dir.tsnew file mode 100644index 00000000..abc89515--- /dev/null+++ b/computer/src/api/journal-dir.ts@@ -0,0 +1,138 @@+// Where journals live, and how a file there is opened (work 084; one+// directory per session since work 103, C8):+//+// <dataDir>/journals/ provisioning's (02750 where the host makes it)+// <cs_…>/ 02770, made by the host (ensureSessionJournalDir)+// <cs_…>.jsonl the journal (journal.ts)+// <cs_…>.jsonl.ckpt its checkpoint (journal-checkpoint.ts)+// <cs_…>.jsonl.results/<sa_…> subagents' whole results (subagent-results.ts)+//+// A session's directory is the one thing of the journals its sandbox mounts,+// so a session sees and writes only its own.+//+// Invariants:+// - The host makes a session's directory, in a parent it can write; the+// runner never does. Both write inside it: the directory is setgid and+// group-writable and files are 0660, so the host (sp-host, in group agent)+// and the runner (agent) open each other's files. Modes are set outright,+// because mkdir's is masked by the umask and drops setgid; a chmod of a+// directory another uid owns fails and is ignored. A mode is only ever set+// on a directory opened without following a link (`ensureRealDir`).+// - What a session can write is never trusted to be what its name says+// (103, trust rule 4): every open here is O_NOFOLLOW and the result must be+// a regular file (`openRegular`; O_NONBLOCK so a planted FIFO cannot hold+// the caller), and a session's directory must be a directory, not a link.+// - Readers list sessions by directory name (`listJournals`): a file directly+// in `journals/` is not a journal (journal-flat-move.ts moves the old ones).++import { chmodSync, closeSync, constants, fchmodSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync } from 'node:fs';+import path from 'node:path';+import { isSessionId } from '../session-ids.js';++export const JOURNALS_DIR = 'journals';++export class JournalError extends Error {+ constructor(+ readonly code: 'locked' | 'stale_epoch' | 'closed' | 'bad_id' | 'lock_failed' | 'not_regular',+ message: string,+ ) {+ super(message);+ }+}++/** The journal of `sessionId` in a journals directory: `<journals>/<sessionId>/<sessionId>.jsonl`. */+export const journalIn = (journals: string, sessionId: string) => path.join(journals, sessionId, `${sessionId}.jsonl`);++/** `<dataDir>/journals/<sessionId>/<sessionId>.jsonl`. Pure: `ensureSessionJournalDir` makes the directory. */+export function journalPath(dataDir: string, sessionId: string): string {+ if (!isSessionId(sessionId)) throw new JournalError('bad_id', `not a session id: ${sessionId}`);+ return journalIn(path.join(dataDir, JOURNALS_DIR), sessionId);+}++/**+ * Make `dir` when it is missing (its parent exists) and set its mode, never through a link: the mode goes on the+ * directory this opened (O_NOFOLLOW), so a link put at the name, before or meanwhile, is refused and its target untouched.+ */+export function ensureRealDir(dir: string, mode: number): void {+ try {+ mkdirSync(dir, { mode });+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e;+ }+ let fd: number;+ try {+ fd = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);+ } catch (e) {+ const code = (e as NodeJS.ErrnoException).code;+ if (code === 'ELOOP' || code === 'ENOTDIR') throw new JournalError('not_regular', `not a directory: ${dir}`);+ throw e;+ }+ try {+ fchmodSync(fd, mode);+ } catch {+ // another uid owns it (made by the other writer): its mode is that one's to set+ } finally {+ closeSync(fd);+ }+}++/**+ * Create `<dataDir>/journals` when it is missing (02750: only the host makes sessions' directories in it). One that+ * exists keeps its owner and mode: those are provisioning's (deploy/vm/provision.sh). Returns it.+ */+export function ensureJournalDir(dataDir: string): string {+ const dir = path.join(dataDir, JOURNALS_DIR);+ if (mkdirSync(dir, { recursive: true, mode: 0o2750 }) !== undefined) chmodSync(dir, 0o2750); // made here: mkdir's mode is masked+ return dir;+}++/** Create the directory of `sessionId`'s journal (02770: files keep its group). The host calls it before a journal is opened by anyone. Returns it. */+export function ensureSessionJournalDir(dataDir: string, sessionId: string): string {+ const dir = path.dirname(journalPath(dataDir, sessionId));+ ensureJournalDir(dataDir);+ ensureRealDir(dir, 0o2770);+ return dir;+}++/** Every session with a directory in `journals` and where its journal is (the file may not exist). */+export function listJournals(journals: string): Array<{ sessionId: string; file: string }> {+ let names: string[];+ try {+ names = readdirSync(journals);+ } catch {+ return [];+ }+ return names.filter(isSessionId).map((sessionId) => ({ sessionId, file: journalIn(journals, sessionId) }));+}++/** The session a journal file belongs to by where it is: its directory's name, when that is a session id. */+export function sessionOfJournal(file: string): string | undefined {+ const name = path.basename(path.dirname(file));+ return isSessionId(name) ? name : undefined;+}++export const OPEN = {+ read: constants.O_RDONLY,+ /** Read and append, created when missing. */+ append: constants.O_RDWR | constants.O_APPEND | constants.O_CREAT,+ /** A new file to write; fails when the name is taken. */+ create: constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL,+};++/** Open `file` without following a link at its name; throws unless it is a regular file. */+export function openRegular(file: string, flags: number, mode = 0o660): number {+ const fd = openSync(file, flags | constants.O_NOFOLLOW | constants.O_NONBLOCK, mode);+ if (fstatSync(fd).isFile()) return fd;+ closeSync(fd);+ throw new JournalError('not_regular', `not a regular file: ${file}`);+}++/** The whole of a regular file (as `openRegular` takes it). */+export function readRegular(file: string): Buffer {+ const fd = openRegular(file, OPEN.read);+ try {+ return readFileSync(fd);+ } finally {+ closeSync(fd);+ }+}diff --git a/computer/src/api/journal-file.ts b/computer/src/api/journal-file.tsindex ce803c84..beab4667 100644--- a/computer/src/api/journal-file.ts+++ b/computer/src/api/journal-file.ts@@ -13,10 +13,15 @@// under a new epoch and wrote past the old end), is rescanned from the start; `forgetJournalFile` drops a file's state outright (the host// calls it when it rewrites a journal itself).// - Only complete lines count: a torn last line is read once it is whole.+// - The file is in a directory its session can write (work 103, trust rule 4):+// it is opened without following a link and must be a regular file, else it+// reads as no journal; a line naming a session other than the directory's+// is skipped.-import { closeSync, fstatSync, openSync, readSync } from 'node:fs';+import { closeSync, fstatSync, readSync } from 'node:fs';import type { JournalEvent } from '../protocol.js';import { readCheckpoint } from './journal-checkpoint.js';+import { OPEN, openRegular, sessionOfJournal } from './journal-dir.js';const INDEX_EVERY = 64;const CHUNK = 256 * 1024;@@ -48,8 +53,11 @@ export function forgetJournalFile(file: string): void {type OnLine = (v: Record<string, unknown>, offset: number, end: number) => boolean | void;+/** A line that says whose it is, and it is not `sessionId`'s. */+const foreign = (v: Record<string, unknown>, sessionId: string | undefined) => !!sessionId && typeof v.sessionId === 'string' && v.sessionId !== sessionId;+/** Each complete line of `buf` (as parsed JSON) with its offset from `base` and its end; returns the offset after the last newline. */-function eachLine(buf: Buffer, base: number, f: OnLine): number {+function eachLine(buf: Buffer, base: number, f: OnLine, sessionId?: string): number {let at = 0;for (let nl = buf.indexOf(10, at); nl >= 0; at = nl + 1, nl = buf.indexOf(10, at)) {if (nl === at) continue;@@ -59,6 +67,7 @@ function eachLine(buf: Buffer, base: number, f: OnLine): number {} catch {continue; // a line we cannot parse is skipped, never fatal}+ if (foreign(v, sessionId)) continue;if (f(v, base + at, base + nl + 1) === false) return base + nl + 1;}return base + at;@@ -66,8 +75,8 @@ function eachLine(buf: Buffer, base: number, f: OnLine): number {const isEvent = (v: Record<string, unknown>): v is Record<string, unknown> & JournalEvent => typeof v.seq === 'number' && v.k === undefined;-/** Read `fd` from `from` to `to` in chunks, handing complete lines to `f`; stops when `f` returns false. Returns the offset reached. */-export function scanRange(fd: number, from: number, to: number, f: OnLine): number {+/** Read `fd` from `from` to `to` in chunks, handing complete lines to `f` (but none naming a session other than `sessionId`, when given); stops when `f` returns false. Returns the offset reached. */+export function scanRange(fd: number, from: number, to: number, f: OnLine, sessionId?: string): number {const buf = Buffer.allocUnsafe(CHUNK);let carry = Buffer.alloc(0);let pos = from;@@ -85,7 +94,7 @@ export function scanRange(fd: number, from: number, to: number, f: OnLine): numb}const end = eachLine(chunk.subarray(0, lastNl + 1), base, (v, o, e) => {if (f(v, o, e) === false) return (stopped = true), false;- });+ }, sessionId);if (stopped) return end;base += lastNl + 1;carry = Buffer.from(chunk.subarray(lastNl + 1));@@ -94,11 +103,11 @@ export function scanRange(fd: number, from: number, to: number, f: OnLine): numb}/** Bring `file`'s state up to date with what it holds now. */-function refresh(file: string, fd: number): FileState {+function refresh(file: string, fd: number, sessionId: string | undefined): FileState {const st = fstatSync(fd);let s = files.get(file);if (!s || s.ino !== st.ino || st.size < s.scanned || !markHolds(fd, s)) {- const { ck } = readCheckpoint(file, fd, st.size, { fold: false });+ const { ck } = readCheckpoint(file, fd, st.size, { sessionId, fold: false });s = ck? { ino: st.ino, scanned: ck.offset, epoch: ck.epoch, startSeq: ck.startSeq, through: ck.through, lastSeq: ck.lastSeq, index: ck.index, mark: markAt(fd, ck.offset) }: { ino: st.ino, scanned: 0, epoch: 0, startSeq: 0, through: 0, lastSeq: 0, index: [], mark: Buffer.alloc(0) };@@ -117,7 +126,7 @@ function refresh(file: string, fd: number): FileState {if (!last || v.seq - last[0] >= INDEX_EVERY) state.index.push([v.seq, offset]);state.lastSeq = v.seq;}- });+ }, sessionId);state.mark = markAt(fd, state.scanned);}return s;@@ -151,12 +160,13 @@ export interface JournalFileRead {export function readJournalFile(file: string, after: number, limit = 500): JournalFileRead {let fd: number;try {- fd = openSync(file, 'r');+ fd = openRegular(file, OPEN.read);} catch {return { epoch: 0, startSeq: 0, through: 0, lastSeq: 0, events: [] };}try {- const s = refresh(file, fd);+ const sessionId = sessionOfJournal(file);+ const s = refresh(file, fd, sessionId);const events: JournalEvent[] = [];const head = { epoch: s.epoch, startSeq: s.startSeq, through: s.through, lastSeq: s.lastSeq };if (limit <= 0 || after >= s.lastSeq) return { ...head, events };@@ -172,7 +182,7 @@ export function readJournalFile(file: string, after: number, limit = 500): Journwhile (events.length && events[events.length - 1].seq >= v.seq) events.pop();events.push(v);if (events.length >= limit) return false;- });+ }, sessionId);return { ...head, events };} finally {closeSync(fd);diff --git a/computer/src/api/journal-lock.ts b/computer/src/api/journal-lock.tsindex cdf622d6..9d6ec9f0 100644--- a/computer/src/api/journal-lock.ts+++ b/computer/src/api/journal-lock.ts@@ -39,11 +39,16 @@ export class FileLock {});}- /** Hold an exclusive flock on `file` until `release` or this process ends. */- static take(file: string, waitMs = 0, flock = FLOCK): Promise<FileLock> {+ /**+ * Hold an exclusive flock on `file` until `release` or this process ends. With `fd` (the file, already open), the+ * child locks that file through its descriptor and never resolves the name, which a session may have replaced.+ */+ static take(file: string, waitMs = 0, flock = FLOCK, fd?: number): Promise<FileLock> {const wait = waitMs > 0 ? ['-w', String(Math.max(waitMs / 1000, 0.001))] : ['-n'];- const child = spawn(flock, ['-x', ...wait, '-E', String(CONFLICT), '-o', file, 'sh', '-c', 'echo locked; exec cat'], {- stdio: ['pipe', 'pipe', 'pipe'],+ // /dev/fd/3 opens the file anew (its own open file description), so the lock is the child's, not this process's.+ const target = fd === undefined ? file : '/dev/fd/3';+ const child = spawn(flock, ['-x', ...wait, '-E', String(CONFLICT), '-o', target, 'sh', '-c', 'echo locked; exec cat'], {+ stdio: fd === undefined ? ['pipe', 'pipe', 'pipe'] : ['pipe', 'pipe', 'pipe', fd],});return new Promise((resolve, reject) => {let out = '';diff --git a/computer/src/api/journal.test.ts b/computer/src/api/journal.test.tsindex eaba872f..b4d2b745 100644--- a/computer/src/api/journal.test.ts+++ b/computer/src/api/journal.test.ts@@ -5,7 +5,8 @@ import { Schema } from 'effect';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import type { ApiActor } from '../protocol.js';import { mintId } from '../session-ids.js';-import { ensureJournalDir, Journal, journalPath, readJournalFile } from './journal.js';+import { ensureSessionJournalDir, Journal, journalPath, readJournalFile } from './journal.js';+import { readCheckpoint } from './journal-checkpoint.js';import { EVENT_DATA, Event } from './schema-events.js';const ann: ApiActor = { id: 'usr_ann', name: null, via: 'api', client: 'test/1' };@@ -24,18 +25,83 @@ beforeEach(() => {dir = fs.mkdtempSync(path.join(os.tmpdir(), 'journal-'));sid = mintId('cs');file = journalPath(dir, sid);- ensureJournalDir(dir);+ ensureSessionJournalDir(dir, sid);});afterEach(async () => {for (const j of open.splice(0)) await j.release();fs.rmSync(dir, { recursive: true, force: true });});-describe('journalPath / ensureJournalDir', () => {- it('puts journals under <data>/journals with a setgid, group-writable dir', () => {- expect(file).toBe(path.join(dir, 'journals', `${sid}.jsonl`));- expect(fs.statSync(path.join(dir, 'journals')).mode & 0o7777).toBe(0o2770);+describe('journalPath / ensureSessionJournalDir', () => {+ it('puts a journal in its session\'s own setgid, group-writable directory under <data>/journals (work 103 C8)', () => {+ expect(file).toBe(path.join(dir, 'journals', sid, `${sid}.jsonl`));+ expect(fs.statSync(path.join(dir, 'journals')).mode & 0o7777).toBe(0o2750);+ expect(fs.statSync(path.join(dir, 'journals', sid)).mode & 0o7777).toBe(0o2770);expect(() => journalPath(dir, '../x')).toThrow();+ expect(() => ensureSessionJournalDir(dir, '../x')).toThrow();+ // Pure: naming a journal makes nothing.+ const other = mintId('cs');+ journalPath(dir, other);+ expect(fs.existsSync(path.join(dir, 'journals', other))).toBe(false);+ });++ it('refuses a session directory that is a link', () => {+ const other = mintId('cs');+ fs.symlinkSync(os.tmpdir(), path.join(dir, 'journals', other));+ expect(() => ensureSessionJournalDir(dir, other)).toThrow(/not a directory/);+ });+});++describe('a journal its session could have replaced (work 103, trust rule 4)', () => {+ const epochLine = (sessionId: string, epoch = 1) => `${JSON.stringify({ k: 'epoch', sessionId, epoch, startSeq: 1, through: 0, at: 0 })}\n`;+ const ev = (sessionId: string, seq: number) => `${JSON.stringify({ id: `ev_${seq}`, seq, createdAt: '', sessionId, turnId: null, type: 'x', actor: null, data: {} })}\n`;++ it('a symlinked journal is refused: not opened for writing, and read as no journal', async () => {+ const target = path.join(dir, 'elsewhere.jsonl');+ fs.writeFileSync(target, epochLine(sid) + ev(sid, 1));+ fs.symlinkSync(target, file);+ await expect(Journal.open(file, { sessionId: sid, epoch: 1, lastSeq: 0 })).rejects.toMatchObject({ code: 'ELOOP' });+ expect(readJournalFile(file, 0)).toEqual({ epoch: 0, startSeq: 0, through: 0, lastSeq: 0, events: [] });+ expect(fs.readFileSync(target, 'utf8')).toBe(epochLine(sid) + ev(sid, 1)); // untouched+ // A dangling link is not created through either.+ fs.rmSync(file);+ fs.symlinkSync(path.join(dir, 'made.jsonl'), file);+ await expect(Journal.open(file, { sessionId: sid, epoch: 1, lastSeq: 0 })).rejects.toMatchObject({ code: 'ELOOP' });+ expect(fs.existsSync(path.join(dir, 'made.jsonl'))).toBe(false);+ });++ it('something that is not a regular file is refused', async () => {+ fs.mkdirSync(file);+ await expect(Journal.open(file, { sessionId: sid, epoch: 1, lastSeq: 0 })).rejects.toThrow();+ expect(readJournalFile(file, 0).events).toEqual([]);+ });++ it('a symlinked checkpoint is not read', async () => {+ const a = await take();+ for (let i = 0; i < 5; i++) status(a, null, `s${i}`);+ a.checkpoint(null);+ const fd = fs.openSync(file, 'r');+ const size = fs.fstatSync(fd).size;+ expect(readCheckpoint(file, fd, size, { fold: false }).ck?.lastSeq).toBe(5);+ const real = `${file}.ckpt.real`;+ fs.renameSync(`${file}.ckpt`, real);+ fs.symlinkSync(real, `${file}.ckpt`);+ expect(readCheckpoint(file, fd, size, { fold: false })).toEqual({ offset: 0, bytes: 0 });+ fs.closeSync(fd);+ expect(readJournalFile(file, 0).lastSeq).toBe(5); // read whole, from the journal+ });++ it('a line naming another session is skipped by the unlocked reader and by an open', async () => {+ const other = mintId('cs');+ fs.writeFileSync(file, epochLine(sid) + ev(sid, 1) + epochLine(other, 9) + ev(other, 2) + ev(other, 3) + ev(sid, 2));+ const r = readJournalFile(file, 0);+ expect(r).toMatchObject({ epoch: 1, lastSeq: 2 });+ expect(r.events.map((e) => [e.sessionId, e.seq])).toEqual([[sid, 1], [sid, 2]]);+ const j = await take();+ expect(j.epoch).toBe(1);+ expect(j.lastSeq).toBe(2);+ expect(j.read(0, 10).map((e) => [e.sessionId, e.seq])).toEqual([[sid, 1], [sid, 2]]);+ expect(status(j, null, 'next').seq).toBe(3);});});diff --git a/computer/src/api/journal.ts b/computer/src/api/journal.tsindex 5894252b..9d1dce39 100644--- a/computer/src/api/journal.ts+++ b/computer/src/api/journal.ts@@ -1,5 +1,5 @@// A session's journal (work 084, "One writer, one log"): one JSONL file per-// session, `<dataDir>/journals/<cs_…>.jsonl`, written only by the process that+// session, `<dataDir>/journals/<cs_…>/<cs_…>.jsonl` (journal-dir.ts), written only by the process that// holds its flock (journal-lock.ts): the runner while it runs, the host's// session-writer otherwise. Three kinds of line://@@ -25,50 +25,28 @@// holds events a new epoch cuts is not used; one the cut lands below is// removed before the cut.// - `redact` is applied to every string of `data` before the line is written.-// - Files are 0660 in a setgid 02770 directory, so the host (sp-host, in group-// agent) and the runner (agent) can both open each other's files.--import { chmodSync, closeSync, fchmodSync, fstatSync, fsyncSync, ftruncateSync, mkdirSync, openSync, writeSync } from 'node:fs';-import path from 'node:path';+// - Files are 0660 in the session's setgid 02770 directory (journal-dir.ts), so+// the host (sp-host, in group agent) and the runner (agent) can both open+// each other's files.+// - The file is opened once, without following a link, and must be a regular+// file; the lock is taken on that descriptor's file, not on the name. A line+// that names another session is not read (103, trust rule 4): it is skipped+// by every scan, and cut when it is the file's tail.++import { closeSync, fchmodSync, fstatSync, fsyncSync, ftruncateSync, writeSync } from 'node:fs';import type { ApiActor, JournalEvent } from '../protocol.js';import { isSessionId, mintId } from '../session-ids.js';import { type Checkpoint, lineHash, readCheckpoint, removeCheckpoint, writeCheckpoint } from './journal-checkpoint.js';+import { JournalError, OPEN, openRegular } from './journal-dir.js';import { scanRange } from './journal-file.js';import { FileLock, LockError } from './journal-lock.js';import { saveResult } from './subagent-results.js';-export const JOURNALS_DIR = 'journals';const INDEX_EVERY = 64;const IDEM_TTL_MS = 24 * 3600_000;/** A checkpoint is due once the file grew this much past the last one, and at least twice that one's size. */const CHECKPOINT_MIN_BYTES = 1 << 20;-/** `<dataDir>/journals/<sessionId>.jsonl`. */-export function journalPath(dataDir: string, sessionId: string): string {- if (!isSessionId(sessionId)) throw new JournalError('bad_id', `not a session id: ${sessionId}`);- return path.join(dataDir, JOURNALS_DIR, `${sessionId}.jsonl`);-}--/** Create `<dataDir>/journals` (02770: files keep the directory's group). Returns it. */-export function ensureJournalDir(dataDir: string): string {- const dir = path.join(dataDir, JOURNALS_DIR);- mkdirSync(dir, { recursive: true, mode: 0o2770 });- // mkdir's mode is masked by the umask and drops setgid; set it outright (fails harmlessly when another uid owns it).- try {- chmodSync(dir, 0o2770);- } catch {}- return dir;-}--export class JournalError extends Error {- constructor(- readonly code: 'locked' | 'stale_epoch' | 'closed' | 'bad_id' | 'lock_failed',- message: string,- ) {- super(message);- }-}-export interface JournalOpen {sessionId: string;epoch: number;@@ -152,6 +130,7 @@ function redactAll(v: unknown, r: (s: string) => string): unknown {return v;}+export { ensureJournalDir, ensureSessionJournalDir, JournalError, journalPath } from './journal-dir.js';export { forgetJournalFile, readJournalFile } from './journal-file.js';export class Journal {@@ -203,33 +182,24 @@ export class Journal {/** Take the lock and open `file` for `o.sessionId` under `o.epoch`. */static async open(file: string, o: JournalOpen): Promise<Journal> {if (!isSessionId(o.sessionId)) throw new JournalError('bad_id', `not a session id: ${o.sessionId}`);- const fd0 = openSync(file, 'a', 0o660);+ const fd = openRegular(file, OPEN.append);// The umask may have masked the group's write bit; only the creator (the owner) can fix it.try {- fchmodSync(fd0, 0o660);+ fchmodSync(fd, 0o660);} catch {}- closeSync(fd0);let lock: FileLock;try {- lock = await FileLock.take(file, o.waitMs ?? 0);+ lock = await FileLock.take(file, o.waitMs ?? 0, undefined, fd);} catch (e) {+ closeSync(fd);const locked = e instanceof LockError && e.code === 'locked';throw new JournalError(locked ? 'locked' : 'lock_failed', (e as Error).message);}- try {- return Journal.load(file, o, lock);- } catch (e) {- await lock.release();- throw e;- }- }-- private static load(file: string, o: JournalOpen, lock: FileLock): Journal {- const fd = openSync(file, 'a+', 0o660);try {return Journal.loadFd(file, fd, o, lock);} catch (e) {closeSync(fd);+ await lock.release();throw e;}}@@ -272,7 +242,7 @@ export class Journal {}if (held) held.push(l);else take(l);- });+ }, o.sessionId);if (o.epoch < k.epoch) throw new JournalError('stale_epoch', `epoch ${o.epoch} is older than the journal's ${k.epoch}`);let cut = validEnd;if (k.epoch && o.epoch > k.epoch) {@@ -434,7 +404,7 @@ export class Journal {if (!isEvent(v) || v.seq <= after) return;out.push(v);if (out.length >= limit) return false;- });+ }, this.sessionId);return out;}diff --git a/computer/src/api/subagent-results.ts b/computer/src/api/subagent-results.tsindex 8906e1ed..e6c9d410 100644--- a/computer/src/api/subagent-results.ts+++ b/computer/src/api/subagent-results.ts@@ -13,23 +13,21 @@// the journal, as the runner and the host's writer run as different users.// - Never in memory past the call that reads it; never deleted (journals are not).-import { chmodSync, closeSync, fchmodSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeSync } from 'node:fs';+import { closeSync, fchmodSync, renameSync, rmSync, writeSync } from 'node:fs';import path from 'node:path';import { isId } from '../session-ids.js';+import { ensureRealDir, OPEN, openRegular, readRegular } from './journal-dir.js';const dirOf = (journal: string) => `${journal}.results`;export function saveResult(journal: string, subagentId: string, text: string): void {if (!isId('sa', subagentId)) throw new Error(`not a subagent id: ${subagentId}`);const dir = dirOf(journal);- mkdirSync(dir, { recursive: true, mode: 0o770 });- try {- chmodSync(dir, 0o770); // the umask may have masked the group bits- } catch {} // made by the other writer, who owns it+ ensureRealDir(dir, 0o770); // refuses a link planted in the session's directory; the umask may have masked the group bitsconst file = path.join(dir, subagentId);const tmp = `${file}.tmp`;rmSync(tmp, { force: true });- const fd = openSync(tmp, 'w', 0o660);+ const fd = openRegular(tmp, OPEN.create);try {try {fchmodSync(fd, 0o660);@@ -45,7 +43,7 @@ export function saveResult(journal: string, subagentId: string, text: string): vexport function loadResult(journal: string, subagentId: string): string | undefined {if (!isId('sa', subagentId)) return undefined;try {- return readFileSync(path.join(dirOf(journal), subagentId), 'utf8');+ return readRegular(path.join(dirOf(journal), subagentId)).toString('utf8');} catch {return undefined;}diff --git a/computer/src/api/testing.ts b/computer/src/api/testing.tsindex 618a3580..3122a690 100644--- a/computer/src/api/testing.ts+++ b/computer/src/api/testing.ts@@ -7,7 +7,7 @@ import path from 'node:path';import { Schema } from 'effect';import type { ApiActor, JournalEvent } from '../protocol.js';import { mintId } from '../session-ids.js';-import { ensureJournalDir, journalPath } from './journal.js';+import { ensureSessionJournalDir, journalPath } from './journal.js';import { EVENT_DATA, Event } from './schema-events.js';import { SessionLog, type SessionLogOpen } from './session-log.js';@@ -17,8 +17,8 @@ export const ANN_CTX = { actor: ANN, member: 'usr_ann' };/** A fresh data dir and session id; `cleanup` removes the dir. */export function tempSession() {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'api-'));- ensureJournalDir(dir);const sessionId = mintId('cs');+ ensureSessionJournalDir(dir, sessionId);return { dir, sessionId, file: journalPath(dir, sessionId), cleanup: () => fs.rmSync(dir, { recursive: true, force: true }) };}diff --git a/computer/src/host/api-host-epoch.test.ts b/computer/src/host/api-host-epoch.test.tsindex 75f5e46f..e96b0ce2 100644--- a/computer/src/host/api-host-epoch.test.ts+++ b/computer/src/host/api-host-epoch.test.ts@@ -7,7 +7,7 @@ import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, utimesSynimport os from 'node:os';import path from 'node:path';import { afterEach, describe, expect, it } from 'vitest';-import { ensureJournalDir, Journal, journalPath, readJournalFile } from '../api/journal.js';+import { ensureSessionJournalDir, Journal, journalPath, readJournalFile } from '../api/journal.js';import type { ApiClient } from '../api/socket.js';import type { SubscribeOptions } from '../api/writer.js';import type { ApiActor, GatewayToHost, HostToGateway, JournalEvent, SessionSpec } from '../protocol.js';@@ -108,7 +108,7 @@ describe('epoch adoption (recovery-fix)', () => {dirs.push(root);const dataDir = path.join(root, 'data');const file = journalPath(dataDir, S);- ensureJournalDir(dataDir);+ ensureSessionJournalDir(dataDir, S);mkdirSync(path.join(root, 'runners'));const runner = await fakeRunner(file);const dO = fakeDo();@@ -197,7 +197,7 @@ describe('epoch adoption (recovery-fix)', () => {dirs.push(root);const dataDir = path.join(root, 'data');const file = journalPath(dataDir, S);- ensureJournalDir(dataDir);+ ensureSessionJournalDir(dataDir, S);mkdirSync(path.join(root, 'runners'));const runner = await fakeRunner(file);const dO = fakeDo();@@ -407,7 +407,7 @@ describe('epoch adoption (recovery-fix)', () => {dirs.push(root);const dataDir = path.join(root, 'data');const file = journalPath(dataDir, S);- ensureJournalDir(dataDir);+ ensureSessionJournalDir(dataDir, S);const dO = fakeDo();for (const type of ['message.received', 'turn.started', 'tool.started']) dO.log.push({ id: `ev_${type}`, seq: dO.log.length + 1, createdAt: '2026-10-26T00:00:00.000Z', sessionId: S, turnId: 'tn_1', type, actor: null, data: {} });const frame = dO.recover(3);@@ -431,7 +431,7 @@ describe('epoch adoption (recovery-fix)', () => {dirs.push(root);const dataDir = path.join(root, 'data');const file = journalPath(dataDir, S);- ensureJournalDir(dataDir);+ ensureSessionJournalDir(dataDir, S);const ev = (seq: number) => `${JSON.stringify({ id: `ev_${seq}`, seq, createdAt: '2026-10-26T00:00:00.000Z', sessionId: S, turnId: null, type: 'runtime.suspended', actor: null, data: {} })}\n`;appendFileSync(file, `${JSON.stringify({ k: 'epoch', sessionId: S, epoch: 1, startSeq: 1, at: 0 })}\n${ev(1)}${ev(2)}`);const a = apiHost({ dataDir, stateDir: path.join(root, 'state'), runDir: path.join(root, 'run'), runnersDir: root, send: () => true, start: async () => 'idle', scan: async () => [], flushMs: 1 });diff --git a/computer/src/host/api-host.test.ts b/computer/src/host/api-host.test.tsindex f68de399..0ed3b9c3 100644--- a/computer/src/host/api-host.test.ts+++ b/computer/src/host/api-host.test.ts@@ -1,11 +1,14 @@-import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';import os from 'node:os';import path from 'node:path';import { afterEach, describe, expect, it, vi } from 'vitest';import type { ApiClient } from '../api/socket.js';+import { loadResult, saveResult } from '../api/subagent-results.js';+import { openLog, turn } from '../api/testing.js';import { type CallOutcome, RECORD_METHOD, type SubscribeOptions } from '../api/writer.js';import type { ApiActor, GatewayToHost, HostToGateway, JournalEvent, SessionSpec } from '../protocol.js';import { apiHost, type ApiHostDeps, type StartOptions, type WireHooks, type WireLinkLike } from './api-host.js';+import { mintId } from '../session-ids.js';import { subagentsRunning } from './runner-api.js';const S = 'cs_0000000000000001';@@ -179,7 +182,8 @@ describe('apiHost', () => {expect(t.host.handedOff).toBe(true);expect(ra).toMatchObject({ sessionId: S, epoch: 3, lastSeq: 7, socket: path.join(t.root, 'runners', 'beef.api.sock') });expect(ra?.token).toHaveLength(43);- expect(ra?.journal).toBe(path.join(t.root, 'data', 'journals', `${S}.jsonl`));+ expect(ra?.journal).toBe(path.join(t.root, 'data', 'journals', S, `${S}.jsonl`));+ expect(statSync(path.dirname(ra!.journal)).mode & 0o7777).toBe(0o2770); // made for the runner, which cannot// A call while the runner starts waits for it, then goes to it.t.a.onGateway(api('a2', 'sessions.get'));await tick(5);@@ -222,8 +226,8 @@ describe('apiHost', () => {let hooks: WireHooks | undefined;const t = setup({ wire: async (h) => ((hooks = h), { setKey() {}, setAccess() {}, setAdmins() {}, revoked() {}, moved() {}, close: async () => {} }) });// A session that ran before this host booted: its journal is on disk, its spec is not in memory.- mkdirSync(path.join(t.root, 'data', 'journals'), { recursive: true });- writeFileSync(path.join(t.root, 'data', 'journals', `${S}.jsonl`), '');+ mkdirSync(path.join(t.root, 'data', 'journals', S), { recursive: true });+ writeFileSync(path.join(t.root, 'data', 'journals', S, `${S}.jsonl`), '');t.a.onGateway(welcome(4, { wire: { key: 'k' } }));await vi.advanceTimersByTimeAsync(0);expect(await hooks!.where(S)).toMatchObject({ writer: 'host' });@@ -283,7 +287,7 @@ describe('apiHost', () => {it('at boot mirrors what the scan left in journals no writer holds, once the gateway speaks v4', async () => {const root = mkdtempSync(path.join(os.tmpdir(), 'apihost-'));dirs.push(root);- const jdir = path.join(root, 'data', 'journals');+ const jdir = path.join(root, 'data', 'journals', S);mkdirSync(jdir, { recursive: true });const ev = (seq: number) => JSON.stringify({ id: `ev_${seq}`, seq, createdAt: '', sessionId: S, turnId: null, type: 'turn.failed', actor: null, data: {} });writeFileSync(path.join(jdir, `${S}.jsonl`), `${JSON.stringify({ k: 'epoch', sessionId: S, epoch: 2, startSeq: 1, at: 0 })}\n${ev(1)}\n${ev(2)}\n`);@@ -300,6 +304,53 @@ describe('apiHost', () => {});});+describe('journals from before the directory per session (work 103 C8)', () => {+ it('are moved once at host start, read by the hello and the boot scan, and still there after a restart; a new session writes nested', async () => {+ const root = mkdtempSync(path.join(os.tmpdir(), 'apihost-'));+ dirs.push(root);+ const dataDir = path.join(root, 'data');+ const jdir = path.join(dataDir, 'journals');+ mkdirSync(jdir, { recursive: true });+ // An old host's session, as it left it: journal, checkpoint and a result directly in journals/.+ const flat = path.join(jdir, `${S}.jsonl`);+ const old = await openLog(flat, S, { epoch: 2 });+ turn(old);+ old.checkpoint();+ const sa = mintId('sa');+ saveResult(flat, sa, 'whole');+ await old.release();+ const nested = path.join(jdir, S, `${S}.jsonl`);++ const first = setup({ dataDir, scan: undefined });+ expect(readdirSync(jdir)).toEqual([S]);+ expect(readdirSync(path.join(jdir, S)).sort()).toEqual([`${S}.jsonl`, `${S}.jsonl.ckpt`, `${S}.jsonl.results`]);+ expect(first.a.journals()).toMatchObject([{ sessionId: S, epoch: 2, lastSeq: 4 }]);+ const found = await first.a.boot();+ expect(found).toMatchObject([{ sessionId: S, file: nested, epoch: 2 }]);+ const settled = found[0].lastSeq;+ await first.a.stop();++ // The host restarts: nothing is flat, nothing moves, the same journal is read.+ const second = setup({ dataDir, scan: undefined });+ expect(readdirSync(jdir)).toEqual([S]);+ expect(second.a.journals()).toMatchObject([{ sessionId: S, epoch: 2, lastSeq: settled }]);+ expect(await second.a.boot()).toMatchObject([{ sessionId: S, file: nested, lastSeq: settled }]);+ expect(loadResult(nested, sa)).toBe('whole');+ // A runner minted for it, and one for a session with no journal yet, are given the nested path, in a directory that exists.+ second.a.onGateway(welcome(4));+ expect((await second.a.mint(spec, 'beef'))?.journal).toBe(nested);+ const S2 = mintId('cs');+ const fresh = await second.a.mint({ ...spec, sessionId: S2, key: 'k2' }, 'cafe');+ expect(fresh?.journal).toBe(path.join(jdir, S2, `${S2}.jsonl`));+ const log = await openLog(fresh!.journal, S2);+ turn(log);+ await log.release();+ expect(readdirSync(jdir).sort()).toEqual([S, S2].sort());+ expect(second.a.journals().map((j) => j.sessionId).sort()).toEqual([S, S2].sort());+ await second.a.stop();+ });+});+describe('subagentsRunning', () => {it('keeps a runner awake while its report counts running subagents; an older runner reports none', () => {const r = { key: S, status: 'idle' } as const;diff --git a/computer/src/host/api-host.ts b/computer/src/host/api-host.tsindex 71724471..06a43f38 100644--- a/computer/src/host/api-host.ts+++ b/computer/src/host/api-host.ts@@ -26,7 +26,7 @@// - Host session-writers stay open until a runner takes their session over// (v1: never released for idleness; a few fds per suspended session).-import { existsSync, readdirSync, statSync } from 'node:fs';+import { existsSync } from 'node:fs';import path from 'node:path';import type {ApiSessionStatus, Delivery, GatewayToHost, HostCredentials, HostToGateway, JournalReport, ModelRoute, Person,@@ -34,7 +34,9 @@ import type {} from '../protocol.js';import { apiError, RECORD_METHOD } from '../api/writer.js';import { createdOf } from '../api/created.js';-import { ensureJournalDir, forgetJournalFile, Journal, journalPath, readJournalFile } from '../api/journal.js';+import { ensureJournalDir, ensureSessionJournalDir, forgetJournalFile, Journal, journalPath, readJournalFile } from '../api/journal.js';+import { moveFlatJournals, moveFlatSessionLogged } from './journal-flat-move.js';+import { journalReports } from './journal-reports.js';import { type HostWriterOptions, HostSessionWriter, scanJournals } from './session-writer.js';import { isSessionId } from '../session-ids.js';import { RUNNERS_DIR } from '../ipc.js';@@ -108,6 +110,7 @@ const ownerOf = (p: Person | undefined) => ({ id: p?.userId ?? p?.slackUserId ??export function apiHost(d: ApiHostDeps) {const runnersDir = d.runnersDir ?? RUNNERS_DIR;const journals = path.join(d.dataDir, 'journals');+ moveFlatJournals(d.dataDir); // before anything below lists or reads a journal (work 103 C8; goes in its step 12)const tokens = runnerApis(path.join(d.runDir, 'runners.json'));const acks = mirrorAcks(path.join(d.stateDir, 'mirror-acks.json'));const meter = d.meter ?? (d.telemetry && apiMeter(d.telemetry, { journals }));@@ -117,8 +120,7 @@ export function apiHost(d: ApiHostDeps) {const specs = new Map<string, SessionSpec>();/** The log's epoch and the DO's lastSeq, as the last frame said. */const logs = new Map<string, { epoch: number; lastSeq: number }>();- /** The hello's view of each journal on disk, by the file's inode, size and mtime: read again only once it changed. */- let onDisk = new Map<string, { stat: string; report: JournalReport | null }>();+ const reports = journalReports(journals, (sessionId) => logs.get(sessionId)?.epoch);/** The runner serving each session (its RunnerApi), and a port to it. */const live = new Map<string, { runnerId: string; api: RunnerApi; port: ReturnType<typeof remotePort> }>();const hostWriters = new Map<string, { w: Promise<HostWriter>; socket: string; token: string; epoch: number }>();@@ -186,6 +188,8 @@ export function apiHost(d: ApiHostDeps) {const spec = specs.get(sessionId);const journal = journalPath(d.dataDir, sessionId);if (!spec && !existsSync(journal)) return undefined;+ ensureSessionJournalDir(d.dataDir, sessionId);+ moveFlatSessionLogged(d.dataDir, sessionId); // what a runner from before the move left flat (goes in step 12 of work 103)const { epoch, lastSeq } = logOf(sessionId);const h = { socket: apiSocketFor(sessionId, runnersDir), token: mintToken(), epoch, w: undefined as unknown as Promise<HostWriter> };h.w = openHostWriter({@@ -318,7 +322,8 @@ export function apiHost(d: ApiHostDeps) {const r = live.get(sessionId);if (r && !retired.has(r.runnerId)) retired.add(r.runnerId), (retiredRunner = true), await d.retire?.(r.runnerId);await handOff(sessionId);- ensureJournalDir(d.dataDir);+ ensureSessionJournalDir(d.dataDir, sessionId);+ moveFlatSessionLogged(d.dataDir, sessionId); // what a runner from before the move left flat (goes in step 12 of work 103)const j = await Journal.open(file, { sessionId, epoch: m.epoch, lastSeq: m.lastSeq, epochStartSeq: m.startSeq, tail: m.tail, waitMs: fail ? 0 : (d.lockWaitMs ?? 10_000) });await j.release();forgetJournalFile(file);@@ -466,6 +471,8 @@ export function apiHost(d: ApiHostDeps) {await handOff(sessionId);relay.moved(sessionId);const { epoch, lastSeq } = logOf(sessionId);+ ensureSessionJournalDir(d.dataDir, sessionId); // the runner opens the journal there and cannot make the directory itself+ moveFlatSessionLogged(d.dataDir, sessionId); // what a runner from before the move left flat (goes in step 12 of work 103)const api: RunnerApi = { sessionId, journal: journalPath(d.dataDir, sessionId), epoch, lastSeq, socket: apiSocketFor(runnerId, runnersDir), token: mintToken() };tokens.set(runnerId, api);return api;@@ -514,34 +521,7 @@ export function apiHost(d: ApiHostDeps) {},/** For the gateway hello: every journal on disk, its epoch and last seq (so the gateway sends `epoch` where it is ahead). */- journals(): JournalReport[] {- let names: string[] = [];- try {- names = readdirSync(journals);- } catch {}- // A hello per gateway connect: a file unchanged since the last is not read again (past journal-file.ts's- // 512 files, its least recently read state is gone and each hello would rescan them, 084 perf fix 6).- const seen = new Map<string, { stat: string; report: JournalReport | null }>();- for (const n of names) {- const sessionId = n.replace(/\.jsonl$/, '');- if (!n.endsWith('.jsonl') || !isSessionId(sessionId)) continue;- const file = path.join(journals, n);- const st = statSync(file, { throwIfNoEntry: false });- if (!st) continue;- const stat = `${st.ino}:${st.size}:${st.mtimeMs}`;- const was = onDisk.get(sessionId);- if (was?.stat === stat) {- seen.set(sessionId, was);- continue;- }- const { epoch, startSeq, lastSeq } = readJournalFile(file, Number.MAX_SAFE_INTEGER, 0);- // Epoch 0 with events: an adoption into a new file torn before its epoch line (the gateway resends `epoch`).- const report = epoch ? { sessionId, epoch, startSeq, lastSeq } : lastSeq ? { sessionId, epoch: 0, startSeq: 0, lastSeq } : null;- seen.set(sessionId, { stat, report });- }- onDisk = seen;- return [...seen.values()].flatMap(({ report: r }) => (!r ? [] : !r.epoch ? [r] : [{ ...r, epoch: Math.max(r.epoch, logs.get(r.sessionId)?.epoch ?? 0) }]));- },+ journals: (): JournalReport[] => reports(),/** After rediscovery: forget the tokens of runners that did not come back. */rediscovered(liveRunners: Set<string>) {diff --git a/computer/src/host/api-meter.test.ts b/computer/src/host/api-meter.test.tsindex 05d6de4e..55ba0609 100644--- a/computer/src/host/api-meter.test.ts+++ b/computer/src/host/api-meter.test.ts@@ -1,5 +1,5 @@import { afterEach, describe, expect, it } from 'vitest';-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import path from 'node:path';import { checkCliFrame } from '../api/cli-telemetry.js';@@ -94,7 +94,13 @@ describe('apiMeter: the host\'s own units', () => {const { meter, out, journals } = setup();await meter.sample();expect(await out()).toEqual([]);- writeFileSync(path.join(journals, `${sid}.jsonl`), 'x'.repeat(100));+ mkdirSync(path.join(journals, sid));+ writeFileSync(path.join(journals, sid, `${sid}.jsonl`), 'x'.repeat(100));+ // Not journals: a file directly in journals/ (the layout before work 103), and a link where a journal would be.+ writeFileSync(path.join(journals, `${sid}.jsonl`), 'x'.repeat(7));+ const linked = mintId('cs');+ mkdirSync(path.join(journals, linked));+ symlinkSync(path.join(journals, sid, `${sid}.jsonl`), path.join(journals, linked, `${linked}.jsonl`));meter.setGauges(() => ({ v4: true, runnerWriters: 2, hostWriters: 1, heldFrames: 0, mirrorSpooledBytes: 5 }));await meter.sample();const [s] = await out();diff --git a/computer/src/host/api-meter.ts b/computer/src/host/api-meter.tsindex eddc57b9..78baddec 100644--- a/computer/src/host/api-meter.ts+++ b/computer/src/host/api-meter.ts@@ -16,10 +16,11 @@// - A stale-epoch drop is reported once per session and epoch (a runner stuck// on an old epoch must not become one event per frame).-import { readdir, stat } from 'node:fs/promises';-import path from 'node:path';+import { lstat, readdir } from 'node:fs/promises';import { checkCliForward } from '../api/cli-telemetry.js';+import { journalIn } from '../api/journal-dir.js';import { checkWireEvent } from '../api/wire-events.js';+import { isSessionId } from '../session-ids.js';import type { Telemetry } from '../telemetry/emitter.js';import { MirrorMeter } from './mirror-meter.js';@@ -109,7 +110,12 @@ export function apiMeter(t: Telemetry, o: ApiMeterOptions) {async function journalBytes(): Promise<number | undefined> {const read = (async () => {let total = 0;- for (const n of await readdir(o.journals)) if (n.endsWith('.jsonl')) total += (await stat(path.join(o.journals, n)).catch(() => undefined))?.size ?? 0;+ // One directory per session (journal-dir.ts); lstat: a link a session planted is not measured.+ for (const n of await readdir(o.journals)) {+ if (!isSessionId(n)) continue;+ const st = await lstat(journalIn(o.journals, n)).catch(() => undefined);+ if (st?.isFile()) total += st.size;+ }return total;})().catch(() => undefined);const late = new Promise<undefined>((r) => setTimeout(() => r(undefined), 1000).unref?.());diff --git a/computer/src/host/journal-flat-move.test.ts b/computer/src/host/journal-flat-move.test.tsnew file mode 100644index 00000000..12255673--- /dev/null+++ b/computer/src/host/journal-flat-move.test.ts@@ -0,0 +1,295 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { journalPath, readJournalFile } from '../api/journal.js';+import { loadResult } from '../api/subagent-results.js';+import { openLog, turn } from '../api/testing.js';+import { mintId } from '../session-ids.js';+import { moveFlatJournals, moveFlatSession } from './journal-flat-move.js';++// A directory another uid owns (the host is sp-host, the runner agent): chmod fails with EPERM while `uids.other` is set.+const uids = vi.hoisted(() => ({ other: false }));+vi.mock('node:fs', async (original) => {+ const real = await original<typeof import('node:fs')>();+ const eperm =+ <A extends unknown[]>(fn: (...a: A) => void) =>+ (...a: A) => {+ if (uids.other) throw Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' });+ fn(...a);+ };+ const patched = { ...real, chmodSync: eperm(real.chmodSync), fchmodSync: eperm(real.fchmodSync) };+ return { ...patched, default: patched };+});++let data: string;+let journals: string;+beforeEach(() => {+ uids.other = false;+ data = fs.mkdtempSync(path.join(os.tmpdir(), 'flatmove-'));+ journals = path.join(data, 'journals');+ fs.mkdirSync(journals);+});+afterEach(() => fs.rmSync(data, { recursive: true, force: true }));++const text = (sessionId: string, epoch: number, events: number) =>+ `${JSON.stringify({ k: 'epoch', sessionId, epoch, startSeq: 1, through: 0, at: 0 })}\n` ++ Array.from({ length: events }, (_, i) => `${JSON.stringify({ id: `ev_${i + 1}`, seq: i + 1, createdAt: '', sessionId, turnId: null, type: 'x', actor: null, data: {} })}\n`).join('');++/** A session in the layout before work 103: journal, checkpoint and one result, all directly in journals/. */+function flat(epoch = 1, events = 3) {+ const id = mintId('cs');+ const sa = mintId('sa');+ const file = path.join(journals, `${id}.jsonl`);+ fs.writeFileSync(file, text(id, epoch, events));+ fs.writeFileSync(`${file}.ckpt`, 'ckpt');+ fs.mkdirSync(`${file}.results`);+ fs.writeFileSync(path.join(`${file}.results`, sa), 'whole result');+ return { id, sa, file, nested: journalPath(data, id) };+}++const tree = () => (fs.readdirSync(journals, { recursive: true }) as string[]).sort();++describe('moveFlatJournals (work 103 C8)', () => {+ it('moves a flat journal, its checkpoint and its results into the session\'s directory, and reads the same', () => {+ const s = flat();+ const ino = fs.statSync(s.file).ino;+ expect(moveFlatJournals(data)).toBe(3);+ expect(tree()).toEqual([s.id, `${s.id}/${s.id}.jsonl`, `${s.id}/${s.id}.jsonl.ckpt`, `${s.id}/${s.id}.jsonl.results`, `${s.id}/${s.id}.jsonl.results/${s.sa}`]);+ expect(fs.statSync(s.nested).ino).toBe(ino); // a rename: a writer holding the file open keeps writing it+ expect(fs.statSync(path.dirname(s.nested)).mode & 0o7777).toBe(0o2770);+ expect(readJournalFile(s.nested, 0)).toMatchObject({ epoch: 1, lastSeq: 3 });+ expect(loadResult(s.nested, s.sa)).toBe('whole result');+ });++ it('is idempotent: a second run moves nothing and changes nothing', () => {+ const a = flat();+ flat();+ expect(moveFlatJournals(data)).toBe(6);+ const before = tree();+ const content = fs.readFileSync(a.nested, 'utf8');+ expect(moveFlatJournals(data)).toBe(0);+ expect(tree()).toEqual(before);+ expect(fs.readFileSync(a.nested, 'utf8')).toBe(content);+ });++ it('does nothing without a journals directory, and leaves what is not a journal', () => {+ expect(moveFlatJournals(path.join(data, 'none'))).toBe(0);+ fs.writeFileSync(path.join(journals, 'notes.txt'), 'x');+ fs.writeFileSync(path.join(journals, 'not-an-id.jsonl'), 'x');+ expect(moveFlatJournals(data)).toBe(0);+ expect(tree()).toEqual(['not-an-id.jsonl', 'notes.txt']);+ });++ it('finishes a move that was interrupted at any point', () => {+ // Each prefix of the three renames, then the rerun.+ for (const done of [['.results'], ['.ckpt'], [''], ['', '.ckpt'], ['.results', '.ckpt']]) {+ const s = flat();+ fs.mkdirSync(path.dirname(s.nested));+ for (const part of done) fs.renameSync(s.file + part, s.nested + part);+ expect(moveFlatJournals(data)).toBe(3 - done.length);+ expect(fs.readdirSync(journals).filter((n) => n.startsWith(`${s.id}.`))).toEqual([]);+ expect(readJournalFile(s.nested, 0).lastSeq).toBe(3);+ expect(fs.readFileSync(`${s.nested}.ckpt`, 'utf8')).toBe('ckpt');+ expect(loadResult(s.nested, s.sa)).toBe('whole result');+ }+ });++ it('a runner from before the move wrote flat again: its checkpoint and results join the nested ones', () => {+ const s = flat();+ moveFlatJournals(data);+ const sa2 = mintId('sa');+ fs.writeFileSync(`${s.file}.ckpt`, 'newer');+ fs.writeFileSync(`${s.file}.ckpt.tmp`, 'torn');+ fs.mkdirSync(`${s.file}.results`);+ fs.writeFileSync(path.join(`${s.file}.results`, sa2), 'second');+ expect(moveFlatJournals(data)).toBe(2);+ expect(fs.readdirSync(journals)).toEqual([s.id]);+ expect(fs.readFileSync(`${s.nested}.ckpt`, 'utf8')).toBe('newer');+ expect(loadResult(s.nested, s.sa)).toBe('whole result');+ expect(loadResult(s.nested, sa2)).toBe('second');+ });++ it('with both a flat and a nested journal, the one further on is the journal and the other is kept aside', () => {+ const behind = flat(1, 2);+ fs.mkdirSync(path.dirname(behind.nested));+ fs.writeFileSync(behind.nested, text(behind.id, 2, 5));+ const ahead = flat(3, 1);+ fs.mkdirSync(path.dirname(ahead.nested));+ fs.writeFileSync(ahead.nested, text(ahead.id, 2, 5));+ moveFlatJournals(data);+ expect(fs.readFileSync(behind.nested, 'utf8')).toBe(text(behind.id, 2, 5));+ expect(fs.readFileSync(`${behind.nested}.superseded`, 'utf8')).toBe(text(behind.id, 1, 2));+ expect(fs.readFileSync(ahead.nested, 'utf8')).toBe(text(ahead.id, 3, 1));+ expect(fs.readFileSync(`${ahead.nested}.superseded`, 'utf8')).toBe(text(ahead.id, 2, 5));+ expect(readJournalFile(ahead.nested, 0)).toMatchObject({ epoch: 3, lastSeq: 1 });+ expect(fs.readdirSync(journals).sort()).toEqual([behind.id, ahead.id].sort());+ });++ it('never follows a link: a flat name that is one stays where it is, and the others still move', () => {+ const id = mintId('cs');+ const secret = path.join(data, 'secret');+ fs.writeFileSync(secret, text(id, 1, 1));+ fs.symlinkSync(secret, path.join(journals, `${id}.jsonl`));+ fs.symlinkSync(data, path.join(journals, `${id}.jsonl.results`));+ const s = flat();+ expect(moveFlatJournals(data)).toBe(3);+ expect(fs.lstatSync(path.join(journals, `${id}.jsonl`)).isSymbolicLink()).toBe(true);+ expect(fs.existsSync(path.join(journals, id))).toBe(false);+ expect(fs.existsSync(secret)).toBe(true);+ expect(readJournalFile(s.nested, 0).lastSeq).toBe(3);+ });++ it('a second journal set aside does not replace the first (a release rolled back and forward twice)', () => {+ const s = flat(1, 2);+ fs.mkdirSync(path.dirname(s.nested));+ fs.writeFileSync(s.nested, text(s.id, 2, 5));+ moveFlatSession(data, s.id);+ fs.writeFileSync(s.file, text(s.id, 2, 4));+ moveFlatSession(data, s.id);+ fs.writeFileSync(s.file, text(s.id, 3, 1));+ moveFlatSession(data, s.id);+ expect(fs.readFileSync(s.nested, 'utf8')).toBe(text(s.id, 3, 1));+ const asides = fs.readdirSync(path.dirname(s.nested)).filter((n) => n.includes('.superseded'));+ expect(asides.map((n) => fs.readFileSync(path.join(path.dirname(s.nested), n), 'utf8')).sort()).toEqual([text(s.id, 1, 2), text(s.id, 2, 4), text(s.id, 2, 5)].sort());+ });++ describe('a nested .results the session planted (it can write its own directory)', () => {+ /** A flat session whose nested directory already has `.results` as a link to a directory only the host may write. */+ const planted = () => {+ const s = flat();+ const hostOnly = path.join(data, 'host-only');+ fs.mkdirSync(hostOnly, { mode: 0o700 });+ fs.mkdirSync(path.dirname(s.nested));+ fs.symlinkSync(hostOnly, `${s.nested}.results`);+ return { ...s, hostOnly };+ };++ it('is not written through: the flat results stay where they are, the rest moves', () => {+ const s = planted();+ expect(moveFlatJournals(data)).toBe(2);+ expect(fs.readdirSync(s.hostOnly)).toEqual([]);+ expect(fs.readFileSync(path.join(`${s.file}.results`, s.sa), 'utf8')).toBe('whole result');+ expect(fs.lstatSync(`${s.nested}.results`).isSymbolicLink()).toBe(true);+ expect(readJournalFile(s.nested, 0).lastSeq).toBe(3);+ });++ it('is not chmodded, and gets no link from the flat name, when a runner still writes', async () => {+ const s = planted();+ fs.rmSync(`${s.file}.results`, { recursive: true });+ const runner = await openLog(s.file, s.id);+ expect(moveFlatJournals(data)).toBe(2);+ expect(fs.statSync(s.hostOnly).mode & 0o7777).toBe(0o700);+ expect(fs.existsSync(`${s.file}.results`)).toBe(false);+ await runner.release();+ });+ });++ it('moves only regular files named as a subagent into existing nested results; a torn write goes, the rest stays flat', () => {+ const s = flat();+ moveFlatJournals(data);+ const sa2 = mintId('sa');+ const dir = `${s.file}.results`;+ fs.mkdirSync(dir);+ fs.writeFileSync(path.join(dir, sa2), 'second');+ fs.writeFileSync(path.join(dir, `${mintId('sa')}.tmp`), 'torn');+ fs.writeFileSync(path.join(dir, 'other'), 'x');+ fs.symlinkSync(path.join(data, 'secret'), path.join(dir, mintId('sa')));+ moveFlatJournals(data);+ expect(loadResult(s.nested, sa2)).toBe('second');+ expect(fs.readdirSync(`${s.nested}.results`).sort()).toEqual([s.sa, sa2].sort());+ expect(fs.readdirSync(dir).length).toBe(2); // the link and the unknown name+ fs.rmSync(dir, { recursive: true });+ });++ describe('a runner that outlived the host (the previous release: it writes beside the flat name it was given)', () => {+ /** saveResult as the release before work 103 wrote it: no link check, the directory made on the way. */+ const oldSaveResult = (journal: string, sa: string, body: string) => {+ const dir = `${journal}.results`;+ fs.mkdirSync(dir, { recursive: true, mode: 0o770 });+ fs.writeFileSync(path.join(dir, `${sa}.tmp`), body);+ fs.renameSync(path.join(dir, `${sa}.tmp`), path.join(dir, sa));+ };++ it('what it writes after the move reaches the host: results at once, its checkpoint when the session is next opened', async () => {+ const id = mintId('cs');+ const file = path.join(journals, `${id}.jsonl`);+ const nested = journalPath(data, id);+ const [sa1, sa2] = [mintId('sa'), mintId('sa')];+ const runner = await openLog(file, id); // holds the journal open, and its lock, across the host's restart+ turn(runner);+ runner.checkpoint();+ oldSaveResult(file, sa1, 'before');++ expect(moveFlatJournals(data)).toBe(3); // the new host starts+ expect(fs.readdirSync(journals).sort()).toEqual([id, `${id}.jsonl.results`]);+ expect(fs.readlinkSync(`${file}.results`)).toBe(path.join(id, `${id}.jsonl.results`));+ const early = fs.readFileSync(`${nested}.ckpt`);++ turn(runner);+ runner.checkpoint();+ oldSaveResult(file, sa2, 'after');+ const lastSeq = runner.journal.lastSeq;++ // The host, reading only the nested layout: the events, both results, and a checkpoint that is older but right.+ expect(readJournalFile(nested, 0)).toMatchObject({ lastSeq });+ expect(loadResult(nested, sa1)).toBe('before');+ expect(loadResult(nested, sa2)).toBe('after');+ expect(fs.readFileSync(`${nested}.ckpt`)).toEqual(early);+ // Another host restart under the same runner changes nothing but takes the checkpoint so far.+ const second = fs.readFileSync(`${file}.ckpt`);+ expect(moveFlatJournals(data)).toBe(1);+ expect(fs.readFileSync(`${nested}.ckpt`)).toEqual(second);+ expect(fs.lstatSync(`${file}.results`).isSymbolicLink()).toBe(true);++ turn(runner);+ runner.checkpoint(); // its last, flat+ await runner.release(); // the lock goes with it+ const last = fs.readFileSync(`${file}.ckpt`);+ expect(last).not.toEqual(second);+ expect(moveFlatSession(data, id)).toBe(1); // the host, before it opens the session+ expect(fs.readdirSync(journals)).toEqual([id]); // the link went with the runner+ expect(fs.readFileSync(`${nested}.ckpt`)).toEqual(last);+ const next = await openLog(nested, id);+ expect(next.journal.lastSeq).toBe(runner.journal.lastSeq);+ expect(loadResult(nested, sa2)).toBe('after');+ await next.release();+ expect(moveFlatSession(data, id)).toBe(0);+ });++ it('gets its link where the nested results are another uid\'s (the chmod is refused)', async () => {+ const id = mintId('cs');+ const file = path.join(journals, `${id}.jsonl`);+ const runner = await openLog(file, id);+ fs.mkdirSync(path.join(journals, id));+ fs.mkdirSync(`${journalPath(data, id)}.results`); // made by the runner's uid+ uids.other = true;+ expect(moveFlatSession(data, id)).toBe(1);+ uids.other = false;+ expect(fs.readlinkSync(`${file}.results`)).toBe(path.join(id, `${id}.jsonl.results`));+ await runner.release();+ });++ it('is not looked for behind a journal nobody wrote for a day: host start runs no lock probe per old journal', async () => {+ const id = mintId('cs');+ const file = path.join(journals, `${id}.jsonl`);+ const holder = await openLog(file, id); // the lock is held, so a probe would say a writer lives and leave a link+ const old = Date.now() / 1000 - 2 * 86400;+ fs.utimesSync(file, old, old);+ expect(moveFlatJournals(data)).toBe(1);+ expect(fs.readdirSync(journals)).toEqual([id]);+ await holder.release();+ });++ it('a nested checkpoint newer than the flat one is kept, and no link is left for a session nobody writes', async () => {+ const s = flat();+ moveFlatJournals(data);+ expect(fs.readdirSync(journals)).toEqual([s.id]); // no writer: no link+ fs.writeFileSync(`${s.file}.ckpt`, 'older');+ fs.utimesSync(`${s.file}.ckpt`, 1, 1);+ expect(moveFlatSession(data, s.id)).toBe(1);+ expect(fs.readFileSync(`${s.nested}.ckpt`, 'utf8')).toBe('ckpt');+ expect(fs.readdirSync(journals)).toEqual([s.id]);+ });+ });+});diff --git a/computer/src/host/journal-flat-move.ts b/computer/src/host/journal-flat-move.tsnew file mode 100644index 00000000..2f5dc4ea--- /dev/null+++ b/computer/src/host/journal-flat-move.ts@@ -0,0 +1,220 @@+// The one-off move of journals from the flat layout to a directory per session+// (work 103, C8). DELETED IN STEP 12 OF WORK 103 (this file and its calls in+// api-host.ts), once every computer has started a release with it.+//+// journals/<id>.jsonl -> journals/<id>/<id>.jsonl+// journals/<id>.jsonl.ckpt -> journals/<id>/<id>.jsonl.ckpt+// journals/<id>.jsonl.results/ -> journals/<id>/<id>.jsonl.results/+//+// Run by the host at start, before anything lists or reads a journal, and for+// one session before each open of its journal (adopt, the host's writer, mint).+//+// A runner that outlives the host's restart is the previous release's code. It+// holds the journal open (one descriptor, and the lock on it) and never opens+// it by name again, but it builds `<journal>.ckpt` and `<journal>.results/`+// from the flat name it was given at mint on every write, and nothing the host+// sends an attached runner makes it take another. So the host bends the flat+// names instead of reading two layouts:+// - results: while a writer holds the journal's lock, the flat `.results` is a+// link to the nested directory, so what that runner saves lands where the+// host reads. The link goes on the first pass that finds the lock free.+// - checkpoint: the runner replaces the flat name by rename, which no link+// survives. A checkpoint is a cache checked against its journal by hash and+// the journal only grows, so the older nested one stays right; the flat one+// is taken on the next pass (the next open of the session, or host start).+//+// Invariants:+// - The journal moves by one rename (the inode stays, so that runner keeps+// appending to the file it holds, and keeps its lock). Each pass moves+// whatever is still flat: stopped anywhere and run again, it ends in the+// same place; with nothing flat it does nothing.+// - Nothing of a journal is deleted. Where a session already has a nested+// journal and a flat one appears (a release rolled back and forward), the+// one further on by (epoch, last seq) is the journal and the other is kept+// beside it as `<id>.jsonl.superseded` (`.superseded.2`, … when that is+// taken: one set aside earlier is never replaced), which nothing reads.+// - A flat name that is a link the host did not make, or not the kind of file+// its name says, is left where it is and never followed. The same holds for+// the nested `.results`, which the session can write: where it is not a+// real directory nothing is moved into it, no link points at it and its+// mode is not touched. Into one that exists go only regular files named as+// a subagent (all that subagent-results.ts writes there).+// - The lock is probed (a process each time) only for a journal written in+// the last `RECENT_MS`, so host start does not run one per old journal.+// - One session failing does not stop the others.++import { spawnSync } from 'node:child_process';+import { closeSync, fstatSync, lstatSync, readdirSync, readlinkSync, renameSync, rmdirSync, rmSync, symlinkSync } from 'node:fs';+import path from 'node:path';+import { ensureRealDir, ensureSessionJournalDir, journalPath, OPEN, openRegular } from '../api/journal-dir.js';+import { forgetJournalFile, readJournalFile } from '../api/journal.js';+import { log } from '../log.js';+import { isId, isSessionId } from '../session-ids.js';++const FLAT = /^(.+)\.jsonl(|\.ckpt|\.ckpt\.tmp|\.results)$/;++const kindOf = (file: string) => {+ const st = lstatSync(file, { throwIfNoEntry: false });+ return !st ? undefined : st.isFile() ? 'file' : st.isDirectory() ? 'dir' : st.isSymbolicLink() ? 'link' : 'other';+};++/**+ * How lately a journal must have been written for its lock to be probed. A runner appends on every delivery and is+ * told to exit after SP_IDLE_MS without one (two hours unless set), so a day covers any that still writes. One missed+ * (idle longer, kept by an open terminal) loses nothing: what it then saves flat is moved on the next pass.+ */+const RECENT_MS = 24 * 3600_000;++/**+ * Whether a writer holds the journal's lock (journal-lock.ts). Unsure (the probe did not run) counts as held: the link+ * then stays a pass longer. A journal not written within `RECENT_MS` is not probed and counts as free.+ */+function held(journal: string): boolean {+ let fd: number;+ try {+ fd = openRegular(journal, OPEN.read);+ } catch {+ return false; // no journal: no writer+ }+ try {+ if (Date.now() - fstatSync(fd).mtimeMs > RECENT_MS) return false;+ return spawnSync('/usr/bin/flock', ['-x', '-n', '-E', '75', '/dev/fd/3', 'true'], { stdio: ['ignore', 'ignore', 'ignore', fd] }).status !== 0;+ } finally {+ closeSync(fd);+ }+}++/** Further on: the higher epoch, then the higher last seq. */+function ahead(a: string, b: string): boolean {+ const [x, y] = [a, b].map((f) => readJournalFile(f, Number.MAX_SAFE_INTEGER, 0));+ forgetJournalFile(a);+ forgetJournalFile(b);+ return x.epoch !== y.epoch ? x.epoch > y.epoch : x.lastSeq > y.lastSeq;+}++/** A name beside the journal that nothing has: `.superseded`, then `.superseded.2`, … */+function asideOf(nested: string): string {+ for (let n = 1; ; n++) {+ const name = `${nested}.superseded${n > 1 ? `.${n}` : ''}`;+ if (kindOf(name) === undefined) return name;+ }+}++function moveJournal(flat: string, nested: string): void {+ if (kindOf(nested) !== undefined) {+ if (!ahead(flat, nested)) {+ renameSync(flat, asideOf(nested));+ return;+ }+ renameSync(nested, asideOf(nested));+ }+ renameSync(flat, nested);+}++/**+ * Returns false when nothing could be moved (the nested name is not a directory). Into nested results that exist go+ * the regular files named as a subagent; a write that never finished (`<sa_…>.tmp`) is dropped once no writer lives;+ * anything else stays flat, and the flat directory with it.+ */+function moveResults(flat: string, nested: string, writerLives: () => boolean): boolean {+ const have = kindOf(nested);+ if (have === undefined) {+ renameSync(flat, nested);+ return true;+ }+ if (have !== 'dir') {+ log.warn(`journal move: ${nested} is not a directory, ${flat} left in place`);+ return false;+ }+ for (const n of readdirSync(flat)) {+ const from = path.join(flat, n);+ if (kindOf(from) !== 'file') continue;+ const torn = n.endsWith('.tmp') && isId('sa', n.slice(0, -4));+ if (isId('sa', n)) renameSync(from, path.join(nested, n));+ else if (torn && !writerLives()) rmSync(from, { force: true });+ }+ try {+ rmdirSync(flat);+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code !== 'ENOTEMPTY') throw e;+ log.warn(`journal move: ${flat} holds what is not a subagent's result, left in place`);+ }+ return true;+}++/** The newer checkpoint stays: a flat one written before the nested one (by a runner as it exited) is dropped. */+function moveCheckpoint(flat: string, nested: string): void {+ const have = lstatSync(nested, { throwIfNoEntry: false });+ if (have && have.mtimeMs > lstatSync(flat).mtimeMs) rmSync(flat, { force: true });+ else renameSync(flat, nested);+}++/**+ * Move what is flat of one session into its directory, and keep or drop the link for a runner from before the move+ * (see the header). Returns how many names it moved. Throws on the first name it cannot move.+ */+export function moveFlatSession(dataDir: string, sessionId: string): number {+ const nested = journalPath(dataDir, sessionId);+ const flat = path.join(dataDir, 'journals', `${sessionId}.jsonl`);+ const linkTo = path.join(sessionId, `${path.basename(nested)}.results`); // relative to journals/+ const kinds = ['', '.ckpt.tmp', '.ckpt', '.results'].map((part) => [part, kindOf(flat + part)] as const).filter(([, k]) => k !== undefined);+ if (!kinds.length) return 0;+ let moved = 0;+ let live: boolean | undefined;+ const writerLives = () => (live ??= held(nested));+ for (const [part, kind] of kinds) {+ const from = flat + part;+ if (part === '.results' && kind === 'link' && readlinkSync(from) === linkTo) {+ if (!writerLives()) rmSync(from, { force: true }); // that runner ended: nothing writes the flat name any more+ continue;+ }+ if (kind !== (part === '.results' ? 'dir' : 'file')) {+ log.warn(`journal move: ${from} is not a ${part === '.results' ? 'directory' : 'regular file'}, left in place`);+ continue;+ }+ ensureSessionJournalDir(dataDir, sessionId);+ if (part === '') moveJournal(from, nested);+ else if (part === '.ckpt.tmp') {+ if (!writerLives()) rmSync(from, { force: true }); // a checkpoint write that never finished (a live runner's may be under way)+ continue;+ } else if (part === '.ckpt') moveCheckpoint(from, nested + part);+ else if (!moveResults(from, nested + part, writerLives)) continue;+ moved++;+ }+ // A runner from before the move still writes: its results go through the flat name into the nested directory.+ if (moved && kindOf(`${flat}.results`) === undefined && writerLives()) {+ try {+ ensureRealDir(`${nested}.results`, 0o770); // as subagent-results.ts makes it: the runner is another uid of the group+ } catch (e) {+ log.warn(`journal move: no link for ${flat}.results: ${(e as Error).message}`); // what the session put there is not a directory+ return moved;+ }+ symlinkSync(linkTo, `${flat}.results`);+ }+ return moved;+}++/** Move every flat journal under `<dataDir>/journals` into its session's directory. Returns how many names it moved. */+export function moveFlatJournals(dataDir: string): number {+ let names: string[];+ try {+ names = readdirSync(path.join(dataDir, 'journals'));+ } catch {+ return 0;+ }+ const ids = new Set(names.flatMap((n) => FLAT.exec(n)?.[1] ?? []).filter(isSessionId));+ let moved = 0;+ for (const id of ids) moved += moveFlatSessionLogged(dataDir, id);+ if (moved) log.info(`journal move: ${moved} flat journal file(s) moved into their session's directory`);+ return moved;+}++/** `moveFlatSession`, a failure logged instead of thrown: the open that follows reads what did move. */+export function moveFlatSessionLogged(dataDir: string, sessionId: string): number {+ try {+ return moveFlatSession(dataDir, sessionId);+ } catch (e) {+ log.warn(`journal move: ${sessionId}: ${(e as Error).message}`);+ return 0;+ }+}diff --git a/computer/src/host/journal-reports.ts b/computer/src/host/journal-reports.tsnew file mode 100644index 00000000..21ed8837--- /dev/null+++ b/computer/src/host/journal-reports.ts@@ -0,0 +1,41 @@+// The hello's listing of the journals on this host's disk (work 084): for each+// session directory, its journal's epoch, the epoch's first seq and the last+// seq, so the gateway sends `epoch` where the log is ahead.+//+// Invariants:+// - A hello goes out per gateway connect: a file unchanged since the last+// (inode, size, mtime) is not read again (past journal-file.ts's 512 files+// its least recently read state is gone and each hello would rescan them,+// 084 perf fix 6).+// - Only `journals/<id>/<id>.jsonl` is a journal (journal-dir.ts), and only+// when it is a regular file: the stat does not follow a link (work 103).++import { lstatSync } from 'node:fs';+import { listJournals } from '../api/journal-dir.js';+import { readJournalFile } from '../api/journal.js';+import type { JournalReport } from '../protocol.js';++/** A lister over `journals`; `epochOf` is the epoch the host holds for a session, when it is ahead of the file's. */+export function journalReports(journals: string, epochOf: (sessionId: string) => number | undefined): () => JournalReport[] {+ /** The last hello's view, by session. */+ let onDisk = new Map<string, { stat: string; report: JournalReport | null }>();+ return () => {+ const seen = new Map<string, { stat: string; report: JournalReport | null }>();+ for (const { sessionId, file } of listJournals(journals)) {+ const st = lstatSync(file, { throwIfNoEntry: false });+ if (!st?.isFile()) continue;+ const stat = `${st.ino}:${st.size}:${st.mtimeMs}`;+ const was = onDisk.get(sessionId);+ if (was?.stat === stat) {+ seen.set(sessionId, was);+ continue;+ }+ const { epoch, startSeq, lastSeq } = readJournalFile(file, Number.MAX_SAFE_INTEGER, 0);+ // Epoch 0 with events: an adoption into a new file torn before its epoch line (the gateway resends `epoch`).+ const report = epoch ? { sessionId, epoch, startSeq, lastSeq } : lastSeq ? { sessionId, epoch: 0, startSeq: 0, lastSeq } : null;+ seen.set(sessionId, { stat, report });+ }+ onDisk = seen;+ return [...seen.values()].flatMap(({ report: r }) => (!r ? [] : !r.epoch ? [r] : [{ ...r, epoch: Math.max(r.epoch, epochOf(r.sessionId) ?? 0) }]));+ };+}diff --git a/computer/src/host/session-writer.test.ts b/computer/src/host/session-writer.test.tsindex 00ec9ae6..86917dc2 100644--- a/computer/src/host/session-writer.test.ts+++ b/computer/src/host/session-writer.test.ts@@ -3,7 +3,7 @@ import path from 'node:path';import { afterEach, describe, expect, it } from 'vitest';import type { ApiDelivery, JournalEvent } from '../protocol.js';import { mintId } from '../session-ids.js';-import { journalPath } from '../api/journal.js';+import { ensureSessionJournalDir, journalPath } from '../api/journal.js';import { dialApi } from '../api/socket.js';import { ANN, ANN_CTX, askOf, assertEvent, openLog, subagentOf, tempSession, turn } from '../api/testing.js';import { HostSessionWriter, QUEUE_MAX, scanJournals } from './session-writer.js';@@ -237,13 +237,14 @@ describe('scanJournals', () => {// A second, locked journal (a running runner's) is skipped.const other = mintId('cs');+ ensureSessionJournalDir(t.dir, other);const held = await openLog(journalPath(t.dir, other), other);turn(held);cleanups.push(() => held.release());const before = log.lastSeq;await log.release();- const dir = path.dirname(t.file);+ const dir = path.join(t.dir, 'journals');const r1 = await scanJournals(dir, { owner });const mine = r1.find((r) => r.sessionId === t.sessionId);expect(r1.find((r) => r.sessionId === other)?.skipped).toBe('locked');@@ -269,7 +270,12 @@ describe('scanJournals', () => {expect(await scanJournals('/nonexistent/dir')).toEqual([]);const t = tempSession();cleanups.push(t.cleanup);+ const journals = path.join(t.dir, 'journals');+ fs.writeFileSync(path.join(journals, 'notes.txt'), 'x');fs.writeFileSync(path.join(path.dirname(t.file), 'notes.txt'), 'x');- expect(await scanJournals(path.dirname(t.file))).toEqual([]);+ // A journal directly in journals/ (the layout before work 103) is not one, nor is a directory that is not a session's.+ fs.writeFileSync(path.join(journals, `${t.sessionId}.jsonl`), `${JSON.stringify({ k: 'epoch', sessionId: t.sessionId, epoch: 1, startSeq: 1, at: 0 })}\n`);+ fs.mkdirSync(path.join(journals, 'other'));+ expect(await scanJournals(journals)).toEqual([]);});});diff --git a/computer/src/host/session-writer.ts b/computer/src/host/session-writer.tsindex 51b3eb7e..4ae500cf 100644--- a/computer/src/host/session-writer.ts+++ b/computer/src/host/session-writer.ts@@ -25,6 +25,7 @@ import { log as logger } from '../log.js';import { isSessionId, mintId } from '../session-ids.js';import type { SessionCreated } from '../api/created.js';import { type SessionSeed, SYSTEM_ACTOR } from '../api/fold.js';+import { listJournals } from '../api/journal-dir.js';import { JournalError, readJournalFile } from '../api/journal.js';import { dispatch, type WriteHandlers } from '../api/read-methods.js';import { SessionLog } from '../api/session-log.js';@@ -310,23 +311,14 @@ export interface ScanResult {const LOST = { code: 'runtime_lost', message: 'The agent process ended unexpectedly' } as const;/**- * Boot: for every journal in `dir` no writer holds, close what a dead runner left open, under the+ * Boot: for every journal in `dir` (one directory per session, journal-dir.ts) no writer holds, close what a dead runner left open, under the* file's epoch: per unended turn, `tool.failed` (settledBy `turn.failed`) for each open call, then* `turn.failed runtime_lost`; every open ask `ask.closed` as `interrupted`; then, if anything* was open or the session was not suspended, `runtime.suspended {reason: 'lost'}` and the status.*/export async function scanJournals(dir: string, o: { owner?: SessionSeed['owner'] } = {}): Promise<ScanResult[]> {- let names: string[];- try {- names = fs.readdirSync(dir);- } catch {- return [];- }const out: ScanResult[] = [];- for (const name of names) {- const sessionId = name.replace(/\.jsonl$/, '');- if (!name.endsWith('.jsonl') || !isSessionId(sessionId)) continue;- const file = path.join(dir, name);+ for (const { sessionId, file } of listJournals(dir)) {const { epoch, through, lastSeq } = readJournalFile(file, Number.MAX_SAFE_INTEGER, 0);if (!epoch) continue;const r: ScanResult = { sessionId, file, epoch, lastSeq: 0, closedTurns: [] };