Apply session record transitions against current writer rows

This commit is contained in:
Brennan Benson
2026-11-08 15:10:01 -08:00
parent 8eceb06cfd
commit 54605efcbc
50 changed files with 1761 additions and 1021 deletions
@@ -13,6 +13,7 @@ import {
type JournalDomainLifecycleCommit
} from './journal-domain-lifecycle'
import type { JournalStopSettleFact } from './journal-writer-host-facts'
import { isPlanApprovalSubject } from '../../../shared/agent-session/agent-session-approval-subject'
/** Revision and answer ownership are checked after every preceding writer command. */
export function applyJournalDomainPromptMutation(
@@ -62,6 +63,18 @@ export function applyJournalDomainPromptMutation(
)
const item = written.items.find((item) => item.itemId === current!.itemId)!
const cursor = { ...empty.cursor, sequence: written.cursor.sequence }
const choice =
pending.prompt.kind === 'approval' &&
isPlanApprovalSubject(pending.prompt.subject) &&
input.resolution.state === 'resolved'
? input.resolution.selectedOptionId
: undefined
const planApprovalMode =
choice === 'allow' || choice === 'allowForSession'
? ('default' as const)
: choice === 'deny'
? ('plan' as const)
: undefined
return {
...written,
cursor,
@@ -71,7 +84,12 @@ export function applyJournalDomainPromptMutation(
kind: 'item',
epoch: target.epoch,
seq: cursor.sequence,
promptAnswer: { itemId: item.itemId, revision: item.revision, resolution: input.resolution }
promptAnswer: {
itemId: item.itemId,
revision: item.revision,
resolution: input.resolution
},
...(planApprovalMode ? { planApprovalMode } : {})
}
],
value: { itemId: item.itemId, revision: item.revision, cursor }
@@ -34,12 +34,16 @@ export function finishJournalSqlCommand(
coordinates.length > 0
? claimJournalSqlItemInputs(db, stateDirectory, command, result)
: { referencedUploads: result.referencedUploads ?? [] }
const effects =
coordinates.length > 0
? (command.effects ?? []).map((effect) =>
applyJournalWriterEffect(db, stateDirectory, effect, publicCoordinates)
)
: []
const receiptWritten =
coordinates.length > 0 ||
command.effects?.some(
(effect) => effect.kind === 'store' && effect.mutation.input.kind === 'rewind-complete'
)
const effects = receiptWritten
? (command.effects ?? []).map((effect) =>
applyJournalWriterEffect(db, stateDirectory, effect, publicCoordinates)
)
: []
const publication = {
...result,
cursor,
@@ -73,7 +77,7 @@ export function finishJournalSqlCommand(
value: publicJournalSqlValue(command, value, cursor),
...('goals' in claims ? { goals: claims.goals } : {}),
effects,
...(coordinates.length > 0 && command.effects ? { receiptWritten: true as const } : {})
...(receiptWritten && command.effects ? { receiptWritten: true as const } : {})
}
}
@@ -1,6 +1,8 @@
import { agentSessionAttachmentStoreRoot } from '../agent-session-attachments/agent-session-attachment-references'
import type Database from '../../sqlite/sync-database'
import type { AgentSessionStoreRowWrites } from '../../runtime/agent-session/records/agent-session-store-draft'
import type { AgentSessionStoreRowWrites } from './journal-writer-store-row-changes'
import type { AgentSessionStoreMutation } from '../../runtime/agent-session/records/agent-session-store-mutation'
import type { AgentSessionRuntimeFacts } from '../../runtime/agent-session/agent-session-runtime-attribution'
import { applyJournalWriterStoreEffect } from './journal-writer-store-effect'
import {
claimAgentSessionAttachmentsInTransaction,
@@ -25,10 +27,18 @@ export type JournalWriterCoordinate = {
epoch: string
seq: number
promptAnswer?: AgentSessionPromptResult
planApprovalMode?: 'default' | 'plan'
}
export type JournalWriterEffect =
| { kind: 'store'; writes: AgentSessionStoreRowWrites; insertOperationsIfAbsent: boolean }
| {
kind: 'store'
mutation: {
input: AgentSessionStoreMutation
at?: number
runtime?: AgentSessionRuntimeFacts
}
}
| {
kind: 'receipt'
scope: CommandReceiptScope
@@ -50,7 +60,7 @@ export type JournalReceiptRowBinding = {
at: 'first' | 'last'
/** Kinds the row may have; any other row, or none, fails the command unless `absent` answers. */
kinds?: readonly JournalRow['kind'][]
answer: 'journal-row' | 'prompt-answer'
answer: 'journal-row' | 'prompt-answer' | CommandReceiptResult
absent?: CommandReceiptResult
}
@@ -66,6 +76,7 @@ export type JournalWriterStoreResult = {
kind: 'store'
disposition: 'applied' | 'noop'
writes: AgentSessionStoreRowWrites
value?: unknown
}
/** Host-computed values still recheck uniqueness and sweep authority on the sole connection. */
@@ -77,7 +88,7 @@ export function applyJournalWriterEffect(
): JournalWriterEffectResult {
switch (effect.kind) {
case 'store':
return applyJournalWriterStoreEffect(db, effect)
return applyJournalWriterStoreEffect(db, effect, rows)
case 'receipt': {
const row = effect.row && (effect.row.at === 'first' ? rows[0] : rows.at(-1))
const receipt = effect.row ? boundReceipt(effect.receipt, effect.row, row) : effect.receipt
@@ -123,6 +134,9 @@ function boundReceipt(
if (receipt.status !== 'accepted') {
throw new Error('only an accepted receipt binds its row')
}
if (typeof binding.answer === 'object') {
return { ...receipt, result: binding.answer }
}
if (!row || (binding.kinds && !binding.kinds.includes(row.kind))) {
if (binding.absent) {
return { ...receipt, result: binding.absent }
@@ -1,59 +1,34 @@
import type Database from '../../sqlite/sync-database'
import type { AgentSessionStoreRowWrites } from '../../runtime/agent-session/records/agent-session-store-draft'
import {
insertAgentSessionOperationRowsIfAbsent,
writeAgentSessionStoreRows
} from '../../runtime/agent-session/records/agent-session-record-rows'
import type { JournalWriterEffect, JournalWriterStoreResult } from './journal-writer-effects'
import { writeAgentSessionStoreRows } from '../../runtime/agent-session/records/agent-session-record-rows'
import type {
JournalWriterEffect,
JournalWriterStoreResult,
JournalWriterCoordinate
} from './journal-writer-effects'
import type { JournalRow } from './durable-rows/journal-row-schema'
import { resolveJournalWriterStoreMutation } from './journal-writer-store-mutation'
/** Return the touched rows at the writer position, never a host's provisional copy. */
export function applyJournalWriterStoreEffect(
db: Database.Database,
effect: Extract<JournalWriterEffect, { kind: 'store' }>
effect: Extract<JournalWriterEffect, { kind: 'store' }>,
rows: readonly (JournalRow | JournalWriterCoordinate)[] = []
): JournalWriterStoreResult {
const { writes } = effect
if (effect.insertOperationsIfAbsent) {
insertAgentSessionOperationRowsIfAbsent(db, writes.operations.upsert)
}
writeAgentSessionStoreRows(
const resolved = resolveJournalWriterStoreMutation(
db,
effect.insertOperationsIfAbsent
? { ...writes, operations: { ...writes.operations, upsert: [] } }
: writes
effect.mutation.input,
effect.mutation.at,
rows
.flatMap((row) =>
'planApprovalMode' in row && row.planApprovalMode ? [row.planApprovalMode] : []
)
.at(-1),
effect.mutation.runtime
)
writeAgentSessionStoreRows(db, resolved.writes)
return {
kind: 'store',
disposition: 'applied',
writes: {
...writes,
records: resolvedRows(writes.records, (key) =>
db
.prepare('SELECT record_json AS json FROM agent_session_records WHERE session_id=?')
.get(key)
),
operations: resolvedRows(writes.operations, (key) =>
db
.prepare('SELECT row_json AS json FROM agent_session_operations WHERE operation_key=?')
.get(key)
)
}
disposition: resolved.changed ? 'applied' : 'noop',
writes: resolved.acknowledged,
value: resolved.value
}
}
function resolvedRows(
touched: AgentSessionStoreRowWrites['records'],
read: (key: string) => { json?: unknown } | undefined
): AgentSessionStoreRowWrites['records'] {
const result: AgentSessionStoreRowWrites['records'] = { upsert: [], remove: [] }
for (const key of new Set([...touched.upsert.map(([id]) => id), ...touched.remove])) {
const row = read(key)
if (!row) {
result.remove.push(key)
} else if (typeof row.json === 'string') {
result.upsert.push([key, row.json])
} else {
throw new Error('a written store row has no saved form')
}
}
return result
}
@@ -0,0 +1,243 @@
import { copyAgentSessionStoreCache } from '../../runtime/agent-session/records/agent-session-store-cache'
import { journalDomainPublicCursor } from './journal-domain-context-replacement'
import {
loadAgentSessionStoreTabs,
loadAgentSessionStoreRecordRow
} from '../../runtime/agent-session/records/agent-session-record-rows'
import type Database from '../../sqlite/sync-database'
import { encodeAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record-stored-form'
import {
applyAgentSessionStoreMutation,
agentSessionStoreMutationKeys,
type AgentSessionStoreMutation
} from '../../runtime/agent-session/records/agent-session-store-mutation'
import {
agentSessionStoreRowChanges,
type AgentSessionStoreRowWrites
} from './journal-writer-store-row-changes'
import type { AgentSessionStoreState } from '../../runtime/agent-session/records/agent-session-store-state'
import { isReadableAgentSessionStoreOperation } from '../../runtime/agent-session/records/agent-session-store-row-rules'
import { JournalSqlScope } from './journal-sql-scope'
import { JournalSqlStatusContext } from './journal-sql-status-context'
import { readJournalSqlUsageLimitContinueIdentity } from './journal-sql-status-cuts'
import {
attributeAgentSessionRuntimeRecord,
type AgentSessionRuntimeFacts
} from '../../runtime/agent-session/agent-session-runtime-attribution'
export function emptyJournalWriterStoreRows(): AgentSessionStoreRowWrites {
return {
records: { upsert: [], remove: [] },
operations: { upsert: [], remove: [] },
retiredClaimKeys: null,
sessionTabs: null
}
}
/** No row draft survives this source group; SQLite owns composition and rollback. */
export function resolveJournalWriterStoreMutation(
db: Database.Database,
mutation: AgentSessionStoreMutation,
at: number | undefined,
planMode?: 'default' | 'plan',
runtime?: AgentSessionRuntimeFacts
): {
writes: AgentSessionStoreRowWrites
acknowledged: AgentSessionStoreRowWrites
value: unknown
changed: boolean
} {
const state: AgentSessionStoreState = {
records: new Map(),
operations: new Map(),
unreadableRecords: new Map(),
retiredClaimKeys: [],
sessionTabs: null
}
const touched = emptyJournalWriterStoreRows()
const identity = agentSessionStoreMutationKeys(mutation)
if (identity.tabs) {
state.sessionTabs = loadAgentSessionStoreTabs(db)
}
const recordIds = identity.allRecords
? db
.prepare('SELECT session_id FROM agent_session_records ORDER BY rowid')
.all()
.map((row) => String(row.session_id))
: identity.recordIds
const loadRecord = (id: string) => {
const row = db
.prepare('SELECT record_json FROM agent_session_records WHERE session_id=?')
.get(id)
if (!row) {
return
}
loadAgentSessionStoreRecordRow(
state,
id,
String(row.record_json),
mutation.kind === 'command' && mutation.command.kind === 'restart'
)
}
for (const id of recordIds) {
loadRecord(id)
}
if (identity.pruneAt !== undefined) {
const expired = db
.prepare(`SELECT operation_key,row_json FROM agent_session_operations
WHERE CASE WHEN json_valid(row_json) THEN json_extract(row_json,'$.expiresAt')<=? ELSE 0 END`)
.all(identity.pruneAt)
for (const row of expired) {
const key = String(row.operation_key)
if (isReadableAgentSessionStoreOperation(key, JSON.parse(String(row.row_json)))) {
db.prepare('DELETE FROM agent_session_operations WHERE operation_key=?').run(key)
touched.operations.remove.push(key)
}
}
}
const operationKeys =
identity.allCallers && identity.operationId !== undefined
? db
.prepare('SELECT operation_key FROM agent_session_operations WHERE operation_id=?')
.all(identity.operationId)
.map((row) => String(row.operation_key))
: []
if (identity.operationKey && !operationKeys.includes(identity.operationKey)) {
operationKeys.push(identity.operationKey)
}
for (const key of operationKeys) {
const row = db
.prepare('SELECT row_json FROM agent_session_operations WHERE operation_key=?')
.get(key)
if (!row) {
continue
}
const saved: unknown = JSON.parse(String(row.row_json))
if (!isReadableAgentSessionStoreOperation(key, saved)) {
throw new Error('agent_session_store_operation_unreadable')
}
state.operations.set(key, saved)
if (
mutation.kind === 'command' &&
(mutation.command.kind === 'reserve' || mutation.command.kind === 'found') &&
saved.outcome.status === 'succeeded' &&
!identity.recordIds.includes(saved.outcome.sessionId)
) {
identity.recordIds.push(saved.outcome.sessionId)
loadRecord(saved.outcome.sessionId)
}
}
const draft = copyAgentSessionStoreCache(state)
const action = mutation.kind === 'operation' ? mutation.record : undefined
const head =
mutation.kind === 'rewind-complete' ||
(action?.action.kind === 'stop-continue' && action.action.enabled)
? db
.prepare(
'SELECT epoch,last_sequence FROM journal_chat_state WHERE session_id=? AND epoch IS NOT NULL'
)
.get(mutation.kind === 'rewind-complete' ? mutation.sessionId : (action?.sessionId ?? ''))
: undefined
const continueCut =
head && (action || mutation.kind === 'rewind-complete')
? readJournalSqlUsageLimitContinueIdentity(
new JournalSqlStatusContext(
new JournalSqlScope(
db,
mutation.kind === 'rewind-complete' ? mutation.sessionId : (action?.sessionId ?? ''),
String(head.epoch)
)
)
)
: undefined
const sleepingWithPendingInput =
mutation.kind === 'record' &&
mutation.command.kind === 'sleep' &&
!!db
.prepare(`SELECT 1 FROM journal_submission_attempts AS input
JOIN journal_chat_state AS chat ON chat.session_id=input.session_id AND chat.epoch=input.epoch
WHERE input.session_id=? AND input.current=1 AND input.dispatch_state='pending' LIMIT 1`)
.get(mutation.sessionId)
let value = sleepingWithPendingInput
? null
: applyAgentSessionStoreMutation(draft, mutation, at, {
planMode,
continueCut,
cursor:
mutation.kind === 'rewind-complete' && head
? journalDomainPublicCursor(
db,
{ sessionId: mutation.sessionId, epoch: String(head.epoch) },
Number(head.last_sequence)
)
: undefined
})
if (runtime) {
for (const [id, after] of draft.records) {
const before = state.records.get(id)
const attributed = attributeAgentSessionRuntimeRecord(
before,
after,
runtime.ends,
runtime.incarnation
)
draft.records.set(id, attributed)
if (value instanceof Map && value.get(id) === after) {
value.set(id, attributed)
}
if (Array.isArray(value)) {
value = value.map((entry) => (entry === after ? attributed : entry))
}
if (value === after) {
value = attributed
} else if (
value &&
typeof value === 'object' &&
'record' in value &&
value.record === after
) {
value = { ...value, record: attributed }
}
}
}
const changed = agentSessionStoreRowChanges(state, draft)
const writes = changed ?? emptyJournalWriterStoreRows()
const acknowledged = {
...writes,
records: { upsert: [...writes.records.upsert], remove: [...writes.records.remove] },
operations: {
upsert: [...writes.operations.upsert],
remove: [...writes.operations.remove, ...touched.operations.remove].filter(
(key) => !writes.operations.upsert.some(([id]) => id === key)
)
}
}
for (const id of identity.recordIds) {
if (acknowledged.records.upsert.some(([key]) => key === id)) {
continue
}
const record = draft.records.get(id)
if (record) {
acknowledged.records.upsert.push([id, JSON.stringify(encodeAgentSessionRecord(record))])
} else if (!draft.unreadableRecords.has(id)) {
acknowledged.records.remove.push(id)
}
}
for (const key of operationKeys) {
if (acknowledged.operations.upsert.some(([id]) => id === key)) {
continue
}
const row = draft.operations.get(key)
if (row) {
acknowledged.operations.upsert.push([key, JSON.stringify(row)])
} else {
acknowledged.operations.remove.push(key)
}
}
return {
writes,
acknowledged,
value,
changed: changed !== null || touched.operations.remove.length > 0
}
}
@@ -1,28 +1,17 @@
// Publish drafts only after row commit so readers never see changes that can roll back.
import { encodeAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record-stored-form'
import { encodeAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record-stored-form'
import type {
AgentSessionStoreState,
RetiredAgentSessionClaimKey
} from './agent-session-store-state'
} from '../../runtime/agent-session/records/agent-session-store-state'
import {
isReadableAgentSessionStoreOperation,
isReadableAgentSessionStoreRecord,
isReadableAgentSessionStoreTab,
isReadableRetiredAgentSessionClaimKey
} from './agent-session-store-row-rules'
import type { PersistedAgentSessionTab } from '../agent-session-tab-table'
/** Unreadable rows are derived at load and never written, so the draft shares them. */
export function draftAgentSessionStoreState(state: AgentSessionStoreState): AgentSessionStoreState {
return {
...state,
records: new Map(state.records),
operations: new Map(state.operations),
retiredClaimKeys: [...state.retiredClaimKeys],
sessionTabs: state.sessionTabs?.clone() ?? null
}
}
} from '../../runtime/agent-session/records/agent-session-store-row-rules'
import type { PersistedAgentSessionTab } from '../../runtime/agent-session/agent-session-tab-table'
type KeyedRowWrites = { upsert: [key: string, json: string][]; remove: string[] }
@@ -75,7 +64,7 @@ function retiredClaimKeysChanged(
}
/** Diff rows by identity; validate their serialized form with load rules before committing. */
export function agentSessionStoreDraftRowWrites(
export function agentSessionStoreRowChanges(
published: AgentSessionStoreState,
draft: AgentSessionStoreState
): AgentSessionStoreRowWrites | null {
@@ -2,6 +2,7 @@ import type { CommandReceipt, CommandReceiptScope } from './command-receipt-sche
import { insertCommandReceiptIfAbsent, type CommandReceiptInsert } from './command-receipt-table'
import type { JournalOperationReceipt } from './journal-row-writer'
import type { JournalRow } from '../durable-rows/journal-row-schema'
import type { JournalReceiptRowBinding } from '../journal-writer-effects'
type CommandReceiptNotInserted = Extract<CommandReceiptInsert, { inserted: false }>
@@ -15,19 +16,36 @@ export class CommandReceiptExistsError extends Error {
export function buildCommandReceiptTransaction(
scope: CommandReceiptScope,
receipt: CommandReceipt | ((row?: JournalRow) => CommandReceipt)
receipt: CommandReceipt,
binding?: JournalReceiptRowBinding,
committed?: (receipt: CommandReceipt, row: JournalRow['kind'] | null) => void
): JournalOperationReceipt {
return {
write: (db, row) => {
const result = insertCommandReceiptIfAbsent(
db,
scope,
typeof receipt === 'function' ? receipt(row) : receipt
)
write: (db) => {
const result = insertCommandReceiptIfAbsent(db, scope, receipt)
if (!result.inserted) {
throw new CommandReceiptExistsError(result)
}
},
committed: () => undefined
committed: () => committed?.(receipt, null),
stage: async () => ({
effects: [{ kind: 'receipt', scope, receipt, ...(binding ? { row: binding } : {}) }],
settle: (results) => {
if (results === undefined) {
return
}
const result = results[0]
if (
results.length !== 1 ||
!result ||
typeof result !== 'object' ||
!('receipt' in result) ||
!('row' in result)
) {
throw new Error('the writer returned a missing command receipt')
}
committed?.(result.receipt, result.row)
}
})
}
}
@@ -25,6 +25,13 @@ export function moveQueuedStructuredAgentMessage(
fields,
conversationWrite: true,
commandReceipt: {
binding: {
at: 'last',
answer: {
kind: 'no-op',
outcome: { kind: 'queue-move', messageId: params.messageId, status: 'moved' }
}
},
result: () => ({
kind: 'no-op',
outcome: { kind: 'queue-move', messageId: params.messageId, status: 'moved' }
@@ -97,6 +97,7 @@ export function sendQueuedStructuredAgentMessage(
conversationWrite: true,
commandReceipt: {
result: (row) => journalRowReceiptResult(row, 'submission'),
binding: { at: 'last', kinds: ['submission'], answer: 'journal-row' },
unwritten: (value, ctx) =>
submissionRowReceipt(ctx, 'submission' in value ? value.submission : undefined)
},
@@ -210,6 +211,7 @@ export function deleteQueuedStructuredAgentMessage(
conversationWrite: true,
commandReceipt: {
result: () => ({ kind: 'queued-draft', messageId }),
binding: { at: 'last', answer: { kind: 'queued-draft', messageId } },
unwritten: (value) =>
value.deleted
? null
@@ -258,6 +260,7 @@ export function resumeStructuredAgentQueue(
conversationWrite: true,
commandReceipt: {
result: (row) => journalRowReceiptResult(row, 'tombstone'),
binding: { at: 'last', kinds: ['tombstone'], answer: 'journal-row' },
unwritten: () => ({ kind: 'no-op', outcome: { kind: 'queue-resume', resumed: false } })
},
run: async (ctx) => ({
@@ -16,7 +16,7 @@ import type { StructuredAgentSessionEndedEvent } from '../providers/structured-a
export type StructuredAgentSessionLeaseStore = Pick<
AgentSessionRecordStore,
'getRecord' | 'transitionHandoff'
'getRecord' | 'updateRecord'
>
/** Release the observed child; throw agent_session_checkpoint_stale if ownership changed. */
@@ -60,25 +60,10 @@ export async function upgradeStoredStructuredAgentSessionOwnerExitEvidence(
record.lease.deathEvidence?.kind === 'kill-delivered' &&
record.lease.deathEvidence.ownerFence === event.fence
) {
await store.transitionHandoff(event.sessionId, (current) => {
if (
current.lease.claimStatus !== 'released' ||
current.lease.deathEvidence?.kind !== 'kill-delivered' ||
current.lease.deathEvidence.ownerFence !== event.fence
) {
return current
}
return {
...current,
lease: {
...current.lease,
deathEvidence: {
...current.lease.deathEvidence,
kind: 'exit-observed',
observedAt: event.observedAt ?? now
}
}
}
await store.updateRecord(event.sessionId, {
kind: 'exit-observed',
fence: event.fence,
observedAt: event.observedAt ?? now
})
}
}
@@ -109,10 +109,7 @@ export class StructuredAgentSessionSavedStatus {
const entry = { edge }
this.queued.set(sessionId, entry)
const write = this.deps()
.store.transitionHandoff(sessionId, (record) => {
const { lastTurn: _previous, ...rest } = record
return lastTurn ? { ...rest, lastTurn } : _previous ? rest : record
})
.store.updateRecord(sessionId, { kind: 'last-turn', lastTurn })
.then(
() => {},
(error: unknown) => {
@@ -1,10 +1,7 @@
// Atomically accept Stop/withdrawals/receipt before acting on the captured target.
// Queue session-ending wind-down in the mutation’s tick; saved failures answer from the receipt.
import {
cancelAgentSessionUsageLimitContinue,
type UsageLimitContinueIdentity
} from '../../../../shared/agent-session/lifecycle/agent-session-usage-limit-continue'
import type { UsageLimitContinueIdentity } from '../../../../shared/agent-session/lifecycle/agent-session-usage-limit-continue'
import { usageLimitContinueIdentity } from '../../../../shared/native-chat/native-chat-usage-limit-cut'
import type {
AgentSessionCancelResult,
@@ -264,8 +261,7 @@ export function mutateWithChatStop<TValue>(
envelope,
{
...plan,
acceptanceRecord: (record) =>
withdrawnCut ? cancelAgentSessionUsageLimitContinue(record, withdrawnCut) : record,
acceptanceRecord: { kind: 'stop-continue', enabled: turnId === undefined },
run: (ctx) =>
run(ctx, async () => ({ outcome: await stop(ctx), endsSession: windDown !== undefined }))
},
@@ -14,7 +14,7 @@ import {
composeJournalOperationReceipts,
type JournalOperationReceipt
} from '../../agent-session-journal/writing/journal-row-writer'
import type { JournalRow } from '../../agent-session-journal/durable-rows/journal-row-schema'
import type { JournalReceiptRowBinding } from '../../agent-session-journal/journal-writer-effects'
import type {
MutationCommandReceipt,
MutationPlan
@@ -42,23 +42,23 @@ export async function runCommandReceiptMutation<TValue>(
let acceptedReceipt: CommandReceipt | undefined
let submissionWritten = false
let committed = false
const accepting = (result: (row?: JournalRow) => CommandReceiptResult) => {
const receipt = acceptanceReceipt(input, (row) => {
acceptedReceipt = acceptedCommandReceipt(input, result(row))
return acceptedReceipt
})
return {
write: receipt.write,
committed: () => {
const accepting = (result: CommandReceiptResult, binding?: JournalReceiptRowBinding) => {
const receipt = acceptanceReceipt(
input,
acceptedCommandReceipt(input, result),
binding,
(actual, row) => {
acceptedReceipt = actual
submissionWritten = row === 'submission'
committed = true
receipt.committed?.()
}
}
)
return receipt
}
const receipt = accepting((row) => {
submissionWritten = row?.kind === 'submission'
return commandReceipt.result(row)
})
const receipt = accepting(
commandReceipt.binding.absent ?? { kind: 'stop' },
commandReceipt.binding
)
const commitAlone = async (alone: JournalOperationReceipt): Promise<void> => {
if (!committed) {
await input.store.commitOperationReceipt(alone)
@@ -75,8 +75,7 @@ export async function runCommandReceiptMutation<TValue>(
})
if (!committed) {
const unwritten = ran.ok ? commandReceipt.unwritten?.(ran.value, context) : null
return unwritten &&
!(await commitNoOpReceipt(input, () => commitAlone(accepting(() => unwritten))))
return unwritten && !(await commitNoOpReceipt(input, () => commitAlone(accepting(unwritten))))
? unknownOutcome(input)
: ran
}
@@ -140,13 +139,17 @@ function acceptedCommandReceipt(
function acceptanceReceipt(
input: CommandReceiptIdentity,
receipt: (row?: JournalRow) => CommandReceipt
receipt: CommandReceipt,
binding: JournalReceiptRowBinding | undefined,
accepted: NonNullable<Parameters<typeof buildCommandReceiptTransaction>[3]>
): JournalOperationReceipt {
const { store, operationCallerKey, envelope, plan, fingerprint, context } = input
return composeJournalOperationReceipts(
buildCommandReceiptTransaction(
commandReceiptScope(operationCallerKey, plan.operationIdScope),
receipt
receipt,
binding,
accepted
),
// TEMPORARY: ledger co-write preserves cross-family identity until every mutation uses receipts.
store.operationOutcomeReceipt({
@@ -154,7 +157,7 @@ function acceptanceReceipt(
operationId: envelope.clientOperationId,
fingerprint,
...(plan.acceptanceRecord
? { record: { sessionId: envelope.sessionId, update: plan.acceptanceRecord } }
? { record: { sessionId: envelope.sessionId, action: plan.acceptanceRecord } }
: {}),
now: context.now(),
...(plan.operationIdScope ? { operationIdScope: plan.operationIdScope } : {}),
@@ -1,4 +1,5 @@
import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record'
import type { AgentSessionRecordAcceptance } from '../../../runtime/agent-session/records/agent-session-store-mutation'
import type { JournalReceiptRowBinding } from '../../agent-session-journal/journal-writer-effects'
// Command receipts prove acceptance; other plans use ledger rows and journal replay.
import { readNoChoiceOptionResult } from '../options/structured-agent-session-option-observation'
@@ -52,7 +53,7 @@ export type MutationPlan<TValue> = {
method: string
fields: Record<string, unknown>
operationIdScope?: 'global'
acceptanceRecord?: (record: AgentSessionRecord) => AgentSessionRecord
acceptanceRecord?: AgentSessionRecordAcceptance
/** Needs no writer lease. */
conversationWrite?: true
run: (ctx: AgentSessionTurnContext) => Promise<TurnOutcome<TValue>>
@@ -87,6 +88,7 @@ export type MutationPlan<TValue> = {
/** Insert acceptance with its effect, if absent. */
export type MutationCommandReceipt<TValue> = {
binding: JournalReceiptRowBinding
/** Resolve inside the effect transaction; draft writes have no journal row. */
result: (row: JournalRow | undefined) => CommandReceiptResult
/** Commit a standalone receipt before answering a row-free result; null records nothing. */
@@ -105,6 +107,12 @@ export function journalRowReceiptResult(
function submissionOrDraftReceipt<TValue>(clientMessageId: string): MutationCommandReceipt<TValue> {
return {
binding: {
at: 'last',
kinds: ['submission'],
answer: 'journal-row',
absent: { kind: 'queued-draft', messageId: clientMessageId }
},
result: (row) =>
row
? journalRowReceiptResult(row, 'submission')
@@ -1,4 +1,3 @@
import { isPlanApprovalSubject } from '../../../../shared/agent-session/agent-session-approval-subject'
import type { AgentSessionPromptResult } from '../../../../shared/agent-session/agent-session-wire'
import { refusingNewerOrcaJournal } from '../../agent-session-journal/replay/journal-open-failure'
import type { MutationPlan } from './structured-agent-session-mutation-plans'
@@ -15,7 +14,6 @@ import {
export function promptPlan(
params: AgentSessionPromptRequest
): MutationPlan<AgentSessionPromptResult> {
let planChoice: 'default' | 'plan' | undefined
return {
method: `agentSession.respondTo:${params.kind}`,
fields: {
@@ -26,35 +24,11 @@ export function promptPlan(
},
// Retain the resolved or previously recorded prompt answer in the receipt.
commandReceipt: {
result: (row) => {
const body = row?.kind === 'item' ? row.body : undefined
const choice =
body?.kind === 'approval' &&
body.resolution.state === 'resolved' &&
isPlanApprovalSubject(body.subject)
? body.resolution.selectedOptionId
: undefined
planChoice =
choice === 'allow' || choice === 'allowForSession'
? 'default'
: choice === 'deny'
? 'plan'
: undefined
return promptAnswerReceipt(promptRowAnswer(row))
},
binding: { at: 'last', kinds: ['item'], answer: 'prompt-answer' },
result: (row) => promptAnswerReceipt(promptRowAnswer(row)),
unwritten: (value) => promptAnswerReceipt(value)
},
acceptanceRecord: (record) => {
if (
record.provider !== 'claude' ||
planChoice === undefined ||
(planChoice === 'default' && record.options?.interactionMode !== 'plan') ||
record.options?.interactionMode === planChoice
) {
return record
}
return { ...record, options: { ...record.options, interactionMode: planChoice } }
},
acceptanceRecord: { kind: 'validated-plan' },
run: (ctx) => refusingNewerOrcaJournal(performPrompt(ctx, params)),
replay: (_ctx, _outcome, receipt) => acceptedPromptAnswer(receipt)
}
@@ -30,6 +30,12 @@ import type {
/** Preserve the first committed result, including no-op; later failures answer from that receipt. */
export const STOP_COMMAND_RECEIPT: MutationCommandReceipt<AgentSessionCancelResult> = {
binding: {
at: 'last',
kinds: ['tombstone', 'item'],
answer: 'journal-row',
absent: { kind: 'stop' }
},
result: (row) => (row ? journalRowReceiptResult(row, 'tombstone', 'item') : { kind: 'stop' }),
unwritten: (value) => ({
kind: 'no-op',
@@ -18,7 +18,6 @@ import {
structuredAgentSessionPickReply
} from './structured-agent-session-pick-reply'
import type { StructuredAgentSessionAdapter } from '../providers/structured-agent-session-adapter'
import { pickAgentSessionOption } from '../../../runtime/agent-session/records/agent-session-record-options'
function acceptsOptionPick(
agents: Pick<StructuredAgentRegistry, 'definition'>,
@@ -56,10 +55,7 @@ export function structuredAgentSessionOptionOverridesRefusal(
/** Records literal picks for registered keys; the native control owns value acceptance. */
export async function recordStructuredAgentSessionOptionIntent(
deps: {
store: Pick<
AgentSessionRecordStore,
'getRecord' | 'replaceSessionOptions' | 'reviseSessionOptions'
>
store: Pick<AgentSessionRecordStore, 'getRecord' | 'replaceSessionOptions' | 'updateRecord'>
agents: Pick<StructuredAgentRegistry, 'definition'>
adapter?: Pick<StructuredAgentSessionAdapter, 'projectOptions'>
} & Parameters<typeof savedAgentSessionCatalogModels>[0],
@@ -90,7 +86,9 @@ export async function recordStructuredAgentSessionOptionIntent(
options = { ...record.options, [input.key]: input.value }
} else {
const picked = { sessionId, fence, ...input, models: undefined, now: ctx.now() }
options = (await deps.store.reviseSessionOptions(pickAgentSessionOption, picked)).options ?? {}
options =
(await deps.store.updateRecord(picked.sessionId, { kind: 'pick-option', args: picked }))
.options ?? {}
}
ctx.publish()
return {
@@ -8,7 +8,6 @@ import type {
StructuredAgentSessionProviderChild
} from '../host/structured-agent-session-host-types'
import { structuredAgentSessionOptionOverridesRefusal } from './structured-agent-session-option-intent'
import { recordAgentSessionRanOptions } from '../../../runtime/agent-session/records/agent-session-record-options'
type RanOptionsContext = {
deps: Pick<StructuredAgentSessionHostDeps, 'store' | 'logger' | 'agents' | 'modelCatalog'>
@@ -176,13 +175,16 @@ export async function recordStructuredAgentSessionRanOptions(
return
}
await store
.reviseSessionOptions(recordAgentSessionRanOptions, {
sessionId,
fence: child.fence,
model,
options: ran,
models: undefined,
now: context.now()
.updateRecord(sessionId, {
kind: 'ran-options',
args: {
sessionId,
fence: child.fence,
model,
options: ran,
models: undefined,
now: context.now()
}
})
.catch((error: unknown) =>
logger.warn('recording the options a turn ran failed', {
@@ -9,7 +9,6 @@ import {
} from '../../../../shared/agent-session/lifecycle/agent-session-lease-adjudication'
import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record'
import { PROVIDER_SUPERVISOR_MAX_STOP_MS } from '../../../provider-process/provider-process-supervisor'
import { releaseUnprovenAgentSessionOwner } from '../../../runtime/agent-session/ownership/agent-session-lease-transitions'
import type { AgentSessionRecordStore } from '../../../runtime/agent-session/records/agent-session-record-store'
export type StructuredSessionRecoveryStopSignal = 'SIGTERM' | 'SIGKILL'
@@ -61,13 +60,10 @@ export async function resolveStructuredSessionRecovery(
}
try {
await (owner && !isProvenDeadProbe(probe)
? deps.store.transitionHandoff(sessionId, (latest) =>
releaseUnprovenAgentSessionOwner({
record: latest,
expectedFence: record.lease.runtimeFence,
now: deps.now()
})
)
? deps.store.updateRecord(sessionId, {
kind: 'release-unproven',
args: { expectedFence: record.lease.runtimeFence, now: deps.now() }
})
: deps.store.evictProvenDeadOwner({
sessionId,
expectedFence: record.lease.runtimeFence,
@@ -11,12 +11,7 @@ export function persistRewindRecord(
): Promise<unknown> {
// Drop legacy copied history; the retained journal remains authoritative.
const { retained: _retained, hydrationVerified: _hydrationVerified, ...current } = rewind
return store.transitionHandoff(sessionId, (record) => {
if (record.lease.runtimeFence !== fence) {
throw new Error('agent_session_checkpoint_stale')
}
return { ...record, rewind: current }
})
return store.updateRecord(sessionId, { kind: 'rewind', fence, rewind: current })
}
/** Pre-fork Claude rewinds never ran; refuse them without blocking the already-attached chat. */
@@ -123,9 +123,10 @@ export async function recordStartedHandle(
return store.getRecord(event.sessionId)?.lease.provenHandleLinkId != null
}
try {
const committed = await store.transitionHandoff(event.sessionId, (record) =>
recordAgentSessionProviderHandle({ record, fence: event.fence, link, now: context.now() })
)
const committed = await store.updateRecord(event.sessionId, {
kind: 'provider-handle',
args: { fence: event.fence, link, now: context.now() }
})
// Inherit only a committed new context; a resumed CLI keeps its own later title.
if (event.newConversation ?? (link.origin === 'created' || link.origin === 'forked')) {
context.deps.nameProviderConversation?.(committed)
@@ -1,4 +1,3 @@
import { recordAgentSessionAcquisitionExit } from '../../../runtime/agent-session/agent-session-acquisition-exit-transition'
import {
agentSessionLeaseIsReleased,
agentSessionLeaseOwnerVerdict
@@ -39,21 +38,24 @@ export async function stopWorkspaceSleepChat(input: {
const receipt = deps.adapter.stoppedAcquisition?.(sessionId)
if (ownedStopped && receipt) {
try {
await deps.store.transitionHandoff(sessionId, (record) => {
if (
deps.adapter.stoppedAcquisition?.(sessionId) !== receipt ||
sessions.get(sessionId)?.child
) {
throw new Error('agent_session_ownership_unknown')
}
return recordAgentSessionAcquisitionExit(
record,
await deps.store.updateRecord(
sessionId,
{
kind: 'acquisition-exit',
receipt,
input.fence,
input.now(),
stopped === 'kill-delivered' ? stopped : undefined
)
})
fence: input.fence,
now: input.now(),
deathEvidenceKind: stopped === 'kill-delivered' ? stopped : undefined
},
() => {
if (
deps.adapter.stoppedAcquisition?.(sessionId) !== receipt ||
sessions.get(sessionId)?.child
) {
throw new Error('agent_session_ownership_unknown')
}
}
)
deps.adapter.acknowledgeSessionRelease?.(sessionId, receipt)
} catch (error) {
deps.logger.warn('saving failed acquisition exit evidence failed', {
@@ -165,11 +165,23 @@ async function settleWorkspaceSleepChat(
}
let marked = false
const now = host.deps.now?.() ?? Date.now()
// Check inside the write so the mark and receipt cannot disagree.
await host.deps.store.transitionHandoff(sessionId, (record) => {
marked = quiet(record)
return marked ? { ...record, sleptAt: now, updatedAt: now } : record
})
const changed = new Error('workspace sleep was superseded')
try {
const result = await host.deps.store.updateRecord(
sessionId,
{ kind: 'sleep', now, fence: current.lease.runtimeFence },
() => {
if (!quiet(host.deps.store.requireWritableRecord(sessionId))) {
throw changed
}
}
)
marked = result !== null
} catch (error) {
if (error !== changed) {
throw error
}
}
if (marked) {
host.publishRecordNotes(sessionId)
}
+4 -4
View File
@@ -11,7 +11,6 @@ import { PI_RPC_AGENT } from './rpc-agent-definition'
import { piRpcLaunchPart } from './rpc-launch-resolution'
import { PiRpcSessionAdapter } from './rpc-session-adapter'
import { PI_RPC_RUNTIME_METADATA } from './rpc-runtime-metadata'
import { reviseAgentSessionProviderResumePoint } from '../runtime/agent-session/ownership/agent-session-provider-handle-transition'
function createPiRpcAdapter(context: StructuredAgentAdapterContext): StructuredAgentRuntimeAdapter {
const { deps } = context
@@ -37,9 +36,10 @@ function createPiRpcAdapter(context: StructuredAgentAdapterContext): StructuredA
})
},
persistResumePoint: async ({ sessionId, fence, handle }) => {
await context.store.transitionHandoff(sessionId, (record) =>
reviseAgentSessionProviderResumePoint({ record, fence, handle, now: Date.now() })
)
await context.store.updateRecord(sessionId, {
kind: 'resume-point',
args: { fence, handle, now: Date.now() }
})
},
logger: deps.logger
})
@@ -1,5 +1,7 @@
import type { AgentSessionStoreState } from './agent-session/records/agent-session-store-state'
import type { AgentSessionStoreCommand } from './agent-session/records/agent-session-store-command'
import type { AgentSessionStoreTransactions } from './agent-session/records/agent-session-store-transactions'
import type { AgentSessionRecordCommand } from './agent-session/records/agent-session-record-command'
import { isDeepStrictEqual } from 'node:util'
export abstract class AgentSessionRecordPublication {
constructor(protected readonly transactions: AgentSessionStoreTransactions) {}
@@ -20,29 +22,36 @@ export abstract class AgentSessionRecordPublication {
return () => this.firstRecordListeners.delete(listener)
}
/** Serialize draft mutations; publish to readers only after row commit. */
protected transact = async <T>(
apply: (draft: AgentSessionStoreState) => T,
options?: { inMemoryWhenReadOnly?: boolean }
): Promise<T> => {
let proven: string[] = []
let heldBefore = true
const result = await this.transactions.transact((draft) => {
heldBefore = this.holdsRecords()
if (this.deathEvidenceListeners.size === 0) {
return apply(draft)
protected async commitRecordCommand<C extends AgentSessionRecordCommand>(
id: string,
command: C,
check?: () => void
) {
const before = this.transactions.state.records.get(id)?.lease.deathEvidence
const result = await this.transactions.record(id, command, check)
const after = this.transactions.state.records.get(id)?.lease.deathEvidence
if (after && !isDeepStrictEqual(before, after)) {
this.deathEvidenceListeners.forEach((listener) => listener(id))
}
return result
}
protected async commitStoreCommand<C extends AgentSessionStoreCommand>(
command: C,
check?: () => void
) {
const before = new Map(
[...this.transactions.state.records].map(([id, record]) => [id, record.lease.deathEvidence])
)
const heldBefore = this.holdsRecords()
const result = await this.transactions.command(command, check)
for (const [id, record] of this.transactions.state.records) {
if (
record.lease.deathEvidence &&
!isDeepStrictEqual(before.get(id), record.lease.deathEvidence)
) {
this.deathEvidenceListeners.forEach((listener) => listener(id))
}
const before = new Map(
[...draft.records].map(([id, record]) => [id, record.lease.deathEvidence])
)
const applied = apply(draft)
proven = [...draft.records]
.filter(([id, { lease }]) => lease.deathEvidence && lease.deathEvidence !== before.get(id))
.map(([id]) => id)
return applied
}, options)
for (const sessionId of proven) {
this.deathEvidenceListeners.forEach((listener) => listener(sessionId))
}
if (!heldBefore && this.holdsRecords()) {
this.firstRecordListeners.forEach((listener) => listener())
@@ -4,7 +4,7 @@ import {
} from '../../shared/agent-session/lifecycle/agent-session-record'
import type { AgentSessionConversationView } from '../../shared/agent-session/lifecycle/agent-session-conversation-view'
import type { AgentSessionStoreState } from './agent-session/records/agent-session-store-state'
import type { AgentSessionStoreRowWrites } from './agent-session/records/agent-session-store-draft'
import type { AgentSessionStoreRowWrites } from '../native-chat/agent-session-journal/journal-writer-store-row-changes'
/** The session a committed /clear continued this one in: the durable forward pointer. */
export function clearSuccessor(
@@ -1,44 +1,29 @@
import type { AgentSessionForkedFrom } from '../../../shared/agent-session/lifecycle/agent-session-record'
import type { AgentSessionStoreTransactions } from './records/agent-session-store-transactions'
import {
commitConversationClearRecord,
type AgentSessionConversationClear
} from './records/agent-session-conversation-command-record'
import { settleAgentSessionOperationInto } from './ownership/agent-session-operation-admission'
import { commitAgentSessionRewindCompletion } from './agent-session-rewind-completion'
import type { AgentSessionConversationClear } from './records/agent-session-conversation-command-record'
import type { commitAgentSessionRewindCompletion } from './agent-session-rewind-completion'
export function createAgentSessionConversationReceipts(
transactions: Pick<AgentSessionStoreTransactions, 'receipt'>
transactions: Pick<AgentSessionStoreTransactions, 'mutationReceipt'>
) {
return {
forkBoundary: (sessionId: string, forkedFrom: AgentSessionForkedFrom) =>
transactions.receipt((draft) => {
const record = draft.records.get(sessionId)
if (!record) {
throw new Error('agent_session_fork:record-missing')
}
draft.records.set(sessionId, { ...record, forkedFrom })
}),
transactions.mutationReceipt({ kind: 'fork-boundary', sessionId, forkedFrom }),
clear: (
clear: () => AgentSessionConversationClear,
operation: { callerKey: string; operationId: string }
) =>
transactions.receipt((draft) => {
const completed = clear()
commitConversationClearRecord(draft, completed)
settleAgentSessionOperationInto(draft, {
...operation,
outcome: {
status: 'succeeded',
sessionId: completed.sessionId,
conversationCommand: completed.command
}
})
}),
) => transactions.mutationReceipt(() => ({ kind: 'clear', clear: clear(), operation })),
rewind: (
...args: Parameters<typeof commitAgentSessionRewindCompletion> extends [unknown, ...infer A]
? A
: never
) => transactions.receipt((draft) => commitAgentSessionRewindCompletion(draft, ...args))
) =>
transactions.mutationReceipt({
kind: 'rewind-complete',
sessionId: args[0],
fence: args[1],
rewind: args[2],
childBoundary: args[5]
})
}
}
@@ -1,17 +1,16 @@
import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record'
import type { JournalOperationReceipt } from '../../native-chat/agent-session-journal/writing/journal-row-writer'
import type { AgentSessionOperationOutcome } from '../../../shared/agent-session/lifecycle/agent-session-operation-ledger'
import {
insertAcceptedAgentSessionOperationInto,
import type {
settleAgentSessionOperationInto,
type AgentSessionOperationAcceptance
AgentSessionOperationAcceptance
} from './ownership/agent-session-operation-admission'
import type { AgentSessionRecordAcceptance } from './records/agent-session-store-mutation'
import type { AgentSessionStoreTransactions } from './records/agent-session-store-transactions'
export type AgentSessionOperationReceiptInput = (
| Parameters<typeof settleAgentSessionOperationInto>[1]
| (AgentSessionOperationAcceptance & { outcome: AgentSessionOperationOutcome })
) & { record?: { sessionId: string; update: (record: AgentSessionRecord) => AgentSessionRecord } }
) & { record?: { sessionId: string; action: AgentSessionRecordAcceptance } }
export function agentSessionOperationOutcomeReceipt(
transactions: AgentSessionStoreTransactions,
@@ -19,23 +18,14 @@ export function agentSessionOperationOutcomeReceipt(
): JournalOperationReceipt {
const submissionSessionId =
args.outcome.status === 'succeeded' ? args.outcome.sessionId : undefined
return transactions.receipt(
(draft) => {
if ('fingerprint' in args) {
insertAcceptedAgentSessionOperationInto(draft, args)
} else {
settleAgentSessionOperationInto(draft, args)
}
if (args.record) {
const record = draft.records.get(args.record.sessionId)
if (record) {
draft.records.set(record.sessionId, args.record.update(record))
}
}
const { record, ...operation } = args
return transactions.mutationReceipt(
{
kind: 'operation',
operation,
...(record ? { record } : {}),
...(submissionSessionId ? { wakeSessionId: submissionSessionId } : {})
},
// TEMPORARY: ledger co-write preserves cross-family identity until every mutation uses receipts.
'fingerprint' in args
? { insertOperationsIfAbsent: true, submissionSessionId }
: { submissionSessionId }
submissionSessionId
)
}
@@ -7,6 +7,11 @@ import type { AgentSessionStoreState } from './records/agent-session-store-state
let incarnation = randomUUID()
export type AgentSessionRuntimeFacts = {
incarnation: string
ends: AgentSessionStoreState['runtimeEnds']
}
export function agentSessionRuntimeIncarnation(): string {
return incarnation
}
@@ -15,16 +20,17 @@ export function beginAgentSessionRuntimeIncarnationForTest(): void {
incarnation = randomUUID()
}
function attributed(
export function attributeAgentSessionRuntimeRecord(
before: AgentSessionRecord | undefined,
after: AgentSessionRecord,
runtimeEnds: AgentSessionStoreState['runtimeEnds']
runtimeEnds: AgentSessionStoreState['runtimeEnds'],
runtime: string = incarnation
): AgentSessionRecord {
const { ownerProcess, deathEvidence } = after.lease
if (ownerProcess && !ownerProcess.runtime && ownerProcess !== before?.lease.ownerProcess) {
return {
...after,
lease: { ...after.lease, ownerProcess: { ...ownerProcess, runtime: incarnation } }
lease: { ...after.lease, ownerProcess: { ...ownerProcess, runtime } }
}
}
const heldBy = before?.lease.ownerProcess?.runtime
@@ -33,7 +39,7 @@ function attributed(
deathEvidence === before?.lease.deathEvidence ||
deathEvidence.runtimeEnd !== undefined ||
!heldBy ||
heldBy === incarnation ||
heldBy === runtime ||
// Terminal-owned agents never depended on Orca's pipes.
before?.lease.claimStatus === 'conflicted' ||
!runtimeEnds
@@ -55,7 +61,7 @@ export function attributeAgentSessionRuntime(
for (const [sessionId, record] of draft.records) {
const before = published.records.get(sessionId)
if (record !== before) {
const next = attributed(before, record, draft.runtimeEnds)
const next = attributeAgentSessionRuntimeRecord(before, record, draft.runtimeEnds)
if (next !== record) {
draft.records.set(sessionId, next)
}
@@ -204,9 +204,10 @@ export abstract class AgentSessionRecordTabs extends AgentSessionRecordPublicati
this.transactions.state.sessionTabs !== null && !this.isSessionTabVisible(id)
initializeSessionTabs(): Promise<void> {
return this.transact((draft) =>
initializeAgentSessionTabs(draft, this.transactions.legacySessionTabIds)
)
return this.commitStoreCommand({
kind: 'tabs-initialize',
legacyTabIds: this.transactions.legacySessionTabIds
})
}
getVisibleSessionTabIndex = (): { present: boolean; sessionIds: string[] } =>
@@ -223,53 +224,26 @@ export abstract class AgentSessionRecordTabs extends AgentSessionRecordPublicati
check?: () => void,
capture?: (tabId: string | null) => void
): Promise<void> {
return this.transact((draft) => {
check?.()
const retired =
effectiveAgentSessionTabs(draft, this.transactions.legacySessionTabIds).tabIdFor(
sessionId
) ?? null
setAgentSessionTabVisibility(
draft,
return this.commitStoreCommand(
{
kind: 'tab-visibility',
sessionId,
visible,
tabId,
this.transactions.legacySessionTabIds
)
capture?.(visible ? (draft.sessionTabs?.tabIdFor(sessionId) ?? null) : retired)
})
}
setSwitchedSessionTabVisibility(
sessionId: string,
tabId: string,
visible: boolean,
admit: () => boolean
): Promise<boolean> {
return this.transact((draft) => {
if (
(visible
? draft.sessionTabs?.tabIdFor(sessionId) !== undefined
: draft.sessionTabs?.tabIdFor(sessionId) !== tabId) ||
!admit()
) {
return false
}
setAgentSessionTabVisibility(
draft,
sessionId,
visible,
tabId,
this.transactions.legacySessionTabIds
)
return true
legacyTabIds: this.transactions.legacySessionTabIds
},
check
).then((tab) => {
capture?.(tab)
})
}
/** Publish the complete tab index in one write; a partial index would drop remaining chats on restart. */
showSessionTabs(sessionIds: readonly string[]): Promise<void> {
return this.transact((draft) =>
showAgentSessionTabs(draft, sessionIds, this.transactions.legacySessionTabIds)
)
return this.commitStoreCommand({
kind: 'tabs-show',
sessionIds,
legacyTabIds: this.transactions.legacySessionTabIds
})
}
}
@@ -1,4 +1,3 @@
import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record'
import { claudeProviderHandle } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding'
import type { ClaudeEnvDeps } from '../../../claude/structured/launch/claude-structured-child-env'
import { ClaudeStructuredSessionAdapter } from '../../../claude/structured/claude-structured-session-adapter'
@@ -9,10 +8,6 @@ import type {
import { claudeProviderHandleLink } from '../../../claude/structured/claude-structured-owner-identity'
import type { StructuredAgentSessionLifecycleEvent } from '../../../native-chat/agent-session-wire/providers/structured-agent-session-adapter'
import {
recordAgentSessionProviderHandle,
reviseAgentSessionProviderResumePoint
} from '../ownership/agent-session-provider-handle-transition'
import type { AgentSessionRecordStore } from '../records/agent-session-record-store'
import {
ClaudeAtRestCommandCatalog,
@@ -108,9 +103,9 @@ export function createStructuredClaudeRuntimeAdapter(
persistHandle: async ({ sessionId, providerSessionId, leafUuid, fence }) => {
const currentFence = store.getRecord(sessionId)?.lease.runtimeFence ?? fence
const observedAt = Date.now()
await store.transitionHandoff(sessionId, (record: AgentSessionRecord) =>
recordAgentSessionProviderHandle({
record,
await store.updateRecord(sessionId, {
kind: 'provider-handle',
args: {
fence: currentFence,
link: claudeProviderHandleLink({
sessionId: providerSessionId,
@@ -120,18 +115,18 @@ export function createStructuredClaudeRuntimeAdapter(
observedAt
}),
now: observedAt
})
)
}
})
},
persistResumePoint: async ({ sessionId, providerSessionId, leafUuid, fence }) => {
await store.transitionHandoff(sessionId, (record: AgentSessionRecord) =>
reviseAgentSessionProviderResumePoint({
record,
await store.updateRecord(sessionId, {
kind: 'resume-point',
args: {
fence,
handle: claudeProviderHandle(providerSessionId, leafUuid),
now: Date.now()
})
)
}
})
},
onEvent: (event) => {
const lifecycle = structuredClaudeLifecycleEvent(event)
@@ -1,4 +1,3 @@
import { newChatPermissionMode } from '../../../../shared/agent-launch/permissions/agent-chat-permission-mode'
import type { AgentSessionStoreTransactions } from '../records/agent-session-store-transactions'
/** Backfill once as the chat host installs; legacy chats used their agent's Arguments. */
@@ -9,24 +8,10 @@ export function backfillAgentSessionPermissionModes(
if (store.readOnly) {
return Promise.resolve()
}
return store.transact((draft) => {
for (const [sessionId, record] of draft.records) {
if (record.permissionMode !== undefined) {
continue
}
// Temporary: only the dev team's hourly builds saved the mode among options; remove after 1.4.226 ships.
const { permissionMode: saved, ...options } = record.options ?? {}
if (saved !== undefined) {
draft.records.set(sessionId, { ...record, options, permissionMode: saved })
continue
}
const permissionMode = newChatPermissionMode(
record.provider,
ranWithFullAccess(record.provider) ? 'full-access' : 'ask'
)
if (permissionMode) {
draft.records.set(sessionId, { ...record, permissionMode })
}
}
})
const fullAccess = new Map(
[...new Set([...store.state.records.values()].map((record) => record.provider))].map(
(provider) => [provider, ranWithFullAccess(provider)]
)
)
return store.command({ kind: 'permission-backfill', fullAccess })
}
@@ -1,10 +1,9 @@
// Retry crash-interrupted create ids at the next fence only after recovery releases the old reservation; held reservations replay unchanged.
import { closeTestJournalHostDatabases } from '../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import {
AGENT_SESSION_MAX_NEW_OPERATION_AGE_MS,
AGENT_SESSION_OPERATION_FUTURE_SKEW_MS
@@ -12,7 +11,11 @@ import {
import type { AgentSessionOwnerProbe } from '../../../../shared/agent-session/lifecycle/agent-session-lease-adjudication'
import type { AgentSessionLease } from '../../../../shared/agent-session/lifecycle/agent-session-record'
import type { AgentSessionRecordStore } from '../records/agent-session-record-store'
import { openTestAgentSessionRecordStore } from '../records/agent-session-record-store-test-harness'
import {
openTestAgentSessionRecordStore,
closeTestAgentSessionRecordStores,
withTestAgentSessionDatabase
} from '../records/agent-session-record-store-test-harness'
import type { AgentSessionReserveRequest } from './agent-session-reservation-admission'
import { codexProviderHandle } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding'
@@ -30,7 +33,7 @@ beforeEach(async () => {
})
afterEach(async () => {
await closeTestJournalHostDatabases()
await closeTestAgentSessionRecordStores()
await rm(directory, { recursive: true, force: true })
})
@@ -81,7 +84,7 @@ describe('a create retried after recovery released its reservation', () => {
['its operation row has expired', PAST_EXPIRY]
])('continues when %s, and the old reservation can never commit', async (_case, elapsed) => {
const now = NOW + elapsed
const store = await releasedByRestart(now)
const store = await releasedByRestart(NOW + 1_000)
const continued = await store.reserveOwner(createRequest({ spawnToken: () => 'spawn-b', now }))
expect(continued.disposition).toBe('reserved')
@@ -105,11 +108,9 @@ describe('a create retried after recovery released its reservation', () => {
store.commitProcessIdentity({ sessionId: SESSION, fence: 3, process: lateSpawn, now })
).rejects.toThrow('agent_session_ownership_unknown')
const mint = vi.fn(() => 'spawn-c')
const retried = await store.reserveOwner(createRequest({ spawnToken: mint, now }))
const retried = await store.reserveOwner(createRequest({ spawnToken: 'spawn-c', now }))
expect(retried.disposition).toBe('replayed')
expect(retried.record.lease).toMatchObject({ runtimeFence: 3, reservedSpawnToken: 'spawn-b' })
expect(mint).not.toHaveBeenCalled()
})
it('refuses an expired retry of a session that has no record', async () => {
@@ -160,10 +161,13 @@ describe('a create retried after recovery released its reservation', () => {
])('still refuses a retry whose reservation is %s', async (_case, lease, code) => {
const store = await open()
await store.reserveOwner(createRequest())
await store.transitionHandoff(SESSION, (record) => ({
...record,
lease: { ...record.lease, ...lease }
}))
await withTestAgentSessionDatabase(directory, (db) =>
db
.prepare(
`UPDATE agent_session_records SET record_json=json_patch(record_json,?) WHERE session_id=?`
)
.run(JSON.stringify({ lease }), SESSION)
)
await expect(store.reserveOwner(createRequest())).rejects.toThrow(code)
expect(store.getRecord(SESSION)?.lease.runtimeFence).toBe(1)
@@ -14,7 +14,7 @@ export type AgentSessionRestartProbeArgs = {
now: number
}
type RestartProbe = { record: AgentSessionRecord; probe: AgentSessionOwnerProbe }
export type AgentSessionRestartProbe = { record: AgentSessionRecord; probe: AgentSessionOwnerProbe }
export async function collectAgentSessionRestartProbes(
store: {
@@ -22,8 +22,8 @@ export async function collectAgentSessionRestartProbes(
getRecord: (sessionId: string) => AgentSessionRecord | null
},
args: AgentSessionRestartProbeArgs
): Promise<Map<string, RestartProbe>> {
const probes = new Map<string, RestartProbe>()
): Promise<Map<string, AgentSessionRestartProbe>> {
const probes = new Map<string, AgentSessionRestartProbe>()
const target = args.sessionId === undefined ? null : store.getRecord(args.sessionId)
const candidates = args.sessionId === undefined ? store.listRecords() : target ? [target] : []
const records = candidates.filter((record) => record.lease.unreconciled)
@@ -46,7 +46,7 @@ export async function collectAgentSessionRestartProbes(
export function applyAgentSessionRestartProbes(
state: AgentSessionStoreState,
probes: ReadonlyMap<string, RestartProbe>,
probes: ReadonlyMap<string, AgentSessionRestartProbe>,
now: number
): Map<string, AgentSessionRecord> {
const reconciled = new Map<string, AgentSessionRecord>()
@@ -10,7 +10,7 @@ import { nextAgentSessionFence } from '../../../../shared/agent-session/lifecycl
import { assertFence, withLease } from './agent-session-lease-transitions'
import type { AgentSessionRecordStore } from '../records/agent-session-record-store'
export type AgentSessionRecordTransitionStore = Pick<AgentSessionRecordStore, 'transitionHandoff'>
export type AgentSessionRecordTransitionStore = Pick<AgentSessionRecordStore, 'updateRecord'>
/** Only this host's owned lease is releasable; handoffs and free leases use other transitions. */
export function isSurfaceReleasableAgentSessionRecord(record: AgentSessionRecord): boolean {
@@ -66,7 +66,5 @@ export function releaseStoredAgentSessionOwnerAfterSurfaceClose(
exitReason?: string
}
): Promise<AgentSessionRecord> {
return store.transitionHandoff(args.sessionId, (record) =>
releaseAgentSessionOwnerAfterSurfaceClose({ ...args, record })
)
return store.updateRecord(args.sessionId, { kind: 'release-surface', args })
}
@@ -115,4 +115,21 @@ describe('AgentSessionRecordStore.setConversationName', () => {
await store.compareAndSetConversationName(SESSION, 'Stale generation', placeholder)
).toBeNull()
})
it('checks a stale generation against the saved user name before writing', async () => {
const store = await reservedStore()
await store.compareAndSetConversationName(SESSION, 'First prompt', null)
const stale = await openTestAgentSessionRecordStore(directory)
await store.setUserConversationName(SESSION, 'First prompt', 'rename')
expect(
await stale.compareAndSetConversationName(SESSION, 'Late generated name', 'First prompt')
).toBeNull()
await stale.pinLaunchDirectory(SESSION, '/workspace/current')
expect((await openTestAgentSessionRecordStore(directory)).getRecord(SESSION)).toMatchObject({
conversationName: 'First prompt',
conversationNameSource: 'user',
launchDirectory: '/workspace/current'
})
})
})
@@ -1,8 +1,8 @@
import { agentSessionRefusalError } from '../../../../shared/agent-session/failures/agent-session-wire-refusals'
import { onJournalReceiptCommitted } from '../../../native-chat/agent-session-journal/writing/journal-row-writer'
import type { JournalOperationReceipt } from '../../../native-chat/agent-session-journal/writing/journal-row-writer'
import { commitAgentSessionFounding } from './agent-session-founding-admission'
import type { AgentSessionReserveRequest } from '../ownership/agent-session-reservation-admission'
import { draftAgentSessionStoreState } from './agent-session-store-draft'
import { copyAgentSessionStoreCache } from './agent-session-store-cache'
import type { AgentSessionStoreTransactions } from './agent-session-store-transactions'
/** Founding shares the store's admission and publishes only after the message transaction commits. */
@@ -13,15 +13,18 @@ export function createAgentSessionFoundingStore(
return {
prepare: (request: AgentSessionReserveRequest) =>
commitAgentSessionFounding(
draftAgentSessionStoreState(transactions.state),
copyAgentSessionStoreCache(transactions.state),
request,
transactions.legacySessionTabIds
),
commit: async (request: AgentSessionReserveRequest) => {
let heldBefore = true
const result = await transactions.transact((draft) => {
heldBefore = draft.records.size > 0 || draft.unreadableRecords.size > 0
return commitAgentSessionFounding(draft, request, transactions.legacySessionTabIds)
const heldBefore =
transactions.state.records.size > 0 || transactions.state.unreadableRecords.size > 0
const result = await transactions.command({
kind: 'found',
request: { ...request, spawnToken: '' },
leaseTtlMs: 0,
legacyTabIds: transactions.legacySessionTabIds
})
if (!heldBefore) {
firstRecordListeners.forEach((listener) => listener())
@@ -29,41 +32,23 @@ export function createAgentSessionFoundingStore(
return result
},
receipt: (request: AgentSessionReserveRequest): JournalOperationReceipt => {
let heldBefore = true
const receipt = transactions.receipt((draft) => {
heldBefore = draft.records.size > 0 || draft.unreadableRecords.size > 0
const result = commitAgentSessionFounding(draft, request, transactions.legacySessionTabIds)
if (result.disposition === 'replayed') {
throw agentSessionRefusalError('agent_session_operation_unknown', {
reason: 'outcomeUnknown'
})
const heldBefore =
transactions.state.records.size > 0 || transactions.state.unreadableRecords.size > 0
const receipt = transactions.mutationReceipt({
kind: 'command',
command: {
kind: 'found',
request: { ...request, spawnToken: '' },
leaseTtlMs: 0,
legacyTabIds: transactions.legacySessionTabIds,
refuseReplay: true
}
})
const founded = () => {
return onJournalReceiptCommitted(receipt, () => {
if (!heldBefore) {
firstRecordListeners.forEach((listener) => listener())
}
}
return {
write: receipt.write,
committed: () => {
receipt.committed?.()
founded()
},
stage: async (context) => {
const staged = await receipt.stage(context)
return {
effects: staged.effects,
adopt: staged.adopt,
settle: (results) => {
staged.settle(results)
if (results) {
founded()
}
}
}
}
}
})
}
}
}
@@ -0,0 +1,202 @@
import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record'
import type { AgentSessionOptionsReplacement } from '../../../../shared/agent-session/options/agent-session-options-replacement'
import { withAcquiredAgentSessionAccount } from '../../../../shared/agent-session/lifecycle/agent-session-acquired-account'
import {
cancelAgentSessionUsageLimitContinue,
type UsageLimitContinueIdentity
} from '../../../../shared/agent-session/lifecycle/agent-session-usage-limit-continue'
import type { AgentSessionRewindRecord } from '../../../../shared/agent-session/lifecycle/agent-session-rewind'
import type { AgentSessionLastTurn } from '../../../../shared/agent-session/lifecycle/agent-session-last-turn'
import type { createAgentSessionOwnerProof } from '../../agent-session-owner-proof'
import { recordAgentSessionAcquisitionExit } from '../agent-session-acquisition-exit-transition'
import {
commitAgentSessionProcessIdentity,
evictAgentSessionOwner,
proveAgentSessionOwner,
releaseUnprovenAgentSessionOwner
} from '../ownership/agent-session-lease-transitions'
import {
recordAgentSessionProviderHandle,
reviseAgentSessionProviderResumePoint
} from '../ownership/agent-session-provider-handle-transition'
import { releaseAgentSessionOwnerAfterSurfaceClose } from '../ownership/agent-session-surface-release-transition'
import { pinAgentSessionRecordLaunchDirectory } from './agent-session-record-launch-directory'
import {
pickAgentSessionOption,
recordAgentSessionRanOptions,
replaceAgentSessionRecordOptions,
type AgentSessionOptionPick,
type AgentSessionRanOptions
} from './agent-session-record-options'
import {
setAgentSessionRecordConversationName,
setAgentSessionRecordUserName,
type AgentSessionUserNameWrite
} from './agent-session-record-conversation-name'
type WithoutRecord<F extends (...args: never[]) => unknown> = Omit<Parameters<F>[0], 'record'>
export type AgentSessionRecordCommand =
| { kind: 'name'; name: string | null; now: number }
| { kind: 'user-name'; name: string; write: AgentSessionUserNameWrite; now: number }
| {
kind: 'name-if-current'
name: string | null
expected: string | null
contextId: string | null
now: number
}
| { kind: 'launch-directory'; launchDirectory: string; now: number }
| { kind: 'options'; args: AgentSessionOptionsReplacement }
| { kind: 'pick-option'; args: AgentSessionOptionPick }
| { kind: 'ran-options'; args: AgentSessionRanOptions }
| { kind: 'process'; args: WithoutRecord<typeof commitAgentSessionProcessIdentity> }
| {
kind: 'prove'
args: Parameters<ReturnType<typeof createAgentSessionOwnerProof>>[0]
leaseTtlMs: number
}
| { kind: 'evict'; args: WithoutRecord<typeof evictAgentSessionOwner> }
| { kind: 'release-unproven'; args: WithoutRecord<typeof releaseUnprovenAgentSessionOwner> }
| { kind: 'provider-handle'; args: WithoutRecord<typeof recordAgentSessionProviderHandle> }
| { kind: 'resume-point'; args: WithoutRecord<typeof reviseAgentSessionProviderResumePoint> }
| {
kind: 'release-surface'
args: WithoutRecord<typeof releaseAgentSessionOwnerAfterSurfaceClose>
}
| { kind: 'cancel-continue'; cut: UsageLimitContinueIdentity }
| { kind: 'last-turn'; lastTurn?: AgentSessionLastTurn }
| { kind: 'rewind'; fence: number; rewind: AgentSessionRewindRecord }
| { kind: 'sleep'; now: number; fence: number }
| {
kind: 'acquisition-exit'
receipt: Parameters<typeof recordAgentSessionAcquisitionExit>[1]
fence: number
now: number
deathEvidenceKind?: 'kill-delivered'
}
| { kind: 'exit-observed'; fence: number; observedAt: number }
export type AgentSessionRecordCommandResult<C extends AgentSessionRecordCommand> = C extends {
kind: 'user-name'
}
? { record: AgentSessionRecord; applied: boolean }
: C extends { kind: 'name-if-current' | 'sleep' }
? AgentSessionRecord | null
: AgentSessionRecord
export function applyAgentSessionRecordCommand(
record: AgentSessionRecord,
command: AgentSessionRecordCommand
): {
record: AgentSessionRecord
result: AgentSessionRecordCommandResult<AgentSessionRecordCommand>
} {
let next: AgentSessionRecord
switch (command.kind) {
case 'name':
next = setAgentSessionRecordConversationName(record, command.name, command.now)
break
case 'user-name': {
const result = setAgentSessionRecordUserName(record, command.name, command.write, command.now)
return { record: result.record, result }
}
case 'name-if-current':
if (
record.conversationNameSource === 'user' ||
(record.conversationName ?? null) !== command.expected ||
(record.providerContextBoundary?.operationId ?? null) !== command.contextId
) {
return { record, result: null }
}
next = setAgentSessionRecordConversationName(record, command.name, command.now)
break
case 'launch-directory':
next = pinAgentSessionRecordLaunchDirectory(record, command.launchDirectory, command.now)
break
case 'options':
next = replaceAgentSessionRecordOptions(record, command.args)
break
case 'pick-option':
next = pickAgentSessionOption(record, command.args)
break
case 'ran-options':
next = recordAgentSessionRanOptions(record, command.args)
break
case 'process':
next = commitAgentSessionProcessIdentity({ ...command.args, record })
break
case 'prove':
next = withAcquiredAgentSessionAccount(
proveAgentSessionOwner({
...command.args,
record,
leaseTtlMs: command.args.leaseTtlMs ?? command.leaseTtlMs
}),
command.args.accountAcquisition
)
break
case 'evict':
next = evictAgentSessionOwner({ ...command.args, record })
break
case 'release-unproven':
next = releaseUnprovenAgentSessionOwner({ ...command.args, record })
break
case 'provider-handle':
next = recordAgentSessionProviderHandle({ ...command.args, record })
break
case 'resume-point':
next = reviseAgentSessionProviderResumePoint({ ...command.args, record })
break
case 'release-surface':
next = releaseAgentSessionOwnerAfterSurfaceClose({ ...command.args, record })
break
case 'cancel-continue':
next = cancelAgentSessionUsageLimitContinue(record, command.cut)
break
case 'last-turn': {
const { lastTurn: previous, ...rest } = record
next = command.lastTurn ? { ...rest, lastTurn: command.lastTurn } : previous ? rest : record
break
}
case 'rewind':
if (record.lease.runtimeFence !== command.fence) {
throw new Error('agent_session_checkpoint_stale')
}
next = { ...record, rewind: command.rewind }
break
case 'sleep':
if (record.lease.runtimeFence !== command.fence) {
throw new Error('agent_session_checkpoint_stale')
}
next = { ...record, sleptAt: command.now, updatedAt: command.now }
break
case 'acquisition-exit':
next = recordAgentSessionAcquisitionExit(
record,
command.receipt,
command.fence,
command.now,
command.deathEvidenceKind
)
break
case 'exit-observed':
next =
record.lease.claimStatus === 'released' &&
record.lease.deathEvidence?.kind === 'kill-delivered' &&
record.lease.deathEvidence.ownerFence === command.fence
? {
...record,
lease: {
...record.lease,
deathEvidence: {
...record.lease.deathEvidence,
kind: 'exit-observed',
observedAt: command.observedAt
}
}
}
: record
}
return { record: next, result: next }
}
@@ -12,7 +12,7 @@ import { decodePersistedAgentSessionRecord } from '../../../../shared/agent-sess
import type Database from '../../../sqlite/sync-database'
import type { SqliteRow } from '../../../sqlite/sqlite-statement'
import type { AgentSessionStoreState } from './agent-session-store-state'
import type { AgentSessionStoreRowWrites } from './agent-session-store-draft'
import type { AgentSessionStoreRowWrites } from '../../../native-chat/agent-session-journal/journal-writer-store-row-changes'
import { agentSessionRefusalError } from '../../../../shared/agent-session/failures/agent-session-wire-refusals'
import {
isReadableAgentSessionStoreOperation,
@@ -73,6 +73,42 @@ function unreadableRecordReason(value: unknown): string {
: 'unsupported_schema'
}
export function loadAgentSessionStoreRecordRow(
state: AgentSessionStoreState,
sessionId: string,
json: string | null,
unreconciled: boolean
): void {
const parsed = parseJson(json)
const value = parsed.ok ? parsed.value : json
if (parsed.ok && isReadableAgentSessionStoreRecord(sessionId, value)) {
const { record } = decodePersistedAgentSessionRecord(value)
state.records.set(sessionId, {
...record,
lease: {
...withoutRetiredLeaseLatches(record.lease),
...(unreconciled ? { unreconciled: true } : {})
}
})
return
}
const decoded =
isPersistedAgentSessionObservationRecord(value) && value.sessionId === sessionId
? decodePersistedAgentSessionRecord(structuredClone(value)).record
: undefined
const conversation = decoded
? agentSessionConversationView({
...decoded,
lease: { ...decoded.lease, unreconciled: true }
})
: undefined
state.unreadableRecords.set(sessionId, {
reason: unreadableRecordReason(value),
raw: value,
...(conversation ? { conversation: Object.freeze(conversation) } : {})
})
}
/** Loaded leases are unreconciled until this host proves ownership; persisted state alone grants no writer.
* Unreadable operation/key/tab rows are skipped; unreadable records are set aside intact. */
export function loadAgentSessionStoreRows(db: Database.Database): AgentSessionStoreState {
@@ -98,31 +134,7 @@ export function loadAgentSessionStoreRows(db: Database.Database): AgentSessionSt
if (sessionId === null) {
continue
}
const parsed = parseJson(text(row, 'record_json'))
const value = parsed.ok ? parsed.value : text(row, 'record_json')
if (parsed.ok && isReadableAgentSessionStoreRecord(sessionId, value)) {
const { record } = decodePersistedAgentSessionRecord(value)
state.records.set(sessionId, {
...record,
lease: { ...withoutRetiredLeaseLatches(record.lease), unreconciled: true }
})
} else {
const decoded =
isPersistedAgentSessionObservationRecord(value) && value.sessionId === sessionId
? decodePersistedAgentSessionRecord(structuredClone(value)).record
: undefined
const conversation = decoded
? agentSessionConversationView({
...decoded,
lease: { ...decoded.lease, unreconciled: true }
})
: undefined
state.unreadableRecords.set(sessionId, {
reason: unreadableRecordReason(value),
raw: value,
...(conversation ? { conversation: Object.freeze(conversation) } : {})
})
}
loadAgentSessionStoreRecordRow(state, sessionId, text(row, 'record_json'), true)
}
for (const row of db
.prepare('SELECT operation_key, row_json FROM agent_session_operations ORDER BY rowid')
@@ -143,6 +155,13 @@ export function loadAgentSessionStoreRows(db: Database.Database): AgentSessionSt
state.retiredClaimKeys.push(entry)
}
}
state.sessionTabs = loadAgentSessionStoreTabs(db)
return state
}
export function loadAgentSessionStoreTabs(
db: Database.Database
): AgentSessionStoreState['sessionTabs'] {
const recorded = db
.prepare('SELECT 1 AS present FROM agent_session_store_meta WHERE key = ?')
.get(SESSION_TABS_RECORDED)
@@ -162,9 +181,9 @@ export function loadAgentSessionStoreRows(db: Database.Database): AgentSessionSt
}
}
if (recorded) {
state.sessionTabs = table
return table
}
return state
return null
}
function writeTabIndex(
@@ -9,7 +9,8 @@ import type { AgentSessionRecordStore } from './agent-session-record-store'
import {
closeTestAgentSessionRecordStores,
openTestAgentSessionRecordStore,
readPersistedTestAgentSessionStore
readPersistedTestAgentSessionStore,
withTestAgentSessionDatabase
} from './agent-session-record-store-test-harness'
import type { AgentSessionReserveRequest } from '../ownership/agent-session-reservation-admission'
@@ -65,6 +66,25 @@ async function open(): Promise<AgentSessionRecordStore> {
}
describe('chat tab table', () => {
it('keeps an observable record in its tab when its lease has an unknown write requirement', async () => {
const store = await open()
await store.reserveOwner(reserveRequest())
await withTestAgentSessionDatabase(directory, (db) =>
db
.prepare(
`UPDATE agent_session_records SET record_json=json_set(record_json,'$.lease.minimumNextFence','future-floor') WHERE session_id=?`
)
.run('session-alpha')
)
const reopened = await open()
await reopened.setSessionTabVisibility('session-alpha', true, 'tab-alpha')
expect(reopened.getSessionTabId('session-alpha')).toBe('tab-alpha')
expect((await readPersistedTestAgentSessionStore(directory)).sessionTabs).toEqual([
{ tabId: 'tab-alpha', sessionId: 'session-alpha' }
])
await expect(reopened.setConversationName('session-alpha', 'changed')).rejects.toThrow()
})
it('takes a reserved id only when the tab is shown, and refuses it to a second chat', async () => {
const store = await open()
await store.reserveOwner(reserveRequest({ surfaceTabId: 'tab-alpha' }))
@@ -131,6 +131,23 @@ afterEach(async () => {
})
describe('acquisition path', () => {
it('replays a successful reservation using its saved session when the retry proposes another id', async () => {
const store = await open()
const request = reserveRequest()
await store.reserveOwner(request)
await store.commitOperationReceipt(
store.operationOutcomeReceipt({
callerKey: request.operation.callerKey,
operationId: request.operation.operationId,
outcome: { status: 'succeeded', sessionId: 'session-alpha' }
})
)
const replay = await store.reserveOwner({ ...request, sessionId: 'session-beta' })
expect(replay.disposition).toBe('replayed')
expect(replay.record.sessionId).toBe('session-alpha')
expect(store.getRecord('session-beta')).toBeNull()
})
it('refuses a child that cannot echo the reserved spawn token', async () => {
const store = await open()
await store.reserveOwner(reserveRequest())
@@ -1,30 +1,22 @@
import { clearSuccessor } from '../../agent-session-sender-identity-revision'
import * as usageLimitContinue from '../../../../shared/agent-session/lifecycle/agent-session-usage-limit-continue'
import { createAgentSessionOwnerProof } from '../../agent-session-owner-proof'
import type * as usageLimitContinue from '../../../../shared/agent-session/lifecycle/agent-session-usage-limit-continue'
import type { createAgentSessionOwnerProof } from '../../agent-session-owner-proof'
import { backfillAgentSessionPermissionModes } from '../ownership/agent-session-permission-backfill'
import { createAgentSessionConversationReceipts } from '../agent-session-conversation-receipts'
import { pinAgentSessionRecordLaunchDirectory } from './agent-session-record-launch-directory'
import {
agentSessionOperationKey,
type AgentSessionOperationDecision,
type AgentSessionOperationRow
} from '../../../../shared/agent-session/lifecycle/agent-session-operation-ledger'
import {
admitAgentSessionGlobalOperationInto,
admitAgentSessionMutationOperation,
evaluateAgentSessionMutationOperation,
admitAgentSessionOperationInto,
claimAgentSessionOperationInto,
admitAndClaimAgentSessionOperationInto,
type ClaimAfterAdmission,
settleAgentSessionOperationInto,
type claimAgentSessionOperationInto,
type admitAndClaimAgentSessionOperationInto,
type settleAgentSessionOperationInto,
type AgentSessionMutationOperationAdmission,
type AgentSessionOperationAdmission
} from '../ownership/agent-session-operation-admission'
import {
isAgentSessionClaimKeyVerifiable,
retireAgentSessionClaimKey
} from '../ownership/agent-session-claim-key-retention'
import { isAgentSessionClaimKeyVerifiable } from '../ownership/agent-session-claim-key-retention'
import type { AgentSessionOwnerProbe } from '../../../../shared/agent-session/lifecycle/agent-session-lease-adjudication'
import {
agentSessionScopeKey,
@@ -33,31 +25,20 @@ import {
} from '../../../../shared/agent-session/lifecycle/agent-session-record'
import { readAgentSessionWorkspaceAttention } from './agent-session-workspace-attention'
import type { AgentSessionOptionsReplacement } from '../../../../shared/agent-session/options/agent-session-options-replacement'
import {
commitAgentSessionProcessIdentity,
evictAgentSessionOwner,
type AgentSessionProcessIdentityCommit
} from '../ownership/agent-session-lease-transitions'
import {
settleFailedAgentSessionAcquisition,
settleFailedAgentSessionPostAcquisitionAttachment,
type AgentSessionFailedAcquisitionSettlement,
type AgentSessionFailedPostAcquisitionAttachmentSettlement
import type { AgentSessionProcessIdentityCommit } from '../ownership/agent-session-lease-transitions'
import type {
AgentSessionFailedAcquisitionSettlement,
AgentSessionFailedPostAcquisitionAttachmentSettlement
} from '../agent-session-acquisition-failure-settlement'
import type { AgentSessionLeaseRenewal } from '../ownership/agent-session-lease-renewal'
import {
renewAgentSessionLeases,
type AgentSessionLeaseRenewal
} from '../ownership/agent-session-lease-renewal'
import {
applyAgentSessionRestartProbes,
collectAgentSessionRestartProbes,
type AgentSessionRestartProbeArgs
} from '../ownership/agent-session-restart-reconciliation'
import { replaceAgentSessionRecordOptions } from './agent-session-record-options'
import {
commitAgentSessionReservation,
type AgentSessionReserveRequest,
type AgentSessionReserveResult
import type { AgentSessionRecordCommand } from './agent-session-record-command'
import type {
AgentSessionReserveRequest,
AgentSessionReserveResult
} from '../ownership/agent-session-reservation-admission'
import {
getAgentSessionConversation,
@@ -73,12 +54,9 @@ import type { JournalOperationReceipt } from '../../../native-chat/agent-session
import { agentSessionOperationOutcomeReceipt } from '../agent-session-operation-receipt'
import { AgentSessionStoreTransactions } from './agent-session-store-transactions'
import { createAgentSessionFoundingStore } from './agent-session-founding-store'
import {
compareAndSetAgentSessionRecordName,
type AgentSessionUserNameWrite,
type CompareAndSetConversationName,
setAgentSessionRecordConversationName,
setAgentSessionRecordUserNameThrough
import type {
AgentSessionUserNameWrite,
CompareAndSetConversationName
} from './agent-session-record-conversation-name'
/** Single-writer records/operation ledger in the host chat-journal database. */
@@ -178,24 +156,28 @@ export class AgentSessionRecordStore extends AgentSessionRecordTabs {
return this.listRecords().filter((record) => agentSessionScopeKey(record.location) === scope)
}
/** Names are metadata, not ownership: write unfenced; null clears. */
setConversationName = (sessionId: string, name: string | null): Promise<AgentSessionRecord> =>
this.mutate(sessionId, (record) =>
setAgentSessionRecordConversationName(record, name, Date.now())
)
updateRecord = <C extends AgentSessionRecordCommand>(
sessionId: string,
command: C,
check?: () => void
) => this.commitRecordCommand(sessionId, command, check)
setConversationName = (sessionId: string, name: string | null) =>
this.updateRecord(sessionId, { kind: 'name', name, now: Date.now() })
/** The user's name for the conversation; see `AgentSessionUserNameWrite`. */
setUserConversationName = (sessionId: string, name: string, write: AgentSessionUserNameWrite) =>
setAgentSessionRecordUserNameThrough((apply) => this.mutate(sessionId, apply), name, write)
this.updateRecord(sessionId, { kind: 'user-name', name, write, now: Date.now() })
compareAndSetConversationName: CompareAndSetConversationName = (id, name, expected, context) =>
compareAndSetAgentSessionRecordName((apply) => this.mutate(id, apply), name, expected, context)
compareAndSetConversationName: CompareAndSetConversationName = (
id,
name,
expected,
contextId = null
) =>
this.updateRecord(id, { kind: 'name-if-current', name, expected, contextId, now: Date.now() })
/** Launch history is metadata and does not contend with the writer lease. */
pinLaunchDirectory = (sessionId: string, launchDirectory: string): Promise<AgentSessionRecord> =>
this.mutate(sessionId, (record) =>
pinAgentSessionRecordLaunchDirectory(record, launchDirectory, Date.now())
)
this.updateRecord(sessionId, { kind: 'launch-directory', launchDirectory, now: Date.now() })
/** Unreadable records still count as present and can never grant writers. */
isSessionUnreadable = (sessionId: string): boolean => this.state.unreadableRecords.has(sessionId)
@@ -212,40 +194,48 @@ export class AgentSessionRecordStore extends AgentSessionRecordTabs {
request: AgentSessionReserveRequest,
check?: () => void
): Promise<AgentSessionReserveResult> =>
this.transact((draft) => {
check?.()
return commitAgentSessionReservation(
draft,
request,
AGENT_SESSION_LEASE_TTL_MS,
this.transactions.legacySessionTabIds
)
})
this.commitStoreCommand(
{
kind: 'reserve',
request: {
...request,
spawnToken:
typeof request.spawnToken === 'function' ? request.spawnToken() : request.spawnToken
},
leaseTtlMs: AGENT_SESSION_LEASE_TTL_MS,
legacyTabIds: this.transactions.legacySessionTabIds
},
check
)
readonly founding: ReturnType<typeof createAgentSessionFoundingStore>
commitProcessIdentity = (args: AgentSessionProcessIdentityCommit): Promise<AgentSessionRecord> =>
this.mutate(args.sessionId, (record) => commitAgentSessionProcessIdentity({ ...args, record }))
this.updateRecord(args.sessionId, { kind: 'process', args })
proveOwner = createAgentSessionOwnerProof(
(id, transition) => this.mutate(id, transition),
AGENT_SESSION_LEASE_TTL_MS
)
proveOwner = (args: Parameters<ReturnType<typeof createAgentSessionOwnerProof>>[0]) =>
this.updateRecord(args.sessionId, {
kind: 'prove',
args,
leaseTtlMs: AGENT_SESSION_LEASE_TTL_MS
})
settleFailedAcquisition = (args: AgentSessionFailedAcquisitionSettlement) =>
this.transact((draft) => settleFailedAgentSessionAcquisition(draft, args))
this.commitStoreCommand({ kind: 'failed-acquisition', args, attached: false })
settleFailedPostAcquisitionAttachment = (
args: AgentSessionFailedPostAcquisitionAttachmentSettlement
) => this.transact((draft) => settleFailedAgentSessionPostAcquisitionAttachment(draft, args))
) => this.commitStoreCommand({ kind: 'failed-acquisition', args, attached: true })
renewLease = (args: AgentSessionLeaseRenewal): Promise<AgentSessionRecord> =>
this.renewLeases([args]).then(([renewed]) => renewed)
async renewLeases(renewals: readonly AgentSessionLeaseRenewal[]): Promise<AgentSessionRecord[]> {
return this.transact((draft) =>
renewAgentSessionLeases(draft, renewals, AGENT_SESSION_LEASE_TTL_MS)
)
return this.commitStoreCommand({
kind: 'renew',
renewals,
leaseTtlMs: AGENT_SESSION_LEASE_TTL_MS
})
}
async evictProvenDeadOwner(args: {
@@ -254,38 +244,29 @@ export class AgentSessionRecordStore extends AgentSessionRecordTabs {
probe: AgentSessionOwnerProbe
now: number
}): Promise<AgentSessionRecord> {
return this.mutate(args.sessionId, (record) => evictAgentSessionOwner({ ...args, record }))
return this.updateRecord(args.sessionId, { kind: 'evict', args })
}
cancelUsageLimitContinue = (id: string, cut: usageLimitContinue.UsageLimitContinueIdentity) =>
this.mutate(id, (record) =>
usageLimitContinue.cancelAgentSessionUsageLimitContinue(record, cut)
)
transitionHandoff = (
sessionId: string,
transition: (record: AgentSessionRecord) => AgentSessionRecord
): Promise<AgentSessionRecord> => this.mutate(sessionId, transition)
this.updateRecord(id, { kind: 'cancel-continue', cut })
/** Reconcile loaded leases before writer admission. Newer databases keep verdicts in memory only and cannot grant writers. */
async reconcileOnRestart(args: AgentSessionRestartProbeArgs) {
const probes = await collectAgentSessionRestartProbes(this, args)
return this.transact((draft) => applyAgentSessionRestartProbes(draft, probes, args.now), {
inMemoryWhenReadOnly: true
})
return this.commitStoreCommand({ kind: 'restart', probes, now: args.now })
}
admitOperation = (args: AgentSessionOperationAdmission): Promise<AgentSessionOperationDecision> =>
this.transact((draft) => admitAgentSessionOperationInto(draft, args))
this.commitStoreCommand({ kind: 'admit', args })
/** Global send ids survive caller reconnect/identity changes. */
admitGlobalOperation = (
args: AgentSessionOperationAdmission
): Promise<AgentSessionOperationDecision> =>
this.transact((draft) => admitAgentSessionGlobalOperationInto(draft, args))
this.commitStoreCommand({ kind: 'global-admit', args })
admitMutationOperation = (args: AgentSessionMutationOperationAdmission) =>
this.transact((draft) => admitAgentSessionMutationOperation(draft, args))
this.commitStoreCommand({ kind: 'admit-mutation', args })
/** Replay evaluation writes nothing; admitMutationOperation owns the transaction. */
evaluateMutationOperation = (args: AgentSessionMutationOperationAdmission) =>
@@ -293,16 +274,17 @@ export class AgentSessionRecordStore extends AgentSessionRecordTabs {
/** Durable CAS decides which pending replay may run its effect; reading pending alone cannot grant it. */
claimOperation = (args: Parameters<typeof claimAgentSessionOperationInto>[1]) =>
this.transact((draft) => claimAgentSessionOperationInto(draft, args))
this.commitStoreCommand({ kind: 'claim', args })
admitAndClaimOperation = (
args: Parameters<typeof admitAndClaimAgentSessionOperationInto>[1],
claimAfter: ClaimAfterAdmission
) => this.transact((draft) => admitAndClaimAgentSessionOperationInto(draft, args, claimAfter))
admitAndClaimOperation = (args: Parameters<typeof admitAndClaimAgentSessionOperationInto>[1]) =>
this.commitStoreCommand({ kind: 'admit-launch', args })
recordOperationOutcome = (
args: Parameters<typeof settleAgentSessionOperationInto>[1]
): Promise<void> => this.transact((draft) => settleAgentSessionOperationInto(draft, args))
): Promise<void> =>
this.transactions.commitReceipt(
this.transactions.mutationReceipt({ kind: 'operation', operation: args })
)
/** Commit settlement with the journal write, including any action-owned record transformation;
* new submissions also clear Sleep in that draft. */
@@ -314,23 +296,12 @@ export class AgentSessionRecordStore extends AgentSessionRecordTabs {
id: string,
cut: usageLimitContinue.UsageLimitContinueIdentity
): JournalOperationReceipt | undefined => {
const saved = this.getRecord(id)?.usageLimitContinueCancel
return saved?.turnItemId === cut.turnItemId && saved.resetsAt === cut.resetsAt
? undefined
: this.transactions.receipt((draft) => {
const record = draft.records.get(id)
if (record) {
draft.records.set(
id,
usageLimitContinue.cancelAgentSessionUsageLimitContinue(record, cut)
)
}
})
return this.transactions.mutationReceipt({ kind: 'cancel-continue', sessionId: id, cut })
}
/** Automatic queue admission uses the same record transition as a client's send receipt. */
submissionReceipt = (sessionId: string) =>
this.transactions.receipt(() => {}, { submissionSessionId: sessionId })
this.transactions.mutationReceipt({ kind: 'submission-wake', sessionId }, sessionId)
onAcceptedSend = (listener: (sessionId: string) => void): (() => void) => {
this.transactions.acceptedSendListeners.add(listener)
@@ -348,27 +319,5 @@ export class AgentSessionRecordStore extends AgentSessionRecordTabs {
this.transactions.readCommandReceipt(...args)
replaceSessionOptions = (args: AgentSessionOptionsReplacement): Promise<AgentSessionRecord> =>
this.mutate(args.sessionId, (record) => replaceAgentSessionRecordOptions(record, args))
/** Evaluate options against the record held by this ordered write. */
reviseSessionOptions = <A extends { sessionId: string }>(
revise: (record: AgentSessionRecord, args: A) => AgentSessionRecord,
args: A
) => this.mutate(args.sessionId, (record) => revise(record, args))
async retireClaimKey(keyId: string, now: number): Promise<void> {
await this.transact((draft) => retireAgentSessionClaimKey(draft, keyId, now))
}
private async mutate(
sessionId: string,
apply: (record: AgentSessionRecord) => AgentSessionRecord
): Promise<AgentSessionRecord> {
return this.transact((draft) => {
const record = requireWritableAgentSessionRecord(draft, sessionId)
const next = apply(record)
draft.records.set(sessionId, next)
return next
})
}
this.updateRecord(args.sessionId, { kind: 'options', args })
}
@@ -0,0 +1,90 @@
import { decodePersistedAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record-stored-form'
import { isDeepStrictEqual } from 'node:util'
import { sessionCrewChanges } from '../../orchestration/crew/crew-changes'
import { AgentSessionTabTable } from '../agent-session-tab-table'
import type { AgentSessionStoreRowWrites } from '../../../native-chat/agent-session-journal/journal-writer-store-row-changes'
import type { AgentSessionStoreState } from './agent-session-store-state'
import {
isReadableAgentSessionStoreOperation,
isReadableAgentSessionStoreRecord
} from './agent-session-store-row-rules'
/** Live adoption preserves the saved lease; startup's unreconciled policy does not apply. */
export function applyAgentSessionStoreCacheRows(
draft: AgentSessionStoreState,
writes: AgentSessionStoreRowWrites
): void {
for (const [id, json] of writes.records.upsert) {
const saved: unknown = JSON.parse(json)
if (!isReadableAgentSessionStoreRecord(id, saved)) {
throw new Error('the writer returned an unreadable record')
}
draft.records.set(id, decodePersistedAgentSessionRecord(saved).record)
}
for (const id of writes.records.remove) {
draft.records.delete(id)
}
for (const [key, json] of writes.operations.upsert) {
const saved: unknown = JSON.parse(json)
if (!isReadableAgentSessionStoreOperation(key, saved)) {
throw new Error('the writer returned an unreadable operation')
}
draft.operations.set(key, saved)
}
for (const key of writes.operations.remove) {
draft.operations.delete(key)
}
if (writes.retiredClaimKeys !== null) {
draft.retiredClaimKeys = writes.retiredClaimKeys
}
if (writes.sessionTabs !== null) {
draft.sessionTabs = writes.sessionTabs.recorded
? new AgentSessionTabTable(
writes.sessionTabs.tabs.map(({ tabId, sessionId }) => [tabId, sessionId])
)
: null
}
}
/** Unreadable rows are derived at load and never written, so the draft shares them. */
export function copyAgentSessionStoreCache(state: AgentSessionStoreState): AgentSessionStoreState {
return {
...state,
records: new Map(state.records),
operations: new Map(state.operations),
retiredClaimKeys: [...state.retiredClaimKeys],
sessionTabs: state.sessionTabs?.clone() ?? null
}
}
export function notifyAgentSessionStoreCacheChanges(
before: AgentSessionStoreState,
after: AgentSessionStoreState,
writes: AgentSessionStoreRowWrites
): void {
const topologyChanged =
writes.sessionTabs !== null ||
writes.records.remove.length > 0 ||
writes.records.upsert.some(([id]) => {
const previous = before.records.get(id)
const next = after.records.get(id)
return (
!previous ||
!next ||
previous.lease.claimStatus !== next.lease.claimStatus ||
previous.provider !== next.provider ||
!isDeepStrictEqual(previous.location, next.location) ||
!isDeepStrictEqual(previous.conversationCommand, next.conversationCommand)
)
})
const renamed = writes.records.upsert
.filter(
([id]) => before.records.get(id)?.conversationName !== after.records.get(id)?.conversationName
)
.map(([id]) => id)
if (topologyChanged) {
sessionCrewChanges.notify(new Set(['records']))
} else if (renamed.length) {
sessionCrewChanges.notify(Object.assign(new Set(['names'] as const), { recordIds: renamed }))
}
}
@@ -0,0 +1,231 @@
import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record'
import type {
AgentSessionOperationClaim,
AgentSessionOperationDecision
} from '../../../../shared/agent-session/lifecycle/agent-session-operation-ledger'
import { newChatPermissionMode } from '../../../../shared/agent-launch/permissions/agent-chat-permission-mode'
import { agentSessionRefusalError } from '../../../../shared/agent-session/failures/agent-session-wire-refusals'
import {
commitAgentSessionReservation,
type AgentSessionReserveRequest,
type AgentSessionReserveResult
} from '../ownership/agent-session-reservation-admission'
import {
admitAgentSessionOperationInto,
admitAgentSessionGlobalOperationInto,
admitAgentSessionMutationOperation,
admitAndClaimAgentSessionOperationInto,
claimAgentSessionOperationInto,
type AgentSessionMutationOperationAdmission,
type AgentSessionMutationOperationDecision,
type AgentSessionOperationAdmission
} from '../ownership/agent-session-operation-admission'
import {
applyAgentSessionRestartProbes,
type AgentSessionRestartProbe
} from '../ownership/agent-session-restart-reconciliation'
import {
renewAgentSessionLeases,
type AgentSessionLeaseRenewal
} from '../ownership/agent-session-lease-renewal'
import {
settleFailedAgentSessionAcquisition,
settleFailedAgentSessionPostAcquisitionAttachment,
type AgentSessionFailedAcquisitionSettlement
} from '../agent-session-acquisition-failure-settlement'
import {
initializeAgentSessionTabs,
effectiveAgentSessionTabs,
setAgentSessionTabVisibility,
showAgentSessionTabs
} from '../agent-session-tab-table'
import { commitAgentSessionFounding } from './agent-session-founding-admission'
import type { AgentSessionStoreState } from './agent-session-store-state'
export type AgentSessionStoreCommand =
| {
kind: 'reserve' | 'found'
request: Omit<AgentSessionReserveRequest, 'spawnToken'> & { spawnToken: string }
leaseTtlMs: number
legacyTabIds: readonly string[]
refuseReplay?: boolean
}
| { kind: 'failed-acquisition'; args: AgentSessionFailedAcquisitionSettlement; attached: boolean }
| { kind: 'renew'; renewals: readonly AgentSessionLeaseRenewal[]; leaseTtlMs: number }
| { kind: 'restart'; probes: ReadonlyMap<string, AgentSessionRestartProbe>; now: number }
| { kind: 'admit' | 'global-admit' | 'admit-launch'; args: AgentSessionOperationAdmission }
| { kind: 'admit-mutation'; args: AgentSessionMutationOperationAdmission }
| { kind: 'claim'; args: { callerKey: string; operationId: string } }
| { kind: 'tabs-initialize'; legacyTabIds: readonly string[] }
| { kind: 'tabs-show'; sessionIds: readonly string[]; legacyTabIds: readonly string[] }
| {
kind: 'tab-visibility'
sessionId: string
visible: boolean
tabId?: string
legacyTabIds: readonly string[]
}
| { kind: 'permission-backfill'; fullAccess: ReadonlyMap<string, boolean> }
export type AgentSessionStoreCommandResult<C extends AgentSessionStoreCommand> = C extends {
kind: 'reserve' | 'found'
}
? AgentSessionReserveResult
: C extends { kind: 'failed-acquisition' }
? AgentSessionRecord
: C extends { kind: 'renew' }
? AgentSessionRecord[]
: C extends { kind: 'restart' }
? Map<string, AgentSessionRecord>
: C extends { kind: 'admit' | 'global-admit' }
? AgentSessionOperationDecision
: C extends { kind: 'admit-launch' }
? { decision: AgentSessionOperationDecision; claim: AgentSessionOperationClaim | null }
: C extends { kind: 'admit-mutation' }
? AgentSessionMutationOperationDecision
: C extends { kind: 'claim' }
? AgentSessionOperationClaim
: C extends { kind: 'tab-visibility' }
? string | null
: void
export function agentSessionStoreCommandSelection(command: AgentSessionStoreCommand): {
recordIds: string[]
operation?: { callerKey: string; operationId: string }
allRecords?: boolean
allCallers?: boolean
tabs?: boolean
pruneAt?: number
} {
switch (command.kind) {
case 'reserve':
case 'found':
return {
recordIds: [command.request.sessionId],
operation: command.request.operation,
allRecords:
!!command.request.adoptedHandleLink ||
command.kind === 'found' ||
command.request.surfaceTabId !== undefined,
tabs: true,
pruneAt: command.request.now
}
case 'failed-acquisition':
return { recordIds: [command.args.sessionId], operation: command.args }
case 'renew':
return { recordIds: command.renewals.map((renewal) => renewal.sessionId) }
case 'restart':
return { recordIds: [...command.probes.keys()], pruneAt: command.now }
case 'admit':
case 'global-admit':
case 'admit-launch':
case 'claim':
return {
recordIds: [],
operation: command.args,
allCallers: command.kind === 'global-admit',
...('now' in command.args ? { pruneAt: command.args.now } : {})
}
case 'admit-mutation':
return {
recordIds: [command.args.envelope.sessionId],
operation: {
callerKey: command.args.callerKey,
operationId: command.args.envelope.clientOperationId
},
allCallers: command.args.operationIdScope === 'global',
pruneAt: command.args.now
}
case 'tabs-initialize':
case 'tabs-show':
case 'tab-visibility':
return { recordIds: [], allRecords: true, tabs: true }
case 'permission-backfill':
return { recordIds: [], allRecords: true }
}
}
export function applyAgentSessionStoreCommand(
state: AgentSessionStoreState,
command: AgentSessionStoreCommand
): unknown {
switch (command.kind) {
case 'reserve':
return commitAgentSessionReservation(
state,
command.request,
command.leaseTtlMs,
command.legacyTabIds
)
case 'found': {
const result = commitAgentSessionFounding(state, command.request, command.legacyTabIds)
if (command.refuseReplay && result.disposition === 'replayed') {
throw agentSessionRefusalError('agent_session_operation_unknown', {
reason: 'outcomeUnknown'
})
}
return result
}
case 'failed-acquisition':
return command.attached
? settleFailedAgentSessionPostAcquisitionAttachment(state, command.args)
: settleFailedAgentSessionAcquisition(state, command.args)
case 'renew':
return renewAgentSessionLeases(state, command.renewals, command.leaseTtlMs)
case 'restart':
return applyAgentSessionRestartProbes(state, command.probes, command.now)
case 'admit':
return admitAgentSessionOperationInto(state, command.args)
case 'global-admit':
return admitAgentSessionGlobalOperationInto(state, command.args)
case 'admit-launch':
return admitAndClaimAgentSessionOperationInto(
state,
command.args,
(decision) =>
decision.decision === 'admit' ||
(decision.decision === 'replay' && decision.row.outcome.status === 'pending')
)
case 'admit-mutation':
return admitAgentSessionMutationOperation(state, command.args)
case 'claim':
return claimAgentSessionOperationInto(state, command.args)
case 'tabs-initialize':
return initializeAgentSessionTabs(state, command.legacyTabIds)
case 'tabs-show':
return showAgentSessionTabs(state, command.sessionIds, command.legacyTabIds)
case 'tab-visibility': {
const retired =
effectiveAgentSessionTabs(state, command.legacyTabIds).tabIdFor(command.sessionId) ?? null
setAgentSessionTabVisibility(
state,
command.sessionId,
command.visible,
command.tabId,
command.legacyTabIds
)
return command.visible ? (state.sessionTabs?.tabIdFor(command.sessionId) ?? null) : retired
}
case 'permission-backfill':
for (const [id, record] of state.records) {
if (record.permissionMode !== undefined) {
continue
}
const { permissionMode: saved, ...options } = record.options ?? {}
const permissionMode =
saved ??
newChatPermissionMode(
record.provider,
command.fullAccess.get(record.provider) ? 'full-access' : 'ask'
)
if (permissionMode) {
state.records.set(id, {
...record,
...(saved !== undefined ? { options } : {}),
permissionMode
})
}
}
return undefined
}
}
@@ -0,0 +1,222 @@
import { commitAgentSessionRewindCompletion } from '../agent-session-rewind-completion'
import type { AgentSessionRewindRecord } from '../../../../shared/agent-session/lifecycle/agent-session-rewind'
import type { AgentJournalCursor } from '../../../../shared/agent-session/journal/agent-session-journal-identity'
import {
applyAgentSessionStoreCommand,
agentSessionStoreCommandSelection,
type AgentSessionStoreCommand
} from './agent-session-store-command'
import type {
AgentSessionForkedFrom,
AgentSessionRecord
} from '../../../../shared/agent-session/lifecycle/agent-session-record'
import type { AgentSessionOperationOutcome } from '../../../../shared/agent-session/lifecycle/agent-session-operation-ledger'
import { agentSessionOperationKey } from '../../../../shared/agent-session/lifecycle/agent-session-operation-ledger'
import type { UsageLimitContinueIdentity } from '../../../../shared/agent-session/lifecycle/agent-session-usage-limit-continue'
import { cancelAgentSessionUsageLimitContinue } from '../../../../shared/agent-session/lifecycle/agent-session-usage-limit-continue'
import {
insertAcceptedAgentSessionOperationInto,
settleAgentSessionOperationInto,
type AgentSessionOperationAcceptance
} from '../ownership/agent-session-operation-admission'
import {
commitConversationClearRecord,
type AgentSessionConversationClear
} from './agent-session-conversation-command-record'
import {
requireWritableAgentSessionRecord,
type AgentSessionStoreState
} from './agent-session-store-state'
import {
applyAgentSessionRecordCommand,
type AgentSessionRecordCommand
} from './agent-session-record-command'
export type AgentSessionOperationMutation =
| (AgentSessionOperationAcceptance & { outcome: AgentSessionOperationOutcome })
| Parameters<typeof settleAgentSessionOperationInto>[1]
export type AgentSessionRecordAcceptance =
| { kind: 'validated-plan' }
| { kind: 'stop-continue'; enabled: boolean }
export type AgentSessionStoreMutation =
| {
kind: 'rewind-complete'
sessionId: string
fence: number
rewind: AgentSessionRewindRecord
childBoundary?: NonNullable<AgentSessionRecord['forkedFrom']>['childBoundary']
}
| { kind: 'command'; command: AgentSessionStoreCommand }
| { kind: 'record'; sessionId: string; command: AgentSessionRecordCommand }
| {
kind: 'operation'
operation: AgentSessionOperationMutation
record?: { sessionId: string; action: AgentSessionRecordAcceptance }
wakeSessionId?: string
}
| { kind: 'fork-boundary'; sessionId: string; forkedFrom: AgentSessionForkedFrom }
| {
kind: 'clear'
clear: AgentSessionConversationClear
operation: { callerKey: string; operationId: string }
}
| { kind: 'cancel-continue'; sessionId: string; cut: UsageLimitContinueIdentity }
| { kind: 'submission-wake'; sessionId: string }
export function agentSessionStoreMutationKeys(mutation: AgentSessionStoreMutation): {
recordIds: string[]
operationId?: string
operationKey?: string
allCallers?: boolean
allRecords?: boolean
tabs?: boolean
pruneAt?: number
} {
if (mutation.kind === 'command') {
const selection = agentSessionStoreCommandSelection(mutation.command)
const operation = selection.operation
return {
...selection,
operationId: operation?.operationId,
operationKey: operation?.callerKey
? agentSessionOperationKey(operation.callerKey, operation.operationId)
: undefined
}
}
const operation =
mutation.kind === 'operation' || mutation.kind === 'clear'
? mutation.operation
: mutation.kind === 'rewind-complete'
? { callerKey: mutation.rewind.callerKey, operationId: mutation.rewind.operationId }
: undefined
const recordIds =
mutation.kind === 'operation'
? [mutation.record?.sessionId, mutation.wakeSessionId].filter(
(id): id is string => id !== undefined
)
: [mutation.kind === 'clear' ? mutation.clear.sessionId : mutation.sessionId]
return {
recordIds: [...new Set(recordIds)],
operationId: operation?.operationId,
operationKey: operation?.callerKey
? agentSessionOperationKey(operation.callerKey, operation.operationId)
: undefined,
allCallers:
operation !== undefined &&
(!operation.callerKey ||
('operationIdScope' in operation && operation.operationIdScope === 'global'))
}
}
/** A local source group operates on exact current rows, then discards its decoded state. */
export function applyAgentSessionStoreMutation(
state: AgentSessionStoreState,
mutation: AgentSessionStoreMutation,
at: number | undefined,
facts: {
planMode?: 'default' | 'plan'
continueCut?: UsageLimitContinueIdentity
cursor?: AgentJournalCursor
} = {}
): unknown {
switch (mutation.kind) {
case 'rewind-complete':
if (!facts.cursor) {
throw new Error('rewind completion requires its current journal cursor')
}
return commitAgentSessionRewindCompletion(
state,
mutation.sessionId,
mutation.fence,
mutation.rewind,
facts.cursor,
facts.continueCut,
mutation.childBoundary
)
case 'command':
return applyAgentSessionStoreCommand(state, mutation.command)
case 'record': {
const applied = applyAgentSessionRecordCommand(
requireWritableAgentSessionRecord(state, mutation.sessionId),
mutation.command
)
state.records.set(mutation.sessionId, applied.record)
return applied.result
}
case 'operation':
if ('fingerprint' in mutation.operation) {
insertAcceptedAgentSessionOperationInto(state, mutation.operation)
} else {
settleAgentSessionOperationInto(state, mutation.operation)
}
if (mutation.record) {
const { sessionId, action } = mutation.record
if (action.kind === 'stop-continue' && action.enabled && facts.continueCut) {
cancelContinue(state, sessionId, facts.continueCut)
} else if (action.kind === 'validated-plan') {
const record = state.records.get(sessionId)
const mode = facts.planMode
if (
record?.provider === 'claude' &&
mode !== undefined &&
(mode !== 'default' || record.options?.interactionMode === 'plan') &&
record.options?.interactionMode !== mode
) {
state.records.set(sessionId, {
...record,
options: { ...record.options, interactionMode: mode }
})
}
}
}
if (mutation.wakeSessionId) {
wake(state, mutation.wakeSessionId, at)
}
return
case 'fork-boundary': {
const record = state.records.get(mutation.sessionId)
if (!record) {
throw new Error('agent_session_fork:record-missing')
}
state.records.set(record.sessionId, { ...record, forkedFrom: mutation.forkedFrom })
return
}
case 'clear':
commitConversationClearRecord(state, mutation.clear)
settleAgentSessionOperationInto(state, {
...mutation.operation,
outcome: {
status: 'succeeded',
sessionId: mutation.clear.sessionId,
conversationCommand: mutation.clear.command
}
})
return
case 'cancel-continue':
cancelContinue(state, mutation.sessionId, mutation.cut)
return
case 'submission-wake':
return wake(state, mutation.sessionId, at)
}
}
function cancelContinue(
state: AgentSessionStoreState,
sessionId: string,
cut: UsageLimitContinueIdentity
) {
const record = state.records.get(sessionId)
if (record) {
state.records.set(sessionId, cancelAgentSessionUsageLimitContinue(record, cut))
}
}
function wake(state: AgentSessionStoreState, sessionId: string, at: number | undefined) {
const record: AgentSessionRecord = requireWritableAgentSessionRecord(state, sessionId)
if (record.sleptAt !== undefined) {
const { sleptAt: _sleptAt, ...awake } = record
state.records.set(sessionId, { ...awake, updatedAt: at ?? record.updatedAt })
}
}
@@ -1,45 +0,0 @@
import { decodePersistedAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record-stored-form'
import { AgentSessionTabTable } from '../agent-session-tab-table'
import type { AgentSessionStoreRowWrites } from './agent-session-store-draft'
import type { AgentSessionStoreState } from './agent-session-store-state'
import {
isReadableAgentSessionStoreOperation,
isReadableAgentSessionStoreRecord
} from './agent-session-store-row-rules'
/** Live adoption preserves the saved lease; startup's unreconciled policy does not apply. */
export function adoptAgentSessionStoreResolvedRows(
draft: AgentSessionStoreState,
writes: AgentSessionStoreRowWrites
): void {
for (const [id, json] of writes.records.upsert) {
const saved: unknown = JSON.parse(json)
if (!isReadableAgentSessionStoreRecord(id, saved)) {
throw new Error('the writer returned an unreadable record')
}
draft.records.set(id, decodePersistedAgentSessionRecord(saved).record)
}
for (const id of writes.records.remove) {
draft.records.delete(id)
}
for (const [key, json] of writes.operations.upsert) {
const saved: unknown = JSON.parse(json)
if (!isReadableAgentSessionStoreOperation(key, saved)) {
throw new Error('the writer returned an unreadable operation')
}
draft.operations.set(key, saved)
}
for (const key of writes.operations.remove) {
draft.operations.delete(key)
}
if (writes.retiredClaimKeys !== null) {
draft.retiredClaimKeys = writes.retiredClaimKeys
}
if (writes.sessionTabs !== null) {
draft.sessionTabs = writes.sessionTabs.recorded
? new AgentSessionTabTable(
writes.sessionTabs.tabs.map(({ tabId, sessionId }) => [tabId, sessionId])
)
: null
}
}
@@ -1,4 +1,3 @@
import { cancelAgentSessionUsageLimitContinue } from '../../../../shared/agent-session/lifecycle/agent-session-usage-limit-continue'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -92,9 +91,15 @@ describe('a receipt', () => {
turnItemId: `orca:${'long-supported-identity'.repeat(220)}`,
resetsAt: NOW + 60_000
}
const change = {
sessionId: 'chat-a-0001',
update: (record: AgentSessionRecord) => cancelAgentSessionUsageLimitContinue(record, cancel)
function cancellationReceipt(
store: AgentSessionRecordStore,
args: Parameters<AgentSessionRecordStore['operationOutcomeReceipt']>[0],
cut = cancel
) {
return composeJournalOperationReceipts(
store.operationOutcomeReceipt(args),
store.usageLimitContinueCancelReceipt('chat-a-0001', cut)
)
}
async function pendingOperation(insert = false): Promise<AgentSessionRecordStore> {
const store = await openTestAgentSessionRecordStore(root)
@@ -117,11 +122,10 @@ describe('a receipt', () => {
it.each([false, true])('rolls record and operation back together (insert=%s)', async (insert) => {
const store = await pendingOperation(insert)
const receipt = store.operationOutcomeReceipt({
const receipt = cancellationReceipt(store, {
callerKey: 'client-1',
operationId,
outcome,
record: change,
...(insert ? { fingerprint: 'fp', now: NOW } : {})
})
@@ -153,14 +157,13 @@ describe('a receipt', () => {
operationId,
fingerprint: 'fp',
now: NOW,
outcome,
record: change
outcome
}
await store.commitOperationReceipt(store.operationOutcomeReceipt(args))
await store.commitOperationReceipt(cancellationReceipt(store, args))
expect(await persistedStatus()).toBe('pending')
expect(store.getRecord('chat-a-0001')?.usageLimitContinueCancel).toEqual(cancel)
await expect(
store.commitOperationReceipt(store.operationOutcomeReceipt({ ...args, fingerprint: 'other' }))
store.commitOperationReceipt(cancellationReceipt(store, { ...args, fingerprint: 'other' }))
).rejects.toThrow()
const stale = await openTestAgentSessionRecordStore(root)
const otherId = `${NOW}-${'8'.repeat(32)}`
@@ -172,33 +175,29 @@ describe('a receipt', () => {
})
await expect(
stale.commitOperationReceipt(
stale.operationOutcomeReceipt({
...args,
operationId: otherId,
record: { ...change, update: (r) => ({ ...r, conversationName: 'lost' }) }
})
cancellationReceipt(
stale,
{ ...args, operationId: otherId },
{ ...cancel, resetsAt: NOW + 90_000 }
)
)
).rejects.toThrow()
expect(stale.getRecord('chat-a-0001')?.conversationName).not.toBe('lost')
expect(stale.getRecord('chat-a-0001')?.usageLimitContinueCancel).toEqual(cancel)
expect(
(await openTestAgentSessionRecordStore(root)).getRecord('chat-a-0001')?.conversationName
).not.toBe('lost')
(await openTestAgentSessionRecordStore(root)).getRecord('chat-a-0001')
?.usageLimitContinueCancel
).toEqual(cancel)
})
it('stages for the writer, holds later store writes until it settles, and adopts only a committed draft', async () => {
it('applies a staged receipt to the current SQL rows and ignores a discarded receipt', async () => {
const store = await pendingOperation()
const args = { callerKey: 'client-1', operationId, outcome, record: change }
const rolledBack = await store.operationOutcomeReceipt(args).stage!({ savedAt: NOW })
expect(rolledBack.effects).toEqual([expect.objectContaining({ kind: 'store' })])
const rename = store.setConversationName('chat-a-0001', 'after')
await new Promise(setImmediate)
expect(store.getRecord('chat-a-0001')?.conversationName).not.toBe('after')
const args = { callerKey: 'client-1', operationId, outcome }
const rolledBack = await cancellationReceipt(store, args).stage!({ savedAt: NOW })
await store.setConversationName('chat-a-0001', 'after')
rolledBack.settle(undefined)
await rename
expect(store.getRecord('chat-a-0001')?.usageLimitContinueCancel).toBeUndefined()
expect(store.getOperationRow('client-1', operationId)?.outcome.status).toBe('pending')
const committed = await store.operationOutcomeReceipt(args).stage!({ savedAt: NOW })
const committed = await cancellationReceipt(store, args).stage!({ savedAt: NOW })
const database = await openTestAgentSessionDatabase(root)
committed.settle(await database.effects(committed.effects))
expect(store.getRecord('chat-a-0001')).toMatchObject({
@@ -207,7 +206,7 @@ describe('a receipt', () => {
})
expect(store.getOperationRow('client-1', operationId)?.outcome.status).toBe('succeeded')
})
it('commits receipts co-staged in one writer command, the later on the earlier draft', async () => {
it('composes receipts against the rows written earlier in the same transaction', async () => {
const store = await pendingOperation()
const forkedFrom = {
sessionId: 'chat-parent',
@@ -215,11 +214,10 @@ describe('a receipt', () => {
childBoundary: { kind: 'start' as const }
}
const composed = composeJournalOperationReceipts(
store.operationOutcomeReceipt({
cancellationReceipt(store, {
callerKey: 'client-1',
operationId,
outcome,
record: change
outcome
}),
store.conversationReceipts.forkBoundary('chat-a-0001', forkedFrom)
)
@@ -247,11 +245,10 @@ describe('a receipt', () => {
}
const composed = composeJournalOperationReceipts(
onJournalReceiptCommitted(
store.operationOutcomeReceipt({
cancellationReceipt(store, {
callerKey: 'client-1',
operationId,
outcome,
record: change
outcome
}),
() => {
expect(store.getRecord('chat-a-0001')).toMatchObject(actual)
@@ -261,17 +258,18 @@ describe('a receipt', () => {
store.conversationReceipts.forkBoundary('chat-a-0001', forkedFrom)
)
const staged = await composed.stage!({ savedAt: NOW })
const later = store.setConversationName('chat-a-0001', 'after')
await withTestAgentSessionDatabase(root, (db) =>
db.exec(
"CREATE TRIGGER bind_record AFTER UPDATE ON agent_session_records BEGIN UPDATE agent_session_records SET record_json=json_set(NEW.record_json, '$.options.interactionMode', 'plan') WHERE session_id=NEW.session_id; END"
)
)
const other = await openTestAgentSessionRecordStore(root)
await other.replaceSessionOptions({
sessionId: 'chat-a-0001',
fence: 1,
options: { interactionMode: 'plan' },
now: NOW
})
expect(store.getRecord('chat-a-0001')?.options?.interactionMode).toBeUndefined()
const database = await openTestAgentSessionDatabase(root)
const results = await database.effects(staged.effects)
await withTestAgentSessionDatabase(root, (db) => db.exec('DROP TRIGGER bind_record'))
staged.settle(results)
await later
await store.setConversationName('chat-a-0001', 'after')
expect(store.getRecord('chat-a-0001')).toMatchObject({ ...actual, conversationName: 'after' })
expect((await openTestAgentSessionRecordStore(root)).getRecord('chat-a-0001')).toMatchObject({
...actual,
@@ -280,11 +278,10 @@ describe('a receipt', () => {
})
it('fences later writes when a committed store acknowledgement has no resolved rows', async () => {
const store = await pendingOperation()
const staged = await store.operationOutcomeReceipt({
const staged = await cancellationReceipt(store, {
callerKey: 'client-1',
operationId,
outcome,
record: change
outcome
}).stage!({ savedAt: NOW })
const database = await openTestAgentSessionDatabase(root)
await database.effects(staged.effects)
@@ -1,12 +1,16 @@
import { sessionCrewChanges } from '../../orchestration/crew/crew-changes'
import {
applyAgentSessionStoreCommand,
type AgentSessionStoreCommand,
type AgentSessionStoreCommandResult
} from './agent-session-store-command'
import { isDeepStrictEqual } from 'node:util'
import type { JournalSqlDatabase } from '../../../native-chat/agent-session-journal/database/journal-sql-database'
import type { JournalWriterEffectResult } from '../../../native-chat/agent-session-journal/journal-writer-effects'
import type { JournalOperationReceipt } from '../../../native-chat/agent-session-journal/writing/journal-row-writer'
import {
AgentSessionStoreWriterLanes,
stageAgentSessionStoreReceipt
} from './agent-session-store-writer-stage'
import type {
JournalOperationReceipt,
JournalReceiptStage,
JournalStagedReceipt
} from '../../../native-chat/agent-session-journal/writing/journal-row-writer'
import { journalOpenRefusalError } from '../../../native-chat/agent-session-journal/replay/journal-open-failure'
import { AgentSessionJournalError } from '../../../native-chat/agent-session-journal/writing/journal-write-guards'
import type { AgentSessionStoreState } from './agent-session-store-state'
@@ -24,47 +28,22 @@ import {
type AgentSessionReplacedRuntime
} from '../agent-session-replaced-runtime'
import {
agentSessionStoreDraftRowWrites,
draftAgentSessionStoreState,
agentSessionStoreRowChanges,
type AgentSessionStoreRowWrites
} from './agent-session-store-draft'
} from '../../../native-chat/agent-session-journal/journal-writer-store-row-changes'
import { changesAgentSenderIdentity } from '../../agent-session-sender-identity-revision'
import type { AgentSessionStoreMutation } from './agent-session-store-mutation'
import type {
AgentSessionRecordCommand,
AgentSessionRecordCommandResult
} from './agent-session-record-command'
import {
applyAgentSessionStoreCacheRows,
copyAgentSessionStoreCache,
notifyAgentSessionStoreCacheChanges
} from './agent-session-store-cache'
// The worker commits validated draft rows before publication; failures discard the draft.
// The promise queue preserves FIFO across transactions and staged writer receipts.
// Identity-based diffs miss in-place edits; freeze rows in dev/tests to catch them.
const FREEZE_ROWS = process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test'
function deepFreeze(value: unknown): void {
if (typeof value !== 'object' || value === null || Object.isFrozen(value)) {
return
}
Object.freeze(value)
for (const child of Object.values(value)) {
deepFreeze(child)
}
}
function freezeRows(
state: AgentSessionStoreState,
writes: AgentSessionStoreRowWrites | null
): void {
if (!FREEZE_ROWS) {
return
}
const records = writes ? writes.records.upsert.map(([key]) => key) : state.records.keys()
for (const sessionId of records) {
deepFreeze(state.records.get(sessionId))
}
const operations = writes ? writes.operations.upsert.map(([key]) => key) : state.operations.keys()
for (const key of operations) {
deepFreeze(state.operations.get(key))
}
if (!writes || writes.retiredClaimKeys) {
state.retiredClaimKeys.forEach(deepFreeze)
}
}
// The writer owns every transition; the host publishes acknowledged row changes only.
function readOnlyStoreRefusal(): Error {
return journalOpenRefusalError(
@@ -75,14 +54,6 @@ function readOnlyStoreRefusal(): Error {
)
}
export type StagedStoreTransaction<T> = {
result: T
draft: AgentSessionStoreState
writes: AgentSessionStoreRowWrites | null
/** Publish only after row commit. */
adopt: () => void
}
export class AgentSessionStoreTransactions {
private queue: Promise<unknown> = Promise.resolve()
// Reads/reopens do not admit work; a count survives handle eviction without replaying history.
@@ -94,13 +65,10 @@ export class AgentSessionStoreTransactions {
/** Replaced only when a record joins or leaves, or a /clear links one conversation to the next:
* lookups derived from every record's lineage stay valid across admission and lease writes. */
private lineage: object = {}
private readonly writerLanes = new AgentSessionStoreWriterLanes(
(hold) => {
const held = this.queue.then(hold)
this.queue = held.catch(() => {})
},
() => this.published
)
private readonly receiptCommits = new WeakMap<
JournalReceiptStage,
{ remaining: number; results: (readonly JournalWriterEffectResult[])[]; failed: boolean }
>()
/** Loaded takeover evidence; immutable for this runtime. */
readonly replacedRuntimes: ReadonlyMap<string, AgentSessionReplacedRuntime>
@@ -110,7 +78,6 @@ export class AgentSessionStoreTransactions {
hostId: string,
readonly legacySessionTabIds: readonly string[]
) {
freezeRows(loaded, null)
this.published = {
...loaded,
runtimeEnds: readAgentSessionRuntimeEnds(journalDatabase.stateDirectory)
@@ -145,40 +112,159 @@ export class AgentSessionStoreTransactions {
return this.journalDatabase.readCommandReceipt(scope, operationId)
}
/** Mutate only the draft. Newer databases refuse writes; inMemoryWhenReadOnly permits startup-derived verdicts. */
transact<T>(
apply: (draft: AgentSessionStoreState) => T,
options: { inMemoryWhenReadOnly?: boolean } = {}
): Promise<T> {
const run = this.queue.then(() => this.commit(apply, options.inMemoryWhenReadOnly === true))
record<C extends AgentSessionRecordCommand>(
sessionId: string,
command: C,
check?: () => void
): Promise<AgentSessionRecordCommandResult<C>> {
return this.executeMutation({ kind: 'record', sessionId, command }, check)
}
command<C extends AgentSessionStoreCommand>(
command: C,
check?: () => void
): Promise<AgentSessionStoreCommandResult<C>> {
return this.executeMutation({ kind: 'command', command }, check)
}
private executeMutation<T>(input: AgentSessionStoreMutation, check?: () => void): Promise<T> {
const run = this.queue.then(async () => {
check?.()
if (this.readOnly && input.kind === 'command' && input.command.kind === 'restart') {
const next = copyAgentSessionStoreCache(this.published)
const result = applyAgentSessionStoreCommand(next, input.command)
attributeAgentSessionRuntime(this.published, next)
if (result instanceof Map) {
for (const id of result.keys()) {
result.set(id, next.records.get(id))
}
}
this.publish(next, this.published, agentSessionStoreRowChanges(this.published, next))
return result as T
}
if (this.readOnly) {
throw readOnlyStoreRefusal()
}
const [result] = await this.journalDatabase.effects([
{
kind: 'store',
mutation: {
input,
runtime: {
incarnation: agentSessionRuntimeIncarnation(),
ends: this.published.runtimeEnds
}
}
}
])
if (!result || typeof result !== 'object' || !('kind' in result) || result.kind !== 'store') {
const error = new Error('the writer returned a different store result')
this.journalDatabase.fault(error)
throw error
}
this.publishResults([result])
return result.value as T
})
this.queue = run.catch(() => {})
return run
}
/** Staged into a worker writer command; co-staged receipts in one command build on each other. */
receipt(
apply: (draft: AgentSessionStoreState) => void,
options: { insertOperationsIfAbsent?: true; submissionSessionId?: string } = {}
mutationReceipt(
mutation: AgentSessionStoreMutation | (() => AgentSessionStoreMutation),
submissionSessionId?: string
): JournalOperationReceipt & Required<Pick<JournalOperationReceipt, 'stage'>> {
return {
stage: (context) =>
stageAgentSessionStoreReceipt(
{
refusal: () => (this.journalDatabase.readOnly ? readOnlyStoreRefusal() : undefined),
lanes: this.writerLanes,
stage: (run, base) => this.stage(run, base),
admit: (sessionId) => this.admitSend(sessionId),
publish: (draft) =>
this.publish(
draft,
this.published,
agentSessionStoreDraftRowWrites(this.published, draft)
),
fault: (error) => this.journalDatabase.fault(error)
},
{ apply, ...options },
context
)
stage: async (context): Promise<JournalStagedReceipt> => {
if (this.readOnly) {
throw readOnlyStoreRefusal()
}
const input = typeof mutation === 'function' ? mutation() : mutation
const admitted = context.row === 'submission' ? submissionSessionId : undefined
const effective =
input.kind === 'operation' && !admitted ? { ...input, wakeSessionId: undefined } : input
let group = this.receiptCommits.get(context)
if (!group) {
group = { remaining: 0, results: [], failed: false }
this.receiptCommits.set(context, group)
}
const index = group.results.length
group.results.push([])
group.remaining++
let adopted = false
let settled = false
const adopt: NonNullable<JournalStagedReceipt['adopt']> = (results) => {
if (adopted) {
return
}
adopted = true
group.remaining--
if (results === undefined) {
group.failed = true
} else if (results.length !== 1) {
group.failed = true
const error = new Error('the writer returned missing store results')
this.journalDatabase.fault(error)
throw error
} else {
group.results[index] = results
}
if (group.remaining === 0 && !group.failed) {
try {
this.publishResults(group.results.flat())
} catch (error) {
group.failed = true
throw error
}
}
}
return {
effects: [
{
kind: 'store',
mutation: {
input: effective,
at: context.savedAt,
runtime: {
incarnation: agentSessionRuntimeIncarnation(),
ends: this.published.runtimeEnds
}
}
}
],
adopt,
settle: (results) => {
if (settled) {
return
}
settled = true
adopt(results)
if (results !== undefined && !group.failed && admitted) {
this.admitSend(admitted)
}
}
}
}
}
}
private publishResults(results: readonly JournalWriterEffectResult[]): void {
try {
const next = copyAgentSessionStoreCache(this.published)
for (const result of results) {
if (
!result ||
typeof result !== 'object' ||
!('kind' in result) ||
result.kind !== 'store'
) {
throw new Error('the writer returned a different store result')
}
applyAgentSessionStoreCacheRows(next, result.writes)
}
this.publish(next, this.published, agentSessionStoreRowChanges(this.published, next))
} catch (error) {
this.journalDatabase.fault(error instanceof Error ? error : new Error(String(error)))
throw error
}
}
@@ -203,48 +289,12 @@ export class AgentSessionStoreTransactions {
}
}
private async commit<T>(
apply: (draft: AgentSessionStoreState) => T,
inMemoryWhenReadOnly: boolean
): Promise<T> {
const readOnly = this.journalDatabase.readOnly
if (readOnly && !inMemoryWhenReadOnly) {
throw readOnlyStoreRefusal()
}
const staged = this.stage(apply)
const writes = staged.writes
if (writes && !readOnly) {
await this.journalDatabase.effects([
{ kind: 'store', writes, insertOperationsIfAbsent: false }
])
}
staged.adopt()
return staged.result
}
private stage<T>(
apply: (draft: AgentSessionStoreState) => T,
published = this.published
): StagedStoreTransaction<T> {
const draft = draftAgentSessionStoreState(published)
const result = apply(draft)
attributeAgentSessionRuntime(published, draft)
const writes = agentSessionStoreDraftRowWrites(published, draft)
return {
result,
draft,
writes,
adopt: () => this.publish(draft, published, writes)
}
}
private publish(
draft: AgentSessionStoreState,
published: AgentSessionStoreState,
writes: AgentSessionStoreRowWrites | null
): void {
if (writes) {
freezeRows(draft, writes)
if (changesAgentSenderIdentity(published, draft, writes)) {
this.senderIdentityRevision++
}
@@ -261,34 +311,7 @@ export class AgentSessionStoreTransactions {
if (lineageChanged) {
this.lineage = {}
}
const topologyChanged =
writes.sessionTabs !== null ||
writes.records.remove.length > 0 ||
writes.records.upsert.some(([id]) => {
const before = published.records.get(id)
const after = draft.records.get(id)
return (
!before ||
!after ||
before.lease.claimStatus !== after.lease.claimStatus ||
before.provider !== after.provider ||
!isDeepStrictEqual(before.location, after.location) ||
!isDeepStrictEqual(before.conversationCommand, after.conversationCommand)
)
})
const renamed = writes.records.upsert
.filter(
([id]) =>
published.records.get(id)?.conversationName !== draft.records.get(id)?.conversationName
)
.map(([id]) => id)
if (topologyChanged) {
sessionCrewChanges.notify(new Set(['records']))
} else if (renamed.length) {
sessionCrewChanges.notify(
Object.assign(new Set(['names'] as const), { recordIds: renamed })
)
}
notifyAgentSessionStoreCacheChanges(published, draft, writes)
}
}
}
@@ -1,177 +0,0 @@
import type {
JournalReceiptStage,
JournalStagedReceipt
} from '../../../native-chat/agent-session-journal/writing/journal-row-writer'
import {
requireWritableAgentSessionRecord,
type AgentSessionStoreState
} from './agent-session-store-state'
import type { StagedStoreTransaction } from './agent-session-store-transactions'
import { draftAgentSessionStoreState } from './agent-session-store-draft'
import { adoptAgentSessionStoreResolvedRows } from './agent-session-store-resolved-rows'
type StoreWriterLane = {
draft: AgentSessionStoreState
resolved: AgentSessionStoreState
pending: number
committed: boolean
failed: boolean
/** Staged receipts not yet settled; the lane releases when none remain. */
open: number
release: () => void
}
/** A send admitted on a slept record wakes it in the same draft. */
function wakeAdmittedRecord(
draft: AgentSessionStoreState,
admitted: string | undefined,
at: number | undefined
): void {
const record = admitted ? requireWritableAgentSessionRecord(draft, admitted) : undefined
if (record?.sleptAt !== undefined) {
const { sleptAt: _sleptAt, ...awake } = record
draft.records.set(record.sessionId, { ...awake, updatedAt: at ?? record.updatedAt })
}
}
/** One writer command holds the store lane from its first staged receipt until all settle. */
export class AgentSessionStoreWriterLanes {
private readonly lanes = new WeakMap<JournalReceiptStage, StoreWriterLane>()
constructor(
/** Joins the store's FIFO lane, shared with transact(). */
private readonly enqueue: (hold: () => Promise<void>) => void,
private readonly published: () => AgentSessionStoreState
) {}
hold(context: JournalReceiptStage): Promise<StoreWriterLane> {
const held = this.lanes.get(context)
if (held) {
return Promise.resolve(held)
}
return new Promise((resolve) => {
this.enqueue(
() =>
new Promise<void>((release) => {
const draft = this.published()
const lane = {
draft,
resolved: draftAgentSessionStoreState(draft),
pending: 0,
committed: false,
failed: false,
open: 0,
release
}
this.lanes.set(context, lane)
resolve(lane)
})
)
})
}
settle(context: JournalReceiptStage, lane: StoreWriterLane): void {
if (lane.open === 0 && this.lanes.get(context) === lane) {
this.lanes.delete(context)
lane.release()
}
}
}
/** Stage for the worker writer: the draft rides as an effect and is adopted only after its COMMIT. */
export async function stageAgentSessionStoreReceipt(
deps: {
refusal: () => Error | undefined
lanes: AgentSessionStoreWriterLanes
stage: (
apply: (draft: AgentSessionStoreState) => void,
base: AgentSessionStoreState
) => StagedStoreTransaction<void>
admit: (sessionId: string) => void
publish: (draft: AgentSessionStoreState) => void
fault: (error: Error) => void
},
receipt: {
apply: (draft: AgentSessionStoreState) => void
insertOperationsIfAbsent?: true
submissionSessionId?: string
},
context: JournalReceiptStage
): Promise<JournalStagedReceipt> {
const refusal = deps.refusal()
if (refusal) {
throw refusal
}
const lane = await deps.lanes.hold(context)
const admitted = context.row === 'submission' ? receipt.submissionSessionId : undefined
let staged: StagedStoreTransaction<void>
try {
staged = deps.stage((draft) => {
receipt.apply(draft)
wakeAdmittedRecord(draft, admitted, context.savedAt)
}, lane.draft)
} catch (error) {
deps.lanes.settle(context, lane)
throw error
}
lane.draft = staged.draft
lane.open++
lane.pending++
const { writes } = staged
let resolved = false
let settled = false
const adopt: NonNullable<JournalStagedReceipt['adopt']> = (results) => {
if (resolved) {
return
}
resolved = true
lane.pending--
try {
if (results !== undefined) {
if (results.length !== (writes ? 1 : 0)) {
throw new Error('the writer returned missing store results')
}
for (const result of results) {
if (
!result ||
typeof result !== 'object' ||
!('kind' in result) ||
result.kind !== 'store'
) {
throw new Error('the writer returned a different store result')
}
adoptAgentSessionStoreResolvedRows(lane.resolved, result.writes)
}
lane.committed = true
}
if (lane.pending === 0 && lane.committed && !lane.failed) {
deps.publish(lane.resolved)
}
} catch (error) {
lane.failed = true
deps.fault(error instanceof Error ? error : new Error(String(error)))
throw error
}
}
return {
effects: writes
? [{ kind: 'store', writes, insertOperationsIfAbsent: !!receipt.insertOperationsIfAbsent }]
: [],
adopt,
settle: (results) => {
if (settled) {
return
}
settled = true
try {
adopt(results)
if (results !== undefined && !lane.failed && admitted) {
deps.admit(admitted)
}
} finally {
lane.open--
deps.lanes.settle(context, lane)
}
}
}
}
@@ -177,14 +177,12 @@ export async function admitAgentLaunchOperation(
const callerKey = agentLaunchOperationCallerKey(context)
// The ledger alone: admitting a terminal launch has no use for the chat host.
const store = await context.runtime.openAgentSessionRecordStore()
const { decision: admitted, claim } = await store.admitAndClaimOperation(
{ callerKey, operationId, fingerprint, now },
// A fresh row, or a replayed one no one has answered yet, leaves the right to run open.
(decision) =>
decision.decision === 'admit' ||
(decision.decision === 'replay' &&
answerFromRecordedRow(operationId, decision.row.outcome) === null)
)
const { decision: admitted, claim } = await store.admitAndClaimOperation({
callerKey,
operationId,
fingerprint,
now
})
if (admitted.decision === 'refused') {
return refusal(operationId, admitted.code, `was refused: ${admitted.code}`)
}