Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
11 changes: 10 additions & 1 deletion src/main/native-chat/agent-session-journal/journal-reducer.ts
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 { journalRowRemovesSessionWork, journalRowWroteSessionWork } 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 @@ -62,12 +64,19 @@ export function createJournalReducerState(sessionId: string, epoch: string): Jou
}

export function applyJournalRow(state: JournalReducerState, row: JournalRow): void {
const removesSessionWork = journalRowRemovesSessionWork(state, row)
applyJournalRowContent(state, row)
if (removesSessionWork || journalRowWroteSessionWork(state, row)) {
state.lastActivityAt = Math.max(state.lastActivityAt, row.ts)
}
}

function applyJournalRowContent(state: JournalReducerState, row: JournalRow): void {
state.lastSequence = Math.max(state.lastSequence, row.seq)
state.highestFence = Math.max(state.highestFence, row.fence)
if (row.kind === 'epoch') {
return
}
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,215 @@
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 subagent row's removal: a tombstone names no producer, the row it removes does", () => {
const own = item(1, 'own-1', text('delegating'))
const child = item(2, 'child-1', text('reading'), CHILD)
const removal: JournalRow = { kind: 'tombstone', itemId: 'child-1', revision: 3, ...base(3) }
expect(fold([own, child, removal]).lastActivityAt).toBe(own.ts)
})

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,64 @@
// 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.
//
// The clock reads the reducer's attribution of the items a row touches, never the raw row:
// a batch or a revision need not name the producer the reducer attributes the item to.

import { isRootAgentJournalItem } from '../../../shared/agent-session-journal-producer'
import type { 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>
}

/** Read BEFORE the reducer applies `row`: whether it removes the session's own work. */
export function journalRowRemovesSessionWork(lookup: JournalItemLookup, row: JournalRow): boolean {
if (row.kind === 'tombstone') {
return isSessionWork(currentItem(lookup, row.itemId))
}
if (row.kind === 'lifecycle-batch') {
return row.mutations.some(
(mutation) =>
mutation.kind === 'tombstone' && isSessionWork(currentItem(lookup, mutation.itemId))
)
}
return false
}

/** Read AFTER the reducer applied `row`: whether it wrote the session's own work. */
export function journalRowWroteSessionWork(lookup: JournalItemLookup, row: JournalRow): boolean {
if (row.kind === 'item') {
return isSessionWork(currentItem(lookup, row.itemId))
}
if (row.kind === 'lifecycle-batch') {
return row.mutations.some(
(mutation) => mutation.kind === 'item' && isSessionWork(currentItem(lookup, mutation.itemId))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

git diff 563dd5487fb6ca2f9a79b12075df2ed054934d7d..85cdfca4130c68862ad15541d319591bc1ef7620 -- src/main/native-chat/agent-session-journal/journal-session-clock.ts src/main/native-chat/agent-session-journal/journal-reducer.ts src/main/native-chat/agent-session-journal/journal-row-builders.ts
rg -n -C 4 'journalRenderItem|lifecycle-batch|agentId|settle' src/main/native-chat/agent-session-journal src/main/codex
sed -n '1,130p' src/main/native-chat/agent-session-journal/journal-session-clock.ts

Repository: stablyai/orca

Length of output: 45545


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- symbols ---'
rg -n -C 3 'journalLifecycleBatchRowBuilder|journalRenderItem|currentItem|journalRowWroteSessionWork|lifecycle-batch|agentId|settleCodexJournalSession|appendCodexLifecycleMutations|recency|lastActivityAt' \
  src/main/native-chat/agent-session-journal/journal-row-builders.ts \
  src/main/native-chat/agent-session-journal/journal-reducer.ts \
  src/main/native-chat/agent-session-journal/journal-row-schema.ts \
  src/main/native-chat/agent-session-journal \
  src/main/codex/codex-structured-journal-settlement.ts \
  src/main/codex/codex-structured-journal-sink.ts \
  src/main/codex \
  src/shared/agent-session-journal-producer.ts \
  src/shared/agent-session-journal-types.ts \
  | head -n 1200

printf '%s\n' '--- builders ---'
sed -n '1,260p' src/main/native-chat/agent-session-journal/journal-row-builders.ts
printf '%s\n' '--- reducer ---'
sed -n '1,300p' src/main/native-chat/agent-session-journal/journal-reducer.ts
printf '%s\n' '--- schema ---'
sed -n '1,260p' src/main/native-chat/agent-session-journal/journal-row-schema.ts
printf '%s\n' '--- settlement ---'
sed -n '1,220p' src/main/codex/codex-structured-journal-settlement.ts
printf '%s\n' '--- sink ---'
sed -n '1,240p' src/main/codex/codex-structured-journal-sink.ts

Repository: stablyai/orca

Length of output: 43113


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- row builders 80-165 ---'
sed -n '80,165p' src/main/native-chat/agent-session-journal/journal-row-builders.ts
printf '%s\n' '--- render item ---'
sed -n '1,240p' src/main/native-chat/agent-session-journal/journal-render-item.ts
printf '%s\n' '--- reducer 60-125 ---'
sed -n '60,125p' src/main/native-chat/agent-session-journal/journal-reducer.ts
printf '%s\n' '--- identity and linkage definitions ---'
rg -n -C 5 'type AgentJournalItemIdentity|interface AgentJournalItemIdentity|producerLinkage|agentId|parentAgentId|codexJournalItem|codexStreamingJournalItem' \
  src/shared/agent-session-journal-types.ts \
  src/main/codex/codex-structured-item-translation.ts \
  src/main/codex/codex-structured-journal-items.ts \
  src/main/codex
printf '%s\n' '--- recency tests and settlement translator tests ---'
rg -l -n 'journalRowWroteSessionWork|lastActivityAt|parent.*recency|recency|settlement' \
  src/main/native-chat/agent-session-journal \
  src/main/codex \
  | head -n 80

Repository: stablyai/orca

Length of output: 42702


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- Codex linkage writes and active item registration ---'
rg -n -C 6 'agentId|parentAgentId|producerKind|activeItems\.set|activeItems|appendItem\(|tryAppendItem\(|appendLifecycleBatch|tryAppendLifecycleBatch' \
  src/main/codex \
  src/main/native-chat/agent-session-journal \
  | head -n 1600
printf '%s\n' '--- session clock tests ---'
sed -n '1,320p' src/main/native-chat/agent-session-journal/journal-session-clock.test.ts
printf '%s\n' '--- Codex settlement tests ---'
sed -n '1,420p' src/main/codex/codex-structured-journal-translation-settlement.test.ts

Repository: stablyai/orca

Length of output: 42722


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- all producer-linkage references in relevant source ---'
rg -n -C 4 'AgentJournalProducerLinkage|agentJournalLinkageFields|agentId|parentAgentId|producerKind|providerParentRef' \
  src/main/codex \
  src/main/native-chat/agent-session-journal \
  src/main/native-chat/agent-session-wire \
  src/shared \
  | head -n 1200
printf '%s\n' '--- sink option and journal append contracts ---'
rg -n -C 8 'tryAppendItem|appendItem|tryAppendLifecycleBatch|appendLifecycleBatch|lifecycle.*true|coalescingKey|linkage' \
  src/main/native-chat/agent-session-wire \
  src/main/native-chat/agent-session-journal \
  | head -n 1400
printf '%s\n' '--- Codex subagent execution linkage context ---'
sed -n '1,260p' src/main/codex/codex-subagent-executions.ts
sed -n '1,180p' src/main/codex/codex-subagent-execution-projection.ts

Repository: stablyai/orca

Length of output: 45543


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- Codex production agentId references ---'
rg -n 'agentId|parentAgentId|producerKind|providerParentRef' src/main/codex || true
printf '%s\n' '--- linkage helper ---'
rg -l 'function agentJournalLinkageFields|agentJournalLinkageFields' src/shared src/main/native-chat
for f in $(rg -l 'function agentJournalLinkageFields|agentJournalLinkageFields' src/shared src/main/native-chat); do
  echo "--- $f ---"
  rg -n -C 12 'agentJournalLinkageFields|AgentJournalProducerLinkage' "$f"
done
printf '%s\n' '--- append option declarations ---'
rg -n -C 14 'type JournalItemAppendOptions|interface JournalItemAppendOptions|JournalItemAppendOptions|JournalLifecycleBatchInput' \
  src/main/native-chat/agent-session-journal \
  src/main/native-chat/agent-session-wire \
  src/shared

Repository: stablyai/orca

Length of output: 42439


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- structured sink option declarations ---'
rg -n -C 20 'export type StructuredAgentSessionAppendOptions|type StructuredAgentSessionAppendOptions|interface StructuredAgentSessionAppendOptions|StructuredAgentSessionAppendOptions' \
  src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts \
  src/main/native-chat/agent-session-wire
printf '%s\n' '--- sink forwarding implementation ---'
rg -n -C 12 'structuredAgentSessionJournalAppendOptions|appendItem:|tryAppendItem:|appendLifecycleBatch:|tryAppendLifecycleBatch:' \
  src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts

Repository: stablyai/orca

Length of output: 41588


Preserve child ownership in lifecycle-batch revisions.

When a Codex settlement revises a child-linked item, the lifecycle batch omits producer linkage. journalRenderItem then replaces the item with a render item that has no agentId. The reducer and journalRowWroteSessionWork read that replacement as root-owned, so the child revision can advance the parent session’s lastActivityAt.

Carry producer ownership per mutation, or preserve the existing item’s ownership when applying settlement revisions. Add a settlement-to-reducer test. The current clock test supplies agentId manually and does not exercise the translator path.

)
}
return row.kind === 'submission' || row.kind === 'dispatch'
}

/** The session's own agent at work. Not a subagent's row, 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. */
function isSessionWork(item: AgentJournalRenderItem | undefined): boolean {
return (
item !== undefined &&
isRootAgentJournalItem(item) &&
!(item.body.kind === 'message' && item.body.blocks.some(isSubagentGroupBlock))
)
}

function currentItem(
lookup: JournalItemLookup,
itemId: string
): AgentJournalRenderItem | undefined {
return lookup.items.get(lookup.aliases.get(itemId) ?? itemId)
}
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