Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
41 changes: 37 additions & 4 deletions lib/claude-public-transcript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,33 @@ const object = (value: unknown): value is Record<string, any> =>
const validTimestamp = (value: unknown): value is string =>
typeof value === 'string' && Number.isFinite(Date.parse(value));

/** Claude Code parents the first user message on the SessionStart hook
* attachments it writes at startup, chained from a null root. That preamble
* carries no conversation, so it stands in for a null parent and nothing else:
* returns the UUIDs of same-session, same-cwd SessionStart attachments whose
* whole chain reaches a null root through other such attachments. */
function sessionStartPreamble(records: unknown[], cwd: string, filename: string): Set<string> {
const uuid = (value: unknown): value is string => typeof value === 'string' &&
/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value);
const hooks = new Map<string, Record<string, any>>();
for (const r of records) {
if (!object(r) || filename !== `${r.sessionId}.jsonl` || r.agentId != null || r.isSidechain !== false ||
r.type !== 'attachment' || r.message != null || r.cwd !== cwd || !uuid(r.uuid) ||
!validTimestamp(r.timestamp) || !object(r.attachment) || r.attachment.hookEvent !== 'SessionStart' ||
(r.parentUuid !== null && !uuid(r.parentUuid))) continue;
if (hooks.has(r.uuid)) return new Set();
hooks.set(r.uuid, r);
}
const admitted = new Set<string>();
for (const id of hooks.keys()) {
const seen = new Set<string>();
let hook = hooks.get(id);
while (hook && hook.parentUuid !== null && !seen.has(hook.uuid)) { seen.add(hook.uuid); hook = hooks.get(hook.parentUuid); }
if (hook?.parentUuid === null) admitted.add(id);
}
return admitted;
}

/** Read one length-delimited protobuf field, rejecting malformed/ambiguous input. */
function signatureField(bytes: Uint8Array | undefined, wanted: number): Uint8Array | undefined {
if (!bytes) return;
Expand Down Expand Up @@ -166,6 +193,8 @@ function ownedCausalLines(lines: string[], cwd: string, filename: string): strin
const parent = (r: Record<string, any>): string | undefined => uuid(r.parentUuid) ? r.parentUuid :
r.parentUuid === null && r.type === 'system' && r.subtype === 'compact_boundary' &&
r.message == null && uuid(r.logicalParentUuid) ? r.logicalParentUuid : undefined;
const preamble = sessionStartPreamble(scoped.map(x => x.record), cwd, filename);
const rooted = (r: Record<string, any>) => r.parentUuid === null || preamble.has(r.parentUuid);
// Anchor through the first observed conversation node, never an unrelated
// later root. An unflushed/malformed ancestor supplies no ownership.
let root = first;
Expand All @@ -174,14 +203,14 @@ function ownedCausalLines(lines: string[], cwd: string, filename: string): strin
if (ancestry.has(root.record.uuid)) throw Error('cyclic owned native ancestry');
ancestry.add(root.record.uuid);
const id = parent(root.record);
if (!id) break;
if (!id || preamble.has(id)) break;
const next = byId.get(id);
if (!next) return [];
root = next;
}
if (root.record.parentUuid !== null || root.record.cwd !== cwd ||
if (!rooted(root.record) || root.record.cwd !== cwd ||
!object(root.record.message) || root.record.message.role !== 'user') return [];
if (nodes.some(x => x !== root && x.record.parentUuid === null &&
if (nodes.some(x => x !== root && rooted(x.record) &&
object(x.record.message) && x.record.message.role === 'user')) throw Error('competing owned native roots');
// Stable topological traversal preserves physical order whenever two ready
// records have no parent dependency. No timestamp provides ordering credit.
Expand Down Expand Up @@ -276,6 +305,9 @@ export function readPlanCountTranscript(configDir: string, cwd: string,
}
return causalMembership.has(id);
};
let preamble: Set<string> | undefined;
const preambleHas = (id: string) => (preamble ??= sessionStartPreamble(
completeLines.flatMap(line => line.trim() ? [JSON.parse(line)] : []), cwd, entry.name)).has(id);
for (const line of ownedSnapshot ? ownedCausalLines(completeLines, cwd, entry.name) : completeLines) {
if (!line.trim()) continue;
const record = JSON.parse(line);
Expand All @@ -295,7 +327,8 @@ export function readPlanCountTranscript(configDir: string, cwd: string,
if (!originSeen && object(record.message) && ['user', 'assistant'].includes(record.message.role)) {
originSeen = true;
if (parentMetadata && record.cwd === cwd && record.message.role === 'user' &&
record.parentUuid === null) ancestry.add(record.uuid);
(record.parentUuid === null || (nativeUuid(record.parentUuid) && preambleHas(record.parentUuid))))
ancestry.add(record.uuid);
}
if (continuation) ancestry.add(record.uuid);
// Native compaction resets parentUuid but links its prior owned
Expand Down
86 changes: 86 additions & 0 deletions test/plan-count-sessionstart-preamble.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import {afterEach, expect, test} from 'bun:test';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {readPlanCountTranscript, readOwnedClaudePublicTranscript, type NativePublicToolEvent} from '../lib/claude-public-transcript';

// At startup Claude Code writes a chain of SessionStart hook attachments from a
// null root, and parents the first user message on the last of them.
const dirs:string[]=[];
afterEach(()=>{for(const d of dirs.splice(0))fs.rmSync(d,{recursive:true,force:true});});
const uuid=(n:number)=>`00000000-0000-4000-8000-${String(n).padStart(12,'0')}`;
const sid='session-owned',cwd='/fixture/repo',time='2026-09-30T20:13:09.603Z';
const base=(n:number,parent:number|null)=>({sessionId:sid,cwd,isSidechain:false,uuid:uuid(n),
parentUuid:parent===null?null:uuid(parent),timestamp:time});
const hook=(n:number,parent:number|null)=>({...base(n,parent),type:'attachment',
attachment:{type:'hook_success',hookName:'SessionStart:startup',hookEvent:'SessionStart',exitCode:0}});
const msg=(n:number,parent:number|null,role:string,content:any)=>({...base(n,parent),type:role,message:{role,content}});
const autoplan='<command-message>autoplan</command-message>\n<command-name>/autoplan</command-name>';
function conversation(parent:number|null):any[]{return [
{...msg(10,parent,'user',autoplan),origin:{kind:'human'},promptId:uuid(80)},
msg(11,10,'assistant',[{type:'tool_use',id:'read-owned',name:'Read',input:{file_path:'/fixture/plan.md'}}]),
msg(12,11,'user',[{type:'tool_result',tool_use_id:'read-owned',content:'Plan.'}]),
];}
const preamble=()=>[hook(1,null),hook(2,1),hook(3,2)];
const withPreamble=()=>[...preamble(),...conversation(3)];
function write(records:any[]){
const config=fs.mkdtempSync(path.join(os.tmpdir(),'sessionstart-'));dirs.push(config);
const project=path.join(config,'projects','owned');fs.mkdirSync(project,{recursive:true});
const file=path.join(project,sid+'.jsonl');
fs.writeFileSync(file,records.map(r=>JSON.stringify(r)).join('\n')+'\n');
return {config,file};
}
function legacy(records:any[]){
const {config}=write(records);const events:NativePublicToolEvent[]=[];
readPlanCountTranscript(config,cwd,e=>events.push(e));return events;
}
const owned=(records:any[])=>readOwnedClaudePublicTranscript(write(records).file,cwd,sid);
const uses=(events:{kind:string}[])=>events.filter(e=>e.kind==='use'||e.kind==='result').length;

test('a SessionStart hook preamble is transparent to session ownership',()=>{
const plain=owned(conversation(null)),hooked=owned(withPreamble());
expect(hooked.transcript.status).toBe('ready');
expect(hooked).toEqual(plain);
expect(hooked.events.find(e=>e.kind==='user_turn')).toMatchObject({autoplan:true});
expect(legacy(withPreamble())).toEqual(legacy(conversation(null)));
expect(uses(legacy(withPreamble()))).toBe(2);
});
test('the scan keeps following the session across a cwd change after the preamble',()=>{

expect(uses(legacy(moved(withPreamble())))).toBe(2);
expect(uses(owned(moved(withPreamble())).events)).toBe(2);
});
test('a preamble flushed after its child keeps ownership',()=>{
const r=withPreamble();expect(owned([r[3],r[2],r[0],r[1],...r.slice(4)])).toEqual(owned(r));
});

for(const [name,change] of Object.entries({
'non-SessionStart hook':(r:any[])=>r[1].attachment.hookEvent='UserPromptSubmit',
'attachment without hook event':(r:any[])=>delete r[1].attachment,
'assistant anchored on the preamble':(r:any[])=>r[1].message={role:'assistant',content:[]},
'foreign preamble cwd':(r:any[])=>r[1].cwd='/another/fixture',
'sidechain preamble':(r:any[])=>r[1].isSidechain=true,
'agent preamble':(r:any[])=>r[1].agentId='reviewer-child',
'foreign preamble session':(r:any[])=>r[1].sessionId='foreign-session',
'dangling preamble root':(r:any[])=>r[0].parentUuid=uuid(99),
'missing preamble link':(r:any[])=>r.splice(1,1),
'cyclic preamble':(r:any[])=>r[0].parentUuid=uuid(3),
'competing root on the preamble':(r:any[])=>r.push({...msg(20,3,'user','second root')}),
'competing null root':(r:any[])=>r.push({...msg(21,null,'user','second root')}),
})) test(`${name} supplies no ownership`,()=>{
const r=withPreamble();change(r);
expect(uses(owned(r).events)).toBe(0);
});

const moved=(r:any[])=>{for(const x of r.slice(-2))x.cwd='/fixture/elsewhere';return r;};
for(const [name,change] of Object.entries({
'non-SessionStart hook':(r:any[])=>r[1].attachment.hookEvent='UserPromptSubmit',
'foreign preamble cwd':(r:any[])=>r[1].cwd='/another/fixture',
'sidechain preamble':(r:any[])=>r[1].isSidechain=true,
'agent preamble':(r:any[])=>r[1].agentId='reviewer-child',
'foreign preamble session':(r:any[])=>r[1].sessionId='foreign-session',
'dangling preamble root':(r:any[])=>r[0].parentUuid=uuid(99),
'cyclic preamble':(r:any[])=>r[0].parentUuid=uuid(3),
})) test(`${name} cannot carry the scan across a cwd change`,()=>{
const r=moved(withPreamble());change(r);expect(uses(legacy(r))).toBe(0);
});