Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 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
658 changes: 658 additions & 0 deletions ATTRIBUTION-parent-recency.md

Large diffs are not rendered by default.

299 changes: 173 additions & 126 deletions PR-BODY.md

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ describe('claude journal translation — subagents', () => {
})

describe('producer attribution', () => {
it("stamps a subagent frame's message, tool call and tool result, and leaves the roster row alone", () => {
it("stamps a subagent frame's message, tool call and tool result, and the roster row too", () => {
const { translator, appended } = harness()
translator.handle(userTurn('user-1'))
translator.handle(assistantFrame('root-1', null, [{ type: 'text', text: 'delegating' }]))
Expand All @@ -343,6 +343,8 @@ describe('producer attribution', () => {

const stamped = appended()
.filter((item) => item.options?.producedBySubagent === true)
// The roster row is stamped too, and is asserted on its own below.
.filter((item) => orcaClientMessageId(item.identity) !== GROUP_ITEM_ID)
.map((item) => item.body.kind)
expect(stamped).toEqual(['message', 'tool-call', 'tool-call'])

Expand All @@ -353,13 +355,17 @@ describe('producer attribution', () => {
)
expect(rootProse?.options?.producedBySubagent).toBeUndefined()

// The roster group row is the PARENT's own display of its children, so it must
// stay root — stamping it would hide the subagent list from the parent.
// The roster group row holds nothing but children's state and is rewritten on every
// child transition, so it is child-produced even though the parent's code writes it.
// Leaving it root let it move the session's recency clock on its own, which is the
// defect with the attribution already in place. Nothing is hidden by stamping it: the
// transcript renders every producer's rows, and the sidebar's child list comes from the
// live roster the host publishes, not from this row.
const rosterRow = appended().findLast(
(item) => orcaClientMessageId(item.identity) === GROUP_ITEM_ID
)
expect(rosterRow).toBeDefined()
expect(rosterRow?.options?.producedBySubagent).toBeUndefined()
expect(rosterRow?.options?.producedBySubagent).toBe(true)
})

it("stamps a subagent's STREAMED prose, which carries no message envelope when it persists", () => {
Expand Down
26 changes: 24 additions & 2 deletions src/main/claude/claude-subagent-roster.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type {
import type { AgentSessionJournal } from '../native-chat/agent-session-journal/journal-store'
import {
createDeferredStructuredAgentSessionEventSink,
type StructuredAgentSessionAppendOptions,
type StructuredAgentSessionEventSink
} from '../native-chat/agent-session-wire/structured-agent-session-event-sink'
import { ClaudeSubagentRoster } from './claude-subagent-roster'
Expand All @@ -31,10 +32,16 @@ function isGroupRow(identity: AgentJournalItemIdentity, groupId: string): boolea
}

function harness(groupKey: string | null = TURN_1) {
const items: { identity: AgentJournalItemIdentity; body: AgentJournalItemBody }[] = []
// Options are captured, not dropped: producer attribution rides on them, and a harness
// that discards the argument reports every append as root and passes.
const items: {
identity: AgentJournalItemIdentity
body: AgentJournalItemBody
options: StructuredAgentSessionAppendOptions | undefined
}[] = []
const tombstones: AgentJournalItemIdentity[] = []
const sink: StructuredAgentSessionEventSink = {
appendItem: (identity, body) => items.push({ identity, body }),
appendItem: (identity, body, options) => items.push({ identity, body, options }),
appendTombstone: (identity) => tombstones.push(identity),
publish: vi.fn()
}
Expand Down Expand Up @@ -139,6 +146,21 @@ describe('ClaudeSubagentRoster', () => {
expect(items).toHaveLength(1)
})

it('marks every roster row child-produced, on the first write and on each revision', () => {
const { roster, items } = harness()
roster.observeSystemFrame(
started({ task_id: 'task-1', tool_use_id: 'toolu_1', description: 'Audit' })
)
roster.observeSystemFrame(
system('task_updated', { task_id: 'task-1', patch: { status: 'completed' } })
)
expect(items.length).toBeGreaterThan(1)
// The row is written from the parent's context and no `parent_tool_use_id` is near it,
// so nothing else would attribute it — yet it holds only children's state and is
// rewritten on every child transition. Unmarked, it alone re-stamps the session.
expect(items.map((item) => item.options?.producedBySubagent)).toEqual(items.map(() => true))
})

it('does not duplicate a resumed task re-announced under a new tool_use_id', () => {
const { roster, roles } = harness()
roster.observeSystemFrame(
Expand Down
8 changes: 7 additions & 1 deletion src/main/claude/claude-subagent-roster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,12 @@ export class ClaudeSubagentRoster {
private write(group: RosterGroup): void {
const agents = [...group.entries.values()].map((tracked) => tracked.entry)
const options = { coalescingKey: `claude-subagents:${group.groupId}` }
// Child-produced, though it is written from the parent's context and no
// `parent_tool_use_id` comes near it: every byte of the row is children's state and it
// is rewritten on every child transition. Unmarked it moves the session's recency
// clock by itself. The removal below stays root — it only ever runs once the group
// holds no children at all.
const childRow = { ...options, producedBySubagent: true as const }
if (agents.length === 0) {
// The row's last child turned out not to be a subagent. An empty roster is
// not a roster of nothing, so the row goes rather than reading "Ran 0".
Expand All @@ -380,7 +386,7 @@ export class ClaudeSubagentRoster {
return
}
group.lastSerialized = serialized
this.deps.sink.appendItem(group.identity, body, options)
this.deps.sink.appendItem(group.identity, body, childRow)
// Publish keeps the sink's own coalescing slot: sharing the row's key makes
// each queued publish evict the append it was meant to flush.
this.deps.sink.publish()
Expand Down
65 changes: 65 additions & 0 deletions src/main/native-chat/agent-session-journal/journal-reducer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -718,3 +718,68 @@ describe('producer attribution round-trips through the reducer', () => {
expect(renderJournalState(state).items[0]?.producedBySubagent).toBeUndefined()
})
})

describe("the session's recency clock", () => {
it("advances on the session's own rows and not on a subagent's", () => {
const state = fold([
{ kind: 'item', itemId: 'root-1', revision: 1, body: text('delegating'), ...base(1) },
{
kind: 'item',
itemId: 'child-1',
revision: 1,
body: text('the child is reading files'),
...base(2),
producedBySubagent: true
},
{
kind: 'item',
itemId: 'child-2',
revision: 1,
body: text('the child is still reading files'),
...base(3),
producedBySubagent: true
}
])
// Ordering still counts every row; only the clock is the session's own.
expect(state.lastSequence).toBe(3)
expect(state.lastActivityAt).toBe(base(1).ts)
})

it("resumes on the session's next own row", () => {
const state = fold([
{ kind: 'item', itemId: 'root-1', revision: 1, body: text('delegating'), ...base(1) },
{
kind: 'item',
itemId: 'child-1',
revision: 1,
body: text('the child reported back'),
...base(2),
producedBySubagent: true
},
{ kind: 'item', itemId: 'root-2', revision: 1, body: text('done'), ...base(3) }
])
expect(state.lastActivityAt).toBe(base(3).ts)
})

it('advances on a lifecycle batch a subagent did not produce, and holds on one it did', () => {
const own = fold([
{
kind: 'lifecycle-batch',
settlementId: 'settle-1',
mutations: [{ kind: 'item', itemId: 'i-1', revision: 1, body: text('settled') }],
...base(1)
}
])
expect(own.lastActivityAt).toBe(base(1).ts)
const child = fold([
{
kind: 'lifecycle-batch',
settlementId: 'settle-2',
mutations: [{ kind: 'item', itemId: 'i-2', revision: 1, body: text('settled') }],
...base(1),
producedBySubagent: true
}
])
expect(child.lastActivityAt).toBe(0)
})
})
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 @@ -18,6 +18,7 @@ import {
agentJournalSubmissionKey,
parseAgentJournalItemKey
} from '../../../shared/agent-session-journal-item-key'
import { isRootAgentJournalItem } from '../../../shared/agent-session-journal-producer'
import { structuredAgentSessionPayloadFingerprint } from '../../../shared/structured-agent-session-mutation'
import { journalItemRevisionIsStale } from './journal-item-revision'
import type { JournalRow } from './journal-row-schema'
Expand Down Expand Up @@ -67,7 +68,15 @@ export function applyJournalRow(state: JournalReducerState, row: JournalRow): vo
if (row.kind === 'epoch') {
return
}
state.lastActivityAt = Math.max(state.lastActivityAt, row.ts)
// Recency is the SESSION'S OWN agent's. A subagent's rows share this journal and are
// the newest ones in it while a child runs, so a journal-wide clock stamps an idle
// parent "now" on every child frame — and that clock becomes the row's
// `stateStartedAt`, which is the acknowledgement clock, so the parent also went
// unread again each time. A child's work reaches the parent's row as a status
// rollup instead; see the status feed.
if (isRootAgentJournalItem(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,103 @@
// What a subagent may and may not say about the session that spawned it, as this feed
// publishes it.
//
// One journal holds the session's own agent's rows and every descendant's. The status
// summary is the session's row in every list that renders one, so the split matters here:
// a child's frames must not move the session's recency clock, and a child that is still
// working must still keep the session's row from reading finished.

import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import type { AgentSessionBackgroundTask } from '../../../shared/agent-session-wire'
import { createStatusFeedTestBed } from './structured-agent-session-status-feed-test-bed'

const SESSION = 'status-session'
const USER_IDENTITY = {
provider: 'codex',
threadId: 'thread-1',
turnId: 'turn-1',
ordinal: 1
} as const

const { open, close, openJournal, feedFor } = createStatusFeedTestBed(SESSION)

beforeEach(open)
afterEach(close)

describe('a subagent and the status summary of the session that spawned it', () => {
it("holds an idle session's clock and its publications while a subagent's rows land", async () => {
// An explicit, always-advancing journal clock. On the wall clock five appends can share
// a millisecond, and a `Math.max` over the same number moves nothing — the test would
// pass against an unattributed clock and prove nothing.
let appendedAt = 10_000
const journal = await openJournal(SESSION, () => (appendedAt += 1_000))
const { feed, events } = feedFor(new Map([[SESSION, { journal }]]))
await journal.appendItem(
USER_IDENTITY,
{ kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'fan out' }] },
{ fence: 1 }
)
feed.publish(SESSION, journal)
const settled = events.at(-1)
if (settled?.type !== 'status') {
throw new Error('status publication missing')
}
expect(settled.session.status).toBe('idle')
const published = events.length

for (let row = 0; row < 5; row += 1) {
await journal.appendItem(
{ provider: 'claude', sessionId: 'claude-session', uuid: `child-${row}` },
{ kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: `reading ${row}` }] },
{ fence: 1, producedBySubagent: true }
)
feed.publish(SESSION, journal)
}

// The clock is the session's own. `summariesEqual` treats `updatedAt` as significant
// only while idle, so an idle parent with a working child is the exact case where a
// contaminated clock re-broadcasts the whole summary to every subscriber, local and
// remote, once per child frame.
expect(events).toHaveLength(published)
const latest = events.at(-1)
if (latest?.type !== 'status') {
throw new Error('status publication missing')
}
expect(latest.session.updatedAt).toBe(settled.session.updatedAt)
})

it('reads a session with a working subagent as working, without moving its clock', async () => {
let appendedAt = 10_000
const journal = await openJournal(SESSION, () => (appendedAt += 1_000))
let tasks: AgentSessionBackgroundTask[] = [
{ id: 'child-1', kind: 'agent', name: 'deep_review', state: 'working' }
]
const { feed, events } = feedFor(new Map([[SESSION, { journal }]]), null, undefined, () => ({
state: 'monitoring',
tasks
}))
await journal.appendItem(
USER_IDENTITY,
{ kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'fan out' }] },
{ fence: 1 }
)
feed.publish(SESSION, journal)
const busy = events.at(-1)
if (busy?.type !== 'status') {
throw new Error('status publication missing')
}
// The session's own agent has settled; its child has not. The row reads busy off the
// rollup, and off nothing else — the clock stays the parent's own last row.
expect(busy.session.status).toBe('working')
expect(busy.session.updatedAt).toBe(journal.lastActivityAt())
// Rolled-up work is the child's, so the parent's row claims no tool of its own.
expect(busy.session.toolName).toBeUndefined()

// A backgrounded shell is not a subagent, and a settled child is not working.
tasks = [{ id: 'shell-1', kind: 'command', state: 'working' }]
feed.publish(SESSION, journal)
expect(events.at(-1)).toMatchObject({ type: 'status', session: { status: 'idle' } })
tasks = [{ id: 'child-1', kind: 'agent', name: 'deep_review', state: 'done' }]
feed.publish(SESSION, journal)
expect(events.at(-1)).toMatchObject({ type: 'status', session: { status: 'idle' } })
})
})
Loading
Loading