File size: 163,493 Bytes
4e23b01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { execFile } from 'node:child_process';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';

import {
  INTERACTION_TAG_SESSION_ID,
  IAgentLifecycleService,
  IAgentContextMemoryService,
  IAgentConversationUndoParticipantRegistry,
  IAgentLoopService,
  IAgentScopeContext,
  IAgentTaskService,
  IEventBus,
  IFlagService,
  ISessionIndex,
  ISessionMetadata,
  ISessionLifecycleService,
  ISessionManager,
  IWorkspaceInstanceManager,
  LifecycleScope,
  interactions,
  makeAgentScopeContext,
  type AgentContext,
  type ContextMessage,
  type AgentConversationUndoParticipant,
  type Event2,
  TOWER_FLAG_ID,
  _setTowerFeatureAssembledForTests,
  type ISessionScopeHandle,
  type Scope,
} from '@moonshot-ai/agent-core-v2';

import { TowerStore } from '@moonshot-ai/agent-core-v2/features/tower/protocol/index';
import {
  AgentTranscript,
  TranscriptStore,
  type AgentTranscriptSnapshot,
  type AppendOp,
  type FrameUpsertOp,
  type InteractionUpsertOp,
  type TranscriptFrame,
  type TranscriptOperation,
  type TranscriptTask,
  type TranscriptTurn,
} from '@moonshot-ai/transcript';
import { afterEach, describe, expect, it, vi } from 'vitest';

import { bindSessionTranscript } from '../../src/services/transcript/coreBinding';
import { toWireQuestion } from '../../src/protocol/question-wire';
import type { AgentActivitySnapshot } from '@moonshot-ai/agent-core-v2/agent/loop/loop';
import type { LegacyActivityApproval } from '../../src/services/legacyStatus/legacyStatus';
import {
  AgentTranscriptProjector,
  type ProjectorBusEvent,
} from '../../src/services/transcript/coreEventMap';
import {
  healTurnOps,
  TranscriptService,
  snapshotToOps,
  TRANSCRIPT_OPS_JOURNAL_CAPACITY,
} from '../../src/services/transcript/transcriptService';

_setTowerFeatureAssembledForTests(true);

const execFileAsync = promisify(execFile);

function ev(payload: Record<string, unknown>): ProjectorBusEvent {
  return payload as unknown as ProjectorBusEvent;
}

const TEST_SESSION_ID = 'session-test';

function turnOps(turnId: string, items: ReturnType<AgentTranscript['getItems']>): TranscriptTurn {
  const turn = items.find(
    (item): item is TranscriptTurn => item.kind === 'turn' && item.turnId === turnId,
  );
  if (turn === undefined) throw new Error(`turn ${turnId} not found`);
  return turn;
}

function coldTranscriptService(home: string): TranscriptService {
  return new TranscriptService({
    homeDir: home,
    core: {
      accessor: {
        get: (token: unknown) => {
          if (token === ISessionManager) return { get: () => undefined, list: () => [] };
          if (token === IWorkspaceInstanceManager) {
            return { list: () => [], onDidChange: () => ({ dispose: () => undefined }) };
          }
          if (token === ISessionIndex) return { get: async () => ({ workspaceId: 'ws' }) };
          return undefined;
        },
      },
    } as unknown as Scope,
  });
}

describe('AgentTranscriptProjector', () => {
  it('keeps cron steers grouped while undo removes only the appropriate suffix', async () => {
    const home = await mkdtemp(join(tmpdir(), 'transcript-cron-undo-'));
    const wireDir = join(home, 'sessions', 'ws', 's1', 'agents', 'main');
    const append = (role: string, text: string, kind?: string) => ({
      type: 'context.append_message',
      message: { role, content: [{ type: 'text', text }], toolCalls: [], origin: kind === undefined ? undefined : { kind } },
    });
    const steer = (text: string) => ({ type: 'turn.steer', input: [{ type: 'text', text }], origin: { kind: 'cron_job' } });
    const records: Record<string, unknown>[] = [
      append('user', 'first prompt', 'user'),
      append('assistant', 'first answer'),
      steer('retained cron'),
      append('user', 'retained cron', 'cron_job'),
      append('assistant', 'cron answer'),
      append('user', 'second prompt', 'user'),
      steer('removed cron'),
      append('user', 'removed cron', 'cron_job'),
      append('assistant', 'second answer'),
    ];
    try {
      await mkdir(wireDir, { recursive: true });
      const service = coldTranscriptService(home);
      const read = async () => {
        await writeFile(join(wireDir, 'wire.jsonl'), records.map((record) => JSON.stringify(record)).join('\n') + '\n');
        return (await service.readColdSnapshot('s1', 'main'))!.items.filter((item) => item.kind === 'turn');
      };
      const before = await read();
      expect(before.map((turn) => turn.prompt)).toEqual(['first prompt', 'second prompt']);
      records.push({ type: 'context.undo', count: 1 });
      const after = await read();
      expect(after.map((turn) => turn.prompt)).toEqual(['first prompt']);
      expect(after[0]!.steps.flatMap((step) => step.frames).filter((frame) => frame.kind === 'text').map((frame) => frame.text)).toEqual(['first answer', 'retained cron', 'cron answer']);
      records.push(append('user', 'removed cron', 'cron_job'), append('assistant', 'new cron answer'));
      expect((await read()).map((turn) => turn.prompt)).toEqual(['first prompt', 'removed cron']);
    } finally {
      await rm(home, { recursive: true, force: true });
    }
  });

  it('projects a full turn: headers, delta appends, flush, tool frames', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const ops: TranscriptOperation[] = [];
    const feed = (event: ProjectorBusEvent): void => {
      const mapped = projector.map(event);
      ops.push(...mapped);
      tx.apply(mapped);
    };

    feed(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'user' } }));
    feed(ev({ type: 'turn.step.started', turnId: 1, step: 1, stepId: 'u1' }));
    feed(ev({ type: 'assistant.delta', turnId: 1, delta: 'Hello' }));
    feed(ev({ type: 'assistant.delta', turnId: 1, delta: ' world' }));
    feed(
      ev({
        type: 'tool.call.started',
        turnId: 1,
        toolCallId: 'call_1',
        name: 'Bash',
        args: '{"command":"ls"}',
        display: { kind: 'command', command: 'ls' },
      }),
    );
    feed(ev({ type: 'tool.result', turnId: 1, toolCallId: 'call_1', output: 'file.txt' }));
    feed(ev({ type: 'turn.step.completed', turnId: 1, step: 1, stepId: 'u1' }));
    feed(ev({ type: 'turn.ended', turnId: 1, reason: 'completed' }));

    const appends = ops.filter((op): op is AppendOp => op.op === 'append');
    expect(appends.map((op) => [op.offset, op.text])).toEqual([
      [0, 'Hello'],
      [5, ' world'],
    ]);
    const upserts = ops.filter((op): op is FrameUpsertOp => op.op === 'frame.upsert');
    const flushUpsert = upserts.find(
      (op) => op.frame.kind === 'text' && op.frame.text === 'Hello world',
    );
    expect(flushUpsert).toBeDefined();

    const turn = turnOps('t1', tx.getItems());
    expect(turn.state).toBe('completed');
    expect(turn.origin).toEqual({ kind: 'user', payload: { kind: 'user' } });
    expect(turn.endedAt).toBeTypeOf('string');
    expect(turn.steps).toHaveLength(1);
    const step = turn.steps[0]!;
    expect(step.state).toBe('completed');
    const text = step.frames.find((frame) => frame.kind === 'text');
    expect(text).toMatchObject({ role: 'assistant', text: 'Hello world' });
    const tool = step.frames.find((frame) => frame.kind === 'tool');
    expect(tool).toMatchObject({
      frameId: 't1.1.call_1',
      toolCallId: 'call_1',
      name: 'Bash',
      state: 'done',
      input: { command: 'ls' },
      output: 'file.txt',
      display: { kind: 'command', command: 'ls' },
    });
  });

  it('projects the live prompt from turn.started and keeps it through turn.ended', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => {
      tx.apply(projector.map(event));
    };

    feed(ev({
      type: 'turn.started',
      turnId: 0,
      promptId: 'prompt-1',
      origin: { kind: 'user' },
      prompt: 'fix the bug',
    }));
    feed(ev({ type: 'assistant.delta', turnId: 0, delta: 'on it' }));
    feed(ev({ type: 'turn.ended', turnId: 0, reason: 'completed' }));

    const turn = turnOps('t0', tx.getItems());
    expect(turn.triggerPromptId).toBe('prompt-1');
    expect(turn.prompt).toBe('fix the bug');
    expect(turn.state).toBe('completed');
  });

  it('projects the live prompt for subagent system triggers and keeps it through turn.ended', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => {
      tx.apply(projector.map(event));
    };

    feed(
      ev({
        type: 'turn.started',
        turnId: 0,
        origin: { kind: 'system_trigger', name: 'subagent' },
        prompt: 'scan the repo',
        promptAttachments: [{ kind: 'image', fileId: 'file_1' }],
      }),
    );
    feed(ev({ type: 'assistant.delta', turnId: 0, delta: 'scanning' }));
    feed(ev({ type: 'turn.ended', turnId: 0, reason: 'completed' }));

    const turn = turnOps('t0', tx.getItems());
    expect(turn.prompt).toBe('scan the repo');
    expect(turn.attachmentIds).toEqual(['t0.att1']);
    expect(turn.state).toBe('completed');
  });

  it('projects turn.started promptAttachments into attachment entities and turn.attachmentIds', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const ops: TranscriptOperation[] = [];
    const feed = (event: ProjectorBusEvent): void => {
      const mapped = projector.map(event);
      ops.push(...mapped);
      tx.apply(mapped);
    };

    feed(
      ev({
        type: 'turn.started',
        turnId: 0,
        origin: { kind: 'user' },
        prompt: 'what is this?',
        promptAttachments: [{ kind: 'image', fileId: 'file_1', name: 'photo.png' }],
      }),
    );
    feed(ev({ type: 'turn.ended', turnId: 0, reason: 'completed' }));

    expect(ops.filter((op) => op.op === 'attachment.upsert')).toEqual([
      {
        op: 'attachment.upsert',
        attachment: {
          attachmentId: 't0.att1',
          mediaType: 'image/*',
          name: 'photo.png',
          source: { kind: 'session_media', fileId: 'file_1' },
        },
      },
    ]);

    const turn = turnOps('t0', tx.getItems());
    expect(turn.prompt).toBe('what is this?');
    expect(turn.attachmentIds).toEqual(['t0.att1']);
    expect(tx.getAttachment('t0.att1')).toEqual({
      attachmentId: 't0.att1',
      mediaType: 'image/*',
      name: 'photo.png',
      source: { kind: 'session_media', fileId: 'file_1' },
    });
  });

  it('projects turn.started file promptAttachments into path-sourced attachment entities', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const ops: TranscriptOperation[] = [];
    const feed = (event: ProjectorBusEvent): void => {
      const mapped = projector.map(event);
      ops.push(...mapped);
      tx.apply(mapped);
    };

    feed(
      ev({
        type: 'turn.started',
        turnId: 0,
        origin: { kind: 'user' },
        prompt: 'summarize this',
        promptAttachments: [
          {
            kind: 'file',
            name: 'report.pdf',
            mediaType: 'application/pdf',
            size: 1234,
            path: '/data/report.pdf',
          },
        ],
      }),
    );
    feed(ev({ type: 'turn.ended', turnId: 0, reason: 'completed' }));

    expect(ops.filter((op) => op.op === 'attachment.upsert')).toEqual([
      {
        op: 'attachment.upsert',
        attachment: {
          attachmentId: 't0.att1',
          mediaType: 'application/pdf',
          name: 'report.pdf',
          size: 1234,
        },
      },
    ]);

    const turn = turnOps('t0', tx.getItems());
    expect(turn.prompt).toBe('summarize this');
    expect(turn.attachmentIds).toEqual(['t0.att1']);
    expect(tx.getAttachment('t0.att1')).toEqual({
      attachmentId: 't0.att1',
      mediaType: 'application/pdf',
      name: 'report.pdf',
      size: 1234,
    });
  });

  it('places late-attach deltas into the engine-reported active step', () => {
    const tx = new AgentTranscript('main');
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID, {
      stepOrdinal: (turnId) => (turnId === 't0' ? 2 : undefined),
    });

    const ops = projector.map(ev({ type: 'assistant.delta', turnId: 0, delta: 'late' }));
    tx.apply(ops);

    const turn = turnOps('t0', tx.getItems());
    expect(turn.steps.map((s) => s.stepId)).toEqual(['t0.2']);
    expect(turn.steps[0]?.frames[0]).toMatchObject({ kind: 'text', text: 'late' });
  });

  it('adopts a backfilled stream frame on mid-turn attach instead of clobbering it', () => {
    const tx = new AgentTranscript('main');
    tx.apply([
      {
        op: 'turn.upsert',
        turn: { kind: 'turn', turnId: 't0', ordinal: 0, state: 'running', origin: { kind: 'user' } },
      },
      {
        op: 'step.upsert',
        turnId: 't0',
        step: { kind: 'step', stepId: 't0.1', turnId: 't0', ordinal: 1, state: 'running' },
      },
      {
        op: 'frame.upsert',
        turnId: 't0',
        stepId: 't0.1',
        frame: { kind: 'text', frameId: 't0.1.f1', role: 'assistant', text: 'Hello ' },
      },
    ]);
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID, {
      stepFrames: (turnId, stepId) =>
        tx.getTurn(turnId)?.steps.find((s) => s.stepId === stepId)?.frames,
    });

    const ops = projector.map(ev({ type: 'assistant.delta', turnId: 0, delta: 'world' }));
    tx.apply(ops);
    expect(ops.some((op) => op.op === 'frame.upsert')).toBe(false);
    const append = ops.find((op): op is AppendOp => op.op === 'append');
    expect(append && [append.offset, append.text]).toEqual([6, 'world']);
    const turn = turnOps('t0', tx.getItems());
    const text = turn.steps[0]?.frames.find((frame) => frame.kind === 'text');
    expect(text).toMatchObject({ text: 'Hello world' });

    const next = projector.map(ev({ type: 'thinking.delta', turnId: 0, delta: 'hmm' }));
    const created = next.find((op): op is FrameUpsertOp => op.op === 'frame.upsert');
    expect(created?.frame.frameId).toBe('t0.1.f2');
  });

  it('adopts a backfilled tool frame when the result arrives after a mid-bind attach', () => {
    const tx = new AgentTranscript('main');
    tx.apply([
      {
        op: 'turn.upsert',
        turn: { kind: 'turn', turnId: 't0', ordinal: 0, state: 'running', origin: { kind: 'user' } },
      },
      {
        op: 'step.upsert',
        turnId: 't0',
        step: { kind: 'step', stepId: 't0.1', turnId: 't0', ordinal: 1, state: 'running' },
      },
      {
        op: 'frame.upsert',
        turnId: 't0',
        stepId: 't0.1',
        frame: {
          kind: 'tool',
          frameId: 't0.1.call_1',
          toolCallId: 'call_1',
          name: 'Bash',
          state: 'running',
          input: { command: 'ls' },
        },
      },
    ]);
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID, {
      toolFrame: (toolCallId) => {
        for (const item of tx.getItems()) {
          if (item.kind !== 'turn') continue;
          for (const step of item.steps) {
            for (const frame of step.frames) {
              if (frame.kind === 'tool' && frame.toolCallId === toolCallId) {
                return { turnId: item.turnId, stepId: step.stepId, frame };
              }
            }
          }
        }
        return undefined;
      },
    });

    const ops = projector.map(ev({ type: 'tool.result', toolCallId: 'call_1', output: 'file.txt' }));
    expect(ops).toHaveLength(1);
    tx.apply(ops);
    const turn = turnOps('t0', tx.getItems());
    const tool = turn.steps[0]?.frames.find((frame) => frame.kind === 'tool');
    expect(tool).toMatchObject({ toolCallId: 'call_1', state: 'done', output: 'file.txt' });
  });

  it('adopts a seeded parent tool frame when subagent.spawned links the child', () => {
    const tx = new AgentTranscript('main');
    tx.apply([
      {
        op: 'turn.upsert',
        turn: { kind: 'turn', turnId: 't0', ordinal: 0, state: 'running', origin: { kind: 'user' } },
      },
      {
        op: 'step.upsert',
        turnId: 't0',
        step: { kind: 'step', stepId: 't0.1', turnId: 't0', ordinal: 1, state: 'running' },
      },
      {
        op: 'frame.upsert',
        turnId: 't0',
        stepId: 't0.1',
        frame: {
          kind: 'tool',
          frameId: 't0.1.call_agent',
          toolCallId: 'call_agent',
          name: 'Agent',
          state: 'running',
          input: { prompt: 'scan' },
        },
      },
    ]);
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID, {
      toolFrame: (toolCallId) => {
        for (const item of tx.getItems()) {
          if (item.kind !== 'turn') continue;
          for (const step of item.steps) {
            for (const frame of step.frames) {
              if (frame.kind === 'tool' && frame.toolCallId === toolCallId) {
                return { turnId: item.turnId, stepId: step.stepId, frame };
              }
            }
          }
        }
        return undefined;
      },
    });

    const ops = projector.map(
      ev({
        type: 'subagent.spawned',
        subagentId: 'agent-1',
        subagentName: 'explore',
        parentToolCallId: 'call_agent',
        runInBackground: false,
      }),
    );
    tx.apply(ops);
    const turn = turnOps('t0', tx.getItems());
    const tool = turn.steps[0]?.frames.find((frame) => frame.kind === 'tool');
    expect(tool?.kind === 'tool' && tool.agentRefs).toEqual([{ agentId: 'agent-1', role: 'child' }]);
  });

  it('gives live markers their own namespace so they never collide with backfilled markers', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    tx.apply([{ op: 'marker.upsert', item: { kind: 'marker', markerId: 'm1', marker: 'skill' } }]);

    const ops = projector.map(ev({ type: 'compaction.started', trigger: 'auto' }));
    tx.apply(ops);

    const markers = tx
      .getItems()
      .filter((item): item is Extract<typeof item, { kind: 'marker' }> => item.kind === 'marker');
    expect(markers.map((m) => [m.markerId, m.marker])).toEqual([
      ['m1', 'skill'],
      ['live-m1', 'compaction'],
    ]);
  });

  it('snapshotToOps anchors standalone items so backfill keeps history order against live turns', () => {
    const snapshot: AgentTranscriptSnapshot = {
      interactions: [],
      attachments: [],
      todos: [],
      prompts: [],
      items: [
        {
          kind: 'turn',
          turnId: 't0',
          ordinal: 0,
          state: 'completed',
          origin: { kind: 'user' },
          prompt: 'one',
          steps: [],
        },
        { kind: 'marker', markerId: 'm1', marker: 'skill' },
        {
          kind: 'turn',
          turnId: 't1',
          ordinal: 1,
          state: 'completed',
          origin: { kind: 'user' },
          prompt: 'two',
          steps: [],
        },
        { kind: 'taskref', refId: 'r1', taskId: 'bash-1' },
      ],
      tasks: [],
      meta: {},
    };
    const ops = snapshotToOps(snapshot);
    expect(ops.find((op) => op.op === 'marker.upsert')).toMatchObject({ beforeTurn: 1 });
    expect(ops.find((op) => op.op === 'taskref.upsert')).toMatchObject({ beforeTurn: 2 });

    const tx = new AgentTranscript('main');
    tx.apply([
      {
        op: 'turn.upsert',
        turn: { kind: 'turn', turnId: 't2', ordinal: 2, state: 'running', origin: { kind: 'user' } },
      },
    ]);
    tx.apply(ops);
    expect(
      tx.getItems().map((item) => {
        if (item.kind === 'turn') return item.turnId;
        if (item.kind === 'marker') return item.markerId;
        return item.refId;
      }),
    ).toEqual(['t0', 'm1', 't1', 'r1', 't2']);
  });

  it('snapshotToOps flattens attachment entities so backfilled attachmentIds never dangle', () => {
    const snapshot: AgentTranscriptSnapshot = {
      interactions: [],
      attachments: [
        {
          attachmentId: 'att_1',
          mediaType: 'image/*',
          name: 'shot.png',
          source: { kind: 'file', fileId: 'file_1' },
        },
      ],
      todos: [],
      prompts: [],
      items: [
        {
          kind: 'turn',
          turnId: 't0',
          ordinal: 0,
          state: 'completed',
          origin: { kind: 'user' },
          prompt: 'what is this?',
          attachmentIds: ['att_1'],
          steps: [],
        },
      ],
      tasks: [],
      meta: {},
    };

    const ops = snapshotToOps(snapshot);
    expect(ops.filter((op) => op.op === 'attachment.upsert')).toEqual([
      { op: 'attachment.upsert', attachment: snapshot.attachments[0] },
    ]);

    const tx = new AgentTranscript('main');
    tx.apply(ops);
    expect(tx.getAttachment('att_1')).toEqual(snapshot.attachments[0]);
    expect(turnOps('t0', tx.getItems()).attachmentIds).toEqual(['att_1']);
  });

  it('flushes open frames on turn.ended even without step completion', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'user' } }));
    feed(ev({ type: 'turn.step.started', turnId: 1, step: 1 }));
    feed(ev({ type: 'thinking.delta', turnId: 1, delta: 'hmm' }));
    feed(ev({ type: 'assistant.delta', turnId: 1, delta: 'partial' }));
    feed(ev({ type: 'turn.ended', turnId: 1, reason: 'cancelled' }));

    const turn = turnOps('t1', tx.getItems());
    expect(turn.state).toBe('cancelled');
    const step = turn.steps[0]!;
    expect(step.state).toBe('interrupted');
    expect(step.frames).toContainEqual(
      expect.objectContaining({ kind: 'thinking', text: 'hmm' }),
    );
    expect(step.frames).toContainEqual(
      expect.objectContaining({ kind: 'text', text: 'partial' }),
    );
  });

  it('marks a user-cancelled turn with an interruption marker, but not programmatic aborts', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'turn.started', turnId: 0, origin: { kind: 'user' }, prompt: 'hi' }));
    feed(
      ev({ type: 'turn.ended', turnId: 0, reason: 'cancelled', interruptReason: 'user_cancelled' }),
    );
    feed(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'user' }, prompt: 'again' }));
    feed(ev({ type: 'turn.ended', turnId: 1, reason: 'cancelled', interruptReason: 'aborted' }));
    feed(ev({ type: 'turn.started', turnId: 2, origin: { kind: 'user' }, prompt: 'legacy' }));
    feed(ev({ type: 'turn.ended', turnId: 2, reason: 'cancelled' }));

    const markers = tx
      .getItems()
      .filter((item): item is Extract<typeof item, { kind: 'marker' }> => item.kind === 'marker');
    expect(markers).toHaveLength(1);
    expect(markers[0]).toMatchObject({
      marker: 'interruption',
      payload: { turnId: 0, reason: 'user_cancelled' },
    });
  });

  it('carries usage / finishReason / the full timing breakdown on turn.step.completed', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'user' } }));
    feed(ev({ type: 'turn.step.started', turnId: 1, step: 1 }));
    feed(
      ev({
        type: 'turn.step.completed',
        turnId: 1,
        step: 1,
        usage: { inputOther: 100, output: 20, inputCacheRead: 30, inputCacheCreation: 40 },
        rawFinishReason: 'tool_calls',
        llmFirstTokenLatencyMs: 120,
        llmStreamDurationMs: 900,
        llmRequestBuildMs: 10,
        llmServerFirstTokenMs: 110,
        llmServerDecodeMs: 800,
        llmClientConsumeMs: 100,
        llmClientBlockedMs: 40,
      }),
    );

    const step = turnOps('t1', tx.getItems()).steps[0]!;
    expect(step.state).toBe('completed');
    expect(step.usage).toEqual({
      inputOther: 100,
      output: 20,
      inputCacheRead: 30,
      inputCacheCreation: 40,
    });
    expect(step.finishReason).toBe('tool_calls');
    expect(step.timing).toEqual({
      llmFirstTokenLatencyMs: 120,
      llmStreamDurationMs: 900,
      llmRequestBuildMs: 10,
      llmServerFirstTokenMs: 110,
      llmServerDecodeMs: 800,
      llmClientConsumeMs: 100,
      llmClientBlockedMs: 40,
    });

    feed(ev({ type: 'turn.step.started', turnId: 1, step: 2 }));
    feed(
      ev({
        type: 'turn.step.completed',
        turnId: 1,
        step: 2,
        finishReason: 'stop',
        rawFinishReason: 'raw_stop',
        providerFinishReason: 'provider_stop',
      }),
    );
    expect(turnOps('t1', tx.getItems()).steps[1]!.finishReason).toBe('stop');
    feed(ev({ type: 'turn.step.started', turnId: 1, step: 3 }));
    feed(
      ev({ type: 'turn.step.completed', turnId: 1, step: 3, providerFinishReason: 'length' }),
    );
    expect(turnOps('t1', tx.getItems()).steps[2]!.finishReason).toBe('length');
  });

  it('carries endReason / endMessage on turn.step.interrupted', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'user' } }));
    feed(ev({ type: 'turn.step.started', turnId: 1, step: 1 }));
    feed(
      ev({
        type: 'turn.step.interrupted',
        turnId: 1,
        step: 1,
        reason: 'aborted',
        message: 'user cancelled',
      }),
    );

    const step = turnOps('t1', tx.getItems()).steps[0]!;
    expect(step.state).toBe('interrupted');
    expect(step.endReason).toBe('aborted');
    expect(step.endMessage).toBe('user cancelled');
  });

  it('sets retry on turn.step.retrying and clears it at the terminal upsert', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));
    const step = (): TranscriptTurn['steps'][number] => turnOps('t1', tx.getItems()).steps[0]!;

    feed(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'user' } }));
    feed(ev({ type: 'turn.step.started', turnId: 1, step: 1 }));
    feed(
      ev({
        type: 'turn.step.retrying',
        turnId: 1,
        step: 1,
        failedAttempt: 1,
        nextAttempt: 2,
        maxAttempts: 3,
        delayMs: 2000,
        errorName: 'ProviderRateLimitError',
        errorMessage: '429 too many requests',
        statusCode: 429,
      }),
    );

    expect(step().state).toBe('running');
    expect(step().retry).toEqual({
      failedAttempt: 1,
      nextAttempt: 2,
      maxAttempts: 3,
      delayMs: 2000,
      errorName: 'ProviderRateLimitError',
      errorMessage: '429 too many requests',
      statusCode: 429,
    });

    feed(ev({ type: 'turn.step.completed', turnId: 1, step: 1 }));
    expect(step().state).toBe('completed');
    expect(step().retry).toBeUndefined();
  });

  it('fills durationMs / error / accumulated step usage on turn.ended', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'user' } }));
    feed(ev({ type: 'turn.step.started', turnId: 1, step: 1 }));
    feed(
      ev({
        type: 'turn.step.completed',
        turnId: 1,
        step: 1,
        usage: { inputOther: 100, output: 10, inputCacheRead: 5, inputCacheCreation: 50 },
      }),
    );
    feed(ev({ type: 'turn.step.started', turnId: 1, step: 2 }));
    feed(
      ev({
        type: 'turn.step.completed',
        turnId: 1,
        step: 2,
        usage: { inputOther: 200, output: 20, inputCacheRead: 0, inputCacheCreation: 25 },
      }),
    );
    feed(ev({ type: 'turn.ended', turnId: 1, reason: 'completed', durationMs: 4200 }));

    const turn = turnOps('t1', tx.getItems());
    expect(turn.durationMs).toBe(4200);
    expect(turn.usage).toEqual({ inputTokens: 375, cachedTokens: 5, outputTokens: 30 });

    feed(ev({ type: 'turn.started', turnId: 2, origin: { kind: 'user' } }));
    feed(
      ev({
        type: 'turn.ended',
        turnId: 2,
        reason: 'failed',
        durationMs: 50,
        error: { code: 'internal', message: 'kaboom', retryable: false },
      }),
    );
    const failed = turnOps('t2', tx.getItems());
    expect(failed.state).toBe('failed');
    expect(failed.error).toBe('kaboom');
    expect(failed.usage).toBeUndefined();
  });

  it('takes the turn header endedAt from the turn.ended event time', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'user' } }));
    feed(ev({ type: 'turn.ended', turnId: 1, reason: 'completed', time: 1_700_000_000_000 }));
    expect(turnOps('t1', tx.getItems()).endedAt).toBe(new Date(1_700_000_000_000).toISOString());

    feed(ev({ type: 'turn.started', turnId: 2, origin: { kind: 'user' } }));
    feed(ev({ type: 'turn.ended', turnId: 2, reason: 'completed' }));
    expect(turnOps('t2', tx.getItems()).endedAt).toBeTypeOf('string');
  });

  it('accumulates tool.call.delta into inputText, kept across tool.call.started', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));
    const toolFrame = (toolCallId: string): TranscriptFrame | undefined =>
      turnOps('t1', tx.getItems())
        .steps.flatMap((step) => step.frames)
        .find((frame) => frame.kind === 'tool' && frame.toolCallId === toolCallId);

    feed(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'user' } }));
    feed(ev({ type: 'turn.step.started', turnId: 1, step: 1 }));
    feed(
      ev({
        type: 'tool.call.delta',
        turnId: 1,
        toolCallId: 'c1',
        name: 'Bash',
        argumentsPart: '{"comm',
      }),
    );
    feed(ev({ type: 'tool.call.delta', turnId: 1, toolCallId: 'c1', argumentsPart: 'and":"ls"}' }));
    expect(toolFrame('c1')).toMatchObject({
      kind: 'tool',
      frameId: 't1.1.c1',
      name: 'Bash',
      state: 'running',
      inputText: '{"command":"ls"}',
    });
    feed(ev({ type: 'tool.call.delta', turnId: 1, toolCallId: 'c2', argumentsPart: '{}' }));
    expect(toolFrame('c2')).toMatchObject({ name: '', inputText: '{}' });

    feed(
      ev({
        type: 'tool.call.started',
        turnId: 1,
        toolCallId: 'c1',
        name: 'Bash',
        args: { command: 'ls' },
      }),
    );
    expect(toolFrame('c1')).toMatchObject({
      input: { command: 'ls' },
      inputText: '{"command":"ls"}',
    });
    feed(ev({ type: 'tool.call.delta', turnId: 1, toolCallId: 'c1', argumentsPart: '\n' }));
    expect(toolFrame('c1')).toMatchObject({ inputText: '{"command":"ls"}\n' });
    feed(ev({ type: 'tool.result', turnId: 1, toolCallId: 'c1', output: 'file.txt' }));
    expect(toolFrame('c1')).toMatchObject({ state: 'done', inputText: '{"command":"ls"}\n' });
  });

  it('overwrites tool frame progress and drops progress for unknown calls', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    expect(
      projector.map(
        ev({
          type: 'tool.progress',
          turnId: 1,
          toolCallId: 'ghost',
          update: { kind: 'stdout', text: 'x' },
        }),
      ),
    ).toEqual([]);

    feed(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'user' } }));
    feed(ev({ type: 'turn.step.started', turnId: 1, step: 1 }));
    feed(
      ev({ type: 'tool.call.started', turnId: 1, toolCallId: 'c1', name: 'Bash', args: {} }),
    );
    feed(
      ev({
        type: 'tool.progress',
        turnId: 1,
        toolCallId: 'c1',
        update: { kind: 'stdout', text: 'line1' },
      }),
    );
    const tool = (): TranscriptFrame | undefined =>
      turnOps('t1', tx.getItems()).steps[0]!.frames.find((frame) => frame.kind === 'tool');
    expect(tool()).toMatchObject({ progress: { kind: 'stdout', text: 'line1' } });

    feed(
      ev({
        type: 'tool.progress',
        turnId: 1,
        toolCallId: 'c1',
        update: { kind: 'progress', percent: 40 },
      }),
    );
    expect(tool()).toMatchObject({ progress: { kind: 'progress', percent: 40 } });
    expect((tool() as { progress?: Record<string, unknown> }).progress?.['text']).toBeUndefined();
  });

  it('marks tool.result errors and keeps the display payload', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'user' } }));
    feed(ev({ type: 'turn.step.started', turnId: 1, step: 1 }));
    feed(
      ev({
        type: 'tool.call.started',
        turnId: 1,
        toolCallId: 'c1',
        name: 'Read',
        args: { path: '/x' },
        display: { kind: 'file', path: '/x' },
      }),
    );
    feed(ev({ type: 'tool.result', turnId: 1, toolCallId: 'c1', output: 'ENOENT', isError: true }));

    const tool = turnOps('t1', tx.getItems()).steps[0]!.frames.find((f) => f.kind === 'tool');
    expect(tool).toMatchObject({
      state: 'error',
      output: 'ENOENT',
      error: 'ENOENT',
      display: { kind: 'file', path: '/x' },
    });
  });

  it('projects process tasks as shell tasks with streaming output', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const ops: TranscriptOperation[] = [];
    const feed = (event: ProjectorBusEvent): void => {
      const mapped = projector.map(event);
      ops.push(...mapped);
      tx.apply(mapped);
    };

    const started = {
      taskId: 'bash-1',
      kind: 'process',
      description: 'ls -la',
      status: 'running',
      detached: false,
      startedAt: 1_700_000_000_000,
      endedAt: null,
    };
    feed(ev({ type: 'task.started', info: started }));
    feed(ev({ type: 'shell.started', commandId: 'cmd-1', taskId: 'bash-1' }));
    feed(ev({ type: 'shell.output', commandId: 'cmd-1', update: { kind: 'stdout', text: 'a\n' } }));
    feed(ev({ type: 'shell.output', commandId: 'cmd-1', update: { kind: 'stderr', text: 'b\n' } }));
    feed(
      ev({
        type: 'task.terminated',
        info: { ...started, status: 'completed', endedAt: 1_700_000_001_000 },
      }),
    );

    expect(ops.some((op) => op.op === 'taskref.upsert' && op.item.taskId === 'bash-1')).toBe(true);
    const appends = ops.filter((op): op is AppendOp => op.op === 'append');
    expect(appends.map((op) => [op.offset, op.text])).toEqual([
      [0, 'a\n'],
      [2, 'b\n'],
    ]);

    const task = tx.getTask('bash-1');
    expect(task).toMatchObject({
      kind: 'shell',
      state: 'completed',
      detached: false,
      description: 'ls -la',
      outputTail: 'a\nb\n',
    });
    expect(
      projector.map(
        ev({ type: 'shell.output', commandId: 'cmd-1', update: { kind: 'progress', percent: 50 } }),
      ),
    ).toEqual([]);
  });

  it('fills the shell task output from late stderr chunks before completing', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');

    tx.apply(projector.map(ev({ type: 'shell.started', commandId: 'c1', taskId: 'task-1' })));
    tx.apply(
      projector.map(ev({ type: 'shell.output', commandId: 'c1', update: { kind: 'stderr', text: 'boom' } })),
    );
    tx.apply(projector.map(ev({ type: 'shell.completed', commandId: 'c1', isError: true })));

    expect(tx.getTask('task-1')).toMatchObject({ state: 'failed', outputTail: 'boom' });
  });

  it('routes shell output/completion via the event taskId when shell.started was missed', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');

    tx.apply(
      projector.map(
        ev({ type: 'shell.output', commandId: 'c1', taskId: 'task-1', update: { kind: 'stdout', text: 'hello' } }),
      ),
    );
    expect(tx.getTask('task-1')).toMatchObject({ kind: 'shell', state: 'running', outputTail: 'hello' });
    expect(tx.getItems()).toContainEqual(expect.objectContaining({ kind: 'taskref', taskId: 'task-1' }));

    tx.apply(projector.map(ev({ type: 'shell.completed', commandId: 'c1', taskId: 'task-1', isError: false })));
    expect(tx.getTask('task-1')).toMatchObject({ state: 'completed', outputTail: 'hello' });
  });

  it('emits a taskref when only shell.completed arrives for a command', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');

    tx.apply(projector.map(ev({ type: 'shell.completed', commandId: 'c1', taskId: 'task-1', isError: true })));

    expect(tx.getTask('task-1')).toMatchObject({ kind: 'shell', state: 'failed' });
    expect(tx.getItems()).toContainEqual(expect.objectContaining({ kind: 'taskref', taskId: 'task-1' }));
  });

  it('projects no-taskId shell failures under a synthetic per-command task id', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');

    tx.apply(
      projector.map(ev({ type: 'shell.output', commandId: 'c1', update: { kind: 'stderr', text: 'boom' } })),
    );
    expect(tx.getTask('shell-c1')).toMatchObject({ kind: 'shell', state: 'running', outputTail: 'boom' });

    tx.apply(projector.map(ev({ type: 'shell.completed', commandId: 'c1', isError: true })));
    expect(tx.getTask('shell-c1')).toMatchObject({ state: 'failed', outputTail: 'boom' });
    expect(tx.getItems()).toContainEqual(expect.objectContaining({ kind: 'taskref', taskId: 'shell-c1' }));
  });

  it('marks a foreground shell task terminal on shell.completed', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');

    tx.apply(projector.map(ev({ type: 'shell.started', commandId: 'c1', taskId: 'task-1' })));
    expect(tx.getTask('task-1')?.state).toBe('running');

    tx.apply(projector.map(ev({ type: 'shell.completed', commandId: 'c1', isError: false })));
    expect(tx.getTask('task-1')).toMatchObject({ kind: 'shell', state: 'completed' });
    expect(tx.getTask('task-1')?.endedAt).toBeTypeOf('string');

    tx.apply(projector.map(ev({ type: 'shell.started', commandId: 'c2', taskId: 'task-2' })));
    tx.apply(projector.map(ev({ type: 'shell.completed', commandId: 'c2', isError: true })));
    expect(tx.getTask('task-2')?.state).toBe('failed');
  });

  it('ignores task.notified (it re-surfaces as an origin:task turn)', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    expect(projector.map(ev({ type: 'task.notified', taskId: 't' }))).toEqual([]);
  });

  it('links spawned subagents to the spawning tool frame (member for swarm)', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'user' } }));
    feed(ev({ type: 'turn.step.started', turnId: 1, step: 1 }));
    feed(
      ev({
        type: 'tool.call.started',
        turnId: 1,
        toolCallId: 'call_swarm',
        name: 'AgentSwarm',
        args: {},
      }),
    );
    feed(
      ev({
        type: 'subagent.spawned',
        subagentId: 'agent-0',
        subagentName: 'worker',
        parentToolCallId: 'call_swarm',
        description: 'scan the repo',
        swarmIndex: 0,
        runInBackground: false,
        model: 'example-model',
        thinkingEffort: 'high',
      }),
    );
    feed(ev({ type: 'subagent.completed', subagentId: 'agent-0', resultSummary: 'done' }));

    const tool = turnOps('t1', tx.getItems()).steps[0]!.frames.find((f) => f.kind === 'tool');
    expect(tool).toMatchObject({
      agentRefs: [{ agentId: 'agent-0', role: 'member' }],
    });
    const task = tx.getTask('agent-0');
    expect(task).toMatchObject({
      kind: 'subagent',
      state: 'completed',
      agentId: 'agent-0',
      description: 'scan the repo',
      detached: false,
      model: 'example-model',
      thinkingEffort: 'high',
    });
  });

  it('keys an Agent-tool subagent row by its registered task id and folds the lifecycle', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(
      ev({
        type: 'subagent.spawned',
        subagentId: 'agent-1',
        subagentName: 'explore',
        parentToolCallId: 'call-1',
        description: 'Inspect files',
        runInBackground: true,
        taskId: 'task-9',
      }),
    );
    feed(
      ev({
        type: 'task.started',
        info: {
          taskId: 'task-9',
          kind: 'agent',
          description: 'Inspect files',
          status: 'running',
          detached: true,
          agentId: 'agent-1',
          startedAt: 1_700_000_000_000,
          endedAt: null,
        },
      }),
    );
    feed(ev({ type: 'subagent.completed', subagentId: 'agent-1', resultSummary: 'done' }));
    feed(
      ev({
        type: 'task.terminated',
        info: {
          taskId: 'task-9',
          kind: 'agent',
          description: 'Inspect files',
          status: 'completed',
          detached: true,
          agentId: 'agent-1',
          startedAt: 1_700_000_000_000,
          endedAt: 1_700_000_001_000,
        },
      }),
    );

    expect(tx.getTask('task-9')).toMatchObject({
      kind: 'subagent',
      state: 'completed',
      agentId: 'agent-1',
      description: 'Inspect files',
      detached: true,
      resultSummary: 'done',
    });
    expect(tx.getTask('agent-1')).toBeUndefined();
  });

  it('drops the stale task mapping when a child respawns without a task id', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(
      ev({
        type: 'subagent.spawned',
        subagentId: 'agent-1',
        subagentName: 'explore',
        parentToolCallId: 'call-1',
        description: 'Inspect files',
        runInBackground: true,
        taskId: 'task-9',
      }),
    );
    feed(ev({ type: 'subagent.completed', subagentId: 'agent-1', resultSummary: 'done' }));
    feed(
      ev({
        type: 'subagent.spawned',
        subagentId: 'agent-1',
        subagentName: 'worker',
        parentToolCallId: 'call-2',
        description: 'scan again',
        runInBackground: false,
      }),
    );
    feed(ev({ type: 'subagent.started', subagentId: 'agent-1' }));

    expect(tx.getTask('task-9')).toMatchObject({ state: 'completed', resultSummary: 'done' });
    expect(tx.getTask('agent-1')).toMatchObject({ kind: 'subagent', state: 'running' });
  });

  it('resets the agent-run generation stamps when a completed subagent is resumed for rework', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(
      ev({
        type: 'subagent.spawned',
        subagentId: 'agent-1',
        subagentName: 'worker',
        parentToolCallId: 'call-1',
        description: 'tower worker',
        runInBackground: true,
      }),
    );
    feed(
      ev({
        type: 'task.started',
        info: {
          taskId: 'task-9',
          kind: 'agent',
          description: 'tower worker',
          status: 'running',
          detached: true,
          agentId: 'agent-1',
          startedAt: 1_700_000_000_000,
          endedAt: null,
        },
      }),
    );
    feed(ev({ type: 'subagent.completed', subagentId: 'agent-1', resultSummary: 'done' }));
    feed(
      ev({
        type: 'task.terminated',
        info: {
          taskId: 'task-9',
          kind: 'agent',
          description: 'tower worker',
          status: 'completed',
          detached: true,
          agentId: 'agent-1',
          startedAt: 1_700_000_000_000,
          endedAt: 1_700_000_001_000,
        },
      }),
    );
    const firstRun = tx.getTask('agent-1');
    expect(firstRun).toMatchObject({ state: 'completed', resultSummary: 'done' });

    feed(
      ev({
        type: 'subagent.spawned',
        subagentId: 'agent-1',
        subagentName: 'worker',
        parentToolCallId: 'call-2',
        description: 'tower worker',
        runInBackground: true,
        taskId: 'task-10',
      }),
    );
    feed(ev({ type: 'subagent.started', subagentId: 'agent-1' }));

    const resumed = tx.getTask('agent-1');
    expect(resumed).toMatchObject({ kind: 'subagent', state: 'running' });
    expect(resumed?.endedAt).toBeUndefined();
    expect(resumed?.resultSummary).toBeUndefined();
    expect(resumed?.error).toBeUndefined();
    expect((resumed?.startedAt ?? '') >= (firstRun?.endedAt ?? '')).toBe(true);
    expect(tx.getTask('task-9')).toMatchObject({
      state: 'completed',
      resultSummary: 'done',
      endedAt: new Date(1_700_000_001_000).toISOString(),
    });
    expect(tx.getTask('task-10')).toMatchObject({
      kind: 'subagent',
      state: 'running',
      agentId: 'agent-1',
    });
  });

  it('clears the terminal stamps when a terminal subagent is respawned without a task id', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(
      ev({
        type: 'subagent.spawned',
        subagentId: 'agent-1',
        subagentName: 'worker',
        parentToolCallId: 'call-1',
        description: 'scan',
        runInBackground: false,
      }),
    );
    feed(ev({ type: 'subagent.completed', subagentId: 'agent-1', resultSummary: 'done' }));
    const finished = tx.getTask('agent-1');
    expect(finished).toMatchObject({ state: 'completed', resultSummary: 'done' });

    feed(
      ev({
        type: 'subagent.spawned',
        subagentId: 'agent-1',
        subagentName: 'worker',
        parentToolCallId: 'call-2',
        description: 'scan again',
        runInBackground: false,
      }),
    );

    const respawned = tx.getTask('agent-1');
    expect(respawned).toMatchObject({ kind: 'subagent', state: 'running' });
    expect(respawned?.endedAt).toBeUndefined();
    expect(respawned?.resultSummary).toBeUndefined();
    expect((respawned?.startedAt ?? '') >= (finished?.endedAt ?? '')).toBe(true);
  });

  it('keeps the run stamps when subagent.started arrives for an already-running task', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(
      ev({
        type: 'subagent.spawned',
        subagentId: 'agent-1',
        subagentName: 'explore',
        parentToolCallId: 'call-1',
        description: 'Inspect files',
        runInBackground: true,
        taskId: 'task-9',
      }),
    );
    feed(ev({ type: 'subagent.started', subagentId: 'agent-1' }));
    const startedAt = tx.getTask('task-9')?.startedAt;
    feed(ev({ type: 'subagent.started', subagentId: 'agent-1' }));

    expect(tx.getTask('task-9')).toMatchObject({ state: 'running', startedAt });
  });

  it('recovers the agent → task association from a backfilled task.started', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(
      ev({
        type: 'task.started',
        info: {
          taskId: 'task-9',
          kind: 'agent',
          description: 'Inspect files',
          status: 'running',
          detached: true,
          agentId: 'agent-1',
          startedAt: 1_700_000_000_000,
          endedAt: null,
        },
      }),
    );
    feed(ev({ type: 'subagent.completed', subagentId: 'agent-1', resultSummary: 'done' }));

    expect(tx.getTask('task-9')).toMatchObject({ state: 'completed', resultSummary: 'done' });
    expect(tx.getTask('agent-1')).toBeUndefined();
  });

  it('projects goal updates into meta.goal plus an inline marker', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const snapshot = {
      goalId: 'g1',
      objective: 'ship it',
      status: 'active',
      completionCriterion: 'tests green',
      turnsUsed: 3,
      tokensUsed: 1234,
      wallClockMs: 5000,
      budget: { tokenBudget: 50000 },
    };
    const ops = projector.map(ev({ type: 'goal.updated', snapshot, change: { kind: 'lifecycle' } }));
    tx.apply(ops);

    expect(tx.getMeta().goal).toEqual({
      objective: 'ship it',
      status: 'active',
      completionCriterion: 'tests green',
      budgetUsed: 1234,
      budgetLimit: 50000,
    });
    const marker = tx.getItems().find((item) => item.kind === 'marker');
    expect(marker).toMatchObject({ marker: 'goal', payload: { snapshot } });

    const clearedOps = projector.map(ev({ type: 'goal.updated', snapshot: null }));
    expect(clearedOps[0]).toEqual({ op: 'meta.merge', meta: { goal: null } });
    tx.apply(clearedOps);
    expect(tx.getMeta().goal).toBeUndefined();
  });

  it('mirrors plan / swarm mode slices into meta.modes (only when provided)', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');

    tx.apply(projector.map(ev({ type: 'agent.status.updated', planMode: true })));
    tx.apply(projector.map(ev({ type: 'agent.status.updated', swarmMode: true })));
    expect(tx.getMeta().modes).toEqual({ plan: {}, swarm: {} });

    tx.apply(projector.map(ev({ type: 'agent.status.updated', planMode: false })));
    expect(tx.getMeta().modes).toEqual({ swarm: {} });
    tx.apply(projector.map(ev({ type: 'agent.status.updated', swarmMode: false })));
    expect(tx.getMeta().modes).toBeUndefined();
  });

  it('mirrors the tower mode slice into meta.modes', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');

    tx.apply(projector.map(ev({ type: 'agent.status.updated', towerMode: true })));
    expect(tx.getMeta().modes).toEqual({ tower: {} });

    tx.apply(projector.map(ev({ type: 'agent.status.updated', towerMode: false })));
    expect(tx.getMeta().modes).toBeUndefined();
  });

  it('mirrors status slices into meta.agent (shallow-merged across slices)', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    const usageOnly = projector.map(ev({ type: 'agent.status.updated', usage: {} }));
    expect(usageOnly).toEqual([{ op: 'meta.merge', meta: { agent: { usage: {} } } }]);

    feed(ev({ type: 'agent.status.updated', model: 'k2', thinkingEffort: 'high' }));
    feed(
      ev({
        type: 'agent.status.updated',
        usage: {
          total: { inputOther: 1, output: 2, inputCacheRead: 3, inputCacheCreation: 4 },
        },
      }),
    );
    feed(
      ev({
        type: 'agent.status.updated',
        contextTokens: 1000,
        maxContextTokens: 200000,
        contextUsage: 0.5,
      }),
    );
    feed(ev({ type: 'agent.status.updated', permission: 'yolo' }));

    expect(tx.getMeta().agent).toEqual({
      model: 'k2',
      thinkingEffort: 'high',
      usage: { total: { inputOther: 1, output: 2, inputCacheRead: 3, inputCacheCreation: 4 } },
      contextTokens: 1000,
      maxContextTokens: 200000,
      contextUsage: 0.5,
      permission: 'yolo',
    });

    feed(ev({ type: 'agent.status.updated', model: 'k3' }));
    expect(tx.getMeta().agent).toMatchObject({ model: 'k3', thinkingEffort: 'high' });
  });

  it('maps domain events into meta.agent.phase', () => {
    let snapshot: AgentActivitySnapshot = {};
    let approvals: readonly LegacyActivityApproval[] = [];
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID, {
      activitySnapshot: () => snapshot,
      pendingApprovals: () => approvals,
    });
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));
    const runningTurn = (overrides: Record<string, unknown>): AgentActivitySnapshot => ({
      turn: {
        turnId: 1,
        phase: 'running',
        step: 1,
        ending: false,
        activeToolCalls: [],
        since: 1000,
        ...overrides,
      },
    });

    snapshot = runningTurn({});
    feed(ev({ type: 'turn.started', agentId: 'main', turnId: 1, origin: { kind: 'user' } }));
    expect(tx.getMeta().agent?.phase).toEqual({
      kind: 'running',
      turnId: 1,
      step: 1,
      stepId: '',
      since: 1000,
    });

    snapshot = runningTurn({
      phase: 'retrying',
      retry: { failedAttempt: 1, nextAttempt: 2, maxAttempts: 10, delayMs: 500 },
    });
    feed(
      ev({
        type: 'turn.step.retrying',
        agentId: 'main',
        turnId: 1,
        step: 1,
        failedAttempt: 1,
        nextAttempt: 2,
        maxAttempts: 10,
        delayMs: 500,
        errorName: 'status',
        errorMessage: 'boom',
      }),
    );
    expect(tx.getMeta().agent?.phase).toMatchObject({
      kind: 'retrying',
      failedAttempt: 1,
      nextAttempt: 2,
      maxAttempts: 10,
    });

    approvals = [{ approvalId: 'ap1', toolCallId: 'c1', since: 1500 }];
    feed(
      ev({
        type: 'permission.approval.requested',
        agentId: 'main',
        turnId: 1,
        toolCallId: 'c1',
        id: 'ap1',
      }),
    );
    expect(tx.getMeta().agent?.phase).toEqual({
      kind: 'awaiting_approval',
      turnId: 1,
      step: 1,
      approval: { approvalId: 'ap1', toolCallId: 'c1' },
      since: 1500,
    });

    feed(ev({ type: 'turn.ended', agentId: 'main', turnId: 1, reason: 'completed', durationMs: 100 }));
    expect(tx.getMeta().agent?.phase).toMatchObject({
      kind: 'ended',
      turnId: 1,
      reason: 'completed',
      durationMs: 100,
    });

    snapshot = {};
    feed(ev({ type: 'permission.approval.resolved', agentId: 'main', turnId: 1, toolCallId: 'c1', id: 'ap1', decision: 'approved' }));
    expect(tx.getMeta().agent?.phase).toMatchObject({ kind: 'ended', turnId: 1 });
  });

  it('projects plan.revision as a marker and refines the active plan badge', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID, {
      resolvePlanRevisionKey: (key) => `sessions/w/s/agents/main/${key}`,
    });
    const tx = new AgentTranscript('main');

    const revision = {
      type: 'plan.revision',
      id: 'plan-1',
      version: 1,
      key: 'plan/plan-1/v1.md',
      sha256: 'deadbeef',
      bytes: 128,
    };

    tx.apply(projector.map(ev(revision)));
    expect(tx.getMeta().modes).toBeUndefined();

    tx.apply(projector.map(ev({ type: 'agent.status.updated', planMode: true })));
    expect(tx.getMeta().modes).toEqual({ plan: {} });
    tx.apply(
      projector.map(ev({ ...revision, version: 2, key: 'plan/plan-1/v2.md' })),
    );
    expect(tx.getMeta().modes).toEqual({
      plan: { reviewPath: 'sessions/w/s/agents/main/plan/plan-1/v2.md', version: 2 },
    });

    const markers = tx
      .getItems()
      .filter((item) => item.kind === 'marker' && item.marker === 'plan.revision');
    expect(markers.map((item) => item.kind === 'marker' && item.markerId)).toEqual([
      'live-m1',
      'live-m2',
    ]);
    expect(markers[1]).toMatchObject({
      payload: {
        id: 'plan-1',
        version: 2,
        path: 'sessions/w/s/agents/main/plan/plan-1/v2.md',
        sha256: 'deadbeef',
        bytes: 128,
      },
    });

    tx.apply(projector.map(ev({ type: 'agent.status.updated', planMode: false })));
    expect(tx.getMeta().modes).toBeUndefined();
    expect(
      tx.getItems().filter((item) => item.kind === 'marker' && item.marker === 'plan.revision'),
    ).toHaveLength(2);
  });

  it('projects skill / plugin-command / cron / compaction / hook / undo markers', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'skill.activated', activationId: 'a1', skillName: 'gen-docs', trigger: 'user-slash' }));
    feed(
      ev({
        type: 'plugin_command.activated',
        activationId: 'a2',
        pluginId: 'p',
        commandName: 'c',
        trigger: 'user-slash',
      }),
    );
    feed(ev({ type: 'cron.fired', origin: { kind: 'cron_job', jobId: 'j1' }, prompt: 'ping' }));
    feed(ev({ type: 'compaction.started', trigger: 'auto' }));
    feed(ev({ type: 'compaction.completed', result: { kept: 3 } }));
    feed(ev({ type: 'hook.result', hookEvent: 'SessionStart', content: 'hook says hi' }));
    feed(
      ev({
        type: 'hook.result',
        turnId: 3,
        hookEvent: 'UserPromptSubmit',
        content: 'blocked by hook',
        blocked: true,
      }),
    );
    feed(ev({ type: 'context.spliced', start: 1, deleteCount: 2, messages: [] }));

    const markers = tx
      .getItems()
      .filter((item): item is Extract<typeof item, { kind: 'marker' }> => item.kind === 'marker');
    expect(markers.map((m) => m.marker)).toEqual([
      'skill',
      'skill',
      'cron.fired',
      'compaction',
      'compaction',
      'hook',
      'hook',
      'undo',
    ]);
    expect(markers[1]!.payload).toMatchObject({ variant: 'plugin_command' });
    expect(markers[3]!.payload).toMatchObject({ phase: 'started' });
    expect(markers[4]!.payload).toMatchObject({ phase: 'completed' });
    expect(markers[5]!.payload).toEqual({ hookEvent: 'SessionStart', content: 'hook says hi' });
    expect(markers[6]!.payload).toEqual({
      turnId: 3,
      hookEvent: 'UserPromptSubmit',
      content: 'blocked by hook',
      blocked: true,
    });
    expect(markers[7]!.payload).toMatchObject({ start: 1, deleteCount: 2 });
  });

  it('does not infer removed turns from an undo count', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    expect(projector.map(ev({ type: 'context.undone', agentId: 'main', turns: 1, fromTurnId: 0 }))).toEqual([]);
  });

  it('projects error / warning events as notice markers outside any step', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');

    tx.apply(
      projector.map(ev({ type: 'error', code: 'mcp.failed', message: 'boom', retryable: false })),
    );
    tx.apply(projector.map(ev({ type: 'warning', message: 'AGENTS.md oversized' })));

    const markers = tx
      .getItems()
      .filter((item): item is Extract<typeof item, { kind: 'marker' }> => item.kind === 'marker');
    expect(markers).toHaveLength(2);
    expect(markers[0]).toMatchObject({
      marker: 'notice',
      payload: { level: 'error', message: 'boom', event: { code: 'mcp.failed' } },
    });
    expect(markers[1]).toMatchObject({
      marker: 'notice',
      payload: { level: 'warning', message: 'AGENTS.md oversized' },
    });
  });

  it('emits interactions as global entities only (no inline frame), back-links on resolve', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'turn.started', turnId: 2, origin: { kind: 'user' } }));
    feed(ev({ type: 'turn.step.started', turnId: 2, step: 1 }));
    feed(
      ev({
        type: 'tool.call.started',
        turnId: 2,
        toolCallId: 'call_9',
        name: 'Bash',
        args: {},
      }),
    );

    const request = {
      toolCallId: 'call_9',
      toolName: 'Bash',
      action: 'run',
      display: { kind: 'command', command: 'rm -rf /tmp/x' },
    };
    tx.apply(
      projector.mapInteractionRequested({
        id: 'apr-1',
        kind: 'approval',
        payload: request,
        createdAt: 1000,
      }),
    );

    expect(turnOps('t2', tx.getItems()).steps[0]!.frames.map((f) => f.kind)).toEqual(['tool']);
    expect(tx.getInteraction('apr-1')).toMatchObject({
      interactionId: 'apr-1',
      interactionKind: 'approval',
      toolCallId: 'call_9',
      state: 'pending',
      request,
    });
    expect(tx.listPendingInteractions()).toEqual(['apr-1']);

    tx.apply(projector.mapInteractionResolved('apr-1', { decision: 'approved', scope: 'session' }));

    const tool = turnOps('t2', tx.getItems()).steps[0]!.frames.find((f) => f.kind === 'tool');
    expect(tool).toMatchObject({ approvalId: 'apr-1' });
    expect(turnOps('t2', tx.getItems()).steps[0]!.frames.map((f) => f.kind)).toEqual(['tool']);
    expect(tx.getInteraction('apr-1')).toMatchObject({
      state: 'approved',
      response: { decision: 'approved', scope: 'session' },
    });
    expect(tx.listPendingInteractions()).toEqual([]);
  });

  it('surfaces a mid-turn task notification as a user input frame linked to the task', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    const notified = (): ProjectorBusEvent =>
      ev({
        type: 'task.notified',
        notificationType: 'task.completed',
        title: 'Background process completed',
        body: 'pnpm test — 42 passed',
        severity: 'info',
        sourceKind: 'background_task',
        sourceId: 'task_1',
      });

    tx.apply(projector.map(notified()));
    expect(tx.getItems()).toHaveLength(0);

    feed(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'user' } }));
    feed(ev({ type: 'turn.step.started', turnId: 1, step: 1 }));
    tx.apply(projector.map(notified()));

    const frames = turnOps('t1', tx.getItems()).steps[0]!.frames;
    const frame = frames.find((f) => f.kind === 'text' && f.role === 'user');
    expect(frame).toMatchObject({ kind: 'text', role: 'user', taskId: 'task_1' });
    expect(frame?.kind === 'text' && frame.text).toContain('Background process completed');
  });

  it('attaches a between-steps task notification to the following step', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    const notified = (sourceId: string): ProjectorBusEvent =>
      ev({
        type: 'task.notified',
        notificationType: 'task.completed',
        title: 'Background agent completed',
        body: 'inspect done.',
        severity: 'info',
        sourceKind: 'background_task',
        sourceId,
      });

    feed(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'user' } }));
    feed(ev({ type: 'turn.step.started', turnId: 1, step: 1 }));
    feed(ev({ type: 'turn.step.completed', turnId: 1, step: 1 }));
    feed(notified('task_1'));
    feed(notified('task_2'));
    expect(turnOps('t1', tx.getItems()).steps[0]!.frames).toHaveLength(0);

    feed(ev({ type: 'turn.step.started', turnId: 1, step: 2 }));
    const steps = turnOps('t1', tx.getItems()).steps;
    expect(steps).toHaveLength(2);
    expect(steps[1]!.frames.map((f) => f.kind === 'text' && f.taskId)).toEqual(['task_1', 'task_2']);
  });

  it('drops a task notification that is the turn prompt itself', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'task', taskId: 'task_1' } }));
    feed(
      ev({
        type: 'task.notified',
        notificationType: 'task.completed',
        title: 'Background agent completed',
        body: 'inspect done.',
        severity: 'info',
        sourceKind: 'background_task',
        sourceId: 'task_1',
      }),
    );
    feed(ev({ type: 'turn.step.started', turnId: 1, step: 1 }));
    expect(turnOps('t1', tx.getItems()).steps[0]!.frames).toHaveLength(0);
  });

  it('keeps a different task’s notification in a task-origin turn', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'task', taskId: 'task_1' } }));
    feed(
      ev({
        type: 'task.notified',
        notificationType: 'task.completed',
        title: 'Background agent completed',
        body: 'second task done.',
        severity: 'info',
        sourceKind: 'background_task',
        sourceId: 'task_2',
      }),
    );
    feed(ev({ type: 'turn.step.started', turnId: 1, step: 1 }));
    const frames = turnOps('t1', tx.getItems()).steps[0]!.frames;
    expect(frames.map((f) => f.kind === 'text' && f.taskId)).toEqual(['task_2']);
  });

  it('drops a buffered task notification when the turn ends before the next step', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'user' } }));
    feed(ev({ type: 'turn.step.started', turnId: 1, step: 1 }));
    feed(ev({ type: 'turn.step.completed', turnId: 1, step: 1 }));
    feed(
      ev({
        type: 'task.notified',
        notificationType: 'task.completed',
        title: 'Background agent completed',
        body: 'inspect done.',
        severity: 'info',
        sourceKind: 'background_task',
        sourceId: 'task_1',
      }),
    );
    feed(ev({ type: 'turn.ended', turnId: 1, reason: 'completed' }));

    feed(ev({ type: 'turn.started', turnId: 2, origin: { kind: 'user' } }));
    feed(ev({ type: 'turn.step.started', turnId: 2, step: 1 }));
    expect(turnOps('t2', tx.getItems()).steps[0]!.frames).toHaveLength(0);
  });

  it('replaces the global todo document on a confirmed TodoList write', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'user' } }));
    feed(ev({ type: 'turn.step.started', turnId: 1, step: 1 }));

    feed(ev({ type: 'tool.call.started', turnId: 1, toolCallId: 'call_read', name: 'TodoList', args: {} }));
    feed(ev({ type: 'tool.result', toolCallId: 'call_read', output: '2 todos' }));
    expect(tx.getTodo('todo')).toBeUndefined();

    feed(
      ev({
        type: 'tool.call.started',
        turnId: 1,
        toolCallId: 'call_write',
        name: 'TodoList',
        args: { todos: [{ title: 'write tests', status: 'in_progress' }, { title: 'ship', status: 'pending' }] },
      }),
    );
    const writeFrame = turnOps('t1', tx.getItems()).steps[0]!.frames.find(
      (f) => f.kind === 'tool' && f.toolCallId === 'call_write',
    );
    expect(writeFrame?.kind === 'tool' && writeFrame.todoId).toBe('todo');

    feed(ev({ type: 'tool.result', toolCallId: 'call_write', output: 'updated' }));
    expect(tx.getTodo('todo')?.items).toEqual([
      { title: 'write tests', status: 'in_progress' },
      { title: 'ship', status: 'pending' },
    ]);

    feed(
      ev({
        type: 'tool.call.started',
        turnId: 1,
        toolCallId: 'call_fail',
        name: 'TodoList',
        args: { todos: [] },
      }),
    );
    feed(ev({ type: 'tool.result', toolCallId: 'call_fail', output: 'boom', isError: true }));
    expect(tx.getTodo('todo')?.items).toHaveLength(2);
  });

  it('emits an unanchored entity when the payload has no toolCallId', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');

    tx.apply(
      projector.mapInteractionRequested({
        id: 'q1',
        kind: 'question',
        payload: { questions: [{ question: 'Pick', options: [] }] },
        createdAt: 1000,
      }),
    );
    expect(tx.getItems()).toHaveLength(0);
    const entity = tx.getInteraction('q1');
    expect(entity).toMatchObject({ interactionKind: 'question', state: 'pending' });
    expect(entity?.toolCallId).toBeUndefined();
    expect(tx.listPendingInteractions()).toEqual(['q1']);

    tx.apply(projector.mapInteractionResolved('q1', null));
    expect(tx.getInteraction('q1')).toMatchObject({ state: 'dismissed' });
    expect(tx.listPendingInteractions()).toEqual([]);
  });

  it('projects question requests onto the wire shape with stable question/option ids', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');

    tx.apply(
      projector.mapInteractionRequested({
        id: 'q-wire',
        kind: 'question',
        payload: {
          toolCallId: 'call_q',
          turnId: 3,
          questions: [
            {
              question: 'Pick one',
              header: 'h',
              body: 'b',
              multiSelect: false,
              otherLabel: 'Other',
              otherDescription: 'free text',
              options: [{ label: 'A', description: 'first' }, { label: 'B' }],
            },
          ],
        },
        createdAt: 7000,
      }),
    );

    const entity = tx.getInteraction('q-wire');
    expect(entity?.toolCallId).toBe('call_q');
    expect(entity?.request).toEqual({
      question_id: 'q-wire',
      session_id: TEST_SESSION_ID,
      questions: [
        {
          id: 'q_0',
          question: 'Pick one',
          header: 'h',
          body: 'b',
          multi_select: false,
          allow_other: true,
          other_label: 'Other',
          other_description: 'free text',
          options: [
            { id: 'opt_0_0', label: 'A', description: 'first' },
            { id: 'opt_0_1', label: 'B' },
          ],
        },
      ],
      created_at: new Date(7000).toISOString(),
      turn_id: 3,
      tool_call_id: 'call_q',
    });

    tx.apply(projector.mapInteractionResolved('q-wire', { q_0: 'A' }));
    expect(tx.getInteraction('q-wire')).toMatchObject({ state: 'answered' });
  });

  it('keeps a malformed question payload raw instead of failing the projection', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');

    tx.apply(
      projector.mapInteractionRequested({
        id: 'q-raw',
        kind: 'question',
        payload: { toolCallId: 'call_x' },
        createdAt: 1000,
      }),
    );

    const entity = tx.getInteraction('q-raw');
    expect(entity?.toolCallId).toBe('call_x');
    expect(entity?.request).toEqual({ toolCallId: 'call_x' });
  });

  it('preserves queue metadata through prompt lifecycle updates', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));
    const metadata = [{ display_text: 'Save button', kimi_code_composer: { version: 1, doc: { type: 'doc' } } }];
    feed(ev({ type: 'prompt.submitted', promptId: 'p1', userMessageId: 'm1', status: 'queued', content: [{ type: 'text', text: 'wire' }], clientMetadata: metadata, createdAt: '2026-01-01T00:00:00.000Z' }));
    feed(ev({ type: 'prompt.queued', promptId: 'p1', content: [{ type: 'text', text: 'wire' }], queueLength: 1, clientMetadata: metadata }));
    feed(ev({ type: 'prompt.started', promptId: 'p1' }));
    feed(ev({ type: 'prompt.completed', promptId: 'p1', finishedAt: '2026-01-01T00:00:02.000Z', reason: 'completed' }));
    expect(tx.getPrompt('p1')?.clientMetadata).toEqual(metadata);
  });

  it('projects prompt submitted/completed/aborted/steered as global queue entities', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(
      ev({
        type: 'prompt.submitted',
        promptId: 'p1',
        userMessageId: 'm1',
        status: 'running',
        content: [{ type: 'text', text: 'first' }],
        createdAt: '2026-01-01T00:00:00.000Z',
      }),
    );
    feed(
      ev({
        type: 'prompt.submitted',
        promptId: 'p2',
        userMessageId: 'm2',
        status: 'queued',
        content: [{ type: 'text', text: 'second' }],
        createdAt: '2026-01-01T00:00:01.000Z',
      }),
    );
    expect(tx.getPrompt('p1')).toMatchObject({ status: 'running', userMessageId: 'm1' });
    expect(tx.getPrompt('p2')).toMatchObject({ status: 'queued' });

    feed(ev({ type: 'prompt.started', promptId: 'p2' }));
    expect(tx.getPrompt('p2')).toMatchObject({
      status: 'running',
      userMessageId: 'm2',
      content: [{ type: 'text', text: 'second' }],
      createdAt: '2026-01-01T00:00:01.000Z',
    });

    feed(
      ev({
        type: 'prompt.steered',
        activePromptId: 'p1',
        promptIds: ['p2'],
        content: [
          { type: 'text', text: 'first' },
          { type: 'text', text: 'second' },
        ],
        steeredAt: '2026-01-01T00:00:02.000Z',
      }),
    );
    expect(tx.getPrompt('p1')).toMatchObject({
      status: 'running',
      steeredAt: '2026-01-01T00:00:02.000Z',
      content: [
        { type: 'text', text: 'first' },
        { type: 'text', text: 'second' },
      ],
    });
    expect(tx.getPrompt('p2')).toMatchObject({
      status: 'completed',
      userMessageId: 'm2',
      steeredAt: '2026-01-01T00:00:02.000Z',
      finishedAt: '2026-01-01T00:00:02.000Z',
    });

    feed(
      ev({
        type: 'prompt.completed',
        promptId: 'p1',
        finishedAt: '2026-01-01T00:00:10.000Z',
        reason: 'completed',
      }),
    );
    expect(tx.getPrompt('p1')).toMatchObject({
      status: 'completed',
      finishedAt: '2026-01-01T00:00:10.000Z',
      content: [
        { type: 'text', text: 'first' },
        { type: 'text', text: 'second' },
      ],
    });

    feed(ev({ type: 'prompt.aborted', promptId: 'p3', abortedAt: '2026-01-01T00:00:03.000Z' }));
    expect(tx.getPrompt('p3')).toEqual({
      promptId: 'p3',
      status: 'aborted',
      createdAt: '2026-01-01T00:00:03.000Z',
      finishedAt: '2026-01-01T00:00:03.000Z',
    });
    feed(
      ev({
        type: 'prompt.completed',
        promptId: 'p4',
        finishedAt: '2026-01-01T00:00:04.000Z',
        reason: 'failed',
      }),
    );
    expect(tx.getPrompt('p4')).toEqual({
      promptId: 'p4',
      status: 'failed',
      createdAt: '2026-01-01T00:00:04.000Z',
      finishedAt: '2026-01-01T00:00:04.000Z',
    });
  });

  it('projects prompt.steered media content to the wire shape (no daemon ref or path leak)', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(
      ev({
        type: 'prompt.steered',
        activePromptId: 'p1',
        promptIds: ['p2'],
        content: [
          { type: 'text', text: 'look at this' },
          {
            type: 'image_url',
            imageUrl: { url: 'kimi-file://f_img1?path=%2Fabs%2Fsession%2Fmedia%2Ff_img1.png' },
          },
        ],
        steeredAt: '2026-01-01T00:00:02.000Z',
      }),
    );

    const prompt = tx.getPrompt('p1');
    expect(prompt?.content).toEqual([
      { type: 'text', text: 'look at this' },
      { type: 'image', source: { kind: 'session_media', file_id: 'f_img1' } },
    ]);
  });

  it('projects turn.steer as a user frame at the next step start, pairing promptIds from prompt.steered', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'turn.started', turnId: 3, origin: { kind: 'user' }, prompt: 'active' }));
    feed(ev({ type: 'turn.step.started', turnId: 3, step: 1 }));
    feed(ev({ type: 'turn.step.completed', turnId: 3, step: 1 }));
    feed(
      ev({
        type: 'prompt.steered',
        activePromptId: 'p1',
        promptIds: ['p2'],
        content: [
          { type: 'text', text: 'steered in' },
          { type: 'video_url', videoUrl: { url: 'kimi-file://f_vid2', name: 'queued.mp4' } },
        ],
        steeredAt: '2026-01-01T00:00:02.000Z',
      }),
    );
    feed(
      ev({
        type: 'turn.steer',
        input: [
          { type: 'text', text: 'steered in' },
          { type: 'video_url', videoUrl: { url: 'kimi-file://f_vid2', name: 'queued.mp4' } },
        ],
        origin: { kind: 'user' },
      }),
    );
    expect(turnOps('t3', tx.getItems()).steps).toHaveLength(1);

    feed(ev({ type: 'turn.step.started', turnId: 3, step: 2 }));
    const turn = turnOps('t3', tx.getItems());
    expect(turn.steps).toHaveLength(2);
    const frame = turn.steps[1]?.frames[0];
    expect(frame).toMatchObject({
      kind: 'text',
      role: 'user',
      text: 'steered in',
      promptIds: ['p2'],
      origin: { kind: 'user' },
    });
    expect(frame?.kind === 'text' ? frame.attachmentIds : undefined).toHaveLength(1);
    const attachmentId = frame?.kind === 'text' ? frame.attachmentIds?.[0] : undefined;
    expect(attachmentId === undefined ? undefined : tx.getAttachment(attachmentId)).toMatchObject({
      mediaType: 'video/*',
      name: 'queued.mp4',
      source: { kind: 'session_media', fileId: 'f_vid2' },
    });
  });

  it('projects turn.steer into the running step immediately, with daemon media as attachments', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const ops: TranscriptOperation[] = [];
    const feed = (event: ProjectorBusEvent): void => {
      const mapped = projector.map(event);
      ops.push(...mapped);
      tx.apply(mapped);
    };

    feed(ev({ type: 'turn.started', turnId: 4, origin: { kind: 'user' }, prompt: 'active' }));
    feed(ev({ type: 'turn.step.started', turnId: 4, step: 1 }));
    feed(
      ev({
        type: 'prompt.steered',
        activePromptId: 'p1',
        promptIds: ['p2', 'p3'],
        content: [
          { type: 'text', text: 'look at this' },
          {
            type: 'image_url',
            imageUrl: {
              url: 'kimi-file://f_img9?path=%2Fabs%2Fsession%2Fmedia%2Ff_img9.png',
              name: 'architecture.png',
            },
          },
        ],
        steeredAt: '2026-01-01T00:00:02.000Z',
      }),
    );
    feed(
      ev({
        type: 'turn.steer',
        input: [
          { type: 'text', text: '<skill-loaded name="deploy">private instructions</skill-loaded>' },
          { type: 'text', text: '<skill-loaded name="review">private instructions</skill-loaded>' },
          { type: 'text', text: 'look at this' },
          {
            type: 'image_url',
            imageUrl: {
              url: 'kimi-file://f_img9?path=%2Fabs%2Fsession%2Fmedia%2Ff_img9.png',
              name: 'architecture.png',
            },
          },
        ],
        origin: {
          kind: 'user',
          skillActivations: [
            { activationId: 'a1', skillName: 'deploy', skillPath: '/private/deploy/SKILL.md' },
            { activationId: 'a2', skillName: 'review', skillArgs: 'strict', skillPath: '/private/review/SKILL.md' },
          ],
          attachments: [{
            name: 'secret.txt',
            mediaType: 'text/plain',
            size: 12,
            path: '/private/secret.txt',
          }],
        },
      }),
    );

    const attachmentOp = ops.find((op) => op.op === 'attachment.upsert');
    expect(attachmentOp).toMatchObject({
      attachment: {
        mediaType: 'image/*',
        name: 'architecture.png',
        source: { kind: 'session_media', fileId: 'f_img9' },
      },
    });
    const frame = turnOps('t4', tx.getItems()).steps[0]?.frames[0];
    expect(frame).toMatchObject({
      kind: 'text',
      role: 'user',
      text: 'look at this',
      promptIds: ['p2', 'p3'],
      origin: {
        kind: 'user',
        skillActivations: [
          { skillName: 'deploy' },
          { skillName: 'review', skillArgs: 'strict' },
        ],
      },
    });
    expect(JSON.stringify(frame)).not.toContain('/private/');
    const attachmentIds = frame?.kind === 'text' ? frame.attachmentIds : undefined;
    expect(attachmentIds).toHaveLength(2);
    expect(attachmentIds?.[0]).toBe(
      attachmentOp?.op === 'attachment.upsert' ? attachmentOp.attachment.attachmentId : undefined,
    );
    expect(tx.getAttachment(attachmentIds![1]!)).toEqual({
      attachmentId: attachmentIds![1],
      mediaType: 'text/plain',
      name: 'secret.txt',
      size: 12,
    });
    expect(JSON.stringify([...tx.getAttachments().values()])).not.toContain('/private/');
  });

  it('records a user slash skill activation steered into a running turn without taking a queued prompt id', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));
    const origin = { kind: 'skill_activation' as const, activationId: 'act-1', trigger: 'user-slash' as const, skillName: 'example-skill', skillArgs: 'args' };
    feed(ev({ type: 'turn.started', turnId: 5, origin: { kind: 'user' }, prompt: 'active' }));
    feed(ev({ type: 'turn.step.started', turnId: 5, step: 1 }));
    feed(ev({ type: 'prompt.steered', activePromptId: 'active', promptIds: ['queued'], content: [{ type: 'text', text: 'queued input' }], steeredAt: '2026-01-01T00:00:02.000Z' }));
    feed(ev({ type: 'turn.steer', input: [{ type: 'text', text: 'User activated the skill' }], origin }));
    feed(ev({ type: 'turn.steer', input: [{ type: 'text', text: 'queued input' }], origin: { kind: 'user' } }));
    const frames = turnOps('t5', tx.getItems()).steps[0]!.frames;
    expect(frames[0]).toMatchObject({ role: 'user', text: 'User activated the skill', origin: { kind: 'skill_activation', trigger: 'user-slash', skillName: 'example-skill' } });
    expect((frames[0] as { promptIds?: readonly string[] }).promptIds).toBeUndefined();
    expect(frames[1]).toMatchObject({ text: 'queued input', promptIds: ['queued'] });
  });

  it('projects origin file attachments on steered frames for user prompts and slash skills', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));
    const file = { name: 'notes.pdf', mediaType: 'application/pdf', size: 42, path: '/tmp/notes.pdf' };
    feed(ev({ type: 'turn.started', turnId: 7, origin: { kind: 'user' }, prompt: 'active' }));
    feed(ev({ type: 'turn.step.started', turnId: 7, step: 1 }));
    feed(ev({ type: 'turn.steer', input: [{ type: 'text', text: 'User activated the skill' }], origin: { kind: 'skill_activation', activationId: 'act-3', trigger: 'user-slash', skillName: 'example-skill', attachments: [file] } }));
    feed(ev({ type: 'prompt.steered', activePromptId: 'active', promptIds: ['queued'], content: [{ type: 'text', text: 'see file' }], steeredAt: '2026-01-01T00:00:02.000Z' }));
    feed(ev({ type: 'turn.steer', input: [{ type: 'text', text: 'see file' }], origin: { kind: 'user', attachments: [file] } }));
    const frames = turnOps('t7', tx.getItems()).steps[0]!.frames as { attachmentIds?: readonly string[] }[];
    expect(frames).toHaveLength(2);
    for (const frame of frames) {
      expect(frame.attachmentIds).toHaveLength(1);
      expect(tx.getAttachment(frame.attachmentIds![0]!)).toMatchObject({ name: 'notes.pdf', mediaType: 'application/pdf', size: 42 });
    }
  });

  it('still ignores a model-triggered skill activation steer', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));
    feed(ev({ type: 'turn.started', turnId: 6, origin: { kind: 'user' }, prompt: 'active' }));
    feed(ev({ type: 'turn.step.started', turnId: 6, step: 1 }));
    feed(ev({ type: 'turn.steer', input: [{ type: 'text', text: 'model tool activation' }], origin: { kind: 'skill_activation', activationId: 'act-2', trigger: 'model-tool', skillName: 'example-skill' } }));
    expect(turnOps('t6', tx.getItems()).steps[0]!.frames).toHaveLength(0);
  });

  it('projects a live user turn payload without server-local paths', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const clientMetadata = [{ display_text: 'Visible prompt' }];
    tx.apply(projector.map(ev({
      type: 'turn.started',
      turnId: 9,
      prompt: 'visible prompt',
      origin: {
        kind: 'user',
        clientMetadata,
        skillActivations: [{ activationId: 'a1', skillName: 'deploy', skillArgs: 'now', skillPath: '/private/deploy/SKILL.md' }],
        attachments: [{ name: 'notes.pdf', mediaType: 'application/pdf', size: 42, path: '/private/notes.pdf' }],
      },
    })));
    const turn = turnOps('t9', tx.getItems());
    expect(turn.origin).toEqual({ kind: 'user', payload: { kind: 'user', clientMetadata, skillActivations: [{ skillName: 'deploy', skillArgs: 'now' }] } });
    expect(JSON.stringify(turn)).not.toContain('/private/');
  });

  it('keeps client metadata on a steered slash skill frame', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));
    const clientMetadata = [{ display_text: 'Save button' }];
    feed(ev({ type: 'turn.started', turnId: 8, origin: { kind: 'user' }, prompt: 'active' }));
    feed(ev({ type: 'turn.step.started', turnId: 8, step: 1 }));
    feed(ev({ type: 'turn.steer', input: [{ type: 'text', text: 'User skill context' }], origin: { kind: 'skill_activation', activationId: 'act-4', trigger: 'user-slash', skillName: 'example-skill', clientMetadata } }));
    expect(turnOps('t8', tx.getItems()).steps[0]!.frames[0]).toMatchObject({
      role: 'user',
      origin: { kind: 'skill_activation', skillName: 'example-skill', clientMetadata },
    });
  });

  it('ignores turn.steer for non-user origins and for turns that are not running', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'turn.started', turnId: 5, origin: { kind: 'user' }, prompt: 'active' }));
    feed(ev({ type: 'turn.step.started', turnId: 5, step: 1 }));
    feed(
      ev({
        type: 'turn.steer',
        input: [{ type: 'text', text: 'backgrounded output' }],
        origin: { kind: 'injection', variant: 'shell_command_backgrounded' },
      }),
    );
    expect(turnOps('t5', tx.getItems()).steps[0]?.frames).toHaveLength(0);

    feed(ev({ type: 'turn.step.completed', turnId: 5, step: 1 }));
    feed(ev({ type: 'turn.ended', turnId: 5, reason: 'completed' }));
    feed(
      ev({
        type: 'turn.steer',
        input: [{ type: 'text', text: 'too late' }],
        origin: { kind: 'user' },
      }),
    );
    expect(
      turnOps('t5', tx.getItems()).steps.flatMap((step) => step.frames),
    ).toHaveLength(0);
  });

  it('flushes a pending steer into the last step when the turn ends before the next step', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'turn.started', turnId: 6, origin: { kind: 'user' }, prompt: 'active' }));
    feed(ev({ type: 'turn.step.started', turnId: 6, step: 1 }));
    feed(ev({ type: 'turn.step.completed', turnId: 6, step: 1 }));
    feed(
      ev({
        type: 'prompt.steered',
        activePromptId: 'p1',
        promptIds: ['p2'],
        content: [{ type: 'text', text: 'last word' }],
        steeredAt: '2026-01-01T00:00:02.000Z',
      }),
    );
    feed(
      ev({
        type: 'turn.steer',
        input: [{ type: 'text', text: 'last word' }],
        origin: { kind: 'user' },
      }),
    );
    feed(ev({ type: 'turn.ended', turnId: 6, reason: 'cancelled', interruptReason: 'user_cancelled' }));

    const turn = turnOps('t6', tx.getItems());
    const lastStep = turn.steps.at(-1);
    expect(lastStep?.frames.at(-1)).toMatchObject({
      kind: 'text',
      role: 'user',
      text: 'last word',
      promptIds: ['p2'],
      origin: { kind: 'user' },
    });
  });

  it('flushes a pending steer into a user-only step when the turn ends before its first step', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'turn.started', turnId: 7, origin: { kind: 'user' }, prompt: 'active' }));
    feed(
      ev({
        type: 'prompt.steered',
        activePromptId: 'p1',
        promptIds: ['p2'],
        content: [{ type: 'text', text: 'last word' }],
        steeredAt: '2026-01-01T00:00:02.000Z',
      }),
    );
    feed(
      ev({
        type: 'turn.steer',
        input: [
          { type: 'text', text: '<skill-loaded name="review">private instructions</skill-loaded>' },
          { type: 'text', text: 'last word' },
        ],
        origin: {
          kind: 'user',
          skillActivations: [{ activationId: 'a1', skillName: 'review', skillArgs: 'strict' }],
        },
      }),
    );
    feed(ev({ type: 'turn.ended', turnId: 7, reason: 'cancelled', interruptReason: 'user_cancelled' }));

    const turn = turnOps('t7', tx.getItems());
    expect(turn.steps).toHaveLength(1);
    expect(turn.steps[0]).toMatchObject({ state: 'interrupted' });
    expect(turn.steps[0]?.frames[0]).toMatchObject({
      kind: 'text',
      role: 'user',
      text: 'last word',
      promptIds: ['p2'],
      origin: {
        kind: 'user',
        skillActivations: [{ skillName: 'review', skillArgs: 'strict' }],
      },
    });
  });

  it('buffers turn.steer seen before the projector ever saw turn.started (mid-turn attach)', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const ops: TranscriptOperation[] = [];
    const feed = (event: ProjectorBusEvent): void => {
      ops.push(...projector.map(event));
    };

    feed(
      ev({
        type: 'prompt.steered',
        activePromptId: 'p1',
        promptIds: ['p2'],
        content: [{ type: 'text', text: 'steered mid-attach' }],
        steeredAt: '2026-01-01T00:00:02.000Z',
      }),
    );
    feed(
      ev({
        type: 'turn.steer',
        input: [{ type: 'text', text: 'steered mid-attach' }],
        origin: { kind: 'user' },
      }),
    );
    expect(ops).toHaveLength(2);
    expect(ops.every((op) => op.op === 'prompt.upsert')).toBe(true);

    feed(ev({ type: 'turn.step.started', turnId: 3, step: 2 }));
    const frameOp = ops.find((op) => op.op === 'frame.upsert');
    expect(frameOp).toMatchObject({
      turnId: 't3',
      stepId: 't3.2',
      frame: {
        kind: 'text',
        role: 'user',
        text: 'steered mid-attach',
        promptIds: ['p2'],
        origin: { kind: 'user' },
      },
    });
  });

  it('readColdSnapshot answers empty for path-hostile agent ids without touching disk', async () => {
    const service = new TranscriptService({
      homeDir: '/nonexistent-home',
      core: {
        accessor: {
          get: (token: unknown) => {
            if (token === ISessionManager) {
              return { get: () => undefined, list: () => [] };
            }
            if (token === IWorkspaceInstanceManager) {
              return { list: () => [], onDidChange: () => ({ dispose: () => undefined }) };
            }
            if (token === ISessionIndex) return { get: async () => ({ workspaceId: 'ws' }) };
            return undefined;
          },
        },
      } as unknown as Scope,
    });
    for (const hostile of ['../../main', '..', 'a/b', 'a\\b']) {
      const snapshot = await service.readColdSnapshot('s1', hostile);
      expect(snapshot?.items).toEqual([]);
    }
  });

  it('readColdSnapshot folds task/todo/goal/plan/interaction records into the cold snapshot', async () => {
    const home = await mkdtemp(join(tmpdir(), 'transcript-cold-facts-'));
    try {
      const wireDir = join(home, 'sessions', 'ws', 's1', 'agents', 'main');
      await mkdir(wireDir, { recursive: true });
      const records = [
        {
          type: 'context.append_message',
          message: {
            role: 'user',
            content: [{ type: 'text', text: 'hi' }],
            toolCalls: [],
            origin: { kind: 'user' },
          },
          time: 1000,
        },
        {
          type: 'context.append_message',
          message: {
            role: 'assistant',
            content: [{ type: 'text', text: 'running' }],
            toolCalls: [{ type: 'function', id: 'call_1', name: 'Bash', arguments: '{"command":"ls"}' }],
          },
          time: 2000,
        },
        {
          type: 'tools.update_store',
          key: 'todo',
          value: [{ title: 'write tests', status: 'in_progress' }],
          time: 3000,
        },
        { type: 'goal.create', goalId: 'g1', objective: 'fix the bug', time: 4000 },
        { type: 'plan_mode.enter', id: 'plan-1', time: 5000 },
        {
          type: 'task.started',
          info: {
            taskId: 'task_1',
            kind: 'process',
            description: 'pnpm test',
            status: 'running',
            startedAt: 6000,
            endedAt: null,
          },
          time: 6000,
        },
        {
          type: 'task.terminated',
          info: {
            taskId: 'task_1',
            kind: 'process',
            description: 'pnpm test',
            status: 'completed',
            startedAt: 6000,
            endedAt: 9000,
          },
          outputTail: '42 passed',
          time: 9000,
        },
        {
          type: 'interaction.request',
          id: 'apr-1',
          kind: 'approval',
          toolCallId: 'call_1',
          request: { toolName: 'Bash' },
          time: 7000,
        },
        {
          type: 'interaction.resolved',
          id: 'apr-1',
          response: { decision: 'approved' },
          time: 8000,
        },
      ];
      await writeFile(join(wireDir, 'wire.jsonl'), `${records.map((r) => JSON.stringify(r)).join('\n')}\n`);

      const service = new TranscriptService({
        homeDir: home,
        core: {
          accessor: {
            get: (token: unknown) => {
              if (token === ISessionManager) return { get: () => undefined, list: () => [] };
              if (token === IWorkspaceInstanceManager) {
              return { list: () => [], onDidChange: () => ({ dispose: () => undefined }) };
            }
              if (token === ISessionIndex) return { get: async () => ({ workspaceId: 'ws' }) };
              return undefined;
            },
          },
        } as unknown as Scope,
      });
      const snapshot = await service.readColdSnapshot('s1', 'main');
      expect(snapshot).toBeDefined();

      expect(snapshot!.tasks).toEqual([
        {
          taskId: 'task_1',
          kind: 'shell',
          state: 'completed',
          detached: true,
          description: 'pnpm test',
          agentId: undefined,
          outputTail: '42 passed',
          startedAt: new Date(6000).toISOString(),
          endedAt: new Date(9000).toISOString(),
        },
      ]);
      expect(snapshot!.todos).toEqual([
        {
          todoId: 'todo',
          items: [{ title: 'write tests', status: 'in_progress' }],
          updatedAt: new Date(3000).toISOString(),
        },
      ]);
      expect(snapshot!.meta.goal).toMatchObject({ objective: 'fix the bug', status: 'active' });
      expect(snapshot!.meta.modes).toEqual({ plan: {} });
      expect(snapshot!.interactions).toEqual([
        {
          interactionId: 'apr-1',
          interactionKind: 'approval',
          toolCallId: 'call_1',
          state: 'approved',
          request: { toolName: 'Bash' },
          response: { decision: 'approved' },
        },
      ]);

      const standalone = snapshot!.items.filter((item) => item.kind !== 'turn');
      expect(standalone).toEqual([
        expect.objectContaining({ kind: 'marker', marker: 'goal', markerId: 'm1' }),
        expect.objectContaining({ kind: 'marker', marker: 'plan.enter', markerId: 'm2' }),
        expect.objectContaining({ kind: 'taskref', refId: 'ref-task_1', taskId: 'task_1' }),
      ]);
      service.dropSession('s1');
    } finally {
      await rm(home, { recursive: true, force: true });
    }
  });

  it('readColdSnapshot projects question requests onto the wire shape without rewriting the log', async () => {
    const home = await mkdtemp(join(tmpdir(), 'transcript-cold-question-'));
    try {
      const wireDir = join(home, 'sessions', 'ws', 's1', 'agents', 'main');
      await mkdir(wireDir, { recursive: true });
      const records = [
        {
          type: 'interaction.request',
          id: 'q-cold',
          kind: 'question',
          toolCallId: 'call_q',
          request: {
            toolCallId: 'call_q',
            questions: [{ question: 'Pick', options: [{ label: 'A' }, { label: 'B' }] }],
          },
          time: 7000,
        },
        {
          type: 'interaction.request',
          id: 'q-inner',
          kind: 'question',
          request: {
            toolCallId: 'call_inner',
            questions: [{ question: 'Inner', options: [{ label: 'X' }] }],
          },
          time: 8500,
        },
        {
          type: 'interaction.request',
          id: 'q-bad',
          kind: 'question',
          request: { toolName: 'nope' },
          time: 8000,
        },
        {
          type: 'interaction.request',
          id: 'apr-1',
          kind: 'approval',
          toolCallId: 'call_1',
          request: { toolName: 'Bash' },
          time: 9000,
        },
      ];
      const wireFile = join(wireDir, 'wire.jsonl');
      const content = `${records.map((r) => JSON.stringify(r)).join('\n')}\n`;
      await writeFile(wireFile, content);

      const service = coldTranscriptService(home);
      const snapshot = await service.readColdSnapshot('s1', 'main');
      const byId = new Map(snapshot!.interactions.map((i) => [i.interactionId, i]));
      expect(byId.get('q-cold')).toMatchObject({
        interactionKind: 'question',
        toolCallId: 'call_q',
        state: 'cancelled',
      });
      expect(byId.get('q-cold')?.request).toEqual({
        question_id: 'q-cold',
        session_id: 's1',
        questions: [
          {
            id: 'q_0',
            question: 'Pick',
            options: [
              { id: 'opt_0_0', label: 'A' },
              { id: 'opt_0_1', label: 'B' },
            ],
            allow_other: true,
          },
        ],
        created_at: new Date(7000).toISOString(),
        tool_call_id: 'call_q',
      });
      expect(byId.get('q-bad')?.request).toEqual({ toolName: 'nope' });
      expect(byId.get('q-inner')).toMatchObject({ toolCallId: 'call_inner' });
      expect(byId.get('q-inner')?.request).toMatchObject({
        question_id: 'q-inner',
        tool_call_id: 'call_inner',
      });
      expect(byId.get('apr-1')?.request).toEqual({ toolName: 'Bash' });
      await expect(readFile(wireFile, 'utf-8')).resolves.toBe(content);
      service.dropSession('s1');
    } finally {
      await rm(home, { recursive: true, force: true });
    }
  });

  it('readColdSnapshot derives meta.activity from the final turn state when no live session exists', async () => {
    const home = await mkdtemp(join(tmpdir(), 'transcript-cold-activity-'));
    try {
      const wireDir = join(home, 'sessions', 'ws', 's1', 'agents', 'main');
      await mkdir(wireDir, { recursive: true });
      const write = async (records: unknown[]): Promise<void> =>
        writeFile(join(wireDir, 'wire.jsonl'), `${records.map((r) => JSON.stringify(r)).join('\n')}\n`);
      const user = { type: 'context.append_message', message: { id: 'prompt-1', role: 'user', content: [{ type: 'text', text: 'hi' }], toolCalls: [], origin: { kind: 'user' } }, time: 1000 };
      const assistant = { type: 'context.append_message', message: { role: 'assistant', content: [{ type: 'text', text: 'answer' }], toolCalls: [] }, time: 2000 };
      const boundary = { type: 'turn.prompt', input: [{ type: 'text', text: 'hi' }], origin: { kind: 'user' }, promptId: 'prompt-1', time: 500 };

      await write([boundary, user, assistant, { type: 'turn.ended', turnId: 0, reason: 'completed', time: 3000 }]);
      const ended = await coldTranscriptService(home).readColdSnapshot('s1', 'main');
      expect(ended!.meta.activity).toBe('idle');
      expect(ended!.items[0]).toMatchObject({ triggerPromptId: 'prompt-1' });

      await write([boundary, user, assistant]);
      const dangling = await coldTranscriptService(home).readColdSnapshot('s1', 'main');
      expect(dangling!.meta.activity).toBe('idle');
    } finally {
      await rm(home, { recursive: true, force: true });
    }
  });

  it('readColdSnapshot opens a task-origin turn only when the wire has the turn.prompt boundary', async () => {
    const home = await mkdtemp(join(tmpdir(), 'transcript-cold-taskturn-'));
    try {
      const wireDir = join(home, 'sessions', 'ws', 's1', 'agents', 'main');
      await mkdir(wireDir, { recursive: true });
      const notification =
        '<notification id="task:task_9:completed" category="task" type="task.completed" source_kind="background_task" source_id="task_9">\nTitle: Background agent completed\nSeverity: info\ninspect done.\n</notification>';
      const taskOrigin = { kind: 'task', taskId: 'task_9', status: 'completed', notificationId: 'n1' };
      const opening = [
        { type: 'context.append_message', message: { role: 'user', content: [{ type: 'text', text: 'hi' }], toolCalls: [], origin: { kind: 'user' } }, time: 1000 },
        { type: 'context.append_message', message: { role: 'assistant', content: [{ type: 'text', text: 'answer' }], toolCalls: [] }, time: 2000 },
      ];
      const boundary = { type: 'turn.prompt', input: [{ type: 'text', text: notification }], origin: taskOrigin, time: 3000 };
      const delivered = { type: 'context.append_message', message: { role: 'user', content: [{ type: 'text', text: notification }], toolCalls: [], origin: taskOrigin }, time: 4000 };
      const reply = { type: 'context.append_message', message: { role: 'assistant', content: [{ type: 'text', text: 'reporting back' }], toolCalls: [] }, time: 5000 };
      const write = async (records: unknown[]): Promise<void> =>
        writeFile(join(wireDir, 'wire.jsonl'), `${records.map((r) => JSON.stringify(r)).join('\n')}\n`);

      await write([...opening, boundary, delivered, reply]);
      const withBoundary = await coldTranscriptService(home).readColdSnapshot('s1', 'main');
      const originKinds = withBoundary!.items
        .filter((item) => item.kind === 'turn')
        .map((item) => (item.kind === 'turn' ? item.origin.kind : ''));
      expect(originKinds).toEqual(['user', 'task']);

      await write([...opening, delivered, reply]);
      const withoutBoundary = await coldTranscriptService(home).readColdSnapshot('s1', 'main');
      const turns = withoutBoundary!.items.filter((item) => item.kind === 'turn');
      expect(turns).toHaveLength(1);
      const turn = turns[0];
      if (turn?.kind !== 'turn') throw new Error('expected turn');
      expect(
        turn.steps.flatMap((step) => step.frames).some((f) => f.kind === 'text' && f.role === 'user'),
      ).toBe(true);
    } finally {
      await rm(home, { recursive: true, force: true });
    }
  });

  it('readColdSnapshot folds a steered user message into its turn instead of opening a new one', async () => {
    const home = await mkdtemp(join(tmpdir(), 'transcript-cold-steer-'));
    try {
      const wireDir = join(home, 'sessions', 'ws', 's1', 'agents', 'main');
      await mkdir(wireDir, { recursive: true });
      const records = [
        { type: 'context.append_message', message: { role: 'user', content: [{ type: 'text', text: 'active' }], toolCalls: [], origin: { kind: 'user' } }, time: 1000 },
        { type: 'context.append_message', message: { role: 'assistant', content: [{ type: 'text', text: 'working' }], toolCalls: [] }, time: 2000 },
        { type: 'turn.steer', input: [{ type: 'text', text: 'steered in' }], origin: { kind: 'user' }, time: 3000 },
        { type: 'context.append_message', message: { role: 'user', content: [{ type: 'text', text: 'steered in' }], toolCalls: [], origin: { kind: 'user' } }, time: 3001 },
        { type: 'context.append_message', message: { role: 'assistant', content: [{ type: 'text', text: 'noted' }], toolCalls: [] }, time: 4000 },
      ];
      await writeFile(join(wireDir, 'wire.jsonl'), `${records.map((r) => JSON.stringify(r)).join('\n')}\n`);

      const snapshot = await coldTranscriptService(home).readColdSnapshot('s1', 'main');
      const turns = snapshot!.items.filter((item) => item.kind === 'turn');
      expect(turns).toHaveLength(1);
      const turn = turns[0];
      if (turn?.kind !== 'turn') throw new Error('expected turn');
      expect(turn.steps).toHaveLength(2);
      expect(turn.steps[1]?.frames[0]).toMatchObject({
        kind: 'text',
        role: 'user',
        text: 'steered in',
        origin: { kind: 'user' },
      });
    } finally {
      await rm(home, { recursive: true, force: true });
    }
  });

  it('readColdSnapshot preserves safe bundled skill provenance before the first step', async () => {
    const home = await mkdtemp(join(tmpdir(), 'transcript-cold-bundled-steer-'));
    try {
      const wireDir = join(home, 'sessions', 'ws', 's1', 'agents', 'main');
      await mkdir(wireDir, { recursive: true });
      const origin = {
        kind: 'user',
        skillActivations: [
          { activationId: 'a1', skillName: 'deploy', skillPath: '/private/deploy/SKILL.md' },
          { activationId: 'a2', skillName: 'review', skillArgs: 'strict', skillPath: '/private/review/SKILL.md' },
        ],
        attachments: [{
          name: 'secret.txt',
          mediaType: 'text/plain',
          size: 12,
          path: '/private/secret.txt',
        }],
      };
      const content = [
        { type: 'text', text: '<skill-loaded name="deploy">private instructions</skill-loaded>' },
        { type: 'text', text: '<skill-loaded name="review">private instructions</skill-loaded>' },
        { type: 'text', text: 'steered in' },
      ];
      const records = [
        { type: 'context.append_message', message: { role: 'user', content: [{ type: 'text', text: 'active' }], toolCalls: [], origin: { kind: 'user' } }, time: 1000 },
        { type: 'turn.steer', input: content, origin, time: 3000 },
        { type: 'context.append_message', message: { role: 'user', content, toolCalls: [], origin }, time: 3001 },
      ];
      await writeFile(join(wireDir, 'wire.jsonl'), `${records.map((r) => JSON.stringify(r)).join('\n')}\n`);

      const snapshot = await coldTranscriptService(home).readColdSnapshot('s1', 'main');
      const turn = snapshot?.items.find((item) => item.kind === 'turn');
      if (turn?.kind !== 'turn') throw new Error('expected turn');
      const frame = turn.steps.flatMap((step) => step.frames).find(
        (candidate) => candidate.kind === 'text' && candidate.role === 'user',
      );
      expect(frame).toMatchObject({
        kind: 'text',
        role: 'user',
        text: 'steered in',
        origin: {
          kind: 'user',
          skillActivations: [
            { skillName: 'deploy' },
            { skillName: 'review', skillArgs: 'strict' },
          ],
        },
      });
      expect(JSON.stringify(frame)).not.toContain('/private/');
    } finally {
      await rm(home, { recursive: true, force: true });
    }
  });

  it('readColdSnapshot keeps skill-activation steers as skill markers instead of user frames', async () => {
    const home = await mkdtemp(join(tmpdir(), 'transcript-cold-skillsteer-'));
    try {
      const wireDir = join(home, 'sessions', 'ws', 's1', 'agents', 'main');
      await mkdir(wireDir, { recursive: true });
      const skillOrigin = {
        kind: 'skill_activation',
        activationId: 'a1',
        skillName: 'write-tui',
        trigger: 'model-tool',
        skillSource: 'project',
      };
      const nestedOrigin = { ...skillOrigin, activationId: 'a2', skillName: 'design', trigger: 'nested-skill' };
      const skillText = 'Skill tool loaded instructions for this request. Follow them.';
      const nestedText = 'Nested skill instructions.';
      const records = [
        { type: 'context.append_message', message: { role: 'user', content: [{ type: 'text', text: 'active' }], toolCalls: [], origin: { kind: 'user' } }, time: 1000 },
        { type: 'context.append_message', message: { role: 'assistant', content: [{ type: 'text', text: 'working' }], toolCalls: [] }, time: 2000 },
        { type: 'turn.steer', input: [{ type: 'text', text: skillText }], origin: skillOrigin, time: 3000 },
        { type: 'context.append_message', message: { role: 'user', content: [{ type: 'text', text: skillText }], toolCalls: [], origin: skillOrigin }, time: 3001 },
        { type: 'turn.steer', input: [{ type: 'text', text: nestedText }], origin: nestedOrigin, time: 3002 },
        { type: 'context.append_message', message: { role: 'user', content: [{ type: 'text', text: nestedText }], toolCalls: [], origin: nestedOrigin }, time: 3003 },
        { type: 'context.append_message', message: { role: 'assistant', content: [{ type: 'text', text: 'noted' }], toolCalls: [] }, time: 4000 },
      ];
      await writeFile(join(wireDir, 'wire.jsonl'), `${records.map((r) => JSON.stringify(r)).join('\n')}\n`);

      const snapshot = await coldTranscriptService(home).readColdSnapshot('s1', 'main');
      const markers = snapshot!.items.filter((item) => item.kind === 'marker');
      expect(markers).toHaveLength(2);
      expect(markers.every((item) => item.kind === 'marker' && item.marker === 'skill')).toBe(true);
      const turns = snapshot!.items.filter((item) => item.kind === 'turn');
      expect(turns).toHaveLength(1);
      const turn = turns[0];
      if (turn?.kind !== 'turn') throw new Error('expected turn');
      expect(turn.prompt).toBe('active');
      const userFrames = turn.steps
        .flatMap((step) => step.frames)
        .filter((frame) => frame.kind === 'text' && frame.role === 'user');
      expect(userFrames).toHaveLength(0);
    } finally {
      await rm(home, { recursive: true, force: true });
    }
  });

  it('readColdSnapshot drops undone task-turn boundaries so a redelivered notification folds', async () => {
    const home = await mkdtemp(join(tmpdir(), 'transcript-cold-undoboundary-'));
    try {
      const wireDir = join(home, 'sessions', 'ws', 's1', 'agents', 'main');
      await mkdir(wireDir, { recursive: true });
      const notification =
        '<notification id="task:task_9:completed" category="task" type="task.completed" source_kind="background_task" source_id="task_9">\nTitle: Background agent completed\nSeverity: info\ninspect done.\n</notification>';
      const taskOrigin = { kind: 'task', taskId: 'task_9', status: 'completed', notificationId: 'n1' };
      const opening = [
        { type: 'context.append_message', message: { role: 'user', content: [{ type: 'text', text: 'hi' }], toolCalls: [], origin: { kind: 'user' } }, time: 1000 },
        { type: 'context.append_message', message: { role: 'assistant', content: [{ type: 'text', text: 'answer' }], toolCalls: [] }, time: 2000 },
      ];
      const boundary = { type: 'turn.prompt', input: [{ type: 'text', text: notification }], origin: taskOrigin, time: 3000 };
      const delivered = { type: 'context.append_message', message: { role: 'user', content: [{ type: 'text', text: notification }], toolCalls: [], origin: taskOrigin }, time: 4000 };
      const reply = { type: 'context.append_message', message: { role: 'assistant', content: [{ type: 'text', text: 'reporting back' }], toolCalls: [] }, time: 5000 };
      const again = { type: 'context.append_message', message: { role: 'user', content: [{ type: 'text', text: 'again' }], toolCalls: [], origin: { kind: 'user' } }, time: 7000 };
      const answer2 = { type: 'context.append_message', message: { role: 'assistant', content: [{ type: 'text', text: 'answer2' }], toolCalls: [] }, time: 8000 };
      const redelivered = { type: 'context.append_message', message: { role: 'user', content: [{ type: 'text', text: notification }], toolCalls: [], origin: taskOrigin }, time: 9000 };
      const write = async (records: unknown[]): Promise<void> =>
        writeFile(join(wireDir, 'wire.jsonl'), `${records.map((r) => JSON.stringify(r)).join('\n')}\n`);

      await write([...opening, boundary, delivered, reply, again, answer2, redelivered]);
      const withBoundary = await coldTranscriptService(home).readColdSnapshot('s1', 'main');
      const originKinds = withBoundary!.items
        .filter((item) => item.kind === 'turn')
        .map((item) => (item.kind === 'turn' ? item.origin.kind : ''));
      expect(originKinds).toEqual(['user', 'task', 'user', 'task']);

      await write([...opening, boundary, delivered, reply, { type: 'context.undo', count: 1, time: 6000 }, again, answer2, redelivered]);
      const withUndo = await coldTranscriptService(home).readColdSnapshot('s1', 'main');
      const undoTurns = withUndo!.items.filter((item) => item.kind === 'turn');
      expect(undoTurns).toHaveLength(1);
      const undoTurn = undoTurns[0];
      if (undoTurn?.kind !== 'turn') throw new Error('expected turn');
      expect(undoTurn.origin.kind).toBe('user');
      expect(
        undoTurn.steps
          .flatMap((step) => step.frames)
          .some((f) => f.kind === 'text' && f.text.includes('inspect done')),
      ).toBe(false);
    } finally {
      await rm(home, { recursive: true, force: true });
    }
  });

  it('gates the cold tower mode badge behind the tower experiment flag', async () => {
    const home = await mkdtemp(join(tmpdir(), 'transcript-cold-tower-'));
    try {
      const wireDir = join(home, 'sessions', 'ws', 's1', 'agents', 'main');
      await mkdir(wireDir, { recursive: true });
      const records = [
        {
          type: 'context.append_message',
          message: {
            role: 'user',
            content: [{ type: 'text', text: 'hi' }],
            toolCalls: [],
            origin: { kind: 'user' },
          },
          time: 1000,
        },
        { type: 'tower_mode.enter', time: 2000 },
      ];
      await writeFile(join(wireDir, 'wire.jsonl'), `${records.map((r) => JSON.stringify(r)).join('\n')}\n`);

      const serviceWith = (
        flagOn: boolean,
        opts: { cwd?: string; liveSessionIds?: string[] } = {},
      ) =>
        new TranscriptService({
          homeDir: home,
          core: {
            accessor: {
              get: (token: unknown) => {
                if (token === ISessionManager) {
                  return {
                    get: (id: string) => (opts.liveSessionIds?.includes(id) ? {} : undefined),
                    list: () => [],
                  };
                }
                if (token === IWorkspaceInstanceManager) {
                  return { list: () => [], onDidChange: () => ({ dispose: () => undefined }) };
                }
                if (token === ISessionIndex) {
                  return { get: async () => ({ workspaceId: 'ws', cwd: opts.cwd }) };
                }
                if (token === IFlagService) {
                  return { enabled: (id: string) => flagOn && id === TOWER_FLAG_ID };
                }
                return undefined;
              },
            },
          } as unknown as Scope,
        });

      const withFlag = await serviceWith(true).readColdSnapshot('s1', 'main');
      expect(withFlag!.meta.modes).toEqual({ tower: {} });

      const withoutFlag = await serviceWith(false).readColdSnapshot('s1', 'main');
      expect(withoutFlag!.meta.modes).toBeUndefined();

      _setTowerFeatureAssembledForTests(false);
      try {
        const notAssembled = await serviceWith(true).readColdSnapshot('s1', 'main');
        expect(notAssembled!.meta.modes).toBeUndefined();
      } finally {
        _setTowerFeatureAssembledForTests(true);
      }

      const repo = await mkdtemp(join(tmpdir(), 'tower-cold-owner-'));
      try {
        await execFileAsync('git', ['init', '-b', 'main'], { cwd: repo });
        await execFileAsync('git', ['config', 'user.email', 'tower-test@example.com'], { cwd: repo });
        await execFileAsync('git', ['config', 'user.name', 'Tower Test'], { cwd: repo });
        await writeFile(join(repo, 'README.md'), '# fixture\n');
        await execFileAsync('git', ['add', 'README.md'], { cwd: repo });
        await execFileAsync('git', ['commit', '-m', 'initial'], { cwd: repo });
        await new TowerStore(repo).init('session-b');

        const adoptedByLive = await serviceWith(true, {
          cwd: repo,
          liveSessionIds: ['session-b'],
        }).readColdSnapshot('s1', 'main');
        expect(adoptedByLive!.meta.modes).toBeUndefined();

        const adoptedByDead = await serviceWith(true, { cwd: repo }).readColdSnapshot('s1', 'main');
        expect(adoptedByDead!.meta.modes).toEqual({ tower: {} });
      } finally {
        await rm(repo, { recursive: true, force: true });
      }

      const childDir = join(home, 'sessions', 'ws', 's1', 'agents', 'worker-1');
      await mkdir(childDir, { recursive: true });
      await writeFile(
        join(childDir, 'wire.jsonl'),
        `${records.map((r) => JSON.stringify(r)).join('\n')}\n`,
      );
      const child = await serviceWith(true).readColdSnapshot('s1', 'worker-1');
      expect(child!.meta.modes).toBeUndefined();
    } finally {
      await rm(home, { recursive: true, force: true });
    }
  });

  it('folds blocked turn endings into failed (engine wire contract)', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    tx.apply(projector.map(ev({ type: 'turn.started', turnId: 0, origin: { kind: 'user' } })));
    tx.apply(projector.map(ev({ type: 'turn.ended', turnId: 0, reason: 'blocked' })));
    expect(turnOps('t0', tx.getItems()).state).toBe('failed');
  });

  it('tracks the prompt queue from submitted/queued through terminal', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'prompt.submitted', promptId: 'p1', userMessageId: 'p1', status: 'running', content: [{ type: 'text', text: 'now' }], createdAt: '2026-08-20T00:00:00.000Z' }));
    expect(tx.getPrompt('p1')).toMatchObject({ status: 'running' });
    feed(ev({ type: 'prompt.queued', promptId: 'p2', content: [{ type: 'text', text: 'later' }], queueLength: 1 }));
    expect(tx.getPrompt('p2')).toMatchObject({ status: 'queued' });
    feed(ev({ type: 'prompt.completed', promptId: 'p2', finishedAt: '2026-08-20T00:00:01.000Z', reason: 'completed' }));
    expect(tx.getPrompt('p2')).toMatchObject({ status: 'completed' });
    feed(ev({ type: 'prompt.aborted', promptId: 'p1', abortedAt: '2026-08-20T00:00:02.000Z' }));
    expect(tx.getPrompt('p1')).toMatchObject({ status: 'aborted' });
  });

  it('mirrors turn liveness into meta.activity', () => {    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    expect(tx.getMeta().activity).toBeUndefined();
    feed(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'user' } }));
    expect(tx.getMeta().activity).toBe('turn');
    feed(ev({ type: 'turn.ended', turnId: 1, reason: 'completed' }));
    expect(tx.getMeta().activity).toBe('idle');
    feed(ev({ type: 'turn.started', turnId: 2, origin: { kind: 'user' } }));
    expect(tx.getMeta().activity).toBe('turn');
    feed(ev({ type: 'turn.ended', turnId: 2, reason: 'failed' }));
    expect(tx.getMeta().activity).toBe('idle');
  });

  it('maps cron / task origins onto the turn header', () => {    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(
      ev({
        type: 'turn.started',
        turnId: 1,
        origin: { kind: 'cron_job', jobId: 'job-9', cron: '* * * * *' },
      }),
    );
    feed(
      ev({
        type: 'turn.started',
        turnId: 2,
        origin: { kind: 'task', taskId: 'bash-1', status: 'completed', notificationId: 'n1' },
      }),
    );

    expect(turnOps('t1', tx.getItems()).origin).toEqual({
      kind: 'cron',
      taskId: 'job-9',
      payload: { kind: 'cron_job', jobId: 'job-9', cron: '* * * * *' },
    });
    expect(turnOps('t2', tx.getItems()).origin).toEqual({
      kind: 'task',
      taskId: 'bash-1',
      payload: { kind: 'task', taskId: 'bash-1', status: 'completed', notificationId: 'n1' },
    });
  });

  it('treats subagent.started/failed/suspended within the running→failed vocabulary', () => {
    const projector = new AgentTranscriptProjector('main', TEST_SESSION_ID);
    const tx = new AgentTranscript('main');
    const feed = (event: ProjectorBusEvent): void => void tx.apply(projector.map(event));

    feed(ev({ type: 'subagent.started', subagentId: 'agent-1' }));
    expect(tx.getTask('agent-1')).toMatchObject({ kind: 'subagent', state: 'running' });
    feed(ev({ type: 'subagent.suspended', subagentId: 'agent-1', reason: 'approval' }));
    expect(tx.getTask('agent-1')).toMatchObject({ state: 'running', stateReason: 'approval' });
    feed(ev({ type: 'subagent.failed', subagentId: 'agent-1', error: 'boom' }));
    expect(tx.getTask('agent-1')).toMatchObject({ state: 'failed', error: 'boom' });

    feed(
      ev({
        type: 'subagent.completed',
        subagentId: 'agent-2',
        resultSummary: 'found 3 files',
        usage: { inputOther: 10, output: 5, inputCacheRead: 2, inputCacheCreation: 1 },
      }),
    );
    expect(tx.getTask('agent-2')).toMatchObject({
      state: 'completed',
      resultSummary: 'found 3 files',
      usage: { inputOther: 10, output: 5, inputCacheRead: 2, inputCacheCreation: 1 },
    });
  });
});

describe('AgentTranscript transcript task vocabulary', () => {
  it('documents the task states used by the projector', () => {
    const states: Array<TranscriptTask['state']> = [
      'running',
      'completed',
      'failed',
      'timed_out',
      'killed',
      'lost',
    ];
    expect(states).toHaveLength(6);
  });
});

describe('bindSessionTranscript', () => {
  class FakeBus {
    private readonly handlers = new Set<(event: Event2<any>) => void>();
    subscribe(cb: (event: Event2<any>) => void): { dispose: () => void } {
      this.handlers.add(cb);
      return { dispose: () => this.handlers.delete(cb) };
    }
    emit(event: Event2<any>): void {
      for (const cb of this.handlers) cb(event);
    }
  }


  interface FakeAgentHandle {
    readonly id: string;
    readonly context: AgentContext;
    readonly bus: FakeBus;
    contextMessages: ContextMessage[];
    readonly undoParticipants: Map<string, AgentConversationUndoParticipant>;
    readonly accessor: { get: (token: unknown) => unknown };
  }

  class FakeAgents {
    private readonly handles = new Map<string, FakeAgentHandle>();
    private readonly createHandlers = new Set<(context: AgentContext) => void>();
    private readonly closeHandlers = new Set<(context: AgentContext) => void>();

    list(): AgentContext[] {
      return [...this.handles.values()].map((handle) => handle.context);
    }
    get(agentId: string): AgentContext | undefined {
      return this.handles.get(agentId)?.context;
    }
    handleOf(agentId: string): FakeAgentHandle | undefined {
      return this.handles.get(agentId);
    }
    byId(id: string): FakeAgentHandle | undefined {
      return this.handles.get(id);
    }
    onDidCreate(cb: (context: AgentContext) => void): { dispose: () => void } {
      this.createHandlers.add(cb);
      return { dispose: () => this.createHandlers.delete(cb) };
    }
    onDidClose(cb: (context: AgentContext) => void): { dispose: () => void } {
      this.closeHandlers.add(cb);
      return { dispose: () => this.closeHandlers.delete(cb) };
    }
    add(id: string, opts?: { loopStatus?: { state?: 'idle' | 'running'; activeTurnId?: number }; tasks?: readonly unknown[]; activePromptId?: string }): FakeAgentHandle {
      const bus = this.handles.get(id)?.bus ?? new FakeBus();
      const undoParticipants = new Map<string, AgentConversationUndoParticipant>();
      const scope = makeAgentScopeContext({
        agentId: id,
        agentScope: `agents/${id}`,
        generation: 1,
      });
      let activity: AgentActivitySnapshot = {};
      bus.subscribe((event) => {
        if (event.type === 'turn.started') {
          activity = {
            turn: {
              turnId: (event as { turnId?: number }).turnId ?? 0,
              phase: 'running',
              step: 1,
              ending: false,
              activeToolCalls: [],
              since: 0,
            },
          };
        } else if (event.type === 'turn.ended') {
          activity = {};
        }
      });
      const handle: FakeAgentHandle = {
        id,
        context: scope.agentContext,
        bus,
        contextMessages: [],
        undoParticipants,
        accessor: {
          get: (token: unknown) => {
            if (token === IAgentScopeContext) return scope;
            if (token === IEventBus) return bus;
            if (token === IAgentContextMemoryService) return { get: () => handle.contextMessages };
            if (token === IAgentConversationUndoParticipantRegistry) {
              return {
                register: (participant: AgentConversationUndoParticipant) => {
                  undoParticipants.set(participant.id, participant);
                  return { dispose: () => { undoParticipants.delete(participant.id); } };
                },
              };
            }
            if (token === IAgentLoopService) {
              const active =
                opts?.activePromptId === undefined
                  ? undefined
                  : {
                      id: opts.activePromptId,
                      userMessageId: opts.activePromptId,
                      createdAt: '2026-01-01T00:00:00.000Z',
                      state: 'running' as const,
                      message: {
                        role: 'user' as const,
                        content: [{ type: 'text' as const, text: 'hi' }],
                        toolCalls: [],
                        origin: { kind: 'user' as const },
                      },
                      launched: Promise.resolve(undefined),
                      completion: new Promise(() => {}),
                    };
              return {
                snapshot: () => ({
                  state: opts?.loopStatus?.state ?? (activity.turn === undefined ? 'idle' : 'running'),
                  activeTurnId: opts?.loopStatus?.activeTurnId ?? activity.turn?.turnId,
                  activePromptId: opts?.activePromptId,
                  queue: [],
                  notificationCount: 0,
                  paused: false,
                  hasPendingRequests: activity.turn !== undefined,
                  turn: activity.turn,
                  activeTraceId: undefined,
                }),
                promptHandle: (id: string) => (active?.id === id ? active : undefined),
              };
            }
            if (token === IAgentTaskService) {
              return { list: () => opts?.tasks ?? [] };
            }
            return undefined;
          },
        },
      };
      this.handles.set(id, handle);
      for (const cb of this.createHandlers) cb(handle.context);
      return handle;
    }
    remove(id: string): void {
      const removed = this.handles.get(id);
      this.handles.delete(id);
      if (removed !== undefined) {
        for (const cb of this.closeHandlers) cb(removed.context);
      }
    }
  }

  function fakeSession(manager: FakeAgents): ISessionScopeHandle {
    return {
      id: 's1',
      accessor: {
        get: (token: unknown) => {
          if (token === IAgentLifecycleService) return manager;
          if (token === ISessionMetadata) return { read: async () => ({ agents: {} }) };
          return undefined;
        },
      },
    } as unknown as ISessionScopeHandle;
  }

  afterEach(() => {
    interactions.purgeSession('s1');
  });

  it('registers pre-bind pendings without frames and replays an early resolve at seed time', () => {
    const agents = new FakeAgents();
    interactions.enqueue({
      id: 'apr-1',
      kind: 'approval',
      payload: { toolCallId: 'call_1' },
      tags: { agentId: 'main', sessionId: 's1', turnId: 0 },
    });

    const store = new TranscriptStore('s1');
    const ops: TranscriptOperation[] = [];
    const binding = bindSessionTranscript(store, fakeSession(agents), undefined, (event) =>
      ops.push(...event.ops),
    );

    expect(ops).toHaveLength(0);

    interactions.respond('apr-1', { decision: 'approved' });
    expect(ops).toHaveLength(0);

    binding.seedPendingInteractions();
    const states = ops
      .filter((op): op is InteractionUpsertOp => op.op === 'interaction.upsert')
      .map((op) => op.interaction.state);
    expect(states).toEqual(['pending', 'approved']);
    binding.dispose();
  });

  it('keeps the materialized transcript and roster entry when an agent is disposed', () => {
    const agents = new FakeAgents();
    const store = new TranscriptStore('s1');
    const binding = bindSessionTranscript(
      store,
      fakeSession(agents),
    );

    const sub = agents.add('sub-1');
    agents.add('main');
    sub.bus.emit(ev({ type: 'turn.started', turnId: 0, origin: { kind: 'user' }, prompt: 'scan' }));
    sub.bus.emit(ev({ type: 'turn.ended', turnId: 0, reason: 'completed' }));
    expect(store.getAgent('sub-1')?.getItems()).toHaveLength(1);

    agents.remove('sub-1');
    expect(store.getAgent('sub-1')?.getItems()).toHaveLength(1);
    const descriptor = store.agents().find((a) => a.agentId === 'sub-1');
    expect(descriptor).toBeDefined();
    expect(typeof descriptor?.disposedAt).toBe('string');
    expect(store.agents().find((a) => a.agentId === 'main')?.disposedAt).toBeUndefined();
    binding.dispose();
  });

  it('seeds pre-attach Agent task mappings so a late-bound projector folds the lifecycle', () => {
    const agents = new FakeAgents();
    agents.add('main', {
      tasks: [
        {
          taskId: 'task-9',
          kind: 'agent',
          agentId: 'agent-1',
          status: 'running',
          description: 'Inspect',
          detached: false,
          startedAt: 1_700_000_000_000,
        },
      ],
    });
    const store = new TranscriptStore('s1');
    const binding = bindSessionTranscript(
      store,
      fakeSession(agents),
    );

    expect(store.getAgent('main')?.getTask('task-9')).toMatchObject({
      kind: 'subagent',
      state: 'running',
      detached: false,
      description: 'Inspect',
      agentId: 'agent-1',
    });

    agents.byId('main')!.bus.emit(ev({ type: 'subagent.completed', subagentId: 'agent-1', resultSummary: 'done' }));

    expect(store.getAgent('main')?.getTask('task-9')).toMatchObject({
      state: 'completed',
      resultSummary: 'done',
      detached: false,
    });
    expect(store.getAgent('main')?.getTask('agent-1')).toBeUndefined();
    binding.dispose();
  });

  const SHOT_PNG_UPLOAD = {
    type: 'file',
    file_id: 'file_1',
    media_type: 'image/png',
    name: 'shot.png',
  };

  async function seedWireHome(attachment?: Record<string, unknown>): Promise<string> {
    const home = await mkdtemp(join(tmpdir(), 'transcript-overlay-'));
    const wireDir = join(home, 'sessions', 'ws', 's1', 'agents', 'main');
    await mkdir(wireDir, { recursive: true });
    const records: Record<string, unknown>[] = [
      {
        type: 'context.append_message',
        message: {
          role: 'user',
          content:
            attachment === undefined
              ? [{ type: 'text', text: 'hi' }]
              : [{ type: 'text', text: 'what is this?' }, attachment],
          toolCalls: [],
          origin: { kind: 'user' },
        },
        time: new Date().toISOString(),
      },
    ];
    if (attachment !== undefined) {
      records.push({
        type: 'context.append_message',
        message: {
          role: 'assistant',
          content: [{ type: 'text', text: 'a screenshot' }],
          toolCalls: [],
        },
        time: new Date().toISOString(),
      });
    }
    await writeFile(join(wireDir, 'wire.jsonl'), `${records.map((r) => JSON.stringify(r)).join('\n')}\n`);
    return home;
  }

  function fakeCoreWithAgents(agents: FakeAgents): Scope {
    const sessionLifecycle = {
      onDidCloseSession: () => ({ dispose: () => undefined }),
      onDidArchiveSession: () => ({ dispose: () => undefined }),
      get: (sid: string) => (sid === 's1' ? fakeSession(agents) : undefined),
    };
    const handler = {
      id: 'ws',
      kind: 'program',
      accessor: {
        get: (t: unknown) => (t === ISessionLifecycleService ? sessionLifecycle : undefined),
      },
      dispose: () => undefined,
    };
    return {
      accessor: {
        get: (token: unknown) => {
          if (token === ISessionManager) {
            return { get: sessionLifecycle.get, list: () => [sessionLifecycle.get('s1')] };
          }
          if (token === IWorkspaceInstanceManager) {
            return {
              list: () => [{ program: { accessor: handler.accessor } }],
              onDidChange: () => ({ dispose: () => undefined }),
            };
          }
          if (token === ISessionIndex) return { get: async () => ({ workspaceId: 'ws' }) };
          return undefined;
        },
      },
    } as unknown as Scope;
  }

  it('stops projecting for an agent once it is disposed', () => {
    const agents = new FakeAgents();
    const store = new TranscriptStore('s1');
    const binding = bindSessionTranscript(
      store,
      fakeSession(agents),
    );

    const sub = agents.add('sub-1');
    sub.bus.emit(ev({ type: 'turn.started', turnId: 0, origin: { kind: 'user' }, prompt: 'scan' }));
    expect(store.getAgent('sub-1')?.getItems()).toHaveLength(1);

    agents.remove('sub-1');
    sub.bus.emit(ev({ type: 'turn.ended', turnId: 0, reason: 'completed' }));
    expect(store.getAgent('sub-1')?.getItems()[0]).toMatchObject({ kind: 'turn', state: 'running' });
    binding.dispose();
  });

  it('heals a kind-mismatched frame instead of skipping it on length', () => {
    const snapshotTurn: TranscriptTurn = {
      kind: 'turn',
      turnId: 't0',
      ordinal: 0,
      state: 'completed',
      origin: { kind: 'user' },
      steps: [
        {
          kind: 'step',
          stepId: 't0.1',
          turnId: 't0',
          ordinal: 1,
          state: 'completed',
          frames: [
            { kind: 'thinking', frameId: 't0.1.f1', text: 'hmm' },
            { kind: 'text', frameId: 't0.1.f2', role: 'assistant', text: 'Hello world' },
          ],
        },
      ],
    };
    const liveTurn: TranscriptTurn = {
      kind: 'turn',
      turnId: 't0',
      ordinal: 0,
      state: 'completed',
      origin: { kind: 'user' },
      steps: [
        {
          kind: 'step',
          stepId: 't0.1',
          turnId: 't0',
          ordinal: 1,
          state: 'completed',
          frames: [{ kind: 'text', frameId: 't0.1.f1', role: 'assistant', text: 'world' }],
        },
      ],
    };

    const frames = healTurnOps(snapshotTurn, liveTurn)
      .filter((op): op is FrameUpsertOp => op.op === 'frame.upsert')
      .map((op) => op.frame);
    expect(frames).toContainEqual(expect.objectContaining({ kind: 'thinking', frameId: 't0.1.f1', text: 'hmm' }));
    expect(frames).toContainEqual(expect.objectContaining({ kind: 'text', frameId: 't0.1.f2', text: 'Hello world' }));
  });

  it('heals missing tool frames and missed results, keeps richer live ones', () => {
    const makeTurn = (frames: TranscriptTurn['steps'][number]['frames']): TranscriptTurn => ({
      kind: 'turn',
      turnId: 't0',
      ordinal: 0,
      state: 'completed',
      origin: { kind: 'user' },
      steps: [
        { kind: 'step', stepId: 't0.1', turnId: 't0', ordinal: 1, state: 'completed', frames },
      ],
    });
    const snapshotTurn = makeTurn([
      { kind: 'tool', frameId: 't0.1.call_1', toolCallId: 'call_1', name: 'Bash', state: 'done', input: { command: 'ls' }, output: 'a.txt' },
      { kind: 'tool', frameId: 't0.1.call_2', toolCallId: 'call_2', name: 'Read', state: 'done', input: {}, output: 'x' },
      { kind: 'tool', frameId: 't0.1.call_3', toolCallId: 'call_3', name: 'Bash', state: 'done', input: {}, output: 'y' },
    ]);
    const liveTurn = makeTurn([
      { kind: 'tool', frameId: 't0.1.call_1', toolCallId: 'call_1', name: 'Bash', state: 'running', input: { command: 'ls' }, display: { kind: 'command', command: 'ls' } },
      { kind: 'tool', frameId: 't0.1.call_2', toolCallId: 'call_2', name: 'Read', state: 'done', input: {}, output: 'live-out' },
    ]);

    const frames = healTurnOps(snapshotTurn, liveTurn)
      .filter((op): op is FrameUpsertOp => op.op === 'frame.upsert')
      .map((op) => op.frame);
    expect(frames).toHaveLength(2);
    expect(frames).toContainEqual(
      expect.objectContaining({
        frameId: 't0.1.call_1',
        state: 'done',
        output: 'a.txt',
        display: { kind: 'command', command: 'ls' },
      }),
    );
    expect(frames).toContainEqual(expect.objectContaining({ frameId: 't0.1.call_3', output: 'y' }));
  });

  it('heal keeps the live attachment ids over the snapshot cold ids', () => {
    const makeTurn = (attachmentIds: string[] | undefined): TranscriptTurn => ({
      kind: 'turn',
      turnId: 't0',
      ordinal: 0,
      state: 'completed',
      origin: { kind: 'user' },
      attachmentIds,
      steps: [],
    });
    const header = healTurnOps(makeTurn(['att_1']), makeTurn(['t0.att1'])).find(
      (op) => op.op === 'turn.upsert',
    );
    expect(header).toMatchObject({ turn: { attachmentIds: ['t0.att1'] } });
    const fallback = healTurnOps(makeTurn(['att_1']), makeTurn(undefined)).find(
      (op) => op.op === 'turn.upsert',
    );
    expect(fallback).toMatchObject({ turn: { attachmentIds: ['att_1'] } });
  });

  it('heal keeps the live trigger prompt id over a cold turn without one', () => {
    const makeTurn = (triggerPromptId: string | undefined): TranscriptTurn => ({
      kind: 'turn',
      turnId: 't0',
      triggerPromptId,
      ordinal: 0,
      state: 'completed',
      origin: { kind: 'user' },
      steps: [],
    });
    const header = healTurnOps(makeTurn(undefined), makeTurn('prompt-1')).find(
      (op) => op.op === 'turn.upsert',
    );
    expect(header).toMatchObject({ turn: { triggerPromptId: 'prompt-1' } });
  });

  it('terminal turn.upsert inherits the backfilled header when the projector missed turn.started', () => {
    const agents = new FakeAgents();
    const store = new TranscriptStore('s1');
    const ops: TranscriptOperation[] = [];
    const binding = bindSessionTranscript(
      store,
      fakeSession(agents),
      undefined,
      (event) => ops.push(...event.ops),
    );
    const main = agents.add('main');

    store.ensureAgent('main').apply([
      {
        op: 'attachment.upsert',
        attachment: {
          attachmentId: 'att_1',
          mediaType: 'image/*',
          name: 'shot.png',
          source: { kind: 'file', fileId: 'f_1' },
        },
      },
      {
        op: 'turn.upsert',
        turn: {
          kind: 'turn',
          turnId: 't0',
          ordinal: 0,
          state: 'running',
          origin: { kind: 'user' },
          prompt: 'hi',
          attachmentIds: ['att_1'],
          startedAt: '2026-08-04T00:00:00.000Z',
        },
      },
    ]);

    main.bus.emit(ev({ type: 'turn.ended', turnId: 0, reason: 'completed' }));

    const terminal = ops.filter((op) => op.op === 'turn.upsert');
    expect(terminal).toHaveLength(1);
    expect(terminal[0]).toMatchObject({
      turn: {
        turnId: 't0',
        state: 'completed',
        origin: { kind: 'user' },
        prompt: 'hi',
        attachmentIds: ['att_1'],
        startedAt: '2026-08-04T00:00:00.000Z',
      },
    });
    expect(store.getAgent('main')?.getTurn('t0')).toMatchObject({
      state: 'completed',
      prompt: 'hi',
      attachmentIds: ['att_1'],
    });
    binding.dispose();
  });

  it('seeds pending interactions per agent, not before that agent is backfilled', () => {
    const agents = new FakeAgents();
    interactions.enqueue({ id: 'q-main', kind: 'question', payload: { toolCallId: 'call_main' }, tags: { agentId: 'main', sessionId: 's1', turnId: 0 } });
    interactions.enqueue({ id: 'q-sub', kind: 'question', payload: { toolCallId: 'call_sub' }, tags: { agentId: 'sub-1', sessionId: 's1', turnId: 0 } });

    const store = new TranscriptStore('s1');
    const byAgent = new Map<string, TranscriptOperation[]>();
    const binding = bindSessionTranscript(store, fakeSession(agents), undefined, (event) => {
      byAgent.set(event.agentId, [...(byAgent.get(event.agentId) ?? []), ...event.ops]);
    });

    binding.seedPendingInteractions('main');
    expect([...byAgent.keys()]).toEqual(['main']);

    binding.seedPendingInteractions('sub-1');
    expect([...byAgent.keys()].toSorted()).toEqual(['main', 'sub-1']);
    binding.dispose();
  });

  it('projects live question entities with the same wire shape as the legacy question event', () => {
    const agents = new FakeAgents();
    const asked = interactions.enqueue({
      id: 'q-parity',
      kind: 'question',
      payload: {
        questions: [
          {
            question: 'Pick one',
            options: [{ label: 'A', description: 'first' }, { label: 'B' }],
          },
        ],
      },
      tags: { agentId: 'main', sessionId: 's1', turnId: 0 },
    });
    const store = new TranscriptStore('s1');
    const binding = bindSessionTranscript(store, fakeSession(agents));

    binding.seedPendingInteractions('main');

    const entity = store.getAgent('main')?.getInteraction('q-parity');
    expect(entity?.state).toBe('pending');
    expect(entity?.request).toEqual(toWireQuestion(asked, 's1'));
    binding.dispose();
  });

  it('defers pendings created before their owning agent is seeded', () => {
    const agents = new FakeAgents();
    const store = new TranscriptStore('s1');
    const byAgent = new Map<string, TranscriptOperation[]>();
    const binding = bindSessionTranscript(store, fakeSession(agents), undefined, (event) => {
      byAgent.set(event.agentId, [...(byAgent.get(event.agentId) ?? []), ...event.ops]);
    });

    interactions.enqueue({ id: 'q-sub', kind: 'question', payload: { toolCallId: 'call_sub' }, tags: { agentId: 'sub-1', sessionId: 's1', turnId: 0 } });
    expect(byAgent.size).toBe(0);

    binding.seedPendingInteractions('main');
    expect(byAgent.size).toBe(0);

    binding.seedPendingInteractions('sub-1');
    expect([...byAgent.keys()]).toEqual(['sub-1']);
    binding.dispose();
  });

  it('announces pendings from live-created agents immediately (their projector is complete)', () => {
    const agents = new FakeAgents();
    const store = new TranscriptStore('s1');
    const byAgent = new Map<string, TranscriptOperation[]>();
    const binding = bindSessionTranscript(store, fakeSession(agents), undefined, (event) => {
      byAgent.set(event.agentId, [...(byAgent.get(event.agentId) ?? []), ...event.ops]);
    });

    agents.add('sub-1');
    interactions.enqueue({ id: 'q1', kind: 'question', payload: { toolCallId: 'call_q1' }, tags: { agentId: 'sub-1', sessionId: 's1', turnId: 0 } });
    expect([...byAgent.keys()]).toEqual(['sub-1']);
    binding.dispose();
  });

  async function seedWireHomeWithTool(): Promise<string> {
    const home = await mkdtemp(join(tmpdir(), 'transcript-backfill-live-'));
    const wireDir = join(home, 'sessions', 'ws', 's1', 'agents', 'main');
    await mkdir(wireDir, { recursive: true });
    const records = [
      {
        type: 'context.append_message',
        message: {
          role: 'user',
          content: [{ type: 'text', text: 'hi' }],
          toolCalls: [],
          origin: { kind: 'user' },
        },
        time: new Date().toISOString(),
      },
      {
        type: 'context.append_message',
        message: {
          role: 'assistant',
          content: [{ type: 'text', text: 'Hello ' }],
          toolCalls: [{ type: 'function', id: 'call_1', name: 'Bash', arguments: '{"command":"ls"}' }],
        },
        time: new Date().toISOString(),
      },
      {
        type: 'context.append_message',
        message: {
          role: 'tool',
          content: [{ type: 'text', text: 'a.txt' }],
          toolCallId: 'call_1',
          toolCalls: [],
        },
        time: new Date().toISOString(),
      },
    ];
    await writeFile(join(wireDir, 'wire.jsonl'), `${records.map((r) => JSON.stringify(r)).join('\n')}\n`);
    return home;
  }

  async function waitFor(condition: () => boolean, timeoutMs = 2000): Promise<void> {
    const deadline = Date.now() + timeoutMs;
    while (!condition()) {
      if (Date.now() > deadline) throw new Error('waitFor timed out');
      await new Promise((resolve) => setTimeout(resolve, 20));
    }
  }

  it('subscribes the bus for an agent whose projector was seeded before its handle existed', () => {
    const agents = new FakeAgents();
    interactions.enqueue({ id: 'q-sub', kind: 'question', payload: { toolCallId: 'call_sub' }, tags: { agentId: 'sub-1', sessionId: 's1', turnId: 0 } });
    const store = new TranscriptStore('s1');
    const byAgent = new Map<string, TranscriptOperation[]>();
    const binding = bindSessionTranscript(store, fakeSession(agents), undefined, (event) => {
      byAgent.set(event.agentId, [...(byAgent.get(event.agentId) ?? []), ...event.ops]);
    });

    binding.seedPendingInteractions('sub-1');
    expect(byAgent.get('sub-1')?.map((op) => op.op)).toEqual(['interaction.upsert']);

    const sub = agents.add('sub-1');
    sub.bus.emit(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'user' } }));
    expect(byAgent.get('sub-1')!.length).toBeGreaterThan(1);
    binding.dispose();
  });

  it('seeds active prompt identity before a late-bound turn ends', () => {
    const agents = new FakeAgents();
    const main = agents.add('main', {
      loopStatus: { state: 'running', activeTurnId: 0 },
      activePromptId: 'prompt-1',
    });
    const store = new TranscriptStore('s1');
    const binding = bindSessionTranscript(store, fakeSession(agents));

    main.bus.emit(ev({ type: 'turn.ended', turnId: 0, reason: 'completed' }));

    expect(store.getAgent('main')?.getTurn('t0')).toMatchObject({
      state: 'completed',
      triggerPromptId: 'prompt-1',
    });
    binding.dispose();
  });

  it('overlays the in-flight turn as running after a backfill', async () => {
    const home = await seedWireHome();
    try {
      const agents = new FakeAgents();
      agents.add('main', {
        loopStatus: { state: 'running', activeTurnId: 0 },
        activePromptId: 'prompt-1',
      });
      const service = new TranscriptService({
        homeDir: home,
        core: fakeCoreWithAgents(agents),
      });
      const store = service.forSessionLive('s1');
      await service.whenReady('s1');
      expect(store?.getAgent('main')?.getTurn('t0')).toMatchObject({
        state: 'running',
        triggerPromptId: 'prompt-1',
        prompt: 'hi',
      });
      service.dropSession('s1');
    } finally {
      await rm(home, { recursive: true, force: true });
    }
  });

  it('merges the backfill live-first: live frame fields and longer text survive', async () => {
    const home = await seedWireHomeWithTool();
    try {
      const agents = new FakeAgents();
      agents.add('main', { loopStatus: { state: 'running', activeTurnId: 0 } });
      const service = new TranscriptService({
        homeDir: home,
        core: fakeCoreWithAgents(agents),
      });
      const store = service.forSessionLive('s1');
      const bus = agents.byId('main')!.bus;
      bus.emit(ev({ type: 'turn.started', turnId: 0, origin: { kind: 'user' }, prompt: 'hi' }));
      bus.emit(ev({ type: 'turn.step.started', turnId: 0, step: 1 }));
      bus.emit(ev({ type: 'assistant.delta', turnId: 0, delta: 'Hello world' }));
      bus.emit(
        ev({
          type: 'tool.call.started',
          turnId: 0,
          toolCallId: 'call_1',
          name: 'Bash',
          args: { command: 'ls' },
          display: { kind: 'command', command: 'ls' },
        }),
      );
      await service.whenReady('s1');

      const turn = store?.getAgent('main')?.getTurn('t0');
      expect(turn?.state).toBe('running');
      const text = turn?.steps[0]?.frames.find((f) => f.kind === 'text');
      expect(text).toMatchObject({ text: 'Hello world' });
      const tool = turn?.steps[0]?.frames.find((f) => f.kind === 'tool');
      expect(tool).toMatchObject({
        state: 'done',
        output: 'a.txt',
        display: { kind: 'command', command: 'ls' },
      });
      service.dropSession('s1');
    } finally {
      await rm(home, { recursive: true, force: true });
    }
  });

  it('re-asserts running when the backfill rebuilds the live turn completed', async () => {
    const home = await seedWireHome();
    try {
      const agents = new FakeAgents();
      agents.add('main', { loopStatus: { state: 'running', activeTurnId: 0 } });
      const service = new TranscriptService({
        homeDir: home,
        core: fakeCoreWithAgents(agents),
      });
      const store = service.forSessionLive('s1');
      agents
        .byId('main')!
        .bus.emit(ev({ type: 'turn.started', turnId: 0, origin: { kind: 'user' }, prompt: 'live hi' }));
      await service.whenReady('s1');
      expect(store?.getAgent('main')?.getTurn('t0')).toMatchObject({
        state: 'running',
        prompt: 'live hi',
      });
      service.dropSession('s1');
    } finally {
      await rm(home, { recursive: true, force: true });
    }
  });

  it('backfill + overlay keep the live attachment ids and drop the cold counterpart entity', async () => {
    const home = await seedWireHome(SHOT_PNG_UPLOAD);
    try {
      const agents = new FakeAgents();
      agents.add('main', { loopStatus: { state: 'running', activeTurnId: 0 } });
      const service = new TranscriptService({
        homeDir: home,
        core: fakeCoreWithAgents(agents),
      });
      const store = service.forSessionLive('s1');
      agents.byId('main')!.bus.emit(
        ev({
          type: 'turn.started',
          turnId: 0,
          origin: { kind: 'user' },
          prompt: 'live prompt',
          promptAttachments: [{ kind: 'image', fileId: 'file_1' }],
        }),
      );
      await service.whenReady('s1');

      const agent = store?.getAgent('main');
      expect(agent?.getTurn('t0')).toMatchObject({
        state: 'running',
        prompt: 'live prompt',
        attachmentIds: ['t0.att1'],
      });
      expect(agent?.getAttachment('t0.att1')).toBeDefined();
      expect(agent?.getAttachment('att_1')).toBeUndefined();
      service.dropSession('s1');
    } finally {
      await rm(home, { recursive: true, force: true });
    }
  });

  it('post-turn heal keeps the live attachment ids and never upserts the cold counterparts', async () => {
    const home = await seedWireHome(SHOT_PNG_UPLOAD);
    try {
      const agents = new FakeAgents();
      agents.add('main', { loopStatus: { state: 'idle' } });
      const service = new TranscriptService({
        homeDir: home,
        core: fakeCoreWithAgents(agents),
      });
      const store = service.forSessionLive('s1');
      const batches: TranscriptOperation[][] = [];
      service.onSessionOps('s1', (event) => {
        if (event.agentId === 'main') batches.push([...event.ops]);
      });
      const bus = agents.byId('main')!.bus;
      bus.emit(
        ev({
          type: 'turn.started',
          turnId: 0,
          origin: { kind: 'user' },
          prompt: 'live prompt',
          promptAttachments: [{ kind: 'image', fileId: 'file_1' }],
        }),
      );
      await service.whenReady('s1');

      bus.emit(ev({ type: 'turn.ended', turnId: 0, reason: 'completed' }));
      await waitFor(() =>
        batches.some((batch) => batch.some((op) => op.op === 'step.upsert' && op.turnId === 't0')),
      );
      const healBatch = batches.find((batch) =>
        batch.some((op) => op.op === 'step.upsert' && op.turnId === 't0'),
      )!;
      expect(healBatch.find((op) => op.op === 'turn.upsert')).toMatchObject({
        turn: { attachmentIds: ['t0.att1'] },
      });
      const attachmentUpserts = batches.flatMap((batch) =>
        batch.filter((op) => op.op === 'attachment.upsert'),
      );
      expect(attachmentUpserts).toEqual([
        { op: 'attachment.upsert', attachment: expect.objectContaining({ attachmentId: 't0.att1' }) },
      ]);

      const agent = store?.getAgent('main');
      expect(agent?.getTurn('t0')).toMatchObject({
        state: 'completed',
        attachmentIds: ['t0.att1'],
      });
      expect(agent?.getAttachment('t0.att1')).toBeDefined();
      expect(agent?.getAttachment('att_1')).toBeUndefined();
      service.dropSession('s1');
    } finally {
      await rm(home, { recursive: true, force: true });
    }
  });

  it.each([1, 2])('removes undone content even when the history read fails %i times', async (failures) => {
    const home = await seedWireHome();
    const agents = new FakeAgents();
    const main = agents.add('main');
    const service = new TranscriptService({ homeDir: home, core: fakeCoreWithAgents(agents) });
    try {
      const store = service.forSessionLive('s1')!;
      await service.whenReady('s1');
      expect(store.getAgent('main')!.getItems().length).toBeGreaterThan(0);
      main.contextMessages = [{ role: 'user', content: [{ type: 'text', text: 'hi' }], toolCalls: [], origin: { kind: 'user' } }];
      main.bus.emit(ev({ type: 'turn.started', turnId: 1, origin: { kind: 'user' }, prompt: 'undone prompt' }));
      const read = vi.spyOn(service, 'readColdSnapshot');
      for (let i = 0; i < failures; i++) read.mockRejectedValueOnce(new Error('temporary read failure'));
      await main.undoParticipants.get('transcript')!.reconcileAfterUndo();
      expect(store.getAgent('main')!.getItems().filter((item) => item.kind === 'turn').map((turn) => turn.prompt)).toEqual(['hi']);
      expect(service.getOpsSince('s1', 'main', 0)?.batches.at(-1)?.ops[0]?.op).toBe('reset');
      read.mockRestore();
    } finally {
      service.dropSession('s1');
      await rm(home, { recursive: true, force: true });
    }
  });

  it('does not restore undone messages from an earlier history read', async () => {
    const home = await seedWireHome();
    const agents = new FakeAgents();
    const main = agents.add('main');
    const service = new TranscriptService({ homeDir: home, core: fakeCoreWithAgents(agents) });
    try {
      const store = service.forSessionLive('s1')!;
      await service.whenReady('s1');
      const stale = await service.readColdSnapshot('s1', 'main');
      let release!: (snapshot: AgentTranscriptSnapshot | undefined) => void;
      const pending = new Promise<AgentTranscriptSnapshot | undefined>((resolve) => { release = resolve; });
      const read = vi.spyOn(service, 'readColdSnapshot').mockImplementationOnce(() => pending);
      main.bus.emit(ev({ type: 'turn.ended', turnId: 0, reason: 'completed' }));
      await waitFor(() => read.mock.calls.length === 1);
      await writeFile(join(home, 'sessions', 'ws', 's1', 'agents', 'main', 'wire.jsonl'), '');
      await main.undoParticipants.get('transcript')!.reconcileAfterUndo();
      expect(store.getAgent('main')?.getItems()).toEqual([]);
      release(stale);
      await new Promise((resolve) => setTimeout(resolve, 0));
      expect(store.getAgent('main')?.getItems()).toEqual([]);
      read.mockRestore();
    } finally {
      service.dropSession('s1');
      await rm(home, { recursive: true, force: true });
    }
  });

  describe('op journal', () => {
    it('assigns consecutive per-agent seqs and serves catch-up from the journal', async () => {
      const agents = new FakeAgents();
      const main = agents.add('main');
      const service = new TranscriptService({
        homeDir: '/nonexistent-home',
        core: fakeCoreWithAgents(agents),
      });
      service.forSessionLive('s1');
      await service.whenReady('s1');
      const base = service.getSeqWatermark('s1', 'main');

      const seen: number[] = [];
      service.onSessionOps('s1', (_event, seq) => seen.push(seq));
      main.bus.emit(ev({ type: 'turn.started', turnId: 0, origin: { kind: 'user' } }));
      main.bus.emit(ev({ type: 'turn.ended', turnId: 0, reason: 'completed' }));

      expect(seen).toEqual([base + 1, base + 2]);
      expect(service.getSeqWatermark('s1', 'main')).toBe(base + 2);

      const catchup = service.getOpsSince('s1', 'main', base);
      expect(catchup?.complete).toBe(true);
      expect(catchup?.latestSeq).toBe(base + 2);
      expect(catchup?.batches.map((batch) => batch.seq)).toEqual([base + 1, base + 2]);

      expect(service.getOpsSince('s1', 'main', base + 2)).toMatchObject({
        batches: [],
        latestSeq: base + 2,
        complete: true,
      });
      expect(service.getOpsSince('s1', 'main', base + 3)?.complete).toBe(false);

      const sub = agents.add('sub-1');
      sub.bus.emit(ev({ type: 'turn.started', turnId: 0, origin: { kind: 'user' } }));
      expect(service.getSeqWatermark('s1', 'sub-1')).toBe(1);
      expect(service.getOpsSince('s1', 'sub-1', 0)?.batches.map((batch) => batch.seq)).toEqual([1]);

      expect(service.getSeqWatermark('s1', 'nope')).toBe(0);
      expect(service.getOpsSince('nope-session', 'main', 0)).toBeUndefined();
      service.dropSession('s1');
    });

    it('marks catch-up incomplete once the bounded journal evicts old batches', async () => {
      const agents = new FakeAgents();
      const main = agents.add('main');
      const service = new TranscriptService({
        homeDir: '/nonexistent-home',
        core: fakeCoreWithAgents(agents),
      });
      service.forSessionLive('s1');
      await service.whenReady('s1');
      const base = service.getSeqWatermark('s1', 'main');

      for (let turnId = 1; turnId <= TRANSCRIPT_OPS_JOURNAL_CAPACITY + 1; turnId++) {
        main.bus.emit(ev({ type: 'turn.started', turnId, origin: { kind: 'user' } }));
      }
      const watermark = service.getSeqWatermark('s1', 'main');
      expect(watermark).toBe(base + TRANSCRIPT_OPS_JOURNAL_CAPACITY + 1);

      const evicted = service.getOpsSince('s1', 'main', base);
      expect(evicted?.complete).toBe(false);
      expect(evicted?.latestSeq).toBe(watermark);
      expect(evicted?.batches).toHaveLength(TRANSCRIPT_OPS_JOURNAL_CAPACITY);

      const recent = service.getOpsSince('s1', 'main', watermark - 10);
      expect(recent?.complete).toBe(true);
      expect(recent?.batches.map((batch) => batch.seq)).toEqual(
        Array.from({ length: 10 }, (_, i) => watermark - 9 + i),
      );
      service.dropSession('s1');
    });
  });
});