Persist bounded history detail and conversation outline projections

This commit is contained in:
Brennan Benson
2026-11-08 17:38:40 -08:00
parent 482543528d
commit f906c84d17
31 changed files with 956 additions and 187 deletions
@@ -2,60 +2,18 @@ import type Database from '../../../sqlite/sync-database'
import { runJournalTransaction } from './journal-database'
import { JOURNAL_DOMAIN_SCHEMA_001 } from './journal-domain-schema-001'
export const JOURNAL_DOMAIN_MIGRATIONS: readonly {
version: number
migrate: (db: Database.Database) => void
}[] = [
{ version: 1, migrate: (db) => db.exec(JOURNAL_DOMAIN_SCHEMA_001) },
{
version: 2,
migrate: (db) =>
db.exec(`
ALTER TABLE agent_session_operations ADD COLUMN operation_id TEXT GENERATED ALWAYS AS (
CASE WHEN json_valid(row_json) THEN json_extract(row_json, '$.operationId') END
) VIRTUAL;
CREATE INDEX agent_session_operations_identity ON agent_session_operations(operation_id);
`)
},
{
version: 3,
migrate: (db) =>
db.exec(`
ALTER TABLE agent_session_operations ADD COLUMN expires_at INTEGER GENERATED ALWAYS AS (
CASE WHEN json_valid(row_json) THEN json_extract(row_json, '$.expiresAt') END
) VIRTUAL;
CREATE INDEX agent_session_operations_expiry ON agent_session_operations(expires_at,operation_key);
`)
},
{
version: 4,
migrate: (db) =>
db.exec(`
ALTER TABLE agent_session_records ADD COLUMN adopted_native_id TEXT GENERATED ALWAYS AS (
CASE WHEN json_valid(record_json) THEN COALESCE(
json_extract(record_json,'$.providerHandleChain[#-1].handle.nativeId'),
json_extract(record_json,'$.providerHandleChain[#-1].handle.sessionId'),
json_extract(record_json,'$.providerHandleChain[#-1].handle.threadId')) END
) VIRTUAL;
CREATE INDEX agent_session_records_adopted_native ON agent_session_records(adopted_native_id);
`)
}
]
export const JOURNAL_DOMAIN_SCHEMA_VERSION = 1
export const JOURNAL_DOMAIN_SCHEMA_VERSION = JOURNAL_DOMAIN_MIGRATIONS.at(-1)!.version
/** Each completed step and its version commit together; reopen resumes the next step. */
/** The domain database starts at one frozen schema; shipped source formats import separately. */
export function migrateJournalDomainSchema(db: Database.Database): void {
const stored = Number(db.pragma('user_version', { simple: true }))
if (stored > JOURNAL_DOMAIN_SCHEMA_VERSION) {
throw new Error('journal domain schema is newer than this writer')
}
for (const migration of JOURNAL_DOMAIN_MIGRATIONS) {
if (migration.version > stored) {
runJournalTransaction(db, () => {
migration.migrate(db)
db.pragma(`user_version = ${migration.version}`)
})
}
if (stored < JOURNAL_DOMAIN_SCHEMA_VERSION) {
runJournalTransaction(db, () => {
db.exec(JOURNAL_DOMAIN_SCHEMA_001)
db.pragma(`user_version = ${JOURNAL_DOMAIN_SCHEMA_VERSION}`)
})
}
}
@@ -3,12 +3,27 @@ import { JOURNAL_DOMAIN_SCHEMA_001_INDEXES } from './journal-domain-schema-001-i
export const JOURNAL_DOMAIN_SCHEMA_001 = `
CREATE TABLE agent_session_records (
session_id TEXT PRIMARY KEY,
record_json TEXT NOT NULL
record_json TEXT NOT NULL,
adopted_native_id TEXT GENERATED ALWAYS AS (
CASE WHEN json_valid(record_json) THEN COALESCE(
json_extract(record_json,'$.providerHandleChain[#-1].handle.nativeId'),
json_extract(record_json,'$.providerHandleChain[#-1].handle.sessionId'),
json_extract(record_json,'$.providerHandleChain[#-1].handle.threadId')) END
) VIRTUAL
);
CREATE INDEX agent_session_records_adopted_native ON agent_session_records(adopted_native_id);
CREATE TABLE agent_session_operations (
operation_key TEXT PRIMARY KEY,
row_json TEXT NOT NULL
row_json TEXT NOT NULL,
operation_id TEXT GENERATED ALWAYS AS (
CASE WHEN json_valid(row_json) THEN json_extract(row_json, '$.operationId') END
) VIRTUAL,
expires_at INTEGER GENERATED ALWAYS AS (
CASE WHEN json_valid(row_json) THEN json_extract(row_json, '$.expiresAt') END
) VIRTUAL
);
CREATE INDEX agent_session_operations_identity ON agent_session_operations(operation_id);
CREATE INDEX agent_session_operations_expiry ON agent_session_operations(expires_at,operation_key);
CREATE TABLE agent_session_retired_claim_keys (
key_id TEXT PRIMARY KEY,
retired_at INTEGER NOT NULL
@@ -58,6 +73,7 @@ CREATE TABLE journal_chat_state (
history_origin_json TEXT,
accepted_handover_sequence INTEGER NOT NULL DEFAULT 0,
queue_revision INTEGER NOT NULL DEFAULT 0,
submissions_revision INTEGER NOT NULL DEFAULT 0,
queue_latest_stop_json TEXT,
queue_manual_stop_json TEXT,
queue_resumed_sequence INTEGER NOT NULL DEFAULT 0,
@@ -90,6 +106,9 @@ CREATE TABLE journal_items (
subagent_group_key TEXT,
turn_marker INTEGER NOT NULL DEFAULT 0,
wire_bytes INTEGER,
wire_json TEXT,
detail_json TEXT,
outline_source_json TEXT,
turn_item_id TEXT,
original_stop_note_json TEXT,
queue_command_turn INTEGER NOT NULL DEFAULT 0,
@@ -193,6 +212,7 @@ CREATE TABLE journal_submission_attempts (
admission_family_id TEXT,
handover_fence INTEGER,
facts_json TEXT NOT NULL DEFAULT '{}',
outline_json TEXT,
payload_json TEXT NOT NULL,
PRIMARY KEY(session_id, epoch, message_id, attempt_sequence, attempt_index)
);
@@ -250,5 +270,36 @@ CREATE TABLE journal_maintenance (
id INTEGER PRIMARY KEY CHECK(id=1),
compacted_at INTEGER NOT NULL
);
CREATE TABLE journal_outline_members (
session_id TEXT NOT NULL,
epoch TEXT NOT NULL,
item_id TEXT NOT NULL,
source_revision INTEGER NOT NULL,
sequence INTEGER NOT NULL,
sequence_index INTEGER NOT NULL,
ordinal INTEGER NOT NULL,
structure_json TEXT NOT NULL,
turn_key TEXT,
reply TEXT,
entry_json TEXT,
short_json TEXT,
empty_json TEXT,
entry_bytes INTEGER NOT NULL,
short_bytes INTEGER NOT NULL,
empty_bytes INTEGER NOT NULL,
PRIMARY KEY(session_id,epoch,item_id)
) WITHOUT ROWID;
CREATE INDEX journal_outline_entries ON journal_outline_members(session_id,epoch,sequence,sequence_index,ordinal)
WHERE entry_json IS NOT NULL;
CREATE INDEX journal_outline_reply_candidates ON journal_outline_members(session_id,epoch,turn_key,sequence DESC,sequence_index DESC,ordinal DESC)
WHERE reply IS NOT NULL;
CREATE TABLE journal_outline_replies (
session_id TEXT NOT NULL,
epoch TEXT NOT NULL,
turn_key TEXT NOT NULL,
reply TEXT NOT NULL,
reply_bytes INTEGER NOT NULL,
PRIMARY KEY(session_id,epoch,turn_key)
) WITHOUT ROWID;
${JOURNAL_DOMAIN_SCHEMA_001_INDEXES}
`
@@ -20,6 +20,129 @@ const body = (text: string): AgentJournalMessageItem => ({
const readsOf = (f: ReturnType<typeof domainLifecycleFixture>) =>
journalSqlReads({ point: async (request) => readJournalSqlPoint(f.db, request) }, 'chat')
it('keeps a fork validation current through streaming but invalidates a send and its later settlement', async () => {
const f = domainLifecycleFixture(cleanup)
const reads = readsOf(f)
await f.run({
kind: 'submission',
input: {
clientMessageId: 'unrelated',
fence: 1,
body: body('Old send'),
payloadFingerprint: 'old'
}
})
await f.run({
kind: 'item',
identity: identity('selected'),
body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Saved reply' }] },
options
})
const boundary = () => reads.forkBoundary('orca:selected', undefined, true)
const original = await boundary()
await f.run({
kind: 'item',
identity: identity('stream'),
body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Streaming' }] },
options
})
expect((await boundary()).submissionsToken).toBe(original.submissionsToken)
await f.run({
kind: 'submission',
input: {
clientMessageId: 'send',
fence: 1,
body: body('New request'),
payloadFingerprint: 'send'
}
})
const admitted = await boundary()
expect(admitted.submissionsToken).not.toBe(original.submissionsToken)
await f.run({
kind: 'dispatch',
input: {
clientMessageId: 'send',
fence: 1,
state: 'accepted',
providerIdentity: { provider: 'claude', sessionId: 'provider', uuid: 'echo' }
}
})
const accepted = await boundary()
expect(accepted.submissionsToken).not.toBe(admitted.submissionsToken)
// Unrelated old dispatch data is not needed to validate the selected response.
f.db
.prepare(
"UPDATE journal_submission_attempts SET payload_json='unreadable historical send' WHERE message_id='unrelated'"
)
.run()
expect((await boundary()).submissionsToken).toBe(accepted.submissionsToken)
})
it('keeps tool echoes and harness sidecars out of the outline across neighbouring assistant rows', async () => {
const f = domainLifecycleFixture(cleanup)
const reads = readsOf(f)
await f.run({ kind: 'item', identity: identity('prompt'), body: body('Real prompt'), options })
await f.run({
kind: 'item',
identity: identity('turn'),
options,
body: { kind: 'turn', turnId: 'turn', state: 'running', userItemId: 'orca:prompt' }
})
const scoped = { ...options, turnScope: { kind: 'turn' as const, turnItemId: 'orca:turn' } }
await f.run({
kind: 'item',
identity: identity('answer'),
options: scoped,
body: {
kind: 'message',
role: 'assistant',
blocks: [
{ type: 'text', text: 'Answer' },
{ type: 'tool-call', callId: 'read', name: 'Read', input: 'x' }
]
}
})
await f.run({
kind: 'item',
identity: identity('echo'),
options: scoped,
body: {
kind: 'message',
role: 'user',
blocks: [{ type: 'tool-result', callId: 'read', output: 'Large output' }]
}
})
await f.run({
kind: 'item',
identity: identity('tool-pair'),
options: scoped,
body: {
kind: 'message',
role: 'user',
blocks: [
{ type: 'tool-call', callId: 'other', name: 'Read', input: 'y' },
{ type: 'tool-result', callId: 'other', output: 'More output' }
]
}
})
await f.run({
kind: 'item',
identity: identity('sidecar'),
options: scoped,
body: {
kind: 'message',
role: 'user',
blocks: [
{ type: 'text', text: '<system-reminder>Injected context</system-reminder>' },
{ type: 'tool-result', callId: 'read', output: 'Background result' }
]
}
})
expect((await reads.conversationOutline(100_000)).entries).toEqual([
{ itemId: 'orca:prompt', sequence: 1, preview: 'Real prompt', imageCount: 0, reply: 'Answer' }
])
})
it('reads outline prompts and the last useful reply for their owning turn without loading other bodies', async () => {
const f = domainLifecycleFixture(cleanup)
const reads = readsOf(f)
@@ -84,6 +207,95 @@ it('reads outline prompts and the last useful reply for their owning turn withou
}
])
expect(outline.omittedEntries).toBe(0)
await f.run({
kind: 'steps',
steps: [
{
kind: 'resolved-item',
reservedBytes: 4096,
options: scope,
resolution: {
kind: 'text-snapshot',
identity: identity('reply'),
body: {
kind: 'message',
role: 'assistant',
blocks: [{ type: 'text', text: '**Updated answer**' }]
}
}
}
]
})
expect((await reads.conversationOutline(100_000)).entries.map((entry) => entry.reply)).toEqual([
'Updated answer',
'Updated answer'
])
await f.run({ kind: 'tombstone', identity: identity('reply'), fence: 1 })
expect((await reads.conversationOutline(100_000)).entries.map((entry) => entry.reply)).toEqual([
'Old reply',
'Old reply'
])
f.db.prepare("UPDATE journal_items SET payload_json='originals are not outline inputs'").run()
f.reopen()
expect((await reads.conversationOutline(100_000)).entries).toEqual([
{
itemId: 'orca:prompt',
sequence: 1,
preview: 'First request',
imageCount: 0,
reply: 'Old reply'
},
{
itemId: 'orca:steer',
sequence: 6,
preview: 'Follow up',
imageCount: 0,
turnKey: 'orca:prompt',
reply: 'Old reply'
}
])
})
it('degrades all outline previews before omitting the oldest entries', async () => {
const f = domainLifecycleFixture(cleanup)
const reads = readsOf(f)
for (const id of ['first', 'second']) {
await f.run({ kind: 'item', identity: identity(id), options, body: body('x'.repeat(1_000)) })
await f.run({
kind: 'item',
identity: identity(`${id}-turn`),
options,
body: { kind: 'turn', turnId: `${id}-turn`, state: 'running', userItemId: `orca:${id}` }
})
await f.run({
kind: 'item',
identity: identity(`${id}-reply`),
options: { ...options, turnScope: { kind: 'turn', turnItemId: `orca:${id}-turn` } },
body: {
kind: 'message',
role: 'assistant',
blocks: [{ type: 'text', text: 'a'.repeat(1_000) }]
}
})
}
expect(
(await reads.conversationOutline(700)).entries.map(({ preview, reply }) => ({ preview, reply }))
).toEqual([
{ preview: 'x'.repeat(200), reply: undefined },
{ preview: 'x'.repeat(200), reply: undefined }
])
expect((await reads.conversationOutline(350)).entries.map((entry) => entry.preview)).toEqual([
'x'.repeat(60),
'x'.repeat(60)
])
expect((await reads.conversationOutline(170)).entries.map((entry) => entry.preview)).toEqual([
'',
''
])
expect(await reads.conversationOutline(100)).toMatchObject({
entries: [{ itemId: 'orca:second', preview: '', imageCount: 0 }],
omittedEntries: 1
})
})
it('names only the sole eligible current prompt automatically and keeps manual naming after another prompt', async () => {
@@ -1,4 +1,5 @@
import { beforeJournalRequestWrite } from './journal-writer-request-events'
import { advanceJournalDomainSubmissionRevision } from './journal-domain-submission-revision'
import type Database from '../../sqlite/sync-database'
import {
JOURNAL_DOMAIN_SUBMISSION_COLUMNS,
@@ -28,13 +29,15 @@ export function writeJournalDomainDispatchAttempt(
): void {
const { submission: next, candidate, handover } = attempt
beforeJournalRequestWrite(db, target, 'refused-send', next.clientMessageId)
const payload = JSON.stringify(next)
advanceJournalDomainSubmissionRevision(db, target, next.clientMessageId, payload)
db.prepare(`UPDATE journal_submission_attempts SET candidate=?,payload_json=?,
${JOURNAL_DOMAIN_SUBMISSION_COLUMNS.map((column) => `${column}=?`).join(',')},
handover_fence=?,facts_json=?,
admission_body_json=CASE WHEN ? THEN admission_body_json ELSE NULL END
WHERE session_id=? AND epoch=? AND message_id=? AND current=1`).run(
Number(candidate),
JSON.stringify(next),
payload,
...journalDomainSubmissionColumns(next, attempt.carries),
handover?.fence ?? null,
journalDomainSubmissionFactsJson(attempt),
@@ -19,6 +19,7 @@ export type JournalDomainEntityRead = Extract<
| 'provider-turn-in-namespace'
| 'saved-item-ids'
| 'item'
| 'item-detail'
| 'submission'
| 'submission-body'
| 'acceptance'
@@ -93,13 +94,14 @@ export function readJournalDomainEntity(
historyOrigin
}
}
case 'item': {
case 'item':
case 'item-detail': {
const row = db
.prepare(`SELECT payload_json FROM journal_items
.prepare(`SELECT ${operation.kind === 'item-detail' ? 'COALESCE(detail_json,payload_json)' : 'payload_json'} AS payload_json FROM journal_items
WHERE session_id=? AND epoch=? AND item_id=? AND hidden=0`)
.get(...prefix, operation.itemId)
const item: AgentJournalRenderItem | null = row ? JSON.parse(String(row.payload_json)) : null
return { kind: 'item', item }
return { kind: operation.kind, item }
}
case 'submission': {
const row = db
@@ -1,4 +1,3 @@
import { createHash } from 'node:crypto'
import type {
AgentJournalRenderItem,
AgentJournalSnapshot,
@@ -111,15 +110,10 @@ export function readJournalDomainForkBoundary(
.map((row) => scope.decode<AgentJournalSubmission>(scope.examined(row).payload_json))
let submissionsToken: string | null = null
if (compareSubmissions) {
const digest = createHash('sha256').update(scope.epoch)
for (const row of db
.prepare(`SELECT payload_json FROM journal_submission_attempts
INDEXED BY journal_submission_ordinal WHERE session_id=? AND epoch=? AND current=1 ORDER BY ordinal`)
.iterate(...prefix)) {
const json = String(scope.examined(row).payload_json)
digest.update(`${Buffer.byteLength(json)}:`).update(json)
}
submissionsToken = digest.digest('hex')
const row = db
.prepare('SELECT submissions_revision FROM journal_chat_state WHERE session_id=? AND epoch=?')
.get(...prefix)!
submissionsToken = JSON.stringify([scope.epoch, Number(row.submissions_revision)])
}
return {
snapshot: {
@@ -11,7 +11,11 @@ import {
HISTORY_PAGE_CONTENT_BUDGET_BYTES,
isSubagentRow
} from '../agent-session-wire/publication/history/agent-session-history-page-bounds'
import { agentJournalItemForWire } from '../agent-session-wire/publication/history/agent-session-item-wire-form'
import { REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES } from '../../../shared/remote-runtime/remote-runtime-memory-limits'
import {
agentJournalItemForWire,
shortenedAgentJournalItem
} from '../agent-session-wire/publication/history/agent-session-item-wire-form'
/** Facts history selects before decoding a body; written from each current item revision. */
export type JournalDomainHistoryMetadata = {
@@ -22,6 +26,8 @@ export type JournalDomainHistoryMetadata = {
turnMarker: number
/** Client-form bytes when they differ from the stored payload; null reads the stored length. */
wireBytes: number | null
wireJson: string | null
detailJson: string | null
}
/** Pass the stored payload text when the caller already serialized it. */
@@ -39,7 +45,7 @@ export function journalDomainHistoryMetadata(
turnMarker: Number(
readAgentJournalTurn(item.body) !== null || isAgentSessionContextClear(item.body)
),
wireBytes: wireBytes(item, payloadJson)
...journalDomainItemWire(item, payloadJson)
}
}
@@ -51,15 +57,25 @@ export function journalDomainNamedSubagentIds(item: AgentJournalRenderItem): str
// The client form cuts tool/diff heads and whole items over the page budget; skipping the
// form elsewhere only overstates a size, which shortens a page but never drops content.
function wireBytes(item: AgentJournalRenderItem, payloadJson: string | undefined): number | null {
export const JOURNAL_ITEM_DETAIL_MAX_BYTES = REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - 64 * 1024
export function journalDomainItemWire(item: AgentJournalRenderItem, payloadJson?: string) {
const bytes = Buffer.byteLength(payloadJson ?? JSON.stringify(item), 'utf8')
const detailJson =
bytes > JOURNAL_ITEM_DETAIL_MAX_BYTES
? JSON.stringify(shortenedAgentJournalItem(item, JOURNAL_ITEM_DETAIL_MAX_BYTES, bytes))
: null
if (
item.body.kind !== 'tool-call' &&
item.body.kind !== 'diff' &&
Buffer.byteLength(payloadJson ?? JSON.stringify(item), 'utf8') <=
HISTORY_PAGE_CONTENT_BUDGET_BYTES
bytes <= HISTORY_PAGE_CONTENT_BUDGET_BYTES
) {
return null
return { wireBytes: null, wireJson: null, detailJson }
}
const sent = agentJournalItemForWire(item)
return sent.item === item ? null : sent.bytes
return {
wireBytes: sent.item === item ? null : sent.bytes,
wireJson: sent.item === item ? null : JSON.stringify(sent.item),
detailJson
}
}
@@ -200,14 +200,14 @@ function formHistoryGroups(
): AgentJournalRenderItem[][] {
const sizes = submissionBytesByItemId(submissions)
const body = db.prepare(
'SELECT payload_json FROM journal_items WHERE session_id=? AND epoch=? AND item_id=?'
'SELECT COALESCE(wire_json,payload_json) AS wire_json FROM journal_items WHERE session_id=? AND epoch=? AND item_id=?'
)
const kept: AgentJournalRenderItem[][] = []
let total = 0
for (const group of groups) {
const formed = group.map((header) =>
reader.form(
JSON.parse(String(body.get(head.sessionId, head.epoch, header.itemId)!.payload_json))
JSON.parse(String(body.get(head.sessionId, head.epoch, header.itemId)!.wire_json))
)
)
const bytes = historyContentBytes(formed, [], sizes)
@@ -232,11 +232,16 @@ function itemEnvelope(
header: JournalDomainHistoryHeader
): AgentJournalRenderItem {
const row = db
.prepare(`SELECT json_remove(payload_json, '$.body') AS envelope FROM journal_items
.prepare(`SELECT placement_json AS envelope,revision,sequence,sequence_index FROM journal_items
WHERE session_id=? AND epoch=? AND item_id=?`)
.get(...prefix, header.itemId)!
// The placeholder replaces the omitted body.
return JSON.parse(String(row.envelope))
return {
...JSON.parse(String(row.envelope)),
revision: Number(row.revision),
sequence: Number(row.sequence),
sequenceIndex: Number(row.sequence_index)
}
}
function latestTurnItem(
@@ -244,7 +249,7 @@ function latestTurnItem(
head: JournalDomainHistoryHead
): AgentJournalRenderItem | null {
const row = db
.prepare(`SELECT payload_json FROM journal_items WHERE session_id=? AND epoch=? AND hidden=0
.prepare(`SELECT COALESCE(wire_json,payload_json) AS payload_json FROM journal_items WHERE session_id=? AND epoch=? AND hidden=0
AND turn_marker=1 ORDER BY sequence DESC, sequence_index DESC, ordinal DESC LIMIT 1`)
.get(head.sessionId, head.epoch)
return row ? JSON.parse(String(row.payload_json)) : null
@@ -275,7 +280,7 @@ function currentRows(
sessionId: head.sessionId,
cursor: head.cursor,
items: db
.prepare(`SELECT item.payload_json FROM json_each(?) wanted
.prepare(`SELECT COALESCE(item.wire_json,item.payload_json) AS payload_json FROM json_each(?) wanted
CROSS JOIN journal_items item
WHERE item.session_id=? AND item.epoch=? AND item.item_id=wanted.value AND item.hidden=0
ORDER BY item.sequence, item.sequence_index, item.ordinal`)
@@ -132,7 +132,7 @@ it('keeps revised naming items at their visible history position and removes obs
})
it('never splits a same-sequence group, marking it oversized backward and paging it whole forward', () => {
const { seedItem, head, event, read } = history()
const { db, seedItem, head, event, read } = history()
const group = Array.from({ length: 200 }, (_, index) =>
text(50, 'x'.repeat(1000), { sequenceIndex: index })
)
@@ -150,6 +150,10 @@ it('never splits a same-sequence group, marking it oversized backward and paging
event(sequence, [`orca:${sequence}:0`])
}
head(60, 48)
const originals = db
.prepare('SELECT item_id,payload_json FROM journal_items WHERE sequence=50')
.all()
db.prepare('UPDATE journal_items SET payload_json=? WHERE sequence=50').run('x'.repeat(1000))
const small = { form: measureHistoryItem, budgetBytes: 50_000 }
const tail = read({ direction: 'tail', limit: 40 }, small)
expect(sequences(tail)).toEqual([51, 52, 53, 54, 55, 56, 57, 58, 59, 60])
@@ -161,6 +165,12 @@ it('never splits a same-sequence group, marking it oversized backward and paging
expect(sequences(rest)).toEqual([49])
expect(rest.page.hasOlder).toBe(false)
for (const row of originals) {
db.prepare('UPDATE journal_items SET payload_json=? WHERE item_id=?').run(
row.payload_json,
row.item_id
)
}
const forward: string[] = []
let cursor = { epoch: 'epoch', sequence: 48 }
for (const expected of [true, true, false]) {
@@ -16,6 +16,8 @@ export function discardJournalDomainImportPage(
}
let remaining = 512
for (const [table, key] of [
['journal_outline_members', 'epoch,item_id'],
['journal_outline_replies', 'epoch,turn_key'],
['journal_item_subagent_names', 'epoch,subagent_id,item_id'],
['journal_items', 'epoch,item_id'],
['journal_item_tombstones', 'epoch,item_id'],
@@ -8,6 +8,7 @@ import type Database from '../../sqlite/sync-database'
import { insertJournalDomainQueueRow, journalDomainQueueRow } from './journal-domain-queue-rows'
import type { JournalDomainImportHeader, JournalDomainImportPage } from './journal-domain-import'
import { writeJournalDomainItemNames } from './journal-domain-item-names'
import { rebuildJournalDomainOutline } from './journal-domain-outline-write'
export type JournalDomainImportState =
| { state: 'converting'; epoch: null }
@@ -252,5 +253,6 @@ export function finishJournalDomainImport(
if (state.state !== 'ready') {
throw new Error('journal domain import did not publish its chat head')
}
rebuildJournalDomainOutline(db, header)
return state.epoch
}
@@ -7,6 +7,7 @@ import { currentAgentSessionThreadGoalSourceBySequence } from '../../../shared/a
import { readAgentJournalTurn } from '../../../shared/agent-session/lifecycle/agent-session-turn-record'
import { claudeAgentRowFacts } from '../../claude/claude-subagent-journaled-identities'
import { journalDomainHistoryMetadata } from './journal-domain-history-metadata'
import { journalDomainOutlineSource } from './journal-domain-outline-source'
import {
journalItemLifecycleState,
journalItemStatusMetadata
@@ -85,6 +86,9 @@ export const JOURNAL_DOMAIN_ITEM_COLUMNS = [
'subagent_group_key',
'turn_marker',
'wire_bytes',
'wire_json',
'detail_json',
'outline_source_json',
'turn_item_id',
'kind',
'message_role',
@@ -119,6 +123,9 @@ export function journalDomainItemColumns(item: AgentJournalRenderItem, payload:
metadata.subagentGroupKey,
metadata.turnMarker,
metadata.wireBytes,
metadata.wireJson,
metadata.detailJson,
journalDomainOutlineSource(item),
item.turnScope?.kind === 'turn' ? item.turnScope.turnItemId : null,
...journalDomainItemReadColumns(item),
...journalDomainItemLifecycleColumns(item),
@@ -14,7 +14,23 @@ export type JournalDomainMaintenanceResult =
const RETIRED_PAGE_BYTES = 1024 * 1024
// Only a ready head naming another epoch proves retirement; import shells have no epoch.
const RETIRED_TABLES: readonly { name: string; key: string; payload?: readonly string[] }[] = [
{ name: 'journal_items', key: 'item_id', payload: ['payload_json', 'original_stop_note_json'] },
{
name: 'journal_items',
key: 'item_id',
payload: [
'payload_json',
'original_stop_note_json',
'wire_json',
'detail_json',
'outline_source_json'
]
},
{
name: 'journal_outline_members',
key: 'item_id',
payload: ['structure_json', 'entry_json', 'short_json', 'empty_json', 'reply']
},
{ name: 'journal_outline_replies', key: 'turn_key', payload: ['reply'] },
{ name: 'journal_item_subagent_names', key: 'subagent_id,item_id' },
{ name: 'journal_item_tombstones', key: 'item_id' },
{ name: 'journal_removed_turns', key: 'turn_id' },
@@ -0,0 +1,160 @@
import {
AGENT_SESSION_OUTLINE_PREVIEW_MAX_CHARS,
assistantReplyProse,
nativeChatUserMessagePreview,
truncateOutlinePreview,
type NativeChatUserMessagePreview
} from '../../../shared/agent-session/agent-session-conversation-outline'
import type {
AgentJournalRenderItem,
AgentJournalSubmission
} from '../../../shared/agent-session/journal/agent-session-journal-types'
import { isRootAgentJournalItem } from '../../../shared/agent-session/journal/agent-session-journal-producer'
import { readAgentJournalTurn } from '../../../shared/agent-session/lifecycle/agent-session-turn-record'
import { isAgentSessionContextClear } from '../../../shared/agent-session/agent-session-context-clear'
import { projectStructuredItemToNativeChat } from '../../../shared/agent-session/view/structured-agent-session-projection'
import { nativeChatToolFoldKind } from '../../../shared/native-chat/tools/native-chat-tool-fold'
import { isNoiseMessage } from '../../../shared/native-chat/native-chat-noise'
import { nativeChatRowRendersContent } from '../../../shared/native-chat/transcript/native-chat-row-content'
import type {
NativeChatBlock,
NativeChatMessage
} from '../../../shared/native-chat/native-chat-types'
export type JournalOutlineSource = {
item: AgentJournalRenderItem
message: NativeChatMessage | null
preview: NativeChatUserMessagePreview | null
reply: string | null
}
/** Keep tool identities and classification prefixes so neighbours still decide which rows draw. */
function outlineBlocks(blocks: readonly NativeChatBlock[]): NativeChatBlock[] {
return blocks.flatMap((block): NativeChatBlock[] => {
switch (block.type) {
case 'text':
return [
{
type: 'text',
text: block.text.trimStart().slice(0, 320),
...(block.contextClear ? { contextClear: block.contextClear } : {}),
...(block.failure?.kind === 'providerRetrying' ? { failure: block.failure } : {})
}
]
case 'tool-call':
return [{ type: 'tool-call', name: '', input: null, callId: block.callId }]
case 'tool-result':
return [{ type: 'tool-result', output: '', callId: block.callId }]
case 'image-ref':
return [{ type: 'image-ref' }]
default:
return []
}
})
}
/** Classify originals once, before clipping: noise and tool-only rows must not become prompts. */
export function journalDomainOutlineSource(item: AgentJournalRenderItem): string | null {
const { body, ...placement } = item
const turn = readAgentJournalTurn(body)
const compact: AgentJournalRenderItem = {
...placement,
body: turn
? {
kind: 'turn',
turnId: turn.turnId,
state: turn.state,
...(turn.userItemId === undefined ? {} : { userItemId: turn.userItemId }),
...(turn.startedAt === undefined ? {} : { startedAt: turn.startedAt }),
...(turn.completedAt === undefined ? {} : { completedAt: turn.completedAt })
}
: body.kind === 'message'
? {
kind: 'message',
role: body.role,
blocks: [],
...(body.command ? { command: body.command } : {})
}
: body.kind === 'status' && isAgentSessionContextClear(body)
? { kind: 'status', text: '', contextClear: body.contextClear }
: { kind: 'status', text: '' }
}
const projected = isRootAgentJournalItem(item) ? projectStructuredItemToNativeChat(item) : null
let message: JournalOutlineSource['message'] = null
let preview: NativeChatUserMessagePreview | null = null
if (projected && nativeChatToolFoldKind(projected) !== 'pass') {
message = { ...projected, blocks: outlineBlocks(projected.blocks) }
if (projected.role === 'user') {
const full = nativeChatUserMessagePreview(projected.blocks)
preview = {
text: truncateOutlinePreview(full.text, AGENT_SESSION_OUTLINE_PREVIEW_MAX_CHARS),
imageCount: full.imageCount
}
}
}
return JSON.stringify({
item: compact,
message,
preview,
reply: projected?.role === 'assistant' ? assistantReplyProse(projected.blocks) || null : null
} satisfies JournalOutlineSource)
}
/** Source position and membership only; body revisions and prose do not regroup a turn. */
export function journalOutlineStructure(source: JournalOutlineSource): string {
const { revision: _revision, ...item } = source.item
const { blocks: _blocks, ...message } = source.message ?? { blocks: [] }
return JSON.stringify({
item,
message,
fold: source.message && nativeChatToolFoldKind(source.message),
noise: source.message && isNoiseMessage(source.message),
renders: source.message && nativeChatRowRendersContent(source.message.blocks),
tools: source.message?.blocks.flatMap((block) =>
block.type === 'tool-call' || block.type === 'tool-result' ? [[block.type, block.callId]] : []
)
})
}
export function journalOutlineMessage(source: JournalOutlineSource): NativeChatMessage | null {
return source.message
}
export function journalDomainOutlineSubmission(submission: AgentJournalSubmission): string {
const {
clientMessageId,
fence,
payloadFingerprint,
dispatchState,
providerItemId,
reason,
submittedAt,
resolvedAt,
submittedSequence,
acceptedSequence,
queuedMessageId,
keptAsQueuedMessageId,
handoverRecorded,
handedOverAt,
answeredInTurn,
rejection
} = submission
return JSON.stringify({
clientMessageId,
fence,
payloadFingerprint,
dispatchState,
providerItemId,
reason,
submittedAt,
resolvedAt,
submittedSequence,
acceptedSequence,
queuedMessageId,
keptAsQueuedMessageId,
handoverRecorded,
handedOverAt,
answeredInTurn,
rejection
} satisfies AgentJournalSubmission)
}
@@ -0,0 +1,205 @@
import type Database from '../../sqlite/sync-database'
import type { SqliteRow } from '../../sqlite/sqlite-statement'
import {
projectAgentSessionConversationOutline,
truncateOutlinePreview,
type AgentSessionConversationOutlineEntry
} from '../../../shared/agent-session/agent-session-conversation-outline'
import type { AgentJournalSubmission } from '../../../shared/agent-session/journal/agent-session-journal-types'
import {
journalOutlineMessage,
journalOutlineStructure,
type JournalOutlineSource
} from './journal-domain-outline-source'
type Target = { sessionId: string; epoch: string }
type SourceRow = { source: JournalOutlineSource; ordinal: number; structure: string }
function writeMember(
db: Database.Database,
target: Target,
row: SourceRow,
turnKey: string | undefined,
entry: AgentSessionConversationOutlineEntry | undefined
): void {
const json = entry ? JSON.stringify(entry) : null
const short = entry
? JSON.stringify({ ...entry, preview: truncateOutlinePreview(entry.preview, 60) })
: null
const empty = entry ? JSON.stringify({ ...entry, preview: '' }) : null
db.prepare(`INSERT INTO journal_outline_members(session_id,epoch,item_id,source_revision,
sequence,sequence_index,ordinal,structure_json,turn_key,reply,entry_json,short_json,empty_json,
entry_bytes,short_bytes,empty_bytes) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
ON CONFLICT(session_id,epoch,item_id) DO UPDATE SET
source_revision=excluded.source_revision,sequence=excluded.sequence,sequence_index=excluded.sequence_index,
ordinal=excluded.ordinal,structure_json=excluded.structure_json,turn_key=excluded.turn_key,
reply=excluded.reply,entry_json=excluded.entry_json,short_json=excluded.short_json,empty_json=excluded.empty_json,
entry_bytes=excluded.entry_bytes,short_bytes=excluded.short_bytes,empty_bytes=excluded.empty_bytes
WHERE source_revision<>excluded.source_revision OR structure_json<>excluded.structure_json
OR turn_key IS NOT excluded.turn_key OR reply IS NOT excluded.reply OR entry_json IS NOT excluded.entry_json`).run(
target.sessionId,
target.epoch,
row.source.item.itemId,
row.source.item.revision,
row.source.item.sequence,
row.source.item.sequenceIndex ?? 0,
row.ordinal,
row.structure,
turnKey ?? null,
row.source.reply,
json,
short,
empty,
json === null ? 0 : Buffer.byteLength(json, 'utf8') + 1,
short === null ? 0 : Buffer.byteLength(short, 'utf8') + 1,
empty === null ? 0 : Buffer.byteLength(empty, 'utf8') + 1
)
}
function refreshReply(db: Database.Database, target: Target, key: string): void {
const prefix = [target.sessionId, target.epoch, key] as const
const row = db
.prepare(`SELECT reply FROM journal_outline_members
INDEXED BY journal_outline_reply_candidates WHERE session_id=? AND epoch=? AND turn_key=? AND reply IS NOT NULL
ORDER BY sequence DESC,sequence_index DESC,ordinal DESC LIMIT 1`)
.get(...prefix)
if (!row) {
db.prepare(
'DELETE FROM journal_outline_replies WHERE session_id=? AND epoch=? AND turn_key=?'
).run(...prefix)
return
}
const reply = String(row.reply)
db.prepare(`INSERT INTO journal_outline_replies(session_id,epoch,turn_key,reply,reply_bytes) VALUES(?,?,?,?,?)
ON CONFLICT(session_id,epoch,turn_key) DO UPDATE SET reply=excluded.reply,reply_bytes=excluded.reply_bytes
WHERE reply<>excluded.reply`).run(
...prefix,
reply,
Buffer.byteLength(JSON.stringify({ reply }), 'utf8') - 1
)
}
function sourceRow(row: SqliteRow): SourceRow {
const source: JournalOutlineSource = JSON.parse(String(row.outline_source_json))
return { source, ordinal: Number(row.ordinal), structure: journalOutlineStructure(source) }
}
/** Membership changes can refer backward through aliases/Stop; reproject compact facts, never originals. */
export function rebuildJournalDomainOutline(db: Database.Database, target: Target): void {
const prefix = [target.sessionId, target.epoch] as const
const sources = db
.prepare(`SELECT ordinal,outline_source_json FROM journal_items
INDEXED BY journal_items_visible_position WHERE session_id=? AND epoch=? AND hidden=0
AND outline_source_json IS NOT NULL ORDER BY sequence,sequence_index,ordinal`)
.all(...prefix)
.map(sourceRow)
const byId = new Map(sources.map((row) => [row.source.item.itemId, row]))
const submissions = db
.prepare(`SELECT outline_json FROM journal_submission_attempts
INDEXED BY journal_submission_ordinal WHERE session_id=? AND epoch=? AND current=1 ORDER BY ordinal`)
.all(...prefix)
.map((row): AgentJournalSubmission => JSON.parse(String(row.outline_json)))
const turnKeys = new Map<string, string>()
const entries = projectAgentSessionConversationOutline(
sources.map((row) => row.source.item),
submissions,
(messages, keys) => {
messages.forEach((message, index) => {
const key = keys[index]
if (key !== undefined) {
turnKeys.set(message.id, key)
}
})
return new Map()
},
{
projectItems: (items) =>
items.flatMap((item) => {
const source = byId.get(item.itemId)?.source
const message = source && journalOutlineMessage(source)
return message ? [message] : []
}),
userPreview: (message) => byId.get(message.id)!.source.preview!
}
)
const entriesById = new Map(entries.map((entry) => [entry.itemId, entry]))
const old = db
.prepare('SELECT item_id,turn_key FROM journal_outline_members WHERE session_id=? AND epoch=?')
.all(...prefix)
const affected = new Set<string>()
const remove = db.prepare(
'DELETE FROM journal_outline_members WHERE session_id=? AND epoch=? AND item_id=?'
)
for (const row of old) {
if (row.turn_key !== null) {
affected.add(String(row.turn_key))
}
if (!byId.has(String(row.item_id))) {
remove.run(...prefix, String(row.item_id))
}
}
for (const source of sources) {
const key = turnKeys.get(source.source.item.itemId)
if (key !== undefined) {
affected.add(key)
}
writeMember(db, target, source, key, entriesById.get(source.source.item.itemId))
}
for (const key of affected) {
refreshReply(db, target, key)
}
}
/** Stable prose revisions replace one preview/candidate; only structural facts regroup membership. */
export function refreshJournalDomainOutline(
db: Database.Database,
target: Target,
itemIds: readonly string[],
submissionsChanged: boolean
): void {
if (submissionsChanged) {
rebuildJournalDomainOutline(db, target)
return
}
const prefix = [target.sessionId, target.epoch] as const
const current = db.prepare(`SELECT ordinal,outline_source_json FROM journal_items
WHERE session_id=? AND epoch=? AND item_id=? AND hidden=0 AND outline_source_json IS NOT NULL`)
const member = db.prepare(`SELECT structure_json,turn_key,entry_json FROM journal_outline_members
WHERE session_id=? AND epoch=? AND item_id=?`)
const updates: { row: SourceRow; old: SqliteRow }[] = []
for (const id of new Set(itemIds)) {
const saved = current.get(...prefix, id)
const old = member.get(...prefix, id)
if (!saved && !old) {
continue
}
const row = saved && sourceRow(saved)
if (!row || !old || row.structure !== old.structure_json) {
rebuildJournalDomainOutline(db, target)
return
}
updates.push({ row, old })
}
const affected = new Set<string>()
for (const { row, old } of updates) {
const key = old.turn_key === null ? undefined : String(old.turn_key)
const preview = row.source.preview
const entry =
old.entry_json === null || preview === null
? undefined
: {
itemId: row.source.item.itemId,
sequence: row.source.item.sequence,
preview: preview.text,
imageCount: preview.imageCount,
...(key === undefined || key === row.source.item.itemId ? {} : { turnKey: key })
}
writeMember(db, target, row, key, entry)
if (key !== undefined) {
affected.add(key)
}
}
for (const key of affected) {
refreshReply(db, target, key)
}
}
@@ -1,84 +1,60 @@
import type {
AgentJournalRenderItem,
AgentJournalSubmission
} from '../../../shared/agent-session/journal/agent-session-journal-types'
import {
nativeChatTurnReplyPreviews,
projectAgentSessionConversationOutline
} from '../../../shared/agent-session/agent-session-conversation-outline'
import { projectStructuredItemToNativeChat } from '../../../shared/agent-session/view/structured-agent-session-projection'
import type { AgentSessionConversationOutlineEntry } from '../../../shared/agent-session/agent-session-conversation-outline'
import { journalDomainContextHead } from './journal-sql-continuation-context'
import { boundJournalConversationOutline } from './journal-outline-budget'
import type { JournalSqlScope } from './journal-sql-scope'
/** Outline membership uses saved placement; only prompts, turns and winning reply prose need bodies. */
/** Choose the global degradation before reading the admitted recent suffix. */
export function readJournalDomainOutline(scope: JournalSqlScope, budgetBytes: number) {
const { db, prefix } = scope
const rows = db
.prepare(`SELECT item_id,revision,sequence,placement_json,assistant_prose,
CASE WHEN (kind='message' AND message_role='user') OR turn_marker=1 OR context_clear=1
THEN payload_json END AS payload_json
FROM journal_items INDEXED BY journal_items_root_position
WHERE session_id=? AND epoch=? AND hidden=0 AND root=1
AND ((kind='message' AND message_role IN ('user','assistant'))
OR turn_marker=1 OR context_clear=1 OR turn_scope_kind='unknown')
ORDER BY sequence,sequence_index,ordinal`)
.all(...prefix)
const prose = new Set(
rows.filter((row) => row.assistant_prose === 1).map((row) => String(row.item_id))
)
const items = rows.map((row): AgentJournalRenderItem => {
const totals = db
.prepare(`SELECT COUNT(*) AS count,
COALESCE(SUM(member.entry_bytes + COALESCE(reply.reply_bytes,0)),0) AS with_reply,
COALESCE(SUM(member.entry_bytes),0) AS full,
COALESCE(SUM(member.short_bytes),0) AS short,
COALESCE(SUM(member.empty_bytes),0) AS empty
FROM journal_outline_members member INDEXED BY journal_outline_entries
LEFT JOIN journal_outline_replies reply ON reply.session_id=member.session_id
AND reply.epoch=member.epoch AND reply.turn_key=member.turn_key
WHERE member.session_id=? AND member.epoch=? AND member.entry_json IS NOT NULL`)
.get(...prefix)!
const replies = Number(totals.with_reply) <= budgetBytes
const variant =
replies || Number(totals.full) <= budgetBytes
? 'entry'
: Number(totals.short) <= budgetBytes
? 'short'
: 'empty'
const json = variant === 'entry' ? 'entry_json' : `${variant}_json`
const bytes = variant === 'entry' ? 'entry_bytes' : `${variant}_bytes`
const entries: AgentSessionConversationOutlineEntry[] = []
let total = 0
for (const row of db
.prepare(`SELECT member.${json} AS entry_json,
member.${bytes} + ${replies ? 'COALESCE(reply.reply_bytes,0)' : '0'} AS bytes,
${replies ? 'reply.reply' : 'NULL'} AS reply
FROM journal_outline_members member INDEXED BY journal_outline_entries
${
replies
? `LEFT JOIN journal_outline_replies reply ON reply.session_id=member.session_id
AND reply.epoch=member.epoch AND reply.turn_key=member.turn_key`
: ''
}
WHERE member.session_id=? AND member.epoch=? AND member.entry_json IS NOT NULL
ORDER BY member.sequence DESC,member.sequence_index DESC,member.ordinal DESC`)
.iterate(...prefix)) {
const next = Number(row.bytes)
if (total + next > budgetBytes) {
break
}
total += next
scope.examined(row)
if (row.payload_json !== null) {
return scope.decode<AgentJournalRenderItem>(row.payload_json)
}
return {
...scope.decode<Omit<AgentJournalRenderItem, 'body'>>(row.placement_json),
revision: Number(row.revision),
sequence: Number(row.sequence),
body: { kind: 'message', role: 'assistant', blocks: [] }
}
})
const submissions = db
.prepare(`SELECT payload_json FROM journal_submission_attempts
INDEXED BY journal_submission_ordinal WHERE session_id=? AND epoch=? AND current=1
ORDER BY ordinal`)
.all(...prefix)
.map((row) => scope.decode<AgentJournalSubmission>(scope.examined(row).payload_json))
const body = db.prepare(`SELECT payload_json FROM journal_items
WHERE session_id=? AND epoch=? AND item_id=? AND hidden=0`)
const entries = projectAgentSessionConversationOutline(items, submissions, (messages, keys) => {
const replies = new Map<string, string>()
for (let index = messages.length - 1; index >= 0; index--) {
const message = messages[index]
const key = keys[index]
if (
message.role !== 'assistant' ||
key === undefined ||
replies.has(key) ||
!prose.has(message.id)
) {
continue
}
const row = body.get(...prefix, message.id)
if (!row) {
continue
}
const saved = projectStructuredItemToNativeChat(
scope.decode<AgentJournalRenderItem>(scope.examined(row).payload_json)
)
if (saved) {
const reply = nativeChatTurnReplyPreviews([saved], [key]).get(key)
if (reply !== undefined) {
replies.set(key, reply)
}
}
}
return replies
})
return boundJournalConversationOutline(
{ sessionId: scope.sessionId, cursor: journalDomainContextHead(db, scope) },
const entry = scope.decode<AgentSessionConversationOutlineEntry>(row.entry_json)
entries.push(row.reply === null ? entry : { ...entry, reply: String(row.reply) })
}
entries.reverse()
return {
sessionId: scope.sessionId,
cursor: journalDomainContextHead(db, scope),
entries,
budgetBytes
)
omittedEntries: Number(totals.count) - entries.length
}
}
@@ -29,6 +29,7 @@ import {
import { readJournalDomainTurnScope } from './journal-domain-turn-scope'
import { writeJournalDomainQueueReopenMark } from './journal-domain-queue-pauses'
import { appendJournalSqlEvent } from './journal-sql-event-tail'
import { advanceJournalDomainSubmissionRevision } from './journal-domain-submission-revision'
import {
JOURNAL_DOMAIN_SUBMISSION_COLUMNS,
journalDomainSubmissionColumns
@@ -158,6 +159,8 @@ export function applyJournalDomainSubmission(
familyId
)
}
const payload = JSON.stringify(submission)
advanceJournalDomainSubmissionRevision(db, target, input.clientMessageId, payload)
db.prepare(`INSERT INTO journal_submission_attempts(session_id,epoch,message_id,attempt_sequence,attempt_index,current,
item_id,ordinal,candidate,admitted_personal,payload_json,
admission_body_json,admission_family_id,facts_json,${JOURNAL_DOMAIN_SUBMISSION_COLUMNS.join(',')})
@@ -175,7 +178,7 @@ export function applyJournalDomainSubmission(
? selected !== null && journalDomainAdmittedPersonal(selected.card)
: input.source?.kind === 'user' || (input.source === undefined && input.origin === 'client')
),
JSON.stringify(submission),
payload,
JSON.stringify(input.body),
familyId ?? null,
JSON.stringify({
@@ -1,4 +1,5 @@
import type { AgentJournalSubmission } from '../../../shared/agent-session/journal/agent-session-journal-types'
import { journalDomainOutlineSubmission } from './journal-domain-outline-source'
import { readWholeAgentSessionFailureFact } from '../../../shared/agent-session/failures/agent-session-failure'
import { classifyDispatchRejection } from '../../../shared/agent-session/requests/structured-agent-session-dispatch-rejection'
import {
@@ -18,7 +19,8 @@ export const JOURNAL_DOMAIN_SUBMISSION_COLUMNS = [
'request_failure',
'steer_turn_item_id',
'stopped_history',
'covers_stopped_history'
'covers_stopped_history',
'outline_json'
] as const
/** All current-attempt selectors describe the same saved dispatch and its source coverage. */
@@ -44,6 +46,7 @@ export function journalDomainSubmissionColumns(
),
submission.answeredInTurn?.via === 'steer' ? submission.answeredInTurn.turnItemId : null,
Number(stoppedHistoryCandidate(submission)),
Number(carries.length > 0 && !refusedBeforeWrite(submission))
Number(carries.length > 0 && !refusedBeforeWrite(submission)),
journalDomainOutlineSubmission(submission)
]
}
@@ -0,0 +1,21 @@
import type Database from '../../sqlite/sync-database'
/** Fork validation tracks public send changes, independently of streamed item revisions. */
export function advanceJournalDomainSubmissionRevision(
db: Database.Database,
target: { sessionId: string; epoch: string },
messageId: string,
payload: string
): void {
db.prepare(`UPDATE journal_chat_state SET submissions_revision=submissions_revision+1
WHERE session_id=? AND epoch=? AND NOT EXISTS(
SELECT 1 FROM journal_submission_attempts
WHERE session_id=? AND epoch=? AND message_id=? AND current=1 AND payload_json=?)`).run(
target.sessionId,
target.epoch,
target.sessionId,
target.epoch,
messageId,
payload
)
}
@@ -2,7 +2,8 @@ import { isDeepStrictEqual } from 'node:util'
import type Database from '../../sqlite/sync-database'
import type { SqliteRow } from '../../sqlite/sqlite-statement'
import type { AgentJournalRenderItem } from '../../../shared/agent-session/journal/agent-session-journal-types'
import { journalDomainHistoryMetadata } from './journal-domain-history-metadata'
import { journalDomainItemWire } from './journal-domain-history-metadata'
import { journalDomainOutlineSource } from './journal-domain-outline-source'
import { journalItemStatusMetadata } from './journal-item-status-metadata'
/** Stable text placement and classifications need no membership or indexed-column rewrite. */
@@ -37,12 +38,15 @@ export function writeJournalDomainTextSnapshot(
return false
}
const payload = JSON.stringify(item)
const { wireBytes } = journalDomainHistoryMetadata(item, payload)
db.prepare(`UPDATE journal_items SET payload_json=?,revision=?,wire_bytes=?
const { wireBytes, wireJson, detailJson } = journalDomainItemWire(item, payload)
db.prepare(`UPDATE journal_items SET payload_json=?,revision=?,wire_bytes=?,wire_json=?,detail_json=?,outline_source_json=?
WHERE session_id=? AND epoch=? AND item_id=?`).run(
payload,
revision,
wireBytes,
wireJson,
detailJson,
journalDomainOutlineSource(item),
target.sessionId,
target.epoch,
item.itemId
@@ -0,0 +1,73 @@
import { afterEach, expect, it } from 'vitest'
import {
domainLifecycleFixture,
lifecycleIdentity,
lifecycleOptions
} from './journal-domain-lifecycle.test-fixture'
import { readJournalSqlPoint } from './journal-sql-point-read'
import { readJournalDomainHistoryPage } from './journal-domain-history-page'
const cleanup: (() => void)[] = []
afterEach(() => cleanup.splice(0).forEach((close) => close()))
it('serves bounded history and detail without decoding originals, then replaces both with the next revision', async () => {
const f = domainLifecycleFixture(cleanup)
const head = 'é'.repeat(3 * 1024 * 1024)
const output = { head, byteLength: 6 * 1024 * 1024, digest: '0'.repeat(64), truncated: false }
await f.run({
kind: 'item',
identity: lifecycleIdentity('tool'),
options: lifecycleOptions,
body: { kind: 'tool-call', name: 'read', input: {}, output, state: 'completed' }
})
const point = (kind: 'item' | 'item-detail') =>
readJournalSqlPoint(f.db, {
sessionId: 'chat',
operation: { kind, itemId: 'orca:tool' }
})
expect(point('item')).toMatchObject({ item: { body: { output } } })
const original = f.db
.prepare("SELECT payload_json FROM journal_items WHERE item_id='orca:tool'")
.get()!.payload_json
f.db
.prepare("UPDATE journal_items SET payload_json=? WHERE item_id='orca:tool'")
.run('original must not be decoded')
const tail = readJournalDomainHistoryPage(f.db, { sessionId: 'chat', direction: 'tail' })
const forward = readJournalDomainHistoryPage(f.db, {
sessionId: 'chat',
direction: 'after',
cursor: { epoch: 'epoch', sequence: 0 }
})
expect(tail.page.items[0]).toMatchObject({
revision: 1,
shortened: true,
body: { output: { truncated: true } }
})
expect(forward.page.items).toEqual(tail.page.items)
const item = point('item-detail')
if (item.kind !== 'item-detail' || item.item?.body.kind !== 'tool-call') {
throw new Error('detail unavailable')
}
expect(item.item.shortened).toBe(true)
expect(item.item.body.output!.head.length).toBeGreaterThan(16 * 1024)
expect(Buffer.byteLength(JSON.stringify(item.item))).toBeLessThan(4 * 1024 * 1024)
f.db.prepare("UPDATE journal_items SET payload_json=? WHERE item_id='orca:tool'").run(original)
await f.run({
kind: 'item',
identity: lifecycleIdentity('tool'),
options: lifecycleOptions,
body: {
kind: 'tool-call',
name: 'read',
input: {},
output: { ...output, head: 'new result', byteLength: 10 },
state: 'completed'
}
})
expect(point('item-detail')).toMatchObject({
item: { revision: 2, body: { output: { head: 'new result' } } }
})
expect(
readJournalDomainHistoryPage(f.db, { sessionId: 'chat', direction: 'tail' }).page.items[0]
).toMatchObject({ revision: 2, body: { output: { head: 'new result' } } })
})
@@ -77,7 +77,7 @@ it('keeps bounded snapshot prefixes and controls in enqueue order', async () =>
kind: 'steps',
steps: Array.from({ length: steps }, () => ({
kind: 'resolved-item',
reservedBytes: 1024,
reservedBytes: Buffer.byteLength(text, 'utf8') + 1024,
resolution: { ...message(text), kind: 'text-snapshot' },
options: { fence: 1, turnScope: { kind: 'thread' } }
}))
@@ -2,6 +2,7 @@ import { appendJournalRequestEvent } from './journal-writer-request-events'
import type Database from '../../sqlite/sync-database'
import type { JournalDomainEventChanges } from './journal-domain-schema'
import { invalidateJournalDomainQueue } from './journal-domain-queue-revision'
import { refreshJournalDomainOutline } from './journal-domain-outline-write'
export const JOURNAL_EVENT_HISTORY_MS = 24 * 60 * 60 * 1000
const MAX_EVENT_SEQUENCES = 4096
@@ -17,6 +18,12 @@ export function appendJournalSqlEvent(
activity?: { fence: number; observedAt: number }
): void {
const prefix = [target.sessionId, target.epoch] as const
refreshJournalDomainOutline(
db,
target,
[...changes.items.map((item) => item.itemId), ...(changes.removedItemIds ?? [])],
changes.submissions.length > 0
)
const json = JSON.stringify(changes)
const oversized = Buffer.byteLength(json, 'utf8') > MAX_EVENT_BYTES
if (changes.cards.length > 0 || changes.submissions.length > 0) {
@@ -1,4 +1,5 @@
import type Database from '../../sqlite/sync-database'
import { advanceJournalDomainSubmissionRevision } from './journal-domain-submission-revision'
import { refreshJournalDomainAcceptedHandover } from './journal-domain-input-ends'
import type {
AgentJournalMessageItem,
@@ -87,11 +88,18 @@ export function acceptJournalSqlMessageEcho(
resolvedAt: row.ts
}
delete accepted.recovered
const payload = JSON.stringify(accepted)
advanceJournalDomainSubmissionRevision(
db,
{ sessionId: prefix[0], epoch: prefix[1] },
accepted.clientMessageId,
payload
)
db.prepare(`UPDATE journal_submission_attempts SET candidate=0,payload_json=?,
${JOURNAL_DOMAIN_SUBMISSION_COLUMNS.map((column) => `${column}=?`).join(',')},
echo_observed=1,admission_body_json=CASE WHEN ? THEN admission_body_json ELSE NULL END
WHERE session_id=? AND epoch=? AND message_id=? AND current=1`).run(
JSON.stringify(accepted),
payload,
...journalDomainSubmissionColumns(accepted, facts.carries),
Number(retainedSource),
...prefix,
@@ -62,6 +62,7 @@ export type JournalSqlPointRead = {
| { kind: 'input-read'; operation: JournalInputRead }
| { kind: 'metadata' }
| { kind: 'item'; itemId: string }
| { kind: 'item-detail'; itemId: string }
| { kind: 'submission'; clientMessageId: string }
| { kind: 'submission-body'; clientMessageId: string }
| { kind: 'acceptance'; clientMessageId: string }
@@ -110,6 +111,7 @@ export type JournalSqlPointReadResult =
historyOrigin: JournalReducerState['historyOrigin']
}
| { kind: 'item'; item: AgentJournalRenderItem | null }
| { kind: 'item-detail'; item: AgentJournalRenderItem | null }
| { kind: 'submission'; submission: AgentJournalSubmission | undefined }
| { kind: 'submission-body'; body: AgentJournalMessageItem | null }
| { kind: 'acceptance'; receipt: AgentJournalAcceptanceReceipt | null }
@@ -147,6 +147,7 @@ function read(
case 'provider-turn-in-namespace':
case 'saved-item-ids':
case 'item':
case 'item-detail':
case 'submission':
case 'submission-body':
case 'acceptance':
@@ -24,6 +24,7 @@ import type {
} from './journal-input-reads'
export type JournalSqlReads = AgentSessionJournalReads & {
itemDetail(itemId: string): Promise<AgentJournalRenderItem | null>
forkBoundary(
itemId: string,
inheritedAnchor: string | undefined,
@@ -167,6 +168,7 @@ export function journalSqlReads(
lastActivityAt: async () => (await metadata()).lastActivityAt,
historyOrigin: async () => (await metadata()).historyOrigin,
item,
itemDetail: async (itemId) => (await read({ kind: 'item-detail', itemId })).item,
itemBody: async (itemId) => (await item(itemId))?.body ?? null,
itemFence: async (itemId) => {
const { executionOwner, ownerFence } = await provenance(itemId)
@@ -25,7 +25,26 @@ export function prepareJournalSqlRequest(
batch = {
sessionId: command.command.target.sessionId,
steps: operation.steps.length,
bytes: Buffer.byteLength(JSON.stringify(command.command), 'utf8')
// Admission already reserved identity/body bytes; only size the remaining envelope.
bytes:
operation.steps.reduce((total, step) => total + step.reservedBytes, 0) +
Buffer.byteLength(
JSON.stringify({
...command.command,
operation: {
...operation,
steps: operation.steps.map((step) =>
step.kind === 'resolved-item' && step.resolution.kind === 'text-snapshot'
? {
...step,
resolution: { ...step.resolution, body: null, identity: null }
}
: step
)
}
}),
'utf8'
)
}
}
}
@@ -57,7 +57,7 @@ export class StructuredAgentSessionBackgroundTaskChannel {
(await this.conversation(sessionId)).journal.reads.savedContent()
historyItem = async (sessionId: string, itemId: string) =>
(await this.conversation(sessionId)).journal.reads.item(itemId)
(await this.conversation(sessionId)).journal.reads.itemDetail(itemId)
conversationOutline = async (sessionId: string) =>
(await this.conversation(sessionId)).journal.reads.conversationOutline(
@@ -71,19 +71,22 @@ export class StructuredAgentSessionBackgroundTaskChannel {
replaceNormalizedHistory = true
): Promise<AgentSessionHistoryResult> {
const journal = (await this.conversation(request.sessionId)).journal
const work = await this.currentWork(request.sessionId)
const result = await readStructuredAgentSessionHistoryResult({
journal,
record: this.deps.store.getConversation(request.sessionId),
forkMarker: readForkMarker(this.deps.store, request.sessionId),
request,
scope,
reader,
replaceNormalizedHistory,
...(work ? { work } : {})
})
const [result, queue] = await Promise.all([
this.currentWork(request.sessionId).then((work) =>
readStructuredAgentSessionHistoryResult({
journal,
record: this.deps.store.getConversation(request.sessionId),
forkMarker: readForkMarker(this.deps.store, request.sessionId),
request,
scope,
reader,
replaceNormalizedHistory,
...(work ? { work } : {})
})
),
this.subscribers.readQueuePublication(request.sessionId)
])
const backgroundTasks = this.read(request.sessionId)
const queue = await this.subscribers.readQueuePublication(request.sessionId)
const hostNow = this.deps.now?.() ?? Date.now()
return {
...result,
@@ -3,14 +3,11 @@
import type { AgentJournalRenderItem } from '../../../../../../shared/agent-session/journal/agent-session-journal-types'
import { ItemParams } from '../../../../../../shared/rpc-contract/structured-agent-session-params'
import { shortenedAgentJournalItem } from '../../../../../native-chat/agent-session-wire/publication/history/agent-session-item-wire-form'
import { REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES } from '../../../../../../shared/remote-runtime/remote-runtime-memory-limits'
import { JOURNAL_ITEM_DETAIL_MAX_BYTES } from '../../../../../native-chat/agent-session-journal/journal-domain-history-metadata'
import { defineMethod } from '../../../core'
import { requireInstalledStructuredHost } from '../creation/structured-agent-session-gate'
import { projectReceiptDeviceItem } from '../subscriptions/structured-agent-session-receipt-devices'
/** The item's share of one reply, with room for the envelope beside it. */
const ITEM_REPLY_MAX_BYTES = REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - 64 * 1024
export const STRUCTURED_AGENT_SESSION_ITEM_METHODS = [
defineMethod({
name: 'agentSession.item',
@@ -25,7 +22,10 @@ export const STRUCTURED_AGENT_SESSION_ITEM_METHODS = [
}
// Null only for an item whose identifiers alone exceed a reply; the client keeps its head.
return {
item: shortenedAgentJournalItem(projectReceiptDeviceItem(item, ctx), ITEM_REPLY_MAX_BYTES)
item: shortenedAgentJournalItem(
projectReceiptDeviceItem(item, ctx),
JOURNAL_ITEM_DETAIL_MAX_BYTES
)
}
}
})
@@ -68,7 +68,7 @@ const replies = new WeakMap<readonly NativeChatBlock[], string>()
/** An assistant message as preview prose: fenced code, rules and markdown markers
* dropped, cut to the preview cap. */
function assistantReplyProse(blocks: readonly NativeChatBlock[]): string {
export function assistantReplyProse(blocks: readonly NativeChatBlock[]): string {
const cached = replies.get(blocks)
if (cached !== undefined) {
return cached
@@ -151,7 +151,11 @@ export function projectAgentSessionConversationOutline(
readReplies: (
messages: readonly NativeChatMessage[],
turnKeys: readonly (string | undefined)[]
) => ReadonlyMap<string, string> = nativeChatTurnReplyPreviews
) => ReadonlyMap<string, string> = nativeChatTurnReplyPreviews,
facts?: {
projectItems: (items: readonly AgentJournalRenderItem[]) => NativeChatMessage[]
userPreview: (message: NativeChatMessage) => NativeChatUserMessagePreview
}
): AgentSessionConversationOutlineEntry[] {
const sequences = new Map<string, number>()
for (const item of items) {
@@ -168,7 +172,7 @@ export function projectAgentSessionConversationOutline(
const entries: AgentSessionConversationOutlineEntry[] = []
const transcript = projectNativeChatTranscriptMessages(
// Unchanged on the wire: a not-sent row ticks only once a desktop loads its page.
projectStructuredAgentSessionMessages(items, [], submissions).filter(
projectStructuredAgentSessionMessages(items, [], submissions, facts?.projectItems).filter(
(message) => !message.unsent
)
)
@@ -184,7 +188,7 @@ export function projectAgentSessionConversationOutline(
) {
continue
}
const preview = nativeChatUserMessagePreview(message.blocks)
const preview = facts?.userPreview(message) ?? nativeChatUserMessagePreview(message.blocks)
const turnKey = turnKeys[index]
const reply = turnKey === undefined ? undefined : replies.get(turnKey)
entries.push({