Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

Add PostgreSQL session store and unify pagination token encoding.

debajyoti-truefoundry6cd584f03a89
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 854654df7..53be442d6 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -45,3 +45,73 @@ jobs:
- name: Test
run: pnpm test
+
+ postgres-store-tests:
+ name: Postgres Session Store Tests
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ permissions:
+ contents: read
+
+ services:
+ postgres:
+ image: postgres:17-alpine
+ env:
+ POSTGRES_USER: proto
+ POSTGRES_PASSWORD: proto
+ POSTGRES_DB: proto
+ ports:
+ - 55432:5432
+ options: >-
+ --health-cmd "pg_isready -U proto -d proto"
+ --health-interval 5s
+ --health-timeout 5s
+ --health-retries 10
+
+ steps:
+ - name: Check out repository code
+ uses: actions/checkout@v4
+
+ - name: Detect session-store path changes
+ uses: dorny/paths-filter@v3
+ id: filter
+ with:
+ filters: |
+ store:
+ - 'packages/server/src/db/session-store/**'
+ - 'packages/server/tests/**'
+ - 'packages/harness/src/agent-session/**'
+ - 'packages/harness/tests/agent-session/**'
+ - 'packages/server/src/db/migrations/**'
+ - 'packages/server/src/db/migrate.ts'
+ - 'packages/server/src/db/types.ts'
+ - 'packages/server/src/db/client.ts'
+
+ - name: Skip — no session-store changes
+ if: steps.filter.outputs.store != 'true'
+ run: echo "No session-store paths changed; skipping Postgres store tests."
+
+ - name: Setup pnpm
+ if: steps.filter.outputs.store == 'true'
+ uses: pnpm/action-setup@v4
+
+ - name: Setup Node.js
+ if: steps.filter.outputs.store == 'true'
+ uses: actions/setup-node@v4
+ with:
+ node-version: '24'
+ cache: 'pnpm'
+
+ - name: Install dependencies
+ if: steps.filter.outputs.store == 'true'
+ run: pnpm install --frozen-lockfile
+
+ - name: Build
+ if: steps.filter.outputs.store == 'true'
+ run: pnpm build
+
+ - name: Postgres session store contract tests
+ if: steps.filter.outputs.store == 'true'
+ env:
+ SESSION_STORE_TEST_PG_URL: postgres://proto:proto@localhost:55432/proto
+ run: pnpm --dir packages/server test:store
diff --git a/packages/harness/package.json b/packages/harness/package.json
index 26fd0511e..51e70098e 100644
--- a/packages/harness/package.json
+++ b/packages/harness/package.json
@@ -51,7 +51,7 @@
"build:pkg": "node scripts/make-dist-package-json.mjs",
"build:check": "node scripts/check-dist.mjs",
"typecheck": "pnpm run build:gen && tsc --noEmit",
- "test": "pnpm run build:gen && jest --config jest.config.cjs --forceExit",
+ "test": "pnpm run build:gen && jest --config jest.config.cjs",
"pack:dry": "cd dist && pnpm pack --dry-run"
},
"dependencies": {
diff --git a/packages/harness/src/agent-session/SessionHandle.ts b/packages/harness/src/agent-session/SessionHandle.ts
index 57a6de93d..591a3e252 100644
--- a/packages/harness/src/agent-session/SessionHandle.ts
+++ b/packages/harness/src/agent-session/SessionHandle.ts
@@ -2,9 +2,14 @@
* Bound session handle: starts turns via {@link SessionHandle.createTurn}.
*/
import { ulid } from 'ulid';
+import { newEventId } from '../core/events/schema';
import type { AgentDefinition } from '../core/runtime/AgentDefinition';
import { AgentThread } from '../core/runtime/AgentThread';
-import type { AgentThreadSendBatch, AgentThreadSnapshot } from '../core/runtime/AgentThread.types';
+import type {
+ AgentThreadAppendContext,
+ AgentThreadSendBatch,
+ AgentThreadSnapshot,
+} from '../core/runtime/AgentThread.types';
import { AgentThreadOrchestrator } from '../core/runtime/AgentThreadOrchestrator';
import {
isApprovalDecisionMessage,
@@ -19,22 +24,24 @@ import type { ITurnResourceResolver } from './ITurnResourceResolver';
import type { SessionRecord } from './models/SessionRecord';
import { MAIN_THREAD_ID, type TurnRecord } from './models/TurnRecord';
import type { SessionEventItem } from './schemas/events';
+import { EventType, type TurnDoneEvent } from './schemas/events';
import type { TokenPagination } from './schemas/pagination';
import type { TurnInputItem } from './schemas/turn';
-import type { ISessionStore } from './store/ISessionStore';
+import { CancellationReason } from './schemas/turn';
+import type { ISessionStore, NewThreadInit, TurnContextAppend, TurnRecordWithoutSnapshot } from './store/ISessionStore';
import { TurnHandle } from './TurnHandle';
/** How many recent ancestors SessionHandle persists on each turn. Store-local. */
const MAX_TURN_ANCESTORS = 20;
function resolvePreviousTurnId(
requested: string | null | undefined,
- lastTurnId: string | undefined,
-): string | undefined {
+ lastTurnId: string | null | undefined,
+): string | null {
if (requested === null) {
- return undefined;
+ return null;
}
if (requested === undefined || requested === 'auto') {
- return lastTurnId;
+ return lastTurnId ?? null;
}
return requested;
}
@@ -52,6 +59,53 @@ function toSendBatch(input: TurnInputItem[] | undefined): AgentThreadSendBatch {
throw new Error('input must be homogeneous: all user messages, or all approval/tool-response messages');
}
+function toNewThreadInit(snapshot: AgentThreadSnapshot): NewThreadInit {
+ const { context, current_context_usage, completion, capability_state, ...rest } = snapshot;
+ void context;
+ void current_context_usage;
+ void completion;
+ void capability_state;
+ return rest;
+}
+
+function collectContextAppends(
+ events: AsyncGenerator<AgentThreadAppendContext, void, unknown>,
+): Promise<TurnContextAppend[]> {
+ return (async () => {
+ const appendMap = new Map<string, TurnContextAppend>();
+ for await (const event of events) {
+ const existing = appendMap.get(event.thread_id);
+ if (existing) {
+ existing.context.push(...event.context);
+ if (event.current_context_usage !== undefined) {
+ existing.current_context_usage = event.current_context_usage;
+ }
+ } else {
+ appendMap.set(event.thread_id, {
+ thread_id: event.thread_id,
+ context: [...event.context],
+ current_context_usage: event.current_context_usage ?? null,
+ });
+ }
+ }
+ return [...appendMap.values()];
+ })();
+}
+
+function cancelledTurnDoneEvent(): TurnDoneEvent {
+ return {
+ type: EventType.TURN_DONE,
+ id: newEventId(),
+ created_at: new Date().toISOString(),
+ state: {
+ status: 'cancelled',
+ reason: CancellationReason.CancelledForNextTurn,
+ completed_at: new Date().toISOString(),
+ },
+ thread_id: null,
+ };
+}
+
function threadsRecordFromMap(threads: Map<string, AgentThread>): Record<string, AgentThreadSnapshot> {
const out: Record<string, AgentThreadSnapshot> = {};
for (const [id, thread] of threads) {
@@ -76,15 +130,15 @@ export class SessionHandle<
return this.session.session_id;
}
- get tenant_name(): string {
- return this.session.tenant_name;
+ get tenant_id(): string {
+ return this.session.tenant_id;
}
get agent_spec() {
return this.session.agent_spec;
}
- get custom(): TSessionCustom | undefined {
+ get custom(): TSessionCustom | null {
return this.session.custom;
}
@@ -126,14 +180,15 @@ export class SessionHandle<
}): Promise<TurnHandle<TTurnCustom>> {
const previousTurnId = resolvePreviousTurnId(input.previous_turn_id, this.session.last_turn_id);
const previous = previousTurnId
- ? await this.store.getTurn({
- tenant_name: this.tenant_name,
+ ? await this.store.freezeAndGetTurn({
+ tenant_id: this.tenant_id,
session_id: this.session.session_id,
turn_id: previousTurnId,
+ turn_done_event: cancelledTurnDoneEvent(),
})
: undefined;
- const custom = typeof input.custom === 'function' ? input.custom(previous?.custom) : input.custom;
+ const custom = typeof input.custom === 'function' ? input.custom(previous?.custom ?? undefined) : input.custom;
const spec = this.session.agent_spec;
// Dispose-on-early-failure: any resource acquired below (sandbox handle,
@@ -146,7 +201,7 @@ export class SessionHandle<
const tracing = input.resolver.createTracing();
const sandbox = await input.resolver.resolveSandbox({
spec,
- existing: previous?.snapshot.sandbox_info,
+ existing: previous?.snapshot.sandbox_info ?? undefined,
previousTurn: previous,
signal: input.signal,
tracing,
@@ -176,39 +231,61 @@ export class SessionHandle<
// SEND BEFORE COMMIT — validate + append; throw ⇒ nothing persisted.
const sendBatch = toSendBatch(input.input);
- for await (const event of orchestrator.send(sendBatch)) {
- void event; // drain only
- }
+ const new_context_appends = await collectContextAppends(orchestrator.send(sendBatch));
const turnId = ulid().toLowerCase();
const now = new Date().toISOString();
- const turnRecord: TurnRecord<TTurnCustom> = {
+
+ const new_threads: NewThreadInit[] = [];
+ if (!previous) {
+ const root = agentThreads.get(MAIN_THREAD_ID);
+ if (root) {
+ new_threads.push(toNewThreadInit(root.toSnapshot()));
+ }
+ } else {
+ for (const [threadId, thread] of agentThreads) {
+ if (previous.snapshot.threads[threadId] === undefined) {
+ new_threads.push(toNewThreadInit(thread.toSnapshot()));
+ }
+ }
+ }
+
+ const turnInit: TurnRecordWithoutSnapshot<TTurnCustom> = {
turn_id: turnId,
session_id: this.session.session_id,
first_turn_id: previous?.first_turn_id ?? turnId,
- // Truncate to a recent window; stores spill if they need older ancestors.
ancestor_ids: previous ? [...previous.ancestor_ids, previous.turn_id].slice(-MAX_TURN_ANCESTORS) : [],
previous_turn_id: previousTurnId,
state: { status: 'running' },
input: input.input ?? [],
+ created_at: now,
+ updated_at: now,
+ custom: custom ?? null,
+ };
+
+ const turnRecord: TurnRecord<TTurnCustom> = {
+ ...turnInit,
snapshot: {
threads: threadsRecordFromMap(agentThreads),
- mcp_servers: previous?.snapshot.mcp_servers,
- sandbox_info: previous?.snapshot.sandbox_info,
+ mcp_servers: previous?.snapshot.mcp_servers ?? null,
+ sandbox_info: previous?.snapshot.sandbox_info ?? null,
},
- created_at: now,
- updated_at: now,
- custom,
};
await this.store.createTurn({
- tenant_name: this.tenant_name,
- turn: turnRecord,
- update_session_title_if_not_exist: input.update_session_title_if_not_exist,
+ tenant_id: this.tenant_id,
+ turn: turnInit,
+ new_threads,
+ new_context_appends,
+ capability_states: [...agentThreads].map(([thread_id, thread]) => ({
+ thread_id,
+ capability_state: thread.toSnapshot().capability_state,
+ })),
+ update_session_title_if_not_exist: input.update_session_title_if_not_exist ?? null,
});
const refreshed = await this.store.getSession({
- tenant_name: this.tenant_name,
+ tenant_id: this.tenant_id,
session_id: this.session.session_id,
});
if (refreshed) {
@@ -217,7 +294,7 @@ export class SessionHandle<
return new TurnHandle({
store: this.store,
- tenantName: this.tenant_name,
+ tenantId: this.tenant_id,
turn: turnRecord,
orchestrator,
resolver: input.resolver,
@@ -236,7 +313,7 @@ export class SessionHandle<
/** Returns the turn handle (store-backed; not executable), or undefined if not found. */
async getTurn(turn_id: string): Promise<TurnHandle<TTurnCustom> | undefined> {
const turn = await this.store.getTurn({
- tenant_name: this.tenant_name,
+ tenant_id: this.tenant_id,
session_id: this.session.session_id,
turn_id,
});
@@ -245,18 +322,18 @@ export class SessionHandle<
}
return TurnHandle.fromRecord({
store: this.store,
- tenantName: this.tenant_name,
+ tenantId: this.tenant_id,
turn,
});
}
- /** Paginated list of this session's turn records. */
+ /** Paginated list of this session's turn rows (no snapshot). */
async listTurns(input: {
limit: number;
page_token?: string | undefined;
- }): Promise<{ data: TurnRecord<TTurnCustom>[]; pagination: TokenPagination }> {
+ }): Promise<{ data: TurnRecordWithoutSnapshot<TTurnCustom>[]; pagination: TokenPagination }> {
return this.store.listTurns({
- tenant_name: this.tenant_name,
+ tenant_id: this.tenant_id,
session_id: this.session.session_id,
limit: input.limit,
page_token: input.page_token,
@@ -277,7 +354,7 @@ export class SessionHandle<
pagination: TokenPagination;
}> {
return this.store.listSessionEvents({
- tenant_name: this.tenant_name,
+ tenant_id: this.tenant_id,
session_id: this.session.session_id,
limit: input.limit,
page_token: input.page_token,
@@ -325,7 +402,7 @@ export class SessionHandle<
const { definition, extraCapabilities } = await input.resolver.resolveAgentDefinition({
spec: this.session.agent_spec,
thread_id: input.threadId,
- agent_info: input.data?.agent_info,
+ agent_info: input.data?.agent_info ?? undefined,
previousTurn: input.previous,
signal: input.signal,
tracing: input.tracing,
@@ -349,11 +426,11 @@ export class SessionHandle<
sandbox: input.sandbox,
context: input.data?.context,
currentContextUsage: input.data?.current_context_usage,
- parent: input.data?.parent,
- agentInfo: input.data?.agent_info,
- preComputedCompletion: input.data?.completion,
+ parent: input.data?.parent ?? undefined,
+ agentInfo: input.data?.agent_info ?? undefined,
+ preComputedCompletion: input.data?.completion ?? undefined,
capabilities,
- capabilityState: input.data?.capability_state,
+ capabilityState: input.data?.capability_state ?? undefined,
tracing: input.tracing,
logger: input.resolver.logger,
});
diff --git a/packages/harness/src/agent-session/Sessions.ts b/packages/harness/src/agent-session/Sessions.ts
index 9d006b122..afc129f7f 100644
--- a/packages/harness/src/agent-session/Sessions.ts
+++ b/packages/harness/src/agent-session/Sessions.ts
@@ -5,6 +5,10 @@
import { SessionHandle } from './SessionHandle';
import type { CreateSessionInput, GetSessionInput, ISessionStore } from './store/ISessionStore';
+export type SessionsCreateInput<TSessionCustom extends object> = Omit<CreateSessionInput<TSessionCustom>, 'custom'> & {
+ custom?: TSessionCustom | undefined;
+};
+
export class Sessions<
TSessionCustom extends object = Record<string, never>,
TTurnCustom extends object = Record<string, never>,
@@ -19,10 +23,13 @@ export class Sessions<
* Creates and persists a new session. `agent_spec` is the fully hydrated
* spec; the store may internally persist a blob and/or a uri/id.
*/
- async create(input: CreateSessionInput<TSessionCustom>): Promise<SessionHandle<TSessionCustom, TTurnCustom>> {
- await this.store.createSession(input);
+ async create(input: SessionsCreateInput<TSessionCustom>): Promise<SessionHandle<TSessionCustom, TTurnCustom>> {
+ await this.store.createSession({
+ ...input,
+ custom: input.custom ?? null,
+ });
const record = await this.store.getSession({
- tenant_name: input.tenant_name,
+ tenant_id: input.tenant_id,
session_id: input.session_id,
});
if (!record) {
diff --git a/packages/harness/src/agent-session/TurnHandle.ts b/packages/harness/src/agent-session/TurnHandle.ts
index e28fe5a80..f676eeb6f 100644
--- a/packages/harness/src/agent-session/TurnHandle.ts
+++ b/packages/harness/src/agent-session/TurnHandle.ts
@@ -20,6 +20,7 @@ import { EventType, type PersistedTurnEvent, type TurnCreatedEvent, type TurnDon
import type { TokenPagination } from './schemas/pagination';
import { CancellationReason, type TerminalTurnState, type TurnInputItem, type TurnState } from './schemas/turn';
import type { ISessionStore } from './store/ISessionStore';
+import { TurnNotRunningError } from './store/SessionStoreErrors';
/** Streaming yield union — deltas pass through; never persisted. No sequence_number. */
export type TurnStreamingEvent = PersistedTurnEvent | ModelMessageDeltaEvent;
@@ -68,7 +69,7 @@ function toMCPAuthRequiredEvent(event: InternalMCPAuthRequiredEvent): MCPAuthReq
export class TurnHandle<TTurnCustom extends object = Record<string, never>> {
private readonly store: ISessionStore<object, TTurnCustom>;
- private readonly tenantName: string;
+ private readonly tenantId: string;
private turn: TurnRecord<TTurnCustom>;
private readonly orchestrator: AgentThreadOrchestrator | undefined;
private readonly resolver: ITurnResourceResolver<TTurnCustom> | undefined;
@@ -77,14 +78,14 @@ export class TurnHandle<TTurnCustom extends object = Record<string, never>> {
constructor(options: {
store: ISessionStore<object, TTurnCustom>;
- tenantName: string;
+ tenantId: string;
turn: TurnRecord<TTurnCustom>;
orchestrator?: AgentThreadOrchestrator | undefined;
resolver?: ITurnResourceResolver<TTurnCustom> | undefined;
signal?: AbortSignal | undefined;
}) {
this.store = options.store;
- this.tenantName = options.tenantName;
+ this.tenantId = options.tenantId;
this.turn = options.turn;
this.orchestrator = options.orchestrator;
this.resolver = options.resolver;
@@ -94,7 +95,7 @@ export class TurnHandle<TTurnCustom extends object = Record<string, never>> {
/** Store-only handle (e.g. from {@link SessionHandle.getTurn}) — stream() is not available. */
static fromRecord<TCustom extends object = Record<string, never>>(options: {
store: ISessionStore<object, TCustom>;
- tenantName: string;
+ tenantId: string;
turn: TurnRecord<TCustom>;
}): TurnHandle<TCustom> {
return new TurnHandle(options);
@@ -108,7 +109,7 @@ export class TurnHandle<TTurnCustom extends object = Record<string, never>> {
return this.turn.session_id;
}
- get previous_turn_id(): string | undefined {
+ get previous_turn_id(): string | null {
return this.turn.previous_turn_id;
}
@@ -124,7 +125,7 @@ export class TurnHandle<TTurnCustom extends object = Record<string, never>> {
return this.turn.created_at;
}
- get custom(): TTurnCustom | undefined {
+ get custom(): TTurnCustom | null {
return this.turn.custom;
}
@@ -175,6 +176,7 @@ export class TurnHandle<TTurnCustom extends object = Record<string, never>> {
}
let caughtError: Error | undefined;
+ let frozenByStore = false;
let executeResult: AgentThreadExecutionResult | undefined;
let generator: AsyncGenerator<AgentThreadExecutionEvent, AgentThreadExecutionResult, unknown> | undefined;
@@ -183,14 +185,14 @@ export class TurnHandle<TTurnCustom extends object = Record<string, never>> {
type: EventType.TURN_CREATED,
id: newEventId(),
turn_id: this.turn.turn_id,
- previous_turn_id: this.turn.previous_turn_id ?? null,
+ previous_turn_id: this.turn.previous_turn_id,
...(this.turn.input.length > 0 ? { input: this.turn.input } : {}),
state: { status: 'running' },
created_at: this.turn.created_at,
thread_id: null,
};
await this.store.appendToEvents({
- tenant_name: this.tenantName,
+ tenant_id: this.tenantId,
session_id: this.turn.session_id,
turn_id: this.turn.turn_id,
events: [turnCreated],
@@ -201,9 +203,33 @@ export class TurnHandle<TTurnCustom extends object = Record<string, never>> {
let iterResult = await generator.next();
while (!iterResult.done) {
const event = iterResult.value;
- const yielded = await this.persistExecutionEvent(event);
- if (yielded) {
- yield yielded;
+ try {
+ const yielded = await this.persistExecutionEvent(event);
+ if (yielded) {
+ yield yielded;
+ }
+ } catch (error) {
+ if (error instanceof TurnNotRunningError) {
+ frozenByStore = true;
+ const emptyResult: AgentThreadExecutionResult = {
+ output: null,
+ required_actions: [],
+ metrics: { total: createEmptyAgentThreadMetrics() },
+ };
+ await generator.return(emptyResult);
+ // Cleared so the finally block does not close the generator a second time.
+ generator = undefined;
+ this.turn = { ...this.turn, state: error.state, updated_at: new Date().toISOString() };
+ yield {
+ type: EventType.TURN_DONE,
+ id: newEventId(),
+ created_at: new Date().toISOString(),
+ state: error.state,
+ thread_id: null,
+ };
+ return;
+ }
+ throw error;
}
iterResult = await generator.next();
}
@@ -265,34 +291,48 @@ export class TurnHandle<TTurnCustom extends object = Record<string, never>> {
thread_id: null,
};
- try {
- await this.store.updateTurnState({
- tenant_name: this.tenantName,
- session_id: this.turn.session_id,
- turn_id: this.turn.turn_id,
- state: terminalState,
- });
- await this.store.appendToEvents({
- tenant_name: this.tenantName,
- session_id: this.turn.session_id,
- turn_id: this.turn.turn_id,
- events: [turnDone],
- });
- this.turn = { ...this.turn, state: terminalState, updated_at: createdAt };
- } catch (persistError) {
- // Store-write failures reject the stream (caller drain .catch).
- await resolver.close().catch(() => {
- /* no-op */
- });
- // eslint-disable-next-line no-unsafe-finally -- deliberate: the terminal-state write runs in finally and its failure must reject the stream
- throw persistError;
+ if (!frozenByStore) {
+ try {
+ await this.store.updateTurnState({
+ tenant_id: this.tenantId,
+ session_id: this.turn.session_id,
+ turn_id: this.turn.turn_id,
+ state: terminalState,
+ turn_done_event: turnDone,
+ });
+ this.turn = { ...this.turn, state: terminalState, updated_at: createdAt };
+ } catch (persistError) {
+ if (persistError instanceof TurnNotRunningError) {
+ this.turn = { ...this.turn, state: persistError.state, updated_at: createdAt };
+ await resolver.close().catch(() => {
+ /* no-op */
+ });
+ yield {
+ type: EventType.TURN_DONE,
+ id: newEventId(),
+ created_at: createdAt,
+ state: persistError.state,
+ thread_id: null,
+ };
+ // eslint-disable-next-line no-unsafe-finally -- deliberate: a concurrent freeze during the terminal write makes the store's state authoritative, so the stream ends here
+ return;
+ }
+ // Store-write failures reject the stream (caller drain .catch).
+ await resolver.close().catch(() => {
+ /* no-op */
+ });
+ // eslint-disable-next-line no-unsafe-finally -- deliberate: the terminal-state write runs in finally and its failure must reject the stream
+ throw persistError;
+ }
}
await resolver.close().catch((err: unknown) => {
resolver.logger.warn('TurnResourceResolver.close() failed', { err });
});
- yield turnDone;
+ if (!frozenByStore) {
+ yield turnDone;
+ }
}
}
@@ -306,7 +346,7 @@ export class TurnHandle<TTurnCustom extends object = Record<string, never>> {
pagination: TokenPagination;
}> {
return this.store.listTurnEvents({
- tenant_name: this.tenantName,
+ tenant_id: this.tenantId,
session_id: this.turn.session_id,
turn_id: this.turn.turn_id,
limit: input.limit,
@@ -321,7 +361,7 @@ export class TurnHandle<TTurnCustom extends object = Record<string, never>> {
*/
private async persistExecutionEvent(event: AgentThreadExecutionEvent): Promise<TurnStreamingEvent | null> {
const scope = {
- tenant_name: this.tenantName,
+ tenant_id: this.tenantId,
session_id: this.turn.session_id,
turn_id: this.turn.turn_id,
};
@@ -370,8 +410,8 @@ export class TurnHandle<TTurnCustom extends object = Record<string, never>> {
...scope,
thread_id: event.thread_id,
context: event.context,
- current_context_usage: event.current_context_usage,
- completion: event.completion,
+ current_context_usage: event.current_context_usage ?? null,
+ completion: event.completion ?? null,
});
if (event.output.length > 0) {
await this.store.appendToEvents({
@@ -408,6 +448,8 @@ export class TurnHandle<TTurnCustom extends object = Record<string, never>> {
agent_info: event.agent_info,
context: [],
current_context_usage: getEmptyUsage(),
+ completion: null,
+ capability_state: null,
},
],
});
diff --git a/packages/harness/src/agent-session/index.ts b/packages/harness/src/agent-session/index.ts
index ce0e839fe..40fc05194 100644
--- a/packages/harness/src/agent-session/index.ts
+++ b/packages/harness/src/agent-session/index.ts
@@ -53,6 +53,7 @@ export type {
AppendToThreadContextInput,
CreateSessionInput,
CreateTurnInput,
+ FreezeAndGetTurnInput,
GetSessionInput,
GetTurnInput,
ISessionStore,
@@ -60,15 +61,29 @@ export type {
ListSessionsInput,
ListTurnEventsInput,
ListTurnsInput,
+ NewThreadInit,
OverwriteThreadContextInput,
PatchMCPServersInput,
PatchSandboxInfoInput,
PatchThreadCapabilityStateInput,
RemoveThreadsInput,
+ TurnContextAppend,
+ TurnRecordWithoutSnapshot,
UpdateSessionInput,
UpdateTurnStateInput,
} from './store/ISessionStore';
-export { SessionStoreConflictError, SessionStoreNotFoundError } from './store/SessionStoreErrors';
+export {
+ InvalidPageTokenError,
+ PreviousTurnRunningError,
+ SessionAlreadyExistsError,
+ SessionNotFoundError,
+ SessionStoreConflictError,
+ SessionStoreInvariantError,
+ SessionStoreNotFoundError,
+ TurnAlreadyExistsError,
+ TurnNotFoundError,
+ TurnNotRunningError,
+} from './store/SessionStoreErrors';
export type { ITurnResourceResolver } from './ITurnResourceResolver';
export { TurnResourceResolver } from './TurnResourceResolver';
diff --git a/packages/harness/src/agent-session/models/SessionRecord.ts b/packages/harness/src/agent-session/models/SessionRecord.ts
index e2ebb39a4..01d683e78 100644
--- a/packages/harness/src/agent-session/models/SessionRecord.ts
+++ b/packages/harness/src/agent-session/models/SessionRecord.ts
@@ -8,7 +8,7 @@ import type { AgentSpec } from '../schemas/agentSpec';
* binding via the updateSession patch.
*/
export interface SessionRecord<TCustom extends object = Record<string, never>> {
- tenant_name: string;
+ tenant_id: string;
session_id: string;
/** Always hydrated on read. Source of `spec` in SessionHandle.createTurn(). */
agent_spec: AgentSpec;
@@ -16,12 +16,12 @@ export interface SessionRecord<TCustom extends object = Record<string, never>> {
* Wire SessionSchema.title (nullable). Written via updateSession patch or
* createTurn's update_session_title_if_not_exist (first write wins; caller derives).
*/
- title?: string | null | undefined;
+ title: string | null;
/**
* Session tip — used for `previous_turn_id: 'auto'` resolution and turn
* listing anchors. Advanced only by `createTurn` (atomic link).
*/
- last_turn_id?: string | undefined;
+ last_turn_id: string | null;
/** ISO-8601 UTC datetime string (for example, `2026-07-24T02:45:00.000Z`). */
created_at: string;
/** ISO-8601 UTC datetime string (for example, `2026-07-24T02:45:00.000Z`). */
@@ -31,5 +31,5 @@ export interface SessionRecord<TCustom extends object = Record<string, never>> {
* updateSession, and createTurn — never on reads.
*/
last_activity_timestamp_ms: number;
- custom?: TCustom | undefined;
+ custom: TCustom | null;
}
diff --git a/packages/harness/src/agent-session/models/TurnRecord.ts b/packages/harness/src/agent-session/models/TurnRecord.ts
index fe5703768..bd72122a6 100644
--- a/packages/harness/src/agent-session/models/TurnRecord.ts
+++ b/packages/harness/src/agent-session/models/TurnRecord.ts
@@ -13,8 +13,8 @@ export const MAIN_THREAD_ID = 'main';
*/
export interface TurnSnapshot {
threads: Record<string, AgentThreadSnapshot>;
- mcp_servers?: Record<string, MCPServerInitInfo> | undefined;
- sandbox_info?: SandboxInfo | undefined;
+ mcp_servers: Record<string, MCPServerInitInfo> | null;
+ sandbox_info: SandboxInfo | null;
}
export interface TurnRecord<TCustom extends object = Record<string, never>> {
@@ -27,7 +27,7 @@ export interface TurnRecord<TCustom extends object = Record<string, never>> {
* need the full chain spill through older turns' own `ancestor_ids`.
*/
ancestor_ids: string[];
- previous_turn_id?: string | undefined;
+ previous_turn_id: string | null;
state: TurnState;
input: TurnInputItem[];
snapshot: TurnSnapshot;
@@ -35,5 +35,5 @@ export interface TurnRecord<TCustom extends object = Record<string, never>> {
created_at: string;
/** ISO-8601 UTC datetime string (for example, `2026-07-24T02:45:00.000Z`). */
updated_at: string;
- custom?: TCustom | undefined;
+ custom: TCustom | null;
}
diff --git a/packages/harness/src/agent-session/schemas/events.ts b/packages/harness/src/agent-session/schemas/events.ts
index 208367554..288ce88c2 100644
--- a/packages/harness/src/agent-session/schemas/events.ts
+++ b/packages/harness/src/agent-session/schemas/events.ts
@@ -86,9 +86,13 @@ export type TurnDoneEvent = z.infer<typeof TurnDoneEventSchema>;
export type SessionEvent = z.infer<typeof SessionEventSchema>;
/**
* Durable turn event log entries: {@link SessionEvent} plus any registered
- * passthrough events. Shared by append and list operations.
+ * passthrough events. Every merged event must carry its monotonic ULID and
+ * creation timestamp; shared by append and list operations.
*/
-export type PersistedTurnEvent = WithRegisteredPassthrough<SessionEvent>;
+export type PersistedTurnEvent = WithRegisteredPassthrough<SessionEvent> & {
+ id: string;
+ created_at: string;
+};
export interface SessionEventItem {
turn_id: string;
event: PersistedTurnEvent;
diff --git a/packages/harness/src/agent-session/store/ISessionStore.ts b/packages/harness/src/agent-session/store/ISessionStore.ts
index fc48197e8..93fb383cd 100644
--- a/packages/harness/src/agent-session/store/ISessionStore.ts
+++ b/packages/harness/src/agent-session/store/ISessionStore.ts
@@ -16,110 +16,162 @@ import type { TerminalTurnState } from '../schemas/turn';
/** Caller-supplied fields for creating a session; the store owns timestamps and tip state. */
export type CreateSessionInput<TSessionCustom extends object = Record<string, never>> = Pick<
SessionRecord<TSessionCustom>,
- 'tenant_name' | 'session_id' | 'agent_spec' | 'custom'
->;
+ 'tenant_id' | 'session_id' | 'agent_spec'
+> & {
+ custom: TSessionCustom | null;
+};
-/** PATCH fields for an existing session; omitted keys are left unchanged. */
+/** PATCH fields for an existing session; `undefined` fields are left unchanged. */
export type UpdateSessionInput<TSessionCustom extends object = Record<string, never>> = Pick<
SessionRecord<TSessionCustom>,
- 'tenant_name' | 'session_id'
-> &
- Partial<Pick<SessionRecord<TSessionCustom>, 'agent_spec' | 'title'>>;
+ 'tenant_id' | 'session_id'
+> & {
+ agent_spec: SessionRecord<TSessionCustom>['agent_spec'] | undefined;
+ title: SessionRecord<TSessionCustom>['title'] | undefined;
+};
export interface GetSessionInput {
- tenant_name: string;
+ tenant_id: string;
session_id: string;
}
export interface ListSessionsInput {
- tenant_name: string;
+ tenant_id: string;
limit: number;
- page_token?: string | undefined;
- order?: 'asc' | 'desc' | undefined;
- start_timestamp?: string | undefined;
- end_timestamp?: string | undefined;
+ page_token: string | undefined;
+ order: 'asc' | 'desc' | undefined;
+ start_timestamp: string | undefined;
+ end_timestamp: string | undefined;
+}
+
+/** Turn row fields without assembled snapshot (create input / listTurns). */
+export type TurnRecordWithoutSnapshot<TTurnCustom extends object = Record<string, never>> = Omit<
+ TurnRecord<TTurnCustom>,
+ 'snapshot'
+>;
+
+/** Thread registration; mutable per-turn data arrives through dedicated createTurn fields. */
+export type NewThreadInit = Omit<
+ AgentThreadSnapshot,
+ 'context' | 'current_context_usage' | 'completion' | 'capability_state'
+>;
+
+/** Full post-send capability map for one thread. */
+export type ThreadCapabilityStateInit = Pick<AgentThreadSnapshot, 'thread_id' | 'capability_state'>;
+
+/** One drained send() append batch for one thread; writer = the new turn. */
+export interface TurnContextAppend {
+ thread_id: string;
+ context: ContextMessage[];
+ current_context_usage: CompletionUsage | null;
}
export interface CreateTurnInput<TTurnCustom extends object = Record<string, never>> {
- tenant_name: string;
- turn: TurnRecord<TTurnCustom>;
- update_session_title_if_not_exist?: string | undefined;
+ tenant_id: string;
+ turn: TurnRecordWithoutSnapshot<TTurnCustom>;
+ /** Threads absent on the previous turn (turn 1: the root thread; else empty). */
+ new_threads: NewThreadInit[];
+ /**
+ * All new messages, for new and carried-forward threads alike — collected by
+ * draining orchestrator.send() BEFORE this call. Draining without persisting is
+ * safe: send() mutates only in-memory threads, and if createTurn fails the whole
+ * in-memory state (orchestrator, threads, resolver) is discarded — so either this
+ * turn commits atomically with its appends, or nothing was persisted at all.
+ */
+ new_context_appends: TurnContextAppend[];
+ /**
+ * Complete post-send capability maps: exactly one entry per turn thread.
+ * Authoritative for this turn; the store does not carry capability rows forward.
+ */
+ capability_states: ThreadCapabilityStateInit[];
+ /** Set only if session.title is NULL (first write wins). */
+ update_session_title_if_not_exist: string | null;
+}
+
+export interface FreezeAndGetTurnInput {
+ tenant_id: string;
+ session_id: string;
+ turn_id: string;
+ /** Caller-built cancelled turn.done event; store persists atomically with state flip when it cancels. */
+ turn_done_event: PersistedTurnEvent;
}
export interface GetTurnInput {
- tenant_name: string;
+ tenant_id: string;
session_id: string;
turn_id: string;
}
export interface ListTurnsInput {
- tenant_name: string;
+ tenant_id: string;
session_id: string;
limit: number;
- page_token?: string | undefined;
+ page_token: string | undefined;
}
export interface UpdateTurnStateInput {
- tenant_name: string;
+ tenant_id: string;
session_id: string;
turn_id: string;
state: TerminalTurnState;
+ /** Caller-built turn.done; written atomically with the state flip in the same tx. */
+ turn_done_event: PersistedTurnEvent;
}
export interface AppendToEventsInput {
- tenant_name: string;
+ tenant_id: string;
session_id: string;
turn_id: string;
events: PersistedTurnEvent[];
}
export interface AddThreadsInput {
- tenant_name: string;
+ tenant_id: string;
session_id: string;
turn_id: string;
threads: AgentThreadSnapshot[];
}
export interface RemoveThreadsInput {
- tenant_name: string;
+ tenant_id: string;
session_id: string;
turn_id: string;
thread_ids: string[];
}
export interface AppendToThreadContextInput {
- tenant_name: string;
+ tenant_id: string;
session_id: string;
turn_id: string;
thread_id: string;
context: ContextMessage[];
- current_context_usage?: CompletionUsage | undefined;
- completion?: SubAgentCompletionMarker | undefined;
+ current_context_usage: CompletionUsage | null;
+ completion: SubAgentCompletionMarker | null;
}
export interface OverwriteThreadContextInput {
- tenant_name: string;
+ tenant_id: string;
session_id: string;
turn_id: string;
event: ThreadOverwriteContextEvent;
}
export interface PatchMCPServersInput {
- tenant_name: string;
+ tenant_id: string;
session_id: string;
turn_id: string;
mcp_servers: MCPServerInitInfo[];
}
export interface PatchSandboxInfoInput {
- tenant_name: string;
+ tenant_id: string;
session_id: string;
turn_id: string;
sandbox_info: SandboxInfo;
}
export interface PatchThreadCapabilityStateInput {
- tenant_name: string;
+ tenant_id: string;
session_id: string;
turn_id: string;
thread_id: string;
@@ -128,28 +180,28 @@ export interface PatchThreadCapabilityStateInput {
}
export interface ListTurnEventsInput {
- tenant_name: string;
+ tenant_id: string;
session_id: string;
turn_id: string;
limit: number;
- page_token?: string | undefined;
- order?: 'asc' | 'desc' | undefined;
+ page_token: string | undefined;
+ order: 'asc' | 'desc' | undefined;
}
export interface ListSessionEventsInput {
- tenant_name: string;
+ tenant_id: string;
session_id: string;
limit: number;
- page_token?: string | undefined;
- last_turn_id?: string | undefined;
+ page_token: string | undefined;
+ last_turn_id: string | undefined;
}
/**
* Session/turn persistence contract. Pure durability: no streaming, SSE, or
* subscription members. Turn-scoped ops take session_id (membership check).
- * Capability durability goes through patchThreadCapabilityState only. Agent
- * binding is session-scoped: reads always return a hydrated agent_spec even
- * if the backend persists a uri/id.
+ * Capability maps are initialized atomically by createTurn and subsequently
+ * updated through patchThreadCapabilityState. Agent binding is session-scoped:
+ * reads always return a hydrated agent_spec even if the backend persists a uri/id.
*/
export interface ISessionStore<
TSessionCustom extends object = Record<string, never>,
@@ -174,8 +226,7 @@ export interface ISessionStore<
* PATCH semantics — update only the provided fields:
* - agent_spec: rewrite binding (full spec and/or backing uri/id). Next getSession hydrates.
* - title: set/replace the session title.
- * Bumps `last_activity_timestamp_ms` (= now). Same liveness rule applies to any
- * future session-update fields: update session ⇒ touch activity.
+ * Bumps `last_activity_timestamp_ms` (= now) in the same update.
*/
updateSession(input: UpdateSessionInput<TSessionCustom>): Promise<void>;
@@ -190,7 +241,11 @@ export interface ISessionStore<
): Promise<{ data: SessionRecord<TSessionCustom>[]; pagination: TokenPagination }>;
/**
- * Creates the turn AND advances `session.last_turn_id`.
+ * Creates the turn AND advances `session.last_turn_id`. Context merging is the
+ * store's responsibility: `new_context_appends` and `new_threads` are applied
+ * on top of the previous turn's snapshot when `turn.previous_turn_id` is set.
+ * `capability_states` is the complete authoritative map for every resulting
+ * thread and is persisted directly without store-side carry-forward.
*
* Atomicity (store contract): insert turn + set `last_turn_id` (+ session
* turn-list append if the backend has one) MUST be one atomic unit per
@@ -201,10 +256,12 @@ export interface ISessionStore<
* Also bumps `session.last_activity_timestamp_ms` in that same atomic unit.
*
* Fork semantics for `turn.previous_turn_id`:
- * - `undefined` — new root turn (no parent); always allowed.
- * - string — must reference an **existing** turn in this session (fork/chain
- * from that turn). Tip-equality is NOT required; concurrent forks from the
- * same tip both succeed. Unknown id → not-found.
+ * - `null` — new root turn (no parent); always allowed.
+ * - string — fork/chain from that turn when it exists. Tip-equality is NOT
+ * required; concurrent forks from the same tip both succeed. Unknown id is
+ * allowed (relaxed) and treated as no inheritance. If that turn exists and
+ * is still `running`, reject with {@link PreviousTurnRunningError} —
+ * callers must {@link freezeAndGetTurn} first.
* `last_turn_id` always advances to the new turn in the same atomic unit.
*
* `update_session_title_if_not_exist`: when set AND `session.title` is
@@ -214,14 +271,26 @@ export interface ISessionStore<
*/
createTurn(input: CreateTurnInput<TTurnCustom>): Promise<void>;
+ /**
+ * One tx: (a) conditionally cancel a running turn with
+ * {@link CancellationReason.CancelledForNextTurn}; (b) if it did cancel,
+ * insert the caller-built `turn_done_event` — already-terminal turns skip the
+ * event insert; (c) return the now-immutable turn record. Missing turn →
+ * {@link TurnNotFoundError}.
+ */
+ freezeAndGetTurn(input: FreezeAndGetTurnInput): Promise<TurnRecord<TTurnCustom>>;
+
/** Returns the turn record, or undefined if not found in this session. */
getTurn(input: GetTurnInput): Promise<TurnRecord<TTurnCustom> | undefined>;
- /** Paginated list of the session's turn records, stable ordering. */
- listTurns(input: ListTurnsInput): Promise<{ data: TurnRecord<TTurnCustom>[]; pagination: TokenPagination }>;
+ /** Paginated list of turn rows (no snapshot); use getTurn for assembled snapshot. */
+ listTurns(
+ input: ListTurnsInput,
+ ): Promise<{ data: TurnRecordWithoutSnapshot<TTurnCustom>[]; pagination: TokenPagination }>;
/**
- * Writes the terminal state. Store contract — **first terminal write wins**:
+ * Writes the terminal state and `turn_done_event` atomically. Store contract —
+ * **first terminal write wins**:
* - Allowed: `running` → `done` | `cancelled` | `error`.
* - Rejected with **409** (or equivalent conflict): any write when status is already
* terminal — including done→cancelled, cancelled→done, error→*, terminal→running.
@@ -237,7 +306,9 @@ export interface ISessionStore<
* `TurnCreatedEvent` at the start of the stream and a terminal `TurnDoneEvent`
* (or its cancelled/error shape) at the end. Every turn written through this
* API persists lifecycle in the stream — implementations never synthesize
- * missing created/done rows on read.
+ * missing created/done rows on read. Every event MUST carry `id` and
+ * `created_at`; `id` is a monotonic ULID and is the primary within-turn sort
+ * key. `created_at` records event creation time but is not the order key.
*/
appendToEvents(input: AppendToEventsInput): Promise<void>;
@@ -262,7 +333,7 @@ export interface ISessionStore<
/** Generic capability KV — store has zero Plan/feature knowledge. */
patchThreadCapabilityState(input: PatchThreadCapabilityStateInput): Promise<void>;
- /** Paginated read of one turn's persisted events, insertion order (asc default). */
+ /** Paginated read ordered lexically by monotonic `event.id` (asc default). */
listTurnEvents(input: ListTurnEventsInput): Promise<{
data: PersistedTurnEvent[];
pagination: TokenPagination;
@@ -273,12 +344,15 @@ export interface ISessionStore<
* turn.created / turn.done lifecycle rows. Reads only — never synthesizes.
*
* Includes events from **running** turns (the HTTP layer may 409 separately;
- * that is not store semantics). Ordering: newest-first across the flattened
- * feed. `last_turn_id` anchors the window to that turn plus its ancestors
- * (oldest first). `ancestor_ids` may be only the previous N ancestors and
- * need not reach the root — implementations that need the full chain must
- * spill through older turns' own `ancestor_ids`. Sibling branches from forks
- * are excluded; omit `last_turn_id` to use the full session turn list.
+ * that is not store semantics). Ordering: newest turn first, then monotonic
+ * `event.id` descending within each turn. `last_turn_id` anchors the window
+ * to that turn plus its ancestors; when omitted, the session's current
+ * `last_turn_id` selects the active branch. Continuation page tokens encode
+ * that anchor and take precedence over `last_turn_id`, so later session
+ * activity cannot move an in-progress pagination walk to another branch.
+ * `ancestor_ids` may include only the previous N ancestors and need not reach
+ * the root — implementations must spill through older turns' own
+ * `ancestor_ids` when needed. Sibling branches from forks are excluded.
*/
listSessionEvents(input: ListSessionEventsInput): Promise<{
data: SessionEventItem[];
diff --git a/packages/harness/src/agent-session/store/InMemorySessionStore.ts b/packages/harness/src/agent-session/store/InMemorySessionStore.ts
index 8d686e179..10a5d440f 100644
--- a/packages/harness/src/agent-session/store/InMemorySessionStore.ts
+++ b/packages/harness/src/agent-session/store/InMemorySessionStore.ts
@@ -1,13 +1,17 @@
+import { getEmptyUsage } from '../../core/llm/LLMTypes';
+import type { AgentThreadSnapshot } from '../../core/runtime/AgentThread.types';
import type { SessionRecord } from '../models/SessionRecord';
-import type { TurnRecord } from '../models/TurnRecord';
+import type { TurnRecord, TurnSnapshot } from '../models/TurnRecord';
import type { PersistedTurnEvent, SessionEventItem } from '../schemas/events';
import type { TokenPagination } from '../schemas/pagination';
+import { CancellationReason, type TerminalTurnState } from '../schemas/turn';
import type {
AddThreadsInput,
AppendToEventsInput,
AppendToThreadContextInput,
CreateSessionInput,
CreateTurnInput,
+ FreezeAndGetTurnInput,
GetSessionInput,
GetTurnInput,
ISessionStore,
@@ -15,15 +19,32 @@ import type {
ListSessionsInput,
ListTurnEventsInput,
ListTurnsInput,
+ NewThreadInit,
OverwriteThreadContextInput,
PatchMCPServersInput,
PatchSandboxInfoInput,
PatchThreadCapabilityStateInput,
RemoveThreadsInput,
+ TurnContextAppend,
+ TurnRecordWithoutSnapshot,
UpdateSessionInput,
UpdateTurnStateInput,
} from './ISessionStore';
-import { SessionStoreConflictError, SessionStoreNotFoundError } from './SessionStoreErrors';
+import { decodeOffsetPageToken, encodeOffsetPageToken } from './OffsetPageToken';
+import {
+ decodeSessionEventPageToken,
+ paginateSessionEventRows,
+ type SessionEventPageCursor,
+} from './SessionEventPageToken';
+import {
+ PreviousTurnRunningError,
+ SessionAlreadyExistsError,
+ SessionNotFoundError,
+ SessionStoreInvariantError,
+ TurnAlreadyExistsError,
+ TurnNotFoundError,
+ TurnNotRunningError,
+} from './SessionStoreErrors';
/* eslint-disable @typescript-eslint/require-await -- in-memory store is synchronous; methods stay async so thrown SessionStore*Error reject as Promises for ISessionStore callers */
@@ -46,28 +67,92 @@ function turnKey(tenant: string, sessionId: string, turnId: string): string {
return `${tenant}:${sessionId}:${turnId}`;
}
-function encodeOffset(offset: number): string {
- return String(offset);
+function newThreadSnapshot(thread: NewThreadInit): AgentThreadSnapshot {
+ return {
+ thread_id: thread.thread_id,
+ parent: thread.parent ?? null,
+ agent_info: thread.agent_info ?? null,
+ capability_state: null,
+ context: [],
+ current_context_usage: getEmptyUsage(),
+ completion: null,
+ };
}
-function decodeOffset(token: string | undefined): number {
- if (token === undefined || token === '') return 0;
- const n = Number(token);
- if (!Number.isInteger(n) || n < 0) {
- throw new SessionStoreConflictError(`Invalid page_token: ${token}`);
+function applyContextAppends(threads: Record<string, AgentThreadSnapshot>, appends: TurnContextAppend[]): void {
+ for (const append of appends) {
+ const thread = threads[append.thread_id];
+ if (!thread) {
+ throw new SessionStoreInvariantError(`new_context_appends references unknown thread ${append.thread_id}`);
+ }
+ thread.context.push(...deepCopy(append.context));
+ if (append.current_context_usage !== null) {
+ thread.current_context_usage = deepCopy(append.current_context_usage);
+ }
}
- return n;
+}
+
+function buildSnapshotFromDelta(input: {
+ previousSnapshot: TurnSnapshot | undefined;
+ new_threads: NewThreadInit[];
+ new_context_appends: TurnContextAppend[];
+ capability_states: CreateTurnInput['capability_states'];
+}): TurnSnapshot {
+ const threads: Record<string, AgentThreadSnapshot> = input.previousSnapshot
+ ? deepCopy(input.previousSnapshot.threads)
+ : {};
+
+ for (const nt of input.new_threads) {
+ if (threads[nt.thread_id] !== undefined) {
+ throw new SessionStoreInvariantError(
+ `new_threads must only contain threads absent on the previous turn; thread '${nt.thread_id}' already exists`,
+ );
+ }
+ threads[nt.thread_id] = newThreadSnapshot(nt);
+ }
+
+ const knownThreadIds = new Set(Object.keys(threads));
+ for (const append of input.new_context_appends) {
+ if (!knownThreadIds.has(append.thread_id)) {
+ throw new SessionStoreInvariantError(`new_context_appends references unknown thread ${append.thread_id}`);
+ }
+ }
+
+ applyContextAppends(threads, input.new_context_appends);
+ const seenCapabilityThreads = new Set<string>();
+ for (const capability of input.capability_states) {
+ const thread = threads[capability.thread_id];
+ if (thread === undefined) {
+ throw new SessionStoreInvariantError(`capability_states references unknown thread ${capability.thread_id}`);
+ }
+ if (seenCapabilityThreads.has(capability.thread_id)) {
+ throw new SessionStoreInvariantError(`capability_states contains duplicate thread ${capability.thread_id}`);
+ }
+ seenCapabilityThreads.add(capability.thread_id);
+ thread.capability_state = deepCopy(capability.capability_state);
+ }
+ for (const threadId of Object.keys(threads)) {
+ if (!seenCapabilityThreads.has(threadId)) {
+ throw new SessionStoreInvariantError(`capability_states is missing thread ${threadId}`);
+ }
+ }
+
+ return {
+ threads,
+ mcp_servers: input.previousSnapshot ? deepCopy(input.previousSnapshot.mcp_servers) : null,
+ sandbox_info: input.previousSnapshot ? deepCopy(input.previousSnapshot.sandbox_info) : null,
+ };
}
function paginate<T>(items: T[], limit: number, pageToken?: string): { data: T[]; pagination: TokenPagination } {
- const offset = decodeOffset(pageToken);
+ const offset = decodeOffsetPageToken(pageToken);
const slice = items.slice(offset, offset + limit);
return {
data: slice,
pagination: {
limit,
- ...(offset + limit < items.length ? { next_page_token: encodeOffset(offset + limit) } : {}),
- ...(offset > 0 ? { previous_page_token: encodeOffset(Math.max(0, offset - limit)) } : {}),
+ ...(offset + limit < items.length ? { next_page_token: encodeOffsetPageToken(offset + limit) } : {}),
+ ...(offset > 0 ? { previous_page_token: encodeOffsetPageToken(Math.max(0, offset - limit)) } : {}),
},
};
}
@@ -85,35 +170,36 @@ export class InMemorySessionStore<
private readonly events = new Map<string, StoredEvent[]>();
async createSession(input: CreateSessionInput<TSessionCustom>): Promise<void> {
- const key = sessionKey(input.tenant_name, input.session_id);
+ const key = sessionKey(input.tenant_id, input.session_id);
if (this.sessions.has(key)) {
- throw new SessionStoreConflictError(`Session already exists: ${input.session_id}`);
+ throw new SessionAlreadyExistsError(input.session_id);
}
const now = new Date().toISOString();
const record: SessionRecord<TSessionCustom> = {
- tenant_name: input.tenant_name,
+ tenant_id: input.tenant_id,
session_id: input.session_id,
agent_spec: deepCopy(input.agent_spec),
title: null,
+ last_turn_id: null,
created_at: now,
updated_at: now,
last_activity_timestamp_ms: Date.now(),
- custom: input.custom !== undefined ? deepCopy(input.custom) : undefined,
+ custom: input.custom !== null ? deepCopy(input.custom) : null,
};
this.sessions.set(key, { record, turnIds: [] });
return;
}
async getSession(input: GetSessionInput): Promise<SessionRecord<TSessionCustom> | undefined> {
- const stored = this.sessions.get(sessionKey(input.tenant_name, input.session_id));
+ const stored = this.sessions.get(sessionKey(input.tenant_id, input.session_id));
return stored ? deepCopy(stored.record) : undefined;
}
async updateSession(input: UpdateSessionInput<TSessionCustom>): Promise<void> {
- const key = sessionKey(input.tenant_name, input.session_id);
+ const key = sessionKey(input.tenant_id, input.session_id);
const stored = this.sessions.get(key);
if (!stored) {
- throw new SessionStoreNotFoundError(`Session not found: ${input.session_id}`);
+ throw new SessionNotFoundError(input.session_id);
}
if (input.agent_spec !== undefined) {
stored.record.agent_spec = deepCopy(input.agent_spec);
@@ -121,15 +207,16 @@ export class InMemorySessionStore<
if (input.title !== undefined) {
stored.record.title = input.title;
}
- stored.record.updated_at = new Date().toISOString();
- stored.record.last_activity_timestamp_ms = Date.now();
+ const now = Date.now();
+ stored.record.updated_at = new Date(now).toISOString();
+ stored.record.last_activity_timestamp_ms = now;
return;
}
async listSessions(
input: ListSessionsInput,
): Promise<{ data: SessionRecord<TSessionCustom>[]; pagination: TokenPagination }> {
- const prefix = `${input.tenant_name}:`;
+ const prefix = `${input.tenant_id}:`;
const records: SessionRecord<TSessionCustom>[] = [];
for (const [key, stored] of this.sessions) {
if (!key.startsWith(prefix)) continue;
@@ -149,77 +236,127 @@ export class InMemorySessionStore<
// Atomicity is free here: this body is fully synchronous, so Node's
// run-to-completion guarantees it. Real backends must still use their own
// locking/transactions to satisfy the ISessionStore createTurn contract.
- const sKey = sessionKey(input.tenant_name, input.turn.session_id);
+ const sKey = sessionKey(input.tenant_id, input.turn.session_id);
const stored = this.sessions.get(sKey);
if (!stored) {
- throw new SessionStoreNotFoundError(`Session not found: ${input.turn.session_id}`);
+ throw new SessionNotFoundError(input.turn.session_id);
}
+
const previousTurnId = input.turn.previous_turn_id;
- if (previousTurnId !== undefined) {
- const prevKey = turnKey(input.tenant_name, input.turn.session_id, previousTurnId);
- if (!this.turns.has(prevKey)) {
- throw new SessionStoreNotFoundError(`previous_turn_id not found in session: ${previousTurnId}`);
+ let previousSnapshot: TurnSnapshot | undefined;
+ if (previousTurnId !== null) {
+ const prevKey = turnKey(input.tenant_id, input.turn.session_id, previousTurnId);
+ const prev = this.turns.get(prevKey);
+ // Unknown previous_turn_id is allowed (relaxed): treat as no inheritance.
+ // A still-running previous must be frozen first.
+ if (prev !== undefined) {
+ if (prev.state.status === 'running') {
+ throw new PreviousTurnRunningError(previousTurnId);
+ }
+ previousSnapshot = prev.snapshot;
}
}
- const tKey = turnKey(input.tenant_name, input.turn.session_id, input.turn.turn_id);
+
+ const tKey = turnKey(input.tenant_id, input.turn.session_id, input.turn.turn_id);
if (this.turns.has(tKey)) {
- throw new SessionStoreConflictError(`Turn already exists: ${input.turn.turn_id}`);
+ throw new TurnAlreadyExistsError(input.turn.turn_id);
}
- this.turns.set(tKey, deepCopy(input.turn));
+
+ const snapshot = buildSnapshotFromDelta({
+ previousSnapshot,
+ new_threads: input.new_threads,
+ new_context_appends: input.new_context_appends,
+ capability_states: input.capability_states,
+ });
+
+ const turnRecord: TurnRecord<TTurnCustom> = {
+ ...deepCopy(input.turn),
+ snapshot,
+ };
+
+ this.turns.set(tKey, turnRecord);
this.events.set(tKey, []);
stored.turnIds.push(input.turn.turn_id);
stored.record.last_turn_id = input.turn.turn_id;
stored.record.last_activity_timestamp_ms = Date.now();
stored.record.updated_at = new Date().toISOString();
- if (
- input.update_session_title_if_not_exist !== undefined &&
- (stored.record.title === undefined || stored.record.title === null)
- ) {
+ if (input.update_session_title_if_not_exist !== null && stored.record.title === null) {
stored.record.title = input.update_session_title_if_not_exist;
}
}
+ async freezeAndGetTurn(input: FreezeAndGetTurnInput): Promise<TurnRecord<TTurnCustom>> {
+ const tKey = turnKey(input.tenant_id, input.session_id, input.turn_id);
+ const turn = this.turns.get(tKey);
+ if (!turn) {
+ throw new TurnNotFoundError(input.turn_id);
+ }
+
+ if (turn.state.status === 'running') {
+ const cancelledState: TerminalTurnState = {
+ status: 'cancelled',
+ reason: CancellationReason.CancelledForNextTurn,
+ completed_at: new Date().toISOString(),
+ };
+ turn.state = cancelledState;
+ turn.updated_at = new Date().toISOString();
+ const list = this.events.get(tKey);
+ if (list) {
+ list.push(deepCopy(input.turn_done_event));
+ }
+ }
+
+ return deepCopy(turn);
+ }
+
async getTurn(input: GetTurnInput): Promise<TurnRecord<TTurnCustom> | undefined> {
- const turn = this.turns.get(turnKey(input.tenant_name, input.session_id, input.turn_id));
+ const turn = this.turns.get(turnKey(input.tenant_id, input.session_id, input.turn_id));
return turn ? deepCopy(turn) : undefined;
}
- async listTurns(input: ListTurnsInput): Promise<{ data: TurnRecord<TTurnCustom>[]; pagination: TokenPagination }> {
- const stored = this.sessions.get(sessionKey(input.tenant_name, input.session_id));
+ async listTurns(
+ input: ListTurnsInput,
+ ): Promise<{ data: TurnRecordWithoutSnapshot<TTurnCustom>[]; pagination: TokenPagination }> {
+ const stored = this.sessions.get(sessionKey(input.tenant_id, input.session_id));
if (!stored) {
- throw new SessionStoreNotFoundError(`Session not found: ${input.session_id}`);
+ throw new SessionNotFoundError(input.session_id);
}
const records = stored.turnIds.map(id => {
- const turn = this.turns.get(turnKey(input.tenant_name, input.session_id, id));
+ const turn = this.turns.get(turnKey(input.tenant_id, input.session_id, id));
if (!turn) {
- throw new SessionStoreNotFoundError(`Turn not found: ${id}`);
+ throw new TurnNotFoundError(id);
}
- return deepCopy(turn);
+ const { snapshot, ...row } = deepCopy(turn);
+ void snapshot;
+ return row;
});
return paginate(records, input.limit, input.page_token);
}
async updateTurnState(input: UpdateTurnStateInput): Promise<void> {
// Same as createTurn: synchronous body ⇒ atomic under run-to-completion.
- const tKey = turnKey(input.tenant_name, input.session_id, input.turn_id);
+ const tKey = turnKey(input.tenant_id, input.session_id, input.turn_id);
const turn = this.turns.get(tKey);
if (!turn) {
- throw new SessionStoreNotFoundError(`Turn not found: ${input.turn_id}`);
+ throw new TurnNotFoundError(input.turn_id);
}
if (turn.state.status !== 'running') {
- throw new SessionStoreConflictError(
- `Turn ${input.turn_id} is already terminal (${turn.state.status}); first terminal write wins`,
- );
+ throw new TurnNotRunningError(input.turn_id, turn.state);
}
turn.state = deepCopy(input.state);
turn.updated_at = new Date().toISOString();
+ const list = this.events.get(tKey);
+ if (list) {
+ list.push(deepCopy(input.turn_done_event));
+ }
}
async appendToEvents(input: AppendToEventsInput): Promise<void> {
- const tKey = turnKey(input.tenant_name, input.session_id, input.turn_id);
+ this.requireRunningTurn(input.tenant_id, input.session_id, input.turn_id);
+ const tKey = turnKey(input.tenant_id, input.session_id, input.turn_id);
const list = this.events.get(tKey);
if (!list) {
- throw new SessionStoreNotFoundError(`Turn not found: ${input.turn_id}`);
+ throw new TurnNotFoundError(input.turn_id);
}
list.push(...deepCopy(input.events));
return;
@@ -228,13 +365,21 @@ export class InMemorySessionStore<
private requireTurn(tenant: string, sessionId: string, turnId: string): TurnRecord<TTurnCustom> {
const turn = this.turns.get(turnKey(tenant, sessionId, turnId));
if (!turn) {
- throw new SessionStoreNotFoundError(`Turn not found: ${turnId}`);
+ throw new TurnNotFoundError(turnId);
+ }
+ return turn;
+ }
+
+ private requireRunningTurn(tenant: string, sessionId: string, turnId: string): TurnRecord<TTurnCustom> {
+ const turn = this.requireTurn(tenant, sessionId, turnId);
+ if (turn.state.status !== 'running') {
+ throw new TurnNotRunningError(turnId, turn.state);
}
return turn;
}
async addThreads(input: AddThreadsInput): Promise<void> {
- const turn = this.requireTurn(input.tenant_name, input.session_id, input.turn_id);
+ const turn = this.requireRunningTurn(input.tenant_id, input.session_id, input.turn_id);
for (const thread of input.threads) {
turn.snapshot.threads[thread.thread_id] = deepCopy(thread);
}
@@ -243,7 +388,7 @@ export class InMemorySessionStore<
}
async removeThreads(input: RemoveThreadsInput): Promise<void> {
- const turn = this.requireTurn(input.tenant_name, input.session_id, input.turn_id);
+ const turn = this.requireRunningTurn(input.tenant_id, input.session_id, input.turn_id);
for (const id of input.thread_ids) {
Reflect.deleteProperty(turn.snapshot.threads, id);
}
@@ -252,16 +397,16 @@ export class InMemorySessionStore<
}
async appendToThreadContext(input: AppendToThreadContextInput): Promise<void> {
- const turn = this.requireTurn(input.tenant_name, input.session_id, input.turn_id);
+ const turn = this.requireRunningTurn(input.tenant_id, input.session_id, input.turn_id);
const thread = turn.snapshot.threads[input.thread_id];
if (!thread) {
- throw new SessionStoreNotFoundError(`Thread not found: ${input.thread_id}`);
+ throw new SessionStoreInvariantError(`Thread not found: ${input.thread_id}`);
}
thread.context.push(...deepCopy(input.context));
- if (input.current_context_usage !== undefined) {
+ if (input.current_context_usage !== null) {
thread.current_context_usage = deepCopy(input.current_context_usage);
}
- if (input.completion !== undefined) {
+ if (input.completion !== null) {
thread.completion = deepCopy(input.completion);
}
turn.updated_at = new Date().toISOString();
@@ -269,11 +414,11 @@ export class InMemorySessionStore<
}
async overwriteThreadContext(input: OverwriteThreadContextInput): Promise<void> {
- const turn = this.requireTurn(input.tenant_name, input.session_id, input.turn_id);
+ const turn = this.requireRunningTurn(input.tenant_id, input.session_id, input.turn_id);
const threadId = input.event.thread_id;
const thread = turn.snapshot.threads[threadId];
if (!thread) {
- throw new SessionStoreNotFoundError(`Thread not found: ${threadId}`);
+ throw new SessionStoreInvariantError(`Thread not found: ${threadId}`);
}
thread.context = deepCopy(input.event.context);
thread.current_context_usage = deepCopy(input.event.current_context_usage);
@@ -282,7 +427,7 @@ export class InMemorySessionStore<
}
async patchMCPServers(input: PatchMCPServersInput): Promise<void> {
- const turn = this.requireTurn(input.tenant_name, input.session_id, input.turn_id);
+ const turn = this.requireRunningTurn(input.tenant_id, input.session_id, input.turn_id);
turn.snapshot.mcp_servers ??= {};
for (const server of input.mcp_servers) {
turn.snapshot.mcp_servers[server.id] = deepCopy(server);
@@ -292,20 +437,27 @@ export class InMemorySessionStore<
}
async patchSandboxInfo(input: PatchSandboxInfoInput): Promise<void> {
- const turn = this.requireTurn(input.tenant_name, input.session_id, input.turn_id);
+ const turn = this.requireRunningTurn(input.tenant_id, input.session_id, input.turn_id);
turn.snapshot.sandbox_info = deepCopy(input.sandbox_info);
turn.updated_at = new Date().toISOString();
return;
}
async patchThreadCapabilityState(input: PatchThreadCapabilityStateInput): Promise<void> {
- const turn = this.requireTurn(input.tenant_name, input.session_id, input.turn_id);
+ const turn = this.requireRunningTurn(input.tenant_id, input.session_id, input.turn_id);
const thread = turn.snapshot.threads[input.thread_id];
if (!thread) {
- throw new SessionStoreNotFoundError(`Thread not found: ${input.thread_id}`);
+ throw new SessionStoreInvariantError(`Thread not found: ${input.thread_id}`);
}
thread.capability_state ??= {};
- thread.capability_state[input.key] = deepCopy(input.state);
+ if (input.state === null) {
+ Reflect.deleteProperty(thread.capability_state, input.key);
+ if (Object.keys(thread.capability_state).length === 0) {
+ thread.capability_state = null;
+ }
+ } else {
+ thread.capability_state[input.key] = deepCopy(input.state);
+ }
turn.updated_at = new Date().toISOString();
return;
}
@@ -314,11 +466,13 @@ export class InMemorySessionStore<
data: PersistedTurnEvent[];
pagination: TokenPagination;
}> {
- const list = this.events.get(turnKey(input.tenant_name, input.session_id, input.turn_id));
+ const list = this.events.get(turnKey(input.tenant_id, input.session_id, input.turn_id));
if (!list) {
- throw new SessionStoreNotFoundError(`Turn not found: ${input.turn_id}`);
+ throw new TurnNotFoundError(input.turn_id);
}
- const ordered = input.order === 'desc' ? [...list].reverse() : list;
+ const ordered = [...list].sort((a, b) =>
+ input.order === 'desc' ? b.id.localeCompare(a.id) : a.id.localeCompare(b.id),
+ );
const page = paginate(ordered, input.limit, input.page_token);
return { data: deepCopy(page.data), pagination: page.pagination };
}
@@ -327,28 +481,38 @@ export class InMemorySessionStore<
data: SessionEventItem[];
pagination: TokenPagination;
}> {
- const stored = this.sessions.get(sessionKey(input.tenant_name, input.session_id));
+ const stored = this.sessions.get(sessionKey(input.tenant_id, input.session_id));
if (!stored) {
- throw new SessionStoreNotFoundError(`Session not found: ${input.session_id}`);
+ throw new SessionNotFoundError(input.session_id);
}
- let turnIds = stored.turnIds;
- if (input.last_turn_id) {
- const anchor = this.turns.get(turnKey(input.tenant_name, input.session_id, input.last_turn_id));
- if (!anchor) {
- throw new SessionStoreNotFoundError(`Turn not found: ${input.last_turn_id}`);
- }
- turnIds = this.resolveAncestorChain(input.tenant_name, input.session_id, anchor);
+
+ const decodedCursor = input.page_token === undefined ? undefined : decodeSessionEventPageToken(input.page_token);
+ const lastTurnId = decodedCursor?.last_turn_id ?? input.last_turn_id ?? stored.record.last_turn_id;
+ if (lastTurnId === null) {
+ return { data: [], pagination: { limit: input.limit } };
}
+ const cursor: SessionEventPageCursor = {
+ last_turn_id: lastTurnId,
+ offset: decodedCursor?.offset ?? 0,
+ };
+
+ const anchor = this.turns.get(turnKey(input.tenant_id, input.session_id, cursor.last_turn_id));
+ if (!anchor) {
+ throw new TurnNotFoundError(cursor.last_turn_id);
+ }
+ const turnIds = this.resolveAncestorChain(input.tenant_id, input.session_id, anchor);
const flattened: SessionEventItem[] = [];
- for (const turnId of turnIds) {
- const evts = this.events.get(turnKey(input.tenant_name, input.session_id, turnId)) ?? [];
- for (const event of evts) {
+ for (const turnId of [...turnIds].reverse()) {
+ const evts = this.events.get(turnKey(input.tenant_id, input.session_id, turnId)) ?? [];
+ for (const event of [...evts].sort((a, b) => b.id.localeCompare(a.id))) {
flattened.push({ turn_id: turnId, event });
}
}
- // Newest first for session feed.
- flattened.reverse();
- const page = paginate(flattened, input.limit, input.page_token);
+ const page = paginateSessionEventRows(
+ flattened.slice(cursor.offset, cursor.offset + input.limit + 1),
+ input.limit,
+ cursor,
+ );
return { data: deepCopy(page.data), pagination: page.pagination };
}
diff --git a/packages/harness/src/agent-session/store/OffsetPageToken.ts b/packages/harness/src/agent-session/store/OffsetPageToken.ts
new file mode 100644
index 000000000..6025ab526
--- /dev/null
+++ b/packages/harness/src/agent-session/store/OffsetPageToken.ts
@@ -0,0 +1,37 @@
+import { z } from 'zod';
+import type { TokenPagination } from '../schemas/pagination';
+import { decodePageToken, encodePageToken } from './PageToken';
+
+export const OffsetPageCursorSchema = z
+ .object({
+ offset: z.number().int().nonnegative().safe(),
+ })
+ .strict();
+
+export type OffsetPageCursor = z.infer<typeof OffsetPageCursorSchema>;
+
+export function encodeOffsetPageToken(offset: number): string {
+ return encodePageToken(OffsetPageCursorSchema, { offset });
+}
+
+export function decodeOffsetPageToken(token: string | undefined): number {
+ if (token === undefined || token === '') return 0;
+ return decodePageToken(OffsetPageCursorSchema, token).offset;
+}
+
+export function paginateOffsetRows<T>(
+ rows: T[],
+ limit: number,
+ offset: number,
+): { data: T[]; pagination: TokenPagination } {
+ const hasMore = rows.length > limit;
+ const data = hasMore ? rows.slice(0, limit) : rows;
+ return {
+ data,
+ pagination: {
+ limit,
+ ...(hasMore ? { next_page_token: encodeOffsetPageToken(offset + limit) } : {}),
+ ...(offset > 0 ? { previous_page_token: encodeOffsetPageToken(Math.max(0, offset - limit)) } : {}),
+ },
+ };
+}
diff --git a/packages/harness/src/agent-session/store/PageToken.ts b/packages/harness/src/agent-session/store/PageToken.ts
new file mode 100644
index 000000000..9ece4511e
--- /dev/null
+++ b/packages/harness/src/agent-session/store/PageToken.ts
@@ -0,0 +1,16 @@
+import type { z } from 'zod';
+import { InvalidPageTokenError } from './SessionStoreErrors';
+
+export function encodePageToken<Output>(schema: z.ZodType<Output>, value: Output): string {
+ const parsed = schema.parse(value);
+ return Buffer.from(JSON.stringify(parsed), 'utf8').toString('base64url');
+}
+
+export function decodePageToken<Output>(schema: z.ZodType<Output>, token: string): Output {
+ try {
+ const value: unknown = JSON.parse(Buffer.from(token, 'base64url').toString('utf8'));
+ return schema.parse(value);
+ } catch {
+ throw new InvalidPageTokenError(token);
+ }
+}
diff --git a/packages/harness/src/agent-session/store/SessionEventPageToken.ts b/packages/harness/src/agent-session/store/SessionEventPageToken.ts
new file mode 100644
index 000000000..d968e2e66
--- /dev/null
+++ b/packages/harness/src/agent-session/store/SessionEventPageToken.ts
@@ -0,0 +1,51 @@
+import { z } from 'zod';
+import type { TokenPagination } from '../schemas/pagination';
+import { decodePageToken, encodePageToken } from './PageToken';
+
+export const SessionEventPageCursorSchema = z
+ .object({
+ last_turn_id: z.string().min(1),
+ offset: z.number().int().nonnegative().safe(),
+ })
+ .strict();
+
+export type SessionEventPageCursor = z.infer<typeof SessionEventPageCursorSchema>;
+
+export function encodeSessionEventPageToken(cursor: SessionEventPageCursor): string {
+ return encodePageToken(SessionEventPageCursorSchema, cursor);
+}
+
+export function decodeSessionEventPageToken(token: string): SessionEventPageCursor {
+ return decodePageToken(SessionEventPageCursorSchema, token);
+}
+
+export function paginateSessionEventRows<T>(
+ rows: T[],
+ limit: number,
+ cursor: SessionEventPageCursor,
+): { data: T[]; pagination: TokenPagination } {
+ const hasMore = rows.length > limit;
+ const data = hasMore ? rows.slice(0, limit) : rows;
+ return {
+ data,
+ pagination: {
+ limit,
+ ...(hasMore
+ ? {
+ next_page_token: encodeSessionEventPageToken({
+ last_turn_id: cursor.last_turn_id,
+ offset: cursor.offset + limit,
+ }),
+ }
+ : {}),
+ ...(cursor.offset > 0
+ ? {
+ previous_page_token: encodeSessionEventPageToken({
+ last_turn_id: cursor.last_turn_id,
+ offset: Math.max(0, cursor.offset - limit),
+ }),
+ }
+ : {}),
+ },
+ };
+}
diff --git a/packages/harness/src/agent-session/store/SessionStoreErrors.ts b/packages/harness/src/agent-session/store/SessionStoreErrors.ts
index b22bc0b45..2caa95164 100644
--- a/packages/harness/src/agent-session/store/SessionStoreErrors.ts
+++ b/packages/harness/src/agent-session/store/SessionStoreErrors.ts
@@ -1,5 +1,7 @@
+import type { TerminalTurnState } from '../schemas/turn';
+
/** Store conflict (e.g. first-terminal-wins violation, concurrent createTurn). */
-export class SessionStoreConflictError extends Error {
+export abstract class SessionStoreConflictError extends Error {
constructor(message: string) {
super(message);
this.name = 'SessionStoreConflictError';
@@ -7,9 +9,91 @@ export class SessionStoreConflictError extends Error {
}
/** Store not-found (session or turn missing). */
-export class SessionStoreNotFoundError extends Error {
+export abstract class SessionStoreNotFoundError extends Error {
constructor(message: string) {
super(message);
this.name = 'SessionStoreNotFoundError';
}
}
+
+/** Implementation bug or thread misuse — not mapped to 4xx by API handlers. */
+export class SessionStoreInvariantError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'SessionStoreInvariantError';
+ }
+}
+
+export class SessionNotFoundError extends SessionStoreNotFoundError {
+ readonly session_id: string;
+
+ constructor(session_id: string) {
+ super(`Session not found: ${session_id}`);
+ this.name = 'SessionNotFoundError';
+ this.session_id = session_id;
+ }
+}
+
+export class TurnNotFoundError extends SessionStoreNotFoundError {
+ readonly turn_id: string;
+
+ constructor(turn_id: string) {
+ super(`Turn not found: ${turn_id}`);
+ this.name = 'TurnNotFoundError';
+ this.turn_id = turn_id;
+ }
+}
+
+export class SessionAlreadyExistsError extends SessionStoreConflictError {
+ readonly session_id: string;
+
+ constructor(session_id: string) {
+ super(`Session already exists: ${session_id}`);
+ this.name = 'SessionAlreadyExistsError';
+ this.session_id = session_id;
+ }
+}
+
+export class TurnAlreadyExistsError extends SessionStoreConflictError {
+ readonly turn_id: string;
+
+ constructor(turn_id: string) {
+ super(`Turn already exists: ${turn_id}`);
+ this.name = 'TurnAlreadyExistsError';
+ this.turn_id = turn_id;
+ }
+}
+
+export class PreviousTurnRunningError extends SessionStoreConflictError {
+ readonly previous_turn_id: string;
+
+ constructor(previous_turn_id: string) {
+ super(
+ `Previous turn ${previous_turn_id} is still running; freezeAndGetTurn must be called before creating a successor`,
+ );
+ this.name = 'PreviousTurnRunningError';
+ this.previous_turn_id = previous_turn_id;
+ }
+}
+
+export class TurnNotRunningError extends SessionStoreConflictError {
+ readonly turn_id: string;
+ readonly state: TerminalTurnState;
+
+ constructor(turn_id: string, state: TerminalTurnState) {
+ super(`Turn ${turn_id} is not running (${state.status})`);
+ this.name = 'TurnNotRunningError';
+ this.turn_id = turn_id;
+ this.state = state;
+ }
+}
+
+export class InvalidPageTokenError extends SessionStoreConflictError {
+ readonly token: string;
+
+ constructor(token: string) {
+ super(`Invalid page token: ${token}`);
+ this.name = 'InvalidPageTokenError';
+ this.token = token;
+ }
+}
diff --git a/packages/harness/src/core/events/PassthroughEvents.ts b/packages/harness/src/core/events/PassthroughEvents.ts
index cf80f0b85..083e13ebd 100644
--- a/packages/harness/src/core/events/PassthroughEvents.ts
+++ b/packages/harness/src/core/events/PassthroughEvents.ts
@@ -17,7 +17,13 @@ export interface AgentPassthroughEventSchemaMap {}
export type RegisteredPassthroughEvent = {
[K in keyof AgentPassthroughEventSchemaMap]: AgentPassthroughEventSchemaMap[K] extends z.ZodType<infer Event>
- ? Event & { type: K }
+ ? Event & {
+ type: K;
+ /** Durable event identity and primary ordering key. */
+ id: string;
+ /** ISO-8601 event creation time; required for every persisted event. */
+ created_at: string;
+ }
: never;
}[keyof AgentPassthroughEventSchemaMap];
@@ -27,5 +33,4 @@ export type RegisteredPassthroughEvent = {
*/
export type WithRegisteredPassthrough<T> = [RegisteredPassthroughEvent] extends [never]
? T
- : // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents -- false branch only when registry is non-empty; empty registry is `never`
- T | RegisteredPassthroughEvent;
+ : T | RegisteredPassthroughEvent;
diff --git a/packages/harness/src/core/events/schema.ts b/packages/harness/src/core/events/schema.ts
index 35ab7ad99..6a836fc85 100644
--- a/packages/harness/src/core/events/schema.ts
+++ b/packages/harness/src/core/events/schema.ts
@@ -1,6 +1,6 @@
// Harness wire-format event schemas (OpenAPI-decorated Zod).
import { z } from '@hono/zod-openapi';
-import { ulid } from 'ulid';
+import { monotonicFactory } from 'ulid';
import {
CompletionUsageSchema,
EnrichedAssistantMessageSchema,
@@ -11,8 +11,17 @@ import {
LLMUserMessageSchema,
} from '../llm/LLMTypes';
+/**
+ * Process-local monotonic ULIDs preserve event creation order, including
+ * multiple events created in the same millisecond. A turn has one sequential
+ * writer, so this is the durable event order key.
+ *
+ * @see https://github.com/ulid/spec#monotonicity
+ */
+const monotonicUlid = monotonicFactory();
+
export function newEventId(): string {
- return ulid().toLowerCase();
+ return monotonicUlid().toLowerCase();
}
/** Canonical string constants for harness wire-level and user-input event `type` fields. */
diff --git a/packages/harness/src/core/runtime/AgentThread.ts b/packages/harness/src/core/runtime/AgentThread.ts
index ab380d341..cf77f4e5f 100644
--- a/packages/harness/src/core/runtime/AgentThread.ts
+++ b/packages/harness/src/core/runtime/AgentThread.ts
@@ -734,24 +734,16 @@ export class AgentThread {
}
public toSnapshot(): AgentThreadSnapshot {
- const capability_state = Object.keys(this.capabilityState).length > 0 ? { ...this.capabilityState } : undefined;
- const base: AgentThreadSnapshot = {
+ const capability_state = Object.keys(this.capabilityState).length > 0 ? { ...this.capabilityState } : null;
+ return {
thread_id: this.threadId,
context: this.context,
current_context_usage: this.currentContextUsage,
- ...(capability_state && { capability_state }),
+ parent: this.parent ?? null,
+ agent_info: this.agentInfo ?? null,
+ completion: this.preComputedCompletion ?? null,
+ capability_state,
};
-
- if (this.parent && this.agentInfo) {
- return {
- ...base,
- parent: this.parent,
- agent_info: this.agentInfo,
- ...(this.preComputedCompletion && { completion: this.preComputedCompletion }),
- };
- }
-
- return base;
}
public getAgentThreadMetrics(): AgentThreadMetrics {
diff --git a/packages/harness/src/core/runtime/AgentThread.types.ts b/packages/harness/src/core/runtime/AgentThread.types.ts
index dd05418ce..1aaa84256 100644
--- a/packages/harness/src/core/runtime/AgentThread.types.ts
+++ b/packages/harness/src/core/runtime/AgentThread.types.ts
@@ -157,11 +157,11 @@ export interface AgentThreadSnapshot {
thread_id: string;
context: ContextMessage[];
current_context_usage: CompletionUsage;
- parent?: AgentParent | undefined;
- agent_info?: AgentInfo | undefined;
- completion?: SubAgentCompletionMarker | undefined;
+ parent: AgentParent | null;
+ agent_info: AgentInfo | null;
+ completion: SubAgentCompletionMarker | null;
/** Cross-turn capability KV. Keys: capability.state.key; `tfy.` reserved for builtins. */
- capability_state?: CapabilityState | undefined;
+ capability_state: CapabilityState | null;
}
export interface AgentThreadConstructorInput {
diff --git a/packages/harness/tests/agent-session/capabilityState.test.ts b/packages/harness/tests/agent-session/capabilityState.test.ts
index d24113fb4..1c173f16b 100644
--- a/packages/harness/tests/agent-session/capabilityState.test.ts
+++ b/packages/harness/tests/agent-session/capabilityState.test.ts
@@ -53,7 +53,7 @@ describe('capability_state (tfy.plan fixture)', () => {
const store = new InMemorySessionStore();
const sessions = new Sessions({ sessionStore: store });
const session = await sessions.create({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
agent_spec: makeAgentSpec(),
});
@@ -82,7 +82,7 @@ describe('capability_state (tfy.plan fixture)', () => {
// drain
}
const stored1 = await store.getTurn({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
turn_id: turn1.id,
});
@@ -112,7 +112,7 @@ describe('capability_state (tfy.plan fixture)', () => {
// drain
}
const stored2 = await store.getTurn({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
turn_id: turn2.id,
});
@@ -124,7 +124,7 @@ describe('capability_state (tfy.plan fixture)', () => {
const store = new InMemorySessionStore();
const sessions = new Sessions({ sessionStore: store });
const session = await sessions.create({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
agent_spec: makeAgentSpec(),
});
@@ -176,20 +176,66 @@ describe('capability_state (tfy.plan fixture)', () => {
// drain
}
const prior = await store.getTurn({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
turn_id: turn1.id,
});
expect(prior?.snapshot.threads[MAIN_THREAD_ID]?.capability_state?.['tfy.plan']).toEqual(planV1);
const latest = await store.getTurn({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
turn_id: turn3.id,
});
expect(latest?.snapshot.threads[MAIN_THREAD_ID]?.capability_state?.['tfy.plan']).toBeUndefined();
});
+ it('CAPABILITY_STATE with undefined state surfaces capability_state_error at persist boundary', async () => {
+ const undefinedStateCapability: AgentCapability = {
+ state: {
+ key: 'tfy.plan',
+ load: () => {
+ /* no-op */
+ },
+ },
+ preLLMProcessors: [
+ {
+ // eslint-disable-next-line @typescript-eslint/require-await -- async generator fixture, not awaiting I/O
+ async *processPreLLM(): AsyncGenerator<AgentContextProcessorOutput> {
+ yield {
+ type: InternalEventType.CAPABILITY_STATE,
+ key: 'tfy.plan',
+ // @ts-expect-error intentional runtime undefined past the JsonValue contract
+ state: undefined,
+ };
+ },
+ },
+ ],
+ };
+ const store = new InMemorySessionStore();
+ const sessions = new Sessions({ sessionStore: store });
+ const session = await sessions.create({
+ tenant_id: tenant,
+ session_id: 's1',
+ agent_spec: makeAgentSpec(),
+ });
+ const turn = await session.createTurn({
+ input: [{ type: EventType.USER_MESSAGE, content: 'x' }],
+ previous_turn_id: null,
+ signal: new AbortController().signal,
+ resolver: makeTestResolver({ extraCapabilities: [undefinedStateCapability] }),
+ });
+ let errorMessage: string | undefined;
+ for await (const event of turn.stream()) {
+ if (event.type === EventType.TURN_DONE && event.state.status === 'error') {
+ errorMessage = event.state.message;
+ }
+ }
+ expect(errorMessage).toContain('CAPABILITY_STATE');
+ expect(errorMessage).toContain('undefined');
+ expect(errorMessage).toContain('null');
+ });
+
it('emit with undeclared key surfaces capability_state_error (emit-key guard)', async () => {
const badCapability: AgentCapability = {
state: {
diff --git a/packages/harness/tests/agent-session/inMemorySessionStore.test.ts b/packages/harness/tests/agent-session/inMemorySessionStore.test.ts
deleted file mode 100644
index 1bc97a60f..000000000
--- a/packages/harness/tests/agent-session/inMemorySessionStore.test.ts
+++ /dev/null
@@ -1,696 +0,0 @@
-import { MAIN_THREAD_ID } from '../../src/agent-session/models/TurnRecord';
-import type { PersistedTurnEvent } from '../../src/agent-session/schemas/events';
-import { CancellationReason } from '../../src/agent-session/schemas/turn';
-import type { ISessionStore } from '../../src/agent-session/store/ISessionStore';
-import { InMemorySessionStore } from '../../src/agent-session/store/InMemorySessionStore';
-import { SessionStoreConflictError, SessionStoreNotFoundError } from '../../src/agent-session/store/SessionStoreErrors';
-import { EventType, newEventId } from '../../src/core/events/schema';
-import { getEmptyUsage } from '../../src/core/llm/LLMTypes';
-import { makeAgentSpec, makeModelMessageEvent, makeRunningTurnRecord, makeTurnCreatedEvent } from './testHelpers';
-
-function mustGet<T>(value: T | undefined | null, label = 'value'): T {
- if (value === undefined || value === null) {
- throw new Error(`Expected ${label} to be defined`);
- }
- return value;
-}
-
-/** Store contract suite — factory-injected so other backends can reuse it. */
-function runStoreContractSuite(createStore: () => ISessionStore) {
- const tenant = 't1';
- const sessionId = 's1';
-
- async function seedSession(store: ISessionStore, agentSpec = makeAgentSpec()) {
- await store.createSession({
- tenant_name: tenant,
- session_id: sessionId,
- agent_spec: agentSpec,
- });
- }
-
- describe('session CRUD + activity', () => {
- it('createSession hydrates agent_spec and sets last_activity_timestamp_ms', async () => {
- const store = createStore();
- const before = Date.now();
- await seedSession(store);
- const session = await store.getSession({ tenant_name: tenant, session_id: sessionId });
- expect(session).toBeDefined();
- expect(mustGet(session).tenant_name).toBe(tenant);
- expect(mustGet(session).agent_spec.model.name).toBe('test-model');
- expect(mustGet(session).last_activity_timestamp_ms).toBeGreaterThanOrEqual(before);
- expect(mustGet(session).title).toBeNull();
- });
-
- it('getSession does not bump last_activity_timestamp_ms', async () => {
- const store = createStore();
- await seedSession(store);
- const first = await store.getSession({ tenant_name: tenant, session_id: sessionId });
- await new Promise(r => setTimeout(r, 5));
- const second = await store.getSession({ tenant_name: tenant, session_id: sessionId });
- expect(mustGet(second).last_activity_timestamp_ms).toBe(mustGet(first).last_activity_timestamp_ms);
- });
-
- it('updateSession patches only provided fields and bumps activity', async () => {
- const store = createStore();
- await seedSession(store);
- const before = await store.getSession({ tenant_name: tenant, session_id: sessionId });
- await new Promise(r => setTimeout(r, 5));
- const nextSpec = makeAgentSpec({ instructions: 'updated' });
- await store.updateSession({
- tenant_name: tenant,
- session_id: sessionId,
- agent_spec: nextSpec,
- title: 'Hello',
- });
- const after = await store.getSession({ tenant_name: tenant, session_id: sessionId });
- expect(mustGet(after).agent_spec.instructions).toBe('updated');
- expect(mustGet(after).title).toBe('Hello');
- expect(mustGet(after).last_activity_timestamp_ms).toBeGreaterThan(mustGet(before).last_activity_timestamp_ms);
- });
-
- it('createSession conflict when session already exists', async () => {
- const store = createStore();
- await seedSession(store);
- await expect(seedSession(store)).rejects.toBeInstanceOf(SessionStoreConflictError);
- });
- });
-
- describe('listSessions', () => {
- async function seedThreeSessions(store: ISessionStore) {
- for (const id of ['sa', 'sb', 'sc']) {
- await store.createSession({ tenant_name: tenant, session_id: id, agent_spec: makeAgentSpec() });
- await new Promise(r => setTimeout(r, 2));
- }
- }
-
- it('lists newest-first by default, asc on request, scoped to tenant', async () => {
- const store = createStore();
- await seedThreeSessions(store);
- await store.createSession({ tenant_name: 'other', session_id: 'sx', agent_spec: makeAgentSpec() });
-
- const desc = await store.listSessions({ tenant_name: tenant, limit: 10 });
- expect(desc.data.map(s => s.session_id)).toEqual(['sc', 'sb', 'sa']);
-
- const asc = await store.listSessions({ tenant_name: tenant, limit: 10, order: 'asc' });
- expect(asc.data.map(s => s.session_id)).toEqual(['sa', 'sb', 'sc']);
- });
-
- it('paginates with next/previous tokens and filters by created_at bounds', async () => {
- const store = createStore();
- await seedThreeSessions(store);
-
- const first = await store.listSessions({ tenant_name: tenant, limit: 2 });
- expect(first.data).toHaveLength(2);
- expect(first.pagination.next_page_token).toBeDefined();
- const second = await store.listSessions({
- tenant_name: tenant,
- limit: 2,
- page_token: first.pagination.next_page_token,
- });
- expect(second.data.map(s => s.session_id)).toEqual(['sa']);
- expect(second.pagination.next_page_token).toBeUndefined();
-
- const all = await store.listSessions({ tenant_name: tenant, limit: 10, order: 'asc' });
- const middleSession = all.data[1];
- if (!middleSession) throw new Error('expected middle session in list');
- const middleCreatedAt = middleSession.created_at;
- const bounded = await store.listSessions({
- tenant_name: tenant,
- limit: 10,
- order: 'asc',
- start_timestamp: middleCreatedAt,
- end_timestamp: middleCreatedAt,
- });
- expect(bounded.data.map(s => s.session_id)).toEqual(['sb']);
- });
- });
-
- describe('createTurn', () => {
- it('atomically links last_turn_id and bumps activity', async () => {
- const store = createStore();
- await seedSession(store);
- const before = await store.getSession({ tenant_name: tenant, session_id: sessionId });
- await new Promise(r => setTimeout(r, 5));
- const turn = makeRunningTurnRecord({ sessionId, turnId: 'turn-1' });
- await store.createTurn({ tenant_name: tenant, turn });
- const after = await store.getSession({ tenant_name: tenant, session_id: sessionId });
- expect(mustGet(after).last_turn_id).toBe('turn-1');
- expect(mustGet(after).last_activity_timestamp_ms).toBeGreaterThan(mustGet(before).last_activity_timestamp_ms);
- });
-
- it('update_session_title_if_not_exist sets once and never overwrites', async () => {
- const store = createStore();
- await seedSession(store);
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-1' }),
- update_session_title_if_not_exist: 'First title',
- });
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({
- sessionId,
- turnId: 'turn-2',
- previousTurnId: 'turn-1',
- firstTurnId: 'turn-1',
- }),
- update_session_title_if_not_exist: 'Second title',
- });
- const session = await store.getSession({ tenant_name: tenant, session_id: sessionId });
- expect(mustGet(session).title).toBe('First title');
- });
-
- it('rejects unknown previous_turn_id with not-found', async () => {
- const store = createStore();
- await seedSession(store);
- await expect(
- store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({
- sessionId,
- turnId: 'turn-2',
- previousTurnId: 'missing',
- }),
- }),
- ).rejects.toBeInstanceOf(SessionStoreNotFoundError);
- });
-
- it('fork from any existing turn succeeds and advances tip', async () => {
- const store = createStore();
- await seedSession(store);
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-1' }),
- });
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({
- sessionId,
- turnId: 'turn-2',
- previousTurnId: 'turn-1',
- firstTurnId: 'turn-1',
- }),
- });
- // Fork from turn-1 (not the tip).
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({
- sessionId,
- turnId: 'turn-fork',
- previousTurnId: 'turn-1',
- firstTurnId: 'turn-1',
- }),
- });
- const session = await store.getSession({ tenant_name: tenant, session_id: sessionId });
- expect(mustGet(session).last_turn_id).toBe('turn-fork');
- });
-
- it('new root turn (no previous_turn_id) succeeds on non-empty session', async () => {
- const store = createStore();
- await seedSession(store);
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-1' }),
- });
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-root-2' }),
- });
- const session = await store.getSession({ tenant_name: tenant, session_id: sessionId });
- expect(mustGet(session).last_turn_id).toBe('turn-root-2');
- });
-
- it('concurrent createTurn forking the same tip: both succeed', async () => {
- const store = createStore();
- await seedSession(store);
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({ sessionId, turnId: 'tip' }),
- });
- const a = makeRunningTurnRecord({
- sessionId,
- turnId: 'turn-a',
- previousTurnId: 'tip',
- firstTurnId: 'tip',
- });
- const b = makeRunningTurnRecord({
- sessionId,
- turnId: 'turn-b',
- previousTurnId: 'tip',
- firstTurnId: 'tip',
- });
- const results = await Promise.allSettled([
- store.createTurn({ tenant_name: tenant, turn: a }),
- store.createTurn({ tenant_name: tenant, turn: b }),
- ]);
- expect(results.every(r => r.status === 'fulfilled')).toBe(true);
- const session = await store.getSession({ tenant_name: tenant, session_id: sessionId });
- expect(['turn-a', 'turn-b']).toContain(mustGet(session).last_turn_id);
- const turns = await store.listTurns({
- tenant_name: tenant,
- session_id: sessionId,
- limit: 10,
- });
- expect(turns.data.map(t => t.turn_id).sort()).toEqual(['tip', 'turn-a', 'turn-b']);
- });
- });
-
- describe('updateTurnState', () => {
- it('allows running → done and rejects second terminal (first-terminal-wins)', async () => {
- const store = createStore();
- await seedSession(store);
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-1' }),
- });
- await store.updateTurnState({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: 'turn-1',
- state: {
- status: 'done',
- output: null,
- required_actions: [],
- completed_at: new Date().toISOString(),
- },
- });
- await expect(
- store.updateTurnState({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: 'turn-1',
- state: {
- status: 'cancelled',
- reason: CancellationReason.ClientCancelled,
- completed_at: new Date().toISOString(),
- },
- }),
- ).rejects.toBeInstanceOf(SessionStoreConflictError);
- });
-
- it('missing turn → not found', async () => {
- const store = createStore();
- await seedSession(store);
- await expect(
- store.updateTurnState({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: 'missing',
- state: {
- status: 'done',
- output: null,
- required_actions: [],
- completed_at: new Date().toISOString(),
- },
- }),
- ).rejects.toBeInstanceOf(SessionStoreNotFoundError);
- });
- });
-
- describe('events + threads + capability_state', () => {
- it('appendToEvents preserves order including lifecycle rows', async () => {
- const store = createStore();
- await seedSession(store);
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-1' }),
- });
- const created = makeTurnCreatedEvent('turn-1');
- const model = makeModelMessageEvent();
- await store.appendToEvents({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: 'turn-1',
- events: [created, model],
- });
- const { data } = await store.listTurnEvents({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: 'turn-1',
- limit: 10,
- });
- expect(data.map(e => e.type)).toEqual(['turn.created', EventType.MODEL_MESSAGE]);
- });
-
- it('add/remove threads and append/overwrite context', async () => {
- const store = createStore();
- await seedSession(store);
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-1' }),
- });
- await store.addThreads({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: 'turn-1',
- threads: [
- {
- thread_id: 'child',
- context: [],
- current_context_usage: getEmptyUsage(),
- parent: { thread_id: MAIN_THREAD_ID, tool_call_id: 'tc1' },
- agent_info: { type: 'dynamic', name: 'child', input: 'do work' },
- },
- ],
- });
- await store.appendToThreadContext({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: 'turn-1',
- thread_id: 'child',
- context: [{ role: 'user', content: 'hello' }],
- });
- let turn = await store.getTurn({ tenant_name: tenant, session_id: sessionId, turn_id: 'turn-1' });
- expect(turn?.snapshot.threads['child']?.context).toHaveLength(1);
-
- await store.overwriteThreadContext({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: 'turn-1',
- event: {
- type: EventType.AGENT_CONTEXT_OVERWRITE,
- id: newEventId(),
- created_at: new Date().toISOString(),
- thread_id: 'child',
- reason: 'compaction',
- context: [{ role: 'user', content: 'replaced' }],
- current_context_usage: getEmptyUsage(),
- compaction_llm_usage: getEmptyUsage(),
- },
- });
- turn = await store.getTurn({ tenant_name: tenant, session_id: sessionId, turn_id: 'turn-1' });
- expect(turn?.snapshot.threads['child']?.context).toEqual([{ role: 'user', content: 'replaced' }]);
-
- await store.removeThreads({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: 'turn-1',
- thread_ids: ['child'],
- });
- turn = await store.getTurn({ tenant_name: tenant, session_id: sessionId, turn_id: 'turn-1' });
- expect(turn?.snapshot.threads['child']).toBeUndefined();
- });
-
- it('patchThreadCapabilityState is LWW per key', async () => {
- const store = createStore();
- await seedSession(store);
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-1' }),
- });
- await store.patchThreadCapabilityState({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: 'turn-1',
- thread_id: MAIN_THREAD_ID,
- key: 'tfy.plan',
- state: { v: 1 },
- });
- await store.patchThreadCapabilityState({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: 'turn-1',
- thread_id: MAIN_THREAD_ID,
- key: 'tfy.plan',
- state: { v: 2 },
- });
- const turn = await store.getTurn({ tenant_name: tenant, session_id: sessionId, turn_id: 'turn-1' });
- expect(turn?.snapshot.threads[MAIN_THREAD_ID]?.capability_state).toEqual({ 'tfy.plan': { v: 2 } });
- });
-
- it('patchMCPServers and patchSandboxInfo', async () => {
- const store = createStore();
- await seedSession(store);
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-1' }),
- });
- await store.patchMCPServers({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: 'turn-1',
- mcp_servers: [{ id: 'svc', name: 'svc', session_id: 'mcp-1', transport_type: 'streamable-http' }],
- });
- await store.patchSandboxInfo({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: 'turn-1',
- sandbox_info: { sandbox_id: 'sbx-1' },
- });
- const turn = await store.getTurn({ tenant_name: tenant, session_id: sessionId, turn_id: 'turn-1' });
- expect(turn?.snapshot.mcp_servers?.['svc']?.session_id).toBe('mcp-1');
- expect(mustGet(turn).snapshot.sandbox_info?.sandbox_id).toBe('sbx-1');
- });
- });
-
- describe('pagination', () => {
- it('listTurns paginates with opaque tokens', async () => {
- const store = createStore();
- await seedSession(store);
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({ sessionId, turnId: 't1' }),
- });
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({
- sessionId,
- turnId: 't2',
- previousTurnId: 't1',
- firstTurnId: 't1',
- }),
- });
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({
- sessionId,
- turnId: 't3',
- previousTurnId: 't2',
- firstTurnId: 't1',
- }),
- });
- const page1 = await store.listTurns({
- tenant_name: tenant,
- session_id: sessionId,
- limit: 2,
- });
- expect(page1.data.map(t => t.turn_id)).toEqual(['t1', 't2']);
- expect(page1.pagination.next_page_token).toBeDefined();
- const page2 = await store.listTurns({
- tenant_name: tenant,
- session_id: sessionId,
- limit: 2,
- page_token: page1.pagination.next_page_token,
- });
- expect(page2.data.map(t => t.turn_id)).toEqual(['t3']);
- });
-
- it('listTurnEvents supports desc order', async () => {
- const store = createStore();
- await seedSession(store);
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-1' }),
- });
- await store.appendToEvents({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: 'turn-1',
- events: [makeTurnCreatedEvent('turn-1'), makeModelMessageEvent()],
- });
- const { data } = await store.listTurnEvents({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: 'turn-1',
- limit: 10,
- order: 'desc',
- });
- expect(data[0]?.type).toBe(EventType.MODEL_MESSAGE);
- });
-
- it('listSessionEvents includes running turns and is newest-first', async () => {
- const store = createStore();
- await seedSession(store);
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({ sessionId, turnId: 't1' }),
- });
- await store.appendToEvents({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: 't1',
- events: [makeTurnCreatedEvent('t1')],
- });
- await store.updateTurnState({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: 't1',
- state: {
- status: 'done',
- output: null,
- required_actions: [],
- completed_at: new Date().toISOString(),
- },
- });
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({
- sessionId,
- turnId: 't2',
- previousTurnId: 't1',
- firstTurnId: 't1',
- }),
- });
- await store.appendToEvents({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: 't2',
- events: [makeTurnCreatedEvent('t2')],
- });
- // t2 still running — must appear in the feed.
- const { data } = await store.listSessionEvents({
- tenant_name: tenant,
- session_id: sessionId,
- limit: 10,
- });
- expect(data.map(row => row.turn_id)).toEqual(['t2', 't1']);
- expect(data.every(row => row.event.type === 'turn.created')).toBe(true);
- });
-
- it('listSessionEvents includes registered passthrough events', async () => {
- const store = createStore();
- await seedSession(store);
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({ sessionId, turnId: 't1' }),
- });
- const passthrough = {
- type: 'custom.event',
- event: { value: 1 },
- } as unknown as PersistedTurnEvent;
- await store.appendToEvents({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: 't1',
- events: [passthrough],
- });
-
- const { data } = await store.listSessionEvents({
- tenant_name: tenant,
- session_id: sessionId,
- limit: 10,
- });
- expect(data).toEqual([{ turn_id: 't1', event: passthrough }]);
- });
-
- it('listSessionEvents with last_turn_id scopes to that branch, excluding fork siblings', async () => {
- const store = createStore();
- await seedSession(store);
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({ sessionId, turnId: 't1' }),
- });
- // Two forks off t1; the sibling is created BEFORE the anchor, so a
- // creation-order prefix would wrongly include it.
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({ sessionId, turnId: 't2-sibling', previousTurnId: 't1', firstTurnId: 't1' }),
- });
- await store.createTurn({
- tenant_name: tenant,
- turn: makeRunningTurnRecord({ sessionId, turnId: 't2-anchor', previousTurnId: 't1', firstTurnId: 't1' }),
- });
- for (const turnId of ['t1', 't2-sibling', 't2-anchor']) {
- await store.appendToEvents({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: turnId,
- events: [makeTurnCreatedEvent(turnId)],
- });
- }
- const { data } = await store.listSessionEvents({
- tenant_name: tenant,
- session_id: sessionId,
- limit: 10,
- last_turn_id: 't2-anchor',
- });
- expect(data.map(row => row.turn_id)).toEqual(['t2-anchor', 't1']);
-
- await expect(
- store.listSessionEvents({
- tenant_name: tenant,
- session_id: sessionId,
- limit: 10,
- last_turn_id: 'missing',
- }),
- ).rejects.toBeInstanceOf(SessionStoreNotFoundError);
- });
-
- it('listSessionEvents spills through truncated ancestor_ids windows to reach the chain root', async () => {
- const store = createStore();
- await seedSession(store);
- // Writer-chosen window shorter than the chain — store must spill.
- const ancestorWindow = 3;
- const chainLength = ancestorWindow + 5;
- const ids = Array.from({ length: chainLength }, (_, i) => `t${String(i + 1)}`);
- for (let i = 0; i < ids.length; i++) {
- const turnId = mustGet(ids[i], `ids[${String(i)}]`);
- const window = ids.slice(Math.max(0, i - ancestorWindow), i);
- await store.createTurn({
- tenant_name: tenant,
- turn: {
- ...makeRunningTurnRecord({
- sessionId,
- turnId,
- ...(i > 0
- ? {
- previousTurnId: mustGet(ids[i - 1], `ids[${String(i - 1)}]`),
- firstTurnId: mustGet(ids[0], 'ids[0]'),
- }
- : {}),
- }),
- ancestor_ids: window,
- },
- });
- await store.appendToEvents({
- tenant_name: tenant,
- session_id: sessionId,
- turn_id: turnId,
- events: [makeTurnCreatedEvent(turnId)],
- });
- }
- const tip = mustGet(ids.at(-1), 'chain tip');
- const { data } = await store.listSessionEvents({
- tenant_name: tenant,
- session_id: sessionId,
- limit: chainLength + 10,
- last_turn_id: tip,
- });
- // Full chain reachable despite truncated windows, newest first.
- expect(data.map(row => row.turn_id)).toEqual([...ids].reverse());
- });
- });
-
- describe('deep-copy boundary', () => {
- it('mutating a returned session does not mutate the store', async () => {
- const store = createStore();
- await seedSession(store);
- const session = await store.getSession({ tenant_name: tenant, session_id: sessionId });
- mustGet(session).agent_spec.instructions = 'mutated';
- const again = await store.getSession({ tenant_name: tenant, session_id: sessionId });
- expect(mustGet(again).agent_spec.instructions).toBe('You are a test agent.');
- });
- });
-
- describe('no SSE surface', () => {
- it('ISessionStore has no subscribe* members', () => {
- const store = createStore();
- const keys = Object.getOwnPropertyNames(Object.getPrototypeOf(store)).concat(Object.keys(store));
- expect(keys.some(k => k.startsWith('subscribe'))).toBe(false);
- });
- });
-}
-
-describe('InMemorySessionStore (ISessionStore contract)', () => {
- runStoreContractSuite(() => new InMemorySessionStore());
-});
diff --git a/packages/harness/tests/agent-session/agentSpecSkills.test.ts b/packages/harness/tests/agent-session/schemas/agentSpecSkills.test.ts
similarity index 96%
rename from packages/harness/tests/agent-session/agentSpecSkills.test.ts
rename to packages/harness/tests/agent-session/schemas/agentSpecSkills.test.ts
index f81fb5f0c..d7be85a45 100644
--- a/packages/harness/tests/agent-session/agentSpecSkills.test.ts
+++ b/packages/harness/tests/agent-session/schemas/agentSpecSkills.test.ts
@@ -1,4 +1,4 @@
-import { AgentSpecSchema } from '../../src/agent-session/schemas/agentSpec';
+import { AgentSpecSchema } from '../../../src/agent-session/schemas/agentSpec';
const base = {
model: { name: 'test-model' },
diff --git a/packages/harness/tests/agent-session/sessions.test.ts b/packages/harness/tests/agent-session/sessions.test.ts
index f5716806a..d5c23ce54 100644
--- a/packages/harness/tests/agent-session/sessions.test.ts
+++ b/packages/harness/tests/agent-session/sessions.test.ts
@@ -10,7 +10,7 @@ describe('Sessions / SessionHandle / TurnHandle (storage + createTurn)', () => {
const store = new InMemorySessionStore<{ tag: string }>();
const sessions = new Sessions<{ tag: string }>({ sessionStore: store });
const created = await sessions.create({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
agent_spec: makeAgentSpec({ instructions: 'hydrate-me' }),
custom: { tag: 'a' },
@@ -18,7 +18,7 @@ describe('Sessions / SessionHandle / TurnHandle (storage + createTurn)', () => {
expect(created.agent_spec.instructions).toBe('hydrate-me');
expect(created.custom).toEqual({ tag: 'a' });
- const loaded = await sessions.get({ tenant_name: tenant, session_id: 's1' });
+ const loaded = await sessions.get({ tenant_id: tenant, session_id: 's1' });
expect(loaded?.agent_spec.instructions).toBe('hydrate-me');
expect(loaded?.session_id).toBe('s1');
});
@@ -27,7 +27,7 @@ describe('Sessions / SessionHandle / TurnHandle (storage + createTurn)', () => {
const store = new InMemorySessionStore();
const sessions = new Sessions({ sessionStore: store });
const session = await sessions.create({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
agent_spec: makeAgentSpec(),
});
@@ -42,12 +42,12 @@ describe('Sessions / SessionHandle / TurnHandle (storage + createTurn)', () => {
expect(turn.input).toHaveLength(1);
const stored = await store.getTurn({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
turn_id: turn.id,
});
expect(stored?.state.status).toBe('running');
- const sessionRecord = await store.getSession({ tenant_name: tenant, session_id: 's1' });
+ const sessionRecord = await store.getSession({ tenant_id: tenant, session_id: 's1' });
expect(sessionRecord?.title).toBe('From first message');
expect(sessionRecord?.last_turn_id).toBe(turn.id);
});
@@ -56,7 +56,7 @@ describe('Sessions / SessionHandle / TurnHandle (storage + createTurn)', () => {
const store = new InMemorySessionStore<{ tag: string }, { n: number }>();
const sessions = new Sessions({ sessionStore: store });
const session = await sessions.create({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
agent_spec: makeAgentSpec(),
});
@@ -83,7 +83,7 @@ describe('Sessions / SessionHandle / TurnHandle (storage + createTurn)', () => {
const store = new InMemorySessionStore();
const sessions = new Sessions({ sessionStore: store });
const session = await sessions.create({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
agent_spec: makeAgentSpec(),
});
@@ -103,8 +103,8 @@ describe('Sessions / SessionHandle / TurnHandle (storage + createTurn)', () => {
signal: new AbortController().signal,
resolver: makeTestResolver(),
});
- expect(root2.previous_turn_id).toBeUndefined();
- const sessionRecord = await store.getSession({ tenant_name: tenant, session_id: 's1' });
+ expect(root2.previous_turn_id).toBeNull();
+ const sessionRecord = await store.getSession({ tenant_id: tenant, session_id: 's1' });
expect(sessionRecord?.last_turn_id).toBe(root2.id);
});
@@ -112,7 +112,7 @@ describe('Sessions / SessionHandle / TurnHandle (storage + createTurn)', () => {
const store = new InMemorySessionStore();
const sessions = new Sessions({ sessionStore: store });
const session = await sessions.create({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
agent_spec: makeAgentSpec(),
});
@@ -134,20 +134,21 @@ describe('Sessions / SessionHandle / TurnHandle (storage + createTurn)', () => {
}),
).rejects.toThrow();
const turns = await store.listTurns({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
limit: 10,
+ page_token: undefined,
});
expect(turns.data).toHaveLength(0);
- const sessionRecord = await store.getSession({ tenant_name: tenant, session_id: 's1' });
- expect(sessionRecord?.last_turn_id).toBeUndefined();
+ const sessionRecord = await store.getSession({ tenant_id: tenant, session_id: 's1' });
+ expect(sessionRecord?.last_turn_id).toBeNull();
});
it('run() failure closes the resolver; success defers close() to stream()', async () => {
const store = new InMemorySessionStore();
const sessions = new Sessions({ sessionStore: store });
const session = await sessions.create({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
agent_spec: makeAgentSpec(),
});
diff --git a/packages/harness/tests/agent-session/store/inMemorySessionStore.test.ts b/packages/harness/tests/agent-session/store/inMemorySessionStore.test.ts
new file mode 100644
index 000000000..862e530bd
--- /dev/null
+++ b/packages/harness/tests/agent-session/store/inMemorySessionStore.test.ts
@@ -0,0 +1,6 @@
+import { InMemorySessionStore } from '../../../src/agent-session/store/InMemorySessionStore';
+import { runStoreContractSuite } from './storeContractSuite';
+
+describe('InMemorySessionStore (ISessionStore contract)', () => {
+ runStoreContractSuite(() => new InMemorySessionStore());
+});
diff --git a/packages/harness/tests/agent-session/store/storeContractSuite.ts b/packages/harness/tests/agent-session/store/storeContractSuite.ts
new file mode 100644
index 000000000..7eed065f6
--- /dev/null
+++ b/packages/harness/tests/agent-session/store/storeContractSuite.ts
@@ -0,0 +1,1389 @@
+import { z } from 'zod';
+import { MAIN_THREAD_ID } from '../../../src/agent-session/models/TurnRecord';
+import type { PersistedTurnEvent } from '../../../src/agent-session/schemas/events';
+import { EventType } from '../../../src/agent-session/schemas/events';
+import { CancellationReason } from '../../../src/agent-session/schemas/turn';
+import type { ISessionStore } from '../../../src/agent-session/store/ISessionStore';
+import { decodeSessionEventPageToken } from '../../../src/agent-session/store/SessionEventPageToken';
+import {
+ PreviousTurnRunningError,
+ SessionStoreConflictError,
+ SessionStoreNotFoundError,
+ TurnAlreadyExistsError,
+ TurnNotRunningError,
+} from '../../../src/agent-session/store/SessionStoreErrors';
+import { newEventId } from '../../../src/core/events/schema';
+import { getEmptyUsage } from '../../../src/core/llm/LLMTypes';
+import type { ContextMessage } from '../../../src/core/runtime/AgentThread.types';
+import {
+ makeAgentSpec,
+ makeCancelledTurnState,
+ makeCreateTurnInput,
+ makeDoneTurnState,
+ makeModelMessageEvent,
+ makeTurnCreatedEvent,
+ makeTurnDoneEvent,
+} from '../testHelpers';
+
+const ContractPassthroughEventSchema = z.object({
+ id: z.string(),
+ created_at: z.string(),
+ event: z.object({ value: z.number() }),
+});
+
+declare module '../../../src/core/events/PassthroughEvents' {
+ interface AgentPassthroughEventSchemaMap {
+ 'custom.event': typeof ContractPassthroughEventSchema;
+ }
+}
+
+function mustGet<T>(value: T | undefined | null, label = 'value'): T {
+ if (value === undefined || value === null) {
+ throw new Error(`Expected ${label} to be defined`);
+ }
+ return value;
+}
+
+function userMessage(content: string): ContextMessage {
+ return { role: 'user', content };
+}
+
+function contextContents(messages: ContextMessage[] | undefined): string[] {
+ return (messages ?? []).map(message => {
+ if ('role' in message && message.role === 'user' && typeof message.content === 'string') {
+ return message.content;
+ }
+ return JSON.stringify(message);
+ });
+}
+
+/** Store contract suite — factory-injected so other backends can reuse it. */
+export function runStoreContractSuite(createStore: () => ISessionStore) {
+ const tenant = 't1';
+ const sessionId = 's1';
+
+ async function finishTurn(store: ISessionStore, turnId: string) {
+ const state = makeDoneTurnState();
+ await store.updateTurnState({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: turnId,
+ state,
+ turn_done_event: makeTurnDoneEvent(state),
+ });
+ }
+
+ async function seedSession(store: ISessionStore, agentSpec = makeAgentSpec()) {
+ await store.createSession({
+ tenant_id: tenant,
+ session_id: sessionId,
+ agent_spec: agentSpec,
+ custom: null,
+ });
+ }
+
+ describe('session CRUD + activity', () => {
+ it('createSession hydrates agent_spec and sets last_activity_timestamp_ms', async () => {
+ const store = createStore();
+ const before = Date.now();
+ await seedSession(store);
+ const session = await store.getSession({ tenant_id: tenant, session_id: sessionId });
+ expect(session).toBeDefined();
+ expect(mustGet(session).tenant_id).toBe(tenant);
+ expect(mustGet(session).agent_spec.model.name).toBe('test-model');
+ expect(mustGet(session).last_activity_timestamp_ms).toBeGreaterThanOrEqual(before);
+ expect(mustGet(session).title).toBeNull();
+ });
+
+ it('getSession does not bump last_activity_timestamp_ms', async () => {
+ const store = createStore();
+ await seedSession(store);
+ const first = await store.getSession({ tenant_id: tenant, session_id: sessionId });
+ await new Promise(r => setTimeout(r, 5));
+ const second = await store.getSession({ tenant_id: tenant, session_id: sessionId });
+ expect(mustGet(second).last_activity_timestamp_ms).toBe(mustGet(first).last_activity_timestamp_ms);
+ });
+
+ it('updateSession patches only provided fields and bumps activity', async () => {
+ const store = createStore();
+ await seedSession(store);
+ const before = await store.getSession({ tenant_id: tenant, session_id: sessionId });
+ await new Promise(r => setTimeout(r, 5));
+ const nextSpec = makeAgentSpec({ instructions: 'updated' });
+ await store.updateSession({
+ tenant_id: tenant,
+ session_id: sessionId,
+ agent_spec: nextSpec,
+ title: 'Hello',
+ });
+ const after = await store.getSession({ tenant_id: tenant, session_id: sessionId });
+ expect(mustGet(after).agent_spec.instructions).toBe('updated');
+ expect(mustGet(after).title).toBe('Hello');
+ expect(mustGet(after).last_activity_timestamp_ms).toBeGreaterThan(mustGet(before).last_activity_timestamp_ms);
+ });
+
+ it('createSession conflict when session already exists', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await expect(seedSession(store)).rejects.toBeInstanceOf(SessionStoreConflictError);
+ });
+ });
+
+ describe('listSessions', () => {
+ async function seedThreeSessions(store: ISessionStore) {
+ for (const id of ['sa', 'sb', 'sc']) {
+ await store.createSession({ tenant_id: tenant, session_id: id, agent_spec: makeAgentSpec(), custom: null });
+ await new Promise(r => setTimeout(r, 2));
+ }
+ }
+
+ it('lists newest-first by default, asc on request, scoped to tenant', async () => {
+ const store = createStore();
+ await seedThreeSessions(store);
+ await store.createSession({ tenant_id: 'other', session_id: 'sx', agent_spec: makeAgentSpec(), custom: null });
+
+ const desc = await store.listSessions({
+ tenant_id: tenant,
+ limit: 10,
+ page_token: undefined,
+ order: undefined,
+ start_timestamp: undefined,
+ end_timestamp: undefined,
+ });
+ expect(desc.data.map(s => s.session_id)).toEqual(['sc', 'sb', 'sa']);
+
+ const asc = await store.listSessions({
+ tenant_id: tenant,
+ limit: 10,
+ page_token: undefined,
+ order: 'asc',
+ start_timestamp: undefined,
+ end_timestamp: undefined,
+ });
+ expect(asc.data.map(s => s.session_id)).toEqual(['sa', 'sb', 'sc']);
+ });
+
+ it('paginates with next/previous tokens and filters by created_at bounds', async () => {
+ const store = createStore();
+ await seedThreeSessions(store);
+
+ const first = await store.listSessions({
+ tenant_id: tenant,
+ limit: 2,
+ page_token: undefined,
+ order: undefined,
+ start_timestamp: undefined,
+ end_timestamp: undefined,
+ });
+ expect(first.data).toHaveLength(2);
+ expect(first.pagination.next_page_token).toBeDefined();
+ const second = await store.listSessions({
+ tenant_id: tenant,
+ limit: 2,
+ page_token: first.pagination.next_page_token,
+ order: undefined,
+ start_timestamp: undefined,
+ end_timestamp: undefined,
+ });
+ expect(second.data.map(s => s.session_id)).toEqual(['sa']);
+ expect(second.pagination.next_page_token).toBeUndefined();
+
+ const all = await store.listSessions({
+ tenant_id: tenant,
+ limit: 10,
+ page_token: undefined,
+ order: 'asc',
+ start_timestamp: undefined,
+ end_timestamp: undefined,
+ });
+ const middleSession = all.data[1];
+ if (!middleSession) throw new Error('expected middle session in list');
+ const middleCreatedAt = middleSession.created_at;
+ const bounded = await store.listSessions({
+ tenant_id: tenant,
+ limit: 10,
+ order: 'asc',
+ page_token: undefined,
+ start_timestamp: middleCreatedAt,
+ end_timestamp: middleCreatedAt,
+ });
+ expect(bounded.data.map(s => s.session_id)).toEqual(['sb']);
+ });
+ });
+
+ describe('createTurn', () => {
+ it('atomically links last_turn_id and bumps activity', async () => {
+ const store = createStore();
+ await seedSession(store);
+ const before = await store.getSession({ tenant_id: tenant, session_id: sessionId });
+ await new Promise(r => setTimeout(r, 5));
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 'turn-1' }));
+ const after = await store.getSession({ tenant_id: tenant, session_id: sessionId });
+ expect(mustGet(after).last_turn_id).toBe('turn-1');
+ expect(mustGet(after).last_activity_timestamp_ms).toBeGreaterThan(mustGet(before).last_activity_timestamp_ms);
+ });
+
+ it('update_session_title_if_not_exist sets once and never overwrites', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(
+ makeCreateTurnInput({ sessionId, turnId: 'turn-1', update_session_title_if_not_exist: 'First title' }),
+ );
+ await finishTurn(store, 'turn-1');
+ await store.createTurn(
+ makeCreateTurnInput({
+ sessionId,
+ turnId: 'turn-2',
+ previousTurnId: 'turn-1',
+ firstTurnId: 'turn-1',
+ update_session_title_if_not_exist: 'Second title',
+ }),
+ );
+ const session = await store.getSession({ tenant_id: tenant, session_id: sessionId });
+ expect(mustGet(session).title).toBe('First title');
+ });
+
+ it('fork from any existing turn succeeds and advances tip', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 'turn-1' }));
+ await finishTurn(store, 'turn-1');
+ await store.createTurn(
+ makeCreateTurnInput({ sessionId, turnId: 'turn-2', previousTurnId: 'turn-1', firstTurnId: 'turn-1' }),
+ );
+ // Fork from turn-1 (not the tip).
+ await store.createTurn(
+ makeCreateTurnInput({ sessionId, turnId: 'turn-fork', previousTurnId: 'turn-1', firstTurnId: 'turn-1' }),
+ );
+ const session = await store.getSession({ tenant_id: tenant, session_id: sessionId });
+ expect(mustGet(session).last_turn_id).toBe('turn-fork');
+ });
+
+ it('new root turn (no previous_turn_id) succeeds on non-empty session', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 'turn-1' }));
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 'turn-root-2' }));
+ const session = await store.getSession({ tenant_id: tenant, session_id: sessionId });
+ expect(mustGet(session).last_turn_id).toBe('turn-root-2');
+ });
+
+ it('concurrent createTurn forking the same tip: both succeed with isolated context', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(
+ makeCreateTurnInput({
+ sessionId,
+ turnId: 'tip',
+ new_context_appends: [
+ {
+ thread_id: MAIN_THREAD_ID,
+ context: [userMessage('shared')],
+ current_context_usage: getEmptyUsage(),
+ },
+ ],
+ }),
+ );
+ await finishTurn(store, 'tip');
+ const results = await Promise.allSettled([
+ store.createTurn(
+ makeCreateTurnInput({
+ sessionId,
+ turnId: 'turn-a',
+ previousTurnId: 'tip',
+ firstTurnId: 'tip',
+ new_context_appends: [
+ {
+ thread_id: MAIN_THREAD_ID,
+ context: [userMessage('a-only')],
+ current_context_usage: getEmptyUsage(),
+ },
+ ],
+ }),
+ ),
+ store.createTurn(
+ makeCreateTurnInput({
+ sessionId,
+ turnId: 'turn-b',
+ previousTurnId: 'tip',
+ firstTurnId: 'tip',
+ new_context_appends: [
+ {
+ thread_id: MAIN_THREAD_ID,
+ context: [userMessage('b-only')],
+ current_context_usage: getEmptyUsage(),
+ },
+ ],
+ }),
+ ),
+ ]);
+ expect(results.every(r => r.status === 'fulfilled')).toBe(true);
+ const session = await store.getSession({ tenant_id: tenant, session_id: sessionId });
+ expect(['turn-a', 'turn-b']).toContain(mustGet(session).last_turn_id);
+ const turns = await store.listTurns({
+ tenant_id: tenant,
+ session_id: sessionId,
+ limit: 10,
+ page_token: undefined,
+ });
+ expect(turns.data.map(t => t.turn_id).sort()).toEqual(['tip', 'turn-a', 'turn-b']);
+
+ const turnA = await store.getTurn({ tenant_id: tenant, session_id: sessionId, turn_id: 'turn-a' });
+ const turnB = await store.getTurn({ tenant_id: tenant, session_id: sessionId, turn_id: 'turn-b' });
+ expect(contextContents(turnA?.snapshot.threads[MAIN_THREAD_ID]?.context)).toEqual(['shared', 'a-only']);
+ expect(contextContents(turnB?.snapshot.threads[MAIN_THREAD_ID]?.context)).toEqual(['shared', 'b-only']);
+ });
+
+ it('rejects createTurn when previous turn is still running', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 'turn-1' }));
+ await expect(
+ store.createTurn(
+ makeCreateTurnInput({ sessionId, turnId: 'turn-2', previousTurnId: 'turn-1', firstTurnId: 'turn-1' }),
+ ),
+ ).rejects.toBeInstanceOf(PreviousTurnRunningError);
+ });
+
+ it('rejects duplicate turn_id with conflict', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 'turn-1' }));
+ await finishTurn(store, 'turn-1');
+ await expect(
+ store.createTurn(
+ makeCreateTurnInput({
+ sessionId,
+ turnId: 'turn-1',
+ previousTurnId: 'turn-1',
+ firstTurnId: 'turn-1',
+ }),
+ ),
+ ).rejects.toBeInstanceOf(TurnAlreadyExistsError);
+ });
+
+ it('linear continuation carries context and persists the caller-supplied capability map', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(
+ makeCreateTurnInput({
+ sessionId,
+ turnId: 't1',
+ new_threads: [
+ {
+ thread_id: MAIN_THREAD_ID,
+ parent: null,
+ agent_info: null,
+ },
+ ],
+ capability_states: [{ thread_id: MAIN_THREAD_ID, capability_state: { 'tfy.plan': { step: 1 } } }],
+ new_context_appends: [
+ {
+ thread_id: MAIN_THREAD_ID,
+ context: [userMessage('L1a'), userMessage('L1b')],
+ current_context_usage: { ...getEmptyUsage(), total_tokens: 2 },
+ },
+ ],
+ }),
+ );
+ await store.patchThreadCapabilityState({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 't1',
+ thread_id: MAIN_THREAD_ID,
+ key: 'tfy.plan',
+ state: { step: 2 },
+ });
+ await finishTurn(store, 't1');
+
+ await store.createTurn(
+ makeCreateTurnInput({
+ sessionId,
+ turnId: 't2',
+ previousTurnId: 't1',
+ firstTurnId: 't1',
+ capability_states: [{ thread_id: MAIN_THREAD_ID, capability_state: { 'tfy.plan': { step: 2 } } }],
+ new_context_appends: [
+ {
+ thread_id: MAIN_THREAD_ID,
+ context: [userMessage('L2')],
+ current_context_usage: { ...getEmptyUsage(), total_tokens: 3 },
+ },
+ ],
+ }),
+ );
+
+ const t2 = await store.getTurn({ tenant_id: tenant, session_id: sessionId, turn_id: 't2' });
+ const main = mustGet(t2).snapshot.threads[MAIN_THREAD_ID];
+ expect(contextContents(main?.context)).toEqual(['L1a', 'L1b', 'L2']);
+ expect(main?.current_context_usage.total_tokens).toBe(3);
+ expect(main?.capability_state).toEqual({ 'tfy.plan': { step: 2 } });
+ });
+
+ it('createTurn atomically persists the complete post-send capability map', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(
+ makeCreateTurnInput({
+ sessionId,
+ turnId: 't1',
+ capability_states: [
+ {
+ thread_id: MAIN_THREAD_ID,
+ capability_state: { keep: { version: 1 }, remove: true },
+ },
+ ],
+ }),
+ );
+ await finishTurn(store, 't1');
+
+ await store.createTurn(
+ makeCreateTurnInput({
+ sessionId,
+ turnId: 't2',
+ previousTurnId: 't1',
+ firstTurnId: 't1',
+ capability_states: [
+ {
+ thread_id: MAIN_THREAD_ID,
+ capability_state: { keep: { version: 2 } },
+ },
+ ],
+ }),
+ );
+
+ const t2 = await store.getTurn({ tenant_id: tenant, session_id: sessionId, turn_id: 't2' });
+ expect(t2?.snapshot.threads[MAIN_THREAD_ID]?.capability_state).toEqual({
+ keep: { version: 2 },
+ });
+ });
+
+ it('fork from an older turn after tip overwrite sees only the parent prefix', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(
+ makeCreateTurnInput({
+ sessionId,
+ turnId: 't1',
+ new_context_appends: [
+ {
+ thread_id: MAIN_THREAD_ID,
+ context: [userMessage('from-t1')],
+ current_context_usage: getEmptyUsage(),
+ },
+ ],
+ }),
+ );
+ await finishTurn(store, 't1');
+
+ await store.createTurn(
+ makeCreateTurnInput({
+ sessionId,
+ turnId: 't2',
+ previousTurnId: 't1',
+ firstTurnId: 't1',
+ new_context_appends: [
+ {
+ thread_id: MAIN_THREAD_ID,
+ context: [userMessage('from-t2')],
+ current_context_usage: getEmptyUsage(),
+ },
+ ],
+ }),
+ );
+ await store.overwriteThreadContext({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 't2',
+ event: {
+ type: EventType.AGENT_CONTEXT_OVERWRITE,
+ id: newEventId(),
+ created_at: new Date().toISOString(),
+ thread_id: MAIN_THREAD_ID,
+ reason: 'compaction',
+ context: [userMessage('t2-summary-only')],
+ current_context_usage: getEmptyUsage(),
+ compaction_llm_usage: getEmptyUsage(),
+ },
+ });
+ await finishTurn(store, 't2');
+
+ await store.createTurn(
+ makeCreateTurnInput({
+ sessionId,
+ turnId: 't3-fork',
+ previousTurnId: 't1',
+ firstTurnId: 't1',
+ new_context_appends: [
+ {
+ thread_id: MAIN_THREAD_ID,
+ context: [userMessage('fork-append')],
+ current_context_usage: getEmptyUsage(),
+ },
+ ],
+ }),
+ );
+
+ const fork = await store.getTurn({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 't3-fork',
+ });
+ expect(contextContents(fork?.snapshot.threads[MAIN_THREAD_ID]?.context)).toEqual(['from-t1', 'fork-append']);
+ });
+
+ it('createTurn with multiple new_threads + appends is atomic (all threads present together)', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(
+ makeCreateTurnInput({
+ sessionId,
+ turnId: 't1',
+ new_threads: [
+ {
+ thread_id: MAIN_THREAD_ID,
+ parent: null,
+ agent_info: null,
+ },
+ {
+ thread_id: 'child-a',
+ parent: { thread_id: MAIN_THREAD_ID, tool_call_id: 'tc-a' },
+ agent_info: { type: 'dynamic', name: 'child-a', input: 'task-a' },
+ },
+ {
+ thread_id: 'child-b',
+ parent: { thread_id: MAIN_THREAD_ID, tool_call_id: 'tc-b' },
+ agent_info: { type: 'dynamic', name: 'child-b', input: 'task-b' },
+ },
+ ],
+ capability_states: [
+ { thread_id: MAIN_THREAD_ID, capability_state: null },
+ { thread_id: 'child-a', capability_state: { 'tfy.plan': { step: 1 } } },
+ { thread_id: 'child-b', capability_state: null },
+ ],
+ new_context_appends: [
+ {
+ thread_id: MAIN_THREAD_ID,
+ context: [userMessage('main-msg')],
+ current_context_usage: getEmptyUsage(),
+ },
+ {
+ thread_id: 'child-a',
+ context: [userMessage('a-msg')],
+ current_context_usage: { ...getEmptyUsage(), total_tokens: 1 },
+ },
+ {
+ thread_id: 'child-b',
+ context: [userMessage('b-msg-1'), userMessage('b-msg-2')],
+ current_context_usage: { ...getEmptyUsage(), total_tokens: 2 },
+ },
+ ],
+ }),
+ );
+
+ const turn = await store.getTurn({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 't1',
+ });
+ const threads = mustGet(turn).snapshot.threads;
+ expect(Object.keys(threads).sort()).toEqual(['child-a', 'child-b', MAIN_THREAD_ID]);
+ expect(contextContents(threads[MAIN_THREAD_ID]?.context)).toEqual(['main-msg']);
+ expect(contextContents(threads['child-a']?.context)).toEqual(['a-msg']);
+ expect(contextContents(threads['child-b']?.context)).toEqual(['b-msg-1', 'b-msg-2']);
+ expect(threads['child-a']?.parent).toEqual({
+ thread_id: MAIN_THREAD_ID,
+ tool_call_id: 'tc-a',
+ });
+ expect(threads['child-a']?.agent_info).toEqual({
+ type: 'dynamic',
+ name: 'child-a',
+ input: 'task-a',
+ });
+ expect(threads['child-a']?.capability_state).toEqual({ 'tfy.plan': { step: 1 } });
+ expect(threads['child-b']?.current_context_usage.total_tokens).toBe(2);
+ });
+ });
+
+ describe('freezeAndGetTurn', () => {
+ it('cancels a running turn, persists turn.done, and fences all turn-scoped writes', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 'turn-1' }));
+ const cancelledState = makeCancelledTurnState(CancellationReason.CancelledForNextTurn);
+ const record = await store.freezeAndGetTurn({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ turn_done_event: makeTurnDoneEvent(cancelledState),
+ });
+ expect(record.state.status).toBe('cancelled');
+ const { data } = await store.listTurnEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ limit: 10,
+ page_token: undefined,
+ order: undefined,
+ });
+ expect(data.some(e => e.type === EventType.TURN_DONE)).toBe(true);
+
+ const keys = { tenant_id: tenant, session_id: sessionId, turn_id: 'turn-1' };
+ const fencedWrites: (() => Promise<unknown>)[] = [
+ () =>
+ store.appendToEvents({
+ ...keys,
+ events: [makeTurnCreatedEvent('turn-1')],
+ }),
+ () =>
+ store.appendToThreadContext({
+ ...keys,
+ thread_id: MAIN_THREAD_ID,
+ context: [userMessage('late')],
+ current_context_usage: null,
+ completion: null,
+ }),
+ () =>
+ store.overwriteThreadContext({
+ ...keys,
+ event: {
+ type: EventType.AGENT_CONTEXT_OVERWRITE,
+ id: newEventId(),
+ created_at: new Date().toISOString(),
+ thread_id: MAIN_THREAD_ID,
+ reason: 'compaction',
+ context: [userMessage('late-overwrite')],
+ current_context_usage: getEmptyUsage(),
+ compaction_llm_usage: getEmptyUsage(),
+ },
+ }),
+ () =>
+ store.addThreads({
+ ...keys,
+ threads: [
+ {
+ thread_id: 'child',
+ context: [],
+ current_context_usage: getEmptyUsage(),
+ parent: { thread_id: MAIN_THREAD_ID, tool_call_id: 'tc1' },
+ agent_info: { type: 'dynamic', name: 'child', input: 'do work' },
+ completion: null,
+ capability_state: null,
+ },
+ ],
+ }),
+ () => store.removeThreads({ ...keys, thread_ids: [MAIN_THREAD_ID] }),
+ () =>
+ store.patchMCPServers({
+ ...keys,
+ mcp_servers: [{ id: 'svc', name: 'svc', session_id: 'mcp-1', transport_type: 'streamable-http' }],
+ }),
+ () => store.patchSandboxInfo({ ...keys, sandbox_info: { sandbox_id: 'sbx-1' } }),
+ () =>
+ store.patchThreadCapabilityState({
+ ...keys,
+ thread_id: MAIN_THREAD_ID,
+ key: 'tfy.plan',
+ state: { v: 1 },
+ }),
+ ];
+
+ for (const write of fencedWrites) {
+ await expect(write()).rejects.toBeInstanceOf(TurnNotRunningError);
+ }
+ });
+
+ it('on an already-terminal turn is a plain read without duplicating turn.done', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 'turn-1' }));
+ await finishTurn(store, 'turn-1');
+ const doneState = makeDoneTurnState();
+ await store.freezeAndGetTurn({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ turn_done_event: makeTurnDoneEvent(doneState),
+ });
+ const { data } = await store.listTurnEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ limit: 10,
+ page_token: undefined,
+ order: undefined,
+ });
+ expect(data.filter(e => e.type === EventType.TURN_DONE)).toHaveLength(1);
+ });
+
+ it('concurrent freeze x freeze is idempotent: one cancels, both return terminal', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 'turn-1' }));
+ const cancelledState = makeCancelledTurnState(CancellationReason.CancelledForNextTurn);
+ const results = await Promise.allSettled([
+ store.freezeAndGetTurn({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ turn_done_event: makeTurnDoneEvent(cancelledState),
+ }),
+ store.freezeAndGetTurn({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ turn_done_event: makeTurnDoneEvent(cancelledState),
+ }),
+ ]);
+ expect(results.every(r => r.status === 'fulfilled')).toBe(true);
+ const turn = await store.getTurn({ tenant_id: tenant, session_id: sessionId, turn_id: 'turn-1' });
+ expect(mustGet(turn).state.status).toBe('cancelled');
+ const { data } = await store.listTurnEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ limit: 10,
+ page_token: undefined,
+ order: undefined,
+ });
+ expect(data.filter(e => e.type === EventType.TURN_DONE)).toHaveLength(1);
+ });
+
+ it('concurrent freeze x updateTurnState: exactly one terminal transition wins', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 'turn-1' }));
+ const cancelledState = makeCancelledTurnState(CancellationReason.CancelledForNextTurn);
+ const doneState = makeDoneTurnState();
+ const results = await Promise.allSettled([
+ store.freezeAndGetTurn({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ turn_done_event: makeTurnDoneEvent(cancelledState),
+ }),
+ store.updateTurnState({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ state: doneState,
+ turn_done_event: makeTurnDoneEvent(doneState),
+ }),
+ ]);
+ const rejected = results.filter(r => r.status === 'rejected');
+ for (const result of rejected) {
+ expect(result.reason).toBeInstanceOf(TurnNotRunningError);
+ }
+ // freeze-after-update is a plain read (both fulfill); update-after-freeze rejects.
+ expect(rejected.length === 0 || rejected.length === 1).toBe(true);
+
+ const turn = await store.getTurn({ tenant_id: tenant, session_id: sessionId, turn_id: 'turn-1' });
+ expect(['cancelled', 'done']).toContain(mustGet(turn).state.status);
+ const { data } = await store.listTurnEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ limit: 10,
+ page_token: undefined,
+ order: undefined,
+ });
+ expect(data.filter(e => e.type === EventType.TURN_DONE)).toHaveLength(1);
+ });
+ });
+
+ describe('updateTurnState', () => {
+ it('allows running → done and rejects second terminal (first-terminal-wins)', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 'turn-1' }));
+ await finishTurn(store, 'turn-1');
+ const cancelledState = makeCancelledTurnState(CancellationReason.ClientCancelled);
+ await expect(
+ store.updateTurnState({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ state: cancelledState,
+ turn_done_event: makeTurnDoneEvent(cancelledState),
+ }),
+ ).rejects.toBeInstanceOf(SessionStoreConflictError);
+ });
+
+ it('writes terminal state and turn.done atomically', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 'turn-1' }));
+ const state = makeDoneTurnState();
+ const turnDone = makeTurnDoneEvent(state);
+ await store.updateTurnState({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ state,
+ turn_done_event: turnDone,
+ });
+
+ const turn = await store.getTurn({ tenant_id: tenant, session_id: sessionId, turn_id: 'turn-1' });
+ expect(mustGet(turn).state).toEqual(state);
+ const { data } = await store.listTurnEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ limit: 10,
+ page_token: undefined,
+ order: undefined,
+ });
+ const doneEvents = data.filter(e => e.type === EventType.TURN_DONE);
+ expect(doneEvents).toHaveLength(1);
+ expect(doneEvents[0]).toEqual(turnDone);
+ });
+
+ it('missing turn → not found', async () => {
+ const store = createStore();
+ await seedSession(store);
+ const state = makeDoneTurnState();
+ await expect(
+ store.updateTurnState({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'missing',
+ state,
+ turn_done_event: makeTurnDoneEvent(state),
+ }),
+ ).rejects.toBeInstanceOf(SessionStoreNotFoundError);
+ });
+ });
+
+ describe('events + threads + capability_state', () => {
+ it('appendToEvents orders by monotonic event id, not append call order', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 'turn-1' }));
+ const created = makeTurnCreatedEvent('turn-1');
+ const model = makeModelMessageEvent();
+ expect(created.id < model.id).toBe(true);
+ expect(created.created_at).toBeDefined();
+ expect(model.created_at).toBeDefined();
+ await store.appendToEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ // Deliberately reversed: durable ordering comes from event.id.
+ events: [model, created],
+ });
+ const { data } = await store.listTurnEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ limit: 10,
+ page_token: undefined,
+ order: undefined,
+ });
+ expect(data.map(e => e.type)).toEqual(['turn.created', EventType.MODEL_MESSAGE]);
+ expect(data.map(e => e.id)).toEqual([created.id, model.id]);
+ });
+
+ it('add/remove threads and append/overwrite context', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 'turn-1' }));
+ await store.addThreads({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ threads: [
+ {
+ thread_id: 'child',
+ context: [],
+ current_context_usage: getEmptyUsage(),
+ parent: { thread_id: MAIN_THREAD_ID, tool_call_id: 'tc1' },
+ agent_info: { type: 'dynamic', name: 'child', input: 'do work' },
+ completion: null,
+ capability_state: null,
+ },
+ ],
+ });
+ await store.appendToThreadContext({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ thread_id: 'child',
+ context: [{ role: 'user', content: 'hello' }],
+ current_context_usage: null,
+ completion: null,
+ });
+ let turn = await store.getTurn({ tenant_id: tenant, session_id: sessionId, turn_id: 'turn-1' });
+ expect(turn?.snapshot.threads['child']?.context).toHaveLength(1);
+
+ await store.overwriteThreadContext({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ event: {
+ type: EventType.AGENT_CONTEXT_OVERWRITE,
+ id: newEventId(),
+ created_at: new Date().toISOString(),
+ thread_id: 'child',
+ reason: 'compaction',
+ context: [{ role: 'user', content: 'replaced' }],
+ current_context_usage: getEmptyUsage(),
+ compaction_llm_usage: getEmptyUsage(),
+ },
+ });
+ turn = await store.getTurn({ tenant_id: tenant, session_id: sessionId, turn_id: 'turn-1' });
+ expect(turn?.snapshot.threads['child']?.context).toEqual([{ role: 'user', content: 'replaced' }]);
+
+ await store.removeThreads({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ thread_ids: ['child'],
+ });
+ turn = await store.getTurn({ tenant_id: tenant, session_id: sessionId, turn_id: 'turn-1' });
+ expect(turn?.snapshot.threads['child']).toBeUndefined();
+ });
+
+ it('context order is identical before persistence and after loading', async () => {
+ const store = createStore();
+ await seedSession(store);
+ const firstBatch = ['m-03', 'm-01', 'm-04'].map(userMessage);
+ const secondBatch = ['m-02', 'm-05', 'm-00'].map(userMessage);
+ const expected = [...firstBatch, ...secondBatch];
+
+ await store.createTurn(
+ makeCreateTurnInput({
+ sessionId,
+ turnId: 'turn-1',
+ new_context_appends: [
+ {
+ thread_id: MAIN_THREAD_ID,
+ context: firstBatch,
+ current_context_usage: getEmptyUsage(),
+ },
+ ],
+ }),
+ );
+ await store.appendToThreadContext({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ thread_id: MAIN_THREAD_ID,
+ context: secondBatch,
+ current_context_usage: null,
+ completion: null,
+ });
+
+ const loaded = await store.getTurn({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ });
+ expect(loaded?.snapshot.threads[MAIN_THREAD_ID]?.context).toEqual(expected);
+ expect(contextContents(loaded?.snapshot.threads[MAIN_THREAD_ID]?.context)).toEqual([
+ 'm-03',
+ 'm-01',
+ 'm-04',
+ 'm-02',
+ 'm-05',
+ 'm-00',
+ ]);
+ });
+
+ it('patchThreadCapabilityState is LWW per key', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 'turn-1' }));
+ await store.patchThreadCapabilityState({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ thread_id: MAIN_THREAD_ID,
+ key: 'tfy.plan',
+ state: { v: 1 },
+ });
+ await store.patchThreadCapabilityState({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ thread_id: MAIN_THREAD_ID,
+ key: 'tfy.plan',
+ state: { v: 2 },
+ });
+ const turn = await store.getTurn({ tenant_id: tenant, session_id: sessionId, turn_id: 'turn-1' });
+ expect(turn?.snapshot.threads[MAIN_THREAD_ID]?.capability_state).toEqual({ 'tfy.plan': { v: 2 } });
+ });
+
+ it('capability state is per-turn: patching the successor does not change a frozen predecessor', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(
+ makeCreateTurnInput({
+ sessionId,
+ turnId: 't1',
+ new_threads: [
+ {
+ thread_id: MAIN_THREAD_ID,
+ parent: null,
+ agent_info: null,
+ },
+ ],
+ capability_states: [{ thread_id: MAIN_THREAD_ID, capability_state: { plan: { step: 1 } } }],
+ }),
+ );
+ await finishTurn(store, 't1');
+ await store.createTurn(
+ makeCreateTurnInput({
+ sessionId,
+ turnId: 't2',
+ previousTurnId: 't1',
+ firstTurnId: 't1',
+ }),
+ );
+ await store.patchThreadCapabilityState({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 't2',
+ thread_id: MAIN_THREAD_ID,
+ key: 'plan',
+ state: { step: 2 },
+ });
+
+ const t1 = await store.getTurn({ tenant_id: tenant, session_id: sessionId, turn_id: 't1' });
+ const t2 = await store.getTurn({ tenant_id: tenant, session_id: sessionId, turn_id: 't2' });
+ expect(t1?.snapshot.threads[MAIN_THREAD_ID]?.capability_state).toEqual({ plan: { step: 1 } });
+ expect(t2?.snapshot.threads[MAIN_THREAD_ID]?.capability_state).toEqual({ plan: { step: 2 } });
+ });
+
+ it('getTurn output is JSON-round-trip total (no undefined holes)', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(
+ makeCreateTurnInput({
+ sessionId,
+ turnId: 'turn-1',
+ new_context_appends: [
+ {
+ thread_id: MAIN_THREAD_ID,
+ context: [userMessage('hello')],
+ current_context_usage: getEmptyUsage(),
+ },
+ ],
+ }),
+ );
+ const turn = await store.getTurn({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ });
+ // Totality: JSON round-trip must not drop keys (undefined is stripped by stringify).
+ const revived = JSON.parse(JSON.stringify(turn)) as unknown;
+ expect(revived).toEqual(turn);
+ expect(JSON.stringify(turn)).toBe(JSON.stringify(revived));
+ });
+
+ it('patchMCPServers and patchSandboxInfo', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 'turn-1' }));
+ await store.patchMCPServers({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ mcp_servers: [{ id: 'svc', name: 'svc', session_id: 'mcp-1', transport_type: 'streamable-http' }],
+ });
+ await store.patchSandboxInfo({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ sandbox_info: { sandbox_id: 'sbx-1' },
+ });
+ const turn = await store.getTurn({ tenant_id: tenant, session_id: sessionId, turn_id: 'turn-1' });
+ expect(turn?.snapshot.mcp_servers?.['svc']?.session_id).toBe('mcp-1');
+ expect(mustGet(turn).snapshot.sandbox_info?.sandbox_id).toBe('sbx-1');
+ });
+ });
+
+ describe('pagination', () => {
+ // Offset-token pagination does not isolate readers from concurrent inserts:
+ // rows added while a client walks pages may appear twice or be skipped.
+ // Callers that need a consistent snapshot re-fetch from the tip.
+
+ it('listTurns paginates with opaque tokens', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 't1' }));
+ await finishTurn(store, 't1');
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 't2', previousTurnId: 't1', firstTurnId: 't1' }));
+ await finishTurn(store, 't2');
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 't3', previousTurnId: 't2', firstTurnId: 't1' }));
+ const page1 = await store.listTurns({
+ tenant_id: tenant,
+ session_id: sessionId,
+ limit: 2,
+ page_token: undefined,
+ });
+ expect(page1.data.map(t => t.turn_id)).toEqual(['t1', 't2']);
+ expect(page1.pagination.next_page_token).toBeDefined();
+ const page2 = await store.listTurns({
+ tenant_id: tenant,
+ session_id: sessionId,
+ limit: 2,
+ page_token: page1.pagination.next_page_token,
+ });
+ expect(page2.data.map(t => t.turn_id)).toEqual(['t3']);
+ });
+
+ it('listTurnEvents supports desc order', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 'turn-1' }));
+ await store.appendToEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ events: [makeTurnCreatedEvent('turn-1'), makeModelMessageEvent()],
+ });
+ const { data } = await store.listTurnEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 'turn-1',
+ limit: 10,
+ order: 'desc',
+ page_token: undefined,
+ });
+ expect(data[0]?.type).toBe(EventType.MODEL_MESSAGE);
+ });
+
+ it('listSessionEvents includes running turns and is newest-first', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 't1' }));
+ await store.appendToEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 't1',
+ events: [makeTurnCreatedEvent('t1')],
+ });
+ await finishTurn(store, 't1');
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 't2', previousTurnId: 't1', firstTurnId: 't1' }));
+ await store.appendToEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 't2',
+ events: [makeTurnCreatedEvent('t2')],
+ });
+ // t2 still running — must appear in the feed.
+ const { data } = await store.listSessionEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ limit: 10,
+ page_token: undefined,
+ last_turn_id: undefined,
+ });
+ expect(data.map(row => row.turn_id)).toEqual(['t2', 't1', 't1']);
+ expect(data.map(row => row.event.type)).toEqual([
+ EventType.TURN_CREATED,
+ EventType.TURN_DONE,
+ EventType.TURN_CREATED,
+ ]);
+ });
+
+ it('listSessionEvents includes registered passthrough events', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 't1' }));
+ // Built through the registered schema so the fixture cannot drift from the registration.
+ const passthrough: PersistedTurnEvent = {
+ type: 'custom.event',
+ ...ContractPassthroughEventSchema.parse({
+ id: newEventId(),
+ created_at: new Date().toISOString(),
+ event: { value: 1 },
+ }),
+ };
+ await store.appendToEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 't1',
+ events: [passthrough],
+ });
+
+ const { data } = await store.listSessionEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ limit: 10,
+ page_token: undefined,
+ last_turn_id: undefined,
+ });
+ expect(data).toEqual([{ turn_id: 't1', event: passthrough }]);
+ });
+
+ it('listSessionEvents defaults to the active branch and excludes fork siblings', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 't1' }));
+ await store.appendToEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 't1',
+ events: [makeTurnCreatedEvent('t1')],
+ });
+ // Two forks off t1; the sibling is created BEFORE the anchor, so a
+ // creation-order prefix would wrongly include it.
+ await finishTurn(store, 't1');
+ await store.createTurn(
+ makeCreateTurnInput({ sessionId, turnId: 't2-sibling', previousTurnId: 't1', firstTurnId: 't1' }),
+ );
+ await store.createTurn(
+ makeCreateTurnInput({ sessionId, turnId: 't2-anchor', previousTurnId: 't1', firstTurnId: 't1' }),
+ );
+ for (const turnId of ['t2-sibling', 't2-anchor']) {
+ await store.appendToEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: turnId,
+ events: [makeTurnCreatedEvent(turnId)],
+ });
+ }
+ const { data } = await store.listSessionEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ limit: 10,
+ last_turn_id: undefined,
+ page_token: undefined,
+ });
+ expect(data.filter(row => row.event.type === EventType.TURN_CREATED).map(row => row.turn_id)).toEqual([
+ 't2-anchor',
+ 't1',
+ ]);
+
+ await expect(
+ store.listSessionEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ limit: 10,
+ last_turn_id: 'missing',
+ page_token: undefined,
+ }),
+ ).rejects.toBeInstanceOf(SessionStoreNotFoundError);
+ });
+
+ it('listSessionEvents page tokens retain their anchor when the active branch changes', async () => {
+ const store = createStore();
+ await seedSession(store);
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 't1' }));
+ await store.appendToEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 't1',
+ events: [makeTurnCreatedEvent('t1')],
+ });
+ await finishTurn(store, 't1');
+ await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 't2', previousTurnId: 't1', firstTurnId: 't1' }));
+ await store.appendToEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 't2',
+ events: [makeTurnCreatedEvent('t2')],
+ });
+
+ const firstPage = await store.listSessionEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ limit: 1,
+ last_turn_id: undefined,
+ page_token: undefined,
+ });
+ expect(firstPage.data.map(row => row.turn_id)).toEqual(['t2']);
+ expect(decodeSessionEventPageToken(mustGet(firstPage.pagination.next_page_token))).toEqual({
+ last_turn_id: 't2',
+ offset: 1,
+ });
+
+ await store.createTurn(
+ makeCreateTurnInput({ sessionId, turnId: 't2-new-active', previousTurnId: 't1', firstTurnId: 't1' }),
+ );
+ await store.appendToEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: 't2-new-active',
+ events: [makeTurnCreatedEvent('t2-new-active')],
+ });
+
+ const secondPage = await store.listSessionEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ limit: 10,
+ last_turn_id: undefined,
+ page_token: firstPage.pagination.next_page_token,
+ });
+ expect(secondPage.data.map(row => row.turn_id)).not.toContain('t2-new-active');
+ expect(secondPage.data.map(row => row.turn_id)).toContain('t1');
+ });
+
+ it('listSessionEvents spills through truncated ancestor_ids windows to reach the chain root', async () => {
+ const store = createStore();
+ await seedSession(store);
+ // Writer-chosen window shorter than the chain — store must spill.
+ const ancestorWindow = 3;
+ const chainLength = ancestorWindow + 5;
+ const ids = Array.from({ length: chainLength }, (_, i) => `t${String(i + 1)}`);
+ for (let i = 0; i < ids.length; i++) {
+ const turnId = mustGet(ids[i], `ids[${String(i)}]`);
+ const window = ids.slice(Math.max(0, i - ancestorWindow), i);
+ if (i > 0) {
+ await finishTurn(store, mustGet(ids[i - 1], `ids[${String(i - 1)}]`));
+ }
+ const input = makeCreateTurnInput({
+ sessionId,
+ turnId,
+ ...(i > 0
+ ? {
+ previousTurnId: mustGet(ids[i - 1], `ids[${String(i - 1)}]`),
+ firstTurnId: mustGet(ids[0], 'ids[0]'),
+ }
+ : {}),
+ });
+ input.turn.ancestor_ids = window;
+ await store.createTurn(input);
+ await store.appendToEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ turn_id: turnId,
+ events: [makeTurnCreatedEvent(turnId)],
+ });
+ }
+ const tip = mustGet(ids.at(-1), 'chain tip');
+ const { data } = await store.listSessionEvents({
+ tenant_id: tenant,
+ session_id: sessionId,
+ limit: chainLength + 10,
+ last_turn_id: tip,
+ page_token: undefined,
+ });
+ // Full chain reachable despite truncated windows, newest-first turn.created rows only.
+ expect(data.filter(row => row.event.type === EventType.TURN_CREATED).map(row => row.turn_id)).toEqual(
+ [...ids].reverse(),
+ );
+ });
+ });
+
+ describe('deep-copy boundary', () => {
+ it('mutating a returned session does not mutate the store', async () => {
+ const store = createStore();
+ await seedSession(store);
+ const session = await store.getSession({ tenant_id: tenant, session_id: sessionId });
+ mustGet(session).agent_spec.instructions = 'mutated';
+ const again = await store.getSession({ tenant_id: tenant, session_id: sessionId });
+ expect(mustGet(again).agent_spec.instructions).toBe('You are a test agent.');
+ });
+ });
+
+ describe('no SSE surface', () => {
+ it('ISessionStore has no subscribe* members', () => {
+ const store = createStore();
+ const keys = Object.getOwnPropertyNames(Object.getPrototypeOf(store)).concat(Object.keys(store));
+ expect(keys.some(k => k.startsWith('subscribe'))).toBe(false);
+ });
+ });
+}
diff --git a/packages/harness/tests/agent-session/testHelpers.ts b/packages/harness/tests/agent-session/testHelpers.ts
index 41e5410eb..ce018ddac 100644
--- a/packages/harness/tests/agent-session/testHelpers.ts
+++ b/packages/harness/tests/agent-session/testHelpers.ts
@@ -1,9 +1,12 @@
import type { ITurnResourceResolver } from '../../src/agent-session/ITurnResourceResolver';
import { MAIN_THREAD_ID, type TurnRecord } from '../../src/agent-session/models/TurnRecord';
import { AgentSpecSchema, type AgentSpec } from '../../src/agent-session/schemas/agentSpec';
+import { EventType } from '../../src/agent-session/schemas/events';
+import { CancellationReason, type TerminalTurnState } from '../../src/agent-session/schemas/turn';
+import type { CreateTurnInput, NewThreadInit, TurnContextAppend } from '../../src/agent-session/store/ISessionStore';
import { TurnResourceResolver } from '../../src/agent-session/TurnResourceResolver';
import type { AgentCapability } from '../../src/core/capabilities/AgentCapability';
-import { EventType, newEventId } from '../../src/core/events/schema';
+import { newEventId } from '../../src/core/events/schema';
import type { ExtendedChatCompletionChunk, RawAssistantMessageWithUsage } from '../../src/core/llm/LLMTypes';
import { getEmptyUsage } from '../../src/core/llm/LLMTypes';
import type { Sandbox } from '../../src/core/sandbox/Sandbox';
@@ -118,10 +121,76 @@ export function makeTestResolver<TTurnCustom extends object = Record<string, nev
return wrapped;
}
+export function makeTurnDoneEvent(state: TerminalTurnState) {
+ return {
+ type: EventType.TURN_DONE,
+ id: newEventId(),
+ created_at: new Date().toISOString(),
+ state,
+ thread_id: null,
+ };
+}
+
+const defaultRootThread: NewThreadInit = {
+ thread_id: MAIN_THREAD_ID,
+ parent: null,
+ agent_info: null,
+};
+
+/** Delta-shaped createTurn input for store contract tests. */
+export function makeCreateTurnInput(input: {
+ tenant?: string;
+ sessionId: string;
+ turnId: string;
+ previousTurnId?: string | null;
+ firstTurnId?: string;
+ new_threads?: NewThreadInit[];
+ new_context_appends?: TurnContextAppend[];
+ capability_states?: CreateTurnInput['capability_states'];
+ update_session_title_if_not_exist?: string;
+}): CreateTurnInput {
+ const turn = makeRunningTurnRecord({
+ sessionId: input.sessionId,
+ turnId: input.turnId,
+ ...(input.previousTurnId !== undefined ? { previousTurnId: input.previousTurnId } : {}),
+ ...(input.firstTurnId !== undefined ? { firstTurnId: input.firstTurnId } : {}),
+ });
+ const { snapshot, ...turnInit } = turn;
+ void snapshot;
+ const isFirstInChain = input.previousTurnId === undefined || input.previousTurnId === null;
+ return {
+ tenant_id: input.tenant ?? 't1',
+ turn: turnInit,
+ new_threads: isFirstInChain ? (input.new_threads ?? [defaultRootThread]) : (input.new_threads ?? []),
+ new_context_appends: input.new_context_appends ?? [],
+ capability_states: input.capability_states ?? [{ thread_id: MAIN_THREAD_ID, capability_state: null }],
+ update_session_title_if_not_exist: input.update_session_title_if_not_exist ?? null,
+ };
+}
+
+export function makeDoneTurnState(): TerminalTurnState {
+ return {
+ status: 'done',
+ output: null,
+ required_actions: [],
+ completed_at: new Date().toISOString(),
+ };
+}
+
+export function makeCancelledTurnState(
+ reason: CancellationReason = CancellationReason.ClientCancelled,
+): TerminalTurnState {
+ return {
+ status: 'cancelled',
+ reason,
+ completed_at: new Date().toISOString(),
+ };
+}
+
export function makeRunningTurnRecord(input: {
sessionId: string;
turnId: string;
- previousTurnId?: string;
+ previousTurnId?: string | null;
firstTurnId?: string;
}): TurnRecord {
const now = new Date().toISOString();
@@ -130,17 +199,24 @@ export function makeRunningTurnRecord(input: {
session_id: input.sessionId,
first_turn_id: input.firstTurnId ?? input.turnId,
ancestor_ids: input.previousTurnId ? [input.previousTurnId] : [],
- previous_turn_id: input.previousTurnId,
+ previous_turn_id: input.previousTurnId ?? null,
state: { status: 'running' },
input: [],
+ custom: null,
snapshot: {
threads: {
[MAIN_THREAD_ID]: {
thread_id: MAIN_THREAD_ID,
context: [],
current_context_usage: getEmptyUsage(),
+ parent: null,
+ agent_info: null,
+ completion: null,
+ capability_state: null,
},
},
+ mcp_servers: null,
+ sandbox_info: null,
},
created_at: now,
updated_at: now,
diff --git a/packages/harness/tests/agent-session/turnStream.test.ts b/packages/harness/tests/agent-session/turnStream.test.ts
index b12823403..ddebbbfae 100644
--- a/packages/harness/tests/agent-session/turnStream.test.ts
+++ b/packages/harness/tests/agent-session/turnStream.test.ts
@@ -14,7 +14,7 @@ describe('TurnHandle.stream()', () => {
const store = new InMemorySessionStore();
const sessions = new Sessions({ sessionStore: store });
const session = await sessions.create({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
agent_spec: makeAgentSpec({
config: {
@@ -48,7 +48,7 @@ describe('TurnHandle.stream()', () => {
expect(data.some(e => e.type === EventType.TURN_DONE)).toBe(true);
const stored = await store.getTurn({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
turn_id: turn.id,
});
@@ -118,7 +118,7 @@ describe('TurnHandle.stream()', () => {
}
expect(closeCalls).toBe(1);
const stored = await store.getTurn({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
turn_id: turn.id,
});
@@ -144,7 +144,7 @@ describe('TurnHandle.stream()', () => {
expect(turn.state.reason).toBe(CancellationReason.ClientCancelled);
}
const stored = await store.getTurn({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
turn_id: turn.id,
});
@@ -169,7 +169,7 @@ describe('TurnHandle.stream()', () => {
expect(turn.state.reason).toBe(CancellationReason.Abandoned);
}
const stored = await store.getTurn({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
turn_id: turn.id,
});
@@ -197,7 +197,7 @@ describe('TurnHandle.stream()', () => {
expect(turn.state.reason).toBe(CancellationReason.ServerExecutionTimeout);
}
const stored = await store.getTurn({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
turn_id: turn.id,
});
@@ -228,7 +228,7 @@ describe('TurnHandle.stream()', () => {
expect(closeCalls).toBe(1);
expect(turn.state.status).toBe('done');
const stored = await store.getTurn({
- tenant_name: tenant,
+ tenant_id: tenant,
session_id: 's1',
turn_id: turn.id,
});
@@ -314,7 +314,7 @@ describe('TurnResourceResolver caches', () => {
const store = new InMemorySessionStore();
const sessions = new Sessions({ sessionStore: store });
const session = await sessions.create({
- tenant_name: 't',
+ tenant_id: 't',
session_id: 's',
agent_spec: makeAgentSpec({
config: {
diff --git a/packages/harness/tests/core/sandboxObjectIdentity.test.ts b/packages/harness/tests/core/capabilities/builtins/sandboxObjectIdentity.test.ts
similarity index 82%
rename from packages/harness/tests/core/sandboxObjectIdentity.test.ts
rename to packages/harness/tests/core/capabilities/builtins/sandboxObjectIdentity.test.ts
index 390fa24d3..12e8a1f99 100644
--- a/packages/harness/tests/core/sandboxObjectIdentity.test.ts
+++ b/packages/harness/tests/core/capabilities/builtins/sandboxObjectIdentity.test.ts
@@ -1,8 +1,8 @@
-import { largeToolResponse } from '../../src/core/capabilities/builtins/LargeToolResponse';
-import { getEmptyUsage } from '../../src/core/llm/LLMTypes';
-import type { IToolSet } from '../../src/core/mcp/IMCPServer';
-import type { ToolCallResult } from '../../src/core/mcp/executeToolCalls';
-import { makeMockIMCPServer, makeSilentLogger, makeStubPublicSandbox } from './harnessMocks';
+import { largeToolResponse } from '../../../../src/core/capabilities/builtins/LargeToolResponse';
+import { getEmptyUsage } from '../../../../src/core/llm/LLMTypes';
+import type { IToolSet } from '../../../../src/core/mcp/IMCPServer';
+import type { ToolCallResult } from '../../../../src/core/mcp/executeToolCalls';
+import { makeMockIMCPServer, makeSilentLogger, makeStubPublicSandbox } from '../../harnessMocks';
const silentLogger = makeSilentLogger();
diff --git a/packages/harness/tests/core/events/eventId.test.ts b/packages/harness/tests/core/events/eventId.test.ts
new file mode 100644
index 000000000..5346a0adb
--- /dev/null
+++ b/packages/harness/tests/core/events/eventId.test.ts
@@ -0,0 +1,17 @@
+import { newEventId } from '../../../src/core/events/schema';
+
+describe('newEventId', () => {
+ it('is lexically monotonic within the same millisecond', () => {
+ jest.useFakeTimers();
+ try {
+ jest.setSystemTime(new Date('2026-07-29T00:00:00.000Z'));
+ const ids = [newEventId(), newEventId(), newEventId()];
+
+ expect(ids).toEqual([...ids].sort());
+ expect(new Set(ids).size).toBe(ids.length);
+ expect(ids).toEqual(ids.map(id => id.toLowerCase()));
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+});
diff --git a/packages/harness/tests/core/toOpenAIChatMessage.test.ts b/packages/harness/tests/core/llm/toOpenAIChatMessage.test.ts
similarity index 93%
rename from packages/harness/tests/core/toOpenAIChatMessage.test.ts
rename to packages/harness/tests/core/llm/toOpenAIChatMessage.test.ts
index 9d3cc0670..a02a60c10 100644
--- a/packages/harness/tests/core/toOpenAIChatMessage.test.ts
+++ b/packages/harness/tests/core/llm/toOpenAIChatMessage.test.ts
@@ -1,16 +1,16 @@
import type { ChatCompletionCreateParamsStreaming } from 'openai/resources/chat';
-import type { ILLM } from '../../src/core/llm/ILLM';
+import type { ILLM } from '../../../src/core/llm/ILLM';
import type {
ExtendedChatCompletionChunk,
InternalEnrichedAssistantMessage,
RawAssistantMessageWithUsage,
-} from '../../src/core/llm/LLMTypes';
-import { getEmptyUsage } from '../../src/core/llm/LLMTypes';
-import { ResponseFormatSchema, toOpenAIResponseFormat } from '../../src/core/llm/responseFormat';
-import { toOpenAIChatMessage } from '../../src/core/llm/toOpenAIChatMessage';
-import { AgentThread } from '../../src/core/runtime/AgentThread';
-import { NOOP_AGENT_TRACING } from '../../src/core/tracing/NoopAgentTracing';
-import { makeSilentLogger } from './harnessMocks';
+} from '../../../src/core/llm/LLMTypes';
+import { getEmptyUsage } from '../../../src/core/llm/LLMTypes';
+import { ResponseFormatSchema, toOpenAIResponseFormat } from '../../../src/core/llm/responseFormat';
+import { toOpenAIChatMessage } from '../../../src/core/llm/toOpenAIChatMessage';
+import { AgentThread } from '../../../src/core/runtime/AgentThread';
+import { NOOP_AGENT_TRACING } from '../../../src/core/tracing/NoopAgentTracing';
+import { makeSilentLogger } from '../harnessMocks';
const toolInfo = {
type: 'mcp' as const,
diff --git a/packages/harness/tests/core/connectRemoteMcp.test.ts b/packages/harness/tests/core/mcp/connectRemoteMcp.test.ts
similarity index 96%
rename from packages/harness/tests/core/connectRemoteMcp.test.ts
rename to packages/harness/tests/core/mcp/connectRemoteMcp.test.ts
index 12303f6c3..1379c5805 100644
--- a/packages/harness/tests/core/connectRemoteMcp.test.ts
+++ b/packages/harness/tests/core/mcp/connectRemoteMcp.test.ts
@@ -1,5 +1,5 @@
-import { McpConnectionError } from '../../src/core/errors';
-import { connectRemoteMcp } from '../../src/core/mcp/remoteMcpClient';
+import { McpConnectionError } from '../../../src/core/errors';
+import { connectRemoteMcp } from '../../../src/core/mcp/remoteMcpClient';
// Records every transport type client.connect() was attempted with, in order.
const mockConnectAttempts: string[] = [];
diff --git a/packages/harness/tests/core/mcpInitializeAggregation.test.ts b/packages/harness/tests/core/mcp/mcpInitializeAggregation.test.ts
similarity index 88%
rename from packages/harness/tests/core/mcpInitializeAggregation.test.ts
rename to packages/harness/tests/core/mcp/mcpInitializeAggregation.test.ts
index 9164bbb02..1b0c7844d 100644
--- a/packages/harness/tests/core/mcpInitializeAggregation.test.ts
+++ b/packages/harness/tests/core/mcp/mcpInitializeAggregation.test.ts
@@ -1,9 +1,9 @@
-import type { MCPServerInitInfo } from '../../src/core/events/schema';
-import { EventType } from '../../src/core/events/schema';
-import type { AgentToolSchema, IToolSet, ListToolsResponse } from '../../src/core/mcp/IMCPServer';
-import { convertMCPServersToTools } from '../../src/core/mcp/convertMCPServers';
-import './harnessMocks';
-import { OBJECT_INPUT_SCHEMA, makeMockIMCPServer } from './harnessMocks';
+import type { MCPServerInitInfo } from '../../../src/core/events/schema';
+import { EventType } from '../../../src/core/events/schema';
+import type { AgentToolSchema, IToolSet, ListToolsResponse } from '../../../src/core/mcp/IMCPServer';
+import { convertMCPServersToTools } from '../../../src/core/mcp/convertMCPServers';
+import '../harnessMocks';
+import { OBJECT_INPUT_SCHEMA, makeMockIMCPServer } from '../harnessMocks';
function makeServer(params: {
name: string;
diff --git a/packages/harness/tests/core/remoteMcpServer.test.ts b/packages/harness/tests/core/mcp/remoteMcpServer.test.ts
similarity index 95%
rename from packages/harness/tests/core/remoteMcpServer.test.ts
rename to packages/harness/tests/core/mcp/remoteMcpServer.test.ts
index 811b473f3..5625b7326 100644
--- a/packages/harness/tests/core/remoteMcpServer.test.ts
+++ b/packages/harness/tests/core/mcp/remoteMcpServer.test.ts
@@ -1,21 +1,21 @@
import type { Logger } from 'winston';
-import { McpConnectionError, RemoteMCP, ToolSet } from '../../src/core';
+import { McpConnectionError, RemoteMCP, ToolSet } from '../../../src/core';
import {
isApprovalRequiredResponse,
isCallToolResponseResult,
type MCPAuthRequired,
type ToolSchema,
-} from '../../src/core/mcp/IMCPServer';
-import type { RemoteMcpHeaders } from '../../src/core/mcp/RemoteMCP';
-import { connectRemoteMcp } from '../../src/core/mcp/remoteMcpClient';
-import type { ToolSelectorConfig } from '../../src/core/mcp/ToolSelectorPolicy';
-import { NOOP_AGENT_TRACING } from '../../src/core/tracing/NoopAgentTracing';
+} from '../../../src/core/mcp/IMCPServer';
+import type { RemoteMcpHeaders } from '../../../src/core/mcp/RemoteMCP';
+import { connectRemoteMcp } from '../../../src/core/mcp/remoteMcpClient';
+import type { ToolSelectorConfig } from '../../../src/core/mcp/ToolSelectorPolicy';
+import { NOOP_AGENT_TRACING } from '../../../src/core/tracing/NoopAgentTracing';
// RemoteMCP connects itself via connectRemoteMcp; mock it so the split RemoteMCP (connection) +
// ToolSet (policy) can be exercised without real networking. isSessionExpiredError stays real.
-jest.mock('../../src/core/mcp/remoteMcpClient', () => {
- const actualUnknown: unknown = jest.requireActual('../../src/core/mcp/remoteMcpClient');
- const actual = actualUnknown as typeof import('../../src/core/mcp/remoteMcpClient');
+jest.mock('../../../src/core/mcp/remoteMcpClient', () => {
+ const actualUnknown: unknown = jest.requireActual('../../../src/core/mcp/remoteMcpClient');
+ const actual = actualUnknown as typeof import('../../../src/core/mcp/remoteMcpClient');
return { __esModule: true as const, ...actual, connectRemoteMcp: jest.fn() };
});
diff --git a/packages/harness/tests/core/deferredLoading.test.ts b/packages/harness/tests/core/runtime/deferredLoading.test.ts
similarity index 83%
rename from packages/harness/tests/core/deferredLoading.test.ts
rename to packages/harness/tests/core/runtime/deferredLoading.test.ts
index 3a73c316f..15672e054 100644
--- a/packages/harness/tests/core/deferredLoading.test.ts
+++ b/packages/harness/tests/core/runtime/deferredLoading.test.ts
@@ -1,9 +1,9 @@
-import { InstructionBuilder } from '../../src/core/InstructionBuilder';
-import type { IToolSet } from '../../src/core/mcp/IMCPServer';
-import { DeferredTool } from '../../src/core/runtime/DeferredTool';
-import { NOOP_AGENT_TRACING } from '../../src/core/tracing/NoopAgentTracing';
-import './harnessMocks';
-import { makeMockIMCPServer, makeSilentLogger } from './harnessMocks';
+import { InstructionBuilder } from '../../../src/core/InstructionBuilder';
+import type { IToolSet } from '../../../src/core/mcp/IMCPServer';
+import { DeferredTool } from '../../../src/core/runtime/DeferredTool';
+import { NOOP_AGENT_TRACING } from '../../../src/core/tracing/NoopAgentTracing';
+import '../harnessMocks';
+import { makeMockIMCPServer, makeSilentLogger } from '../harnessMocks';
const DEFERRED_TOOLS_INSTRUCTION = 'deferred-tools-instructions';
diff --git a/packages/harness/tests/core/openToolCallCloser.test.ts b/packages/harness/tests/core/runtime/openToolCallCloser.test.ts
similarity index 93%
rename from packages/harness/tests/core/openToolCallCloser.test.ts
rename to packages/harness/tests/core/runtime/openToolCallCloser.test.ts
index 7c296533f..75b57b69c 100644
--- a/packages/harness/tests/core/openToolCallCloser.test.ts
+++ b/packages/harness/tests/core/runtime/openToolCallCloser.test.ts
@@ -1,7 +1,7 @@
-import type { InternalEnrichedAssistantMessage, InternalEnrichedToolCall } from '../../src/core/llm/LLMTypes';
-import type { ContextMessage } from '../../src/core/runtime/AgentThread.types';
-import { getClosableOpenToolCallIds } from '../../src/core/runtime/OpenToolCallCloser';
-import './harnessMocks';
+import type { InternalEnrichedAssistantMessage, InternalEnrichedToolCall } from '../../../src/core/llm/LLMTypes';
+import type { ContextMessage } from '../../../src/core/runtime/AgentThread.types';
+import { getClosableOpenToolCallIds } from '../../../src/core/runtime/OpenToolCallCloser';
+import '../harnessMocks';
function makeToolCall(
id: string,
diff --git a/packages/harness/tests/core/passthroughIdentity.test.ts b/packages/harness/tests/core/runtime/passthroughIdentity.test.ts
similarity index 83%
rename from packages/harness/tests/core/passthroughIdentity.test.ts
rename to packages/harness/tests/core/runtime/passthroughIdentity.test.ts
index 3fd76dee4..3ae4b2559 100644
--- a/packages/harness/tests/core/passthroughIdentity.test.ts
+++ b/packages/harness/tests/core/runtime/passthroughIdentity.test.ts
@@ -1,4 +1,4 @@
-import { InternalEventType } from '../../src/core/runtime/AgentThread.types';
+import { InternalEventType } from '../../../src/core/runtime/AgentThread.types';
describe('passthrough event identity (public harness)', () => {
it('includes PASSTHROUGH in public InternalEventType', () => {
diff --git a/packages/harness/tests/core/sendBatchTypes.compile.test.ts b/packages/harness/tests/core/runtime/sendBatchTypes.compile.test.ts
similarity index 88%
rename from packages/harness/tests/core/sendBatchTypes.compile.test.ts
rename to packages/harness/tests/core/runtime/sendBatchTypes.compile.test.ts
index 9455c8374..d8d19e755 100644
--- a/packages/harness/tests/core/sendBatchTypes.compile.test.ts
+++ b/packages/harness/tests/core/runtime/sendBatchTypes.compile.test.ts
@@ -2,10 +2,10 @@
* Compile-time ownership of public vs runtime send batches.
* Accepts the three homogeneous modes; rejects mixed pairs via @ts-expect-error.
*/
-import type { UserToolApprovalMessage, UserToolResponseMessage } from '../../src/core/events/schema';
-import type { LLMToolMessage } from '../../src/core/llm/LLMTypes';
-import type { AgentThreadRuntimeSendBatch, AgentThreadSendBatch } from '../../src/core/runtime/AgentThread.types';
-import type { AgentInputUserMessage } from '../../src/core/runtime/UserInputMessage';
+import type { UserToolApprovalMessage, UserToolResponseMessage } from '../../../src/core/events/schema';
+import type { LLMToolMessage } from '../../../src/core/llm/LLMTypes';
+import type { AgentThreadRuntimeSendBatch, AgentThreadSendBatch } from '../../../src/core/runtime/AgentThread.types';
+import type { AgentInputUserMessage } from '../../../src/core/runtime/UserInputMessage';
const userMsg = { type: 'user.message' as const, content: 'hi' } satisfies AgentInputUserMessage;
const approval = {
diff --git a/packages/harness/tests/core/unknownToolLogging.test.ts b/packages/harness/tests/core/runtime/unknownToolLogging.test.ts
similarity index 86%
rename from packages/harness/tests/core/unknownToolLogging.test.ts
rename to packages/harness/tests/core/runtime/unknownToolLogging.test.ts
index 7a737830d..5b2b27b28 100644
--- a/packages/harness/tests/core/unknownToolLogging.test.ts
+++ b/packages/harness/tests/core/runtime/unknownToolLogging.test.ts
@@ -1,11 +1,11 @@
-import type { ILLM } from '../../src/core/llm/ILLM';
-import type { ExtendedChatCompletionChunk, RawAssistantMessageWithUsage } from '../../src/core/llm/LLMTypes';
-import { getEmptyUsage } from '../../src/core/llm/LLMTypes';
-import { AgentThread } from '../../src/core/runtime/AgentThread';
-import { makeUnknownToolInfo, toToolCallInfo } from '../../src/core/runtime/contextUtils';
-import { NOOP_AGENT_TRACING } from '../../src/core/tracing/NoopAgentTracing';
-import './harnessMocks';
-import { makeSilentLogger } from './harnessMocks';
+import type { ILLM } from '../../../src/core/llm/ILLM';
+import type { ExtendedChatCompletionChunk, RawAssistantMessageWithUsage } from '../../../src/core/llm/LLMTypes';
+import { getEmptyUsage } from '../../../src/core/llm/LLMTypes';
+import { AgentThread } from '../../../src/core/runtime/AgentThread';
+import { makeUnknownToolInfo, toToolCallInfo } from '../../../src/core/runtime/contextUtils';
+import { NOOP_AGENT_TRACING } from '../../../src/core/tracing/NoopAgentTracing';
+import '../harnessMocks';
+import { makeSilentLogger } from '../harnessMocks';
const silentLogger = makeSilentLogger();
const warn = jest.spyOn(silentLogger, 'warn');
diff --git a/packages/harness/tests/core/userInputMessage.test.ts b/packages/harness/tests/core/runtime/userInputMessage.test.ts
similarity index 92%
rename from packages/harness/tests/core/userInputMessage.test.ts
rename to packages/harness/tests/core/runtime/userInputMessage.test.ts
index 23e75fe4a..8e029579f 100644
--- a/packages/harness/tests/core/userInputMessage.test.ts
+++ b/packages/harness/tests/core/runtime/userInputMessage.test.ts
@@ -1,13 +1,13 @@
-import { AgentSandboxRequiredError, InvalidAgentInputError } from '../../src/core/errors';
-import { EventType } from '../../src/core/events/schema';
+import { AgentSandboxRequiredError, InvalidAgentInputError } from '../../../src/core/errors';
+import { EventType } from '../../../src/core/events/schema';
import {
isEmptyMessageContent,
processAgentUserInput,
type AgentInputUserMessage,
type FileContentPart,
-} from '../../src/core/runtime/UserInputMessage';
-import './harnessMocks';
-import { makeStubPublicSandbox } from './harnessMocks';
+} from '../../../src/core/runtime/UserInputMessage';
+import '../harnessMocks';
+import { makeStubPublicSandbox } from '../harnessMocks';
describe('UserInputMessage validation', () => {
const sandbox = makeStubPublicSandbox();
diff --git a/packages/harness/tests/core/createSandboxProvider.test.ts b/packages/harness/tests/core/sandbox/provider/createSandboxProvider.test.ts
similarity index 91%
rename from packages/harness/tests/core/createSandboxProvider.test.ts
rename to packages/harness/tests/core/sandbox/provider/createSandboxProvider.test.ts
index ac0994b6f..4a50ce02d 100644
--- a/packages/harness/tests/core/createSandboxProvider.test.ts
+++ b/packages/harness/tests/core/sandbox/provider/createSandboxProvider.test.ts
@@ -5,9 +5,9 @@
import {
createSandboxProvider,
SandboxProviderSettingsSchema,
-} from '../../src/core/sandbox/provider/createSandboxProvider';
-import { DaytonaSandboxProvider } from '../../src/core/sandbox/provider/DaytonaProvider';
-import { makeSilentLogger } from './harnessMocks';
+} from '../../../../src/core/sandbox/provider/createSandboxProvider';
+import { DaytonaSandboxProvider } from '../../../../src/core/sandbox/provider/DaytonaProvider';
+import { makeSilentLogger } from '../../harnessMocks';
describe('SandboxProviderSettingsSchema', () => {
it('parses minimal daytona settings and applies defaults', () => {
diff --git a/packages/harness/tests/core/skillMounter.test.ts b/packages/harness/tests/core/sandbox/skills/skillMounter.test.ts
similarity index 87%
rename from packages/harness/tests/core/skillMounter.test.ts
rename to packages/harness/tests/core/sandbox/skills/skillMounter.test.ts
index 5fd8609e1..1a4988364 100644
--- a/packages/harness/tests/core/skillMounter.test.ts
+++ b/packages/harness/tests/core/sandbox/skills/skillMounter.test.ts
@@ -3,9 +3,9 @@
* init it hands to Sandbox. (Host-specific mounters, e.g. the gateway's
* TrueFoundry registry mounter, are tested in their own repo.)
*/
-import { InstructionBuilder } from '../../src/core/InstructionBuilder';
-import type { ISkillMounter } from '../../src/core/sandbox/skills/ISkillMounter';
-import { SkillMounter } from '../../src/core/sandbox/skills/SkillMounter';
+import { InstructionBuilder } from '../../../../src/core/InstructionBuilder';
+import type { ISkillMounter } from '../../../../src/core/sandbox/skills/ISkillMounter';
+import { SkillMounter } from '../../../../src/core/sandbox/skills/SkillMounter';
const GIT_SKILL = {
name: 'git-skill',
diff --git a/packages/server/jest.store.config.cjs b/packages/server/jest.store.config.cjs
new file mode 100644
index 000000000..241fb4126
--- /dev/null
+++ b/packages/server/jest.store.config.cjs
@@ -0,0 +1,27 @@
+/** @type {import('jest').Config} */
+module.exports = {
+ testEnvironment: 'node',
+ globalSetup: '<rootDir>/tests/db/session-store/globalSetup.ts',
+ transform: {
+ '^.+\\.(m?js|tsx?)$': [
+ '@swc/jest',
+ {
+ jsc: {
+ parser: { syntax: 'typescript', decorators: true, dynamicImport: true },
+ target: 'es2022',
+ },
+ module: { type: 'commonjs' },
+ },
+ ],
+ },
+ moduleNameMapper: {
+ '^(\\.{1,2}/.*)\\.js$': '$1',
+ '^@truefoundry/utils/agent-session/(.*)$': '<rootDir>/../harness/src/agent-session/$1',
+ '^@truefoundry/utils/core/(.*)$': '<rootDir>/../harness/src/core/$1',
+ },
+ transformIgnorePatterns: ['/node_modules/(?!.*kysely)'],
+ testTimeout: 120_000,
+ maxWorkers: '50%',
+ roots: ['<rootDir>/tests/db/session-store', '<rootDir>/src'],
+ testMatch: ['<rootDir>/tests/db/session-store/**/*.test.ts'],
+};
diff --git a/packages/server/package.json b/packages/server/package.json
index 4c7f2c07e..cb650cc24 100644
--- a/packages/server/package.json
+++ b/packages/server/package.json
@@ -12,6 +12,7 @@
"migrate": "tsx --env-file=.env src/db/migrate-cli.ts",
"typecheck": "tsc --noEmit",
"test": "tsx --test src/**/*.test.ts",
+ "test:store": "jest --config jest.store.config.cjs",
"start": "node dist/main.js"
},
"dependencies": {
@@ -28,8 +29,12 @@
"zod": "^3.24.3"
},
"devDependencies": {
+ "@swc/core": "^1.11.0",
+ "@swc/jest": "^0.2.37",
+ "@types/jest": "^29.5.14",
"@types/node": "^24.12.0",
"@types/pg": "^8.20.0",
+ "jest": "^29.7.0",
"tsup": "^8.5.0",
"tsx": "^4.16.2",
"typescript": "^7.0.2"
diff --git a/packages/server/src/apis/sessions.ts b/packages/server/src/apis/sessions.ts
index bbc4eed14..6f126fd7a 100644
--- a/packages/server/src/apis/sessions.ts
+++ b/packages/server/src/apis/sessions.ts
@@ -20,13 +20,13 @@ import type { McpStore } from '../store/McpStore';
import type { ModelStore } from '../store/ModelStore';
/** The server is single-tenant; every record lives under one fixed tenant scope. */
-export const TENANT_NAME = 'default';
+export const TENANT_ID = 'default';
export function toWireSession(record: SessionRecord): Session {
return {
id: record.session_id,
agent_spec: record.agent_spec,
- title: record.title ?? null,
+ title: record.title,
created_at: record.created_at,
updated_at: record.updated_at,
};
@@ -97,7 +97,7 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
: c.json({ error: { message: specError.message } }, 400);
}
const session = await deps.sessions.create({
- tenant_name: TENANT_NAME,
+ tenant_id: TENANT_ID,
session_id: ulid().toLowerCase(),
agent_spec: body.agent_spec,
});
@@ -106,7 +106,7 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
const getSessionHandler: RouteHandler<typeof getSessionRoute> = async c => {
const { sessionId } = c.req.valid('param');
- const record = await deps.sessionStore.getSession({ tenant_name: TENANT_NAME, session_id: sessionId });
+ const record = await deps.sessionStore.getSession({ tenant_id: TENANT_ID, session_id: sessionId });
if (!record) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
@@ -126,9 +126,10 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
}
try {
await deps.sessionStore.updateSession({
- tenant_name: TENANT_NAME,
+ tenant_id: TENANT_ID,
session_id: sessionId,
- ...(body.agent_spec ? { agent_spec: body.agent_spec } : {}),
+ agent_spec: body.agent_spec,
+ title: undefined,
});
} catch (error) {
if (error instanceof SessionStoreNotFoundError) {
@@ -136,7 +137,7 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
}
throw error;
}
- const record = await deps.sessionStore.getSession({ tenant_name: TENANT_NAME, session_id: sessionId });
+ const record = await deps.sessionStore.getSession({ tenant_id: TENANT_ID, session_id: sessionId });
if (!record) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
@@ -147,7 +148,7 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
const query = c.req.valid('query');
try {
const { data, pagination } = await deps.sessionStore.listSessions({
- tenant_name: TENANT_NAME,
+ tenant_id: TENANT_ID,
limit: query.limit,
order: query.order,
page_token: query.page_token,
@@ -168,7 +169,7 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
// terminal write wins).
const cancelSessionHandler: RouteHandler<typeof cancelSessionRoute> = async c => {
const { sessionId } = c.req.valid('param');
- const record = await deps.sessionStore.getSession({ tenant_name: TENANT_NAME, session_id: sessionId });
+ const record = await deps.sessionStore.getSession({ tenant_id: TENANT_ID, session_id: sessionId });
if (!record) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
@@ -185,7 +186,7 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
const listSessionEventsHandler: RouteHandler<typeof listSessionEventsRoute> = async c => {
const { sessionId } = c.req.valid('param');
const query = c.req.valid('query');
- const session = await deps.sessions.get({ tenant_name: TENANT_NAME, session_id: sessionId });
+ const session = await deps.sessions.get({ tenant_id: TENANT_ID, session_id: sessionId });
if (!session) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
diff --git a/packages/server/src/apis/turns.ts b/packages/server/src/apis/turns.ts
index 6cab054c2..b6f1bcde9 100644
--- a/packages/server/src/apis/turns.ts
+++ b/packages/server/src/apis/turns.ts
@@ -1,11 +1,12 @@
import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';
-import type { Sessions, Turn, TurnRecord, TurnStreamingEvent } from '@truefoundry/utils/agent-session';
+import type { Sessions, Turn, TurnStreamingEvent } from '@truefoundry/utils/agent-session';
import {
CancellationReason,
SessionStoreConflictError,
SessionStoreNotFoundError,
TurnResourceResolver,
type TurnInputItem,
+ type TurnRecordWithoutSnapshot,
type TurnSandboxFactory,
} from '@truefoundry/utils/agent-session';
import {
@@ -23,13 +24,13 @@ import { createAndExecuteTurnRoute, getTurnRoute, listTurnEventsRoute, listTurns
import type { ActiveTurnRegistry } from '../runtime/activeTurns';
import type { McpStore } from '../store/McpStore';
import type { ModelStore } from '../store/ModelStore';
-import { TENANT_NAME } from './sessions';
+import { TENANT_ID } from './sessions';
-function toWireTurn(record: TurnRecord): Turn {
+function toWireTurn(record: TurnRecordWithoutSnapshot): Turn {
return {
id: record.turn_id,
session_id: record.session_id,
- previous_turn_id: record.previous_turn_id ?? null,
+ previous_turn_id: record.previous_turn_id,
input: record.input,
state: record.state,
created_at: record.created_at,
@@ -125,7 +126,7 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
const listTurnsHandler: RouteHandler<typeof listTurnsRoute> = async c => {
const { sessionId } = c.req.valid('param');
const query = c.req.valid('query');
- const session = await deps.sessions.get({ tenant_name: TENANT_NAME, session_id: sessionId });
+ const session = await deps.sessions.get({ tenant_id: TENANT_ID, session_id: sessionId });
if (!session) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
@@ -145,7 +146,7 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
const getTurnHandler: RouteHandler<typeof getTurnRoute> = async c => {
const { sessionId, turnId } = c.req.valid('param');
- const session = await deps.sessions.get({ tenant_name: TENANT_NAME, session_id: sessionId });
+ const session = await deps.sessions.get({ tenant_id: TENANT_ID, session_id: sessionId });
if (!session) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
@@ -159,7 +160,7 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
const listTurnEventsHandler: RouteHandler<typeof listTurnEventsRoute> = async c => {
const { sessionId, turnId } = c.req.valid('param');
const query = c.req.valid('query');
- const session = await deps.sessions.get({ tenant_name: TENANT_NAME, session_id: sessionId });
+ const session = await deps.sessions.get({ tenant_id: TENANT_ID, session_id: sessionId });
if (!session) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
@@ -186,7 +187,7 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
const { sessionId } = c.req.valid('param');
const body = c.req.valid('json');
- const session = await deps.sessions.get({ tenant_name: TENANT_NAME, session_id: sessionId });
+ const session = await deps.sessions.get({ tenant_id: TENANT_ID, session_id: sessionId });
if (!session) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
diff --git a/packages/server/src/db/AGENTS.md b/packages/server/src/db/AGENTS.md
index f5ac3e081..4ad5a6dce 100644
--- a/packages/server/src/db/AGENTS.md
+++ b/packages/server/src/db/AGENTS.md
@@ -1,2 +1,3 @@
- Temporal columns MUST use `timestamptz` (`timestamp with time zone`). Do not use `timestamp` without time zone.
- Application timestamps MUST be treated as UTC instants. Serialize with `Date.prototype.toISOString()` (always `...Z` with milliseconds).
+- Do not run DB queries inside loops (N+1). Prefer a single batched query, a join, or an `IN`/`ANY` lookup over per-item round-trips.
diff --git a/packages/server/src/db/client.ts b/packages/server/src/db/client.ts
index 91d05dfeb..761b174f9 100644
--- a/packages/server/src/db/client.ts
+++ b/packages/server/src/db/client.ts
@@ -1,9 +1,40 @@
import { Kysely, PostgresDialect } from 'kysely';
-import { Pool } from 'pg';
+import pg, { Pool } from 'pg';
import type { Database } from './types';
+const INT8_OID = 20;
+/**
+ * Postgres OID for `bigint[]` / `_int8`. Scalar int8 parser (OID 20) does NOT cover arrays.
+ * Widened setter: node-pg's TypeId enum omits array OIDs.
+ */
+const setTypeParserByOid: (oid: number, parser: (value: string) => unknown) => void = pg.types.setTypeParser.bind(
+ pg.types,
+);
+
+/**
+ * Parse a Postgres array literal of int8 into number[].
+ * Safe below Number.MAX_SAFE_INTEGER (2^53) — same contract as the scalar int8 parser.
+ * Identity append_ids stay far below that bound.
+ */
+function parseInt8Array(value: string): number[] {
+ if (value === '{}' || value === '') {
+ return [];
+ }
+ // Plain unquoted numeric elements (bigint[] never needs quotes).
+ return value
+ .slice(1, -1)
+ .split(',')
+ .map(element => Number(element));
+}
+
+function configurePgTypeParsers(): void {
+ pg.types.setTypeParser(INT8_OID, Number);
+ setTypeParserByOid(1016, parseInt8Array);
+}
+
export function createDb(connectionString: string, poolMax: number): Kysely<Database> {
+ configurePgTypeParsers();
return new Kysely<Database>({
dialect: new PostgresDialect({
pool: new Pool({
@@ -13,3 +44,19 @@ export function createDb(connectionString: string, poolMax: number): Kysely<Data
}),
});
}
+
+/**
+ * Match Postgres errors by SQLSTATE without `instanceof DatabaseError`.
+ * instanceof breaks silently when two copies of pg-protocol load (version skew / dual CJS+ESM);
+ * checking `code` is the conventional node-postgres pattern.
+ */
+export function isPgErrorCode(err: unknown, code: string): boolean {
+ if (typeof err !== 'object' || err === null || !('code' in err)) {
+ return false;
+ }
+ return err.code === code;
+}
+
+export function isUniqueViolation(err: unknown): boolean {
+ return isPgErrorCode(err, '23505');
+}
diff --git a/packages/server/src/db/migrations/20260728_000001_session_store.ts b/packages/server/src/db/migrations/20260728_000001_session_store.ts
new file mode 100644
index 000000000..0e4505b2d
--- /dev/null
+++ b/packages/server/src/db/migrations/20260728_000001_session_store.ts
@@ -0,0 +1,246 @@
+import { sql, type Kysely } from 'kysely';
+
+/**
+ * Session-store tables (canonical DDL owner).
+ *
+ * Write-heat summary: `turn_thread` is the one deliberately-hot table with its hot
+ * columns (`context_ids`, `current_context_usage`) isolated from the pointer-carried
+ * big ones (`agent_info`, `checkpoint`); `session`, `turn`, and
+ * `thread_capability_state` take small bounded HOT-friendly updates; the two logs
+ * are pure insert. Nothing ever rewrites a large value except the array concat
+ * itself — the documented, bounded cost of the raw-array model.
+ *
+ * Column placement rule: top-level column ONLY if (a) key/query target, (b) hot
+ * write target (isolated so nothing else churns with it; typed operators), or
+ * (c) big-and-immutable (own TOAST value carried by pointer through row rewrites).
+ * Everything small/rare/descriptive inlines into a store-owned extensible
+ * `checkpoint` jsonb. `custom` is always its own column: `checkpoint` is
+ * store-owned, `custom` is caller-owned.
+ */
+export async function up(db: Kysely<unknown>): Promise<void> {
+ await db.schema
+ .createTable('session')
+ // key
+ .addColumn('tenant_id', 'text', col => col.notNull())
+ // key
+ .addColumn('session_id', 'text', col => col.notNull())
+ // top: big + immutable-in-practice (updateSession patch only);
+ // TOAST pointer rides through per-turn tip bumps untouched
+ .addColumn('agent_spec', 'jsonb', col => col.notNull())
+ // top: list-displayed, independently patched; first-write-wins
+ // (COALESCE) targets it directly
+ .addColumn('title', 'text')
+ // top: HOT — bumped once per createTurn under the session lock;
+ // tiny fixed-width column keeps the bump a cheap HOT update
+ .addColumn('last_turn_id', 'text')
+ // top: caller-owned opaque extension; never mixed with store state
+ .addColumn('custom', 'jsonb')
+ // top: hot, bumped with the tip ("activity" = turn creation)
+ .addColumn('last_activity_timestamp_ms', 'bigint', col => col.notNull())
+ // top: list ordering (indexed below)
+ .addColumn('created_at', 'timestamptz', col => col.notNull())
+ .addColumn('updated_at', 'timestamptz', col => col.notNull())
+ .addPrimaryKeyConstraint('session_pkey', ['tenant_id', 'session_id'])
+ // headroom so the per-turn bump stays HOT (no index churn)
+ .modifyEnd(sql`WITH (fillfactor = 85)`)
+ .execute();
+
+ await db.schema
+ .createIndex('session_list_idx')
+ .on('session')
+ .columns(['tenant_id', 'created_at', 'session_id'])
+ .execute();
+
+ await db.schema
+ .createTable('turn')
+ // key
+ .addColumn('tenant_id', 'text', col => col.notNull())
+ // key
+ .addColumn('session_id', 'text', col => col.notNull())
+ // key (ulid)
+ .addColumn('turn_id', 'text', col => col.notNull())
+ // top: immutable topology; filter target
+ .addColumn('first_turn_id', 'text', col => col.notNull())
+ // top: immutable topology; NULL = session's first turn
+ .addColumn('previous_turn_id', 'text')
+ // top: immutable; queried by the anchored ancestor-chain walk
+ // (spill through older turns); typed array
+ .addColumn('ancestor_ids', sql`text[]`, col => col.notNull())
+ // top: big + written once at create; TOAST pointer stable after
+ .addColumn('input', 'jsonb', col => col.notNull())
+ // top: THE fence/freeze target — every gated write predicates on
+ // state->>'status'; exactly one terminal flip per turn
+ .addColumn('state', 'jsonb', col => col.notNull())
+ // inlined: {mcp_servers, sandbox_info, ...future} — both small,
+ // patched at most once or twice per turn (resource init);
+ // extensible without migration
+ .addColumn('checkpoint', 'jsonb', col => col.notNull())
+ // top: caller-owned opaque extension
+ .addColumn('custom', 'jsonb')
+ // top: list ordering (indexed below)
+ .addColumn('created_at', 'timestamptz', col => col.notNull())
+ .addColumn('updated_at', 'timestamptz', col => col.notNull())
+ .addPrimaryKeyConstraint('turn_pkey', ['tenant_id', 'session_id', 'turn_id'])
+ // headroom for the state flip + rare checkpoint patches
+ .modifyEnd(sql`WITH (fillfactor = 85)`)
+ .execute();
+
+ await db.schema
+ .createIndex('turn_list_idx')
+ .on('turn')
+ .columns(['tenant_id', 'session_id', 'created_at', 'turn_id'])
+ .execute();
+
+ // the complete STATE of one thread at one turn
+ await db.schema
+ .createTable('turn_thread')
+ // key
+ .addColumn('tenant_id', 'text', col => col.notNull())
+ // key
+ .addColumn('session_id', 'text', col => col.notNull())
+ // key
+ .addColumn('turn_id', 'text', col => col.notNull())
+ // key
+ .addColumn('thread_id', 'text', col => col.notNull())
+ // inlined: {parent, completion, ...future} — parent: small,
+ // immutable; completion: can be big but written ONCE at
+ // thread end (rare + terminal); the hot path below never
+ // touches this jsonb
+ .addColumn('checkpoint', 'jsonb', col => col.notNull())
+ // top: big + immutable thread IDENTITY. Real data: sub-agent
+ // instructions in one working session ran 2.4–8.8KB
+ // (median 4.4KB) — always past the ~2KB TOAST threshold,
+ // so a dedicated column lets every array rewrite carry the
+ // TOAST value by pointer instead of re-serializing it.
+ // Deliberately duplicates context[0] (the task is also the
+ // thread's first user message): the log copy is
+ // conversation state and compaction may reclaim it; this
+ // copy is identity and must survive context surgery
+ // (restore re-resolves the child definition from
+ // name/model/input here). NULL for the root thread.
+ .addColumn('agent_info', 'jsonb')
+ // top: hot — set by the SAME single-statement UPDATE as the
+ // array concat (zero extra row versions; ~300B inline;
+ // byte-neutral vs stamping log rows). Kept out of
+ // checkpoint so the jsonb never rewrites on the hot path.
+ // Escape hatch: if the array ever becomes write-once
+ // (ranges / writer-filter), move this back onto
+ // thread_context_log rows (previously validated design).
+ .addColumn('current_context_usage', 'jsonb', col => col.notNull())
+ // top: THE context — log append_ids in context order. Hot
+ // concat target (`||`), typed bigint[] operator; dominant
+ // TOAST value (~8KB at 1k live messages, entire value
+ // rewritten per append batch — the accepted cost of the
+ // raw-array choice; range-encoding is the recorded shrink
+ // if measured).
+ .addColumn('context_ids', sql`bigint[]`, col => col.notNull())
+ .addColumn('updated_at', 'timestamptz', col => col.notNull())
+ .addPrimaryKeyConstraint('turn_thread_pkey', ['tenant_id', 'session_id', 'turn_id', 'thread_id'])
+ // the ONE deliberately-hot table: rewritten 5–10x while its
+ // turn runs; immutable once the turn is terminal (fence)
+ .modifyEnd(sql`WITH (fillfactor = 70)`)
+ .execute();
+
+ await db.schema
+ .createTable('session_event')
+ // key
+ .addColumn('tenant_id', 'text', col => col.notNull())
+ // key
+ .addColumn('session_id', 'text', col => col.notNull())
+ // top: every read is turn-scoped or turn-attributed (envelope)
+ .addColumn('turn_id', 'text', col => col.notNull())
+ // top/key: event.id, a process-local monotonic ULID minted when the event is
+ // created. Lexical ordering preserves the single turn writer's creation
+ // order, including events created in the same millisecond.
+ //
+ // A database auto-increment id is deliberately not used: it assigns order
+ // at persistence rather than event creation, couples the contract to
+ // Postgres, and sequence allocation across pooled connections,
+ // transactions, retries, or larger sequence caches need not represent
+ // logical event order. The event already owns a portable unique id, so
+ // a second store-generated identity would duplicate identity and make
+ // ordering backend-dependent.
+ //
+ // See https://github.com/ulid/spec#monotonicity
+ .addColumn('event_id', 'text', col => col.notNull())
+ // top: PersistedTurnEvent payload, written once
+ .addColumn('event', 'jsonb', col => col.notNull())
+ // top: copied from event.created_at (required by PersistedTurnEvent), so
+ // future time-range filters can be indexed without inspecting jsonb.
+ // Ordering still uses event_id.
+ .addColumn('created_at', 'timestamptz', col => col.notNull())
+ .addPrimaryKeyConstraint('session_event_pkey', ['tenant_id', 'session_id', 'turn_id', 'event_id'])
+ // pure INSERT → fillfactor 100
+ .execute();
+
+ // pure immutable CONTENT; no state → no checkpoint field
+ await db.schema
+ .createTable('thread_context_log')
+ // key
+ .addColumn('tenant_id', 'text', col => col.notNull())
+ // key
+ .addColumn('session_id', 'text', col => col.notNull())
+ // key
+ .addColumn('thread_id', 'text', col => col.notNull())
+ // top: THE message id — store-assigned (the delta createTurn
+ // interface killed content addressing: the store is told
+ // what's new, so no hashing/dedupe); consumed by
+ // data-modifying CTE in the same statement (RETURNING
+ // → array concat, one network call). bigint on purpose:
+ // no exhaustion (~290M years at 1k msg/s; int4 would die
+ // in months). NOT an order key: the array is the sole
+ // order authority (reads use unnest WITH ORDINALITY).
+ // Cross-statement id order is NEVER relied on for context
+ // (pool + sequence CACHE could invert it); the only id
+ // ordering used is INTRA-statement (array_agg ORDER BY
+ // append_id over one INSERT's RETURNING = VALUES order,
+ // backend-local, safe under any CACHE setting)
+ .addColumn('append_id', 'bigint', col => col.notNull().generatedAlwaysAsIdentity())
+ // top: provenance — which turn wrote the row; debugging + the
+ // future writer-filter migration; tiny; NOT used for
+ // visibility (the array is the sole visibility authority)
+ .addColumn('turn_id', 'text', col => col.notNull())
+ // top: the ContextMessage — written exactly once, never updated
+ .addColumn('body', 'jsonb', col => col.notNull())
+ // top: future indexed time filters without a table rewrite
+ .addColumn('created_at', 'timestamptz', col => col.notNull())
+ .addPrimaryKeyConstraint('thread_context_log_pkey', ['tenant_id', 'session_id', 'thread_id', 'append_id'])
+ // pure INSERT → default fillfactor 100, zero dead tuples;
+ // cleanup is whole-session delete only
+ .execute();
+
+ // PER-TURN KV snapshot, latest-wins per (turn, thread, key)
+ await db.schema
+ .createTable('thread_capability_state')
+ // key
+ .addColumn('tenant_id', 'text', col => col.notNull())
+ // key
+ .addColumn('session_id', 'text', col => col.notNull())
+ // key: capability history is PER TURN — fork/restore from any
+ // turn must see the map AS OF that turn, and a frozen
+ // turn's map must never change under it. (A cross-turn
+ // latest-wins PK was tried and REVERTED for exactly the
+ // fork reason.)
+ .addColumn('turn_id', 'text', col => col.notNull())
+ // key
+ .addColumn('thread_id', 'text', col => col.notNull())
+ // key: capability state key; `tfy.` prefix reserved
+ .addColumn('key', 'text', col => col.notNull())
+ // top: the value IS the row — JsonValue (undefined banned at
+ // the harness boundary); NULL = explicitly cleared
+ .addColumn('state', 'jsonb')
+ .addColumn('updated_at', 'timestamptz', col => col.notNull())
+ .addPrimaryKeyConstraint('thread_capability_state_pkey', ['tenant_id', 'session_id', 'turn_id', 'thread_id', 'key'])
+ // single-statement fenced upsert per CAPABILITY_STATE event
+ .modifyEnd(sql`WITH (fillfactor = 85)`)
+ .execute();
+}
+
+export async function down(db: Kysely<unknown>): Promise<void> {
+ await db.schema.dropTable('thread_capability_state').ifExists().cascade().execute();
+ await db.schema.dropTable('thread_context_log').ifExists().cascade().execute();
+ await db.schema.dropTable('session_event').ifExists().cascade().execute();
+ await db.schema.dropTable('turn_thread').ifExists().cascade().execute();
+ await db.schema.dropTable('turn').ifExists().cascade().execute();
+ await db.schema.dropTable('session').ifExists().cascade().execute();
+}
diff --git a/packages/server/src/db/session-store/PostgresSessionStore.ts b/packages/server/src/db/session-store/PostgresSessionStore.ts
new file mode 100644
index 000000000..c2581a42b
--- /dev/null
+++ b/packages/server/src/db/session-store/PostgresSessionStore.ts
@@ -0,0 +1,209 @@
+import type { SessionRecord } from '@truefoundry/utils/agent-session/models/SessionRecord';
+import type { TurnRecord } from '@truefoundry/utils/agent-session/models/TurnRecord';
+import type { PersistedTurnEvent, SessionEventItem } from '@truefoundry/utils/agent-session/schemas/events';
+import type { TokenPagination } from '@truefoundry/utils/agent-session/schemas/pagination';
+import type {
+ AddThreadsInput,
+ AppendToEventsInput,
+ AppendToThreadContextInput,
+ CreateSessionInput,
+ CreateTurnInput,
+ FreezeAndGetTurnInput,
+ GetSessionInput,
+ GetTurnInput,
+ ISessionStore,
+ ListSessionEventsInput,
+ ListSessionsInput,
+ ListTurnEventsInput,
+ ListTurnsInput,
+ OverwriteThreadContextInput,
+ PatchMCPServersInput,
+ PatchSandboxInfoInput,
+ PatchThreadCapabilityStateInput,
+ RemoveThreadsInput,
+ TurnRecordWithoutSnapshot,
+ UpdateSessionInput,
+ UpdateTurnStateInput,
+} from '@truefoundry/utils/agent-session/store/ISessionStore';
+import { decodeOffsetPageToken, encodeOffsetPageToken } from '@truefoundry/utils/agent-session/store/OffsetPageToken';
+import type { Kysely } from 'kysely';
+import type { Database } from '../types';
+import { patchThreadCapabilityState as patchThreadCapabilityStateQuery } from './queries/capabilities';
+import {
+ appendToEvents as appendToEventsQuery,
+ listSessionEvents as listSessionEventsQuery,
+ listTurnEvents as listTurnEventsQuery,
+} from './queries/events';
+import {
+ createSession as createSessionQuery,
+ getSession as getSessionQuery,
+ listSessions as listSessionsQuery,
+ updateSession as updateSessionQuery,
+} from './queries/sessions';
+import {
+ addThreads as addThreadsQuery,
+ appendToThreadContext as appendToThreadContextQuery,
+ overwriteThreadContext as overwriteThreadContextQuery,
+ patchMCPServers as patchMCPServersQuery,
+ patchSandboxInfo as patchSandboxInfoQuery,
+ removeThreads as removeThreadsQuery,
+} from './queries/threads';
+import type { NewThreadRegistration } from './queries/turns';
+import {
+ createTurn as createTurnQuery,
+ freezeAndGetTurn as freezeAndGetTurnQuery,
+ getTurn as getTurnQuery,
+ listTurns as listTurnsQuery,
+ updateTurnState as updateTurnStateQuery,
+} from './queries/turns';
+
+type SessionCustom = Record<string, never>;
+type TurnCustom = Record<string, never>;
+
+/**
+ * ## Design: append-only context log + per-turn id arrays
+ *
+ * Message bodies live in `thread_context_log`, append-only, written exactly
+ * once; ids are store-assigned (`append_id` identity — the delta createTurn
+ * interface tells the store what's new, so identity needs no hashing).
+ * A turn's context per thread is `turn_thread.context_ids` — the explicit
+ * ordered array of log ids. Turns share no mutable structure: linear
+ * continuation and fork are the same pointer-copy (`parent_array || new_ids`),
+ * overwrite replaces the array, and a still-running ancestor's late appends
+ * touch only its OWN rows — structural leaks are impossible by construction.
+ *
+ * Hard invariants (violations proven by failing tests during prototyping —
+ * see the freeze/fence tests):
+ * 1. Only the session tip can be running. `createTurn` rejects a running
+ * previous turn; callers must `freezeAndGetTurn` first (barge-in IS the
+ * cancellation of the predecessor).
+ * 2. Every turn-scoped write is fenced on `state->>'status' = 'running'`.
+ * 3. Terminal turns are IMMUTABLE — a terminal read is a final read.
+ */
+export class PostgresSessionStore implements ISessionStore<SessionCustom, TurnCustom> {
+ constructor(private readonly db: Kysely<Database>) {}
+
+ createSession(input: CreateSessionInput<SessionCustom>): Promise<void> {
+ return createSessionQuery(this.db, input);
+ }
+
+ getSession(input: GetSessionInput): Promise<SessionRecord<SessionCustom> | undefined> {
+ return getSessionQuery(this.db, input);
+ }
+
+ updateSession(input: UpdateSessionInput<SessionCustom>): Promise<void> {
+ return updateSessionQuery(this.db, input);
+ }
+
+ async listSessions(
+ input: ListSessionsInput,
+ ): Promise<{ data: SessionRecord<SessionCustom>[]; pagination: TokenPagination }> {
+ const result = await listSessionsQuery(this.db, input);
+ return {
+ data: result.data,
+ pagination: {
+ limit: input.limit,
+ ...result.pagination,
+ },
+ };
+ }
+
+ async createTurn(input: CreateTurnInput<TurnCustom>): Promise<void> {
+ await createTurnQuery(this.db, {
+ tenant_id: input.tenant_id,
+ session_id: input.turn.session_id,
+ turn: {
+ turn_id: input.turn.turn_id,
+ first_turn_id: input.turn.first_turn_id,
+ previous_turn_id: input.turn.previous_turn_id,
+ ancestor_ids: input.turn.ancestor_ids,
+ input: input.turn.input,
+ state: input.turn.state,
+ custom: input.turn.custom,
+ },
+ new_threads: input.new_threads.map((thread): NewThreadRegistration => ({
+ thread_id: thread.thread_id,
+ parent: thread.parent,
+ agent_info: thread.agent_info,
+ })),
+ new_context_appends: input.new_context_appends,
+ capability_states: input.capability_states,
+ last_activity_timestamp_ms: Date.now(),
+ update_session_title_if_not_exist: input.update_session_title_if_not_exist,
+ mcp_servers: null,
+ sandbox_info: null,
+ });
+ }
+
+ freezeAndGetTurn(input: FreezeAndGetTurnInput): Promise<TurnRecord<TurnCustom>> {
+ return freezeAndGetTurnQuery(this.db, input);
+ }
+
+ getTurn(input: GetTurnInput): Promise<TurnRecord<TurnCustom> | undefined> {
+ return getTurnQuery(this.db, input);
+ }
+
+ async listTurns(
+ input: ListTurnsInput,
+ ): Promise<{ data: TurnRecordWithoutSnapshot<TurnCustom>[]; pagination: TokenPagination }> {
+ const offset = decodeOffsetPageToken(input.page_token);
+ const result = await listTurnsQuery(this.db, {
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ limit: input.limit,
+ offset,
+ });
+ const pagination: TokenPagination = { limit: input.limit };
+ if (result.next_offset !== null) {
+ pagination.next_page_token = encodeOffsetPageToken(result.next_offset);
+ }
+ if (offset > 0) {
+ pagination.previous_page_token = encodeOffsetPageToken(Math.max(0, offset - input.limit));
+ }
+ return { data: result.turns, pagination };
+ }
+
+ updateTurnState(input: UpdateTurnStateInput): Promise<void> {
+ return updateTurnStateQuery(this.db, input);
+ }
+
+ appendToEvents(input: AppendToEventsInput): Promise<void> {
+ return appendToEventsQuery(this.db, input);
+ }
+
+ addThreads(input: AddThreadsInput): Promise<void> {
+ return addThreadsQuery(this.db, input);
+ }
+
+ removeThreads(input: RemoveThreadsInput): Promise<void> {
+ return removeThreadsQuery(this.db, input);
+ }
+
+ appendToThreadContext(input: AppendToThreadContextInput): Promise<void> {
+ return appendToThreadContextQuery(this.db, input);
+ }
+
+ overwriteThreadContext(input: OverwriteThreadContextInput): Promise<void> {
+ return overwriteThreadContextQuery(this.db, input);
+ }
+
+ patchMCPServers(input: PatchMCPServersInput): Promise<void> {
+ return patchMCPServersQuery(this.db, input);
+ }
+
+ patchSandboxInfo(input: PatchSandboxInfoInput): Promise<void> {
+ return patchSandboxInfoQuery(this.db, input);
+ }
+
+ patchThreadCapabilityState(input: PatchThreadCapabilityStateInput): Promise<void> {
+ return patchThreadCapabilityStateQuery(this.db, input);
+ }
+
+ listTurnEvents(input: ListTurnEventsInput): Promise<{ data: PersistedTurnEvent[]; pagination: TokenPagination }> {
+ return listTurnEventsQuery(this.db, input);
+ }
+
+ listSessionEvents(input: ListSessionEventsInput): Promise<{ data: SessionEventItem[]; pagination: TokenPagination }> {
+ return listSessionEventsQuery(this.db, input);
+ }
+}
diff --git a/packages/server/src/db/session-store/queries/capabilities.ts b/packages/server/src/db/session-store/queries/capabilities.ts
new file mode 100644
index 000000000..0da20e81c
--- /dev/null
+++ b/packages/server/src/db/session-store/queries/capabilities.ts
@@ -0,0 +1,51 @@
+import type { PatchThreadCapabilityStateInput } from '@truefoundry/utils/agent-session/store/ISessionStore';
+import { sql, type Kysely } from 'kysely';
+import type { Database } from '../../types';
+import { json, values } from '../sqlExpressions';
+import { classifyTurnFenceWriteFailure, turnRunningFence } from './turns';
+
+/**
+ * patchThreadCapabilityState — single-statement fenced upsert on the PER-TURN PK;
+ * does NOT bump turn.updated_at.
+ */
+export async function patchThreadCapabilityState(
+ db: Kysely<Database>,
+ input: PatchThreadCapabilityStateInput,
+): Promise<void> {
+ const keys = {
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ turn_id: input.turn_id,
+ };
+
+ const rows = await db
+ .with('turn_fence', qb => turnRunningFence(qb, keys))
+ .insertInto('thread_capability_state')
+ .columns(['tenant_id', 'session_id', 'turn_id', 'thread_id', 'key', 'state', 'updated_at'])
+ .expression(eb =>
+ eb
+ .selectFrom(values([{ one: 1 }], 'src'))
+ .select([
+ sql<string>`${input.tenant_id}`.as('tenant_id'),
+ sql<string>`${input.session_id}`.as('session_id'),
+ sql<string>`${input.turn_id}`.as('turn_id'),
+ sql<string>`${input.thread_id}`.as('thread_id'),
+ sql<string>`${input.key}`.as('key'),
+ json(input.state).as('state'),
+ sql<Date>`now()`.as('updated_at'),
+ ])
+ .where(wb => wb.exists(wb.selectFrom('turn_fence').select(sql`1`.as('one')))),
+ )
+ .onConflict(oc =>
+ oc.columns(['tenant_id', 'session_id', 'turn_id', 'thread_id', 'key']).doUpdateSet({
+ state: sql`excluded.state`,
+ updated_at: sql`now()`,
+ }),
+ )
+ .returning('thread_id')
+ .execute();
+
+ if (rows.length === 0) {
+ await classifyTurnFenceWriteFailure(db, keys);
+ }
+}
diff --git a/packages/server/src/db/session-store/queries/events.ts b/packages/server/src/db/session-store/queries/events.ts
new file mode 100644
index 000000000..9f18dc4ed
--- /dev/null
+++ b/packages/server/src/db/session-store/queries/events.ts
@@ -0,0 +1,192 @@
+import type { PersistedTurnEvent, SessionEventItem } from '@truefoundry/utils/agent-session/schemas/events';
+import type { TokenPagination } from '@truefoundry/utils/agent-session/schemas/pagination';
+import type {
+ AppendToEventsInput,
+ ListSessionEventsInput,
+ ListTurnEventsInput,
+} from '@truefoundry/utils/agent-session/store/ISessionStore';
+import { decodeOffsetPageToken, paginateOffsetRows } from '@truefoundry/utils/agent-session/store/OffsetPageToken';
+import {
+ decodeSessionEventPageToken,
+ paginateSessionEventRows,
+ type SessionEventPageCursor,
+} from '@truefoundry/utils/agent-session/store/SessionEventPageToken';
+import { SessionNotFoundError, TurnNotFoundError } from '@truefoundry/utils/agent-session/store/SessionStoreErrors';
+import type { Kysely } from 'kysely';
+import { sql } from 'kysely';
+import type { Database } from '../../types';
+import { json, unnestWithOrdinality, values } from '../sqlExpressions';
+import { classifyTurnFenceWriteFailure, turnRunningFence } from './turns';
+
+export async function appendToEvents(db: Kysely<Database>, input: AppendToEventsInput): Promise<void> {
+ if (input.events.length === 0) return;
+
+ const keys = {
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ turn_id: input.turn_id,
+ };
+
+ const eventRows = input.events.map(event => ({
+ event_id: event.id,
+ event: json(event),
+ // VALUES parameters default to text; cast the event's required timestamp.
+ created_at: sql<Date>`${event.created_at}::timestamptz`,
+ }));
+
+ const inserted = await db
+ .with('turn_fence', qb => turnRunningFence(qb, keys))
+ .insertInto('session_event')
+ .columns(['tenant_id', 'session_id', 'turn_id', 'event_id', 'event', 'created_at'])
+ .expression(eb =>
+ eb
+ .selectFrom(values(eventRows, 'ev'))
+ .select([
+ sql<string>`${input.tenant_id}`.as('tenant_id'),
+ sql<string>`${input.session_id}`.as('session_id'),
+ sql<string>`${input.turn_id}`.as('turn_id'),
+ 'ev.event_id',
+ 'ev.event',
+ 'ev.created_at',
+ ])
+ .where(wb => wb.exists(wb.selectFrom('turn_fence').select(sql`1`.as('one')))),
+ )
+ .returning('event_id')
+ .execute();
+
+ if (inserted.length === 0) {
+ await classifyTurnFenceWriteFailure(db, keys);
+ }
+}
+
+export async function listTurnEvents(
+ db: Kysely<Database>,
+ input: ListTurnEventsInput,
+): Promise<{ data: PersistedTurnEvent[]; pagination: TokenPagination }> {
+ const offset = decodeOffsetPageToken(input.page_token);
+ const limit = input.limit;
+ const order = input.order ?? 'asc';
+
+ const turnExists = await db
+ .selectFrom('turn')
+ .select('turn_id')
+ .where('tenant_id', '=', input.tenant_id)
+ .where('session_id', '=', input.session_id)
+ .where('turn_id', '=', input.turn_id)
+ .executeTakeFirst();
+ if (!turnExists) {
+ throw new TurnNotFoundError(input.turn_id);
+ }
+
+ const query = db
+ .selectFrom('session_event')
+ .select(['event'])
+ .where('tenant_id', '=', input.tenant_id)
+ .where('session_id', '=', input.session_id)
+ .where('turn_id', '=', input.turn_id)
+ .orderBy('event_id', order === 'desc' ? 'desc' : 'asc')
+ .limit(limit + 1)
+ .offset(offset);
+
+ const rows = await query.execute();
+ const page = paginateOffsetRows(
+ rows.map(r => r.event),
+ limit,
+ offset,
+ );
+ return page;
+}
+
+export async function listSessionEvents(
+ db: Kysely<Database>,
+ input: ListSessionEventsInput,
+): Promise<{ data: SessionEventItem[]; pagination: TokenPagination }> {
+ const limit = input.limit;
+
+ const session = await db
+ .selectFrom('session')
+ .select('last_turn_id')
+ .where('tenant_id', '=', input.tenant_id)
+ .where('session_id', '=', input.session_id)
+ .executeTakeFirst();
+ if (!session) {
+ throw new SessionNotFoundError(input.session_id);
+ }
+
+ const decodedCursor = input.page_token === undefined ? undefined : decodeSessionEventPageToken(input.page_token);
+ const lastTurnId = decodedCursor?.last_turn_id ?? input.last_turn_id ?? session.last_turn_id;
+ if (lastTurnId === null) {
+ return { data: [], pagination: { limit } };
+ }
+ const cursor: SessionEventPageCursor = {
+ last_turn_id: lastTurnId,
+ offset: decodedCursor?.offset ?? 0,
+ };
+
+ const anchor = await db
+ .selectFrom('turn')
+ .select(['turn_id', 'ancestor_ids'])
+ .where('tenant_id', '=', input.tenant_id)
+ .where('session_id', '=', input.session_id)
+ .where('turn_id', '=', cursor.last_turn_id)
+ .executeTakeFirst();
+ if (!anchor) {
+ throw new TurnNotFoundError(cursor.last_turn_id);
+ }
+
+ const chainIds = await resolveAncestorChain(db, input.tenant_id, input.session_id, anchor);
+ const rows = await db
+ .selectFrom(unnestWithOrdinality(chainIds, 'c'))
+ .innerJoin('session_event as e', join =>
+ join
+ .on('e.tenant_id', '=', input.tenant_id)
+ .on('e.session_id', '=', input.session_id)
+ .onRef('e.turn_id', '=', 'c.turn_id'),
+ )
+ .select(['e.turn_id as turn_id', 'e.event as event'])
+ .orderBy('c.pos', 'desc')
+ .orderBy('e.event_id', 'desc')
+ .limit(limit + 1)
+ .offset(cursor.offset)
+ .execute();
+
+ return paginateSessionEventRows(rows, limit, cursor);
+}
+
+/** Anchor turn fields needed for chain resolution. */
+export interface AnchorTurn {
+ turn_id: string;
+ ancestor_ids: string[];
+}
+
+/**
+ * Full chain (oldest first, anchor last). `ancestor_ids` may be only the
+ * previous N ancestors, so spill through the oldest ancestor's own window
+ * until a root or gap. A missing turn or repeated id ends the walk.
+ */
+export async function resolveAncestorChain(
+ db: Kysely<Database>,
+ tenant: string,
+ sessionId: string,
+ anchor: AnchorTurn,
+): Promise<string[]> {
+ const chain = [...anchor.ancestor_ids, anchor.turn_id];
+ const seen = new Set(chain);
+ let oldestId = chain[0];
+ while (oldestId && oldestId !== anchor.turn_id) {
+ const oldest = await db
+ .selectFrom('turn')
+ .select(['ancestor_ids'])
+ .where('tenant_id', '=', tenant)
+ .where('session_id', '=', sessionId)
+ .where('turn_id', '=', oldestId)
+ .executeTakeFirst();
+ if (!oldest) break;
+ const older = oldest.ancestor_ids.filter(id => !seen.has(id));
+ if (older.length === 0) break;
+ chain.unshift(...older);
+ for (const id of older) seen.add(id);
+ oldestId = older[0];
+ }
+ return chain;
+}
diff --git a/packages/server/src/db/session-store/queries/sessions.ts b/packages/server/src/db/session-store/queries/sessions.ts
new file mode 100644
index 000000000..5f1ecb6b0
--- /dev/null
+++ b/packages/server/src/db/session-store/queries/sessions.ts
@@ -0,0 +1,182 @@
+import type { SessionRecord } from '@truefoundry/utils/agent-session/models/SessionRecord';
+import type {
+ CreateSessionInput,
+ GetSessionInput,
+ ListSessionsInput,
+ UpdateSessionInput,
+} from '@truefoundry/utils/agent-session/store/ISessionStore';
+import { decodeOffsetPageToken, paginateOffsetRows } from '@truefoundry/utils/agent-session/store/OffsetPageToken';
+import {
+ SessionAlreadyExistsError,
+ SessionNotFoundError,
+ SessionStoreInvariantError,
+} from '@truefoundry/utils/agent-session/store/SessionStoreErrors';
+import { sql, type Kysely } from 'kysely';
+import type { Database } from '../../types';
+import { json } from '../sqlExpressions';
+
+function isPgUniqueViolation(error: unknown): boolean {
+ if (typeof error !== 'object' || error === null) {
+ return false;
+ }
+ if (!('code' in error)) {
+ return false;
+ }
+ return error.code === '23505';
+}
+
+type SessionCustom = Record<string, never>;
+type ProtoSessionRecord = SessionRecord<SessionCustom>;
+
+function isEmptyCustomRecord(value: Record<string, unknown>): value is SessionCustom {
+ return Object.keys(value).length === 0;
+}
+
+function parseSessionCustom(value: Record<string, unknown> | null): SessionCustom | null {
+ if (value === null) {
+ return null;
+ }
+ if (!isEmptyCustomRecord(value)) {
+ throw new SessionStoreInvariantError('non-empty session custom is not supported');
+ }
+ return value;
+}
+
+function mapRowToSessionRecord(row: {
+ tenant_id: string;
+ session_id: string;
+ agent_spec: ProtoSessionRecord['agent_spec'];
+ title: string | null;
+ last_turn_id: string | null;
+ custom: Record<string, unknown> | null;
+ created_at: Date;
+ updated_at: Date;
+ last_activity_timestamp_ms: number;
+}): ProtoSessionRecord {
+ return {
+ tenant_id: row.tenant_id,
+ session_id: row.session_id,
+ agent_spec: row.agent_spec,
+ title: row.title,
+ last_turn_id: row.last_turn_id,
+ custom: parseSessionCustom(row.custom),
+ created_at: row.created_at.toISOString(),
+ updated_at: row.updated_at.toISOString(),
+ last_activity_timestamp_ms: row.last_activity_timestamp_ms,
+ };
+}
+
+export async function createSession(db: Kysely<Database>, input: CreateSessionInput<SessionCustom>): Promise<void> {
+ const nowMs = Date.now();
+
+ try {
+ await db
+ .insertInto('session')
+ .values({
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ agent_spec: json(input.agent_spec),
+ title: null,
+ custom: input.custom !== null ? json(input.custom) : null,
+ created_at: new Date(nowMs),
+ updated_at: new Date(nowMs),
+ last_activity_timestamp_ms: nowMs,
+ })
+ .execute();
+ } catch (error) {
+ if (isPgUniqueViolation(error)) {
+ throw new SessionAlreadyExistsError(input.session_id);
+ }
+ throw error;
+ }
+}
+
+export async function getSession(
+ db: Kysely<Database>,
+ input: GetSessionInput,
+): Promise<ProtoSessionRecord | undefined> {
+ const row = await db
+ .selectFrom('session')
+ .selectAll()
+ .where('tenant_id', '=', input.tenant_id)
+ .where('session_id', '=', input.session_id)
+ .executeTakeFirst();
+
+ if (row === undefined) {
+ return undefined;
+ }
+
+ return mapRowToSessionRecord(row);
+}
+
+export async function updateSession(db: Kysely<Database>, input: UpdateSessionInput<SessionCustom>): Promise<void> {
+ const agentSpec = input.agent_spec;
+ const title = input.title;
+
+ const result = await db
+ .updateTable('session')
+ .set({
+ updated_at: sql<Date>`now()`,
+ last_activity_timestamp_ms: Date.now(),
+ })
+ .$if(agentSpec !== undefined, qb => {
+ if (agentSpec === undefined) {
+ return qb;
+ }
+ return qb.set({ agent_spec: json(agentSpec) });
+ })
+ .$if(title !== undefined, qb => {
+ if (title === undefined) {
+ return qb;
+ }
+ return qb.set({ title });
+ })
+ .where('tenant_id', '=', input.tenant_id)
+ .where('session_id', '=', input.session_id)
+ .executeTakeFirst();
+
+ const numUpdatedRows = Number(result.numUpdatedRows);
+ if (numUpdatedRows === 0) {
+ throw new SessionNotFoundError(input.session_id);
+ }
+}
+
+export async function listSessions(
+ db: Kysely<Database>,
+ input: ListSessionsInput,
+): Promise<{
+ data: ProtoSessionRecord[];
+ pagination: { next_page_token?: string | undefined; previous_page_token?: string | undefined };
+}> {
+ const limit = input.limit;
+ const offset = decodeOffsetPageToken(input.page_token);
+
+ const order = input.order ?? 'desc';
+
+ let query = db.selectFrom('session').selectAll().where('tenant_id', '=', input.tenant_id);
+
+ if (input.start_timestamp !== undefined) {
+ query = query.where('created_at', '>=', new Date(input.start_timestamp));
+ }
+ if (input.end_timestamp !== undefined) {
+ query = query.where('created_at', '<=', new Date(input.end_timestamp));
+ }
+
+ if (order === 'asc') {
+ query = query.orderBy('created_at', 'asc').orderBy('session_id', 'asc');
+ } else {
+ query = query.orderBy('created_at', 'desc').orderBy('session_id', 'desc');
+ }
+
+ const rows = await query
+ .limit(limit + 1)
+ .offset(offset)
+ .execute();
+
+ const { data, pagination } = paginateOffsetRows(rows, limit, offset);
+
+ return {
+ data: data.map(mapRowToSessionRecord),
+ pagination,
+ };
+}
diff --git a/packages/server/src/db/session-store/queries/threads.ts b/packages/server/src/db/session-store/queries/threads.ts
new file mode 100644
index 000000000..fac1684d2
--- /dev/null
+++ b/packages/server/src/db/session-store/queries/threads.ts
@@ -0,0 +1,419 @@
+import type {
+ AddThreadsInput,
+ AppendToThreadContextInput,
+ OverwriteThreadContextInput,
+ PatchMCPServersInput,
+ PatchSandboxInfoInput,
+ RemoveThreadsInput,
+} from '@truefoundry/utils/agent-session/store/ISessionStore';
+import type { JsonValue } from '@truefoundry/utils/core/capabilities/AgentCapability';
+import type { AgentInfo } from '@truefoundry/utils/core/events/schema';
+import type { CompletionUsage } from '@truefoundry/utils/core/llm/LLMTypes';
+import type { ContextMessage, SubAgentCompletionMarker } from '@truefoundry/utils/core/runtime/AgentThread.types';
+import { sql, type Kysely, type RawBuilder, type Transaction } from 'kysely';
+import type { Database, TurnThreadCheckpoint } from '../../types';
+import { json, jsonbSet, values } from '../sqlExpressions';
+import {
+ assertTurnRunning,
+ classifyTurnFenceWriteFailure,
+ classifyTurnThreadWriteFailure,
+ turnRunningFence,
+ type TurnKeys,
+} from './turns';
+
+type DbOrTrx = Kysely<Database> | Transaction<Database>;
+
+interface CapabilityStateInsertRow {
+ tenant_id: string;
+ session_id: string;
+ turn_id: string;
+ thread_id: string;
+ key: string;
+ state: RawBuilder<JsonValue>;
+ updated_at: RawBuilder<Date>;
+}
+
+/**
+ * addThreads — fenced tx, max 3 batched statements: log INSERT, turn_thread INSERT,
+ * capability upsert. No turn.checkpoint touch (threads live in turn_thread).
+ */
+export async function addThreads(db: Kysely<Database>, input: AddThreadsInput): Promise<void> {
+ await db.transaction().execute(async trx => {
+ await assertTurnRunning(trx, {
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ turn_id: input.turn_id,
+ });
+
+ const now = new Date();
+ const logRows: {
+ tenant_id: string;
+ session_id: string;
+ thread_id: string;
+ turn_id: string;
+ body: RawBuilder<ContextMessage>;
+ created_at: Date;
+ }[] = [];
+ const capabilityStateRows: CapabilityStateInsertRow[] = [];
+ const turnThreadPlans: {
+ thread_id: string;
+ checkpoint: TurnThreadCheckpoint;
+ agent_info: RawBuilder<AgentInfo> | null;
+ current_context_usage: CompletionUsage;
+ }[] = [];
+
+ for (const thread of input.threads) {
+ const threadCheckpoint: TurnThreadCheckpoint = {
+ parent: thread.parent ?? null,
+ completion: thread.completion ?? null,
+ };
+ turnThreadPlans.push({
+ thread_id: thread.thread_id,
+ checkpoint: threadCheckpoint,
+ agent_info: thread.agent_info != null ? json(thread.agent_info) : null,
+ current_context_usage: thread.current_context_usage,
+ });
+
+ for (const body of thread.context) {
+ logRows.push({
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ thread_id: thread.thread_id,
+ turn_id: input.turn_id,
+ body: json(body),
+ created_at: now,
+ });
+ }
+
+ const capabilityState = thread.capability_state;
+ if (capabilityState != null) {
+ for (const key of Object.keys(capabilityState)) {
+ const state = capabilityState[key];
+ if (state === undefined) {
+ throw new Error(
+ `capability_state['${key}'] for thread '${thread.thread_id}' is undefined — undefined is banned from capability state`,
+ );
+ }
+ capabilityStateRows.push({
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ turn_id: input.turn_id,
+ thread_id: thread.thread_id,
+ key,
+ state: json(state),
+ updated_at: sql<Date>`now()`,
+ });
+ }
+ }
+ }
+
+ const newIdsByThread = new Map<string, number[]>();
+ if (logRows.length > 0) {
+ const inserted = await trx
+ .insertInto('thread_context_log')
+ .values(logRows)
+ .returning(['thread_id', 'append_id'])
+ .execute();
+ for (const row of inserted) {
+ const list = newIdsByThread.get(row.thread_id);
+ if (list === undefined) {
+ newIdsByThread.set(row.thread_id, [row.append_id]);
+ } else {
+ list.push(row.append_id);
+ }
+ }
+ }
+
+ const turnThreadRows = turnThreadPlans.map(plan => ({
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ turn_id: input.turn_id,
+ thread_id: plan.thread_id,
+ checkpoint: plan.checkpoint,
+ agent_info: plan.agent_info,
+ current_context_usage: plan.current_context_usage,
+ context_ids: newIdsByThread.get(plan.thread_id) ?? [],
+ updated_at: now,
+ }));
+
+ if (turnThreadRows.length > 0) {
+ await trx.insertInto('turn_thread').values(turnThreadRows).execute();
+ }
+
+ if (capabilityStateRows.length > 0) {
+ await trx.insertInto('thread_capability_state').values(capabilityStateRows).execute();
+ }
+ });
+}
+
+/**
+ * removeThreads — fenced tx: DELETE this turn's turn_thread rows + this turn's
+ * capability rows. Older turns keep their per-turn maps. Log rows stay
+ * (ancestor arrays reference them).
+ */
+export async function removeThreads(db: Kysely<Database>, input: RemoveThreadsInput): Promise<void> {
+ await db.transaction().execute(async trx => {
+ await assertTurnRunning(trx, {
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ turn_id: input.turn_id,
+ });
+
+ if (input.thread_ids.length === 0) {
+ return;
+ }
+
+ await trx
+ .deleteFrom('turn_thread')
+ .where('tenant_id', '=', input.tenant_id)
+ .where('session_id', '=', input.session_id)
+ .where('turn_id', '=', input.turn_id)
+ .where('thread_id', 'in', input.thread_ids)
+ .execute();
+
+ await trx
+ .deleteFrom('thread_capability_state')
+ .where('tenant_id', '=', input.tenant_id)
+ .where('session_id', '=', input.session_id)
+ .where('turn_id', '=', input.turn_id)
+ .where('thread_id', 'in', input.thread_ids)
+ .execute();
+ });
+}
+
+function completionPatchExpr(completion: SubAgentCompletionMarker | null): RawBuilder<TurnThreadCheckpoint> {
+ if (completion === null) {
+ return sql<TurnThreadCheckpoint>`checkpoint`;
+ }
+ return jsonbSet<TurnThreadCheckpoint>(sql`checkpoint`, sql`'{completion}'`, json(completion));
+}
+
+function usageSetExpr(usage: CompletionUsage | null): RawBuilder<CompletionUsage> {
+ if (usage === null) {
+ return sql`current_context_usage`;
+ }
+ // COALESCE matches the plan sketch: provided usage wins, else keep column.
+ return sql`coalesce(${json(usage)}, current_context_usage)`;
+}
+
+async function fencedTurnThreadContextUpdate(
+ db: Kysely<Database>,
+ args: {
+ keys: TurnKeys;
+ thread_id: string;
+ context: ContextMessage[];
+ replace_array: boolean;
+ current_context_usage: CompletionUsage | null;
+ completion: SubAgentCompletionMarker | null;
+ /** When replace_array, usage is set unconditionally (overwrite contract). */
+ usage_unconditional: CompletionUsage | null;
+ },
+): Promise<void> {
+ const { keys, thread_id, context, replace_array } = args;
+
+ if (context.length === 0) {
+ // No log INSERT — still fence + patch usage/completion / clear-or-keep array.
+ const emptyResult = await db
+ .with('turn_fence', qb => turnRunningFence(qb, keys))
+ .updateTable('turn_thread')
+ .set({
+ context_ids: replace_array ? sql<number[]>`'{}'::bigint[]` : sql<number[]>`context_ids`,
+ current_context_usage: args.usage_unconditional ?? usageSetExpr(args.current_context_usage),
+ checkpoint: completionPatchExpr(args.completion),
+ updated_at: sql`now()`,
+ })
+ .where('tenant_id', '=', keys.tenant_id)
+ .where('session_id', '=', keys.session_id)
+ .where('turn_id', '=', keys.turn_id)
+ .where('thread_id', '=', thread_id)
+ .where(sql<boolean>`EXISTS (SELECT 1 FROM turn_fence)`)
+ .executeTakeFirst();
+
+ if (Number(emptyResult.numUpdatedRows) === 0) {
+ await classifyTurnThreadWriteFailure(db, keys, thread_id);
+ }
+ return;
+ }
+
+ const bodyRows = context.map((body, index) => ({
+ ord: sql<number>`${index + 1}::int`,
+ body: json(body),
+ }));
+
+ const arrayExpr: RawBuilder<number[]> = replace_array
+ ? sql<number[]>`coalesce((SELECT array_agg(append_id ORDER BY append_id) FROM new_rows), '{}'::bigint[])`
+ : sql<
+ number[]
+ >`context_ids || coalesce((SELECT array_agg(append_id ORDER BY append_id) FROM new_rows), '{}'::bigint[])`;
+
+ const result = await db
+ .with('turn_fence', qb => turnRunningFence(qb, keys))
+ .with('new_rows', qb =>
+ qb
+ .insertInto('thread_context_log')
+ .columns(['tenant_id', 'session_id', 'thread_id', 'turn_id', 'body', 'created_at'])
+ .expression(eb =>
+ eb
+ .selectFrom(values(bodyRows, 'b'))
+ .select([
+ sql<string>`${keys.tenant_id}`.as('tenant_id'),
+ sql<string>`${keys.session_id}`.as('session_id'),
+ sql<string>`${thread_id}`.as('thread_id'),
+ sql<string>`${keys.turn_id}`.as('turn_id'),
+ 'b.body',
+ sql<Date>`now()`.as('created_at'),
+ ])
+ .where(wb => wb.exists(wb.selectFrom('turn_fence').select(sql`1`.as('one'))))
+ .orderBy('b.ord'),
+ )
+ .returning('append_id'),
+ )
+ .updateTable('turn_thread')
+ .set({
+ context_ids: arrayExpr,
+ current_context_usage: args.usage_unconditional ?? usageSetExpr(args.current_context_usage),
+ checkpoint: completionPatchExpr(args.completion),
+ updated_at: sql`now()`,
+ })
+ .where('tenant_id', '=', keys.tenant_id)
+ .where('session_id', '=', keys.session_id)
+ .where('turn_id', '=', keys.turn_id)
+ .where('thread_id', '=', thread_id)
+ .where(sql<boolean>`EXISTS (SELECT 1 FROM turn_fence)`)
+ .executeTakeFirst();
+
+ if (Number(result.numUpdatedRows) === 0) {
+ await classifyTurnThreadWriteFailure(db, keys, thread_id);
+ }
+}
+
+/**
+ * appendToThreadContext — ONE fenced statement: CTE inserts log rows, outer UPDATE
+ * concats their ids, stamps usage (COALESCE), and patches completion on the same
+ * turn_thread row version.
+ */
+export async function appendToThreadContext(db: Kysely<Database>, input: AppendToThreadContextInput): Promise<void> {
+ await fencedTurnThreadContextUpdate(db, {
+ keys: {
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ turn_id: input.turn_id,
+ },
+ thread_id: input.thread_id,
+ context: input.context,
+ replace_array: false,
+ current_context_usage: input.current_context_usage,
+ completion: input.completion,
+ usage_unconditional: null,
+ });
+}
+
+/**
+ * overwriteThreadContext — same one-statement shape; context_ids is REPLACED.
+ * Old log rows stay — ancestor turns' arrays reference them. No lineage minting.
+ */
+export async function overwriteThreadContext(db: Kysely<Database>, input: OverwriteThreadContextInput): Promise<void> {
+ await fencedTurnThreadContextUpdate(db, {
+ keys: {
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ turn_id: input.turn_id,
+ },
+ thread_id: input.event.thread_id,
+ context: input.event.context,
+ replace_array: true,
+ current_context_usage: null,
+ completion: null,
+ usage_unconditional: input.event.current_context_usage,
+ });
+}
+
+/**
+ * patchMCPServers — one-shot conditional UPDATE on the fence row itself
+ * (`state->>'status' = 'running'`). No separate FOR SHARE fence CTE.
+ * Subscript LHS + expression RHS for shallow merge by server id.
+ */
+export async function patchMCPServers(db: Kysely<Database>, input: PatchMCPServersInput): Promise<void> {
+ const serversById: Record<string, (typeof input.mcp_servers)[number]> = {};
+ for (const server of input.mcp_servers) {
+ serversById[server.id] = server;
+ }
+
+ const keys: TurnKeys = {
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ turn_id: input.turn_id,
+ };
+
+ const result = await db
+ .updateTable('turn')
+ .set(
+ sql`checkpoint['mcp_servers']`,
+ sql`(CASE WHEN jsonb_typeof(checkpoint->'mcp_servers') = 'object'
+ THEN checkpoint->'mcp_servers'
+ ELSE '{}'::jsonb END) || ${json(serversById)}`,
+ )
+ .set({ updated_at: sql`now()` })
+ .where('tenant_id', '=', keys.tenant_id)
+ .where('session_id', '=', keys.session_id)
+ .where('turn_id', '=', keys.turn_id)
+ .where(sql<boolean>`state->>'status' = 'running'`)
+ .executeTakeFirst();
+
+ if (Number(result.numUpdatedRows) === 0) {
+ await classifyTurnFenceWriteFailure(db, keys);
+ }
+}
+
+/**
+ * patchSandboxInfo — one-shot conditional UPDATE on the fence row itself
+ * (`state->>'status' = 'running'`). LWW replace via subscript assignment.
+ */
+export async function patchSandboxInfo(db: Kysely<Database>, input: PatchSandboxInfoInput): Promise<void> {
+ const keys: TurnKeys = {
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ turn_id: input.turn_id,
+ };
+
+ const result = await db
+ .updateTable('turn')
+ .set(sql`checkpoint['sandbox_info']`, json(input.sandbox_info))
+ .set({ updated_at: sql`now()` })
+ .where('tenant_id', '=', keys.tenant_id)
+ .where('session_id', '=', keys.session_id)
+ .where('turn_id', '=', keys.turn_id)
+ .where(sql<boolean>`state->>'status' = 'running'`)
+ .executeTakeFirst();
+
+ if (Number(result.numUpdatedRows) === 0) {
+ await classifyTurnFenceWriteFailure(db, keys);
+ }
+}
+
+/** Test helper: read a turn_thread row. */
+export async function getTurnThread(
+ db: DbOrTrx,
+ tenant_id: string,
+ session_id: string,
+ turn_id: string,
+ thread_id: string,
+): Promise<
+ | {
+ thread_id: string;
+ checkpoint: TurnThreadCheckpoint;
+ agent_info: unknown;
+ current_context_usage: CompletionUsage;
+ context_ids: number[];
+ }
+ | undefined
+> {
+ return await db
+ .selectFrom('turn_thread')
+ .select(['thread_id', 'checkpoint', 'agent_info', 'current_context_usage', 'context_ids'])
+ .where('tenant_id', '=', tenant_id)
+ .where('session_id', '=', session_id)
+ .where('turn_id', '=', turn_id)
+ .where('thread_id', '=', thread_id)
+ .executeTakeFirst();
+}
diff --git a/packages/server/src/db/session-store/queries/turns.ts b/packages/server/src/db/session-store/queries/turns.ts
new file mode 100644
index 000000000..22d582a8f
--- /dev/null
+++ b/packages/server/src/db/session-store/queries/turns.ts
@@ -0,0 +1,779 @@
+import type { TurnRecord, TurnSnapshot } from '@truefoundry/utils/agent-session/models/TurnRecord';
+import {
+ CancellationReason,
+ type TerminalTurnState,
+ type TurnInputItem,
+ type TurnState,
+} from '@truefoundry/utils/agent-session/schemas/turn';
+import type {
+ FreezeAndGetTurnInput,
+ TurnRecordWithoutSnapshot,
+ UpdateTurnStateInput,
+} from '@truefoundry/utils/agent-session/store/ISessionStore';
+import {
+ PreviousTurnRunningError,
+ SessionNotFoundError,
+ SessionStoreConflictError,
+ SessionStoreInvariantError,
+ SessionStoreNotFoundError,
+ TurnAlreadyExistsError,
+ TurnNotFoundError,
+ TurnNotRunningError,
+} from '@truefoundry/utils/agent-session/store/SessionStoreErrors';
+import type { CapabilityState, JsonValue } from '@truefoundry/utils/core/capabilities/AgentCapability';
+import type { AgentInfo, AgentParent, MCPServerInitInfo } from '@truefoundry/utils/core/events/schema';
+import type { CompletionUsage } from '@truefoundry/utils/core/llm/LLMTypes';
+import { getEmptyUsage } from '@truefoundry/utils/core/llm/LLMTypes';
+import type { AgentThreadSnapshot, ContextMessage } from '@truefoundry/utils/core/runtime/AgentThread.types';
+import type { SandboxInfo } from '@truefoundry/utils/core/sandbox/Sandbox';
+import { sql, type Kysely, type QueryCreator, type RawBuilder, type Transaction } from 'kysely';
+import { isUniqueViolation } from '../../client';
+import type { Database, TurnCheckpoint, TurnThreadCheckpoint } from '../../types';
+import { json, lateralUnnestBigintArrayWithOrdinality } from '../sqlExpressions';
+
+type TurnCustom = Record<string, never>;
+
+function isEmptyCustomRecord(value: Record<string, unknown>): value is TurnCustom {
+ return Object.keys(value).length === 0;
+}
+
+function parseTurnCustom(value: Record<string, unknown> | null): TurnCustom | null {
+ if (value === null) {
+ return null;
+ }
+ if (!isEmptyCustomRecord(value)) {
+ throw new SessionStoreInvariantError('non-empty turn custom is not supported');
+ }
+ return value;
+}
+
+/** New thread metadata; mutable per-turn data arrives through dedicated fields. */
+export interface NewThreadRegistration {
+ thread_id: string;
+ parent: AgentParent | null;
+ agent_info: AgentInfo | null;
+}
+
+export interface TurnKeys {
+ tenant_id: string;
+ session_id: string;
+ turn_id: string;
+}
+
+export interface NewContextAppend {
+ thread_id: string;
+ context: ContextMessage[];
+ current_context_usage: CompletionUsage | null;
+}
+
+export interface CreateTurnTurnFields {
+ turn_id: string;
+ first_turn_id: string;
+ previous_turn_id: string | null;
+ ancestor_ids: string[];
+ input: TurnInputItem[];
+ state: TurnState;
+ custom: Record<string, unknown> | null;
+}
+
+export interface CreateTurnInput {
+ tenant_id: string;
+ session_id: string;
+ turn: CreateTurnTurnFields;
+ new_threads: NewThreadRegistration[];
+ new_context_appends: NewContextAppend[];
+ capability_states: {
+ thread_id: string;
+ capability_state: CapabilityState | null;
+ }[];
+ last_activity_timestamp_ms: number;
+ update_session_title_if_not_exist: string | null;
+ mcp_servers: Record<string, MCPServerInitInfo> | null;
+ sandbox_info: SandboxInfo | null;
+}
+
+export interface GetTurnInput {
+ tenant_id: string;
+ session_id: string;
+ turn_id: string;
+}
+
+export interface ListTurnsInput {
+ tenant_id: string;
+ session_id: string;
+ limit: number;
+ offset: number;
+}
+
+export interface ListTurnsResult {
+ turns: TurnRecordWithoutSnapshot<TurnCustom>[];
+ next_offset: number | null;
+}
+
+type DbOrTrx = Kysely<Database> | Transaction<Database>;
+type TurnFenceDb = DbOrTrx | QueryCreator<Database>;
+
+function terminalTurnState(state: TurnState, turn_id: string): TerminalTurnState {
+ switch (state.status) {
+ case 'running':
+ throw new SessionStoreInvariantError(`expected terminal state for turn ${turn_id}, got running`);
+ case 'done':
+ case 'cancelled':
+ case 'error':
+ return state;
+ }
+}
+
+/**
+ * Locking CTE body for single-statement turn-scoped writes: fence + write in one
+ * network call. Under READ COMMITTED, FOR SHARE re-checks the predicate after a
+ * lock wait, so a committed freeze empties the fence and the write inserts 0 rows;
+ * error classification happens on that rare 0-row path.
+ *
+ * Multi-statement turn-scoped writes use {@link assertTurnRunning} instead.
+ */
+export function turnRunningFence(db: TurnFenceDb, keys: TurnKeys) {
+ return db
+ .selectFrom('turn')
+ .select(sql`1`.as('one'))
+ .where('tenant_id', '=', keys.tenant_id)
+ .where('session_id', '=', keys.session_id)
+ .where('turn_id', '=', keys.turn_id)
+ .where(sql`state->>'status'`, '=', 'running')
+ .forShare();
+}
+
+/** Classify a 0-row fenced write: missing turn vs frozen/non-running turn. */
+export async function classifyTurnFenceWriteFailure(db: Kysely<Database>, keys: TurnKeys): Promise<never> {
+ const row = await db
+ .selectFrom('turn')
+ .select('state')
+ .where('tenant_id', '=', keys.tenant_id)
+ .where('session_id', '=', keys.session_id)
+ .where('turn_id', '=', keys.turn_id)
+ .executeTakeFirst();
+
+ if (!row) {
+ throw new TurnNotFoundError(keys.turn_id);
+ }
+ throw new TurnNotRunningError(keys.turn_id, terminalTurnState(row.state, keys.turn_id));
+}
+
+/**
+ * Classify a 0-row fenced turn_thread UPDATE: turn missing/terminal vs thread row missing.
+ */
+export async function classifyTurnThreadWriteFailure(
+ db: Kysely<Database>,
+ keys: TurnKeys,
+ thread_id: string,
+): Promise<never> {
+ const row = await db
+ .selectFrom('turn')
+ .select('state')
+ .where('tenant_id', '=', keys.tenant_id)
+ .where('session_id', '=', keys.session_id)
+ .where('turn_id', '=', keys.turn_id)
+ .executeTakeFirst();
+
+ if (!row) {
+ throw new TurnNotFoundError(keys.turn_id);
+ }
+ if (row.state.status !== 'running') {
+ throw new TurnNotRunningError(keys.turn_id, terminalTurnState(row.state, keys.turn_id));
+ }
+ throw new SessionStoreInvariantError(`thread ${thread_id} not found in turn ${keys.turn_id}`);
+}
+
+export async function assertTurnRunning(db: DbOrTrx, keys: TurnKeys): Promise<void> {
+ // SELECT ... FOR SHARE serializes against freezeAndGetTurn's state UPDATE.
+ const row = await db
+ .selectFrom('turn')
+ .select('state')
+ .where('tenant_id', '=', keys.tenant_id)
+ .where('session_id', '=', keys.session_id)
+ .where('turn_id', '=', keys.turn_id)
+ .forShare()
+ .executeTakeFirst();
+
+ if (!row) {
+ throw new TurnNotFoundError(keys.turn_id);
+ }
+ if (row.state.status !== 'running') {
+ throw new TurnNotRunningError(keys.turn_id, terminalTurnState(row.state, keys.turn_id));
+ }
+}
+
+interface CapabilityAggRow {
+ thread_id: string;
+ capability_state: Record<string, JsonValue> | null;
+}
+
+async function assembleTurnRecord(
+ db: DbOrTrx,
+ args: { tenant_id: string; session_id: string; turn_id: string },
+): Promise<TurnRecord<TurnCustom> | undefined> {
+ const turn = await db
+ .selectFrom('turn')
+ .selectAll()
+ .where('tenant_id', '=', args.tenant_id)
+ .where('session_id', '=', args.session_id)
+ .where('turn_id', '=', args.turn_id)
+ .executeTakeFirst();
+
+ if (!turn) return undefined;
+
+ // LEFT JOIN LATERAL unnest so empty-context threads still appear; LEFT JOIN log
+ // because a null lateral append_id (empty array) must not drop the turn_thread row.
+ const contextRows = await db
+ .selectFrom('turn_thread as tt')
+ .leftJoin(lateralUnnestBigintArrayWithOrdinality(sql<number[]>`tt.context_ids`, 'c'), join => join.onTrue())
+ .leftJoin('thread_context_log as l', join =>
+ join
+ .on('l.tenant_id', '=', args.tenant_id)
+ .on('l.session_id', '=', args.session_id)
+ .onRef('l.thread_id', '=', 'tt.thread_id')
+ .onRef('l.append_id', '=', 'c.append_id'),
+ )
+ .select(['tt.thread_id', 'tt.checkpoint', 'tt.agent_info', 'tt.current_context_usage', 'l.body', 'c.pos'])
+ .where('tt.tenant_id', '=', args.tenant_id)
+ .where('tt.session_id', '=', args.session_id)
+ .where('tt.turn_id', '=', args.turn_id)
+ .orderBy('tt.thread_id')
+ .orderBy('c.pos')
+ .execute();
+
+ const capabilityRows: CapabilityAggRow[] = await db
+ .selectFrom('thread_capability_state')
+ .select(['thread_id', sql<Record<string, JsonValue> | null>`jsonb_object_agg(key, state)`.as('capability_state')])
+ .where('tenant_id', '=', args.tenant_id)
+ .where('session_id', '=', args.session_id)
+ .where('turn_id', '=', args.turn_id)
+ .groupBy('thread_id')
+ .execute();
+
+ const capabilityByThread = new Map<string, Record<string, JsonValue>>();
+ for (const row of capabilityRows) {
+ if (row.capability_state !== null) {
+ capabilityByThread.set(row.thread_id, row.capability_state);
+ }
+ }
+
+ const threads: Record<string, AgentThreadSnapshot> = {};
+ const orderedBodies = new Map<string, ContextMessage[]>();
+ const threadMeta = new Map<
+ string,
+ {
+ checkpoint: TurnThreadCheckpoint;
+ agent_info: AgentInfo | null;
+ current_context_usage: CompletionUsage;
+ }
+ >();
+
+ for (const row of contextRows) {
+ if (!threadMeta.has(row.thread_id)) {
+ threadMeta.set(row.thread_id, {
+ checkpoint: row.checkpoint,
+ agent_info: row.agent_info,
+ current_context_usage: row.current_context_usage,
+ });
+ orderedBodies.set(row.thread_id, []);
+ }
+ if (row.body !== null) {
+ const bodies = orderedBodies.get(row.thread_id);
+ if (bodies !== undefined) {
+ bodies.push(row.body);
+ }
+ }
+ }
+
+ for (const [threadId, meta] of threadMeta) {
+ const context = orderedBodies.get(threadId) ?? [];
+ const capability_state = capabilityByThread.get(threadId) ?? null;
+
+ const snap: AgentThreadSnapshot = {
+ thread_id: threadId,
+ context,
+ current_context_usage: meta.current_context_usage,
+ parent: meta.checkpoint.parent,
+ agent_info: meta.agent_info,
+ completion: meta.checkpoint.completion,
+ capability_state,
+ };
+ threads[threadId] = snap;
+ }
+
+ const checkpoint: TurnCheckpoint = turn.checkpoint;
+ const snapshot: TurnSnapshot = {
+ threads,
+ mcp_servers: checkpoint.mcp_servers,
+ sandbox_info: checkpoint.sandbox_info,
+ };
+
+ return {
+ turn_id: turn.turn_id,
+ session_id: turn.session_id,
+ first_turn_id: turn.first_turn_id,
+ ancestor_ids: turn.ancestor_ids,
+ previous_turn_id: turn.previous_turn_id,
+ state: turn.state,
+ input: turn.input,
+ snapshot,
+ created_at: turn.created_at.toISOString(),
+ updated_at: turn.updated_at.toISOString(),
+ custom: parseTurnCustom(turn.custom),
+ };
+}
+
+interface TurnInsertValues {
+ tenant_id: string;
+ session_id: string;
+ turn_id: string;
+ first_turn_id: string;
+ previous_turn_id: string | null;
+ ancestor_ids: string[];
+ input: RawBuilder<CreateTurnInput['turn']['input']>;
+ state: CreateTurnInput['turn']['state'];
+ checkpoint: TurnCheckpoint;
+ custom: RawBuilder<Record<string, unknown>> | null;
+ created_at: Date;
+ updated_at: Date;
+}
+
+interface LogInsertRow {
+ tenant_id: string;
+ session_id: string;
+ thread_id: string;
+ turn_id: string;
+ body: RawBuilder<ContextMessage>;
+ created_at: Date;
+}
+
+interface TurnThreadInsertRow {
+ tenant_id: string;
+ session_id: string;
+ turn_id: string;
+ thread_id: string;
+ checkpoint: TurnThreadCheckpoint;
+ agent_info: RawBuilder<AgentInfo> | null;
+ current_context_usage: CompletionUsage;
+ context_ids: number[];
+ updated_at: Date;
+}
+
+interface CapabilityStateInsertRow {
+ tenant_id: string;
+ session_id: string;
+ turn_id: string;
+ thread_id: string;
+ key: string;
+ state: RawBuilder<JsonValue>;
+ updated_at: Date;
+}
+
+/**
+ * createTurn — READ COMMITTED tx. Fork and linear are THE SAME pointer-copy path:
+ * child turn_thread rows copy the parent's arrays and concat new append ids.
+ * Tip bump uses SELECT ... FOR UPDATE then UPDATE (safe on PG17; the one-statement
+ * CTE tip-bump is PROVEN UNSAFE under EvalPlanQual — a blocked second writer gets
+ * the stale pre-commit tip because the CTE keeps the statement snapshot).
+ */
+export async function createTurn(db: Kysely<Database>, input: CreateTurnInput): Promise<void> {
+ try {
+ await db.transaction().execute(async trx => {
+ // step1: lock session tip, bump. Two statements on purpose — see PROVEN-UNSAFE-CTE note above.
+ const locked = await trx
+ .selectFrom('session')
+ .select(['last_turn_id'])
+ .where('tenant_id', '=', input.tenant_id)
+ .where('session_id', '=', input.session_id)
+ .forUpdate()
+ .executeTakeFirst();
+
+ if (!locked) throw new SessionNotFoundError(input.session_id);
+
+ await trx
+ .updateTable('session')
+ .set({
+ last_turn_id: input.turn.turn_id,
+ updated_at: sql`now()`,
+ last_activity_timestamp_ms: input.last_activity_timestamp_ms,
+ ...(input.update_session_title_if_not_exist !== null
+ ? {
+ title: sql`COALESCE(title, ${input.update_session_title_if_not_exist})`,
+ }
+ : {}),
+ })
+ .where('tenant_id', '=', input.tenant_id)
+ .where('session_id', '=', input.session_id)
+ .execute();
+
+ const prevTurnId = input.turn.previous_turn_id;
+
+ // step2: previous turn state + its turn_thread rows (pointer-copy source).
+ let prevCheckpoint: TurnCheckpoint | null = null;
+ const prevThreadRows: {
+ thread_id: string;
+ checkpoint: TurnThreadCheckpoint;
+ agent_info: AgentInfo | null;
+ current_context_usage: CompletionUsage;
+ context_ids: number[];
+ }[] = [];
+
+ if (prevTurnId != null) {
+ // One round-trip: previous turn metadata + its turn_thread rows.
+ // Unknown previous_turn_id is allowed (relaxed): treat as no inheritance.
+ const prevRows = await trx
+ .selectFrom('turn as t')
+ .leftJoin('turn_thread as tt', join =>
+ join
+ .onRef('tt.tenant_id', '=', 't.tenant_id')
+ .onRef('tt.session_id', '=', 't.session_id')
+ .onRef('tt.turn_id', '=', 't.turn_id'),
+ )
+ .select([
+ 't.checkpoint as turn_checkpoint',
+ 't.state as turn_state',
+ 'tt.thread_id',
+ 'tt.checkpoint as thread_checkpoint',
+ 'tt.agent_info',
+ 'tt.current_context_usage',
+ 'tt.context_ids',
+ ])
+ .where('t.tenant_id', '=', input.tenant_id)
+ .where('t.session_id', '=', input.session_id)
+ .where('t.turn_id', '=', prevTurnId)
+ .execute();
+
+ const first = prevRows[0];
+ if (first !== undefined) {
+ if (first.turn_state.status === 'running') {
+ throw new PreviousTurnRunningError(prevTurnId);
+ }
+ prevCheckpoint = first.turn_checkpoint;
+
+ for (const row of prevRows) {
+ if (row.thread_id === null) continue;
+ if (row.thread_checkpoint === null || row.current_context_usage === null || row.context_ids === null) {
+ throw new SessionStoreInvariantError(`previous turn_thread row for ${row.thread_id} is incomplete`);
+ }
+ prevThreadRows.push({
+ thread_id: row.thread_id,
+ checkpoint: row.thread_checkpoint,
+ agent_info: row.agent_info,
+ current_context_usage: row.current_context_usage,
+ context_ids: row.context_ids,
+ });
+ }
+ }
+ }
+
+ const newThreadIds = new Set(input.new_threads.map(t => t.thread_id));
+ for (const nt of input.new_threads) {
+ if (prevThreadRows.some(p => p.thread_id === nt.thread_id)) {
+ throw new SessionStoreInvariantError(
+ `new_threads must only contain threads absent on the previous turn; thread '${nt.thread_id}' already exists`,
+ );
+ }
+ }
+
+ const knownThreadIds = new Set([...prevThreadRows.map(r => r.thread_id), ...newThreadIds]);
+ for (const append of input.new_context_appends) {
+ if (!knownThreadIds.has(append.thread_id)) {
+ throw new SessionStoreInvariantError(`new_context_appends references unknown thread ${append.thread_id}`);
+ }
+ }
+
+ const checkpoint: TurnCheckpoint = {
+ mcp_servers: input.mcp_servers ?? prevCheckpoint?.mcp_servers ?? null,
+ sandbox_info: input.sandbox_info ?? prevCheckpoint?.sandbox_info ?? null,
+ };
+
+ const now = new Date();
+
+ const turnCustom = input.turn.custom ?? null;
+
+ // step3: turn row
+ const turnValues: TurnInsertValues = {
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ turn_id: input.turn.turn_id,
+ first_turn_id: input.turn.first_turn_id,
+ previous_turn_id: input.turn.previous_turn_id ?? null,
+ ancestor_ids: input.turn.ancestor_ids,
+ input: json(input.turn.input),
+ state: input.turn.state,
+ checkpoint,
+ custom: turnCustom !== null ? json(turnCustom) : null,
+ created_at: now,
+ updated_at: now,
+ };
+ await trx.insertInto('turn').values(turnValues).execute();
+
+ // step4: new_context_appends bodies; RETURNING feeds the arrays app-side.
+ const logRows: LogInsertRow[] = [];
+ for (const append of input.new_context_appends) {
+ for (const body of append.context) {
+ logRows.push({
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ thread_id: append.thread_id,
+ turn_id: input.turn.turn_id,
+ body: json(body),
+ created_at: now,
+ });
+ }
+ }
+
+ const newIdsByThread = new Map<string, number[]>();
+ if (logRows.length > 0) {
+ const inserted = await trx
+ .insertInto('thread_context_log')
+ .values(logRows)
+ .returning(['thread_id', 'append_id'])
+ .execute();
+ for (const row of inserted) {
+ const list = newIdsByThread.get(row.thread_id);
+ if (list === undefined) {
+ newIdsByThread.set(row.thread_id, [row.append_id]);
+ } else {
+ list.push(row.append_id);
+ }
+ }
+ }
+
+ const appendUsageByThread = new Map<string, CompletionUsage>();
+ for (const append of input.new_context_appends) {
+ if (append.current_context_usage !== null) {
+ appendUsageByThread.set(append.thread_id, append.current_context_usage);
+ }
+ }
+
+ // step5: child turn_thread rows — carried = parent || new ids; new = fresh row.
+ const turnThreadRows: TurnThreadInsertRow[] = [];
+
+ for (const parent of prevThreadRows) {
+ const newIds = newIdsByThread.get(parent.thread_id) ?? [];
+ const usage = appendUsageByThread.get(parent.thread_id) ?? parent.current_context_usage;
+ turnThreadRows.push({
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ turn_id: input.turn.turn_id,
+ thread_id: parent.thread_id,
+ checkpoint: parent.checkpoint,
+ agent_info: parent.agent_info !== null ? json(parent.agent_info) : null,
+ current_context_usage: usage,
+ context_ids: parent.context_ids.concat(newIds),
+ updated_at: now,
+ });
+ }
+
+ for (const nt of input.new_threads) {
+ const newIds = newIdsByThread.get(nt.thread_id) ?? [];
+ const usage = appendUsageByThread.get(nt.thread_id) ?? getEmptyUsage();
+ const threadCheckpoint: TurnThreadCheckpoint = {
+ parent: nt.parent,
+ completion: null,
+ };
+ turnThreadRows.push({
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ turn_id: input.turn.turn_id,
+ thread_id: nt.thread_id,
+ checkpoint: threadCheckpoint,
+ agent_info: nt.agent_info !== null ? json(nt.agent_info) : null,
+ current_context_usage: usage,
+ context_ids: newIds,
+ updated_at: now,
+ });
+ }
+
+ if (turnThreadRows.length > 0) {
+ await trx.insertInto('turn_thread').values(turnThreadRows).execute();
+ }
+
+ // Complete per-turn capability maps are supplied by the caller. Persist
+ // them directly; copying parent rows only to replace them is wasted work.
+ const seenCapabilityThreads = new Set<string>();
+ const capabilityStateRows: CapabilityStateInsertRow[] = [];
+ for (const capability of input.capability_states) {
+ if (!knownThreadIds.has(capability.thread_id)) {
+ throw new SessionStoreInvariantError(`capability_states references unknown thread ${capability.thread_id}`);
+ }
+ if (seenCapabilityThreads.has(capability.thread_id)) {
+ throw new SessionStoreInvariantError(`capability_states contains duplicate thread ${capability.thread_id}`);
+ }
+ seenCapabilityThreads.add(capability.thread_id);
+
+ if (capability.capability_state === null) continue;
+ for (const [key, state] of Object.entries(capability.capability_state)) {
+ capabilityStateRows.push({
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ turn_id: input.turn.turn_id,
+ thread_id: capability.thread_id,
+ key,
+ state: json(state),
+ updated_at: now,
+ });
+ }
+ }
+
+ for (const threadId of knownThreadIds) {
+ if (!seenCapabilityThreads.has(threadId)) {
+ throw new SessionStoreInvariantError(`capability_states is missing thread ${threadId}`);
+ }
+ }
+
+ if (capabilityStateRows.length > 0) {
+ await trx.insertInto('thread_capability_state').values(capabilityStateRows).execute();
+ }
+ });
+ } catch (err) {
+ if (err instanceof SessionStoreNotFoundError || err instanceof SessionStoreConflictError) throw err;
+ if (isUniqueViolation(err)) throw new TurnAlreadyExistsError(input.turn.turn_id);
+ throw err;
+ }
+}
+
+/**
+ * freezeAndGetTurn — cancel if still running (fencing future writes), then return the record.
+ * Terminal turns are returned unchanged (freeze is a plain read).
+ */
+export async function freezeAndGetTurn(db: Kysely<Database>, input: FreezeAndGetTurnInput): Promise<TurnRecord> {
+ return await db.transaction().execute(async trx => {
+ const cancelledState: TerminalTurnState = {
+ status: 'cancelled',
+ reason: CancellationReason.CancelledForNextTurn,
+ completed_at: new Date().toISOString(),
+ };
+
+ // UPDATE waits for in-flight turn-scoped writes (FOR SHARE on this row) to
+ // commit; assembly below then includes every committed straggler.
+ const updateResult = await trx
+ .updateTable('turn')
+ .set({
+ state: cancelledState,
+ updated_at: sql`now()`,
+ })
+ .where('tenant_id', '=', input.tenant_id)
+ .where('session_id', '=', input.session_id)
+ .where('turn_id', '=', input.turn_id)
+ .where(sql<boolean>`state->>'status' = 'running'`)
+ .executeTakeFirst();
+
+ if (Number(updateResult.numUpdatedRows) > 0) {
+ await trx
+ .insertInto('session_event')
+ .values({
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ turn_id: input.turn_id,
+ event_id: input.turn_done_event.id,
+ event: json(input.turn_done_event),
+ created_at: new Date(input.turn_done_event.created_at),
+ })
+ .execute();
+ }
+
+ const record = await assembleTurnRecord(trx, input);
+ if (!record) throw new TurnNotFoundError(input.turn_id);
+ return record;
+ });
+}
+
+/**
+ * getTurn — read-only REPEATABLE READ tx.
+ * Concurrent appends after the first SELECT are invisible to later SELECTs in the same tx.
+ */
+export async function getTurn(db: Kysely<Database>, input: GetTurnInput): Promise<TurnRecord<TurnCustom> | undefined> {
+ return await db
+ .transaction()
+ .setIsolationLevel('repeatable read')
+ .execute(async trx => {
+ return assembleTurnRecord(trx, input);
+ });
+}
+
+/**
+ * listTurns — ORDER BY created_at, turn_id; LIMIT limit+1 OFFSET offset; numeric-offset tokens.
+ * Returns turn rows only (no snapshot assembly); use getTurn for full TurnRecord.
+ */
+export async function listTurns(db: Kysely<Database>, input: ListTurnsInput): Promise<ListTurnsResult> {
+ const rows = await db
+ .selectFrom('turn')
+ .selectAll()
+ .where('tenant_id', '=', input.tenant_id)
+ .where('session_id', '=', input.session_id)
+ .orderBy('created_at', 'asc')
+ .orderBy('turn_id', 'asc')
+ .limit(input.limit + 1)
+ .offset(input.offset)
+ .execute();
+
+ const hasMore = rows.length > input.limit;
+ const page = hasMore ? rows.slice(0, input.limit) : rows;
+
+ const turns: TurnRecordWithoutSnapshot<TurnCustom>[] = page.map(row => ({
+ turn_id: row.turn_id,
+ session_id: row.session_id,
+ first_turn_id: row.first_turn_id,
+ ancestor_ids: row.ancestor_ids,
+ previous_turn_id: row.previous_turn_id,
+ state: row.state,
+ input: row.input,
+ created_at: row.created_at.toISOString(),
+ updated_at: row.updated_at.toISOString(),
+ custom: parseTurnCustom(row.custom),
+ }));
+
+ return {
+ turns,
+ next_offset: hasMore ? input.offset + input.limit : null,
+ };
+}
+
+/**
+ * updateTurnState — conditional on state->>'status'='running'.
+ * 0 rows → SELECT by PK → missing NotFound, present Conflict (first terminal write wins).
+ */
+export async function updateTurnState(db: Kysely<Database>, input: UpdateTurnStateInput): Promise<void> {
+ await db.transaction().execute(async trx => {
+ const result = await trx
+ .updateTable('turn')
+ .set({
+ state: input.state,
+ updated_at: sql`now()`,
+ })
+ .where('tenant_id', '=', input.tenant_id)
+ .where('session_id', '=', input.session_id)
+ .where('turn_id', '=', input.turn_id)
+ .where(sql<boolean>`state->>'status' = 'running'`)
+ .executeTakeFirst();
+
+ const numUpdated = Number(result.numUpdatedRows);
+ if (numUpdated === 0) {
+ const existing = await trx
+ .selectFrom('turn')
+ .select('state')
+ .where('tenant_id', '=', input.tenant_id)
+ .where('session_id', '=', input.session_id)
+ .where('turn_id', '=', input.turn_id)
+ .executeTakeFirst();
+
+ if (!existing) throw new TurnNotFoundError(input.turn_id);
+ throw new TurnNotRunningError(input.turn_id, terminalTurnState(existing.state, input.turn_id));
+ }
+
+ await trx
+ .insertInto('session_event')
+ .values({
+ tenant_id: input.tenant_id,
+ session_id: input.session_id,
+ turn_id: input.turn_id,
+ event_id: input.turn_done_event.id,
+ event: json(input.turn_done_event),
+ created_at: new Date(input.turn_done_event.created_at),
+ })
+ .execute();
+ });
+}
diff --git a/packages/server/src/db/session-store/sqlExpressions.ts b/packages/server/src/db/session-store/sqlExpressions.ts
new file mode 100644
index 000000000..08e64ffd4
--- /dev/null
+++ b/packages/server/src/db/session-store/sqlExpressions.ts
@@ -0,0 +1,75 @@
+/**
+ * Shared Kysely SQL expression helpers for the Postgres session store.
+ */
+import { sql, type AliasedRawBuilder, type Expression, type RawBuilder } from 'kysely';
+
+/** Bind a JS value as jsonb (stringified + cast). Required for arrays and for `||` / jsonb_set operands. */
+export function json<T>(value: T): RawBuilder<T> {
+ return sql`${JSON.stringify(value)}::jsonb`;
+}
+
+/**
+ * `jsonb_set(target, path, new_value)`.
+ * `path` may be a text[] expression (`sql\`ARRAY['threads', ${id}]\``) or a literal path
+ * expression (`sql\`'{sandbox_info}'\`` / `sql\`'{completion}'\``).
+ */
+export function jsonbSet<T = unknown>(
+ target: Expression<unknown>,
+ path: Expression<unknown>,
+ newValue: Expression<unknown>,
+): RawBuilder<T> {
+ return sql<T>`jsonb_set(${target}, ${path}, ${newValue})`;
+}
+
+/**
+ * Typed `(VALUES ...) AS alias(col1, col2, ...)` for use in `.selectFrom(...)`.
+ * VALUES params are unknown→text unless cast — pass `sql\`${n}::bigint\`` (etc.) for non-text cols.
+ * @see https://kysely.dev/docs/recipes/extending-kysely
+ */
+export function values<R extends object, A extends string>(records: R[], alias: A): AliasedRawBuilder<R, A> {
+ const first = records[0];
+ if (first === undefined) {
+ throw new Error('values() requires at least one record');
+ }
+ const keys = Object.keys(first) as (keyof R & string)[];
+
+ const valueTuples = sql.join(records.map(r => sql`(${sql.join(keys.map(k => r[k]))})`));
+
+ const wrappedAlias = sql.ref(alias);
+ const wrappedColumns = sql.join(keys.map(key => sql.ref(key)));
+ const aliasSql = sql`${wrappedAlias}(${wrappedColumns})`;
+
+ return sql<R>`(values ${valueTuples})`.as<A>(aliasSql);
+}
+
+/**
+ * `unnest(ids::text[]) WITH ORDINALITY AS alias(turn_id, pos)` for `.selectFrom(...)`.
+ * Used by listSessionEvents mode-2 (ancestor chain order).
+ */
+export function unnestWithOrdinality<A extends string>(
+ ids: string[],
+ alias: A,
+): AliasedRawBuilder<{ turn_id: string; pos: number }, A> {
+ const wrappedAlias = sql.ref(alias);
+ const aliasSql = sql`${wrappedAlias}(turn_id, pos)`;
+ return sql<{ turn_id: string; pos: number }>`unnest(${ids}::text[]) WITH ORDINALITY`.as<A>(aliasSql);
+}
+
+/**
+ * `LATERAL unnest(array_expr) WITH ORDINALITY AS alias(append_id, pos)` for join use.
+ * Kysely 0.29 has no leftJoinLateral builder — this expression is the join RHS.
+ * Used by getTurn context assembly so empty-context threads still emit a row.
+ */
+export function lateralUnnestBigintArrayWithOrdinality<A extends string>(
+ arrayExpr: Expression<number[] | null>,
+ alias: A,
+): AliasedRawBuilder<{ append_id: number; pos: number }, A> {
+ const wrappedAlias = sql.ref(alias);
+ const aliasSql = sql`${wrappedAlias}(append_id, pos)`;
+ return sql<{ append_id: number; pos: number }>`LATERAL unnest(${arrayExpr}) WITH ORDINALITY`.as<A>(aliasSql);
+}
+
+/** `now()` timestamptz expression. */
+export function now(): RawBuilder<Date> {
+ return sql<Date>`now()`;
+}
diff --git a/packages/server/src/db/types.ts b/packages/server/src/db/types.ts
index 9106ed441..361634a5f 100644
--- a/packages/server/src/db/types.ts
+++ b/packages/server/src/db/types.ts
@@ -1,6 +1,310 @@
/**
- * Live app schema for the runtime Kysely client / future Postgres-backed store.
+ * Live app schema for the runtime Kysely client / Postgres-backed session store.
* Migrations must not use this type — use `Kysely<unknown>` instead.
*/
-// TODO: Replace with an interface whose keys are tables when the first table is added.
-export type Database = Record<string, never>;
+import type { AgentSpec, PersistedTurnEvent, TurnInputItem, TurnState } from '@truefoundry/utils/agent-session';
+import type {
+ AgentInfo,
+ AgentParent,
+ ContextMessage,
+ JsonValue,
+ MCPServerInitInfo,
+ SandboxInfo,
+ SubAgentCompletionMarker,
+} from '@truefoundry/utils/core';
+import type { CompletionUsage } from '@truefoundry/utils/core/llm/LLMTypes';
+import type { ColumnType, Generated, JSONColumnType } from 'kysely';
+
+/**
+ * Trace-level state for one thread at one turn (`turn_thread.checkpoint`).
+ * Total types: `completion` is explicitly null until set — no optional keys.
+ */
+export interface TurnThreadCheckpoint {
+ parent: AgentParent | null;
+ completion: SubAgentCompletionMarker | null;
+}
+
+/** Turn-level checkpoint — threads live in `turn_thread`; only owned top-level keys remain. */
+export interface TurnCheckpoint {
+ mcp_servers: Record<string, MCPServerInitInfo> | null;
+ sandbox_info: SandboxInfo | null;
+}
+
+/**
+ * PRIMARY KEY (tenant_id, session_id)
+ * WITH (fillfactor = 85); headroom so the per-turn bump stays HOT (no index churn)
+ * CREATE INDEX session_list_idx ON session (tenant_id, created_at, session_id)
+ */
+export interface SessionTable {
+ /** key */
+ tenant_id: string;
+ /** key */
+ session_id: string;
+ /**
+ * top: big + immutable-in-practice (updateSession patch only);
+ * TOAST pointer rides through per-turn tip bumps untouched
+ */
+ agent_spec: JSONColumnType<AgentSpec, AgentSpec, AgentSpec>;
+ /**
+ * top: list-displayed, independently patched; first-write-wins
+ * (COALESCE) targets it directly
+ */
+ title: string | null;
+ /**
+ * top: HOT — bumped once per createTurn under the session lock;
+ * tiny fixed-width column keeps the bump a cheap HOT update
+ */
+ last_turn_id: string | null;
+ /** top: caller-owned opaque extension; never mixed with store state */
+ custom: JSONColumnType<Record<string, unknown>, Record<string, unknown>, Record<string, unknown>> | null;
+ /** top: list ordering (indexed below) */
+ created_at: Date;
+ updated_at: Date;
+ /**
+ * top: hot, bumped with the tip ("activity" = turn creation)
+ */
+ last_activity_timestamp_ms: number;
+}
+
+/**
+ * PRIMARY KEY (tenant_id, session_id, turn_id)
+ * WITH (fillfactor = 85); headroom for the state flip + rare checkpoint patches
+ * CREATE INDEX turn_list_idx ON turn (tenant_id, session_id, created_at, turn_id)
+ */
+export interface TurnTable {
+ /** key */
+ tenant_id: string;
+ /** key */
+ session_id: string;
+ /** key (ulid) */
+ turn_id: string;
+ /** top: immutable topology; filter target */
+ first_turn_id: string;
+ /** top: immutable topology; NULL = session's first turn */
+ previous_turn_id: string | null;
+ /**
+ * top: immutable; queried by the anchored ancestor-chain walk
+ * (spill through older turns); typed array
+ */
+ ancestor_ids: string[];
+ /** top: big + written once at create; TOAST pointer stable after */
+ // Insert arrays/objects via json() helper (bare JS arrays become PG arrays via node-pg).
+ input: JSONColumnType<TurnInputItem[], TurnInputItem[] | string, TurnInputItem[] | string>;
+ /**
+ * top: THE fence/freeze target — every gated write predicates on
+ * state->>'status'; exactly one terminal flip per turn
+ */
+ state: JSONColumnType<TurnState, TurnState, TurnState>;
+ /**
+ * inlined: {mcp_servers, sandbox_info, ...future} — both small,
+ * patched at most once or twice per turn (resource init);
+ * extensible without migration
+ */
+ checkpoint: JSONColumnType<TurnCheckpoint, TurnCheckpoint, TurnCheckpoint>;
+ /** top: caller-owned opaque extension */
+ custom: JSONColumnType<
+ Record<string, unknown>,
+ Record<string, unknown> | string,
+ Record<string, unknown> | string
+ > | null;
+ /** top: list ordering (indexed below) */
+ created_at: Date;
+ updated_at: Date;
+}
+
+/**
+ * the complete STATE of one thread at one turn
+ * PRIMARY KEY (tenant_id, session_id, turn_id, thread_id)
+ * WITH (fillfactor = 70); the ONE deliberately-hot table: rewritten 5–10x while its
+ * turn runs; immutable once the turn is terminal (fence)
+ */
+export interface TurnThreadTable {
+ /** key */
+ tenant_id: string;
+ /** key */
+ session_id: string;
+ /** key */
+ turn_id: string;
+ /** key */
+ thread_id: string;
+ /**
+ * inlined: {parent, completion, ...future} — parent: small,
+ * immutable; completion: can be big but written ONCE at
+ * thread end (rare + terminal); the hot path below never
+ * touches this jsonb
+ */
+ checkpoint: JSONColumnType<TurnThreadCheckpoint, TurnThreadCheckpoint, TurnThreadCheckpoint>;
+ /**
+ * top: big + immutable thread IDENTITY. Real data: sub-agent
+ * instructions in one working session ran 2.4–8.8KB
+ * (median 4.4KB) — always past the ~2KB TOAST threshold,
+ * so a dedicated column lets every array rewrite carry the
+ * TOAST value by pointer instead of re-serializing it.
+ * Deliberately duplicates context[0] (the task is also the
+ * thread's first user message): the log copy is
+ * conversation state and compaction may reclaim it; this
+ * copy is identity and must survive context surgery
+ * (restore re-resolves the child definition from
+ * name/model/input here). NULL for the root thread.
+ */
+ agent_info: JSONColumnType<AgentInfo, AgentInfo | null, AgentInfo | null> | null;
+ /**
+ * top: hot — set by the SAME single-statement UPDATE as the
+ * array concat (zero extra row versions; ~300B inline;
+ * byte-neutral vs stamping log rows). Kept out of
+ * checkpoint so the jsonb never rewrites on the hot path.
+ * Escape hatch: if the array ever becomes write-once
+ * (ranges / writer-filter), move this back onto
+ * thread_context_log rows (previously validated design).
+ */
+ current_context_usage: JSONColumnType<CompletionUsage, CompletionUsage, CompletionUsage>;
+ /**
+ * top: THE context — log append_ids in context order. Hot
+ * concat target (`||`), typed bigint[] operator; dominant
+ * TOAST value (~8KB at 1k live messages, entire value
+ * rewritten per append batch — the accepted cost of the
+ * raw-array choice; range-encoding is the recorded shrink
+ * if measured).
+ */
+ // Real Postgres bigint[] — bind JS number[] directly (NOT via json(); that is the jsonb trap).
+ // Select path: int8[] OID 1016 parser in client.ts yields number[].
+ context_ids: number[];
+ updated_at: Date;
+}
+
+/**
+ * pure immutable client-facing event log
+ * PRIMARY KEY (tenant_id, session_id, turn_id, event_id)
+ * pure INSERT → fillfactor 100
+ */
+export interface SessionEventTable {
+ /** key */
+ tenant_id: string;
+ /** key */
+ session_id: string;
+ /** top: every read is turn-scoped or turn-attributed (envelope) */
+ turn_id: string;
+ /**
+ * top/key: event.id, a process-local monotonic ULID minted when the event is
+ * created. Lexical ordering preserves the single turn writer's creation
+ * order, including events created in the same millisecond.
+ *
+ * A database auto-increment id is deliberately not used: it assigns order
+ * at persistence rather than event creation, couples the contract to
+ * Postgres, and sequence allocation across pooled connections,
+ * transactions, retries, or larger sequence caches need not represent
+ * logical event order. The event already owns a portable unique id, so
+ * a second store-generated identity would duplicate identity and make
+ * ordering backend-dependent.
+ *
+ * @see https://github.com/ulid/spec#monotonicity
+ */
+ event_id: string;
+ /** top: PersistedTurnEvent payload, written once */
+ event: JSONColumnType<PersistedTurnEvent, PersistedTurnEvent, PersistedTurnEvent>;
+ /**
+ * top: copied from event.created_at (required by PersistedTurnEvent), so
+ * future time-range filters can be indexed without inspecting jsonb.
+ * Ordering still uses event_id.
+ */
+ created_at: Date;
+}
+
+/**
+ * pure immutable CONTENT; no state → no checkpoint field
+ * PRIMARY KEY (tenant_id, session_id, thread_id, append_id)
+ * pure INSERT → default fillfactor 100, zero dead tuples;
+ * cleanup is whole-session delete only
+ */
+export interface ThreadContextLogTable {
+ /** key */
+ tenant_id: string;
+ /** key */
+ session_id: string;
+ /** key */
+ thread_id: string;
+ /**
+ * top: THE message id — store-assigned (the delta createTurn
+ * interface killed content addressing: the store is told
+ * what's new, so no hashing/dedupe); consumed by
+ * data-modifying CTE in the same statement (RETURNING
+ * → array concat, one network call). bigint on purpose:
+ * no exhaustion (~290M years at 1k msg/s; int4 would die
+ * in months). NOT an order key: the array is the sole
+ * order authority (reads use unnest WITH ORDINALITY).
+ * Cross-statement id order is NEVER relied on for context
+ * (pool + sequence CACHE could invert it); the only id
+ * ordering used is INTRA-statement (array_agg ORDER BY
+ * append_id over one INSERT's RETURNING = VALUES order,
+ * backend-local, safe under any CACHE setting)
+ */
+ append_id: Generated<number>;
+ /**
+ * top: provenance — which turn wrote the row; debugging + the
+ * future writer-filter migration; tiny; NOT used for
+ * visibility (the array is the sole visibility authority)
+ */
+ turn_id: string;
+ /** top: the ContextMessage — written exactly once, never updated */
+ body: JSONColumnType<ContextMessage, ContextMessage, ContextMessage>;
+ /**
+ * top: future indexed time filters without a table rewrite
+ */
+ created_at: Date;
+}
+
+/**
+ * PER-TURN KV snapshot, latest-wins per (turn, thread, key)
+ * PRIMARY KEY (tenant_id, session_id, turn_id, thread_id, key)
+ * WITH (fillfactor = 85); single-statement fenced upsert per CAPABILITY_STATE event
+ *
+ * Capability history is per-turn on purpose: createTurn carries the previous
+ * turn's rows forward (one INSERT..SELECT), so every turn owns its complete
+ * map — fork fidelity and terminal immutability beat the tiny row duplication.
+ * A cross-turn latest-wins PK was tried and REVERTED for the fork reason.
+ */
+export interface ThreadCapabilityStateTable {
+ /** key */
+ tenant_id: string;
+ /** key */
+ session_id: string;
+ /**
+ * key: capability history is PER TURN — fork/restore from any
+ * turn must see the map AS OF that turn, and a frozen
+ * turn's map must never change under it. (A cross-turn
+ * latest-wins PK was tried and REVERTED for exactly the
+ * fork reason.)
+ */
+ turn_id: string;
+ /** key */
+ thread_id: string;
+ /** key: capability state key; `tfy.` prefix reserved */
+ key: string;
+ /**
+ * top: the value IS the row — JsonValue (undefined banned at
+ * the harness boundary); NULL = explicitly cleared
+ */
+ // Insert via json() so scalars/arrays are not mis-encoded by node-pg.
+ // ColumnType (not JSONColumnType): select may be any JSON value, including scalars / null.
+ state: ColumnType<JsonValue | null, JsonValue | null, JsonValue | null>;
+ updated_at: Date;
+}
+
+/**
+ * Write-heat summary: `turn_thread` is the one deliberately-hot table with its hot
+ * columns (`context_ids`, `current_context_usage`) isolated from the pointer-carried
+ * big ones (`agent_info`, `checkpoint`); `session`, `turn`, and
+ * `thread_capability_state` take small bounded HOT-friendly updates; the two logs
+ * are pure insert. Nothing ever rewrites a large value except the array concat
+ * itself — the documented, bounded cost of the raw-array model.
+ *
+ * Canonical Kysely database — six session-store tables.
+ */
+export interface Database {
+ session: SessionTable;
+ turn: TurnTable;
+ turn_thread: TurnThreadTable;
+ session_event: SessionEventTable;
+ thread_context_log: ThreadContextLogTable;
+ thread_capability_state: ThreadCapabilityStateTable;
+}
diff --git a/packages/server/src/main.ts b/packages/server/src/main.ts
index 65fa7d912..5831de2c2 100644
--- a/packages/server/src/main.ts
+++ b/packages/server/src/main.ts
@@ -1,6 +1,6 @@
/**
* Server entry point: validates config, migrates the database, loads the YAML
- * stores, wires the in-memory session runtime and starts the HTTP server.
+ * stores, wires the Postgres session store and starts the HTTP server.
* Any config, migration, or store error aborts startup.
*/
import { serve } from '@hono/node-server';
@@ -15,9 +15,10 @@ try {
{ ModelStore },
{ McpStore },
{ SkillStore },
- { Sessions, InMemorySessionStore, CancellationReason },
+ { Sessions, CancellationReason },
{ ActiveTurnRegistry },
{ createServerSandboxFactory },
+ { PostgresSessionStore },
] = await Promise.all([
import('./app'),
import('./config'),
@@ -29,6 +30,7 @@ try {
import('@truefoundry/utils/agent-session'),
import('./runtime/activeTurns'),
import('./runtime/sandboxFactory'),
+ import('./db/session-store/PostgresSessionStore'),
]);
// Console logger shared by the server runtime (harness components require one).
@@ -41,7 +43,7 @@ try {
const db = createDb(configuration.DATABASE_URL, configuration.DATABASE_POOL_MAX);
await migrateToLatest(db);
- const sessionStore = new InMemorySessionStore();
+ const sessionStore = new PostgresSessionStore(db);
// Throws on malformed SANDBOX_SETTINGS; undefined when sandbox is not configured.
const skillStore = SkillStore.load();
const sandboxFactory = createServerSandboxFactory({ logger });
diff --git a/packages/server/src/routes/sessionRoutes.ts b/packages/server/src/routes/sessionRoutes.ts
index cabcd3680..48165a005 100644
--- a/packages/server/src/routes/sessionRoutes.ts
+++ b/packages/server/src/routes/sessionRoutes.ts
@@ -161,7 +161,7 @@ export const listSessionEventsRoute = createRoute({
tags: [SESSIONS_TAG],
summary: 'List session events',
description:
- 'List session events as `{ turn_id, event }` across the turn chain (newest first). Each turn contributes turn.created, content events (model.message, tool.call, …), and turn.done; streaming deltas are not included. If the newest turn is still running, its events are excluded — subscribe to the running turn for live events. Use `page_token` to paginate backward toward older events.',
+ 'List session events as `{ turn_id, event }` across the active turn branch (newest first), including persisted events from a running tip. Each turn contributes turn.created, content events (model.message, tool.call, …), and turn.done when terminal; streaming deltas are not included. Use `page_token` to paginate backward toward older events while retaining the original branch anchor.',
request: {
params: SessionIdParamsSchema,
query: ListSessionEventsRequestQuerySchema,
diff --git a/packages/server/src/runtime/sandboxFactory.ts b/packages/server/src/runtime/sandboxFactory.ts
index e6a891250..f54acbfa5 100644
--- a/packages/server/src/runtime/sandboxFactory.ts
+++ b/packages/server/src/runtime/sandboxFactory.ts
@@ -12,7 +12,7 @@ import type { TurnSandboxFactory } from '@truefoundry/utils/agent-session';
import { createSandboxProvider, Sandbox, SandboxProviderSettingsSchema, SkillMounter } from '@truefoundry/utils/core';
import type { Logger } from 'winston';
import { ZodError } from 'zod';
-import { TENANT_NAME } from '../apis/sessions';
+import { TENANT_ID } from '../apis/sessions';
import configuration from '../config';
function parseSandboxSettings(rawJson: string) {
@@ -60,7 +60,7 @@ export function createServerSandboxFactory(deps: { logger: Logger }): TurnSandbo
const logger = deps.logger.child({ module: 'sandboxFactory' });
const provider = createSandboxProvider({
settings,
- tenantName: TENANT_NAME,
+ tenantName: TENANT_ID,
fileMaxBytes: configuration.SANDBOX_FILE_MAX_BYTES,
previewUrlExpirySeconds: configuration.SANDBOX_PREVIEW_URL_EXPIRY_SECONDS,
logger,
@@ -89,7 +89,7 @@ export function createServerSandboxFactory(deps: { logger: Logger }): TurnSandbo
// Sandbox reads its tenant from TFY_TENANT_NAME (see Sandbox constructor)
// for the ownership check against provider-created sandbox ids
// (`<tenant>.<uuid>`). Must match the tenantName given to the provider.
- execExtraEnv: { TFY_TENANT_NAME: TENANT_NAME },
+ execExtraEnv: { TFY_TENANT_NAME: TENANT_ID },
...(skillMounter ? { skillMounter } : {}),
tracing,
logger,
diff --git a/packages/server/src/schemas/events.ts b/packages/server/src/schemas/events.ts
index 42da10e02..6527be6d4 100644
--- a/packages/server/src/schemas/events.ts
+++ b/packages/server/src/schemas/events.ts
@@ -53,13 +53,13 @@ export const ListSessionEventsRequestQuerySchema = z
.string()
.optional()
.describe(
- 'Pagination cursor from `pagination.next_page_token`. Returns older events before the cursor (toward session start).',
+ 'Pagination cursor from `pagination.next_page_token`. It retains the branch anchor turn and returns older events toward the session start.',
),
last_turn_id: z
.string()
.optional()
.describe(
- 'Newest turn in the listing window (initial load only; ignored when `page_token` is set). Lists that turn and its ancestors, newest events first. Omit to use the session last turn. If the resolved turn is still running, its events are excluded — subscribe to the running turn for live events.',
+ 'Newest turn in the listing window (initial load only; ignored when `page_token` is set). Lists that turn and its ancestors, newest events first. Omit to use the session last turn.',
),
limit: z.coerce
.number()
diff --git a/packages/server/tests/db/session-store/contract.test.ts b/packages/server/tests/db/session-store/contract.test.ts
new file mode 100644
index 000000000..d7880caa7
--- /dev/null
+++ b/packages/server/tests/db/session-store/contract.test.ts
@@ -0,0 +1,32 @@
+import type { ISessionStore } from '@truefoundry/utils/agent-session/store/ISessionStore';
+
+import { runStoreContractSuite } from '../../../../harness/tests/agent-session/store/storeContractSuite';
+import { createPostgresStoreEnvironment } from './helpers';
+
+const describePg = process.env.PG_STORE_TESTS_ENABLED === '1' ? describe : describe.skip;
+
+describePg('PostgresSessionStore (ISessionStore contract)', () => {
+ let env: Awaited<ReturnType<typeof createPostgresStoreEnvironment>>;
+
+ beforeAll(async () => {
+ env = await createPostgresStoreEnvironment();
+ if (env === undefined) {
+ throw new Error('Postgres test environment unavailable despite globalSetup probe');
+ }
+ }, 120_000);
+
+ afterAll(async () => {
+ await env?.teardown();
+ });
+
+ beforeEach(async () => {
+ await env?.reset();
+ });
+
+ runStoreContractSuite((): ISessionStore => {
+ if (env === undefined) {
+ throw new Error('Postgres test environment not initialized');
+ }
+ return env.store;
+ });
+});
diff --git a/packages/server/tests/db/session-store/globalSetup.ts b/packages/server/tests/db/session-store/globalSetup.ts
new file mode 100644
index 000000000..c0a7e0c6f
--- /dev/null
+++ b/packages/server/tests/db/session-store/globalSetup.ts
@@ -0,0 +1,70 @@
+/**
+ * Probes for a reachable Postgres before the store suite runs and publishes the
+ * outcome through the environment, so the suite can skip rather than fail when
+ * no database is available.
+ */
+import { connect } from 'node:net';
+import { Pool } from 'pg';
+
+const CONFIGURED_URL_ENV = 'SESSION_STORE_TEST_PG_URL';
+const ENABLED_ENV = 'PG_STORE_TESTS_ENABLED';
+const ADMIN_URL_ENV = 'PG_STORE_TESTS_ADMIN_URL';
+
+const DEFAULT_HOST = '127.0.0.1';
+const DEFAULT_PORT = 55432;
+const DEFAULT_URL = 'postgres://proto:proto@localhost:55432/proto';
+
+function isPortOpen(host: string, port: number): Promise<boolean> {
+ return new Promise<boolean>(resolve => {
+ const socket = connect({ host, port });
+ socket.setTimeout(2000);
+ socket.once('connect', () => {
+ socket.destroy();
+ resolve(true);
+ });
+ socket.once('timeout', () => {
+ socket.destroy();
+ resolve(false);
+ });
+ socket.once('error', () => {
+ resolve(false);
+ });
+ });
+}
+
+async function probeUrl(url: string): Promise<boolean> {
+ const pool = new Pool({ connectionString: url, connectionTimeoutMillis: 3000 });
+ try {
+ await pool.query('SELECT 1');
+ return true;
+ } catch {
+ return false;
+ } finally {
+ await pool.end();
+ }
+}
+
+export default async function setupPostgresStoreTests(): Promise<void> {
+ const configuredUrl = process.env[CONFIGURED_URL_ENV];
+ if (configuredUrl !== undefined && configuredUrl !== '') {
+ if (await probeUrl(configuredUrl)) {
+ process.env[ENABLED_ENV] = '1';
+ process.env[ADMIN_URL_ENV] = configuredUrl;
+ return;
+ }
+ }
+
+ if (await isPortOpen(DEFAULT_HOST, DEFAULT_PORT)) {
+ if (await probeUrl(DEFAULT_URL)) {
+ process.env[ENABLED_ENV] = '1';
+ process.env[ADMIN_URL_ENV] = DEFAULT_URL;
+ console.log(`Postgres store tests: using default local URL (${CONFIGURED_URL_ENV} unset)`);
+ return;
+ }
+ }
+
+ process.env[ENABLED_ENV] = '0';
+ console.warn(
+ `Postgres store tests skipped: set ${CONFIGURED_URL_ENV} or start Postgres on ${DEFAULT_HOST}:${String(DEFAULT_PORT)}`,
+ );
+}
diff --git a/packages/server/tests/db/session-store/helpers.ts b/packages/server/tests/db/session-store/helpers.ts
new file mode 100644
index 000000000..f9887f153
--- /dev/null
+++ b/packages/server/tests/db/session-store/helpers.ts
@@ -0,0 +1,107 @@
+import { sql, type Kysely } from 'kysely';
+import { Pool } from 'pg';
+import { ulid } from 'ulid';
+
+import { createDb } from '../../../src/db/client';
+import { migrateToLatest } from '../../../src/db/migrate';
+import { PostgresSessionStore } from '../../../src/db/session-store/PostgresSessionStore';
+import type { Database } from '../../../src/db/types';
+
+const ADMIN_URL_ENV = 'PG_STORE_TESTS_ADMIN_URL';
+
+export interface PostgresStoreEnvironment {
+ store: PostgresSessionStore;
+ reset: () => Promise<void>;
+ teardown: () => Promise<void>;
+}
+
+async function truncateSessionStore(db: Kysely<Database>): Promise<void> {
+ await sql`
+ TRUNCATE TABLE
+ thread_capability_state,
+ session_event,
+ thread_context_log,
+ turn_thread,
+ turn,
+ session
+ RESTART IDENTITY CASCADE
+ `.execute(db);
+}
+
+function resolveAdminUrl(): string | undefined {
+ const url = process.env[ADMIN_URL_ENV];
+ if (url === undefined || url === '') {
+ return undefined;
+ }
+ return url;
+}
+
+function withDatabase(connectionString: string, database: string): string {
+ const parsed = new URL(connectionString.replace(/^postgres:/, 'http:'));
+ parsed.pathname = `/${database}`;
+ return parsed.toString().replace(/^http:/, 'postgres:');
+}
+
+function assertSafeDatabaseName(name: string): void {
+ if (!/^[a-z0-9_]+$/.test(name)) {
+ throw new Error(`invalid database name: ${name}`);
+ }
+}
+
+async function dropDatabase(adminUrl: string, databaseName: string): Promise<void> {
+ assertSafeDatabaseName(databaseName);
+ const pool = new Pool({ connectionString: adminUrl });
+ try {
+ await pool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [databaseName],
+ );
+ await pool.query(`DROP DATABASE IF EXISTS "${databaseName}"`);
+ } finally {
+ await pool.end();
+ }
+}
+
+/**
+ * Creates a throwaway database, migrates it, and returns a PostgresSessionStore bound to it.
+ * Each test file should call this once in beforeAll and teardown in afterAll.
+ */
+export async function createPostgresStoreEnvironment(): Promise<PostgresStoreEnvironment | undefined> {
+ const adminUrl = resolveAdminUrl();
+ if (adminUrl === undefined) {
+ return undefined;
+ }
+
+ const databaseName = `test_${ulid().toLowerCase()}`;
+ assertSafeDatabaseName(databaseName);
+
+ const adminPool = new Pool({ connectionString: adminUrl });
+ try {
+ await adminPool.query(`CREATE DATABASE "${databaseName}"`);
+ } catch (error) {
+ await adminPool.end();
+ throw error;
+ } finally {
+ await adminPool.end();
+ }
+
+ const databaseUrl = withDatabase(adminUrl, databaseName);
+ const db = createDb(databaseUrl, 5);
+ try {
+ await migrateToLatest(db);
+ } catch (error) {
+ await db.destroy();
+ await dropDatabase(adminUrl, databaseName);
+ throw error;
+ }
+
+ const store = new PostgresSessionStore(db);
+ return {
+ store,
+ reset: () => truncateSessionStore(db),
+ async teardown() {
+ await db.destroy();
+ await dropDatabase(adminUrl, databaseName);
+ },
+ };
+}
diff --git a/packages/server/tsconfig.json b/packages/server/tsconfig.json
index b9dc773ea..6205946e9 100644
--- a/packages/server/tsconfig.json
+++ b/packages/server/tsconfig.json
@@ -4,6 +4,8 @@
"types": ["node"],
"noEmit": true
},
- "include": ["src/**/*", "tsup.config.ts"],
- "exclude": ["node_modules", "dist", "src/**/*.test.ts"]
+ "include": ["src/**/*", "tests/**/*", "tsup.config.ts"],
+ // Test bodies pull harness test sources across the package boundary, which needs
+ // that package's own compiler paths; support modules stay in-project.
+ "exclude": ["node_modules", "dist", "src/**/*.test.ts", "tests/**/*.test.ts"]
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 58b9f3d6c..bd5754513 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -210,12 +210,24 @@ importers:
specifier: ^3.24.3
version: 3.25.76
devDependencies:
+ '@swc/core':
+ specifier: ^1.11.0
+ version: 1.15.46
+ '@swc/jest':
+ specifier: ^0.2.37
+ version: 0.2.39(@swc/[email protected])
+ '@types/jest':
+ specifier: ^29.5.14
+ version: 29.5.14
'@types/node':
specifier: ^24.12.0
version: 24.13.3
'@types/pg':
specifier: ^8.20.0
version: 8.20.0
+ jest:
+ specifier: ^29.7.0
tsup:
specifier: ^8.5.0