codeburn/tests/parser-rich-capture.test.ts
Resham Joshi 8e1caae33a
Some checks are pending
CI / semgrep (push) Waiting to run
sessions: fold subagent runs into PR attribution (#791)
* sessions: fold subagent runs into PR attribution

Sidechain (subagent) session cost never reached the by-PR view, so a
session orchestrated on one model with subagent lanes on another showed
only the parent model on every PR row. Fold each sidechain's cost, calls,
models, and categories into the parent turn that spawned it, so it
inherits that turn's PR set under the existing turn-level state machine.

Linkage, in priority order: the spawn result's toolUseResult.agentId
pairs the child's agent id with the Agent/Task tool_use id that launched
it (recorded per turn), which is the true launch point and wins even when
the child's first activity landed during a later turn; else the child's
first-activity timestamp is bucketed into the containing turn span; else
the child folds into the parent's unattributed spend. Children of parents
that referenced no PR, and orphans whose parent is absent from the scan,
contribute nothing, unchanged.

Cache v6 to v7 (neither shipped, so one combined bump from v5): per-turn
spawnToolUseIds, per-file parentSessionId and agentSpawnLinks; the
validator and the append/compact paths thread them like prRefs. By-PR
footers now count parents plus folded subagent runs and the payload gains
an additive subagentSessions field. distinctCost now includes folded
subagent spend, documented in the payload comment.

* sessions: address adversarial review of subagent PR attribution

Rework child attribution to resolve each subagent to the PR its launching
turn was working on, using the parent's UNFILTERED turn data, and enforce
that every dollar is counted exactly once.

- Mutual exclusion: a child that referenced its own PR attributes
  standalone and is never folded; a child with no links is folded only.
  Fixes a double-charge where a self-linking child was both folded and
  self-attributed.
- Recursion: a fold aggregates a child plus its non-self-linking
  descendants (depth-first, cycle-guarded), so grandchildren spawned by
  subagents reach the PR report.
- Global linkage: the subagent index keys by parentSessionId alone
  (UUIDs are globally unique), so a child whose worktree resolves to a
  different project still links.
- Date-range correctness: spawn-to-PR sets are built at assembly from the
  full turn list, so a spawn in a pre-range turn attributes to the right
  PR; a PR-linked parent whose own turns fall out of range is kept as a
  0-cost fold anchor so its in-range child is not lost.
- Timestamp fallback compares epoch ms (mixed UTC offsets order right) and
  is end-bounded: a child active after the parent's last turn is unlinked
  (contributes nothing), matching orphan semantics.
- Cache adoption tries the newest prior versioned file (v6 then v5) so the
  preceding build's expired-PR history survives the v7 bump; an invariant
  note requires the list to cover every version that can exist on disk.
- Spawn-result pairing matches the tool_result block that carries the
  agentId, not the first block, when a record batches several results.
- resolveSubagentAttribution is computed once and shared by aggregateByPr
  and prLinkedTotals.

subagentSessions now counts folded subtrees (children plus descendants).
Verified on real data: attributed + unattributed reconciles to cost, and
parent-only cost plus folded-children cost equals the folded total to the
cent (no double-count).

* sessions: round-2 hardening of subagent PR attribution

Address a second adversarial review of the new machinery.

- ID collision: parents and a child's parent reference are keyed by
  provider + sessionId, not bare sessionId. When two distinct parents
  still share a key (true duplicate/imported data), the child folds into
  NEITHER (deterministic skip, stays standalone): correctness over
  coverage.
- Recursion dedup is global: one claimed-set spans all of a parent's
  direct children, so a descendant reachable through two paths (a diamond
  or duplicate id) folds exactly once and a parent-link cycle terminates.
- Cache adoption migrates every prior version oldest-to-newest and MERGES
  per source path (newer wins per entry), so a sparse or partial newer
  file no longer masks older-only expired-PR orphans.
- Fold anchors (0-cost PR-linked parents kept only for attribution) live
  in a new ProjectSummary.subagentAnchors, never in `sessions`, so they no
  longer contaminate session counts, averages, or any per-session report.
  Folded PR rows take their date span from the contributing child activity
  rather than the anchor's empty timestamps.
- One-pass buildPrAttribution computes rows and totals together; the
  payload builder and CLI call it once. Drops the identity-keyed
  memoization, which could return stale folds if the array was mutated.
- Ambiguous multi-block spawn-result pairing leaves the spawn link unset
  on purpose; the child then folds via the timestamp fallback rather than
  pairing with the wrong id or disappearing.

Every fix is mutation-verified. A fresh real-data drive re-proves the
no-double-count identity to the cent (parent-only cost plus folded cost
equals the folded total) and that the PR rows sum to attributedCost.

* sessions: round-3 hardening of subagent PR attribution

Third adversarial review pass.

- Ambiguity counts ALL candidate parents (and anchors) sharing a
  provider+sessionId key, not just PR-bearing ones, and uses a
  per-record fingerprint: a key carried by more than one DISTINCT record
  folds its child/subtree into NEITHER (identical duplicates still fold
  once). This unifies the parent-collision and duplicate-descendant rules
  and is deterministic across input order.
- Project-rebuilding filters (by day, by date range, by config source)
  now carry subagentAnchors through, and a date filter CONVERTS a spawn
  parent whose in-range turns are all filtered out into an anchor so a
  surviving in-range child still folds. Rebuilt sessions also keep their
  PR + subagent-linkage metadata (prLinks, parentSessionId, spawnPrSets,
  ...), which buildSessionSummary otherwise drops, so by-PR and folding
  work on a filtered slice (menubar/dashboard flow).
- Fold anchors leave ProjectSummary.sessions entirely and folded PR rows
  take their span from the child, so 0-cost anchors never touch session
  counts or averages.
- Ambiguous spawn pairing (parent named the agent but its exact launching
  tool_use could not be paired) is recorded per parent; a late child of
  such a pairing folds to the parent's last turn within a 30 minute grace
  window, else stays unlinked. A truly-absent pairing gets no grace.
- Row session key is NUL-delimited and provider-prefixed, so a project
  name or session id containing a space no longer collides and
  undercounts distinct sessions.

Every fix mutation-verified. A fresh real-data drive re-proves the
no-double-count identity to the cent, and a day-filtered drive proves the
filter fix end to end (anchors created, subagents fold, identity holds).

* sessions: round-4 hardening of subagent PR attribution

Fourth adversarial review pass.

- sessionFingerprint now covers the COMPLETE linkage-relevant payload,
  not just headline stats: a canonical (sorted-key) serialization of
  agentSpawnLinks, spawnPrSets, prRefsAtRangeStart, ambiguousSpawnAgentIds,
  parent/agent identity, and the per-turn prRefs timeline. Two records
  that share an id and headline stats but map the child to different
  spawns/PRs now fingerprint DISTINCT, so the ambiguity rule fires and
  they fold into neither, deterministically rather than order-dependent
  first-wins.
- A date/day filter recomputes prRefsAtRangeStart at the new slice
  boundary by replaying the original full turn sequence, instead of
  copying the wide range's value. A PR switch between the wide start and
  the slice start (July 1 A, July 10 B, slice July 20) now carries B, not
  a stale A; a turn exactly on the boundary stays in-slice and applies its
  own refs. The recompute selects by timestamp, so it is order-independent.
  Non-contiguous day selections are documented as treated contiguous from
  the earliest selected day (a single session-level seed cannot represent
  multiple segments; the menubar selection is a single day or a run).
- The anchor-carry path drops an anchor that duplicates a surviving
  session id, so malformed merged input cannot double-count.

Also: rebuilt filtered sessions were losing their PR/subagent-linkage
metadata (a child its parentSessionId, a parent its prLinks), which
carryLinkageFields now restores, so by-PR and folding work on any filtered
slice.

Every fix mutation-verified. A fresh real-data drive re-proves the
no-double-count identity and reconciliation to the cent for both a
lifetime scan and a day-filtered slice (anchors created, subagents fold
through the filter).

* sessions: round-5 hardening of subagent PR attribution

Fifth adversarial review pass; closed-form fixes.

- sessionFingerprint serializes the COMPLETE fold-determining state via a
  real recursive canonical encoder: session-level linkage AND, per turn in
  sequence, timestamp, prRefs, cost, calls, savings, and per-model cost.
  Object keys are sorted recursively and set-semantic arrays (PR-ref lists,
  ambiguous ids, spawnPrSets values) are sorted, while the turn list keeps
  order; the structure is emitted through JSON.stringify (no delimiter
  concatenation). Two same-id parents that differ only in a turn timestamp
  now fingerprint DISTINCT (fold neither), and records differing only in
  set-array order fingerprint EQUAL (no false ambiguity).
- recomputeRangeStartPrRefs breaks an exact-same-millisecond tie
  deterministically by the lexicographically-last sorted-ref key, so the
  recomputed seed is stable regardless of turn order.
- A day filter seeds EACH selected day's first ref-less turn by replaying
  the original full turn sequence up to that day's start (per-day seeding),
  so a PR switch on an UNSELECTED day between two selected days carries to
  the later day. Contiguous and non-contiguous selections are both correct.
- The anchor dedupe drops an anchor only when a surviving session shares
  the full provider-aware, fingerprint-qualified identity (a proven
  duplicate): a different-provider or different-record same-id session no
  longer wrongly drops the anchor.

Also fixed a double-count the fingerprint test exposed: two duplicate
parent sessions share a key and the SAME resolved children, so folding is
now done once per parent key.

Every fix mutation-verified. Fresh real-data drives (lifetime, single-day,
and a NON-CONTIGUOUS day selection) re-prove no-double-count and
reconciliation to the cent.

---------

Co-authored-by: reviewer <review@local>
2026-07-20 20:47:23 -07:00

370 lines
15 KiB
TypeScript

import { describe, it, expect } from 'vitest'
import {
countStructuredPatchLoc,
collectToolResultMeta,
collectSessionMeta,
emptySessionMeta,
parseApiCall,
groupIntoTurns,
parsedTurnsToCachedTurns,
buildSpawnPrSets,
type ToolResultMeta,
} from '../src/parser.js'
import type { JournalEntry } from '../src/types.js'
// ── structuredPatch LOC counting ───────────────────────────────────────
describe('countStructuredPatchLoc', () => {
it('counts +/- lines across a single hunk', () => {
const patch = [
{ oldStart: 80, oldLines: 7, newStart: 80, newLines: 7, lines: [
' unchanged context',
'- old line',
'+ new line',
' more context',
] },
]
expect(countStructuredPatchLoc(patch)).toEqual({ added: 1, removed: 1 })
})
it('sums across multiple hunks', () => {
const patch = [
{ lines: ['+a', '+b', '-c', ' ctx'] },
{ lines: ['+d', '-e', '-f'] },
]
expect(countStructuredPatchLoc(patch)).toEqual({ added: 3, removed: 3 })
})
it('returns zero for an empty patch (Write-create shape)', () => {
expect(countStructuredPatchLoc([])).toEqual({ added: 0, removed: 0 })
})
it('returns zero for a missing/non-array patch', () => {
expect(countStructuredPatchLoc(undefined)).toEqual({ added: 0, removed: 0 })
expect(countStructuredPatchLoc(null)).toEqual({ added: 0, removed: 0 })
expect(countStructuredPatchLoc({ lines: ['+x'] })).toEqual({ added: 0, removed: 0 })
})
it('ignores hunks whose lines are absent or non-string', () => {
const patch = [{ oldStart: 1 }, { lines: [1, '+ok', null, '-no'] }]
expect(countStructuredPatchLoc(patch)).toEqual({ added: 1, removed: 1 })
})
})
// ── tool-result meta extraction + per-call attribution ─────────────────
function assistantEntry(id: string, toolUseIds: string[]): JournalEntry {
return {
type: 'assistant',
timestamp: '2026-07-01T10:00:00Z',
sessionId: 's1',
gitBranch: 'main',
message: {
type: 'message',
role: 'assistant',
model: 'claude-sonnet-4-20250514',
id,
content: toolUseIds.map(tid => ({ type: 'tool_use' as const, id: tid, name: 'Edit', input: {} })),
usage: { input_tokens: 10, output_tokens: 5 },
},
}
}
function toolResultEntry(opts: {
toolUseId: string
isError?: boolean
structuredPatch?: unknown
interrupted?: boolean
userModified?: boolean
}): JournalEntry {
return {
type: 'user',
timestamp: '2026-07-01T10:00:01Z',
sessionId: 's1',
gitBranch: 'main',
message: {
role: 'user',
content: [{ type: 'tool_result', tool_use_id: opts.toolUseId, is_error: opts.isError, content: 'x' } as never],
},
toolUseResult: {
structuredPatch: opts.structuredPatch,
interrupted: opts.interrupted ?? false,
userModified: opts.userModified ?? false,
},
} as JournalEntry
}
describe('collectToolResultMeta + parseApiCall attribution', () => {
it('attributes LOC, interrupted, userModified, and toolErrors to the issuing call', () => {
const map = new Map<string, ToolResultMeta>()
collectToolResultMeta(toolResultEntry({
toolUseId: 'tu1',
structuredPatch: [{ lines: ['+a', '+b', '-c'] }],
userModified: true,
}), map)
collectToolResultMeta(toolResultEntry({
toolUseId: 'tu2',
isError: true,
interrupted: true,
}), map)
const call = parseApiCall(assistantEntry('m1', ['tu1', 'tu2']), map)
expect(call).not.toBeNull()
expect(call!.locAdded).toBe(2)
expect(call!.locRemoved).toBe(1)
expect(call!.toolErrors).toBe(1)
expect(call!.interrupted).toBe(true)
expect(call!.userModified).toBe(true)
})
it('omits all rich fields when no meta map is supplied', () => {
const call = parseApiCall(assistantEntry('m1', ['tu1']))
expect(call!.locAdded).toBeUndefined()
expect(call!.locRemoved).toBeUndefined()
expect(call!.toolErrors).toBeUndefined()
expect(call!.interrupted).toBeUndefined()
expect(call!.userModified).toBeUndefined()
})
it('omits fields when the map has no matching tool_use id', () => {
const map = new Map<string, ToolResultMeta>()
collectToolResultMeta(toolResultEntry({ toolUseId: 'other', structuredPatch: [{ lines: ['+a'] }] }), map)
const call = parseApiCall(assistantEntry('m1', ['tu1']), map)
expect(call!.locAdded).toBeUndefined()
expect(call!.toolErrors).toBeUndefined()
})
it('counts is_error but not a non-error result with stderr', () => {
// Bash results carry stderr for warnings; only is_error marks a real failure.
const map = new Map<string, ToolResultMeta>()
collectToolResultMeta(toolResultEntry({ toolUseId: 'tu1', isError: false }), map)
const call = parseApiCall(assistantEntry('m1', ['tu1']), map)
expect(call!.toolErrors).toBeUndefined()
})
})
// ── gitBranch representation (per-turn dedup) ──────────────────────────
function userText(text: string, branch: string, sessionId = 's1'): JournalEntry {
return { type: 'user', timestamp: '2026-07-01T10:00:00Z', sessionId, gitBranch: branch, message: { role: 'user', content: text } }
}
function assistant(id: string, branch: string, sessionId = 's1'): JournalEntry {
return {
type: 'assistant', timestamp: '2026-07-01T10:00:02Z', sessionId, gitBranch: branch,
message: { type: 'message', role: 'assistant', model: 'claude-sonnet-4-20250514', id, content: [], usage: { input_tokens: 5, output_tokens: 5 } },
}
}
describe('gitBranch capture + dedup', () => {
it('stores the branch once for a single-branch session', () => {
const entries = [
userText('first', 'main'), assistant('m1', 'main'),
userText('second', 'main'), assistant('m2', 'main'),
]
const turns = groupIntoTurns(entries, new Set())
expect(turns.map(t => t.gitBranch)).toEqual(['main', 'main'])
const cached = parsedTurnsToCachedTurns(turns)
// First turn stores 'main'; second inherits (no stored branch).
expect(cached[0]!.gitBranch).toBe('main')
expect(cached[1]!.gitBranch).toBeUndefined()
})
it('re-stores the branch at a mid-session switch', () => {
const entries = [
userText('a', 'main'), assistant('m1', 'main'),
userText('b', 'feature/x'), assistant('m2', 'feature/x'),
userText('c', 'feature/x'), assistant('m3', 'feature/x'),
userText('d', 'main'), assistant('m4', 'main'),
]
const turns = groupIntoTurns(entries, new Set())
expect(turns.map(t => t.gitBranch)).toEqual(['main', 'feature/x', 'feature/x', 'main'])
const cached = parsedTurnsToCachedTurns(turns)
expect(cached.map(t => t.gitBranch)).toEqual(['main', 'feature/x', undefined, 'main'])
})
})
// ── per-turn PR references (prRefs) ────────────────────────────────────
function prLink(url: string, sessionId = 's1'): JournalEntry {
return { type: 'pr-link', timestamp: '2026-07-01T10:00:03Z', sessionId, prUrl: url } as JournalEntry
}
describe('pr-link capture + per-turn prRefs', () => {
it('attaches a PR referenced during a turn to that turn, and it survives caching', () => {
const entries = [
userText('open a PR', 'main'), assistant('m1', 'main'),
prLink('https://github.com/o/r/pull/1'),
userText('next task', 'main'), assistant('m2', 'main'),
]
const turns = groupIntoTurns(entries, new Set())
expect(turns[0]!.prRefs).toEqual(['https://github.com/o/r/pull/1'])
expect(turns[1]!.prRefs).toBeUndefined()
const cached = parsedTurnsToCachedTurns(turns)
// Stored per-turn directly (no change-detection dedup like gitBranch).
expect(cached[0]!.prRefs).toEqual(['https://github.com/o/r/pull/1'])
expect(cached[1]!.prRefs).toBeUndefined()
})
it('sorts and dedupes multiple refs within one merge-sweep turn', () => {
const entries = [
userText('merge sweep', 'main'), assistant('m1', 'main'),
prLink('https://github.com/o/r/pull/2'),
prLink('https://github.com/o/r/pull/1'),
prLink('https://github.com/o/r/pull/2'),
]
const turns = groupIntoTurns(entries, new Set())
expect(turns[0]!.prRefs).toEqual([
'https://github.com/o/r/pull/1',
'https://github.com/o/r/pull/2',
])
})
})
// ── session meta: ai-title last-wins, pr-link accumulation ─────────────
describe('collectSessionMeta', () => {
it('keeps the LAST ai-title and accumulates unique pr-link URLs', () => {
const meta = emptySessionMeta()
collectSessionMeta({ type: 'ai-title', aiTitle: 'first title' } as JournalEntry, meta)
collectSessionMeta({ type: 'pr-link', prUrl: 'https://github.com/o/r/pull/1' } as JournalEntry, meta)
collectSessionMeta({ type: 'ai-title', aiTitle: 'final title' } as JournalEntry, meta)
collectSessionMeta({ type: 'pr-link', prUrl: 'https://github.com/o/r/pull/1' } as JournalEntry, meta)
collectSessionMeta({ type: 'pr-link', prUrl: 'https://github.com/o/r/pull/2' } as JournalEntry, meta)
collectSessionMeta({ type: 'user', isSidechain: true } as JournalEntry, meta)
expect(meta.title).toBe('final title')
expect(meta.prLinks).toEqual([
'https://github.com/o/r/pull/1',
'https://github.com/o/r/pull/2',
])
expect(meta.isSidechain).toBe(true)
})
it('leaves fields empty for a session with no meta entries', () => {
const meta = emptySessionMeta()
collectSessionMeta({ type: 'user', message: { role: 'user', content: 'hi' } } as JournalEntry, meta)
expect(meta.title).toBeUndefined()
expect(meta.prLinks).toEqual([])
expect(meta.isSidechain).toBe(false)
expect(meta.parentSessionId).toBeUndefined()
expect(meta.agentSpawnLinks).toEqual({})
})
})
// ── subagent linkage: parentSessionId + agentSpawnLinks ────────────────
describe('collectSessionMeta subagent linkage', () => {
it("captures a sidechain's parent id from its internal sessionId (first wins)", () => {
const meta = emptySessionMeta()
collectSessionMeta({ type: 'user', isSidechain: true, sessionId: 'parent-1' } as JournalEntry, meta)
// A later entry restating a different id must not override the first capture.
collectSessionMeta({ type: 'assistant', isSidechain: true, sessionId: 'parent-2' } as JournalEntry, meta)
expect(meta.isSidechain).toBe(true)
expect(meta.parentSessionId).toBe('parent-1')
})
it('maps agentId -> spawn tool_use id from a spawn result (toolUseResult.agentId)', () => {
const meta = emptySessionMeta()
const spawnResult = {
type: 'user',
message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'toolu_spawn1', content: 'agent output' }] },
toolUseResult: { status: 'completed', agentId: 'a17e80ec626c9de38' },
} as JournalEntry
collectSessionMeta(spawnResult, meta)
expect(meta.agentSpawnLinks).toEqual({ a17e80ec626c9de38: 'toolu_spawn1' })
// A non-agent tool_result (no toolUseResult.agentId) adds nothing.
collectSessionMeta({
type: 'user',
message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'toolu_edit', content: 'x' }] },
toolUseResult: { structuredPatch: [] },
} as JournalEntry, meta)
expect(meta.agentSpawnLinks).toEqual({ a17e80ec626c9de38: 'toolu_spawn1' })
})
it('pairs the agentId with the matching block when a record batches several results (unrelated block first)', () => {
const meta = emptySessionMeta()
collectSessionMeta({
type: 'user',
message: { role: 'user', content: [
{ type: 'tool_result', tool_use_id: 'toolu_unrelated', content: 'a bash result' },
{ type: 'tool_result', tool_use_id: 'toolu_spawn', content: 'agent output' },
] },
// The result's content identifies the spawn block, so the FIRST (unrelated)
// block must not capture the agentId.
toolUseResult: { status: 'completed', agentId: 'a999', content: 'agent output' },
} as JournalEntry, meta)
expect(meta.agentSpawnLinks).toEqual({ a999: 'toolu_spawn' })
})
it('omits the spawn link (deferring to the timestamp fallback) when blocks are ambiguous', () => {
const meta = emptySessionMeta()
collectSessionMeta({
type: 'user',
// Two tool_result blocks with IDENTICAL content: the content match cannot
// pick one, so the link is omitted on purpose (resolveChild's timestamp
// fallback then folds the child rather than risking the wrong id).
message: { role: 'user', content: [
{ type: 'tool_result', tool_use_id: 'toolu_a', content: 'same' },
{ type: 'tool_result', tool_use_id: 'toolu_b', content: 'same' },
] },
toolUseResult: { status: 'completed', agentId: 'a777', content: 'same' },
} as JournalEntry, meta)
expect(meta.agentSpawnLinks).toEqual({}) // no guess
// But we KNOW a777 was spawned here, so it is recorded as an ambiguous pairing.
expect(meta.ambiguousSpawnAgentIds).toEqual(['a777'])
})
})
// ── per-turn subagent spawn ids (spawnToolUseIds) ──────────────────────
function spawnAssistant(id: string, blocks: Array<{ id: string; name: string }>): JournalEntry {
return {
type: 'assistant', timestamp: '2026-07-01T10:00:02Z', sessionId: 's1', gitBranch: 'main',
message: {
type: 'message', role: 'assistant', model: 'claude-sonnet-4-20250514', id,
content: blocks.map(b => ({ type: 'tool_use' as const, id: b.id, name: b.name, input: {} })),
usage: { input_tokens: 5, output_tokens: 5 },
},
}
}
describe('per-turn spawnToolUseIds capture', () => {
it('records only Agent/Task spawn ids per turn and survives caching', () => {
const entries = [
userText('launch reviewers', 'main'),
spawnAssistant('m1', [
{ id: 'toolu_agent', name: 'Agent' },
{ id: 'toolu_task', name: 'Task' },
{ id: 'toolu_edit', name: 'Edit' }, // not a spawn -> excluded
]),
userText('unrelated turn', 'main'), assistant('m2', 'main'),
]
const turns = groupIntoTurns(entries, new Set())
expect(turns[0]!.spawnToolUseIds).toEqual(['toolu_agent', 'toolu_task'])
expect(turns[1]!.spawnToolUseIds).toBeUndefined()
const cached = parsedTurnsToCachedTurns(turns)
expect(cached[0]!.spawnToolUseIds).toEqual(['toolu_agent', 'toolu_task'])
expect(cached[1]!.spawnToolUseIds).toBeUndefined()
})
})
describe('buildSpawnPrSets', () => {
it('maps each spawn id to the PR set active at its turn, carrying refs forward', () => {
const sets = buildSpawnPrSets([
{ spawnToolUseIds: ['s0'] }, // before any PR -> empty
{ prRefs: ['pr/A'], spawnToolUseIds: ['s1'] }, // spawn under A
{ spawnToolUseIds: ['s2'] }, // carries A
{ prRefs: ['pr/B'], spawnToolUseIds: ['s3'] }, // spawn under B
])
expect(sets).toEqual({ s0: [], s1: ['pr/A'], s2: ['pr/A'], s3: ['pr/B'] })
})
it('first occurrence of a spawn id wins deterministically', () => {
const sets = buildSpawnPrSets([
{ prRefs: ['pr/A'], spawnToolUseIds: ['dup'] },
{ prRefs: ['pr/B'], spawnToolUseIds: ['dup'] }, // restatement must not overwrite
])
expect(sets['dup']).toEqual(['pr/A'])
})
})