Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
} from '../../../shared/agent-session-journal-item-key'
import { structuredAgentSessionPayloadFingerprint } from '../../../shared/structured-agent-session-mutation'
import { journalItemRevisionIsStale } from './journal-item-revision'
import { journalRowDatesSession } from './journal-session-clock'
import type { JournalRow } from './journal-row-schema'
import { dispatchRejectionWasTransportWriteFailure } from '../../../shared/structured-agent-session-dispatch-rejection'

Expand All @@ -29,6 +30,7 @@ export type JournalReducerState = {
sessionId: string
epoch: string
lastSequence: number
/** Newest `ts` among the session's own rows, not its subagents'. */
lastActivityAt: number
/** Lowest sequence still individually replayable; rows below it were compacted. */
oldestSequence: number
Expand Down Expand Up @@ -67,7 +69,9 @@ export function applyJournalRow(state: JournalReducerState, row: JournalRow): vo
if (row.kind === 'epoch') {
return
}
state.lastActivityAt = Math.max(state.lastActivityAt, row.ts)
if (journalRowDatesSession(state, row)) {
state.lastActivityAt = Math.max(state.lastActivityAt, row.ts)
}
if (row.kind === 'item') {
if (journalItemRevisionIsStale(state, row.itemId, row.revision)) {
return
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import type {
AgentJournalItemBody,
AgentJournalProducerLinkage
} from '../../../shared/agent-session-journal-types'
import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key'
import type { NativeChatSubagentEntry } from '../../../shared/native-chat-types'
import {
claudeBackgroundTaskBody,
claudeBackgroundTaskIdentity
} from '../../claude/claude-background-task-row-journal'
import {
codexSubagentGroupBody,
codexSubagentGroupIdentity
} from '../../codex/codex-subagent-roster'
import {
applyJournalRow,
createJournalReducerState,
type JournalReducerState
} from './journal-reducer'
import type { JournalRow } from './journal-row-schema'
import { createTrackedJournalOpener } from './journal-store-test-open'

const EPOCH = 'epoch-1'
const GROUP_ID = 'thread-1:turn-1'
const ROSTER_ITEM = agentJournalItemKey(codexSubagentGroupIdentity(GROUP_ID))
const CHILD = { agentId: 'task-1', producerKind: 'agent' } as const

function text(value: string): AgentJournalItemBody {
return { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: value }] }
}

function roster(state: NativeChatSubagentEntry['state']): AgentJournalItemBody {
return codexSubagentGroupBody(GROUP_ID, [{ id: 'a', label: 'review', state, startedAt: 1 }])
}

/** Row `seq` lands at `ts = 1_000 + seq`, so every row is newer than the last. */
function base(seq: number, linkage: AgentJournalProducerLinkage = {}) {
return { v: 1, epoch: EPOCH, seq, fence: 1, ts: 1_000 + seq, ...linkage }
}

function item(seq: number, itemId: string, body: AgentJournalItemBody, linkage = {}): JournalRow {
return { kind: 'item', itemId, revision: seq, body, ...base(seq, linkage) }
}

function fold(rows: JournalRow[]): JournalReducerState {
const state = createJournalReducerState('session-1', EPOCH)
for (const row of rows) {
applyJournalRow(state, row)
}
return state
}

describe("the session's clock counts only its own agent's rows", () => {
it.each([
['claude', 'claude:claude-session:child-1'],
['codex', 'codex:thread-child:child-turn:0']
])("holds on a %s subagent's rows, and resumes on the session's next own row", (_, childItem) => {
const own = item(1, 'own-1', text('delegating'))
const child = [
item(2, childItem, text('reading'), CHILD),
item(3, childItem, text('still reading'), CHILD)
]
const held = fold([own, ...child])
// Ordering still counts every row; only the clock is the session's.
expect(held.lastSequence).toBe(3)
expect(held.lastActivityAt).toBe(own.ts)

const resumed = fold([own, ...child, item(4, 'own-2', text('done'))])
expect(resumed.lastActivityAt).toBe(1_004)
})

it("holds on a subagent's lifecycle batch, and moves on the session's own", () => {
const batch = (seq: number, linkage = {}): JournalRow => ({
kind: 'lifecycle-batch',
settlementId: `settle-${seq}`,
mutations: [{ kind: 'item', itemId: `i-${seq}`, revision: 1, body: text('settled') }],
...base(seq, linkage)
})
expect(fold([batch(1, CHILD)]).lastActivityAt).toBe(0)
expect(fold([batch(1)]).lastActivityAt).toBe(1_001)
})

it('holds on every revision of a subagent roster, which the session writes about its children', () => {
const own = item(1, 'own-1', text('delegating'))
const state = fold([
own,
item(2, ROSTER_ITEM, roster('working')),
item(3, ROSTER_ITEM, roster('completed'))
])
expect(state.lastSequence).toBe(3)
expect(state.lastActivityAt).toBe(own.ts)
})

it("holds on a roster's removal, and moves on the removal of the session's own row", () => {
const own = item(1, 'own-1', text('delegating'))
const rosterRow = item(2, ROSTER_ITEM, roster('working'))
const tombstone = (seq: number, itemId: string): JournalRow => ({
kind: 'tombstone',
itemId,
revision: seq,
...base(seq)
})
expect(fold([own, rosterRow, tombstone(3, ROSTER_ITEM)]).lastActivityAt).toBe(own.ts)
expect(fold([own, rosterRow, tombstone(3, 'own-1')]).lastActivityAt).toBe(1_003)
})

it('holds on a batch that only revises rosters, and moves on one that carries anything else', () => {
const batch = (mutations: Extract<JournalRow, { kind: 'lifecycle-batch' }>['mutations']) =>
fold([{ kind: 'lifecycle-batch', settlementId: 'settle-1', mutations, ...base(1) }])
const rosterMutation = {
kind: 'item' as const,
itemId: ROSTER_ITEM,
revision: 1,
body: roster('unverifiable')
}
expect(batch([rosterMutation]).lastActivityAt).toBe(0)
expect(
batch([rosterMutation, { kind: 'item', itemId: 'turn', revision: 1, body: text('ended') }])
.lastActivityAt
).toBe(1_001)
})

it("moves on the session's own system rows that are not a roster", () => {
const status: AgentJournalItemBody = {
kind: 'message',
role: 'system',
blocks: [{ type: 'text', text: 'Compacted' }]
}
expect(fold([item(1, 'status-1', status)]).lastActivityAt).toBe(1_001)
})
})

describe('reopening a journal whose roster was left running', () => {
let root: string
let clock = 1_000
const journals = createTrackedJournalOpener()
const open = () =>
journals.open({
identity: {
sessionId: 'session-1',
workspaceId: 'ws-1',
hostId: 'host-1',
agent: 'codex',
providerHandle: { kind: 'codex', threadId: 'thread-1' }
},
journalDir: root,
now: () => (clock += 1_000),
mintEpoch: () => `epoch-${clock}`
})

beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), 'orca-journal-session-clock-'))
clock = 1_000
})

afterEach(async () => {
await journals.closeAll()
await rm(root, { recursive: true, force: true })
})

it('settles a live background task without dating the session to the restart', async () => {
const live = await open()
await live.appendItem(
{ provider: 'orca', clientMessageId: 'prompt-1' },
{ kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'watch the build' }] },
{ fence: 0 }
)
await live.appendItem(
claudeBackgroundTaskIdentity('task-1'),
claudeBackgroundTaskBody({
type: 'background-task',
taskId: 'task-1',
kind: 'command',
label: 'npm test --watch',
state: 'working'
}),
{ fence: 0 }
)
const ownClock = live.lastActivityAt()
await live.close()

const reopened = await open()
// A control: the reopen DID write the task's settling revision.
expect(reopened.snapshot().items.at(-1)?.revision).toBe(2)
expect(reopened.lastActivityAt()).toBe(ownClock)
})

it('settles the roster without dating the session to the restart', async () => {
const live = await open()
await live.appendItem(
{ provider: 'orca', clientMessageId: 'prompt-1' },
{ kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'fan out' }] },
{ fence: 0 }
)
await live.appendItem(codexSubagentGroupIdentity(GROUP_ID), roster('working'), { fence: 0 })
const ownClock = live.lastActivityAt()
await live.close()

const reopened = await open()
// A control: the reopen DID write the roster's settling revision.
expect(reopened.snapshot().items.at(-1)?.revision).toBe(2)
expect(reopened.lastActivityAt()).toBe(ownClock)
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Which journal rows date the session.
//
// `lastActivityAt` becomes the status summary's `updatedAt`, which the status row uses as its
// completion stamp and acknowledgement clock. Subagents write into the same journal and keep
// going after the session's own agent settles, so counting their rows re-dates an idle
// session and marks it unread again.

import { isRootAgentJournalItem } from '../../../shared/agent-session-journal-producer'
import type {
AgentJournalItemBody,
AgentJournalRenderItem
} from '../../../shared/agent-session-journal-types'
import { isSubagentGroupBlock } from '../../../shared/native-chat-types'
import type { JournalRow } from './journal-row-schema'

type JournalItemLookup = {
items: ReadonlyMap<string, AgentJournalRenderItem>
aliases: ReadonlyMap<string, string>
}

/** Whether a row is the session's own agent at work. Not a subagent's row (its linkage names
* it), and not a subagent roster: the session's row, but revised on every child transition.
* A roster's first write sits beside the spawn call, which dates the session anyway. */
export function journalRowDatesSession(lookup: JournalItemLookup, row: JournalRow): boolean {
if (row.kind === 'epoch' || !isRootAgentJournalItem(row)) {
return false
}
if (row.kind === 'item') {
return !isSubagentRoster(row.body)
}
if (row.kind === 'tombstone') {
return !isSubagentRoster(currentBody(lookup, row.itemId))
}
if (row.kind === 'lifecycle-batch') {
return row.mutations.some(
(mutation) =>
!isSubagentRoster(
mutation.kind === 'item' ? mutation.body : currentBody(lookup, mutation.itemId)
)
)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return true
}

function isSubagentRoster(body: AgentJournalItemBody | undefined): boolean {
return body?.kind === 'message' && body.blocks.some(isSubagentGroupBlock)
}

/** Read before the reducer applies the row: a tombstone names what it is about to remove. */
function currentBody(lookup: JournalItemLookup, itemId: string): AgentJournalItemBody | undefined {
return lookup.items.get(lookup.aliases.get(itemId) ?? itemId)?.body
}
13 changes: 10 additions & 3 deletions src/main/native-chat/agent-session-journal/journal-store-open.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ export async function openJournalStoreState(input: {
appendItem: (
identity: AgentJournalItemIdentity,
body: AgentJournalItemBody,
fence: number
fence: number,
observedAt?: number
) => Promise<unknown>
agent: AgentType
highestFence: () => number
Expand Down Expand Up @@ -129,7 +130,8 @@ async function settleStaleSubagentRosters(
appendItem: (
identity: AgentJournalItemIdentity,
body: AgentJournalItemBody,
fence: number
fence: number,
observedAt: number
) => Promise<unknown>
highestFence: () => number
readOnly: () => boolean
Expand All @@ -140,6 +142,11 @@ async function settleStaleSubagentRosters(
return
}
for (const revision of staleSubagentRosterRevisions(loaded.state.items.values())) {
await input.appendItem(revision.identity, revision.body, input.highestFence())
await input.appendItem(
revision.identity,
revision.body,
input.highestFence(),
revision.observedAt
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@ export function restoreJournalStore(
publishRepairEpoch: () =>
collaborators.epochController.start('unreconcilable_prefix', host.state().highestFence),
adopt: host.adopt,
appendItem: (identity, body, fence) => host.journal().appendItem(identity, body, { fence }),
appendItem: (identity, body, fence, observedAt) =>
host
.journal()
.appendItem(identity, body, { fence, ...(observedAt === undefined ? {} : { observedAt }) }),
agent: host.identity.agent,
highestFence: () => host.state().highestFence,
malformedRows: host.malformedRows,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ import {
export type JournalSubagentLivenessRevision = {
identity: AgentJournalItemIdentity
body: AgentJournalItemBody
/** The row's own time. The verdict restates it as the host that is gone left it, so
* the revision must not date the session to the reopen. */
observedAt: number
}

/** The revisions a reopened journal owes: one per row still claiming a live
Expand All @@ -61,7 +64,11 @@ export function staleSubagentRosterRevisions(
if (!identity || agentJournalItemKey(identity) !== item.itemId) {
continue
}
revisions.push({ identity, body: { ...body, blocks: settleBlocks(body.blocks) } })
revisions.push({
identity,
body: { ...body, blocks: settleBlocks(body.blocks) },
observedAt: item.observedAt
})
}
return revisions
}
Expand Down
Loading
Loading