mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 10:58:10 +00:00
Read rewind admission from one SQL snapshot
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
import { afterEach, expect, it } from 'vitest'
|
||||
import {
|
||||
domainLifecycleFixture,
|
||||
lifecycleIdentity as identity,
|
||||
lifecycleOptions as options
|
||||
} from './journal-domain-lifecycle.test-fixture'
|
||||
import { journalSqlReads } from './journal-sql-reads'
|
||||
import { readJournalSqlPoint } from './journal-sql-point-read'
|
||||
import { rewindRefusalBehindClear } from '../agent-session-wire/rewind/structured-rewind-refusal'
|
||||
import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
|
||||
const cleanup: (() => void)[] = []
|
||||
afterEach(() => cleanup.splice(0).forEach((close) => close()))
|
||||
const prompt: AgentJournalMessageItem = {
|
||||
kind: 'message',
|
||||
role: 'user',
|
||||
blocks: [{ type: 'text', text: 'Request' }]
|
||||
}
|
||||
|
||||
it('admits only the containing turn opener and refuses cleared history', async () => {
|
||||
const f = domainLifecycleFixture(cleanup)
|
||||
const reads = journalSqlReads(
|
||||
{ point: async (request) => readJournalSqlPoint(f.db, request) },
|
||||
'chat'
|
||||
)
|
||||
await f.run({ kind: 'item', identity: identity('old'), body: prompt, options })
|
||||
await f.run({
|
||||
kind: 'item',
|
||||
identity: identity('clear'),
|
||||
body: {
|
||||
kind: 'status',
|
||||
text: 'Cleared',
|
||||
contextClear: { operationId: 'clear', afterFence: 1, clearedAt: 1 }
|
||||
},
|
||||
options
|
||||
})
|
||||
await f.run({
|
||||
kind: 'item',
|
||||
identity: identity('turn'),
|
||||
body: { kind: 'turn', turnId: 'turn', userItemId: 'orca:opener', state: 'completed' },
|
||||
options
|
||||
})
|
||||
for (const id of ['opener', 'steer']) {
|
||||
await f.run({
|
||||
kind: 'item',
|
||||
identity: identity(id),
|
||||
body: prompt,
|
||||
options: { fence: 1, turnScope: { kind: 'turn', turnItemId: 'orca:turn' } }
|
||||
})
|
||||
}
|
||||
const selected = await reads.rewindTarget('orca:opener')
|
||||
expect(selected).toMatchObject({ eligible: true, floor: { sequence: 2 } })
|
||||
expect((await reads.rewindTarget('orca:steer')).eligible).toBe(false)
|
||||
expect((await reads.rewindTarget('orca:old')).eligible).toBe(false)
|
||||
expect((await reads.rewindTarget('orca:missing')).eligible).toBe(false)
|
||||
const target = { itemId: 'orca:old', expectedEpoch: selected.cursor.epoch }
|
||||
expect(await rewindRefusalBehindClear({ reads }, target)).toMatchObject({ ok: false })
|
||||
expect(await rewindRefusalBehindClear({ reads }, { ...target, itemId: 'orca:opener' })).toBeNull()
|
||||
expect(
|
||||
await rewindRefusalBehindClear({ reads }, { ...target, expectedEpoch: 'retired' })
|
||||
).toMatchObject({ refusal: { rewindReason: 'stale-epoch' } })
|
||||
})
|
||||
@@ -0,0 +1,53 @@
|
||||
import { isAgentSessionRewindTarget } from '../../../shared/agent-session/lifecycle/agent-session-rewind'
|
||||
import { readAgentJournalTurn } from '../../../shared/agent-session/lifecycle/agent-session-turn-record'
|
||||
import type { AgentJournalRenderItem } from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import type { AgentJournalCursor } from '../../../shared/agent-session/journal/agent-session-journal-identity'
|
||||
import { journalContextEpoch } from './context-epochs/journal-context-cursor'
|
||||
import type { JournalSqlScope } from './journal-sql-scope'
|
||||
|
||||
export type JournalRewindTarget = {
|
||||
cursor: AgentJournalCursor
|
||||
floor: AgentJournalCursor | null
|
||||
sequence: number | null
|
||||
eligible: boolean
|
||||
}
|
||||
|
||||
/** Admission reads the target, its containing turn and the clear floor in one snapshot. */
|
||||
export function readJournalDomainRewindTarget(
|
||||
scope: JournalSqlScope,
|
||||
itemId: string
|
||||
): JournalRewindTarget {
|
||||
const head = scope.db
|
||||
.prepare(`SELECT last_sequence,context_boundary FROM journal_chat_state
|
||||
WHERE session_id=? AND epoch=?`)
|
||||
.get(...scope.prefix)!
|
||||
scope.examined(head)
|
||||
const epoch = journalContextEpoch(scope.epoch, Number(head.context_boundary))
|
||||
const cleared = scope.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(...scope.prefix)
|
||||
const floor = cleared ? { epoch, sequence: Number(scope.examined(cleared).sequence) } : null
|
||||
const item = (key: string): AgentJournalRenderItem | undefined => {
|
||||
const row = scope.db
|
||||
.prepare(`SELECT payload_json FROM journal_items
|
||||
WHERE session_id=? AND epoch=? AND item_id=? AND hidden=0`)
|
||||
.get(...scope.prefix, key)
|
||||
return row ? scope.decode<AgentJournalRenderItem>(scope.examined(row).payload_json) : undefined
|
||||
}
|
||||
const selected = item(itemId)
|
||||
return {
|
||||
cursor: { epoch, sequence: Number(head.last_sequence) },
|
||||
floor,
|
||||
sequence: selected?.sequence ?? null,
|
||||
eligible: Boolean(
|
||||
selected &&
|
||||
(!floor || selected.sequence > floor.sequence) &&
|
||||
isAgentSessionRewindTarget(
|
||||
selected,
|
||||
(turnItemId) => readAgentJournalTurn(item(turnItemId)?.body)?.userItemId
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,10 @@ import {
|
||||
type JournalConsumerRead,
|
||||
type JournalConsumerReadResult
|
||||
} from './journal-domain-consumer-reads'
|
||||
import {
|
||||
readJournalDomainRewindTarget,
|
||||
type JournalRewindTarget
|
||||
} from './journal-domain-rewind-target'
|
||||
import {
|
||||
readJournalGeneration,
|
||||
type JournalGenerationRead,
|
||||
@@ -61,6 +65,7 @@ import {
|
||||
export type JournalSqlPointRead = {
|
||||
sessionId: string
|
||||
operation:
|
||||
| { kind: 'rewind-target'; itemId: string }
|
||||
| { kind: 'history-source-items'; clientMessageIds: readonly string[] }
|
||||
| { kind: 'provider-turn-in-namespace'; namespace: string }
|
||||
| { kind: 'saved-item-ids'; itemIds: readonly string[] }
|
||||
@@ -93,6 +98,7 @@ export type JournalSqlPointRead = {
|
||||
}
|
||||
|
||||
export type JournalSqlPointReadResult =
|
||||
| { kind: 'rewind-target'; target: JournalRewindTarget }
|
||||
| { kind: 'history-source-items'; items: AgentJournalRenderItem[] }
|
||||
| { kind: 'provider-turn-in-namespace'; present: boolean }
|
||||
| { kind: 'saved-item-ids'; itemIds: string[] }
|
||||
@@ -148,6 +154,11 @@ function read(
|
||||
operation: JournalSqlPointRead['operation']
|
||||
): JournalSqlPointReadResult {
|
||||
switch (operation.kind) {
|
||||
case 'rewind-target':
|
||||
return {
|
||||
kind: operation.kind,
|
||||
target: readJournalDomainRewindTarget(scope, operation.itemId)
|
||||
}
|
||||
case 'naming-prompt':
|
||||
case 'automation-run':
|
||||
return readJournalDomainConsumer(scope, operation)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { JournalGenerationRead, JournalGenerationResult } from './journal-generation-read'
|
||||
import type { JournalRewindTarget } from './journal-domain-rewind-target'
|
||||
import type { JournalObserverRead, JournalObserverResult } from './journal-observer-read'
|
||||
import type { JournalSqlWorkRead, JournalSqlWorkResult } from './journal-work-read'
|
||||
import type { AgentSessionJournalReads } from './journal-reads'
|
||||
@@ -18,6 +19,7 @@ import type {
|
||||
} from './journal-input-reads'
|
||||
|
||||
export type JournalSqlReads = AgentSessionJournalReads & {
|
||||
rewindTarget(itemId: string): Promise<JournalRewindTarget>
|
||||
namingPrompt(hostStartedAt?: number): Promise<string>
|
||||
automationRun(messageId: string, inputIds: readonly string[]): Promise<AgentJournalSnapshot>
|
||||
historySourceItems(clientMessageIds: readonly string[]): Promise<AgentJournalRenderItem[]>
|
||||
@@ -84,6 +86,7 @@ export function journalSqlReads(
|
||||
const provenance = async (itemId: string) =>
|
||||
(await read({ kind: 'item-provenance', itemId })).provenance
|
||||
return {
|
||||
rewindTarget: async (itemId) => (await read({ kind: 'rewind-target', itemId })).target,
|
||||
namingPrompt: async (hostStartedAt) =>
|
||||
(await read({ kind: 'naming-prompt', hostStartedAt })).prompt,
|
||||
automationRun: async (messageId, inputIds) =>
|
||||
|
||||
+7
-2
@@ -64,7 +64,12 @@ export async function runWithReadyStructuredAgentSessionOperation<T>(
|
||||
plan: ReadyOperationPlan<T>,
|
||||
run: (selection: ReadyOperationSelection) => Promise<AgentSessionMutationResult<T>>,
|
||||
options: {
|
||||
beforeAgent?: (row: AgentSessionRecord | null) => AgentSessionMutationSessionPreparation | null
|
||||
beforeAgent?: (
|
||||
row: AgentSessionRecord | null
|
||||
) =>
|
||||
| AgentSessionMutationSessionPreparation
|
||||
| null
|
||||
| Promise<AgentSessionMutationSessionPreparation | null>
|
||||
goal?: boolean
|
||||
needsAgent?: (record: AgentSessionRecord | null) => boolean
|
||||
} = {}
|
||||
@@ -186,7 +191,7 @@ export async function runWithReadyStructuredAgentSessionOperation<T>(
|
||||
return opened
|
||||
}
|
||||
const current = context.deps.store.requireWritableRecord(envelope.sessionId)
|
||||
const checked = options.beforeAgent?.(current)
|
||||
const checked = await options.beforeAgent?.(current)
|
||||
if (checked && !checked.ok) {
|
||||
return checked
|
||||
}
|
||||
|
||||
@@ -109,7 +109,7 @@ export async function rewindStructuredAgentSession(
|
||||
if (ctx.journal.cursor().epoch !== params.expectedEpoch) {
|
||||
return rewindRefusal('stale-epoch')
|
||||
}
|
||||
if (!isStructuredRewindTarget(ctx.journal, params.itemId)) {
|
||||
if (!(await isStructuredRewindTarget(ctx.journal, params.itemId))) {
|
||||
return rewindRefusal('invalid-target')
|
||||
}
|
||||
const head = agentSessionProviderHandleChainHead(record.providerHandleChain)?.handle
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import {
|
||||
savedRewindKeys,
|
||||
isAgentSessionRewindTarget
|
||||
} from '../../../../shared/agent-session/lifecycle/agent-session-rewind'
|
||||
import { savedRewindKeys } from '../../../../shared/agent-session/lifecycle/agent-session-rewind'
|
||||
import { readAgentJournalTurn } from '../../../../shared/agent-session/lifecycle/agent-session-turn-record'
|
||||
import { agentJournalLinkageFields } from '../../../../shared/agent-session/journal/agent-session-journal-producer'
|
||||
import { parseAgentJournalItemKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
@@ -86,15 +83,11 @@ export function structuredRewindCut(
|
||||
}
|
||||
|
||||
/** Admission only; already-saved rewinds complete even if their target is no longer eligible. */
|
||||
export function isStructuredRewindTarget(journal: AgentSessionJournal, itemId: string): boolean {
|
||||
const item = journal.currentRead().items.find((row) => row.itemId === itemId)
|
||||
return (
|
||||
item !== undefined &&
|
||||
isAgentSessionRewindTarget(
|
||||
item,
|
||||
(turnItemId) => readAgentJournalTurn(journal.itemBody(turnItemId) ?? undefined)?.userItemId
|
||||
)
|
||||
)
|
||||
export async function isStructuredRewindTarget(
|
||||
journal: AgentSessionJournal,
|
||||
itemId: string
|
||||
): Promise<boolean> {
|
||||
return (await journal.reads.rewindTarget(itemId)).eligible
|
||||
}
|
||||
|
||||
function scopedTurn(item: AgentJournalRenderItem): string | undefined {
|
||||
|
||||
@@ -34,17 +34,21 @@ export function rewindRefusal(reason: AgentSessionRewindReason): {
|
||||
}
|
||||
|
||||
/** Refuse pre-/clear targets or moved epochs before starting an agent. */
|
||||
export function rewindRefusalBehindClear(
|
||||
journal: Pick<AgentSessionJournal, 'context' | 'cursor' | 'itemsRead'> | undefined,
|
||||
export async function rewindRefusalBehindClear(
|
||||
journal: Pick<AgentSessionJournal, 'reads'> | undefined,
|
||||
target: Pick<AgentSessionRewindParams, 'itemId' | 'expectedEpoch'>
|
||||
): ReturnType<typeof rewindRefusal> | null {
|
||||
const floor = journal?.context.floor()
|
||||
if (!journal || !floor) {
|
||||
): Promise<ReturnType<typeof rewindRefusal> | null> {
|
||||
if (!journal) {
|
||||
return null
|
||||
}
|
||||
if (journal.cursor().epoch !== target.expectedEpoch) {
|
||||
const selected = await journal.reads.rewindTarget(target.itemId)
|
||||
if (!selected.floor) {
|
||||
return null
|
||||
}
|
||||
if (selected.cursor.epoch !== target.expectedEpoch) {
|
||||
return rewindRefusal('stale-epoch')
|
||||
}
|
||||
const item = journal.itemsRead().items.find((entry) => entry.itemId === target.itemId)
|
||||
return !item || item.sequence <= floor.sequence ? rewindRefusal('invalid-target') : null
|
||||
return selected.sequence !== null && selected.sequence > selected.floor.sequence
|
||||
? null
|
||||
: rewindRefusal('invalid-target')
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user