mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
Merge commit '866cbad6069' into brennanb2025/native-chat-sqlite-host
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
import type { AgentJournalRenderItem } from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import { isAgentSessionContextClear } from '../../../shared/agent-session/agent-session-context-clear'
|
||||
import { currentAgentSessionThreadGoalSourceBySequence } from '../../../shared/agent-session/agent-session-thread-goal'
|
||||
import { readAgentJournalTurn } from '../../../shared/agent-session/lifecycle/agent-session-turn-record'
|
||||
import { claudeAgentRowFacts } from '../../claude/claude-subagent-journaled-identities'
|
||||
|
||||
/** journal_items columns the direct item reads seek by; frozen 001 declares them beside history's. */
|
||||
export const JOURNAL_DOMAIN_ITEM_READ_COLUMNS = [
|
||||
'kind TEXT',
|
||||
'message_role TEXT',
|
||||
'turn_id TEXT',
|
||||
'opener_item_id TEXT',
|
||||
'context_clear INTEGER NOT NULL DEFAULT 0',
|
||||
'goal_transition INTEGER NOT NULL DEFAULT 0',
|
||||
'producer_agent_id TEXT',
|
||||
'producer_parent_ref TEXT',
|
||||
'producer_attempt INTEGER'
|
||||
] as const
|
||||
|
||||
export const JOURNAL_DOMAIN_ITEM_READ_INDEXES = `
|
||||
CREATE INDEX journal_items_kind ON journal_items(session_id, epoch, kind, ordinal) WHERE hidden=0;
|
||||
CREATE INDEX journal_items_user_message ON journal_items(session_id, epoch, ordinal)
|
||||
WHERE hidden=0 AND kind='message' AND message_role='user';
|
||||
CREATE INDEX journal_items_named_turn ON journal_items(session_id, epoch, turn_id, sequence, sequence_index, ordinal)
|
||||
WHERE hidden=0 AND turn_id IS NOT NULL;
|
||||
CREATE INDEX journal_items_opener ON journal_items(session_id, epoch, opener_item_id, ordinal)
|
||||
WHERE hidden=0 AND opener_item_id IS NOT NULL;
|
||||
CREATE INDEX journal_items_context_clear ON journal_items(session_id, epoch, sequence)
|
||||
WHERE hidden=0 AND context_clear=1;
|
||||
CREATE INDEX journal_items_goal_transition ON journal_items(session_id, epoch, sequence, ordinal)
|
||||
WHERE hidden=0 AND goal_transition=1;
|
||||
CREATE INDEX journal_items_producer_parent ON journal_items(session_id, epoch, producer_parent_ref, ordinal, producer_agent_id)
|
||||
WHERE hidden=0 AND producer_parent_ref IS NOT NULL;
|
||||
CREATE INDEX journal_items_producer_attempt ON journal_items(session_id, epoch, producer_agent_id, producer_attempt)
|
||||
WHERE hidden=0 AND producer_agent_id IS NOT NULL;
|
||||
CREATE INDEX journal_submission_order ON journal_submission_attempts(session_id, epoch, submitted_at, ordinal, message_id)
|
||||
WHERE current=1;
|
||||
CREATE INDEX journal_item_tombstones_turn ON journal_item_tombstones(session_id, epoch, turn_id)
|
||||
WHERE turn_id IS NOT NULL;
|
||||
`
|
||||
|
||||
/** The removed item's turn ID, written by the tombstone writer from the row it deletes. */
|
||||
export const JOURNAL_DOMAIN_TOMBSTONE_READ_COLUMNS = ['turn_id TEXT'] as const
|
||||
|
||||
/** Bound in JOURNAL_DOMAIN_ITEM_READ_COLUMNS order by the one item/import upsert. */
|
||||
export type JournalDomainItemReadColumns = readonly [
|
||||
kind: string,
|
||||
messageRole: string | null,
|
||||
turnId: string | null,
|
||||
openerItemId: string | null,
|
||||
contextClear: number,
|
||||
goalTransition: number,
|
||||
producerAgentId: string | null,
|
||||
producerParentRef: string | null,
|
||||
producerAttempt: number | null
|
||||
]
|
||||
|
||||
/** Row-local facts only, written from each stored revision; no cross-row verdict. */
|
||||
export function journalDomainItemReadColumns(
|
||||
item: AgentJournalRenderItem
|
||||
): JournalDomainItemReadColumns {
|
||||
const { body } = item
|
||||
const turn = readAgentJournalTurn(body)
|
||||
const producer = claudeAgentRowFacts(item)
|
||||
return [
|
||||
body.kind,
|
||||
body.kind === 'message' ? body.role : null,
|
||||
turn?.turnId ?? null,
|
||||
body.kind === 'turn' ? (body.userItemId ?? null) : null,
|
||||
Number(isAgentSessionContextClear(body)),
|
||||
Number(currentAgentSessionThreadGoalSourceBySequence([item]) !== undefined),
|
||||
producer?.agentId ?? null,
|
||||
producer?.parentRef ?? null,
|
||||
producer?.attempt ?? null
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
import { afterEach, expect, it } from 'vitest'
|
||||
import Database from '../../sqlite/sync-database'
|
||||
import type {
|
||||
AgentJournalItemBody,
|
||||
AgentJournalRenderItem,
|
||||
AgentJournalSubmission
|
||||
} from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import { migrateJournalDomainSchema } from './journal-domain-schema'
|
||||
import { journalDomainHistoryMetadata } from './journal-domain-history-metadata'
|
||||
import { writeJournalDomainItemNames } from './journal-domain-item-names'
|
||||
import {
|
||||
JOURNAL_DOMAIN_ITEM_READ_COLUMNS,
|
||||
JOURNAL_DOMAIN_ITEM_READ_INDEXES,
|
||||
JOURNAL_DOMAIN_TOMBSTONE_READ_COLUMNS,
|
||||
journalDomainItemReadColumns
|
||||
} from './journal-domain-item-read-columns'
|
||||
import { readJournalDomainItems, type JournalDomainItemRead } from './journal-sql-item-reads'
|
||||
|
||||
const target = { sessionId: 'chat', epoch: 'epoch' }
|
||||
const databases: Database.Database[] = []
|
||||
afterEach(() => {
|
||||
for (const db of databases.splice(0)) {
|
||||
db.close()
|
||||
}
|
||||
})
|
||||
|
||||
function chat() {
|
||||
const db = new Database(':memory:')
|
||||
databases.push(db)
|
||||
migrateJournalDomainSchema(db)
|
||||
// TEMPORARY until the author folds the item-read fragment into frozen 001.
|
||||
for (const column of JOURNAL_DOMAIN_ITEM_READ_COLUMNS) {
|
||||
db.exec(`ALTER TABLE journal_items ADD COLUMN ${column}`)
|
||||
}
|
||||
for (const column of JOURNAL_DOMAIN_TOMBSTONE_READ_COLUMNS) {
|
||||
db.exec(`ALTER TABLE journal_item_tombstones ADD COLUMN ${column}`)
|
||||
}
|
||||
db.exec(JOURNAL_DOMAIN_ITEM_READ_INDEXES)
|
||||
db.prepare(
|
||||
`INSERT INTO journal_chat_state(session_id,epoch,last_sequence,highest_fence) VALUES(?,?,900,1)`
|
||||
).run(target.sessionId, target.epoch)
|
||||
// Stored ordinal is admission order; sequence is the item's current render placement.
|
||||
const seed = (
|
||||
item: AgentJournalRenderItem,
|
||||
placement: { ordinal?: number; hidden?: boolean } = {}
|
||||
) => {
|
||||
const ordinal = placement.ordinal ?? item.sequence
|
||||
const payload = JSON.stringify(item)
|
||||
const metadata = journalDomainHistoryMetadata(item, payload)
|
||||
db.prepare(`INSERT INTO journal_items
|
||||
(session_id,epoch,item_id,ordinal,revision,sequence,sequence_index,owner_fence,payload_json,hidden,
|
||||
root,subagent_row,subagent_group_key,turn_marker,wire_bytes,
|
||||
kind,message_role,turn_id,opener_item_id,context_clear,goal_transition,
|
||||
producer_agent_id,producer_parent_ref,producer_attempt)
|
||||
VALUES(?,?,?,?,?,?,?,1,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(
|
||||
target.sessionId,
|
||||
target.epoch,
|
||||
item.itemId,
|
||||
ordinal,
|
||||
item.revision,
|
||||
item.sequence,
|
||||
item.sequenceIndex ?? 0,
|
||||
payload,
|
||||
Number(placement.hidden ?? false),
|
||||
metadata.root,
|
||||
metadata.subagentRow,
|
||||
metadata.subagentGroupKey,
|
||||
metadata.turnMarker,
|
||||
metadata.wireBytes,
|
||||
...journalDomainItemReadColumns(item)
|
||||
)
|
||||
writeJournalDomainItemNames(
|
||||
db,
|
||||
target,
|
||||
item,
|
||||
{ ordinal, hidden: placement.hidden ?? false },
|
||||
metadata.namedSubagentIds
|
||||
)
|
||||
}
|
||||
const alias = (providerItemId: string, itemId: string) =>
|
||||
db
|
||||
.prepare(
|
||||
'INSERT INTO journal_item_aliases(session_id,epoch,provider_item_id,item_id) VALUES(?,?,?,?)'
|
||||
)
|
||||
.run(target.sessionId, target.epoch, providerItemId, itemId)
|
||||
const tombstone = (itemId: string, turnId: string | null = null) =>
|
||||
db
|
||||
.prepare(
|
||||
'INSERT INTO journal_item_tombstones(session_id,epoch,item_id,revision,turn_id) VALUES(?,?,?,9,?)'
|
||||
)
|
||||
.run(target.sessionId, target.epoch, itemId, turnId)
|
||||
const send = (submission: AgentJournalSubmission, ordinal: number) =>
|
||||
db
|
||||
.prepare(`INSERT INTO journal_submission_attempts(session_id,epoch,message_id,attempt_sequence,attempt_index,
|
||||
current,item_id,ordinal,submitted_at,accepted_sequence,fingerprint,dispatch_state,payload_json)
|
||||
VALUES(?,?,?,1,0,1,?,?,?,?,?,?,?)`)
|
||||
.run(
|
||||
target.sessionId,
|
||||
target.epoch,
|
||||
submission.clientMessageId,
|
||||
`orca:${submission.clientMessageId}`,
|
||||
ordinal,
|
||||
submission.submittedAt,
|
||||
submission.acceptedSequence ?? null,
|
||||
submission.clientMessageId,
|
||||
submission.dispatchState,
|
||||
JSON.stringify(submission)
|
||||
)
|
||||
const read = <K extends JournalDomainItemRead['kind']>(
|
||||
operation: Extract<JournalDomainItemRead, { kind: K }>
|
||||
) => {
|
||||
const result = readJournalDomainItems(db, target, operation)
|
||||
if (result.kind !== operation.kind) {
|
||||
throw new Error('item read answered a different operation')
|
||||
}
|
||||
return result as Extract<typeof result, { kind: K }>
|
||||
}
|
||||
return { db, seed, alias, tombstone, send, read }
|
||||
}
|
||||
|
||||
function row(
|
||||
itemId: string,
|
||||
sequence: number,
|
||||
body: AgentJournalItemBody,
|
||||
extra: Partial<AgentJournalRenderItem> = {}
|
||||
): AgentJournalRenderItem {
|
||||
return { itemId, revision: 1, sequence, observedAt: sequence, body, ...extra }
|
||||
}
|
||||
const user = (text: string): AgentJournalItemBody => ({
|
||||
kind: 'message',
|
||||
role: 'user',
|
||||
blocks: [{ type: 'text', text }]
|
||||
})
|
||||
const turn = (
|
||||
turnId: string,
|
||||
state: 'running' | 'completed',
|
||||
extra: Partial<Extract<AgentJournalItemBody, { kind: 'turn' }>> = {}
|
||||
): AgentJournalItemBody => ({ kind: 'turn', turnId, state, ...extra })
|
||||
const clear: AgentJournalItemBody = {
|
||||
kind: 'status',
|
||||
text: 'Cleared',
|
||||
contextClear: { operationId: 'clear', afterFence: 1, clearedAt: 1 }
|
||||
}
|
||||
const window = (tokens: number) => ({ window: { tokens, capturedAt: tokens } })
|
||||
|
||||
it('resolves aliases and openers and presents hidden or removed rows as removed', () => {
|
||||
const { seed, alias, tombstone, read } = chat()
|
||||
seed(row('orca:send', 5, user('hello')))
|
||||
alias('provider:send', 'orca:send')
|
||||
seed(row('turn-a', 6, turn('t-a', 'completed', { userItemId: 'provider:send' })))
|
||||
seed(row('turn-b', 4, turn('t-b', 'completed', { userItemId: 'orca:send' })), { ordinal: 7 })
|
||||
seed(row('orca:rejected', 8, user('no')), { hidden: true })
|
||||
tombstone('gone')
|
||||
|
||||
expect(read({ kind: 'canonical-item-ids', itemIds: ['provider:send', 'x'] }).items).toEqual([
|
||||
{ itemId: 'provider:send', canonicalItemId: 'orca:send' },
|
||||
{ itemId: 'x', canonicalItemId: 'x' }
|
||||
])
|
||||
const history = read({
|
||||
kind: 'history-items',
|
||||
itemIds: ['provider:send', 'orca:rejected', 'gone'],
|
||||
options: { includeOpeners: true }
|
||||
}).items
|
||||
expect(
|
||||
history.map(({ key, canonicalItemId, removed, openedTurnIds }) => ({
|
||||
key,
|
||||
canonicalItemId,
|
||||
removed,
|
||||
openedTurnIds
|
||||
}))
|
||||
).toEqual([
|
||||
{
|
||||
key: 'provider:send',
|
||||
canonicalItemId: 'orca:send',
|
||||
removed: false,
|
||||
openedTurnIds: ['turn-a', 'turn-b']
|
||||
},
|
||||
{
|
||||
key: 'orca:rejected',
|
||||
canonicalItemId: 'orca:rejected',
|
||||
removed: true,
|
||||
openedTurnIds: undefined
|
||||
},
|
||||
{ key: 'gone', canonicalItemId: 'gone', removed: true, openedTurnIds: undefined },
|
||||
{ key: 'orca:send', canonicalItemId: 'orca:send', removed: false, openedTurnIds: undefined },
|
||||
{ key: 'turn-a', canonicalItemId: 'turn-a', removed: false, openedTurnIds: undefined },
|
||||
{ key: 'turn-b', canonicalItemId: 'turn-b', removed: false, openedTurnIds: undefined }
|
||||
])
|
||||
expect(history.find((entry) => entry.key === 'orca:rejected')?.item).toBeNull()
|
||||
})
|
||||
|
||||
it('reads the newest turn, its clear boundary and named turns by current placement', () => {
|
||||
const { seed, tombstone, read } = chat()
|
||||
seed(row('old-turn', 1, turn('t-old', 'completed', { contextUsage: window(10) })))
|
||||
seed(row('clear', 2, clear))
|
||||
seed(row('used-turn', 3, turn('t-used', 'completed', { contextUsage: window(30) })))
|
||||
// Admitted first but moved to the newest placement: placement decides, admission breaks ties.
|
||||
seed(row('moved', 9, turn('t-moved', 'running')), { ordinal: 1 })
|
||||
seed(row('tied-early', 9, turn('t-tied', 'completed')), { ordinal: 0 })
|
||||
seed(row('orca:ask', 4, user('go')))
|
||||
tombstone('removed-turn', 't-removed')
|
||||
|
||||
expect(read({ kind: 'running-turn' }).running).toEqual({
|
||||
item: expect.objectContaining({ itemId: 'moved' }),
|
||||
turnId: 't-moved'
|
||||
})
|
||||
// The input order's newest turn breaks the same placement tie by item ID instead.
|
||||
expect(read({ kind: 'message-options', clientMessageId: 'ask' }).options).toEqual({
|
||||
ordinaryMessage: true,
|
||||
runningTurn: false
|
||||
})
|
||||
expect(read({ kind: 'context-usage' }).usage).toEqual(window(30))
|
||||
expect(read({ kind: 'context-floor' }).floor).toEqual({ epoch: 'epoch', sequence: 2 })
|
||||
expect(read({ kind: 'named-turn', turnId: 't-moved' }).turn).toEqual({
|
||||
scope: { kind: 'turn', turnItemId: 'moved' },
|
||||
removed: false
|
||||
})
|
||||
expect(read({ kind: 'named-turn', turnId: 't-removed' }).turn).toEqual({
|
||||
scope: null,
|
||||
removed: true
|
||||
})
|
||||
})
|
||||
|
||||
it('selects producer identities and the roster from scalars, skipping hidden rows', () => {
|
||||
const { seed, read } = chat()
|
||||
const agentRow = (
|
||||
itemId: string,
|
||||
sequence: number,
|
||||
agentId: string,
|
||||
ref: string,
|
||||
attempt?: number
|
||||
) =>
|
||||
row(
|
||||
itemId,
|
||||
sequence,
|
||||
{ kind: 'message', role: 'assistant', blocks: [] },
|
||||
{
|
||||
agentId,
|
||||
providerParentRef: ref,
|
||||
producerKind: 'agent',
|
||||
...(attempt === undefined ? {} : { attempt })
|
||||
}
|
||||
)
|
||||
seed(agentRow('first', 1, 'agent-a', 'tool-1', 2))
|
||||
// The later-admitted alias wins even when it renders earlier.
|
||||
seed(agentRow('second', 0, 'agent-b', 'tool-1'), { ordinal: 5 })
|
||||
seed(agentRow('hidden', 3, 'agent-c', 'tool-2', 7), { hidden: true })
|
||||
const naming = (itemId: string, sequence: number, id: string) =>
|
||||
row(itemId, sequence, {
|
||||
kind: 'message',
|
||||
role: 'assistant',
|
||||
blocks: [{ type: 'subagent', id, label: id, state: 'working', groupId: 'g' }]
|
||||
})
|
||||
seed(naming('names-a', 6, 'agent-a'))
|
||||
seed(naming('names-c', 7, 'agent-c'), { hidden: true })
|
||||
|
||||
const snapshot = read({ kind: 'claude-snapshot' }).snapshot
|
||||
expect(new Map(snapshot.canonicalByToolUse)).toEqual(new Map([['tool-1', 'agent-b']]))
|
||||
expect(new Map(snapshot.attemptByAgent)).toEqual(
|
||||
new Map([
|
||||
['agent-a', 2],
|
||||
['agent-b', 1]
|
||||
])
|
||||
)
|
||||
expect(snapshot.subagents).toEqual(['agent-a'])
|
||||
})
|
||||
|
||||
it('exports visible rows and sends after the newest clear across bounded query pages', () => {
|
||||
const { seed, send, read } = chat()
|
||||
const submission = (
|
||||
id: string,
|
||||
submittedAt: number,
|
||||
acceptedSequence?: number
|
||||
): AgentJournalSubmission => ({
|
||||
clientMessageId: id,
|
||||
fence: 1,
|
||||
payloadFingerprint: id,
|
||||
dispatchState: acceptedSequence === undefined ? 'pending' : 'accepted',
|
||||
providerItemId: null,
|
||||
reason: null,
|
||||
submittedAt,
|
||||
resolvedAt: null,
|
||||
...(acceptedSequence === undefined ? {} : { acceptedSequence })
|
||||
})
|
||||
seed(row('orca:before', 1, user('before')))
|
||||
send(submission('before', 1, 1), 1)
|
||||
send(submission('pending', 2), 2)
|
||||
seed(row('clear', 3, clear))
|
||||
const tail = Array.from({ length: 300 }, (_, index) => `tail-${index}`)
|
||||
tail.forEach((id, index) => seed(row(id, 4 + index, user(id))))
|
||||
seed(row('orca:after', 400, user('after')))
|
||||
send(submission('after', 3, 400), 3)
|
||||
seed(row('orca:rejected', 401, user('rejected')), { hidden: true })
|
||||
send(submission('rejected', 4, 401), 4)
|
||||
|
||||
const context = read({ kind: 'continuation-context' }).context
|
||||
expect(context.cursor).toEqual({ epoch: 'epoch', sequence: 900 })
|
||||
expect(context.items.map((item) => item.itemId)).toEqual([...tail, 'orca:after'])
|
||||
expect(context.submissions.map((entry) => entry.clientMessageId)).toEqual(['after', 'rejected'])
|
||||
})
|
||||
@@ -1,37 +1,39 @@
|
||||
import type Database from '../../sqlite/sync-database'
|
||||
import type { ClaudeJournalSnapshot } from '../../claude/claude-subagent-journaled-identities'
|
||||
import type { JournalSqlScope } from './journal-sql-scope'
|
||||
|
||||
/** Read the derived columns only: the last alias per parent, the floored highest attempt, the roster. */
|
||||
export function readJournalSqlClaudeIdentities(
|
||||
scope: JournalSqlScope
|
||||
/** Selected scalars and name memberships only: the last alias per parent, the floored highest attempt, the roster. */
|
||||
export function readJournalDomainClaudeIdentities(
|
||||
db: Database.Database,
|
||||
prefix: readonly [string, string]
|
||||
): Omit<ClaudeJournalSnapshot, 'threadGoal'> {
|
||||
const canonical = new Map<string, string>()
|
||||
for (const row of scope.db
|
||||
.prepare(`SELECT producer_parent_ref, producer_agent_id FROM journal_proj_items
|
||||
WHERE session_id=? AND epoch=? AND producer_parent_ref IS NOT NULL AND hidden=0 ORDER BY ordinal`)
|
||||
.all(...scope.prefix)) {
|
||||
scope.examined(row)
|
||||
canonical.set(String(row.producer_parent_ref), String(row.producer_agent_id))
|
||||
}
|
||||
const attempts: [string, number][] = []
|
||||
for (const row of scope.db
|
||||
.prepare(`SELECT producer_agent_id, MAX(producer_attempt) AS attempt FROM journal_proj_items
|
||||
WHERE session_id=? AND epoch=? AND producer_agent_id IS NOT NULL AND hidden=0
|
||||
// SQLite returns the bare agent column from the MAX(ordinal) row of each group.
|
||||
const canonicalByToolUse = db
|
||||
.prepare(`SELECT producer_parent_ref, producer_agent_id, MAX(ordinal) AS ordinal
|
||||
FROM journal_items INDEXED BY journal_items_producer_parent
|
||||
WHERE session_id=? AND epoch=? AND hidden=0 AND producer_parent_ref IS NOT NULL
|
||||
GROUP BY producer_parent_ref ORDER BY ordinal`)
|
||||
.all(...prefix)
|
||||
.map((row): [string, string] => [
|
||||
String(row.producer_parent_ref),
|
||||
String(row.producer_agent_id)
|
||||
])
|
||||
const attemptByAgent = db
|
||||
.prepare(`SELECT producer_agent_id, MAX(producer_attempt) AS attempt
|
||||
FROM journal_items INDEXED BY journal_items_producer_attempt
|
||||
WHERE session_id=? AND epoch=? AND hidden=0 AND producer_agent_id IS NOT NULL
|
||||
GROUP BY producer_agent_id`)
|
||||
.all(...scope.prefix)) {
|
||||
scope.examined(row)
|
||||
attempts.push([String(row.producer_agent_id), Math.max(1, Number(row.attempt))])
|
||||
}
|
||||
const subagents = new Set<string>()
|
||||
for (const row of scope.db
|
||||
.prepare(`SELECT subagent_names FROM journal_proj_items
|
||||
WHERE session_id=? AND epoch=? AND subagent_names IS NOT NULL AND hidden=0 ORDER BY ordinal`)
|
||||
.all(...scope.prefix)) {
|
||||
scope.examined(row)
|
||||
const names: { id: string }[] = JSON.parse(String(row.subagent_names))
|
||||
for (const { id } of names) {
|
||||
subagents.add(id)
|
||||
}
|
||||
}
|
||||
return { canonicalByToolUse: [...canonical], attemptByAgent: attempts, subagents: [...subagents] }
|
||||
.all(...prefix)
|
||||
.map((row): [string, number] => [
|
||||
String(row.producer_agent_id),
|
||||
Math.max(1, Number(row.attempt))
|
||||
])
|
||||
const subagents = db
|
||||
.prepare(`SELECT name.subagent_id FROM journal_item_subagent_names name
|
||||
JOIN journal_items item ON item.session_id=name.session_id AND item.epoch=name.epoch
|
||||
AND item.item_id=name.item_id
|
||||
WHERE name.session_id=? AND name.epoch=? AND item.hidden=0
|
||||
GROUP BY name.subagent_id ORDER BY MIN(item.ordinal)`)
|
||||
.all(...prefix)
|
||||
.map((row) => String(row.subagent_id))
|
||||
return { canonicalByToolUse, attemptByAgent, subagents }
|
||||
}
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
import { afterEach, expect, it } from 'vitest'
|
||||
import type {
|
||||
AgentJournalRenderItem,
|
||||
AgentJournalSubmission
|
||||
} from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import { agentJournalSubmissionKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import Database from '../../sqlite/sync-database'
|
||||
import { JournalSqlScope } from './journal-sql-scope'
|
||||
import { JournalSqlReducer } from './journal-sql-reducer'
|
||||
import { journalSqlProjectionSchema } from './journal-sql-projection-schema'
|
||||
import { readJournalSqlContinuationContext } from './journal-sql-continuation-context'
|
||||
|
||||
const databases: Database.Database[] = []
|
||||
afterEach(() => {
|
||||
for (const db of databases.splice(0)) {
|
||||
db.close()
|
||||
}
|
||||
})
|
||||
|
||||
function send(id: string, submittedAt: number, acceptedSequence?: number): AgentJournalSubmission {
|
||||
return {
|
||||
clientMessageId: id,
|
||||
fence: 1,
|
||||
payloadFingerprint: id,
|
||||
dispatchState: acceptedSequence === undefined ? 'pending' : 'accepted',
|
||||
providerItemId: null,
|
||||
reason: null,
|
||||
submittedAt,
|
||||
resolvedAt: null,
|
||||
...(acceptedSequence === undefined ? {} : { acceptedSequence })
|
||||
}
|
||||
}
|
||||
|
||||
function item(
|
||||
id: string,
|
||||
sequence: number,
|
||||
body: AgentJournalRenderItem['body'] = { kind: 'message', role: 'user', blocks: [] }
|
||||
): AgentJournalRenderItem {
|
||||
return { itemId: id, sequence, observedAt: 1, revision: 0, body }
|
||||
}
|
||||
|
||||
it('exports only visible rows and sends after the newest clear, across query pages', () => {
|
||||
const db = new Database(':memory:')
|
||||
databases.push(db)
|
||||
db.exec(journalSqlProjectionSchema())
|
||||
const scope = () => new JournalSqlScope(db, 'session', 'generation')
|
||||
const reducer = new JournalSqlReducer(scope(), 'epoch')
|
||||
const { state } = reducer
|
||||
const prompt = (id: string, sequence: number, submission: AgentJournalSubmission) => {
|
||||
state.submissions.set(id, submission)
|
||||
state.items.set(agentJournalSubmissionKey(id), item(agentJournalSubmissionKey(id), sequence))
|
||||
}
|
||||
prompt('before', 1, send('before', 1, 1))
|
||||
prompt('pending', 2, send('pending', 2))
|
||||
state.items.set(
|
||||
'clear',
|
||||
item('clear', 3, {
|
||||
kind: 'status',
|
||||
text: 'Cleared',
|
||||
contextClear: { operationId: 'clear', afterFence: 1, clearedAt: 1 }
|
||||
})
|
||||
)
|
||||
const tail = Array.from({ length: 300 }, (_, index) => `tail-${index}`)
|
||||
tail.forEach((id, index) => state.items.set(id, item(id, 4 + index)))
|
||||
prompt('after', 400, send('after', 3, 400))
|
||||
prompt('rejected', 401, send('rejected', 4, 401))
|
||||
state.inputs.rejections.set('rejected', send('rejected', 4, 401))
|
||||
reducer.flush()
|
||||
|
||||
const cleared = readJournalSqlContinuationContext(scope())
|
||||
expect(cleared.items.map((row) => row.itemId)).toEqual([...tail, 'orca:after'])
|
||||
expect(cleared.submissions.map((row) => row.clientMessageId)).toEqual(['after', 'rejected'])
|
||||
|
||||
state.items.delete('clear')
|
||||
reducer.flush()
|
||||
const whole = readJournalSqlContinuationContext(scope())
|
||||
expect(whole.items.map((row) => row.itemId)).toEqual([
|
||||
'orca:before',
|
||||
'orca:pending',
|
||||
...tail,
|
||||
'orca:after'
|
||||
])
|
||||
expect(whole.submissions.map((row) => row.clientMessageId)).toEqual([
|
||||
'before',
|
||||
'pending',
|
||||
'after',
|
||||
'rejected'
|
||||
])
|
||||
})
|
||||
@@ -1,60 +1,79 @@
|
||||
import type { AgentJournalRenderItem } from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import type Database from '../../sqlite/sync-database'
|
||||
import type {
|
||||
AgentJournalRenderItem,
|
||||
AgentJournalSubmission
|
||||
} from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import type { AgentJournalCursor } from '../../../shared/agent-session/journal/agent-session-journal-identity'
|
||||
import type { JournalContinuationContext } from './journal-reads'
|
||||
import { journalContextEpoch } from './context-epochs/journal-context-cursor'
|
||||
import { JournalSqlHistoryValues } from './journal-sql-history-values'
|
||||
import { JournalSqlScalars } from './journal-sql-scalars'
|
||||
import type { JournalSqlScope } from './journal-sql-scope'
|
||||
import type { SqliteBindings, SqliteRow } from '../../sqlite/sqlite-statement'
|
||||
|
||||
const PAGE = 256
|
||||
|
||||
/** The logical cursor of the ready head that owns this epoch; an unready or retired head has none. */
|
||||
export function journalDomainContextHead(
|
||||
db: Database.Database,
|
||||
target: { sessionId: string; epoch: string }
|
||||
): AgentJournalCursor {
|
||||
const head = db
|
||||
.prepare(`SELECT epoch, last_sequence, context_boundary FROM journal_chat_state
|
||||
WHERE session_id=?`)
|
||||
.get(target.sessionId)
|
||||
if (head?.epoch === null || head?.epoch === undefined || String(head.epoch) !== target.epoch) {
|
||||
throw new Error('journal item read targets a chat epoch that is not current')
|
||||
}
|
||||
return {
|
||||
epoch: journalContextEpoch(target.epoch, Number(head.context_boundary)),
|
||||
sequence: Number(head.last_sequence)
|
||||
}
|
||||
}
|
||||
|
||||
/** An explicit export: query chunks are bounded, the answer is the whole effective context. */
|
||||
export function readJournalSqlContinuationContext(
|
||||
scope: JournalSqlScope
|
||||
export function readJournalDomainContinuationContext(
|
||||
db: Database.Database,
|
||||
target: { sessionId: string; epoch: string }
|
||||
): JournalContinuationContext {
|
||||
const scalars = new JournalSqlScalars(scope, 'reducer')
|
||||
const history = new JournalSqlHistoryValues(scope.db, scope, { bodies: 0 })
|
||||
const prefix = [target.sessionId, target.epoch] as const
|
||||
const cursor = journalDomainContextHead(db, target)
|
||||
const clear = Number(
|
||||
scope.db
|
||||
.prepare(`SELECT MAX(sequence) AS sequence FROM journal_proj_items
|
||||
WHERE session_id=? AND epoch=? AND context_clear=1 AND hidden=0`)
|
||||
.get(...scope.prefix)?.sequence ?? 0
|
||||
db
|
||||
.prepare(`SELECT MAX(sequence) AS sequence FROM journal_items INDEXED BY journal_items_context_clear
|
||||
WHERE session_id=? AND epoch=? AND hidden=0 AND context_clear=1`)
|
||||
.get(...prefix)?.sequence ?? 0
|
||||
)
|
||||
const items: AgentJournalRenderItem[] = []
|
||||
let afterItem: SqliteBindings = []
|
||||
do {
|
||||
const rows = scope.db
|
||||
.prepare(`SELECT entry_key, incarnation, sequence, sequence_index, ordinal FROM journal_proj_items
|
||||
const rows = db
|
||||
.prepare(`SELECT payload_json, sequence, sequence_index, ordinal
|
||||
FROM journal_items INDEXED BY journal_items_visible_position
|
||||
WHERE session_id=? AND epoch=? AND hidden=0 AND sequence>?
|
||||
${afterItem.length ? 'AND (sequence, sequence_index, ordinal)>(?, ?, ?)' : ''}
|
||||
ORDER BY sequence, sequence_index, ordinal LIMIT ?`)
|
||||
.all(...scope.prefix, clear, ...afterItem, PAGE)
|
||||
.all(...prefix, clear, ...afterItem, PAGE)
|
||||
for (const row of rows) {
|
||||
items.push(history.item(scope.examined(row)))
|
||||
items.push(JSON.parse(String(row.payload_json)))
|
||||
}
|
||||
afterItem = nextPage(rows, ['sequence', 'sequence_index', 'ordinal'])
|
||||
} while (afterItem.length)
|
||||
// Unaccepted sends belong only to an uncleared context, matching the saved-prompt policy.
|
||||
const submissions: AgentJournalSubmission[] = []
|
||||
let afterSend: SqliteBindings = []
|
||||
do {
|
||||
const rows = scope.db
|
||||
.prepare(`SELECT item_key, submitted_at, input_ordinal, client_message_id FROM journal_proj_submissions
|
||||
WHERE session_id=? AND epoch=? AND current=1 AND item_key IS NOT NULL
|
||||
${clear > 0 ? 'AND accepted_seq>?' : ''}
|
||||
${afterSend.length ? 'AND (submitted_at, input_ordinal, client_message_id)>(?, ?, ?)' : ''}
|
||||
ORDER BY submitted_at, input_ordinal, client_message_id LIMIT ?`)
|
||||
.all(...scope.prefix, ...(clear > 0 ? [clear] : []), ...afterSend, PAGE)
|
||||
history.loadSubmissions(rows.map((row) => String(scope.examined(row).item_key)))
|
||||
afterSend = nextPage(rows, ['submitted_at', 'input_ordinal', 'client_message_id'])
|
||||
const rows = db
|
||||
.prepare(`SELECT payload_json, submitted_at, ordinal, message_id
|
||||
FROM journal_submission_attempts INDEXED BY journal_submission_order
|
||||
WHERE session_id=? AND epoch=? AND current=1
|
||||
${clear > 0 ? 'AND accepted_sequence>?' : ''}
|
||||
${afterSend.length ? 'AND (submitted_at, ordinal, message_id)>(?, ?, ?)' : ''}
|
||||
ORDER BY submitted_at, ordinal, message_id LIMIT ?`)
|
||||
.all(...prefix, ...(clear > 0 ? [clear] : []), ...afterSend, PAGE)
|
||||
for (const row of rows) {
|
||||
submissions.push(JSON.parse(String(row.payload_json)))
|
||||
}
|
||||
afterSend = nextPage(rows, ['submitted_at', 'ordinal', 'message_id'])
|
||||
} while (afterSend.length)
|
||||
return {
|
||||
cursor: {
|
||||
epoch: journalContextEpoch(scope.epoch, scalars.get('contextBoundary', 1)),
|
||||
sequence: scalars.get('lastSequence', 0)
|
||||
},
|
||||
items,
|
||||
submissions: [...history.submissions.values()]
|
||||
}
|
||||
return { cursor, items, submissions }
|
||||
}
|
||||
|
||||
/** The keyset after a full page; empty once a short page proves nothing follows. */
|
||||
|
||||
@@ -1,48 +1,35 @@
|
||||
import type { JournalSqlScope } from './journal-sql-scope'
|
||||
import type Database from '../../sqlite/sync-database'
|
||||
import { JOURNAL_HISTORY_ITEMS_LIMIT } from './journal-history-items'
|
||||
|
||||
/** Only item IDs cross the deterministic prompt lookup; historical bodies stay in SQLite. */
|
||||
export function* journalSqlUserItemIds(
|
||||
scope: JournalSqlScope,
|
||||
visible: (key: string) => boolean
|
||||
export function* journalDomainUserItemIds(
|
||||
db: Database.Database,
|
||||
prefix: readonly [string, string]
|
||||
): Iterable<string> {
|
||||
for (const row of scope.db
|
||||
.prepare(`SELECT entry_key FROM journal_proj_items
|
||||
WHERE session_id=? AND epoch=? AND kind='message' AND message_role='user' ORDER BY ordinal`)
|
||||
.iterate(...scope.prefix)) {
|
||||
scope.examined(row)
|
||||
const key = String(JSON.parse(String(row.entry_key)))
|
||||
if (visible(key)) {
|
||||
yield key
|
||||
}
|
||||
for (const row of db
|
||||
.prepare(`SELECT item_id FROM journal_items INDEXED BY journal_items_user_message
|
||||
WHERE session_id=? AND epoch=? AND hidden=0 AND kind='message' AND message_role='user'
|
||||
ORDER BY ordinal`)
|
||||
.iterate(...prefix)) {
|
||||
yield String(row.item_id)
|
||||
}
|
||||
}
|
||||
|
||||
/** Opener aliases and turn membership both have typed indexes. */
|
||||
export function journalSqlHistoryOpeners(scope: JournalSqlScope, itemId: string): string[] {
|
||||
const openers = [itemId]
|
||||
for (const row of scope.db
|
||||
.prepare(`SELECT alias FROM journal_proj_aliases
|
||||
WHERE session_id=? AND epoch=? AND target=? LIMIT ?`)
|
||||
.iterate(...scope.prefix, itemId, JOURNAL_HISTORY_ITEMS_LIMIT + 1)) {
|
||||
scope.examined(row)
|
||||
openers.push(String(row.alias))
|
||||
if (openers.length > JOURNAL_HISTORY_ITEMS_LIMIT) {
|
||||
throw new Error('history-workspace-too-large')
|
||||
}
|
||||
/** Turns a user item opened, directly or through a provider alias, in admission order. */
|
||||
export function journalDomainHistoryOpeners(
|
||||
db: Database.Database,
|
||||
prefix: readonly [string, string],
|
||||
itemId: string
|
||||
): string[] {
|
||||
const rows = db
|
||||
.prepare(`SELECT item_id FROM journal_items
|
||||
WHERE session_id=?1 AND epoch=?2 AND hidden=0 AND opener_item_id IN (
|
||||
SELECT ?3 UNION SELECT provider_item_id FROM journal_item_aliases
|
||||
WHERE session_id=?1 AND epoch=?2 AND item_id=?3)
|
||||
ORDER BY ordinal LIMIT ?4`)
|
||||
.all(...prefix, itemId, JOURNAL_HISTORY_ITEMS_LIMIT + 1)
|
||||
if (rows.length > JOURNAL_HISTORY_ITEMS_LIMIT) {
|
||||
throw new Error('history-workspace-too-large')
|
||||
}
|
||||
const turns = new Map<string, number>()
|
||||
for (const opener of openers) {
|
||||
for (const row of scope.db
|
||||
.prepare(`SELECT entry_key, ordinal FROM journal_proj_items
|
||||
WHERE session_id=? AND epoch=? AND opener_item_id=? ORDER BY ordinal LIMIT ?`)
|
||||
.iterate(...scope.prefix, opener, JOURNAL_HISTORY_ITEMS_LIMIT + 1)) {
|
||||
scope.examined(row)
|
||||
turns.set(String(JSON.parse(String(row.entry_key))), Number(row.ordinal))
|
||||
if (turns.size > JOURNAL_HISTORY_ITEMS_LIMIT) {
|
||||
throw new Error('history-workspace-too-large')
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...turns].sort((a, b) => a[1] - b[1]).map(([key]) => key)
|
||||
return rows.map((row) => String(row.item_id))
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type Database from '../../sqlite/sync-database'
|
||||
import {
|
||||
readJournalHistoryItems,
|
||||
readClaudeHistoryPrompts,
|
||||
@@ -5,7 +6,7 @@ import {
|
||||
type JournalHistoryReadOptions,
|
||||
type JournalHistoryPrompt
|
||||
} from './journal-history-items'
|
||||
import { journalSqlHistoryOpeners, journalSqlUserItemIds } from './journal-sql-history-items'
|
||||
import { journalDomainHistoryOpeners, journalDomainUserItemIds } from './journal-sql-history-items'
|
||||
import type {
|
||||
AgentJournalItemBody,
|
||||
AgentJournalRenderItem
|
||||
@@ -14,27 +15,27 @@ import type { AgentJournalCursor } from '../../../shared/agent-session/journal/a
|
||||
import type { AgentSessionContextUsage } from '../../../shared/agent-session/agent-session-context-usage'
|
||||
import { latestStructuredAgentContextFacts } from '../../../shared/agent-session/structured-agent-session-context-usage'
|
||||
import { runningStructuredAgentSessionTurnItemBySequence } from '../../../shared/agent-session/view/structured-agent-session-live-turn'
|
||||
import { readAgentJournalTurn } from '../../../shared/agent-session/lifecycle/agent-session-turn-record'
|
||||
import { isAgentSessionContextClear } from '../../../shared/agent-session/agent-session-context-clear'
|
||||
import {
|
||||
journalThreadGoalSource,
|
||||
type JournalThreadGoalSource
|
||||
} from './projection/journal-thread-goal-source'
|
||||
import type { JournalSqlScope } from './journal-sql-scope'
|
||||
import type {
|
||||
JournalContinuationContext,
|
||||
JournalMessageOptions,
|
||||
JournalNamedTurn
|
||||
} from './journal-reads'
|
||||
import { readJournalSqlContinuationContext } from './journal-sql-continuation-context'
|
||||
import { JournalSqlReadValues } from './journal-sql-read-values'
|
||||
import { readJournalSqlInput } from './journal-sql-input-reads'
|
||||
import { agentJournalSubmissionKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import { currentAgentSessionThreadGoalSourceBySequence } from '../../../shared/agent-session/agent-session-thread-goal'
|
||||
import type { ClaudeJournalSnapshot } from '../../claude/claude-subagent-journaled-identities'
|
||||
import { readJournalSqlClaudeIdentities } from './journal-sql-claude-identities'
|
||||
import {
|
||||
readJournalSqlLifecycle,
|
||||
type JournalSqlLifecycleRead,
|
||||
type JournalSqlLifecycleReadResult
|
||||
journalDomainContextHead,
|
||||
readJournalDomainContinuationContext
|
||||
} from './journal-sql-continuation-context'
|
||||
import { agentJournalSubmissionKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import type { ClaudeJournalSnapshot } from '../../claude/claude-subagent-journaled-identities'
|
||||
import { readJournalDomainClaudeIdentities } from './journal-sql-claude-identities'
|
||||
import type {
|
||||
JournalSqlLifecycleRead,
|
||||
JournalSqlLifecycleReadResult
|
||||
} from './journal-sql-lifecycle-reads'
|
||||
|
||||
/** Item reads by type and position; each names the rows it decodes, as projection reads do. */
|
||||
@@ -73,48 +74,51 @@ export type JournalSqlItemReadResult =
|
||||
| { kind: 'continuation-context'; context: JournalContinuationContext }
|
||||
| JournalSqlLifecycleReadResult
|
||||
|
||||
export type JournalSqlItemReadContext = {
|
||||
scope: JournalSqlScope
|
||||
item: (itemId: string) => AgentJournalRenderItem | undefined
|
||||
visible: (itemId: string) => boolean
|
||||
epoch: () => string
|
||||
}
|
||||
export type JournalDomainItemRead = Exclude<JournalSqlItemRead, JournalSqlLifecycleRead>
|
||||
export type JournalDomainItemReadResult = Exclude<
|
||||
JournalSqlItemReadResult,
|
||||
JournalSqlLifecycleReadResult
|
||||
>
|
||||
|
||||
const TURNS_NEWEST_FIRST = `SELECT entry_key, context_clear FROM journal_proj_items
|
||||
WHERE session_id=? AND epoch=? AND (turn_id IS NOT NULL OR context_clear=1)
|
||||
export type JournalDomainItemTarget = { sessionId: string; epoch: string }
|
||||
|
||||
/** Turns and clears, newest first; ties keep the later-admitted row, as an insertion-order fold does. */
|
||||
const TURNS_NEWEST_FIRST = `SELECT payload_json FROM journal_items INDEXED BY journal_items_turn_marker
|
||||
WHERE session_id=? AND epoch=? AND hidden=0 AND turn_marker=1
|
||||
ORDER BY sequence DESC, ordinal DESC`
|
||||
|
||||
export function readJournalSqlItems(
|
||||
context: JournalSqlItemReadContext,
|
||||
operation: JournalSqlItemRead
|
||||
): JournalSqlItemReadResult {
|
||||
const { scope } = context
|
||||
/** Runs on the caller's open reader snapshot; it never writes, waits or caches. */
|
||||
export function readJournalDomainItems(
|
||||
db: Database.Database,
|
||||
target: JournalDomainItemTarget,
|
||||
operation: JournalDomainItemRead
|
||||
): JournalDomainItemReadResult {
|
||||
const prefix = [target.sessionId, target.epoch] as const
|
||||
switch (operation.kind) {
|
||||
case 'canonical-item-ids': {
|
||||
const values = new JournalSqlReadValues(scope, () => {})
|
||||
const canonical = canonicalItemId(db, prefix)
|
||||
return {
|
||||
kind: 'canonical-item-ids',
|
||||
items: operation.itemIds.map((itemId) => ({
|
||||
itemId,
|
||||
canonicalItemId: values.get<string>('aliases', itemId) ?? itemId
|
||||
}))
|
||||
items: operation.itemIds.map((itemId) => ({ itemId, canonicalItemId: canonical(itemId) }))
|
||||
}
|
||||
}
|
||||
case 'history-items': {
|
||||
const values = new JournalSqlReadValues(scope, () => {})
|
||||
const canonical = (key: string) => values.get<string>('aliases', key) ?? key
|
||||
const canonical = canonicalItemId(db, prefix)
|
||||
const removed = db.prepare(`SELECT
|
||||
EXISTS(SELECT 1 FROM journal_item_tombstones WHERE session_id=?1 AND epoch=?2 AND item_id=?3)
|
||||
OR EXISTS(SELECT 1 FROM journal_items WHERE session_id=?1 AND epoch=?2 AND item_id=?3 AND hidden=1)
|
||||
AS removed`)
|
||||
return {
|
||||
kind: 'history-items',
|
||||
items: readJournalHistoryItems(
|
||||
{
|
||||
canonicalItemId: canonical,
|
||||
item: (key) => (context.visible(key) ? (context.item(key) ?? null) : null),
|
||||
presentationRemoved: (key) => {
|
||||
const itemId = canonical(key)
|
||||
return values.has('tombstones', itemId) || !context.visible(itemId)
|
||||
},
|
||||
item: (itemId) => visibleItem(db, prefix, itemId),
|
||||
presentationRemoved: (key) => Boolean(removed.get(...prefix, canonical(key))!.removed),
|
||||
...(operation.options?.includeOpeners
|
||||
? { turnsOpenedBy: (key: string) => journalSqlHistoryOpeners(scope, key) }
|
||||
? {
|
||||
turnsOpenedBy: (itemId: string) => journalDomainHistoryOpeners(db, prefix, itemId)
|
||||
}
|
||||
: {})
|
||||
},
|
||||
operation.itemIds
|
||||
@@ -125,136 +129,177 @@ export function readJournalSqlItems(
|
||||
return {
|
||||
kind: 'claude-history-prompts',
|
||||
prompts: readClaudeHistoryPrompts(
|
||||
journalSqlUserItemIds(scope, context.visible),
|
||||
journalDomainUserItemIds(db, prefix),
|
||||
operation.sessionId,
|
||||
operation.uuids
|
||||
)
|
||||
}
|
||||
case 'continuation-context':
|
||||
return { kind: 'continuation-context', context: readJournalSqlContinuationContext(scope) }
|
||||
case 'message-options': {
|
||||
const itemId = agentJournalSubmissionKey(operation.clientMessageId)
|
||||
const body = context.visible(itemId) ? context.item(itemId)?.body : undefined
|
||||
const newest = readJournalSqlInput(scope, { kind: 'newest-turn' })
|
||||
if (newest.kind !== 'newest-turn') {
|
||||
throw new Error('journal newest turn read returned a different answer')
|
||||
return {
|
||||
kind: 'continuation-context',
|
||||
context: readJournalDomainContinuationContext(db, target)
|
||||
}
|
||||
case 'message-options': {
|
||||
const body = visibleItem(
|
||||
db,
|
||||
prefix,
|
||||
agentJournalSubmissionKey(operation.clientMessageId)
|
||||
)?.body
|
||||
return {
|
||||
kind: 'message-options',
|
||||
options: {
|
||||
ordinaryMessage: body?.kind === 'message' && !body.command,
|
||||
runningTurn: newest.turn?.state === 'running'
|
||||
runningTurn:
|
||||
readAgentJournalTurn(newestTurnOrClear(db, prefix)?.body)?.state === 'running'
|
||||
}
|
||||
}
|
||||
}
|
||||
case 'named-turn': {
|
||||
const row = scope.db
|
||||
.prepare(`SELECT entry_key FROM journal_proj_items
|
||||
const row = db
|
||||
.prepare(`SELECT item_id FROM journal_items INDEXED BY journal_items_named_turn
|
||||
WHERE session_id=? AND epoch=? AND turn_id=? AND hidden=0
|
||||
ORDER BY sequence DESC, sequence_index DESC, ordinal DESC LIMIT 1`)
|
||||
.get(...scope.prefix, operation.turnId)
|
||||
if (row) {
|
||||
scope.examined(row)
|
||||
}
|
||||
.get(...prefix, operation.turnId)
|
||||
return {
|
||||
kind: 'named-turn',
|
||||
turn: {
|
||||
scope: row ? { kind: 'turn', turnItemId: entryItemId(row) } : null,
|
||||
removed: new JournalSqlReadValues(scope, () => {}).has('removedTurnIds', operation.turnId)
|
||||
scope: row ? { kind: 'turn', turnItemId: String(row.item_id) } : null,
|
||||
removed: Boolean(
|
||||
db
|
||||
.prepare(`SELECT 1 FROM journal_item_tombstones
|
||||
WHERE session_id=? AND epoch=? AND turn_id=? LIMIT 1`)
|
||||
.get(...prefix, operation.turnId)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
case 'items-by-kind': {
|
||||
const kinds = [...new Set(operation.kinds)]
|
||||
const rows = kinds.length
|
||||
? scope.db
|
||||
.prepare(`SELECT entry_key, ordinal FROM journal_proj_items
|
||||
WHERE session_id=? AND epoch=? AND kind IN (${kinds.map(() => '?').join(',')})
|
||||
? db
|
||||
.prepare(`SELECT payload_json, ordinal FROM journal_items INDEXED BY journal_items_kind
|
||||
WHERE session_id=? AND epoch=? AND hidden=0 AND kind IN (${kinds.map(() => '?').join(',')})
|
||||
AND ordinal>? ORDER BY ordinal LIMIT ?`)
|
||||
.all(...scope.prefix, ...kinds, operation.afterOrdinal, operation.limit + 1)
|
||||
.all(...prefix, ...kinds, operation.afterOrdinal, operation.limit + 1)
|
||||
: []
|
||||
const page = rows.slice(0, operation.limit)
|
||||
const items: AgentJournalRenderItem[] = []
|
||||
for (const row of page) {
|
||||
scope.examined(row)
|
||||
const itemId = entryItemId(row)
|
||||
const item = context.visible(itemId) ? context.item(itemId) : undefined
|
||||
if (item) {
|
||||
items.push(item)
|
||||
}
|
||||
}
|
||||
return {
|
||||
kind: 'items-by-kind',
|
||||
items,
|
||||
items: page.map(parseItem),
|
||||
nextOrdinal: rows.length > operation.limit ? Number(page.at(-1)!.ordinal) : null
|
||||
}
|
||||
}
|
||||
case 'context-floor': {
|
||||
const row = scope.db
|
||||
.prepare(`SELECT sequence FROM journal_proj_items
|
||||
WHERE session_id=? AND epoch=? AND context_clear=1 ORDER BY sequence DESC LIMIT 1`)
|
||||
.get(...scope.prefix)
|
||||
const row = db
|
||||
.prepare(`SELECT sequence FROM journal_items INDEXED BY journal_items_context_clear
|
||||
WHERE session_id=? AND epoch=? AND hidden=0 AND context_clear=1 ORDER BY sequence DESC LIMIT 1`)
|
||||
.get(...prefix)
|
||||
return {
|
||||
kind: 'context-floor',
|
||||
floor: row ? { epoch: context.epoch(), sequence: Number(row.sequence) } : null
|
||||
floor: row
|
||||
? { epoch: journalDomainContextHead(db, target).epoch, sequence: Number(row.sequence) }
|
||||
: null
|
||||
}
|
||||
}
|
||||
case 'running-turn': {
|
||||
const row = scope.db.prepare(`${TURNS_NEWEST_FIRST} LIMIT 1`).get(...scope.prefix)
|
||||
const item = row ? context.item(entryItemId(row)) : undefined
|
||||
const row = db.prepare(`${TURNS_NEWEST_FIRST} LIMIT 1`).get(...prefix)
|
||||
return {
|
||||
kind: 'running-turn',
|
||||
running: item ? runningStructuredAgentSessionTurnItemBySequence([item]) : null
|
||||
running: row ? runningStructuredAgentSessionTurnItemBySequence([parseItem(row)]) : null
|
||||
}
|
||||
}
|
||||
case 'context-usage': {
|
||||
// Facts before the newest clear never count, so the walk stops there.
|
||||
const turns: AgentJournalRenderItem[] = []
|
||||
for (const row of scope.db.prepare(TURNS_NEWEST_FIRST).iterate(...scope.prefix)) {
|
||||
scope.examined(row)
|
||||
const item = context.item(entryItemId(row))
|
||||
if (item) {
|
||||
turns.push(item)
|
||||
}
|
||||
if (Number(row.context_clear) === 1) {
|
||||
break
|
||||
}
|
||||
}
|
||||
return { kind: 'context-usage', usage: latestStructuredAgentContextFacts(turns.toReversed()) }
|
||||
}
|
||||
case 'context-usage':
|
||||
return { kind: 'context-usage', usage: readContextUsage(db, prefix) }
|
||||
case 'claude-snapshot':
|
||||
return {
|
||||
kind: 'claude-snapshot',
|
||||
snapshot: { ...readJournalSqlClaudeIdentities(scope), threadGoal: readThreadGoal(context) }
|
||||
snapshot: {
|
||||
...readJournalDomainClaudeIdentities(db, prefix),
|
||||
threadGoal: readThreadGoal(db, prefix)
|
||||
}
|
||||
}
|
||||
case 'thread-goal-source':
|
||||
return { kind: 'thread-goal-source', source: readThreadGoal(context) }
|
||||
case 'latest-prompt':
|
||||
case 'restart-progress':
|
||||
case 'outgrown-child':
|
||||
return readJournalSqlLifecycle(context, operation)
|
||||
return { kind: 'thread-goal-source', source: readThreadGoal(db, prefix) }
|
||||
}
|
||||
}
|
||||
|
||||
/** The newest transition wins; on equal sequence the earlier-written row, as a fold scan keeps it. */
|
||||
function readThreadGoal(context: JournalSqlItemReadContext): JournalThreadGoalSource {
|
||||
const { scope } = context
|
||||
const rows = scope.db
|
||||
.prepare(`SELECT entry_key FROM journal_proj_items
|
||||
WHERE session_id=? AND epoch=? AND ((kind='status' AND root=1) OR context_clear=1)
|
||||
ORDER BY sequence DESC, ordinal ASC`)
|
||||
.iterate(...scope.prefix)
|
||||
for (const row of rows) {
|
||||
scope.examined(row)
|
||||
const item = context.item(entryItemId(row))
|
||||
if (item && currentAgentSessionThreadGoalSourceBySequence([item])) {
|
||||
return journalThreadGoalSource([item])
|
||||
type Prefix = readonly [string, string]
|
||||
|
||||
function canonicalItemId(db: Database.Database, prefix: Prefix): (key: string) => string {
|
||||
const alias = db.prepare(`SELECT item_id FROM journal_item_aliases
|
||||
WHERE session_id=? AND epoch=? AND provider_item_id=?`)
|
||||
return (key) => {
|
||||
const row = alias.get(...prefix, key)
|
||||
return row ? String(row.item_id) : key
|
||||
}
|
||||
}
|
||||
|
||||
function visibleItem(
|
||||
db: Database.Database,
|
||||
prefix: Prefix,
|
||||
itemId: string
|
||||
): AgentJournalRenderItem | null {
|
||||
const row = db
|
||||
.prepare(`SELECT payload_json FROM journal_items
|
||||
WHERE session_id=? AND epoch=? AND item_id=? AND hidden=0`)
|
||||
.get(...prefix, itemId)
|
||||
return row ? parseItem(row) : null
|
||||
}
|
||||
|
||||
/** The input order's newest turn: latest position, then the greatest item ID among ties. */
|
||||
function newestTurnOrClear(db: Database.Database, prefix: Prefix): AgentJournalRenderItem | null {
|
||||
let newest: AgentJournalRenderItem | null = null
|
||||
for (const row of db
|
||||
.prepare(`SELECT payload_json FROM journal_items INDEXED BY journal_items_turn_marker
|
||||
WHERE session_id=? AND epoch=? AND hidden=0 AND turn_marker=1
|
||||
ORDER BY sequence DESC, sequence_index DESC`)
|
||||
.iterate(...prefix)) {
|
||||
const item = parseItem(row)
|
||||
if (
|
||||
newest &&
|
||||
(item.sequence !== newest.sequence ||
|
||||
(item.sequenceIndex ?? 0) !== (newest.sequenceIndex ?? 0))
|
||||
) {
|
||||
break
|
||||
}
|
||||
if (!newest || item.itemId.localeCompare(newest.itemId) > 0) {
|
||||
newest = item
|
||||
}
|
||||
}
|
||||
return journalThreadGoalSource([])
|
||||
return newest
|
||||
}
|
||||
|
||||
/** Item rows key by the JSON-encoded item id. */
|
||||
function entryItemId(row: Record<string, unknown>): string {
|
||||
return String(JSON.parse(String(row.entry_key)))
|
||||
/** Walks back to the newest clear, stopping early once older rows can no longer change either fact. */
|
||||
function readContextUsage(db: Database.Database, prefix: Prefix): AgentSessionContextUsage {
|
||||
const turns: AgentJournalRenderItem[] = []
|
||||
let used: number | null = null
|
||||
let window: number | null = null
|
||||
for (const row of db.prepare(TURNS_NEWEST_FIRST).iterate(...prefix)) {
|
||||
const item = parseItem(row)
|
||||
if (used !== null && window !== null && item.sequence < Math.min(used, window)) {
|
||||
break
|
||||
}
|
||||
turns.push(item)
|
||||
if (isAgentSessionContextClear(item.body)) {
|
||||
break
|
||||
}
|
||||
const facts = readAgentJournalTurn(item.body)?.contextUsage
|
||||
used ??= facts?.used ? item.sequence : null
|
||||
window ??= facts?.window ? item.sequence : null
|
||||
}
|
||||
return latestStructuredAgentContextFacts(turns.toReversed())
|
||||
}
|
||||
|
||||
/** The newest transition wins; on equal sequence the earlier-admitted row, as a fold scan keeps it. */
|
||||
function readThreadGoal(db: Database.Database, prefix: Prefix): JournalThreadGoalSource {
|
||||
const row = db
|
||||
.prepare(`SELECT payload_json FROM journal_items INDEXED BY journal_items_goal_transition
|
||||
WHERE session_id=? AND epoch=? AND hidden=0 AND goal_transition=1
|
||||
ORDER BY sequence DESC, ordinal ASC LIMIT 1`)
|
||||
.get(...prefix)
|
||||
return journalThreadGoalSource(row ? [parseItem(row)] : [])
|
||||
}
|
||||
|
||||
function parseItem(row: Record<string, unknown>): AgentJournalRenderItem {
|
||||
return JSON.parse(String(row.payload_json))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user