File size: 261,391 Bytes
1269259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e0fe4e
 
 
 
 
 
 
 
 
 
 
1269259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e0fe4e
1269259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e0fe4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1269259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
// SPF Smart Gateway - MCP Server (JSON-RPC 2.0 over stdio)
// Copyright 2026 Joseph Stone - All Rights Reserved
//
// ALL tool calls route through this gateway.
// Exposes: spf_read, spf_write, spf_edit, spf_bash, spf_status,
//          spf_calculate, spf_session, spf_brain_search, spf_brain_store

use crate::calculate::{self, ToolParams};
use crate::voice::spf_voice;
use crate::config::SpfConfig;
use crate::config_db::SpfConfigDb;
use crate::paths::{spf_root};
use crate::tmp_db::SpfTmpDb;
use crate::agent_state::AgentStateDb;
use crate::fs::SpfFs;
use crate::gate;
use crate::session::Session;
use crate::storage::SpfStorage;
use crate::web::WebClient;
use crate::utf8_safe;
use serde_json::{json, Value};
use std::io::{self, BufRead, Write};
use std::sync::{Arc, Mutex};
use crate::http::ServerState;
use std::process::Command;
use chrono::{DateTime, Local, Utc};
use std::fs::OpenOptions;

// Voice session state: crate::voice::VOICE_SESSION (Block LL — moved to voice.rs for mesh access)

/// Chat engine state — persists across tool calls.
/// Stores conversations, message history, and routes incoming chat.
static CHAT_ENGINE: std::sync::Mutex<Option<crate::chat::ChatEngine>> = std::sync::Mutex::new(None);


const PROTOCOL_VERSION: &str = "2024-11-05";

/// Format Unix timestamp as human-readable ISO8601
fn format_timestamp(ts: u64) -> String {
    if ts == 0 {
        return "Never".to_string();
    }
    DateTime::<Utc>::from_timestamp(ts as i64, 0)
        .map(|dt| dt.format("%Y-%m-%d %H:%M:%S UTC").to_string())
        .unwrap_or_else(|| ts.to_string())
}
const SERVER_NAME: &str = "spf-smart-gate";
const SERVER_VERSION: &str = "3.0.0";

// brain_path() and run_brain() removed — replaced by crate::brain_local (in-process)
// RG-1: run_rag(), rag_collector_path(), rag_collector_dir() removed — Python subprocess eliminated.
// RAG handlers now redirect to brain_local (in-process) or return deprecation messages.

/// Log to stderr (stdout is JSON-RPC)
fn log(msg: &str) {
    eprintln!("[spf-smart-gate] {}", msg);
}

/// Persistent command log → LIVE/SESSION/cmd.log
fn cmd_log(msg: &str) {
    let log_path = spf_root().join("LIVE/SESSION/cmd.log");
    if let Ok(mut f) = OpenOptions::new().create(true).append(true).open(&log_path) {
        let ts = Local::now().format("%Y-%m-%d %H:%M:%S");
        let _ = writeln!(f, "[{}] {}", ts, msg);
    }
}

/// Summarize tool params for logging (truncate large values)
fn param_summary(name: &str, args: &Value) -> String {
    match name {
        n if n.contains("bash") => {
            let cmd = args.get("command").and_then(|v| v.as_str()).unwrap_or("?");
            if cmd.len() > 200 { format!("cmd={}…", utf8_safe::safe_truncate(cmd, 200)) } else { format!("cmd={}", cmd) }
        }
        n if n.contains("read") || n.contains("edit") || n.contains("glob") => {
            let path = args.get("file_path")
                .or_else(|| args.get("path"))
                .or_else(|| args.get("absolute_path"))
                .and_then(|v| v.as_str())
                .unwrap_or("?");
            let pattern = args.get("pattern").and_then(|v| v.as_str());
            match pattern {
                Some(pat) => format!("path={} pattern={}", path, pat),
                None => format!("path={}", path),
            }
        }
        n if n.contains("write") => {
            let path = args.get("file_path")
                .or_else(|| args.get("path"))
                .and_then(|v| v.as_str())
                .unwrap_or("?");
            let size = args.get("content").and_then(|v| v.as_str()).map(|s| s.len()).unwrap_or(0);
            format!("path={} content_len={}", path, size)
        }
        n if n.contains("grep") => {
            let pattern = args.get("pattern").and_then(|v| v.as_str()).unwrap_or("?");
            let path = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");
            format!("pattern={} path={}", pattern, path)
        }
        n if n.contains("web") => {
            let url = args.get("url").and_then(|v| v.as_str()).unwrap_or("?");
            let query = args.get("query").and_then(|v| v.as_str());
            match query {
                Some(q) => format!("query={}", q),
                None => format!("url={}", url),
            }
        }
        n if n.contains("brain") || n.contains("rag") => {
            let query = args.get("query")
                .or_else(|| args.get("text"))
                .or_else(|| args.get("path"))
                .and_then(|v| v.as_str())
                .unwrap_or("?");
            let truncated = utf8_safe::safe_truncate(query, 150);
            format!("q={}", truncated)
        }
        _ => {
            let s = args.to_string();
            if s.len() > 300 { format!("{}…", utf8_safe::safe_truncate(&s, 300)) } else { s }
        }
    }
}

/// Send JSON-RPC response
fn send_response(id: &Value, result: Value) {
    let response = json!({
        "jsonrpc": "2.0",
        "id": id,
        "result": result,
    });
    let msg = serde_json::to_string(&response).unwrap();
    let stdout = io::stdout();
    let mut out = stdout.lock();
    let _ = out.write_all(msg.as_bytes());
    let _ = out.write_all(b"\n");
    let _ = out.flush();
}

/// Send JSON-RPC error response
fn send_error(id: &Value, code: i64, message: &str) {
    let response = json!({
        "jsonrpc": "2.0",
        "id": id,
        "error": { "code": code, "message": message },
    });
    let msg = serde_json::to_string(&response).unwrap();
    let stdout = io::stdout();
    let mut out = stdout.lock();
    let _ = out.write_all(msg.as_bytes());
    let _ = out.write_all(b"\n");
    let _ = out.flush();
}

/// MCP tool definition helper
fn tool_def(name: &str, description: &str, properties: Value, required: Vec<&str>) -> Value {
    json!({
        "name": name,
        "description": description,
        "inputSchema": {
            "type": "object",
            "properties": properties,
            "required": required,
        }
    })
}

/// Return all tool definitions
pub fn tool_definitions() -> Vec<Value> {
    let mut tools = vec![
        // ====== CORE GATE TOOLS ======
        // spf_gate REMOVED — was a bypass vector. Gate is internal only.
        tool_def(
            "spf_calculate",
            "Calculate complexity score for a tool call without executing. Returns C value, tier, and allocation.",
            json!({
                "tool": {"type": "string", "description": "Tool name"},
                "params": {"type": "object", "description": "Tool parameters"}
            }),
            vec!["tool", "params"],
        ),
        tool_def(
            "spf_status",
            "Get current SPF gateway status: session metrics, enforcement mode, complexity budget.",
            json!({}),
            vec![],
        ),
        tool_def(
            "spf_session",
            "Get full session state: files read/written, action history, anchor ratio, complexity history.",
            json!({
                "mode": {"type": "string", "description": "Output mode: 'full' (default) or 'summary' (counts only, ~200 tokens)", "default": "full"},
                "limit": {"type": "integer", "description": "Max manifest/complexity entries to return (default: all)", "default": 0}
            }),
            vec![],
        ),

        // ====== GATED FILE OPERATIONS ======
        tool_def(
            "Read",
            "Read a file through SPF gateway. Tracks read for Build Anchor Protocol. SPFsmartGATE",
            json!({
                "file_path": {"type": "string", "description": "Absolute path to file"},
                "limit": {"type": "integer", "description": "Max lines to read (optional)"},
                "offset": {"type": "integer", "description": "Line offset to start from (optional)"}
            }),
            vec!["file_path"],
        ),
        tool_def(
            "Write",
            "Write a file through SPF gateway. Validates: Build Anchor, blocked paths, file size. SPFsmartGATE",
            json!({
                "file_path": {"type": "string", "description": "Absolute path to file"},
                "content": {"type": "string", "description": "File content to write"}
            }),
            vec!["file_path", "content"],
        ),
        tool_def(
            "Edit",
            "Edit a file through SPF gateway. Validates: Build Anchor, blocked paths, change size. SPFsmartGATE",
            json!({
                "file_path": {"type": "string", "description": "Absolute path to file"},
                "old_string": {"type": "string", "description": "Text to replace"},
                "new_string": {"type": "string", "description": "Replacement text"},
                "replace_all": {"type": "boolean", "description": "Replace all occurrences", "default": false}
            }),
            vec!["file_path", "old_string", "new_string"],
        ),
        tool_def(
            "Bash",
            "Execute a bash command through SPF gateway. Validates: dangerous commands, /tmp access, git force. SPFsmartGATE",
            json!({
                "command": {"type": "string", "description": "Bash command to execute"},
                "timeout": {"type": "integer", "description": "Timeout in seconds (default: 30)", "default": 30}
            }),
            vec!["command"],
        ),

        // ====== SEARCH/GLOB TOOLS ======
        tool_def(
            "Glob",
            "Fast file pattern matching. Supports glob patterns like **/*.rs or src/**/*.ts. SPFsmartGATE",
            json!({
                "pattern": {"type": "string", "description": "Glob pattern to match files"},
                "path": {"type": "string", "description": "Directory to search in (default: current dir)"}
            }),
            vec!["pattern"],
        ),
        tool_def(
            "Grep",
            "Search file contents using regex. Built on ripgrep. SPFsmartGATE",
            json!({
                "pattern": {"type": "string", "description": "Regex pattern to search for"},
                "path": {"type": "string", "description": "File or directory to search"},
                "glob": {"type": "string", "description": "Glob filter (e.g. *.rs)"},
                "case_insensitive": {"type": "boolean", "description": "Case insensitive search", "default": true},
                "context_lines": {"type": "integer", "description": "Lines of context around matches", "default": 0}
            }),
            vec!["pattern"],
        ),

        // ====== WEB BROWSER TOOLS ======
        tool_def(
            "spf_web_search",
            "Search the web for information. Uses Brave API if BRAVE_API_KEY set, otherwise DuckDuckGo.",
            json!({
                "query": {"type": "string", "description": "Search query"},
                "count": {"type": "integer", "description": "Max results (default: 10)", "default": 10}
            }),
            vec!["query"],
        ),
        tool_def(
            "spf_web_fetch",
            "Fetch a URL and return clean readable text. HTML is converted to plain text, JSON is pretty-printed.",
            json!({
                "url": {"type": "string", "description": "URL to fetch"},
                "prompt": {"type": "string", "description": "Prompt to run on fetched content"}
            }),
            vec!["url", "prompt"],
        ),
        tool_def(
            "spf_web_download",
            "Download a file from URL and save to disk.",
            json!({
                "url": {"type": "string", "description": "URL to download"},
                "save_path": {"type": "string", "description": "Local path to save file"}
            }),
            vec!["url", "save_path"],
        ),
        tool_def(
            "spf_web_api",
            "Make an API request. Returns status, headers, and response body.",
            json!({
                "method": {"type": "string", "description": "HTTP method (GET, POST, PUT, DELETE, PATCH)"},
                "url": {"type": "string", "description": "API endpoint URL"},
                "headers": {"type": "string", "description": "JSON object of headers (optional)", "default": ""},
                "body": {"type": "string", "description": "Request body JSON (optional)", "default": ""}
            }),
            vec!["method", "url"],
        ),

        // ====== WEB BROWSER TOOLS — Reverse Proxy Engine (WB-2e) ======
        tool_def(
            "spf_web_connect",
            "Initialise the reverse proxy browser engine. Call once before any other spf_web_* tools. Opens a proxy on the SPF HTTP port — browser navigates through SPF.",
            json!({"port": {"type": "integer", "description": "Proxy port (default: SPF HTTP port)", "default": 0}}),
            vec![],
        ),
        tool_def(
            "spf_web_navigate",
            "Navigate the browser to a URL. SPF fetches the page, injects control JS, serves it locally. Browser connects back via WebSocket.",
            json!({"url": {"type": "string", "description": "URL to navigate to (SSRF-validated)"}}),
            vec!["url"],
        ),
        tool_def(
            "spf_web_click",
            "Click a page element by CSS selector. Routes through injected control JS.",
            json!({"selector": {"type": "string", "description": "CSS selector (e.g. '#submit', '.btn', 'a[href=\"/login\"]')"}}),
            vec!["selector"],
        ),
        tool_def(
            "spf_web_fill",
            "Type text into a form field by CSS selector.",
            json!({
                "selector": {"type": "string", "description": "CSS selector for the input field"},
                "text": {"type": "string", "description": "Text to type into the field"}
            }),
            vec!["selector", "text"],
        ),
        tool_def(
            "spf_web_select",
            "Query page elements by CSS selector. Returns matching elements with tag, id, class, and text.",
            json!({"selector": {"type": "string", "description": "CSS selector"}}),
            vec!["selector"],
        ),
        tool_def(
            "spf_web_eval",
            "Execute JavaScript on the current page and return the result.",
            json!({"expression": {"type": "string", "description": "JavaScript expression to evaluate in the page context"}}),
            vec!["expression"],
        ),
        tool_def(
            "spf_web_screenshot",
            "Capture a screenshot of the current page. Returns file path — use Read tool to view.",
            json!({}),
            vec![],
        ),
        tool_def(
            "spf_web_design",
            "Extract design brief from current page: colours, fonts, spacing, components, images, forms — all computed values via injected JS.",
            json!({}),
            vec![],
        ),
        tool_def(
            "spf_web_page",
            "Get structured overview of current page: title, URL, headings, links, forms, images, buttons.",
            json!({}),
            vec![],
        ),

        // ====== NOTEBOOK TOOL ======
        tool_def(
            "spf_notebook_edit",
            "Edit a Jupyter notebook cell.",
            json!({
                "notebook_path": {"type": "string", "description": "Absolute path to .ipynb file"},
                "cell_number": {"type": "integer", "description": "Cell index (0-based)"},
                "new_source": {"type": "string", "description": "New cell content"},
                "cell_type": {"type": "string", "description": "Cell type: code or markdown"},
                "edit_mode": {"type": "string", "description": "Mode: replace, insert, or delete", "default": "replace"}
            }),
            vec!["notebook_path", "new_source"],
        ),

        // ====== BRAIN PASSTHROUGH ======
        tool_def(
            "spf_brain_search",
            "Search brain through SPF gateway. All brain access is logged and tracked.",
            json!({
                "query": {"type": "string", "description": "Search query"},
                "collection": {"type": "string", "description": "Collection (default: default)", "default": "default"},
                "limit": {"type": "integer", "description": "Max results (default: 5)", "default": 5}
            }),
            vec!["query"],
        ),
        tool_def(
            "spf_brain_store",
            "Store document in brain through SPF gateway.",
            json!({
                "text": {"type": "string", "description": "Text to store"},
                "title": {"type": "string", "description": "Document title", "default": "untitled"},
                "collection": {"type": "string", "description": "Collection", "default": "default"},
                "tags": {"type": "string", "description": "Comma-separated tags", "default": ""}
            }),
            vec!["text"],
        ),
        tool_def(
            "spf_flint_store",
            "Agent memory store through FLINT pipeline. Bypasses brain write gate. Stores in brain vectors + FLINT Working tier for memory lifecycle.",
            json!({
                "text": {"type": "string", "description": "Text to store"},
                "title": {"type": "string", "description": "Document title", "default": "untitled"},
                "collection": {"type": "string", "description": "Collection (default: default)", "default": "default"},
                "tags": {"type": "string", "description": "Comma-separated tags", "default": ""}
            }),
            vec!["text"],
        ),

        // ====== ADDITIONAL BRAIN TOOLS ======
        tool_def(
            "spf_brain_context",
            "Get relevant context for a query. Returns formatted context for prompt injection.",
            json!({
                "query": {"type": "string", "description": "Query to get context for"},
                "max_tokens": {"type": "integer", "description": "Max tokens (default: 2000)", "default": 2000}
            }),
            vec!["query"],
        ),
        tool_def(
            "spf_brain_index",
            "Index a file or directory into the brain.",
            json!({
                "path": {"type": "string", "description": "File or directory to index"}
            }),
            vec!["path"],
        ),
        tool_def(
            "spf_brain_list",
            "List all indexed collections and document counts.",
            json!({}),
            vec![],
        ),
        tool_def(
            "spf_brain_status",
            "Get brain system status.",
            json!({}),
            vec![],
        ),
        tool_def(
            "spf_brain_recall",
            "Search and return full parent documents. Searches vectors then resolves to complete stored document.",
            json!({
                "query": {"type": "string", "description": "Natural language search query"},
                "collection": {"type": "string", "description": "Collection to search (default: default)", "default": "default"}
            }),
            vec!["query"],
        ),
        tool_def(
            "spf_brain_list_docs",
            "List all stored documents in a collection.",
            json!({
                "collection": {"type": "string", "description": "Collection name (default: default)", "default": "default"}
            }),
            vec![],
        ),
        tool_def(
            "spf_brain_get_doc",
            "Retrieve a specific document by its ID.",
            json!({
                "doc_id": {"type": "string", "description": "Document ID to retrieve"},
                "collection": {"type": "string", "description": "Collection name (default: default)", "default": "default"}
            }),
            vec!["doc_id"],
        ),

        // ====== RAG COLLECTOR TOOLS ======
        tool_def(
            "spf_rag_collect_web",
            "Search web and collect documents. Optional topic filter.",
            json!({
                "topic": {"type": "string", "description": "Topic to search (optional)"},
                "auto_index": {"type": "boolean", "description": "Auto-index collected docs", "default": true}
            }),
            vec![],
        ),
        tool_def(
            "spf_rag_collect_file",
            "Process a local file.",
            json!({
                "path": {"type": "string", "description": "File path"},
                "category": {"type": "string", "description": "Category (default: auto)", "default": "auto"}
            }),
            vec!["path"],
        ),
        tool_def(
            "spf_rag_collect_folder",
            "Process all files in a folder.",
            json!({
                "path": {"type": "string", "description": "Folder path"},
                "extensions": {"type": "array", "items": {"type": "string"}, "description": "File extensions to include"}
            }),
            vec!["path"],
        ),
        tool_def(
            "spf_rag_collect_drop",
            "Process files in DROP_HERE folder.",
            json!({}),
            vec![],
        ),
        tool_def(
            "spf_rag_index_gathered",
            "Index all documents in GATHERED to brain.",
            json!({
                "category": {"type": "string", "description": "Category to index (optional)"}
            }),
            vec![],
        ),
        tool_def(
            "spf_rag_dedupe",
            "Deduplicate brain collection.",
            json!({
                "category": {"type": "string", "description": "Category to dedupe"}
            }),
            vec!["category"],
        ),
        tool_def(
            "spf_rag_status",
            "Get collector status and stats.",
            json!({}),
            vec![],
        ),
        tool_def(
            "spf_rag_list_gathered",
            "List documents in GATHERED folder.",
            json!({
                "category": {"type": "string", "description": "Filter by category"}
            }),
            vec![],
        ),
        tool_def(
            "spf_rag_bandwidth_status",
            "Get bandwidth usage stats and limits.",
            json!({}),
            vec![],
        ),
        tool_def(
            "spf_rag_fetch_url",
            "Fetch a single URL with bandwidth limiting.",
            json!({
                "url": {"type": "string", "description": "URL to fetch"},
                "auto_index": {"type": "boolean", "description": "Auto-index after fetch", "default": true}
            }),
            vec!["url"],
        ),
        tool_def(
            "spf_rag_collect_rss",
            "Collect from RSS/Atom feeds.",
            json!({
                "feed_name": {"type": "string", "description": "Specific feed name (optional)"},
                "auto_index": {"type": "boolean", "description": "Auto-index collected", "default": true}
            }),
            vec![],
        ),
        tool_def(
            "spf_rag_list_feeds",
            "List configured RSS feeds.",
            json!({}),
            vec![],
        ),
        tool_def(
            "spf_rag_pending_searches",
            "Get pending SearchSeeker vectors from brain (gaps needing fetch).",
            json!({
                "collection": {"type": "string", "description": "Collection to check", "default": "default"}
            }),
            vec![],
        ),
        tool_def(
            "spf_rag_fulfill_search",
            "Mark a SearchSeeker as fulfilled after RAG fetch.",
            json!({
                "seeker_id": {"type": "string", "description": "SearchSeeker ID to fulfill"},
                "collection": {"type": "string", "description": "Collection name", "default": "default"}
            }),
            vec!["seeker_id"],
        ),
        tool_def(
            "spf_rag_smart_search",
            "Run smart search with completeness check - triggers SearchSeeker if <80%.",
            json!({
                "query": {"type": "string", "description": "Search query"},
                "collection": {"type": "string", "description": "Collection to search", "default": "default"}
            }),
            vec!["query"],
        ),
        tool_def(
            "spf_rag_auto_fetch_gaps",
            "Automatically fetch data for all pending SearchSeekers.",
            json!({
                "collection": {"type": "string", "description": "Collection to check", "default": "default"},
                "max_fetches": {"type": "integer", "description": "Max URLs to fetch", "default": 5}
            }),
            vec![],
        ),

        // ====== SPF_CONFIG TOOLS ======
        // NOTE: spf_config_get and spf_config_set removed from MCP - user-only via CLI
        tool_def(
            "spf_config_paths",
            "List all path rules (allowed/blocked) from SPF_CONFIG LMDB.",
            json!({}),
            vec![],
        ),
        tool_def(
            "spf_config_stats",
            "Get SPF_CONFIG LMDB statistics.",
            json!({}),
            vec![],
        ),

        // ====== TMP_DB TOOLS ======
        tool_def(
            "spf_tmp_list",
            "List all registered projects with trust levels.",
            json!({}),
            vec![],
        ),
        tool_def(
            "spf_tmp_stats",
            "Get TMP_DB LMDB statistics (project count, access log count, resource count).",
            json!({}),
            vec![],
        ),
        tool_def(
            "spf_tmp_get",
            "Get project info by path.",
            json!({
                "path": {"type": "string", "description": "Project path to look up"}
            }),
            vec!["path"],
        ),
        tool_def(
            "spf_tmp_active",
            "Get the currently active project.",
            json!({}),
            vec![],
        ),

        // ====== AGENT_STATE TOOLS ======
        tool_def(
            "spf_agent_stats",
            "Get AGENT_STATE LMDB statistics (memory count, sessions, state keys, tags).",
            json!({}),
            vec![],
        ),
        tool_def(
            "spf_agent_memory_search",
            "Search agent memories by content.",
            json!({
                "query": {"type": "string", "description": "Search query"},
                "limit": {"type": "integer", "description": "Max results (default: 10)"}
            }),
            vec!["query"],
        ),
        tool_def(
            "spf_agent_memory_by_tag",
            "Get agent memories by tag.",
            json!({
                "tag": {"type": "string", "description": "Tag to filter by"}
            }),
            vec!["tag"],
        ),
        tool_def(
            "spf_agent_session_info",
            "Get the most recent session info.",
            json!({}),
            vec![],
        ),
        tool_def(
            "spf_agent_context",
            "Get context summary for session continuity.",
            json!({}),
            vec![],
        ),
        // ====== MESH TOOLS ======
        tool_def(
            "spf_mesh_status",
            "Get mesh network status, role, team, and identity",
            json!({}),
            vec![],
        ),
        tool_def(
            "spf_mesh_peers",
            "List known/trusted mesh peers",
            json!({}),
            vec![],
        ),
        tool_def(
            "spf_mesh_call",
            "Call a peer agent's tool via mesh network",
            json!({
                "peer_key": {"type": "string", "description": "Peer's Ed25519 public key (hex)"},
                "tool": {"type": "string", "description": "Tool name to call on peer"},
                "arguments": {"type": "object", "description": "Tool arguments (optional)"}
            }),
            vec!["peer_key", "tool"],
        ),
        // ====== VOICE TOOLS (Block DD) ======
        tool_def(
            "spf_voice_mode",
            "Control voice pipeline: start/stop audio, TTS speech synthesis, session status, and mic capture. Actions: start, stop, status, speak, listen, stream_on, stream_off, stream_read. SPFsmartGATE",
            json!({
                "action": {"type": "string", "description": "Action: start, stop, status, speak, listen, stream_on, stream_off, or stream_read"},
                "text": {"type": "string", "description": "Text to synthesize (required for 'speak' action)"},
                "sample_rate": {"type": "integer", "description": "Sample rate Hz (optional, default: 16000)"},
                "duration": {"type": "integer", "description": "Capture duration in seconds for 'listen' action (default: 5, max: 60)"}
            }),
            vec!["action"],
        ),
        tool_def(
            "spf_voice_call",
            "Initiate or manage a peer-to-peer voice call. Actions: start (ring peer), accept (answer incoming), reject (decline incoming), end (hang up), status.",
            json!({
                "action": {"type": "string", "description": "Action: start, accept, reject, end, or status"},
                "peer_key": {"type": "string", "description": "Target peer Ed25519 public key hex — required for start"},
                "peer_name": {"type": "string", "description": "Human-readable name for this peer (optional, used in display)"}
            }),
            vec!["action"],
        ),
        tool_def(
            "spf_voice_team",
            "Manage voice team channels for group audio. Actions: create, join, leave, add (invite peer), list, status.",
            json!({
                "action": {"type": "string", "description": "Action: create, join, leave, add, list, or status"},
                "team_id": {"type": "string", "description": "Team channel ID — defaults to 'default'"},
                "name": {"type": "string", "description": "Channel display name — required for create"},
                "peer_key": {"type": "string", "description": "Peer Ed25519 public key hex — required for add"},
                "display_name": {"type": "string", "description": "Display name for yourself when joining (optional)"}
            }),
            vec!["action"],
        ),
        // ====== CHAT TOOLS (Block GG) ======
        tool_def(
            "spf_chat_send",
            "Send a text message to a mesh peer. Creates conversation if needed. Message delivered via QUIC mesh.",
            json!({
                "peer_key": {"type": "string", "description": "Peer's Ed25519 public key (hex)"},
                "text": {"type": "string", "description": "Message text to send"},
                "conversation_id": {"type": "string", "description": "Conversation ID (optional, auto-generated from peer keys)"}
            }),
            vec!["peer_key", "text"],
        ),
        tool_def(
            "spf_chat_history",
            "Get chat message history. Without conversation_id lists all conversations. With conversation_id shows messages.",
            json!({
                "conversation_id": {"type": "string", "description": "Conversation ID (optional, omit to list all)"},
                "limit": {"type": "integer", "description": "Max messages to return (default: 20)"}
            }),
            vec![],
        ),
        tool_def(
            "spf_chat_rooms",
            "List all active chat conversations with participant info and message counts.",
            json!({}),
            vec![],
        ),
        // ====== FLINT WORKER MODE (Block II) ======
        tool_def(
            "spf_flint_execute",
            "Execute any SPF tool through FLINT worker mode. FLINT acts as your hands — tell it which tool to run and why. The inner tool also passes through the gate.",
            json!({
                "tool_name": {"type": "string", "description": "Name of the SPF tool to execute (e.g. spf_brain_search, spf_mesh_call)"},
                "arguments": {"type": "object", "description": "Arguments to pass to the tool"},
                "reason": {"type": "string", "description": "Why FLINT should execute this tool (logged for training)"}
            }),
            vec!["tool_name"],
        ),
        // ====== SPF_FS Tools — REMOVED FROM AI AGENT REGISTRY ======
        // spf_fs_exists, spf_fs_stat, spf_fs_ls, spf_fs_read,
        // spf_fs_write, spf_fs_mkdir, spf_fs_rm, spf_fs_rename
        // These are USER/SYSTEM-ONLY tools. Not exposed to AI agents via MCP.
        // Hard-blocked in gate.rs as additional defense in depth.

        // ====== NETWORK POOL TOOLS (Block NP) ======
        tool_def(
            "spf_pool_status",
            "Get network pool status: worker roles, idle/busy counts, active tasks. NetAdmin shows full pool; Worker shows own status.",
            json!({}),
            vec![],
        ),
        tool_def(
            "spf_pool_assign",
            "Assign a task to an idle worker in the pool. NetAdmin only. Returns task_id and worker info.",
            json!({
                "tool": {"type": "string", "description": "Tool name to execute on the worker"},
                "worker_name": {"type": "string", "description": "Target worker name (optional — auto-selects idle if omitted)"}
            }),
            vec!["tool"],
        ),
        tool_def(
            "spf_pool_release",
            "Release a worker from a task and record proof of work receipt. NetAdmin only.",
            json!({
                "task_id": {"type": "string", "description": "Task ID returned by spf_pool_assign"},
                "result": {"type": "object", "description": "Task result JSON for proof of work hash (optional)"}
            }),
            vec!["task_id"],
        ),

        // ====== CHANNEL HUB (Block CH) ======
        tool_def(
            "spf_channel",
            "Universal agent communication channel. Actions: create (new channel), join (enter channel), leave (exit channel), send (post message), listen (drain inbound buffer), history (get messages), list (show all channels), connect (WS client to remote hub), disconnect (close WS client), status (connection info). Hub runs on orchestrator; agents connect via WebSocket for instant full-duplex push messaging.",
            json!({
                "action": {"type": "string", "description": "Action: create, join, leave, send, listen, history, list, connect, disconnect, status"},
                "channel_id": {"type": "string", "description": "Channel ID (e.g. ch-1) — required for join, leave, send, listen, history, connect"},
                "name": {"type": "string", "description": "Channel name (for create) or display name (for join/connect)"},
                "text": {"type": "string", "description": "Message text (for send action)"},
                "msg_type": {"type": "string", "description": "Message type: text, tool_result, system (default: text)"},
                "hub_url": {"type": "string", "description": "Hub HTTP URL (for connect action, e.g. http://192.168.1.10:8080)"},
                "limit": {"type": "integer", "description": "Max messages to return (for history/listen, default: 50)"}
            }),
            vec!["action"],
        ),
    ];
    // ====== TRANSFORMER TOOLS (Block K) ======
    tools.extend(crate::transformer_tools::tool_definitions());
    tools
}

// ============================================================================
// TOOL ALIAS MAP — QW-1: External LLM compatibility (Qwen, etc)
// ============================================================================

/// Maps external/unprefixed tool names to internal SPF tool names.
/// Enables Qwen and other LLMs to call tools without "spf_" prefix.
/// Called at the start of handle_tool_call() to normalize incoming names.
/// Additive-only — existing callers unaffected. Zero breaking changes.
pub fn tool_alias_map(name: &str) -> &str {
    match name {
        "read" => "Read", "write" => "Write", "edit" => "Edit",
        "bash" => "Bash", "glob" => "Glob", "grep" => "Grep",
        "calculate" => "spf_calculate", "status" => "spf_status", "session" => "spf_session",
        "brain_search" => "spf_brain_search", "brain_store" => "spf_brain_store",
        "flint_store" => "spf_flint_store",
        "brain_context" => "spf_brain_context", "brain_index" => "spf_brain_index",
        "brain_list" => "spf_brain_list", "brain_status" => "spf_brain_status",
        "brain_recall" => "spf_brain_recall", "brain_list_docs" => "spf_brain_list_docs",
        "brain_get_doc" => "spf_brain_get_doc",
        "web_search" => "spf_web_search", "web_fetch" => "spf_web_fetch",
        "web_download" => "spf_web_download", "web_api" => "spf_web_api",
        "web_connect" => "spf_web_connect", "web_navigate" => "spf_web_navigate",
        "web_click" => "spf_web_click", "web_fill" => "spf_web_fill",
        "web_select" => "spf_web_select", "web_eval" => "spf_web_eval",
        "web_screenshot" => "spf_web_screenshot", "web_design" => "spf_web_design",
        "web_page" => "spf_web_page",

        "mesh_status" => "spf_mesh_status", "mesh_peers" => "spf_mesh_peers",
        "mesh_call" => "spf_mesh_call",
        "transformer_status" => "spf_transformer_status",
        "transformer_infer" => "spf_transformer_infer",
        "transformer_chat" => "spf_transformer_chat",
        "transformer_train" => "spf_transformer_train",
        "transformer_metrics" => "spf_transformer_metrics",
        "flint_train_evil" => "spf_flint_train_evil",
        "flint_train_good" => "spf_flint_train_good",
        "pool_status" => "spf_pool_status", "pool_assign" => "spf_pool_assign",
        "pool_release" => "spf_pool_release",
        "voice_mode" => "spf_voice_mode", "voice_call" => "spf_voice_call",
        "voice_team" => "spf_voice_team",
        "chat_send" => "spf_chat_send", "chat_history" => "spf_chat_history",
        "chat_rooms" => "spf_chat_rooms",
        "flint_execute" => "spf_flint_execute",
        "agent_stats" => "spf_agent_stats", "agent_memory_search" => "spf_agent_memory_search",
        "agent_memory_by_tag" => "spf_agent_memory_by_tag",
        "agent_session_info" => "spf_agent_session_info", "agent_context" => "spf_agent_context",
        "config_paths" => "spf_config_paths", "config_stats" => "spf_config_stats",
        "tmp_list" => "spf_tmp_list", "tmp_stats" => "spf_tmp_stats",
        "tmp_get" => "spf_tmp_get", "tmp_active" => "spf_tmp_active",
        "notebook_edit" => "spf_notebook_edit",
        "channel" => "spf_channel",
        "rag_collect_web" => "spf_rag_collect_web", "rag_collect_file" => "spf_rag_collect_file",
        "rag_collect_folder" => "spf_rag_collect_folder", "rag_collect_drop" => "spf_rag_collect_drop",
        "rag_index_gathered" => "spf_rag_index_gathered", "rag_dedupe" => "spf_rag_dedupe",
        "rag_status" => "spf_rag_status", "rag_list_gathered" => "spf_rag_list_gathered",
        "rag_bandwidth_status" => "spf_rag_bandwidth_status", "rag_fetch_url" => "spf_rag_fetch_url",
        "rag_collect_rss" => "spf_rag_collect_rss", "rag_list_feeds" => "spf_rag_list_feeds",
        "rag_pending_searches" => "spf_rag_pending_searches",
        "rag_fulfill_search" => "spf_rag_fulfill_search",
        "rag_smart_search" => "spf_rag_smart_search",
        "rag_auto_fetch_gaps" => "spf_rag_auto_fetch_gaps",
        _ => name,
    }
}

// ============================================================================
// LMDB PARTITION ROUTING — virtual filesystem mount points
// ============================================================================

/// Route spf_fs_* calls to the correct LMDB partition based on path prefix.
/// Returns Some(result) if routed, None to fall through to SpfFs (LMDB 1).
fn route_to_lmdb(
    path: &str,
    op: &str,
    content: Option<&str>,
    config_db: &Option<SpfConfigDb>,
    tmp_db: &Option<SpfTmpDb>,
    agent_db: &Option<AgentStateDb>,
) -> Option<Value> {
    let live_base = spf_root().join("LIVE").display().to_string();

    if path == "/config" || path.starts_with("/config/") {
        return Some(route_config(path, op, config_db));
    }
    // /tmp — device-backed directory in LIVE/TMP/TMP/
    if path == "/tmp" || path.starts_with("/tmp/") {
        let device_tmp = format!("{}/TMP/TMP", live_base);
        return Some(route_device_dir(path, "/tmp", &device_tmp, op, content, tmp_db));
    }
    // /projects — device-backed directory in LIVE/PROJECTS/PROJECTS/
    if path == "/projects" || path.starts_with("/projects/") {
        let device_projects = format!("{}/PROJECTS/PROJECTS", live_base);
        return Some(route_device_dir(path, "/projects", &device_projects, op, content, tmp_db));
    }
    // /home/agent/tmp → redirect to /tmp device directory
    if path == "/home/agent/tmp" || path.starts_with("/home/agent/tmp/") {
        let redirected = path.replacen("/home/agent/tmp", "/tmp", 1);
        let device_tmp = format!("{}/TMP/TMP", live_base);
        return Some(route_device_dir(&redirected, "/tmp", &device_tmp, op, content, tmp_db));
    }
    if path == "/home/agent" || path.starts_with("/home/agent/") {
        // Write permission check for /home/agent/* — ALL writes blocked
        if matches!(op, "write" | "mkdir" | "rm" | "rename") {
            return Some(json!({"type": "text", "text": format!("BLOCKED: {} is read-only in /home/agent/", path)}));
        }
        // Read ops route to agent handler
        return Some(route_agent(path, op, agent_db));
    }
    None
}

/// LMDB 2 — SPF_CONFIG mount at /config/
fn route_config(path: &str, op: &str, config_db: &Option<SpfConfigDb>) -> Value {
    let db = match config_db {
        Some(db) => db,
        None => return json!({"type": "text", "text": "SPF_CONFIG LMDB not initialized"}),
    };

    let relative = path.strip_prefix("/config").unwrap_or("").trim_start_matches('/');

    match op {
        "ls" => {
            if relative.is_empty() {
                json!({"type": "text", "text": "/config:\n-644        0 version\n-644        0 mode\n-644        0 tiers\n-644        0 formula\n-644        0 weights\n-644        0 paths\n-644        0 patterns"})
            } else {
                json!({"type": "text", "text": format!("/config/{}: not a directory", relative)})
            }
        }
        "read" => {
            match relative {
                "version" => match db.get("spf", "version") {
                    Ok(Some(v)) => json!({"type": "text", "text": v}),
                    Ok(None) => json!({"type": "text", "text": "not set"}),
                    Err(e) => json!({"type": "text", "text": format!("error: {}", e)}),
                },
                "mode" => match db.get_enforce_mode() {
                    Ok(mode) => json!({"type": "text", "text": format!("{:?}", mode)}),
                    Err(e) => json!({"type": "text", "text": format!("error: {}", e)}),
                },
                "tiers" => match db.get_tiers() {
                    Ok(tiers) => json!({"type": "text", "text": serde_json::to_string_pretty(&tiers).unwrap_or_else(|e| format!("error: {}", e))}),
                    Err(e) => json!({"type": "text", "text": format!("error: {}", e)}),
                },
                "formula" => match db.get_formula() {
                    Ok(formula) => json!({"type": "text", "text": serde_json::to_string_pretty(&formula).unwrap_or_else(|e| format!("error: {}", e))}),
                    Err(e) => json!({"type": "text", "text": format!("error: {}", e)}),
                },
                "weights" => match db.get_weights() {
                    Ok(weights) => json!({"type": "text", "text": serde_json::to_string_pretty(&weights).unwrap_or_else(|e| format!("error: {}", e))}),
                    Err(e) => json!({"type": "text", "text": format!("error: {}", e)}),
                },
                "paths" => match db.list_path_rules() {
                    Ok(rules) => {
                        let text = rules.iter()
                            .map(|(t, p)| format!("{}: {}", t, p))
                            .collect::<Vec<_>>()
                            .join("\n");
                        json!({"type": "text", "text": if text.is_empty() { "No path rules".to_string() } else { text }})
                    }
                    Err(e) => json!({"type": "text", "text": format!("error: {}", e)}),
                },
                "patterns" => match db.list_dangerous_patterns() {
                    Ok(patterns) => {
                        let text = patterns.iter()
                            .map(|(p, s)| format!("{} (severity: {})", p, s))
                            .collect::<Vec<_>>()
                            .join("\n");
                        json!({"type": "text", "text": if text.is_empty() { "No patterns".to_string() } else { text }})
                    }
                    Err(e) => json!({"type": "text", "text": format!("error: {}", e)}),
                },
                "" => json!({"type": "text", "text": "/config is a directory (use ls)"}),
                _ => json!({"type": "text", "text": format!("not found: /config/{}", relative)}),
            }
        }
        "exists" => {
            let exists = relative.is_empty() || matches!(relative, "version" | "mode" | "tiers" | "formula" | "weights" | "paths" | "patterns");
            json!({"type": "text", "text": format!("/config/{}: {}", relative, if exists { "EXISTS" } else { "NOT FOUND" })})
        }
        "stat" => {
            if relative.is_empty() {
                json!({"type": "text", "text": "Path: /config\nType: Directory\nMount: CONFIG (CONFIG.DB)"})
            } else if matches!(relative, "version" | "mode" | "tiers" | "formula" | "weights" | "paths" | "patterns") {
                json!({"type": "text", "text": format!("Path: /config/{}\nType: File\nMount: CONFIG (CONFIG.DB)\nSource: config_db.{}", relative, relative)})
            } else {
                json!({"type": "text", "text": format!("Not found: /config/{}", relative)})
            }
        }
        "write" | "mkdir" | "rm" | "rename" => {
            json!({"type": "text", "text": "BLOCKED: /config is a read-only mount (use spf_config_* tools)"})
        }
        _ => json!({"type": "text", "text": format!("unsupported operation: {}", op)}),
    }
}

/// Device-backed directory mount: files on device disk, OS provides metadata.
/// Used for /tmp/ and /projects/ — real device filesystem, not LMDB blobs.
fn route_device_dir(
    virtual_path: &str,
    mount_prefix: &str,
    device_base: &str,
    op: &str,
    content: Option<&str>,
    tmp_db: &Option<SpfTmpDb>,
) -> Value {
    let relative = virtual_path.strip_prefix(mount_prefix)
        .unwrap_or("")
        .trim_start_matches('/');

    // Path traversal protection — reject any relative path containing ..
    if relative.contains("..") {
        return json!({"type": "text", "text": format!(
            "BLOCKED: path traversal detected in {}", virtual_path
        )});
    }

    let device_path = if relative.is_empty() {
        std::path::PathBuf::from(device_base)
    } else {
        std::path::PathBuf::from(device_base).join(relative)
    };

    match op {
        "ls" => {
            match std::fs::read_dir(&device_path) {
                Ok(entries) => {
                    let mut items: Vec<String> = Vec::new();
                    for entry in entries.flatten() {
                        let name = entry.file_name().to_string_lossy().to_string();
                        let meta = entry.metadata().ok();
                        let (prefix, size) = match &meta {
                            Some(m) if m.is_dir() => ("d755", 0u64),
                            Some(m) => ("-644", m.len()),
                            None => ("-???", 0u64),
                        };
                        items.push(format!("{} {:>8} {}", prefix, size, name));
                    }
                    items.sort();
                    if items.is_empty() {
                        json!({"type": "text", "text": format!("{}: empty", virtual_path)})
                    } else {
                        json!({"type": "text", "text": format!("{}:\n{}", virtual_path, items.join("\n"))})
                    }
                }
                Err(_) if !device_path.exists() => {
                    json!({"type": "text", "text": format!("{}: empty", virtual_path)})
                }
                Err(e) => {
                    json!({"type": "text", "text": format!("error listing {}: {}", virtual_path, e)})
                }
            }
        }
        "read" => {
            if relative.is_empty() {
                json!({"type": "text", "text": format!("{} is a directory (use ls)", virtual_path)})
            } else {
                match std::fs::read(&device_path) {
                    Ok(bytes) => {
                        match String::from_utf8(bytes.clone()) {
                            Ok(data) => {
                                if let Some(db) = tmp_db {
                                    let _ = db.log_access(virtual_path, device_base, "read", "device", data.len() as u64, true, None);
                                }
                                json!({"type": "text", "text": data})
                            }
                            Err(_) => {
                                if let Some(db) = tmp_db {
                                    let _ = db.log_access(virtual_path, device_base, "read", "device", bytes.len() as u64, true, None);
                                }
                                json!({"type": "text", "text": utf8_safe::binary_info(&bytes)})
                            }
                        }
                    }
                    Err(e) => json!({"type": "text", "text": format!("error reading {}: {}", virtual_path, e)}),
                }
            }
        }
        "write" => {
            if let Some(data) = content {
                if let Some(parent) = device_path.parent() {
                    let _ = std::fs::create_dir_all(parent);
                }
                match std::fs::write(&device_path, data) {
                    Ok(()) => {
                        // Log write to TMP_DB
                        if let Some(db) = tmp_db {
                            let _ = db.log_access(virtual_path, device_base, "write", "device", data.len() as u64, true, None);
                        }
                        json!({"type": "text", "text": format!("Written: {} ({} bytes)", virtual_path, data.len())})
                    }
                    Err(e) => json!({"type": "text", "text": format!("write failed: {}", e)}),
                }
            } else {
                json!({"type": "text", "text": "write requires content"})
            }
        }
        "exists" => {
            let exists = device_path.exists();
            json!({"type": "text", "text": format!("{}: {}", virtual_path, if exists { "EXISTS" } else { "NOT FOUND" })})
        }
        "stat" => {
            match std::fs::metadata(&device_path) {
                Ok(meta) => {
                    let file_type = if meta.is_dir() { "Directory" } else { "File" };
                    json!({"type": "text", "text": format!(
                        "Path: {}\nType: {}\nSize: {}\nMount: device ({})\nAccess: read-write",
                        virtual_path, file_type, meta.len(), device_base
                    )})
                }
                Err(_) => json!({"type": "text", "text": format!("{}: NOT FOUND", virtual_path)}),
            }
        }
        "mkdir" => {
            match std::fs::create_dir_all(&device_path) {
                Ok(()) => json!({"type": "text", "text": format!("Directory created: {}", virtual_path)}),
                Err(e) => json!({"type": "text", "text": format!("mkdir failed: {}", e)}),
            }
        }
        "rm" => {
            if device_path.is_dir() {
                match std::fs::remove_dir(&device_path) {
                    Ok(()) => json!({"type": "text", "text": format!("Removed: {}", virtual_path)}),
                    Err(e) => json!({"type": "text", "text": format!("rm failed (not empty?): {}", e)}),
                }
            } else if device_path.exists() {
                match std::fs::remove_file(&device_path) {
                    Ok(()) => json!({"type": "text", "text": format!("Removed: {}", virtual_path)}),
                    Err(e) => json!({"type": "text", "text": format!("rm failed: {}", e)}),
                }
            } else {
                json!({"type": "text", "text": format!("{}: NOT FOUND", virtual_path)})
            }
        }
        "rename" => {
            // rename needs new_path — handled at spf_fs_rename level
            json!({"type": "text", "text": "rename: use spf_fs_rename with full paths"})
        }
        _ => json!({"type": "text", "text": format!("unsupported operation: {}", op)}),
    }
}

/// LMDB 5 — AGENT_STATE mount at /home/agent/
// ============================================================================
// ROUTE_AGENT REPLACEMENT — Dynamic reads from LMDB5.DB state db
// Copyright 2026 Joseph Stone - All Rights Reserved
//
// REPLACES: lines 1037-1243 in src/mcp.rs
// INSERT: scan_state_dir helper + replacement route_agent function
//
// What changed:
//   1. READ: state db lookup (file:{path} keys) before "not found" catch-all
//   2. LS: skeleton dirs merged with dynamic file: keys from state db
//   3. EXISTS: state db check for file keys and directory prefixes
//   4. State listing filters out file: keys (those belong to LS, not state/)
//   5. New helper: scan_state_dir() scans state keys for directory children
// ============================================================================

/// Scan state db for file: keys that are immediate children of a directory.
/// Returns formatted ls entries like "d755        0 dirname" or "-644        0 filename".
fn scan_state_dir(db: &AgentStateDb, dir_relative: &str) -> Vec<String> {
    let prefix = if dir_relative.is_empty() {
        "file:".to_string()
    } else {
        format!("file:{}/", dir_relative)
    };

    match db.list_state_keys() {
        Ok(keys) => {
            let mut dirs = std::collections::BTreeSet::new();
            let mut files = std::collections::BTreeSet::new();

            for key in &keys {
                if let Some(rest) = key.strip_prefix(&prefix) {
                    if rest.is_empty() { continue; }
                    match rest.find('/') {
                        Some(pos) => { dirs.insert(rest[..pos].to_string()); }
                        None => { files.insert(rest.to_string()); }
                    }
                }
            }

            let mut entries = Vec::new();
            for d in dirs {
                entries.push(format!("d755        0 {}", d));
            }
            for f in files {
                entries.push(format!("-644        0 {}", f));
            }
            entries
        }
        Err(_) => Vec::new(),
    }
}

/// Route /home/agent/* virtual paths to LMDB5 AgentStateDb.
///
/// Three data sources:
/// 1. Skeleton directories (hardcoded structure — defines virtual FS layout)
/// 2. State db file:{path} keys (imported config files — dynamic READ/LS/EXISTS)
/// 3. Dedicated databases (memory, sessions, state, preferences, context)
fn route_agent(path: &str, op: &str, agent_db: &Option<AgentStateDb>) -> Value {
    let db = match agent_db {
        Some(db) => db,
        None => return json!({"type": "text", "text": "AGENT_STATE LMDB not initialized"}),
    };

    let relative = path.strip_prefix("/home/agent").unwrap_or("").trim_start_matches('/');

    match op {
        "ls" => {
            // Special dynamic directories backed by dedicated LMDB databases
            match relative {
                "memory" => {
                    return match db.search_memories("", 100) {
                        Ok(memories) => {
                            let text = memories.iter()
                                .map(|m| format!("-644 {:>8} {}", m.content.len(), m.id))
                                .collect::<Vec<_>>()
                                .join("\n");
                            json!({"type": "text", "text": if text.is_empty() { "/home/agent/memory: empty".to_string() } else { format!("/home/agent/memory:\n{}", text) }})
                        }
                        Err(e) => json!({"type": "text", "text": format!("error: {}", e)}),
                    };
                }
                "sessions" => {
                    return match db.get_latest_session() {
                        Ok(Some(latest)) => {
                            match db.get_session_chain(&latest.session_id) {
                                Ok(chain) => {
                                    let text = chain.iter()
                                        .map(|s| format!("-644 {:>8} {}", s.total_actions, s.session_id))
                                        .collect::<Vec<_>>()
                                        .join("\n");
                                    json!({"type": "text", "text": format!("/home/agent/sessions:\n{}", text)})
                                }
                                Err(e) => json!({"type": "text", "text": format!("error: {}", e)}),
                            }
                        }
                        Ok(None) => json!({"type": "text", "text": "/home/agent/sessions: empty"}),
                        Err(e) => json!({"type": "text", "text": format!("error: {}", e)}),
                    };
                }
                "state" => {
                    // Show state keys EXCEPT file: keys (those are served via LS of their dirs)
                    return match db.list_state_keys() {
                        Ok(keys) => {
                            let text = keys.iter()
                                .filter(|k| !k.starts_with("file:"))
                                .map(|k| format!("-644        0 {}", k))
                                .collect::<Vec<_>>()
                                .join("\n");
                            json!({"type": "text", "text": if text.is_empty() { "/home/agent/state: empty".to_string() } else { format!("/home/agent/state:\n{}", text) }})
                        }
                        Err(e) => json!({"type": "text", "text": format!("error: {}", e)}),
                    };
                }
                _ => {}
            }

            // Skeleton directories — hardcoded virtual FS structure
            let skeleton: Vec<&str> = match relative {
                "" => vec![
                    "-644        0 .claude.json",
                    "d755        0 .claude",
                    "d755        0 bin",
                    "d755        0 tmp",
                    "d755        0 .config",
                    "d755        0 .local",
                    "d755        0 .cache",
                    "d755        0 .memory",
                    "d755        0 .ssh",
                    "d755        0 Documents",
                    "d755        0 Projects",
                    "d755        0 workspace",
                    "-644        0 preferences",
                    "-644        0 context",
                ],
                ".claude" => vec![
                    "d755        0 projects",
                    "d755        0 file-history",
                    "d755        0 paste-cache",
                    "d755        0 session-env",
                    "d755        0 todos",
                    "d755        0 plans",
                    "d755        0 tasks",
                    "d755        0 shell-snapshots",
                    "d755        0 statsig",
                    "d755        0 telemetry",
                ],
                "bin" => vec![
                    "-755        0 spf-smart-gate",
                    "d755        0 claude-code",
                ],
                ".config" => vec!["d755        0 settings"],
                ".local" => vec![
                    "d755        0 bin",
                    "d755        0 share",
                    "d755        0 state",
                ],
                ".local/share" => vec![
                    "d755        0 history",
                    "d755        0 data",
                ],
                ".local/state" => vec!["d755        0 sessions"],
                ".cache" => vec![
                    "d755        0 context",
                    "d755        0 tmp",
                ],
                ".memory" => vec![
                    "d755        0 facts",
                    "d755        0 instructions",
                    "d755        0 preferences",
                    "d755        0 pinned",
                ],
                ".ssh" => vec![],
                "Documents" => vec![
                    "d755        0 notes",
                    "d755        0 templates",
                ],
                "Projects" => vec![],
                "workspace" => vec!["d755        0 current"],
                _ => vec![],
            };

            // Scan state db for imported file: keys in this directory
            let dynamic = scan_state_dir(db, relative);

            // Merge skeleton + dynamic (deduplicate by name)
            let mut seen = std::collections::HashSet::new();
            let mut entries = Vec::new();
            for entry in &skeleton {
                let name = entry.split_whitespace().last().unwrap_or("");
                if seen.insert(name.to_string()) {
                    entries.push(entry.to_string());
                }
            }
            for entry in &dynamic {
                let name = entry.split_whitespace().last().unwrap_or("");
                if seen.insert(name.to_string()) {
                    entries.push(entry.clone());
                }
            }

            // Known skeleton dirs (even when empty) + any dir with dynamic entries
            let is_known_dir = !skeleton.is_empty() || !dynamic.is_empty()
                || matches!(relative, "" | ".ssh" | "Projects");

            if !is_known_dir {
                json!({"type": "text", "text": format!("/home/agent/{}: not a directory", relative)})
            } else {
                let dir = if relative.is_empty() {
                    "/home/agent".to_string()
                } else {
                    format!("/home/agent/{}", relative)
                };
                if entries.is_empty() {
                    json!({"type": "text", "text": format!("{}: empty", dir)})
                } else {
                    json!({"type": "text", "text": format!("{}:\n{}", dir, entries.join("\n"))})
                }
            }
        }
        "read" => {
            if relative.is_empty() {
                return json!({"type": "text", "text": "/home/agent is a directory (use ls)"});
            }

            // Dedicated handlers for special virtual files
            if relative == "preferences" {
                return match db.get_preferences() {
                    Ok(prefs) => json!({"type": "text", "text": serde_json::to_string_pretty(&prefs).unwrap_or_else(|e| format!("error: {}", e))}),
                    Err(e) => json!({"type": "text", "text": format!("error: {}", e)}),
                };
            }
            if relative == "context" {
                return match db.get_context_summary() {
                    Ok(summary) => json!({"type": "text", "text": if summary.is_empty() { "No context available".to_string() } else { summary }}),
                    Err(e) => json!({"type": "text", "text": format!("error: {}", e)}),
                };
            }
            if let Some(mem_id) = relative.strip_prefix("memory/") {
                return match db.recall(mem_id) {
                    Ok(Some(entry)) => json!({"type": "text", "text": format!(
                        "ID: {}\nType: {:?}\nContent: {}\nTags: {}\nSource: {}\nCreated: {}\nAccessed: {} ({}x)\nRelevance: {:.2}",
                        entry.id, entry.memory_type, entry.content,
                        entry.tags.join(", "), entry.source,
                        format_timestamp(entry.created_at), format_timestamp(entry.last_accessed),
                        entry.access_count, entry.relevance
                    )}),
                    Ok(None) => json!({"type": "text", "text": format!("not found: /home/agent/memory/{}", mem_id)}),
                    Err(e) => json!({"type": "text", "text": format!("error: {}", e)}),
                };
            }
            if let Some(session_id) = relative.strip_prefix("sessions/") {
                return match db.get_session(session_id) {
                    Ok(Some(ctx)) => json!({"type": "text", "text": format!(
                        "Session: {}\nParent: {}\nStarted: {}\nEnded: {}\nDir: {}\nActions: {}\nComplexity: {}\nFiles modified: {}\nSummary: {}",
                        ctx.session_id,
                        ctx.parent_session.as_deref().unwrap_or("none"),
                        format_timestamp(ctx.started_at), format_timestamp(ctx.ended_at),
                        ctx.working_dir, ctx.total_actions, ctx.total_complexity,
                        ctx.files_modified.join(", "),
                        if ctx.summary.is_empty() { "none" } else { &ctx.summary }
                    )}),
                    Ok(None) => json!({"type": "text", "text": format!("not found: /home/agent/sessions/{}", session_id)}),
                    Err(e) => json!({"type": "text", "text": format!("error: {}", e)}),
                };
            }
            if let Some(key) = relative.strip_prefix("state/") {
                return match db.get_state(key) {
                    Ok(Some(value)) => json!({"type": "text", "text": value}),
                    Ok(None) => json!({"type": "text", "text": format!("not found: /home/agent/state/{}", key)}),
                    Err(e) => json!({"type": "text", "text": format!("error: {}", e)}),
                };
            }

            // Dynamic read from state db — imported config files (file:{path} keys)
            let file_key = format!("file:{}", relative);
            match db.get_state(&file_key) {
                Ok(Some(content)) => json!({"type": "text", "text": content}),
                Ok(None) => json!({"type": "text", "text": format!("not found: /home/agent/{}", relative)}),
                Err(e) => json!({"type": "text", "text": format!("error reading {}: {}", relative, e)}),
            }
        }
        "exists" => {
            // Hardcoded skeleton paths always exist
            let hardcoded = matches!(relative,
                "" | "memory" | "sessions" | "state" | "preferences" | "context"
                | ".claude" | ".claude.json" | "bin" | "tmp" | ".config" | ".local"
                | ".cache" | ".memory" | ".ssh" | "Documents" | "Projects" | "workspace"
            )
                || relative.starts_with("memory/")
                || relative.starts_with("sessions/")
                || relative.starts_with("state/");

            if hardcoded {
                return json!({"type": "text", "text": format!("/home/agent/{}: EXISTS", relative)});
            }

            // Check state db for file: key (imported config file)
            let file_key = format!("file:{}", relative);
            let is_file = db.get_state(&file_key).ok().flatten().is_some();

            // Check if it's a directory containing file: keys
            let is_dir = if !is_file {
                let dir_prefix = format!("file:{}/", relative);
                db.list_state_keys().ok()
                    .map(|keys| keys.iter().any(|k| k.starts_with(&dir_prefix)))
                    .unwrap_or(false)
            } else {
                false
            };

            let exists = is_file || is_dir;
            json!({"type": "text", "text": format!("/home/agent/{}: {}",
                relative, if exists { "EXISTS" } else { "NOT FOUND" })})
        }
        "stat" => {
            if relative.is_empty() {
                json!({"type": "text", "text": "Path: /home/agent\nType: Directory\nMount: AGENT_STATE (LMDB5.DB)"})
            } else {
                json!({"type": "text", "text": format!("Path: /home/agent/{}\nMount: AGENT_STATE (LMDB5.DB)", relative)})
            }
        }
        "write" | "mkdir" | "rm" | "rename" => {
            json!({"type": "text", "text": "BLOCKED: /home/agent is a read-only mount (use spf_agent_* tools)"})
        }
        _ => json!({"type": "text", "text": format!("unsupported operation: {}", op)}),
    }
}

/// Extract ToolParams from raw JSON args for entry-point gate check.
/// Handles field name variants: path/file_path, pattern/command.
pub fn extract_gate_params(args: &Value) -> ToolParams {
    ToolParams {
        file_path: args["file_path"].as_str()
            .or_else(|| args["path"].as_str())
            .or_else(|| args["absolute_path"].as_str())
            .map(String::from),
        content: args["content"].as_str().map(String::from),
        command: args["command"].as_str()
            .or_else(|| args["tool"].as_str())      // spf_mesh_call uses "tool" arg
            .or_else(|| args["pattern"].as_str()).map(String::from),
        old_string: args["old_string"].as_str().map(String::from),
        new_string: args["new_string"].as_str().map(String::from),
        replace_all: args["replace_all"].as_bool(),
        query: args["query"].as_str().map(String::from),
        pattern: args["pattern"].as_str().map(String::from),
        path: args["path"].as_str().map(String::from),
        url: args["url"].as_str().map(String::from),
        topic: args["topic"].as_str().map(String::from),
        category: args["category"].as_str().map(String::from),
        text: args["text"].as_str().map(String::from),
        collection: args["collection"].as_str().map(String::from),
        title: args["title"].as_str().map(String::from),
        limit: args["limit"].as_u64(),
        tool_name: args["tool_name"].as_str().map(String::from),
        reason: args["reason"].as_str().map(String::from),
        peer_key: args["peer_key"].as_str().map(String::from),
        message: args["message"].as_str().map(String::from),
        prompt: args["prompt"].as_str().map(String::from),
        batch_size: args["batch_size"].as_u64(),
    }
}

/// Handle a tool call
pub fn handle_tool_call(
    name: &str,
    args: &Value,
    source: crate::dispatch::Source,
    gate_decision: &crate::gate::GateDecision,
    config: &SpfConfig,
    session: &mut Session,
    storage: &SpfStorage,
    config_db: &Option<SpfConfigDb>,
    tmp_db: &Option<SpfTmpDb>,
    _fs_db: &Option<SpfFs>,
    agent_db: &Option<AgentStateDb>,
    pub_key_hex: &str,
    mesh_tx: &Option<std::sync::mpsc::Sender<crate::mesh::MeshRequest>>,
    peers: &std::collections::HashMap<String, crate::identity::PeerInfo>,
    transformer: &Option<std::sync::Arc<std::sync::RwLock<crate::transformer_tools::TransformerState>>>,
    transformer_config: &crate::config::TransformerConfig,
    network_config: &crate::config::NetworkConfig,
    pool_state: &Option<std::sync::Arc<crate::network::PoolState>>,
    pipeline: &std::sync::Arc<std::sync::Mutex<crate::pipeline::PipelineState>>,
    browser: &std::sync::Mutex<crate::browser::BrowserSession>,
    ws_browser_channels: &std::sync::Mutex<Option<crate::browser::WsBrowserChannels>>,
    http_port: u16,
    tracked_peers: &std::sync::Mutex<std::collections::HashMap<String, crate::http::MeshPeerStatus>>,
    orchestrator_state: &std::sync::Mutex<Option<Arc<std::sync::Mutex<crate::orchestrator::OrchestratorState>>>>,
    endpoint: &std::sync::Mutex<Option<iroh::Endpoint>>,
    tokio_handle: &std::sync::Mutex<Option<tokio::runtime::Handle>>,
) -> Value {
    // QW-1: Resolve tool alias before routing — enables unprefixed calls from Qwen/external LLMs
    let name = tool_alias_map(name);
    match name {
        // ====== spf_gate ======
        // spf_gate REMOVED — was a bypass vector
        "spf_gate" => {
            json!({"type": "text", "text": "BLOCKED: spf_gate removed — gate is internal only", "_blocked": true})
        }

        // ====== spf_calculate ======
        "spf_calculate" => {
            let tool = args["tool"].as_str().unwrap_or("unknown");
            let params: ToolParams = serde_json::from_value(
                args.get("params").cloned().unwrap_or(json!({}))
            ).unwrap_or_else(|_| ToolParams {
                ..Default::default()
            });
            let result = calculate::calculate(tool, &params, config);
            json!({"type": "text", "text": serde_json::to_string_pretty(&result).unwrap()})
        }

        // ====== spf_status ======
        "spf_status" => {
            let status = format!(
                "SPF Gateway v{}\nMode: {:?}\nSession: {}\nTiers: SIMPLE(<500) LIGHT(<2000) MEDIUM(<10000) CRITICAL(>10000)\nFormula: a_optimal(C) = {} × (1 - 1/ln(C + e))",
                SERVER_VERSION,
                config.enforce_mode,
                session.status_summary(),
                config.formula.w_eff,
            );
            json!({"type": "text", "text": status})
        }

        // ====== spf_session ======
        "spf_session" => {
            let mode = args["mode"].as_str().unwrap_or("full");
            let limit = args["limit"].as_u64().unwrap_or(0) as usize;

            match mode {
                "summary" => {
                    // Compact summary — ~200 tokens instead of 10k+
                    let blocked = session.manifest.iter().filter(|m| m.action == "BLOCKED").count();
                    let allowed = session.manifest.iter().filter(|m| m.action == "ALLOWED").count();
                    let last_manifest = session.manifest.last().map(|m| {
                        format!("{} {} (C={}) {}", m.tool, m.action,
                            m.c, m.command.as_deref().unwrap_or(""))
                    }).unwrap_or_else(|| "none".to_string());

                    json!({"type": "text", "text": format!(
                        "Session Summary:\n  Actions: {}\n  Files read: {}\n  Files written: {}\n  Anchor ratio: {}\n  Manifest: {} allowed, {} blocked\n  Failures: {}\n  Last tool: {}\n  Last manifest: {}\n  Uptime: {}s",
                        session.action_count,
                        session.files_read.len(),
                        session.files_written.len(),
                        session.anchor_ratio(),
                        allowed, blocked,
                        session.failures.len(),
                        session.last_tool.as_deref().unwrap_or("none"),
                        last_manifest,
                        (chrono::Utc::now() - session.started).num_seconds(),
                    )})
                }
                _ => {
                    // Full mode — optionally limit manifest/complexity entries
                    if limit > 0 {
                        let mut limited = session.clone();
                        if limited.manifest.len() > limit {
                            let start = limited.manifest.len() - limit;
                            limited.manifest = limited.manifest[start..].to_vec();
                        }
                        if limited.complexity_history.len() > limit {
                            let start = limited.complexity_history.len() - limit;
                            limited.complexity_history = limited.complexity_history[start..].to_vec();
                        }
                        json!({"type": "text", "text": serde_json::to_string_pretty(&limited).unwrap()})
                    } else {
                        json!({"type": "text", "text": serde_json::to_string_pretty(session).unwrap()})
                    }
                }
            }
        }

        // ====== spf_read ======
        "spf_read" | "Read" => {
            let file_path = args["file_path"].as_str()
                .or_else(|| args["absolute_path"].as_str())
                .unwrap_or("");

            // Execute read — binary-safe: text gets line display, binary gets SHA-256 fingerprint
            match std::fs::read(file_path) {
                Ok(bytes) => {
                    session.track_read(file_path);
                    session.record_action("Read", "success", Some(file_path));
                    let _ = storage.save_session(session);

                    match String::from_utf8(bytes.clone()) {
                        Ok(content) => {
                            // Apply limit/offset if specified
                            let offset = args.get("offset").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
                            let limit = args.get("limit").and_then(|v| v.as_u64()).unwrap_or(0) as usize;

                            let lines: Vec<&str> = content.lines().collect();
                            let total = lines.len();
                            let start = offset.min(total);
                            let end = if limit > 0 { (start + limit).min(total) } else { total };

                            let numbered: String = lines[start..end]
                                .iter()
                                .enumerate()
                                .map(|(i, line)| format!("{:>6}\t{}", start + i + 1, line))
                                .collect::<Vec<_>>()
                                .join("\n");

                            json!({"type": "text", "text": format!("File: {} ({} lines)\n{}", file_path, total, numbered)})
                        }
                        Err(_) => {
                            // Binary file — return fingerprint, not corrupt content
                            json!({"type": "text", "text": utf8_safe::binary_info(&bytes)})
                        }
                    }
                }
                Err(e) => {
                    session.record_action("Read", "failed", Some(file_path));
                    session.record_failure("Read", &e.to_string());
                    let _ = storage.save_session(session);
                    json!({"type": "text", "text": format!("Read failed: {}", e)})
                }
            }
        }

        // ====== spf_write ======
        "spf_write" | "Write" => {
            let file_path = args["file_path"].as_str().unwrap_or("");
            let content = args["content"].as_str().unwrap_or("");

            // Execute write
            // Ensure parent directory exists
            if let Some(parent) = std::path::Path::new(file_path).parent() {
                let _ = std::fs::create_dir_all(parent);
            }

            match std::fs::write(file_path, content) {
                Ok(()) => {
                    session.track_write(file_path);
                    session.record_action("Write", "success", Some(file_path));
                    session.record_manifest_detailed("Write", gate_decision.complexity.c, "ALLOWED", None, Some(file_path), &[file_path.to_string()]);
                    let _ = storage.save_session(session);
                    json!({"type": "text", "text": format!(
                        "Written: {} ({} bytes) | C={} {}",
                        file_path, content.len(), gate_decision.complexity.c, gate_decision.complexity.tier
                    )})
                }
                Err(e) => {
                    session.record_action("Write", "failed", Some(file_path));
                    session.record_failure("Write", &e.to_string());
                    let _ = storage.save_session(session);
                    json!({"type": "text", "text": format!("Write failed: {}", e)})
                }
            }
        }

        // ====== spf_edit ======
        "spf_edit" | "Edit" => {
            let file_path = args["file_path"].as_str().unwrap_or("");
            let old_string = args["old_string"].as_str().unwrap_or("");
            let new_string = args["new_string"].as_str().unwrap_or("");
            let replace_all = args["replace_all"].as_bool().unwrap_or(false);

            // Execute edit — binary-safe: block binary files with clear error
            let content = match std::fs::read(file_path) {
                Ok(bytes) => match String::from_utf8(bytes) {
                    Ok(text) => text,
                    Err(_) => return json!({"type": "text", "text":
                        format!("Edit blocked: {} is a binary file (not editable as text)", file_path)
                    }),
                },
                Err(e) => {
                    session.record_failure("Edit", &e.to_string());
                    let _ = storage.save_session(session);
                    return json!({"type": "text", "text": format!("Edit read failed: {}", e)});
                }
            };

            let new_content = if replace_all {
                content.replace(old_string, new_string)
            } else {
                content.replacen(old_string, new_string, 1)
            };

            if new_content == content {
                json!({"type": "text", "text": format!("Edit: old_string not found in {}", file_path)})
            } else {
                match std::fs::write(file_path, &new_content) {
                    Ok(()) => {
                        session.track_write(file_path);
                        session.record_action("Edit", "success", Some(file_path));
                        session.record_manifest_detailed("Edit", gate_decision.complexity.c, "ALLOWED", None, Some(file_path), &[file_path.to_string()]);
                        let _ = storage.save_session(session);
                        json!({"type": "text", "text": format!(
                            "Edited: {} | C={} {}",
                            file_path, gate_decision.complexity.c, gate_decision.complexity.tier
                        )})
                    }
                    Err(e) => {
                        session.record_failure("Edit", &e.to_string());
                        let _ = storage.save_session(session);
                        json!({"type": "text", "text": format!("Edit write failed: {}", e)})
                    }
                }
            }
        }

        // ====== spf_bash ======
        "spf_bash" | "Bash" => {
            let command = args["command"].as_str().unwrap_or("");
            let timeout_secs = args["timeout"].as_u64().unwrap_or(30).min(300);

            // Execute bash with timeout enforcement
            let output_result = Command::new("timeout")
                .arg("--signal=KILL")
                .arg(format!("{}s", timeout_secs))
                .arg("bash")
                .arg("-c")
                .arg(command)
                .output()
                .or_else(|_| {
                    // timeout binary not found — fall back to direct execution
                    Command::new("bash")
                        .arg("-c")
                        .arg(command)
                        .output()
                });
            match output_result {
                Ok(output) => {
                    let stdout = utf8_safe::process_output_safe(&output.stdout);
                    let stderr = utf8_safe::process_output_safe(&output.stderr);
                    let success = output.status.success();

                    session.record_action("Bash", if success { "success" } else { "failed" }, None);
                    if !success {
                        session.record_failure("Bash", &stderr);
                    }
                    session.record_manifest_detailed("Bash", gate_decision.complexity.c, "ALLOWED", None, Some(command), &crate::validate::extract_bash_targets(command));
                    let _ = storage.save_session(session);

                    let mut result = String::new();
                    if !stdout.is_empty() {
                        result.push_str(&stdout);
                    }
                    if !stderr.is_empty() {
                        result.push_str("\nSTDERR: ");
                        result.push_str(&stderr);
                    }
                    if result.is_empty() {
                        result = format!("Exit code: {}", output.status.code().unwrap_or(-1));
                    }

                    json!({"type": "text", "text": result})
                }
                Err(e) => {
                    session.record_failure("Bash", &e.to_string());
                    let _ = storage.save_session(session);
                    json!({"type": "text", "text": format!("Bash failed: {}", e)})
                }
            }
        }

        // ====== spf_glob ======
        "spf_glob" | "Glob" => {
            let pattern = args["pattern"].as_str().unwrap_or("");
            let path = args["path"].as_str().unwrap_or(".");

            session.record_action("Glob", "called", None);

            // Validate search path is within allowed boundaries
            let search_path = match std::fs::canonicalize(path) {
                Ok(p) => p.to_string_lossy().to_string(),
                Err(_) => {
                    if path.contains("..") {
                        return json!({"type": "text", "text": "BLOCKED: path traversal detected in search path"});
                    }
                    path.to_string()
                }
            };

            if !config.is_path_allowed(&search_path) {
                session.record_manifest("spf_glob", gate_decision.complexity.c, "BLOCKED",
                    Some("Search path outside allowed boundaries"));
                let _ = storage.save_session(session);
                return json!({"type": "text", "text": format!(
                    "BLOCKED: glob search path '{}' is outside allowed paths", path
                ), "_blocked": true});
            }

            // READ-ONLY ENFORCEMENT — WHITELIST approach (stronger than blacklist).
            // Only characters valid for filesystem paths and glob patterns are allowed.
            // Command::new().arg() already prevents shell injection, but defense-in-depth
            // rejects anything that isn't a legitimate path or glob character.
            // find with -name is inherently read-only (no -exec, -delete, -execdir possible
            // because only -name flag is hardcoded in the command construction).
            fn is_safe_glob_char(c: char) -> bool {
                c.is_alphanumeric()
                    || matches!(c, '/' | '.' | '-' | '_' | '*' | '?' | '[' | ']'
                        | ' ' | '+' | '@' | ',' | ':' | '~' | '#')
            }
            if !pattern.chars().all(is_safe_glob_char) {
                return json!({"type": "text", "text": "BLOCKED: glob pattern contains disallowed characters (whitelist: alphanumeric . / - _ * ? [ ] + @ , : ~ #)"});
            }
            if !path.chars().all(is_safe_glob_char) {
                return json!({"type": "text", "text": "BLOCKED: search path contains disallowed characters"});
            }
            if pattern.starts_with('-') {
                return json!({"type": "text", "text": "BLOCKED: pattern cannot start with '-' (flag injection)"});
            }
            if path.contains("..") {
                return json!({"type": "text", "text": "BLOCKED: path traversal not allowed in glob"});
            }

            // Safe: arguments passed directly, no shell interpolation
            match Command::new("find")
                .arg(path)
                .arg("-name")
                .arg(pattern)
                .stderr(std::process::Stdio::null())
                .output()
            {
                Ok(output) => {
                    let stdout = utf8_safe::process_output_safe(&output.stdout);
                    // Limit to first 100 results (replaces piped head -100)
                    let truncated: String = stdout.lines().take(100).collect::<Vec<_>>().join("\n");
                    let _ = storage.save_session(session);
                    if truncated.is_empty() {
                        json!({"type": "text", "text": "No matches found"})
                    } else {
                        json!({"type": "text", "text": truncated})
                    }
                }
                Err(e) => {
                    session.record_failure("Glob", &e.to_string());
                    let _ = storage.save_session(session);
                    json!({"type": "text", "text": format!("Glob failed: {}", e)})
                }
            }
        }

        // ====== spf_grep ======
        "spf_grep" | "Grep" => {
            let pattern = args["pattern"].as_str().unwrap_or("");
            let path = args["path"].as_str().unwrap_or(".");
            let glob_filter = args["glob"].as_str().unwrap_or("");
            let case_insensitive = args["case_insensitive"].as_bool().unwrap_or(false);
            let context = args["context_lines"].as_u64().unwrap_or(0);

            session.record_action("Grep", "called", None);

            // Validate search path is within allowed boundaries
            let search_path = match std::fs::canonicalize(path) {
                Ok(p) => p.to_string_lossy().to_string(),
                Err(_) => {
                    if path.contains("..") {
                        return json!({"type": "text", "text": "BLOCKED: path traversal detected in search path"});
                    }
                    path.to_string()
                }
            };

            if !config.is_path_allowed(&search_path) {
                session.record_manifest("spf_grep", gate_decision.complexity.c, "BLOCKED",
                    Some("Search path outside allowed boundaries"));
                let _ = storage.save_session(session);
                return json!({"type": "text", "text": format!(
                    "BLOCKED: grep search path '{}' is outside allowed paths", path
                ), "_blocked": true});
            }

            // READ-ONLY ENFORCEMENT — WHITELIST approach (stronger than blacklist).
            // Path and glob_filter: only valid filesystem/glob characters allowed.
            // Regex pattern is NOT filtered — regex syntax requires |, $, (), etc.
            // Pattern is protected by "--" separator which prevents flag injection.
            // rg is inherently read-only — cannot modify files under any flags.
            fn is_safe_search_char(c: char) -> bool {
                c.is_alphanumeric()
                    || matches!(c, '/' | '.' | '-' | '_' | '*' | '?' | '[' | ']'
                        | ' ' | '+' | '@' | ',' | ':' | '~' | '#')
            }
            if !path.chars().all(is_safe_search_char) {
                return json!({"type": "text", "text": "BLOCKED: search path contains disallowed characters (whitelist: alphanumeric . / - _ * ? [ ] + @ , : ~ #)"});
            }
            if !glob_filter.is_empty() && !glob_filter.chars().all(is_safe_search_char) {
                return json!({"type": "text", "text": "BLOCKED: glob filter contains disallowed characters"});
            }
            if path.contains("..") {
                return json!({"type": "text", "text": "BLOCKED: path traversal not allowed in grep"});
            }

            // Safe: arguments passed directly, no shell interpolation
            let mut rg = Command::new("rg");
            if case_insensitive {
                rg.arg("-i");
            }
            if context > 0 {
                rg.arg("-C").arg(context.to_string());
            }
            if !glob_filter.is_empty() {
                rg.arg("--glob").arg(glob_filter);
            }
            // "--" prevents pattern from being interpreted as a flag
            rg.arg("--").arg(pattern).arg(path);
            rg.stderr(std::process::Stdio::null());

            match rg.output() {
                Ok(output) => {
                    let stdout = utf8_safe::process_output_safe(&output.stdout);
                    // Limit to first 500 lines (replaces piped head -500)
                    let truncated: String = stdout.lines().take(500).collect::<Vec<_>>().join("\n");
                    let _ = storage.save_session(session);
                    if truncated.is_empty() {
                        json!({"type": "text", "text": "No matches found"})
                    } else {
                        json!({"type": "text", "text": truncated})
                    }
                }
                Err(e) => {
                    session.record_failure("Grep", &e.to_string());
                    let _ = storage.save_session(session);
                    json!({"type": "text", "text": format!("Grep failed: {}", e)})
                }
            }
        }

        // ====== spf_web_fetch ======
        "spf_web_fetch" => {
            let url = args["url"].as_str().unwrap_or("");
            let prompt = args["prompt"].as_str().unwrap_or("Summarize this content");

            session.record_action("WebFetch", "called", None);
            match WebClient::new() {
                Ok(client) => {
                    match client.read_page(url) {
                        Ok((text, raw_len, content_type)) => {
                            session.record_manifest("web_fetch", gate_decision.complexity.c, "ALLOWED", None);
                            let _ = storage.save_session(session);
                            let truncated = utf8_safe::safe_truncate(&text, 50000);
                            json!({"type": "text", "text": format!(
                                "Fetched {} ({} bytes, {})\nPrompt: {}\n\n{}",
                                url, raw_len, content_type, prompt, truncated
                            )})
                        }
                        Err(e) => {
                            session.record_failure("WebFetch", &e);
                            session.record_manifest("web_fetch", gate_decision.complexity.c, "ALLOWED", None);
                            let _ = storage.save_session(session);
                            json!({"type": "text", "text": format!("WebFetch failed: {}", e)})
                        }
                    }
                }
                Err(e) => {
                    session.record_failure("WebFetch", &e);
                    let _ = storage.save_session(session);
                    json!({"type": "text", "text": format!("WebClient init failed: {}", e)})
                }
            }
        }

        // ====== spf_web_search ======
        "spf_web_search" => {
            let query = args["query"].as_str().unwrap_or("");
            let count = args["count"].as_u64().unwrap_or(10) as u32;

            session.record_action("WebSearch", "called", None);
            match WebClient::new() {
                Ok(client) => {
                    match client.search(query, count) {
                        Ok((engine, results)) => {
                            let mut output = format!("Search '{}' via {} ({} results):\n\n", query, engine, results.len());
                            for (i, r) in results.iter().enumerate() {
                                output.push_str(&format!("{}. {}\n   {}\n   {}\n\n", i + 1, r.title, r.url, r.description));
                            }
                            session.record_manifest("web_search", gate_decision.complexity.c, "ALLOWED", None);
                            let _ = storage.save_session(session);
                            json!({"type": "text", "text": output})
                        }
                        Err(e) => {
                            session.record_failure("WebSearch", &e);
                            session.record_manifest("web_search", gate_decision.complexity.c, "ALLOWED", None);
                            let _ = storage.save_session(session);
                            json!({"type": "text", "text": format!("WebSearch failed: {}", e)})
                        }
                    }
                }
                Err(e) => {
                    session.record_failure("WebSearch", &e);
                    let _ = storage.save_session(session);
                    json!({"type": "text", "text": format!("WebClient init failed: {}", e)})
                }
            }
        }

        // ====== spf_web_download ======
        "spf_web_download" => {
            let url = args["url"].as_str().unwrap_or("");
            let save_path = args["save_path"].as_str().unwrap_or("");

            session.record_action("WebDownload", "called", Some(save_path));
            match WebClient::new() {
                Ok(client) => {
                    match client.download(url, save_path) {
                        Ok((size, content_type)) => {
                            session.track_write(save_path);
                            session.record_manifest("web_download", gate_decision.complexity.c, "ALLOWED", None);
                            let _ = storage.save_session(session);
                            json!({"type": "text", "text": format!(
                                "Downloaded {} → {} ({} bytes, {})",
                                url, save_path, size, content_type
                            )})
                        }
                        Err(e) => {
                            session.record_failure("WebDownload", &e);
                            session.record_manifest("web_download", gate_decision.complexity.c, "ALLOWED", None);
                            let _ = storage.save_session(session);
                            json!({"type": "text", "text": format!("Download failed: {}", e)})
                        }
                    }
                }
                Err(e) => {
                    session.record_failure("WebDownload", &e);
                    let _ = storage.save_session(session);
                    json!({"type": "text", "text": format!("WebClient init failed: {}", e)})
                }
            }
        }

        // ====== spf_web_api ======
        "spf_web_api" => {
            let method = args["method"].as_str().unwrap_or("GET");
            let url = args["url"].as_str().unwrap_or("");
            let headers = args["headers"].as_str().unwrap_or("");
            let body = args["body"].as_str().unwrap_or("");

            session.record_action("WebAPI", "called", None);
            match WebClient::new() {
                Ok(client) => {
                    match client.api_request(method, url, headers, body) {
                        Ok((status, resp_headers, resp_body)) => {
                            session.record_manifest("web_api", gate_decision.complexity.c, "ALLOWED", None);
                            let _ = storage.save_session(session);
                            let truncated = if resp_body.len() > 50000 { &resp_body[..50000] } else { &resp_body };
                            json!({"type": "text", "text": format!(
                                "API {} {} → HTTP {}\n\nHeaders:\n{}\n\nBody:\n{}",
                                method, url, status, resp_headers, truncated
                            )})
                        }
                        Err(e) => {
                            session.record_failure("WebAPI", &e);
                            session.record_manifest("web_api", gate_decision.complexity.c, "ALLOWED", None);
                            let _ = storage.save_session(session);
                            json!({"type": "text", "text": format!("API request failed: {}", e)})
                        }
                    }
                }
                Err(e) => {
                    session.record_failure("WebAPI", &e);
                    let _ = storage.save_session(session);
                    json!({"type": "text", "text": format!("WebClient init failed: {}", e)})
                }
            }
        }




        // ====== WEB BROWSER TOOLS — Reverse Proxy Engine (WB-2e) ======

        "spf_web_connect" => {
            let port = args.get("port").and_then(|v| v.as_u64())
                .unwrap_or(http_port as u64) as u16;
            match browser.lock().unwrap().connect(port) {
                Ok((msg, channels)) => {
                    *ws_browser_channels.lock().unwrap() = Some(channels);
                    json!({"type": "text", "text": format!("{}\nProxy: http://localhost:{}/proxy?url=<url>\nWS: ws://localhost:{}/ws/browser", msg, port, port)})
                }
                Err(e) => json!({"type": "text", "text": format!("Connect failed: {}", e)}),
            }
        }

        "spf_web_navigate" => {
            let url = args.get("url").and_then(|v| v.as_str()).unwrap_or("");
            if url.is_empty() {
                return json!({"type": "text", "text": "url required"});
            }
            match browser.lock().unwrap().navigate(url) {
                Ok(msg) => json!({"type": "text", "text": msg}),
                Err(e) => json!({"type": "text", "text": format!("Navigate failed: {}", e)}),
            }
        }

        "spf_web_click" => {
            let selector = args.get("selector").and_then(|v| v.as_str()).unwrap_or("");
            if selector.is_empty() {
                return json!({"type": "text", "text": "selector required"});
            }
            match browser.lock().unwrap().click(selector) {
                Ok(msg) => json!({"type": "text", "text": msg}),
                Err(e) => json!({"type": "text", "text": format!("Click failed: {}", e)}),
            }
        }

        "spf_web_fill" => {
            let selector = args.get("selector").and_then(|v| v.as_str()).unwrap_or("");
            let text = args.get("text").and_then(|v| v.as_str()).unwrap_or("");
            if selector.is_empty() {
                return json!({"type": "text", "text": "selector required"});
            }
            match browser.lock().unwrap().fill(selector, text) {
                Ok(msg) => json!({"type": "text", "text": msg}),
                Err(e) => json!({"type": "text", "text": format!("Fill failed: {}", e)}),
            }
        }

        "spf_web_select" => {
            let selector = args.get("selector").and_then(|v| v.as_str()).unwrap_or("");
            if selector.is_empty() {
                return json!({"type": "text", "text": "selector required"});
            }
            match browser.lock().unwrap().select(selector) {
                Ok(elements) => {
                    let summary: Vec<String> = elements.iter().map(|e| {
                        format!("<{}{}{}> {}",
                            e.tag,
                            e.id.as_deref().map(|i| format!(" id={}", i)).unwrap_or_default(),
                            e.class.as_deref().map(|c| format!(" class={}", c)).unwrap_or_default(),
                            e.text.chars().take(80).collect::<String>())
                    }).collect();
                    json!({"type": "text", "text": format!("Found {} element(s):\n{}", elements.len(), summary.join("\n"))})
                }
                Err(e) => json!({"type": "text", "text": format!("Select failed: {}", e)}),
            }
        }

        "spf_web_eval" => {
            let expression = args.get("expression").and_then(|v| v.as_str()).unwrap_or("");
            if expression.is_empty() {
                return json!({"type": "text", "text": "expression required"});
            }
            match browser.lock().unwrap().eval(expression) {
                Ok(result) => json!({"type": "text", "text": result.to_string()}),
                Err(e) => json!({"type": "text", "text": format!("Eval failed: {}", e)}),
            }
        }

        "spf_web_screenshot" => {
            match browser.lock().unwrap().screenshot() {
                Ok(path) => json!({"type": "text", "text": format!("Screenshot saved: {}\nUse Read tool to view.", path)}),
                Err(e) => json!({"type": "text", "text": format!("Screenshot failed: {}", e)}),
            }
        }

        "spf_web_design" => {
            match browser.lock().unwrap().design() {
                Ok(brief) => {
                    let out = serde_json::to_string_pretty(&brief).unwrap_or_else(|_| format!("{:?}", brief));
                    json!({"type": "text", "text": out})
                }
                Err(e) => json!({"type": "text", "text": format!("Design brief failed: {}", e)}),
            }
        }

        "spf_web_page" => {
            match browser.lock().unwrap().page_info() {
                Ok(info) => json!({"type": "text", "text": info}),
                Err(e) => json!({"type": "text", "text": format!("Page info failed: {}", e)}),
            }
        }









        // ====== spf_notebook_edit ======
        "spf_notebook_edit" => {
            let notebook_path = args["notebook_path"].as_str().unwrap_or("");
            let new_source = args["new_source"].as_str().unwrap_or("");
            let cell_number = args["cell_number"].as_u64().unwrap_or(0) as usize;
            let cell_type = args["cell_type"].as_str().unwrap_or("code");
            let edit_mode = args["edit_mode"].as_str().unwrap_or("replace");

            // HARDCODE: Gate check — NO BYPASS
            let params = ToolParams {
                file_path: Some(notebook_path.to_string()),
                content: Some(new_source.to_string()),
                ..Default::default()
            };

            let decision = gate::process("spf_notebook_edit", &params, config, session, &source);
            if !decision.allowed {
                session.record_manifest("NotebookEdit", decision.complexity.c, "BLOCKED",
                    decision.errors.first().map(|s| s.as_str()));
                let _ = storage.save_session(session);
                return json!({"type": "text", "text": format!("BLOCKED: {}", decision.errors.join(", ")), "_blocked": true});
            }

            session.record_action("NotebookEdit", "called", Some(notebook_path));

            // Read notebook JSON
            match std::fs::read_to_string(notebook_path) {
                Ok(content) => {
                    match serde_json::from_str::<Value>(&content) {
                        Ok(mut notebook) => {
                            if let Some(cells) = notebook.get_mut("cells").and_then(|c| c.as_array_mut()) {
                                match edit_mode {
                                    "replace" => {
                                        if cell_number < cells.len() {
                                            cells[cell_number]["source"] = json!([new_source]);
                                            cells[cell_number]["cell_type"] = json!(cell_type);
                                        } else {
                                            return json!({"type": "text", "text": format!("Cell {} not found", cell_number)});
                                        }
                                    }
                                    "insert" => {
                                        let new_cell = json!({
                                            "cell_type": cell_type,
                                            "source": [new_source],
                                            "metadata": {},
                                            "outputs": []
                                        });
                                        cells.insert(cell_number, new_cell);
                                    }
                                    "delete" => {
                                        if cell_number < cells.len() {
                                            cells.remove(cell_number);
                                        }
                                    }
                                    _ => return json!({"type": "text", "text": "Invalid edit_mode"})
                                }

                                // Write back
                                match std::fs::write(notebook_path, serde_json::to_string_pretty(&notebook).unwrap()) {
                                    Ok(()) => {
                                        session.track_write(notebook_path);
                                        let _ = storage.save_session(session);
                                        json!({"type": "text", "text": format!("Notebook edited: {} cell {} ({})", notebook_path, cell_number, edit_mode)})
                                    }
                                    Err(e) => {
                                        session.record_failure("NotebookEdit", &e.to_string());
                                        let _ = storage.save_session(session);
                                        json!({"type": "text", "text": format!("Write failed: {}", e)})
                                    }
                                }
                            } else {
                                json!({"type": "text", "text": "Invalid notebook: no cells array"})
                            }
                        }
                        Err(e) => json!({"type": "text", "text": format!("JSON parse error: {}", e)})
                    }
                }
                Err(e) => {
                    session.record_failure("NotebookEdit", &e.to_string());
                    let _ = storage.save_session(session);
                    json!({"type": "text", "text": format!("Read failed: {}", e)})
                }
            }
        }

        // ====== spf_brain_search ======
        "spf_brain_search" => {
            let query = args["query"].as_str().unwrap_or("");
            let collection = args["collection"].as_str().unwrap_or("default");
            let limit = args["limit"].as_u64().unwrap_or(5) as usize;

            session.record_action("brain_search", "called", None);
            let output = crate::brain_local::brain_search(query, collection, limit);
            let _ = storage.save_session(session);
            json!({"type": "text", "text": output})
        }

        // ====== spf_brain_store ======
        "spf_brain_store" => {
            let text = args["text"].as_str().unwrap_or("");
            let title = args["title"].as_str().unwrap_or("untitled");
            let collection = args["collection"].as_str().unwrap_or("default");

            session.record_action("brain_store", "called", None);
            let output = crate::brain_local::brain_store(text, title, collection);
            let _ = storage.save_session(session);
            json!({"type": "text", "text": output})
        }

        // ====== spf_flint_store ======
        "spf_flint_store" => {
            let text = args["text"].as_str().unwrap_or("");
            let title = args["title"].as_str().unwrap_or("untitled");
            let collection = args["collection"].as_str().unwrap_or("default");
            let tags_str = args["tags"].as_str().unwrap_or("");

            session.record_action("flint_store", "called", None);

            // Strike 1: Brain store — vector storage for semantic search
            let brain_result = crate::brain_local::brain_store(text, title, collection);

            // Strike 2: Working memory — enables tiered promotion lifecycle
            let working_result = if let Some(ref db) = agent_db {
                let summary: String = text.chars().take(500).collect();
                let tags: Vec<String> = if tags_str.is_empty() {
                    vec![
                        "tool:spf_flint_store".to_string(),
                        "source:flint_store".to_string(),
                        format!("collection:{}", collection),
                    ]
                } else {
                    let mut t: Vec<String> = tags_str.split(',')
                        .map(|s| s.trim().to_string())
                        .filter(|s| !s.is_empty())
                        .collect();
                    t.push("tool:spf_flint_store".to_string());
                    t.push("source:flint_store".to_string());
                    t
                };
                match db.create_memory(&summary, crate::agent_state::MemoryType::Working, tags, "flint_store") {
                    Ok(id) => format!("Working memory created: {}", id),
                    Err(e) => format!("Working memory error: {}", e),
                }
            } else {
                "Agent state DB not available — brain-only store".to_string()
            };

            let _ = storage.save_session(session);
            json!({"type": "text", "text": format!("{}\n{}", brain_result, working_result)})
        }

        // ====== spf_brain_context ======
        "spf_brain_context" => {
            let query = args["query"].as_str().unwrap_or("");
            let max_tokens = args["max_tokens"].as_u64().unwrap_or(2000) as usize;

            session.record_action("brain_context", "called", None);
            let output = crate::brain_local::brain_context(query, "default", max_tokens);
            let _ = storage.save_session(session);
            json!({"type": "text", "text": output})
        }

        // ====== spf_brain_index ======
        "spf_brain_index" => {
            let path = args["path"].as_str().unwrap_or("");

            session.record_action("brain_index", "called", Some(path));
            let output = crate::brain_local::brain_index_path(path, "default");
            let _ = storage.save_session(session);
            json!({"type": "text", "text": output})
        }

        // ====== spf_brain_list ======
        "spf_brain_list" => {
            session.record_action("brain_list", "called", None);
            let output = crate::brain_local::brain_list_collections();
            let _ = storage.save_session(session);
            json!({"type": "text", "text": output})
        }

        // ====== spf_brain_status ======
        "spf_brain_status" => {
            session.record_action("brain_status", "called", None);
            let output = crate::brain_local::brain_status();
            let _ = storage.save_session(session);
            json!({"type": "text", "text": output})
        }

        // ====== spf_brain_recall ======
        "spf_brain_recall" => {
            let query = args["query"].as_str().unwrap_or("");
            let collection = args["collection"].as_str().unwrap_or("default");

            session.record_action("brain_recall", "called", None);
            let output = crate::brain_local::brain_recall(query, collection);
            let _ = storage.save_session(session);
            json!({"type": "text", "text": output})
        }

        // ====== spf_brain_list_docs ======
        "spf_brain_list_docs" => {
            let collection = args["collection"].as_str().unwrap_or("default");

            session.record_action("brain_list_docs", "called", None);
            let output = crate::brain_local::brain_list_docs(collection);
            let _ = storage.save_session(session);
            json!({"type": "text", "text": output})
        }

        // ====== spf_brain_get_doc ======
        "spf_brain_get_doc" => {
            let doc_id = args["doc_id"].as_str().unwrap_or("");
            let collection = args["collection"].as_str().unwrap_or("default");

            session.record_action("brain_get_doc", "called", None);
            let output = crate::brain_local::brain_get_doc(doc_id, collection);
            let _ = storage.save_session(session);
            json!({"type": "text", "text": output})
        }

        // ====== RAG COLLECTOR HANDLERS ======
        // RG-1: Python subprocess eliminated. Handlers redirect to brain_local (in-process).

        // ====== spf_rag_collect_web ======
        "spf_rag_collect_web" => {
            let topic = args["topic"].as_str().unwrap_or("");
            session.record_action("rag_collect_web", "called", None);
            let output = if topic.is_empty() {
                "collect_web requires a topic parameter. Use spf_web_search + spf_brain_store for manual collection.".to_string()
            } else {
                crate::brain_local::brain_search(topic, "default", 10)
            };
            let _ = storage.save_session(session);
            json!({"type": "text", "text": output})
        }

        // ====== spf_rag_collect_file ======
        "spf_rag_collect_file" => {
            let path = args["path"].as_str().unwrap_or("");
            session.record_action("rag_collect_file", "called", Some(path));
            let collection = args["category"].as_str().unwrap_or("default");
            let output = crate::brain_local::brain_index_path(path, collection);
            let _ = storage.save_session(session);
            json!({"type": "text", "text": output})
        }

        // ====== spf_rag_collect_folder ======
        "spf_rag_collect_folder" => {
            let path = args["path"].as_str().unwrap_or("");
            session.record_action("rag_collect_folder", "called", Some(path));
            let output = crate::brain_local::brain_index_path(path, "default");
            let _ = storage.save_session(session);
            json!({"type": "text", "text": output})
        }

        // ====== spf_rag_collect_drop ======
        "spf_rag_collect_drop" => {
            session.record_action("rag_collect_drop", "called", None);
            let drop_path = format!("{}/LIVE/RAG/DROP_HERE", crate::paths::spf_root().display());
            let output = crate::brain_local::brain_index_path(&drop_path, "default");
            let _ = storage.save_session(session);
            json!({"type": "text", "text": output})
        }

        // ====== spf_rag_index_gathered ======
        "spf_rag_index_gathered" => {
            let category = args["category"].as_str().unwrap_or("default");
            session.record_action("rag_index_gathered", "called", None);
            let gathered_path = format!("{}/LIVE/RAG/GATHERED", crate::paths::spf_root().display());
            let output = crate::brain_local::brain_index_path(&gathered_path, category);
            let _ = storage.save_session(session);
            json!({"type": "text", "text": output})
        }

        // ====== spf_rag_dedupe ======
        "spf_rag_dedupe" => {
            let category = args["category"].as_str().unwrap_or("");
            session.record_action("rag_dedupe", "called", None);
            let _ = storage.save_session(session);
            json!({"type": "text", "text": format!("Dedupe not available in-process. Use spf_brain_search to find duplicates in collection '{}'.", category)})
        }

        // ====== spf_rag_status ======
        "spf_rag_status" => {
            session.record_action("rag_status", "called", None);
            let output = crate::brain_local::brain_status();
            let _ = storage.save_session(session);
            json!({"type": "text", "text": output})
        }

        // ====== spf_rag_list_gathered ======
        "spf_rag_list_gathered" => {
            let category = args["category"].as_str().unwrap_or("default");
            session.record_action("rag_list_gathered", "called", None);
            let output = crate::brain_local::brain_list_docs(category);
            let _ = storage.save_session(session);
            json!({"type": "text", "text": output})
        }

        // ====== spf_rag_bandwidth_status ======
        "spf_rag_bandwidth_status" => {
            session.record_action("rag_bandwidth_status", "called", None);
            let _ = storage.save_session(session);
            json!({"type": "text", "text": "Bandwidth tracking removed — brain operates in-process. Use spf_brain_status for system info."})
        }

        // ====== spf_rag_fetch_url ======
        "spf_rag_fetch_url" => {
            let url = args["url"].as_str().unwrap_or("");

            session.record_action("rag_fetch_url", "called", None);
            // RG-1: Redirect to brain_store — caller should use spf_web_fetch first then store result
            let output = format!("Use spf_web_fetch to get content from '{}', then spf_brain_store to index it.", url);
            let success = true;
            let _ = storage.save_session(session);
            if success {
                json!({"type": "text", "text": output})
            } else {
                json!({"type": "text", "text": format!("RAG fetch-url failed: {}", output)})
            }
        }

        // ====== spf_rag_collect_rss ======
        "spf_rag_collect_rss" => {
            session.record_action("rag_collect_rss", "called", None);
            let _ = storage.save_session(session);
            json!({"type": "text", "text": "RSS collection deprecated. Use spf_web_fetch to fetch feed URLs, then spf_brain_store to index content."})
        }

        // ====== spf_rag_list_feeds ======
        "spf_rag_list_feeds" => {
            session.record_action("rag_list_feeds", "called", None);
            let _ = storage.save_session(session);
            json!({"type": "text", "text": "RSS feeds deprecated. Use spf_web_fetch for URL content, spf_brain_store to index."})
        }

        // ====== spf_rag_pending_searches ======
        "spf_rag_pending_searches" => {
            let collection = args["collection"].as_str().unwrap_or("default");
            session.record_action("rag_pending_searches", "called", None);
            let output = crate::brain_local::brain_search("pending", collection, 20);
            let _ = storage.save_session(session);
            json!({"type": "text", "text": output})
        }

        // ====== spf_rag_fulfill_search ======
        "spf_rag_fulfill_search" => {
            session.record_action("rag_fulfill_search", "called", None);
            let _ = storage.save_session(session);
            json!({"type": "text", "text": "SearchSeeker fulfillment deprecated. Brain handles search completeness automatically."})
        }

        // ====== spf_rag_smart_search ======
        "spf_rag_smart_search" => {
            let query = args["query"].as_str().unwrap_or("");
            let collection = args["collection"].as_str().unwrap_or("default");
            session.record_action("rag_smart_search", "called", None);
            let output = crate::brain_local::brain_search(query, collection, 10);
            let _ = storage.save_session(session);
            json!({"type": "text", "text": output})
        }

        // ====== spf_rag_auto_fetch_gaps ======
        "spf_rag_auto_fetch_gaps" => {
            session.record_action("rag_auto_fetch_gaps", "called", None);
            let _ = storage.save_session(session);
            json!({"type": "text", "text": "Auto-fetch gaps deprecated. Use spf_brain_search to find gaps, spf_web_fetch + spf_brain_store to fill them."})
        }

        // ====== SPF_CONFIG HANDLERS ======
        // NOTE: spf_config_get and spf_config_set blocked - user-only via CLI
        "spf_config_get" | "spf_config_set" => {
            json!({"type": "text", "text": "BLOCKED: Config read/write is user-only (use CLI)"})
        }

        "spf_config_paths" => {

            session.record_action("config_paths", "list", None);
            let _ = storage.save_session(session);

            match config_db {
                Some(db) => match db.list_path_rules() {
                    Ok(rules) => {
                        let text = rules.iter()
                            .map(|(t, p)| format!("{}: {}", t, p))
                            .collect::<Vec<_>>()
                            .join("\n");
                        json!({"type": "text", "text": if text.is_empty() { "No path rules configured".to_string() } else { text }})
                    }
                    Err(e) => json!({"type": "text", "text": format!("list_path_rules failed: {}", e)}),
                },
                None => json!({"type": "text", "text": "SPF_CONFIG LMDB not initialized"}),
            }
        }

        "spf_config_stats" => {

            session.record_action("config_stats", "get", None);
            let _ = storage.save_session(session);

            match config_db {
                Some(db) => match db.stats() {
                    Ok((config_count, paths_count, patterns_count)) => {
                        json!({"type": "text", "text": format!(
                            "SPF_CONFIG LMDB Stats:\n  Config entries: {}\n  Path rules: {}\n  Dangerous patterns: {}",
                            config_count, paths_count, patterns_count
                        )})
                    }
                    Err(e) => json!({"type": "text", "text": format!("config_stats failed: {}", e)}),
                },
                None => json!({"type": "text", "text": "SPF_CONFIG LMDB not initialized"}),
            }
        }

        // ====== TMP_DB HANDLERS ======
        "spf_tmp_list" => {

            session.record_action("tmp_list", "list", None);
            let _ = storage.save_session(session);

            match tmp_db {
                Some(db) => match db.list_projects() {
                    Ok(projects) => {
                        let text = projects.iter()
                            .map(|p| format!("{}: {} | trust={:?} | reads={} writes={} | active={}",
                                p.name, p.path, p.trust_level,
                                p.total_reads, p.total_writes, p.is_active))
                            .collect::<Vec<_>>()
                            .join("\n");
                        json!({"type": "text", "text": if text.is_empty() { "No projects registered".to_string() } else { text }})
                    }
                    Err(e) => json!({"type": "text", "text": format!("list_projects failed: {}", e)}),
                },
                None => json!({"type": "text", "text": "TMP_DB LMDB not initialized"}),
            }
        }

        "spf_tmp_stats" => {

            session.record_action("tmp_stats", "get", None);
            let _ = storage.save_session(session);

            match tmp_db {
                Some(db) => match db.db_stats() {
                    Ok((projects_count, access_count, resources_count)) => {
                        json!({"type": "text", "text": format!(
                            "TMP_DB LMDB Stats:\n  Registered projects: {}\n  Access log entries: {}\n  Resource records: {}",
                            projects_count, access_count, resources_count
                        )})
                    }
                    Err(e) => json!({"type": "text", "text": format!("tmp_stats failed: {}", e)}),
                },
                None => json!({"type": "text", "text": "TMP_DB LMDB not initialized"}),
            }
        }

        "spf_tmp_get" => {
            let path_arg = args["path"].as_str().unwrap_or("");

            session.record_action("tmp_get", "get", Some(path_arg));
            let _ = storage.save_session(session);

            match tmp_db {
                Some(db) => match db.get_project(path_arg) {
                    Ok(Some(proj)) => {
                        json!({"type": "text", "text": format!(
                            "Project: {}\nPath: {}\nTrust: {:?}\nActive: {}\nReads: {} | Writes: {} | Session writes: {}/{}\nMax write size: {} | Total C: {}\nProtected: {:?}\nCreated: {} | Last accessed: {}\nNotes: {}",
                            proj.name, proj.path, proj.trust_level, proj.is_active,
                            proj.total_reads, proj.total_writes, proj.session_writes, proj.max_writes_per_session,
                            proj.max_write_size, proj.total_complexity,
                            proj.protected_paths,
                            format_timestamp(proj.created_at), format_timestamp(proj.last_accessed),
                            if proj.notes.is_empty() { "None" } else { &proj.notes }
                        )})
                    }
                    Ok(None) => json!({"type": "text", "text": format!("Project not found: {}", path_arg)}),
                    Err(e) => json!({"type": "text", "text": format!("get_project failed: {}", e)}),
                },
                None => json!({"type": "text", "text": "TMP_DB LMDB not initialized"}),
            }
        }

        "spf_tmp_active" => {

            session.record_action("tmp_active", "get", None);
            let _ = storage.save_session(session);

            match tmp_db {
                Some(db) => match db.get_active() {
                    Ok(Some(path)) => {
                        // Also fetch project details
                        match db.get_project(&path) {
                            Ok(Some(proj)) => {
                                json!({"type": "text", "text": format!(
                                    "Active project: {} ({})\nTrust: {:?} | Reads: {} | Writes: {}",
                                    proj.name, proj.path, proj.trust_level, proj.total_reads, proj.total_writes
                                )})
                            }
                            _ => json!({"type": "text", "text": format!("Active project path: {} (details unavailable)", path)}),
                        }
                    }
                    Ok(None) => json!({"type": "text", "text": "No active project"}),
                    Err(e) => json!({"type": "text", "text": format!("get_active failed: {}", e)}),
                },
                None => json!({"type": "text", "text": "TMP_DB LMDB not initialized"}),
            }
        }

        // ====== AGENT_STATE HANDLERS ======
        // BLOCKED: Write operations are user-only
        "spf_agent_remember" | "spf_agent_forget" | "spf_agent_set_state" => {
            json!({"type": "text", "text": "BLOCKED: Agent state writes are user-only (use CLI)"})
        }

        "spf_agent_stats" => {

            session.record_action("agent_stats", "get", None);
            let _ = storage.save_session(session);

            match agent_db {
                Some(db) => match db.db_stats() {
                    Ok((memory_count, sessions_count, state_count, tags_count)) => {
                        json!({"type": "text", "text": format!(
                            "AGENT_STATE LMDB Stats:\n  Memories: {}\n  Sessions: {}\n  State keys: {}\n  Tags: {}",
                            memory_count, sessions_count, state_count, tags_count
                        )})
                    }
                    Err(e) => json!({"type": "text", "text": format!("agent_stats failed: {}", e)}),
                },
                None => json!({"type": "text", "text": "AGENT_STATE LMDB not initialized"}),
            }
        }

        "spf_agent_memory_search" => {
            let query = args["query"].as_str().unwrap_or("");
            let limit = args["limit"].as_u64().unwrap_or(10) as usize;

            session.record_action("agent_memory_search", "search", Some(query));
            let _ = storage.save_session(session);

            match agent_db {
                Some(db) => match db.search_memories(query, limit) {
                    Ok(memories) => {
                        if memories.is_empty() {
                            json!({"type": "text", "text": format!("No memories found for: {}", query)})
                        } else {
                            let text = memories.iter()
                                .map(|m| format!("[{}] {:?} | {}\n  Tags: {:?} | Created: {}",
                                    m.id, m.memory_type, m.content,
                                    m.tags, format_timestamp(m.created_at)))
                                .collect::<Vec<_>>()
                                .join("\n\n");
                            json!({"type": "text", "text": text})
                        }
                    }
                    Err(e) => json!({"type": "text", "text": format!("search_memories failed: {}", e)}),
                },
                None => json!({"type": "text", "text": "AGENT_STATE LMDB not initialized"}),
            }
        }

        "spf_agent_memory_by_tag" => {
            let tag = args["tag"].as_str().unwrap_or("");

            session.record_action("agent_memory_by_tag", "search", Some(tag));
            let _ = storage.save_session(session);

            match agent_db {
                Some(db) => match db.get_by_tag(tag) {
                    Ok(memories) => {
                        if memories.is_empty() {
                            json!({"type": "text", "text": format!("No memories with tag: {}", tag)})
                        } else {
                            let text = memories.iter()
                                .map(|m| format!("[{}] {:?} | {}",
                                    m.id, m.memory_type, m.content))
                                .collect::<Vec<_>>()
                                .join("\n");
                            json!({"type": "text", "text": text})
                        }
                    }
                    Err(e) => json!({"type": "text", "text": format!("get_by_tag failed: {}", e)}),
                },
                None => json!({"type": "text", "text": "AGENT_STATE LMDB not initialized"}),
            }
        }

        "spf_agent_session_info" => {

            session.record_action("agent_session_info", "get", None);
            let _ = storage.save_session(session);

            match agent_db {
                Some(db) => match db.get_latest_session() {
                    Ok(Some(sess)) => {
                        json!({"type": "text", "text": format!(
                            "Session: {}\nParent: {}\nStarted: {} | Ended: {}\nWorking dir: {}\nProject: {}\nFiles modified: {}\nComplexity: {} | Actions: {}\nSummary: {}",
                            sess.session_id,
                            sess.parent_session.as_deref().unwrap_or("None"),
                            format_timestamp(sess.started_at),
                            if sess.ended_at == 0 { "Ongoing".to_string() } else { format_timestamp(sess.ended_at) },
                            sess.working_dir,
                            sess.active_project.as_deref().unwrap_or("None"),
                            sess.files_modified.len(),
                            sess.total_complexity, sess.total_actions,
                            if sess.summary.is_empty() { "None" } else { &sess.summary }
                        )})
                    }
                    Ok(None) => json!({"type": "text", "text": "No sessions recorded"}),
                    Err(e) => json!({"type": "text", "text": format!("get_latest_session failed: {}", e)}),
                },
                None => json!({"type": "text", "text": "AGENT_STATE LMDB not initialized"}),
            }
        }

        "spf_agent_context" => {

            session.record_action("agent_context", "get", None);
            let _ = storage.save_session(session);

            match agent_db {
                Some(db) => match db.get_context_summary() {
                    Ok(summary) => {
                        json!({"type": "text", "text": if summary.is_empty() { "No context available".to_string() } else { summary }})
                    }
                    Err(e) => json!({"type": "text", "text": format!("get_context_summary failed: {}", e)}),
                },
                None => json!({"type": "text", "text": "AGENT_STATE LMDB not initialized"}),
            }
        }

        // ====== SPF_FS (LMDB 1) Handlers ======
        "spf_fs_exists" => {
            let path = args["path"].as_str().unwrap_or("/");

            let gate_params = ToolParams { file_path: Some(path.to_string()), ..Default::default() };
            let decision = gate::process("spf_fs_exists", &gate_params, config, session, &source);
            if !decision.allowed {
                session.record_manifest("spf_fs_exists", decision.complexity.c,
                    "BLOCKED",
                    decision.errors.first().map(|s| s.as_str()));
                let _ = storage.save_session(session);
                return json!({"type": "text", "text": decision.message, "_blocked": true});
            }
            session.record_action("fs_exists", "check", Some(path));
            let _ = storage.save_session(session);

            if let Some(result) = route_to_lmdb(path, "exists", None, config_db, tmp_db, agent_db) {
                return result;
            }
            json!({"type": "text", "text": format!("BLOCKED: path {} not routable — no LMDB fallback", path)})
        }

        "spf_fs_stat" => {
            let path = args["path"].as_str().unwrap_or("/");

            let gate_params = ToolParams { file_path: Some(path.to_string()), ..Default::default() };
            let decision = gate::process("spf_fs_stat", &gate_params, config, session, &source);
            if !decision.allowed {
                session.record_manifest("spf_fs_stat", decision.complexity.c,
                    "BLOCKED",
                    decision.errors.first().map(|s| s.as_str()));
                let _ = storage.save_session(session);
                return json!({"type": "text", "text": decision.message, "_blocked": true});
            }
            session.record_action("fs_stat", "get", Some(path));
            let _ = storage.save_session(session);

            if let Some(result) = route_to_lmdb(path, "stat", None, config_db, tmp_db, agent_db) {
                return result;
            }
            json!({"type": "text", "text": format!("BLOCKED: path {} not routable — no LMDB fallback", path)})
        }

        "spf_fs_ls" => {
            let path = args["path"].as_str().unwrap_or("/");

            let gate_params = ToolParams { file_path: Some(path.to_string()), ..Default::default() };
            let decision = gate::process("spf_fs_ls", &gate_params, config, session, &source);
            if !decision.allowed {
                session.record_manifest("spf_fs_ls", decision.complexity.c,
                    "BLOCKED",
                    decision.errors.first().map(|s| s.as_str()));
                let _ = storage.save_session(session);
                return json!({"type": "text", "text": decision.message, "_blocked": true});
            }
            session.record_action("fs_ls", "list", Some(path));
            let _ = storage.save_session(session);

            if let Some(result) = route_to_lmdb(path, "ls", None, config_db, tmp_db, agent_db) {
                return result;
            }
            json!({"type": "text", "text": format!("BLOCKED: path {} not routable — no LMDB fallback", path)})
        }

        "spf_fs_read" => {
            let path = args["path"].as_str().unwrap_or("");

            let gate_params = ToolParams { file_path: Some(path.to_string()), ..Default::default() };
            let decision = gate::process("spf_fs_read", &gate_params, config, session, &source);
            if !decision.allowed {
                session.record_manifest("spf_fs_read", decision.complexity.c,
                    "BLOCKED",
                    decision.errors.first().map(|s| s.as_str()));
                let _ = storage.save_session(session);
                return json!({"type": "text", "text": decision.message, "_blocked": true});
            }
            session.record_action("fs_read", "read", Some(path));
            let _ = storage.save_session(session);

            if let Some(result) = route_to_lmdb(path, "read", None, config_db, tmp_db, agent_db) {
                return result;
            }
            json!({"type": "text", "text": format!("BLOCKED: path {} not routable — no LMDB fallback", path)})
        }

        "spf_fs_write" => {
            let path = args["path"].as_str().unwrap_or("");
            let content = args["content"].as_str().unwrap_or("");

            let gate_params = ToolParams { file_path: Some(path.to_string()), content: Some(content.to_string()), ..Default::default() };
            let decision = gate::process("spf_fs_write", &gate_params, config, session, &source);
            if !decision.allowed {
                session.record_manifest("spf_fs_write", decision.complexity.c,
                    "BLOCKED",
                    decision.errors.first().map(|s| s.as_str()));
                let _ = storage.save_session(session);
                return json!({"type": "text", "text": decision.message, "_blocked": true});
            }
            session.record_action("fs_write", "write", Some(path));
            let _ = storage.save_session(session);

            if let Some(result) = route_to_lmdb(path, "write", Some(content), config_db, tmp_db, agent_db) {
                return result;
            }
            json!({"type": "text", "text": format!("BLOCKED: path {} not routable — no LMDB fallback", path)})
        }

        "spf_fs_mkdir" => {
            let path = args["path"].as_str().unwrap_or("");

            let gate_params = ToolParams { file_path: Some(path.to_string()), ..Default::default() };
            let decision = gate::process("spf_fs_mkdir", &gate_params, config, session, &source);
            if !decision.allowed {
                session.record_manifest("spf_fs_mkdir", decision.complexity.c,
                    "BLOCKED",
                    decision.errors.first().map(|s| s.as_str()));
                let _ = storage.save_session(session);
                return json!({"type": "text", "text": decision.message, "_blocked": true});
            }
            session.record_action("fs_mkdir", "create", Some(path));
            let _ = storage.save_session(session);

            if let Some(result) = route_to_lmdb(path, "mkdir", None, config_db, tmp_db, agent_db) {
                return result;
            }
            json!({"type": "text", "text": format!("BLOCKED: path {} not routable — no LMDB fallback", path)})
        }

        "spf_fs_rm" => {
            let path = args["path"].as_str().unwrap_or("");

            let gate_params = ToolParams { file_path: Some(path.to_string()), ..Default::default() };
            let decision = gate::process("spf_fs_rm", &gate_params, config, session, &source);
            if !decision.allowed {
                session.record_manifest("spf_fs_rm", decision.complexity.c,
                    "BLOCKED",
                    decision.errors.first().map(|s| s.as_str()));
                let _ = storage.save_session(session);
                return json!({"type": "text", "text": decision.message, "_blocked": true});
            }
            session.record_action("fs_rm", "remove", Some(path));
            let _ = storage.save_session(session);

            if let Some(result) = route_to_lmdb(path, "rm", None, config_db, tmp_db, agent_db) {
                return result;
            }
            json!({"type": "text", "text": format!("BLOCKED: path {} not routable — no LMDB fallback", path)})
        }

        "spf_fs_rename" => {
            let old_path = args["old_path"].as_str().unwrap_or("");
            let new_path = args["new_path"].as_str().unwrap_or("");

            let gate_params = ToolParams { file_path: Some(old_path.to_string()), ..Default::default() };
            let decision = gate::process("spf_fs_rename", &gate_params, config, session, &source);
            if !decision.allowed {
                session.record_manifest("spf_fs_rename", decision.complexity.c,
                    "BLOCKED",
                    decision.errors.first().map(|s| s.as_str()));
                let _ = storage.save_session(session);
                return json!({"type": "text", "text": decision.message, "_blocked": true});
            }
            session.record_action("fs_rename", "rename", Some(old_path));
            let _ = storage.save_session(session);

            // Device-backed directory rename (handle before route_to_lmdb)
            let is_device_rename = old_path.starts_with("/tmp/") || old_path.starts_with("/projects/");
            if is_device_rename {
                // Path traversal protection
                if old_path.contains("..") || new_path.contains("..") {
                    return json!({"type": "text", "text": "BLOCKED: path traversal detected in rename paths"});
                }
                let live_base = spf_root().join("LIVE").display().to_string();
                let resolve = |vpath: &str| -> std::path::PathBuf {
                    if vpath.starts_with("/tmp/") {
                        std::path::PathBuf::from(format!("{}/TMP/TMP", live_base))
                            .join(vpath.strip_prefix("/tmp/").unwrap_or(""))
                    } else {
                        std::path::PathBuf::from(format!("{}/PROJECTS/PROJECTS", live_base))
                            .join(vpath.strip_prefix("/projects/").unwrap_or(""))
                    }
                };
                let old_device = resolve(old_path);
                let new_device = resolve(new_path);
                if let Some(parent) = new_device.parent() {
                    let _ = std::fs::create_dir_all(parent);
                }
                return match std::fs::rename(&old_device, &new_device) {
                    Ok(()) => json!({"type": "text", "text": format!("Renamed: {} -> {}", old_path, new_path)}),
                    Err(e) => json!({"type": "text", "text": format!("rename failed: {}", e)}),
                };
            }
            if let Some(result) = route_to_lmdb(old_path, "rename", None, config_db, tmp_db, agent_db) {
                return result;
            }
            json!({"type": "text", "text": format!("BLOCKED: paths {}, {} not routable — no LMDB fallback", old_path, new_path)})
        }

        // ================================================================
        // MESH TOOLS — Agent mesh status, peers, and cross-agent calls
        // ================================================================

        "spf_mesh_status" => {
            session.record_action("mesh", "status", None);
            let _ = storage.save_session(session);

            let mesh_json = crate::paths::spf_root().join("LIVE/CONFIG/mesh.json");
            let mesh_cfg = crate::config::MeshConfig::load(&mesh_json).unwrap_or_default();
            let status = if mesh_cfg.enabled { "online" } else { "disabled" };

            // P5: Include tracked peers with roles
            let peers_info = tracked_peers.lock().unwrap();
            let peer_count = peers_info.len();
            let lines: Vec<String> = if peers_info.is_empty() {
                vec!["  (no tracked peers)".to_string()]
            } else {
                peers_info.iter().map(|(k, v)| {
                    format!("  {} | role={} name={} last_seen={}s ago",
                        &k[..16.min(k.len())],
                        v.role,
                        v.name,
                        v.last_seen.elapsed().as_secs())
                }).collect()
            };
            drop(peers_info);

            // P5: Include orchestrator summary if available
            let orch_info = orchestrator_state.lock().unwrap();
            let orch_text = match orch_info.as_ref() {
                Some(orch_arc) => {
                    let orch = orch_arc.lock().unwrap();
                    format!("\nOrchestrator: {}", orch.summary())
                }
                None => String::new(),
            };
            drop(orch_info);

            json!({"type": "text", "text": format!(
                "Mesh: {} | Role: {} | Team: {} | Discovery: {} | Identity: {}\nTracked peers ({}):{}\n{}",
                status, mesh_cfg.role, mesh_cfg.team,
                mesh_cfg.discovery, pub_key_hex,
                peer_count,
                lines.join("\n"),
                orch_text
            )})
        }

        "spf_mesh_peers" => {
            session.record_action("mesh", "peers", None);
            let _ = storage.save_session(session);

            let cfg_dir = crate::paths::spf_root().join("LIVE/CONFIG");
            let trusted = crate::identity::load_trusted_keys(&cfg_dir.join("groups"));
            let mut lines = Vec::new();
            for key in &trusted {
                if let Some(info) = peers.get(key.as_str()) {
                    let addrs = if info.addr.is_empty() { "no addrs".to_string() } else { info.addr.join(", ") };
                    lines.push(format!("  {} ({}, {}, {})", key, info.name, info.role, addrs));
                } else {
                    lines.push(format!("  {} (trusted, no config)", key));
                }
            }
            let count = lines.len();
            let list = if lines.is_empty() {
                "No trusted peers. Add pubkeys to LIVE/CONFIG/groups/*.keys".to_string()
            } else {
                lines.join("\n")
            };
            json!({"type": "text", "text": format!("Mesh Peers ({}):\n{}", count, list)})
        }

        "spf_mesh_call" => {
            session.record_action("mesh", "call", None);
            let _ = storage.save_session(session);

            let peer_key = args["peer_key"].as_str().unwrap_or("");
            let tool_name = args["tool"].as_str().unwrap_or("");
            let tool_args = args.get("arguments").cloned().unwrap_or(json!({}));

            if peer_key.is_empty() || tool_name.is_empty() {
                json!({"type": "text", "text": "ERROR: peer_key and tool are required"})
            } else {
                let cfg_dir = crate::paths::spf_root().join("LIVE/CONFIG");
                let trusted = crate::identity::load_trusted_keys(&cfg_dir.join("groups"));
                if !trusted.contains(peer_key) {
                    json!({"type": "text", "text": format!("BLOCKED: peer not trusted"), "_blocked": true})
                } else if let Some(mesh_tx) = mesh_tx {
                    // Hot-reload peer addresses from disk (same pattern as trust keys above)
                    let live_peers = crate::identity::load_peers(&cfg_dir.join("groups"));
                    let addrs = live_peers.get(peer_key)
                        .map(|p| p.addr.clone())
                        .unwrap_or_default();
                    let (reply_tx, reply_rx) = std::sync::mpsc::channel();
                    let request = crate::mesh::MeshRequest {
                        peer_key: peer_key.to_string(),
                        addrs,
                        tool: tool_name.to_string(),
                        args: tool_args,
                        reply: reply_tx,
                    };
                    if mesh_tx.send(request).is_ok() {
                        match reply_rx.recv_timeout(std::time::Duration::from_secs(30)) {
                            Ok(Ok(result)) => {
                                let text = result.get("result")
                                    .and_then(|r| r.get("content"))
                                    .and_then(|c| c.get(0))
                                    .and_then(|t| t.get("text"))
                                    .and_then(|t| t.as_str())
                                    .unwrap_or("(no text in response)");
                                json!({"type": "text", "text": text})
                            }
                            Ok(Err(e)) => json!({"type": "text", "text": format!("MESH ERROR: {}", e)}),
                            Err(_) => json!({"type": "text", "text": "MESH ERROR: call timed out (30s)"}),
                        }
                    } else {
                        json!({"type": "text", "text": "MESH ERROR: mesh channel closed"})
                    }
                } else {
                    json!({"type": "text", "text": "MESH ERROR: mesh not enabled"})
                }
            }
        }

        // ====== TRANSFORMER TOOLS (Block K) ======

        "spf_transformer_status" => {
            session.record_action("spf_transformer_status", "called", None);
            crate::transformer_tools::handle_status(transformer, transformer_config)
        }

        "spf_transformer_infer" => {
            session.record_action("spf_transformer_infer", "called", None);
            let tokenizer_path = crate::paths::spf_root().join("LIVE/MODELS/tokenizer.json");
            crate::transformer_tools::handle_infer(transformer, args, transformer_config, &tokenizer_path.to_string_lossy())
        }

        "spf_transformer_chat" => {
            session.record_action("spf_transformer_chat", "called", None);
            let tokenizer_path = crate::paths::spf_root().join("LIVE/MODELS/tokenizer.json");
            crate::transformer_tools::handle_chat(transformer, args, transformer_config, &tokenizer_path.to_string_lossy())
        }

        "spf_transformer_train" => {
            session.record_action("spf_transformer_train", "called", None);
            crate::transformer_tools::handle_train(transformer, args, transformer_config)
        }

        "spf_transformer_metrics" => {
            session.record_action("spf_transformer_metrics", "called", None);
            crate::transformer_tools::handle_metrics(transformer, transformer_config)
        }

        // FL-8: Evil/Good training input tools
        "spf_flint_train_evil" => {
            session.record_action("spf_flint_train_evil", "called", None);
            crate::transformer_tools::handle_train_evil(args)
        }

        "spf_flint_train_good" => {
            session.record_action("spf_flint_train_good", "called", None);
            crate::transformer_tools::handle_train_good(args)
        }

        // ====== CHAT TOOLS (Block GG) ======

        "spf_chat_send" => {
            session.record_action("spf_chat_send", "called", None);

            let peer = args["peer_key"].as_str().unwrap_or("");
            let text = args["text"].as_str().unwrap_or("");
            if peer.is_empty() || text.is_empty() {
                return json!({"type": "text", "text": "Error: peer_key and text required"});
            }

            let peer_short = &peer[..8.min(peer.len())];
            let local_short = &pub_key_hex[..8.min(pub_key_hex.len())];

            // Deterministic conversation ID: sorted short keys
            let conv_id = args.get("conversation_id")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string())
                .unwrap_or_else(|| {
                    let mut parts = vec![local_short, peer_short];
                    parts.sort();
                    format!("dm_{}_{}", parts[0], parts[1])
                });

            let ts = chrono::Utc::now().to_rfc3339();

            // Store locally in ChatEngine
            let mut chat_lock = CHAT_ENGINE.lock().unwrap_or_else(|e| e.into_inner());
            let engine = chat_lock.get_or_insert_with(|| {
                crate::chat::ChatEngine::new(local_short.to_string())
            });

            let mut msg = engine.create_message(peer_short, text, &conv_id, &ts);
            msg.msg_type = crate::chat::MessageType::UserText;
            engine.receive_message(msg.clone());
            drop(chat_lock); // Release lock before mesh I/O

            // Send via mesh as tool call to peer
            if let Some(ref tx) = mesh_tx {
                let addrs: Vec<String> = peers.get(peer)
                    .map(|p| p.addr.clone())
                    .unwrap_or_default();
                let (reply_tx, reply_rx) = std::sync::mpsc::channel();
                let request = crate::mesh::MeshRequest {
                    peer_key: peer.to_string(),
                    addrs,
                    tool: "spf_chat_receive".to_string(),
                    args: serde_json::to_value(&msg).unwrap_or(json!({})),
                    reply: reply_tx,
                };
                if tx.send(request).is_ok() {
                    match reply_rx.recv_timeout(std::time::Duration::from_secs(10)) {
                        Ok(Ok(resp)) => {
                            let ack = resp.get("result")
                                .and_then(|r| r.get("content"))
                                .and_then(|c| c.get(0))
                                .and_then(|t| t.get("text"))
                                .and_then(|t| t.as_str())
                                .unwrap_or("delivered");
                            json!({"type": "text", "text": format!(
                                "Sent to {}: {}\nDelivery: {}", peer_short, text, ack
                            )})
                        }
                        Ok(Err(e)) => json!({"type": "text", "text": format!(
                            "Stored locally. Mesh delivery failed: {}", e
                        )}),
                        Err(_) => json!({"type": "text", "text": format!(
                            "Stored locally. Peer {} may be offline (timeout)", peer_short
                        )}),
                    }
                } else {
                    json!({"type": "text", "text": "Stored locally. Mesh channel closed."})
                }
            } else {
                json!({"type": "text", "text": "Stored locally. Mesh not enabled."})
            }
        }

        "spf_chat_receive" => {
            session.record_action("spf_chat_receive", "called", None);

            // Parse ChatMessage from args
            let msg: crate::chat::ChatMessage = match serde_json::from_value(args.clone()) {
                Ok(m) => m,
                Err(e) => return json!({"type": "text", "text": format!("Invalid chat message: {}", e)}),
            };

            let local_short = &pub_key_hex[..8.min(pub_key_hex.len())];
            let mut chat_lock = CHAT_ENGINE.lock().unwrap_or_else(|e| e.into_inner());
            let engine = chat_lock.get_or_insert_with(|| {
                crate::chat::ChatEngine::new(local_short.to_string())
            });

            let from = msg.from.clone();
            let text_preview = msg.text.chars().take(50).collect::<String>();
            let conv_id = engine.receive_message(msg);
            eprintln!("[SPF-CHAT] Received from {}: {} (conv: {})", from, text_preview, conv_id);

            json!({"type": "text", "text": format!("received:{}:{}",  from, conv_id)})
        }

        "spf_chat_history" => {
            session.record_action("spf_chat_history", "called", None);

            let conv_id = args.get("conversation_id").and_then(|v| v.as_str()).unwrap_or("");
            let limit = args.get("limit").and_then(|v| v.as_u64()).unwrap_or(20) as usize;

            let chat_lock = CHAT_ENGINE.lock().unwrap_or_else(|e| e.into_inner());
            match chat_lock.as_ref() {
                Some(engine) => {
                    if conv_id.is_empty() {
                        let convos = engine.list_conversations();
                        if convos.is_empty() {
                            json!({"type": "text", "text": "No conversations"})
                        } else {
                            let text = convos.iter().map(|c| format!(
                                "  {} — {} ({} msgs, last: {})",
                                c.id, c.name, c.message_count, c.last_activity
                            )).collect::<Vec<_>>().join("\n");
                            json!({"type": "text", "text": format!("Conversations:\n{}", text)})
                        }
                    } else {
                        let history = engine.get_history(conv_id, limit);
                        if history.is_empty() {
                            json!({"type": "text", "text": format!("No messages in {}", conv_id)})
                        } else {
                            let text = history.iter().map(|m| format!(
                                "[{}] {}: {}", m.timestamp, m.from, m.text
                            )).collect::<Vec<_>>().join("\n");
                            json!({"type": "text", "text": text})
                        }
                    }
                }
                None => json!({"type": "text", "text": "No chat history. Send or receive a message first."}),
            }
        }

        "spf_chat_rooms" => {
            session.record_action("spf_chat_rooms", "called", None);

            let chat_lock = CHAT_ENGINE.lock().unwrap_or_else(|e| e.into_inner());
            match chat_lock.as_ref() {
                Some(engine) => {
                    let convos = engine.list_conversations();
                    if convos.is_empty() {
                        json!({"type": "text", "text": "No active conversations"})
                    } else {
                        let text = serde_json::to_string_pretty(&convos).unwrap_or_default();
                        json!({"type": "text", "text": text})
                    }
                }
                None => json!({"type": "text", "text": "No active conversations"}),
            }
        }

        // ====== VOICE MODE (Block DD) ======
        "spf_voice_mode" => {
            session.record_action("spf_voice_mode", "called", None);

            let action = args["action"].as_str().unwrap_or("status");

            // Auto-open persistent voice pipeline for audio-requiring actions.
            // Pipeline stays open until explicit "stop". Idempotent — safe to call repeatedly.
            match action {
                "speak" | "listen" | "stream_on" | "call" | "start" => {
                    if let Err(e) = spf_voice::open() {
                        eprintln!("[SPF-VOICE] Pipeline auto-open failed: {}", e);
                    }
                }
                _ => {}
            }

            let mut voice_lock = crate::voice::VOICE_SESSION.lock().unwrap_or_else(|e| e.into_inner());

            match action {
                "start" => {
                    if voice_lock.as_ref().map_or(false, |s| s.is_active()) {
                        let stats = voice_lock.as_ref().unwrap().stats();
                        return json!({"type": "text", "text": format!(
                            "Voice session already active\n{}",
                            serde_json::to_string_pretty(&stats).unwrap_or_default()
                        )});
                    }
                    let mut vconfig = crate::voice::VoiceConfig::default();
                    if let Some(sr) = args.get("sample_rate").and_then(|v| v.as_u64()) {
                        vconfig.sample_rate = sr as u32;
                    }
                    let mut vs = crate::voice::VoiceSession::new(vconfig);
                    match vs.start() {
                        Ok(()) => {
                            let status_json = vs.status().to_json_value();
                            *voice_lock = Some(vs);
                            json!({"type": "text", "text": format!(
                                "Voice session started\n{}",
                                serde_json::to_string_pretty(&status_json).unwrap_or_default()
                            )})
                        }
                        Err(e) => {
                            json!({"type": "text", "text": format!("Voice start failed: {}", e)})
                        }
                    }
                }
                "stop" => {
                    if let Some(ref mut vs) = *voice_lock {
                        vs.stop(); // calls spf_voice::close() internally
                    } else {
                        // No session but pipeline may be open (Light mode auto-open)
                        spf_voice::close();
                    }
                    *voice_lock = None;
                    json!({"type": "text", "text": "Voice pipeline closed, session stopped"})
                }
                "status" => {
                    match voice_lock.as_ref() {
                        Some(vs) => {
                            let stats = vs.stats();
                            json!({"type": "text", "text": serde_json::to_string_pretty(&stats).unwrap_or_default()})
                        }
                        None => {
                            let status = crate::voice::VoiceStatus::from_stubs();
                            json!({"type": "text", "text": format!(
                                "Voice session inactive\n{}",
                                serde_json::to_string_pretty(&status.to_json_value()).unwrap_or_default()
                            )})
                        }
                    }
                }
                "speak" => {
                    let text = args.get("text").and_then(|v| v.as_str()).unwrap_or("");
                    if text.is_empty() {
                        return json!({"type": "text", "text": "Error: 'text' parameter required for speak action"});
                    }
                    // Block MM: Check voice mode — Light (spf-voice in-process TTS) or Rich (full session + Piper)
                    let tts_mode = {
                        let settings = crate::voice::VOICE_SETTINGS.lock().unwrap_or_else(|e| e.into_inner());
                        settings.agent_tts_mode.clone()
                    };
                    match tts_mode {
                        crate::voice::VoiceMode::Light => {
                            // Light mode: in-process TTS via spf-voice (espeak-ng FFI) — zero session, zero battery
                            match spf_voice::speak(text) {
                                Ok(()) => json!({"type": "text", "text": format!(
                                    "Spoke (light/spf-voice): \"{}\" ({} chars)", text, text.len()
                                )}),
                                Err(e) => json!({"type": "text", "text": format!(
                                    "spf-voice speak failed: {}", e
                                )})
                            }
                        }
                        crate::voice::VoiceMode::Rich => {
                            // Rich mode: Full VoiceSession (spf-voice audio + Piper ONNX TTS if available)
                            let needs_start = voice_lock.as_ref().map_or(true, |s| !s.is_active());
                            if needs_start {
                                let mut vs = crate::voice::VoiceSession::new(crate::voice::VoiceConfig::default());
                                match vs.start() {
                                    Ok(()) => {
                                        eprintln!("[SPF-VOICE] Auto-started session for speak (rich mode)");
                                        *voice_lock = Some(vs);
                                    }
                                    Err(e) => {
                                        return json!({"type": "text", "text": format!(
                                            "Voice start failed (rich mode): {}", e)});
                                    }
                                }
                            }
                            let vs = voice_lock.as_mut().unwrap();
                            match vs.speak(text) {
                                Ok(frames) => {
                                    let frame_count = frames.len();
                                    let total_bytes: usize = frames.iter().map(|f| f.data.len()).sum();
                                    let codec = frames.first().map(|f| f.codec.as_str()).unwrap_or("none").to_string();
                                    let mut play_ok = 0usize;
                                    let mut play_err = 0usize;
                                    for frame in &frames {
                                        match vs.play_frame(frame) {
                                            Ok(()) => play_ok += 1,
                                            Err(_) => play_err += 1,
                                        }
                                    }
                                    json!({"type": "text", "text": format!(
                                        "Spoke (rich/piper): {} frames ({} bytes, codec={}) | Played: {} ok, {} failed",
                                        frame_count, total_bytes, codec, play_ok, play_err
                                    )})
                                }
                                Err(e) => json!({"type": "text", "text": format!("TTS error (rich mode): {}", e)})
                            }
                        }
                    }
                }
                "call" => {
                    // Block MM: Start peer voice call via mesh
                    let peer_key = args.get("peer_key").and_then(|v| v.as_str()).unwrap_or("");
                    if peer_key.is_empty() {
                        return json!({"type": "text", "text": "Error: 'peer_key' parameter required for call action"});
                    }
                    // Check not already in a call
                    {
                        let call_state = crate::voice::CALL_STATE.lock().unwrap_or_else(|e| e.into_inner());
                        if let Some(ref cs) = *call_state {
                            if cs.is_in_progress() {
                                let phase_str = if cs.is_ringing() { "ringing" } else { "active" };
                                return json!({"type": "text", "text": format!(
                                    "Already in call with peer {} ({}). Use end_call first.",
                                    &cs.peer_key[..8.min(cs.peer_key.len())], phase_str
                                )});
                            }
                        }
                    }
                    // Start voice session if not active
                    let needs_start = voice_lock.as_ref().map_or(true, |s| !s.is_active());
                    if needs_start {
                        let mut vs = crate::voice::VoiceSession::new(crate::voice::VoiceConfig::default());
                        match vs.start() {
                            Ok(()) => {
                                eprintln!("[SPF-VOICE] Started session for peer call to {}", &peer_key[..8.min(peer_key.len())]);
                                *voice_lock = Some(vs);
                            }
                            Err(e) => {
                                return json!({"type": "text", "text": format!(
                                    "Voice session start failed for call: {}", e)});
                            }
                        }
                    }
                    // Store call state
                    let mut call_state = crate::voice::CALL_STATE.lock().unwrap_or_else(|e| e.into_inner());
                    *call_state = Some(crate::voice::CallState {
                        peer_key: peer_key.to_string(),
                        peer_name: peer_key[..8.min(peer_key.len())].to_string(),
                        direction: crate::voice::CallDirection::Outgoing,
                        phase: crate::voice::CallPhase::Ringing,
                        started_at: std::time::Instant::now(),
                    });
                    // Signal peer via mesh: incoming_ring
                    if let Some(ref tx) = mesh_tx {
                        let addrs: Vec<String> = peers.get(peer_key)
                            .map(|p| p.addr.clone())
                            .unwrap_or_default();
                        let (reply_tx, _) = std::sync::mpsc::channel();
                        let _ = tx.send(crate::mesh::MeshRequest {
                            peer_key: peer_key.to_string(),
                            addrs,
                            tool: "spf_voice_mode".to_string(),
                            args: json!({"action": "incoming_ring", "peer_key": pub_key_hex}),
                            reply: reply_tx,
                        });
                    }
                    let peer_short = &peer_key[..8.min(peer_key.len())];
                    json!({"type": "text", "text": format!(
                        "Calling {}... ring sent. Use end_call to hang up.", peer_short
                    )})
                }
                "end_call" => {
                    // Block MM: End peer voice call
                    let mut call_state = crate::voice::CALL_STATE.lock().unwrap_or_else(|e| e.into_inner());
                    match call_state.take() {
                        Some(cs) if cs.is_in_progress() => {
                            // Signal peer: voice_end
                            if let Some(ref tx) = mesh_tx {
                                let addrs: Vec<String> = peers.get(&cs.peer_key)
                                    .map(|p| p.addr.clone())
                                    .unwrap_or_default();
                                let (reply_tx, _) = std::sync::mpsc::channel();
                                let _ = tx.send(crate::mesh::MeshRequest {
                                    peer_key: cs.peer_key.clone(),
                                    addrs,
                                    tool: "spf_voice_mode".to_string(),
                                    args: json!({"action": "voice_end", "peer_key": pub_key_hex}),
                                    reply: reply_tx,
                                });
                            }
                            let secs = cs.elapsed_secs();
                            let mins = secs / 60;
                            let remaining_secs = secs % 60;
                            // Stop voice session
                            if let Some(ref mut vs) = *voice_lock {
                                vs.stop();
                            }
                            *voice_lock = None;
                            let peer_short = &cs.peer_key[..8.min(cs.peer_key.len())];
                            json!({"type": "text", "text": format!(
                                "Call ended with {}. Duration: {}m {}s", peer_short, mins, remaining_secs
                            )})
                        }
                        _ => {
                            json!({"type": "text", "text": "No active call to end."})
                        }
                    }
                }
                "settings" => {
                    // Block MM: Read/write VoiceSettings
                    let has_updates = args.get("agent_tts_mode").is_some()
                        || args.get("agent_stt_mode").is_some()
                        || args.get("peer_quality").is_some()
                        || args.get("auto_accept_calls").is_some()
                        || args.get("idle_timeout_secs").is_some();
                    if has_updates {
                        let mut settings = crate::voice::VOICE_SETTINGS.lock().unwrap_or_else(|e| e.into_inner());
                        if let Some(mode) = args.get("agent_tts_mode").and_then(|v| v.as_str()) {
                            settings.agent_tts_mode = match mode {
                                "rich" | "Rich" => crate::voice::VoiceMode::Rich,
                                _ => crate::voice::VoiceMode::Light,
                            };
                        }
                        if let Some(mode) = args.get("agent_stt_mode").and_then(|v| v.as_str()) {
                            settings.agent_stt_mode = match mode {
                                "rich" | "Rich" => crate::voice::VoiceMode::Rich,
                                _ => crate::voice::VoiceMode::Light,
                            };
                        }
                        if let Some(mode) = args.get("peer_quality").and_then(|v| v.as_str()) {
                            settings.peer_quality = match mode {
                                "rich" | "Rich" => crate::voice::VoiceMode::Rich,
                                _ => crate::voice::VoiceMode::Light,
                            };
                        }
                        if let Some(val) = args.get("auto_accept_calls").and_then(|v| v.as_bool()) {
                            settings.auto_accept_calls = val;
                        }
                        if let Some(val) = args.get("idle_timeout_secs").and_then(|v| v.as_u64()) {
                            settings.idle_timeout_secs = val as u32;
                        }
                        let settings_json = serde_json::to_string_pretty(&*settings).unwrap_or_default();
                        json!({"type": "text", "text": format!("Voice settings updated:\n{}", settings_json)})
                    } else {
                        // Read-only: show current settings + call status
                        let settings = crate::voice::VOICE_SETTINGS.lock().unwrap_or_else(|e| e.into_inner());
                        let settings_json = serde_json::to_string_pretty(&*settings).unwrap_or_default();
                        let call_state = crate::voice::CALL_STATE.lock().unwrap_or_else(|e| e.into_inner());
                        let call_info = match &*call_state {
                            Some(cs) if cs.is_in_progress() => {
                                let dir = if cs.direction == crate::voice::CallDirection::Incoming { "Incoming" } else { "Outgoing" };
                                let phase = if cs.is_ringing() { "ringing" } else { "active" };
                                format!("{} call: peer={} phase={} duration={}s",
                                    dir, &cs.peer_key[..8.min(cs.peer_key.len())], phase, cs.elapsed_secs())
                            },
                            _ => "No active call".to_string(),
                        };
                        json!({"type": "text", "text": format!(
                            "Voice settings:\n{}\n\nCall status: {}", settings_json, call_info
                        )})
                    }
                }
                "incoming_ring" => {
                    // Peer is calling us — store incoming call state
                    let caller_key = args.get("peer_key").and_then(|v| v.as_str()).unwrap_or("").to_string();
                    if caller_key.is_empty() {
                        return json!({"type": "text", "text": "Error: incoming_ring missing peer_key"});
                    }
                    {
                        let call_state = crate::voice::CALL_STATE.lock().unwrap_or_else(|e| e.into_inner());
                        if let Some(ref cs) = *call_state {
                            if cs.is_in_progress() {
                                eprintln!("[SPF-VOICE] Busy: incoming ring from {} while in call", &caller_key[..8.min(caller_key.len())]);
                                return json!({"type": "text", "text": "busy"});
                            }
                        }
                    }
                    let auto_accept = {
                        let settings = crate::voice::VOICE_SETTINGS.lock().unwrap_or_else(|e| e.into_inner());
                        settings.auto_accept_calls
                    };
                    {
                        let mut call_state = crate::voice::CALL_STATE.lock().unwrap_or_else(|e| e.into_inner());
                        *call_state = Some(crate::voice::CallState {
                            peer_key: caller_key.clone(),
                            peer_name: caller_key[..8.min(caller_key.len())].to_string(),
                            direction: crate::voice::CallDirection::Incoming,
                            phase: if auto_accept { crate::voice::CallPhase::Active } else { crate::voice::CallPhase::Ringing },
                            started_at: std::time::Instant::now(),
                        });
                    }
                    if auto_accept {
                        // Start voice session
                        if voice_lock.as_ref().map_or(true, |s| !s.is_active()) {
                            let mut vs = crate::voice::VoiceSession::new(crate::voice::VoiceConfig::default());
                            if vs.start().is_ok() { *voice_lock = Some(vs); }
                        }
                        // Signal back: accepted
                        if let Some(ref tx) = mesh_tx {
                            let addrs: Vec<String> = peers.get(&caller_key)
                                .map(|p| p.addr.clone())
                                .unwrap_or_default();
                            let (reply_tx, _) = std::sync::mpsc::channel();
                            let _ = tx.send(crate::mesh::MeshRequest {
                                peer_key: caller_key.clone(),
                                addrs,
                                tool: "spf_voice_mode".to_string(),
                                args: json!({"action": "voice_accepted", "peer_key": pub_key_hex}),
                                reply: reply_tx,
                            });
                        }
                        eprintln!("[SPF-VOICE] Auto-accepted call from {}", &caller_key[..8.min(caller_key.len())]);
                        json!({"type": "text", "text": format!(
                            "Auto-accepted call from {}. Voice session active.",
                            &caller_key[..8.min(caller_key.len())]
                        )})
                    } else {
                        eprintln!("[SPF-VOICE] Incoming ring from {} — awaiting decision", &caller_key[..8.min(caller_key.len())]);
                        json!({"type": "text", "text": format!(
                            "Incoming call from {}. Use spf_voice_call action=accept or reject.",
                            &caller_key[..8.min(caller_key.len())]
                        )})
                    }
                }
                "voice_accepted" => {
                    // Peer accepted our outgoing call — activate it
                    let mut call_state = crate::voice::CALL_STATE.lock().unwrap_or_else(|e| e.into_inner());
                    match &mut *call_state {
                        Some(cs) if cs.is_ringing() && cs.direction == crate::voice::CallDirection::Outgoing => {
                            cs.phase = crate::voice::CallPhase::Active;
                            let peer_short = cs.peer_key[..8.min(cs.peer_key.len())].to_string();
                            eprintln!("[SPF-VOICE] Call accepted by {}", peer_short);
                            json!({"type": "text", "text": format!("Call connected with {}", peer_short)})
                        }
                        _ => json!({"type": "text", "text": "voice_accepted: no matching outgoing call"}),
                    }
                }
                "voice_rejected" => {
                    // Peer rejected our outgoing call — clear state
                    let peer_short = {
                        let mut call_state = crate::voice::CALL_STATE.lock().unwrap_or_else(|e| e.into_inner());
                        if call_state.as_ref().map_or(false, |cs| {
                            cs.is_ringing() && cs.direction == crate::voice::CallDirection::Outgoing
                        }) {
                            let s = call_state.as_ref()
                                .map(|cs| cs.peer_key[..8.min(cs.peer_key.len())].to_string())
                                .unwrap_or_default();
                            *call_state = None;
                            s
                        } else {
                            return json!({"type": "text", "text": "voice_rejected: no matching outgoing call"});
                        }
                    };
                    if let Some(ref mut vs) = *voice_lock { vs.stop(); }
                    *voice_lock = None;
                    eprintln!("[SPF-VOICE] Call rejected by {}", peer_short);
                    json!({"type": "text", "text": format!("Call rejected by {}", peer_short)})
                }
                "voice_end" => {
                    // Peer ended an active or ringing call — clear state
                    let call_info = {
                        let mut call_state = crate::voice::CALL_STATE.lock().unwrap_or_else(|e| e.into_inner());
                        call_state.take().map(|cs| (
                            cs.peer_key[..8.min(cs.peer_key.len())].to_string(),
                            cs.elapsed_secs()
                        ))
                    };
                    match call_info {
                        Some((peer_short, secs)) => {
                            if let Some(ref mut vs) = *voice_lock { vs.stop(); }
                            *voice_lock = None;
                            eprintln!("[SPF-VOICE] Peer {} ended call ({}s)", peer_short, secs);
                            json!({"type": "text", "text": format!(
                                "Call ended by peer {}. Duration: {}s", peer_short, secs
                            )})
                        }
                        None => json!({"type": "text", "text": "voice_end: no active call"}),
                    }
                }
                "team_join_notify" => {
                    // Peer has joined a team channel — update local active_members
                    let team_id = args.get("team_id").and_then(|v| v.as_str()).unwrap_or("default").to_string();
                    let peer_key = args.get("peer_key").and_then(|v| v.as_str()).unwrap_or("").to_string();
                    let display_name = args.get("display_name").and_then(|v| v.as_str())
                        .unwrap_or(&peer_key[..8.min(peer_key.len())]).to_string();
                    if peer_key.is_empty() {
                        return json!({"type": "text", "text": "team_join_notify: missing peer_key"});
                    }
                    let summary = {
                        let mut teams = crate::voice::VOICE_TEAMS.lock().unwrap_or_else(|e| e.into_inner());
                        let channel = teams.entry(team_id.clone())
                            .or_insert_with(|| crate::voice::TeamChannel::new(&team_id, &team_id));
                        channel.join(&peer_key, &display_name);
                        channel.summary_line()
                    };
                    eprintln!("[SPF-VOICE] Team {}: peer {} ({}) joined — {}", team_id, &peer_key[..8.min(peer_key.len())], display_name, summary);
                    json!({"type": "text", "text": format!(
                        "Peer {} ({}) joined team [{}]. {}", &peer_key[..8.min(peer_key.len())], display_name, team_id, summary
                    )})
                }
                "team_leave_notify" => {
                    // Peer has left a team channel — remove from local active_members
                    let team_id = args.get("team_id").and_then(|v| v.as_str()).unwrap_or("default").to_string();
                    let peer_key = args.get("peer_key").and_then(|v| v.as_str()).unwrap_or("").to_string();
                    if peer_key.is_empty() {
                        return json!({"type": "text", "text": "team_leave_notify: missing peer_key"});
                    }
                    let (was_present, summary) = {
                        let mut teams = crate::voice::VOICE_TEAMS.lock().unwrap_or_else(|e| e.into_inner());
                        if let Some(channel) = teams.get_mut(&team_id) {
                            let was = channel.leave(&peer_key);
                            (was, channel.summary_line())
                        } else {
                            (false, format!("team [{}] not found", team_id))
                        }
                    };
                    eprintln!("[SPF-VOICE] Team {}: peer {} left (was_present={})", team_id, &peer_key[..8.min(peer_key.len())], was_present);
                    json!({"type": "text", "text": format!(
                        "Peer {} left team [{}]. {}", &peer_key[..8.min(peer_key.len())], team_id, summary
                    )})
                }
                "team_invite" => {
                    // We have been invited to a team channel — create/update local channel entry
                    let team_id = args.get("team_id").and_then(|v| v.as_str()).unwrap_or("default").to_string();
                    let team_name = args.get("team_name").and_then(|v| v.as_str()).unwrap_or(&team_id).to_string();
                    let from_key = args.get("from_key").and_then(|v| v.as_str()).unwrap_or("").to_string();
                    {
                        let mut teams = crate::voice::VOICE_TEAMS.lock().unwrap_or_else(|e| e.into_inner());
                        let channel = teams.entry(team_id.clone())
                            .or_insert_with(|| crate::voice::TeamChannel::new(&team_id, &team_name));
                        if !from_key.is_empty() {
                            channel.add_member(&from_key);
                        }
                    }
                    eprintln!("[SPF-VOICE] Invited to team [{}] ({}) by {}", team_id, team_name, &from_key[..8.min(from_key.len())]);
                    json!({"type": "text", "text": format!(
                        "Invited to team [{}] '{}' by peer {}. Use spf_voice_team action=join team_id={} to join.",
                        team_id, team_name, &from_key[..8.min(from_key.len())], team_id
                    )})
                }
                "listen" => {
                    // Block MM: Capture mic audio for N seconds → Whisper STT → return text
                    let duration_secs = args.get("duration").and_then(|v| v.as_u64()).unwrap_or(5).min(60);

                    // Ensure session is started (input device initialised)
                    if voice_lock.is_none() {
                        let config = crate::voice::VoiceConfig::default();
                        *voice_lock = Some(crate::voice::VoiceSession::new(config));
                    }
                    if let Some(ref mut session) = *voice_lock {
                        if !session.is_active() {
                            if let Err(e) = session.start() {
                                return json!({"type": "text", "text": format!("Failed to start audio input: {}", e)});
                            }
                        }
                    }

                    // Collect frames for the requested duration
                    let deadline = std::time::Duration::from_secs(duration_secs);
                    let start = std::time::Instant::now();
                    let mut frames: Vec<crate::voice::VoiceFrame> = Vec::new();

                    while start.elapsed() < deadline {
                        if let Some(ref mut session) = *voice_lock {
                            match session.capture_frame("listen") {
                                Ok(frame) => frames.push(frame),
                                Err(crate::voice::VoiceError::NotAvailable(_)) => {
                                    return json!({"type": "text", "text": "Audio input not available. Ensure pulseaudio is running (pulseaudio --start) and spf-voice crate is compiled."});
                                }
                                Err(e) => {
                                    eprintln!("[SPF-VOICE-LISTEN] capture error: {}", e);
                                    std::thread::sleep(std::time::Duration::from_millis(5));
                                }
                            }
                        }
                    }

                    if frames.is_empty() {
                        return json!({"type": "text", "text": "No audio captured. Ensure voice session is active and microphone is accessible."});
                    }

                    // Transcribe via Whisper (voice-stt feature) or stub
                    match voice_lock.as_mut().and_then(|s| Some(s.transcribe(&frames))) {
                        Some(Ok(text)) if text.trim().is_empty() => {
                            json!({"type": "text", "text": "(silence — no speech detected)"})
                        }
                        Some(Ok(text)) => json!({"type": "text", "text": text}),
                        Some(Err(crate::voice::VoiceError::NotAvailable(_))) => {
                            json!({"type": "text", "text": "STT not available. Rebuild with --features voice-stt to enable Whisper transcription."})
                        }
                        Some(Err(e)) => json!({"type": "text", "text": format!("Transcription error: {}", e)}),
                        None => json!({"type": "text", "text": "Voice session unavailable."}),
                    }
                }
                "stream_on" => {
                    #[cfg(feature = "voice-stt")]
                    {
                        let model_dir = crate::paths::spf_root().join("LIVE/MODELS/whisper-tiny");
                        match crate::voice::stream_on(model_dir) {
                            Ok(()) => json!({"type": "text", "text": "Streaming STT started. Speak freely. Say 'end stream' or 'stop stream' to finish. Use stream_read to get transcripts."}),
                            Err(e) => json!({"type": "text", "text": format!("Failed to start streaming STT: {}", e)}),
                        }
                    }
                    #[cfg(not(feature = "voice-stt"))]
                    json!({"type": "text", "text": "stream_on requires voice-stt feature."})
                }
                "stream_off" => {
                    crate::voice::stream_off();
                    json!({"type": "text", "text": "Streaming STT stopped."})
                }
                "stream_read" => {
                    let active = crate::voice::STREAM_ACTIVE.load(std::sync::atomic::Ordering::SeqCst);
                    let transcripts = crate::voice::stream_read();
                    if transcripts.is_empty() {
                        json!({"type": "text", "text": format!("No transcripts yet. Streaming: {}", active)})
                    } else {
                        let combined = transcripts.join("\n");
                        json!({"type": "text", "text": format!("Streaming: {}\n---\n{}", active, combined)})
                    }
                }
                other => {
                    json!({"type": "text", "text": format!(
                        "Unknown voice action: '{}'. Valid: start, stop, status, speak, listen, stream_on, stream_off, stream_read, call, end_call, settings, incoming_ring, voice_accepted, voice_rejected, voice_end, team_join_notify, team_leave_notify, team_invite", other
                    )})
                }
            }
        }

        // ====== VOICE CALL (Block TV-5) ======
        "spf_voice_call" => {
            session.record_action("spf_voice_call", "called", None);
            let action = args["action"].as_str().unwrap_or("status");
            let mut voice_lock = crate::voice::VOICE_SESSION.lock().unwrap_or_else(|e| e.into_inner());

            match action {
                "start" => {
                    let peer_key = args.get("peer_key").and_then(|v| v.as_str()).unwrap_or("");
                    if peer_key.is_empty() {
                        return json!({"type": "text", "text": "Error: 'peer_key' required for start"});
                    }
                    // Check not already in a call
                    {
                        let call_state = crate::voice::CALL_STATE.lock().unwrap_or_else(|e| e.into_inner());
                        if let Some(ref cs) = *call_state {
                            if cs.is_in_progress() {
                                let phase = if cs.is_ringing() { "ringing" } else { "active" };
                                return json!({"type": "text", "text": format!(
                                    "Already in call ({} {}). Use end first.",
                                    phase, &cs.peer_key[..8.min(cs.peer_key.len())]
                                )});
                            }
                        }
                    }
                    let peer_name = args.get("peer_name")
                        .and_then(|v| v.as_str())
                        .unwrap_or(&peer_key[..8.min(peer_key.len())])
                        .to_string();
                    // Start voice session
                    if voice_lock.as_ref().map_or(true, |s| !s.is_active()) {
                        let mut vs = crate::voice::VoiceSession::new(crate::voice::VoiceConfig::default());
                        match vs.start() {
                            Ok(()) => { *voice_lock = Some(vs); }
                            Err(e) => return json!({"type": "text", "text": format!("Voice start failed: {}", e)}),
                        }
                    }
                    // Store call state
                    {
                        let mut call_state = crate::voice::CALL_STATE.lock().unwrap_or_else(|e| e.into_inner());
                        *call_state = Some(crate::voice::CallState {
                            peer_key: peer_key.to_string(),
                            peer_name: peer_name.clone(),
                            direction: crate::voice::CallDirection::Outgoing,
                            phase: crate::voice::CallPhase::Ringing,
                            started_at: std::time::Instant::now(),
                        });
                    }
                    // Signal peer via mesh: incoming_ring
                    let signal = if let Some(ref tx) = mesh_tx {
                        let addrs: Vec<String> = peers.get(peer_key)
                            .map(|p| p.addr.clone())
                            .unwrap_or_default();
                        let (reply_tx, reply_rx) = std::sync::mpsc::channel();
                        let req = crate::mesh::MeshRequest {
                            peer_key: peer_key.to_string(),
                            addrs,
                            tool: "spf_voice_mode".to_string(),
                            args: json!({"action": "incoming_ring", "peer_key": pub_key_hex}),
                            reply: reply_tx,
                        };
                        if tx.send(req).is_ok() {
                            match reply_rx.recv_timeout(std::time::Duration::from_secs(5)) {
                                Ok(Ok(_)) => "signal delivered",
                                _ => "signal pending (peer may be offline)",
                            }
                        } else { "mesh unavailable" }
                    } else { "mesh not configured" };
                    json!({"type": "text", "text": format!(
                        "Calling {} ({})... {}. Use action=end to hang up.",
                        peer_name, &peer_key[..8.min(peer_key.len())], signal
                    )})
                }
                "accept" => {
                    // Accept an incoming ringing call
                    let (peer_key, peer_name) = {
                        let mut call_state = crate::voice::CALL_STATE.lock().unwrap_or_else(|e| e.into_inner());
                        match &mut *call_state {
                            Some(cs) if cs.is_ringing() && cs.direction == crate::voice::CallDirection::Incoming => {
                                cs.phase = crate::voice::CallPhase::Active;
                                (cs.peer_key.clone(), cs.peer_name.clone())
                            }
                            _ => return json!({"type": "text", "text": "No incoming ringing call to accept"}),
                        }
                    };
                    // Start voice session
                    if voice_lock.as_ref().map_or(true, |s| !s.is_active()) {
                        let mut vs = crate::voice::VoiceSession::new(crate::voice::VoiceConfig::default());
                        if vs.start().is_ok() { *voice_lock = Some(vs); }
                    }
                    // Signal peer: voice_accepted
                    if let Some(ref tx) = mesh_tx {
                        let addrs: Vec<String> = peers.get(&peer_key)
                            .map(|p| p.addr.clone())
                            .unwrap_or_default();
                        let (reply_tx, _) = std::sync::mpsc::channel();
                        let _ = tx.send(crate::mesh::MeshRequest {
                            peer_key: peer_key.clone(),
                            addrs,
                            tool: "spf_voice_mode".to_string(),
                            args: json!({"action": "voice_accepted", "peer_key": pub_key_hex}),
                            reply: reply_tx,
                        });
                    }
                    json!({"type": "text", "text": format!("Call accepted — connected to {}", peer_name)})
                }
                "reject" => {
                    // Reject an incoming ringing call
                    let peer_key = {
                        let mut call_state = crate::voice::CALL_STATE.lock().unwrap_or_else(|e| e.into_inner());
                        if call_state.as_ref().map_or(false, |cs| {
                            cs.is_ringing() && cs.direction == crate::voice::CallDirection::Incoming
                        }) {
                            let k = call_state.as_ref().map(|cs| cs.peer_key.clone()).unwrap_or_default();
                            *call_state = None;
                            k
                        } else {
                            return json!({"type": "text", "text": "No incoming ringing call to reject"});
                        }
                    };
                    // Signal peer: voice_rejected
                    if let Some(ref tx) = mesh_tx {
                        let addrs: Vec<String> = peers.get(&peer_key)
                            .map(|p| p.addr.clone())
                            .unwrap_or_default();
                        let (reply_tx, _) = std::sync::mpsc::channel();
                        let _ = tx.send(crate::mesh::MeshRequest {
                            peer_key: peer_key.clone(),
                            addrs,
                            tool: "spf_voice_mode".to_string(),
                            args: json!({"action": "voice_rejected", "peer_key": pub_key_hex}),
                            reply: reply_tx,
                        });
                    }
                    json!({"type": "text", "text": format!(
                        "Rejected call from {}", &peer_key[..8.min(peer_key.len())]
                    )})
                }
                "end" => {
                    // End any active or ringing call
                    let call_opt = {
                        let mut call_state = crate::voice::CALL_STATE.lock().unwrap_or_else(|e| e.into_inner());
                        if call_state.as_ref().map_or(false, |cs| cs.is_in_progress()) {
                            call_state.take()
                        } else {
                            None
                        }
                    };
                    match call_opt {
                        Some(cs) => {
                            let peer_key = cs.peer_key.clone();
                            let secs = cs.elapsed_secs();
                            // Stop voice session
                            if let Some(ref mut vs) = *voice_lock { vs.stop(); }
                            *voice_lock = None;
                            // Signal peer: voice_end
                            if let Some(ref tx) = mesh_tx {
                                let addrs: Vec<String> = peers.get(&peer_key)
                                    .map(|p| p.addr.clone())
                                    .unwrap_or_default();
                                let (reply_tx, _) = std::sync::mpsc::channel();
                                let _ = tx.send(crate::mesh::MeshRequest {
                                    peer_key: peer_key.clone(),
                                    addrs,
                                    tool: "spf_voice_mode".to_string(),
                                    args: json!({"action": "voice_end", "peer_key": pub_key_hex}),
                                    reply: reply_tx,
                                });
                            }
                            let mins = secs / 60;
                            let rem = secs % 60;
                            json!({"type": "text", "text": format!(
                                "Call ended. Duration: {}m {}s", mins, rem
                            )})
                        }
                        None => json!({"type": "text", "text": "No active call to end"}),
                    }
                }
                "status" => {
                    let call_state = crate::voice::CALL_STATE.lock().unwrap_or_else(|e| e.into_inner());
                    match &*call_state {
                        Some(cs) => {
                            let dir = if cs.direction == crate::voice::CallDirection::Incoming { "Incoming" } else { "Outgoing" };
                            let phase = if cs.is_ringing() { "ringing" } else { "active" };
                            json!({"type": "text", "text": format!(
                                "{} call with {} ({}) — {} — {}s elapsed",
                                dir, cs.peer_name,
                                &cs.peer_key[..8.min(cs.peer_key.len())],
                                phase, cs.elapsed_secs()
                            )})
                        }
                        None => json!({"type": "text", "text": "No active call"}),
                    }
                }
                other => json!({"type": "text", "text": format!(
                    "Unknown action: '{}'. Valid: start, accept, reject, end, status", other
                )}),
            }
        }

        // ====== VOICE TEAM (Block TV-6) ======
        "spf_voice_team" => {
            session.record_action("spf_voice_team", "called", None);
            let action = args["action"].as_str().unwrap_or("list");
            let team_id = args.get("team_id").and_then(|v| v.as_str()).unwrap_or("default").to_string();

            match action {
                "create" => {
                    let name = args.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string();
                    if name.is_empty() {
                        return json!({"type": "text", "text": "Error: 'name' required for create"});
                    }
                    let summary = {
                        let mut teams = crate::voice::VOICE_TEAMS.lock().unwrap_or_else(|e| e.into_inner());
                        if teams.contains_key(&team_id) {
                            return json!({"type": "text", "text": format!(
                                "Team [{}] already exists. Use status to inspect.", team_id
                            )});
                        }
                        let ch = crate::voice::TeamChannel::new(&team_id, &name);
                        let s = ch.summary_line();
                        teams.insert(team_id.clone(), ch);
                        s
                    };
                    json!({"type": "text", "text": format!("Created team [{}]: {}", team_id, summary)})
                }
                "join" => {
                    let display_name = args.get("display_name").and_then(|v| v.as_str())
                        .unwrap_or(&pub_key_hex[..8.min(pub_key_hex.len())]).to_string();
                    // Join locally
                    let (active_keys, summary) = {
                        let mut teams = crate::voice::VOICE_TEAMS.lock().unwrap_or_else(|e| e.into_inner());
                        let channel = teams.entry(team_id.clone())
                            .or_insert_with(|| crate::voice::TeamChannel::new(&team_id, &team_id));
                        channel.join(pub_key_hex, &display_name);
                        (channel.active_peer_keys(), channel.summary_line())
                    };
                    // Notify all other active members
                    let mut notified = 0usize;
                    for peer_key in &active_keys {
                        if peer_key == pub_key_hex { continue; }
                        if let Some(ref tx) = mesh_tx {
                            let addrs: Vec<String> = peers.get(peer_key)
                                .map(|p| p.addr.clone())
                                .unwrap_or_default();
                            let (reply_tx, _) = std::sync::mpsc::channel();
                            let _ = tx.send(crate::mesh::MeshRequest {
                                peer_key: peer_key.clone(),
                                addrs,
                                tool: "spf_voice_mode".to_string(),
                                args: json!({
                                    "action": "team_join_notify",
                                    "team_id": team_id,
                                    "peer_key": pub_key_hex,
                                    "display_name": display_name
                                }),
                                reply: reply_tx,
                            });
                            notified += 1;
                        }
                    }
                    json!({"type": "text", "text": format!(
                        "Joined team [{}] as '{}'. Notified {} peers. {}",
                        team_id, display_name, notified, summary
                    )})
                }
                "leave" => {
                    let (was_present, active_keys, summary) = {
                        let mut teams = crate::voice::VOICE_TEAMS.lock().unwrap_or_else(|e| e.into_inner());
                        if let Some(channel) = teams.get_mut(&team_id) {
                            // Snapshot active peers BEFORE leaving (so we still notify them)
                            let keys = channel.active_peer_keys();
                            let was = channel.leave(pub_key_hex);
                            (was, keys, channel.summary_line())
                        } else {
                            return json!({"type": "text", "text": format!("Team [{}] not found", team_id)});
                        }
                    };
                    if !was_present {
                        return json!({"type": "text", "text": format!("Not a member of team [{}]", team_id)});
                    }
                    // Notify remaining active members
                    let mut notified = 0usize;
                    for peer_key in &active_keys {
                        if peer_key == pub_key_hex { continue; }
                        if let Some(ref tx) = mesh_tx {
                            let addrs: Vec<String> = peers.get(peer_key)
                                .map(|p| p.addr.clone())
                                .unwrap_or_default();
                            let (reply_tx, _) = std::sync::mpsc::channel();
                            let _ = tx.send(crate::mesh::MeshRequest {
                                peer_key: peer_key.clone(),
                                addrs,
                                tool: "spf_voice_mode".to_string(),
                                args: json!({
                                    "action": "team_leave_notify",
                                    "team_id": team_id,
                                    "peer_key": pub_key_hex
                                }),
                                reply: reply_tx,
                            });
                            notified += 1;
                        }
                    }
                    json!({"type": "text", "text": format!(
                        "Left team [{}]. Notified {} peers. {}", team_id, notified, summary
                    )})
                }
                "add" => {
                    // Invite a peer to the team (add to members list + signal them)
                    let peer_key = args.get("peer_key").and_then(|v| v.as_str()).unwrap_or("");
                    if peer_key.is_empty() {
                        return json!({"type": "text", "text": "Error: 'peer_key' required for add"});
                    }
                    let (team_name, summary) = {
                        let mut teams = crate::voice::VOICE_TEAMS.lock().unwrap_or_else(|e| e.into_inner());
                        let channel = teams.entry(team_id.clone())
                            .or_insert_with(|| crate::voice::TeamChannel::new(&team_id, &team_id));
                        channel.add_member(peer_key);
                        (channel.name.clone(), channel.summary_line())
                    };
                    // Signal peer: team_invite
                    if let Some(ref tx) = mesh_tx {
                        let addrs: Vec<String> = peers.get(peer_key)
                            .map(|p| p.addr.clone())
                            .unwrap_or_default();
                        let (reply_tx, _) = std::sync::mpsc::channel();
                        let _ = tx.send(crate::mesh::MeshRequest {
                            peer_key: peer_key.to_string(),
                            addrs,
                            tool: "spf_voice_mode".to_string(),
                            args: json!({
                                "action": "team_invite",
                                "team_id": team_id,
                                "team_name": team_name,
                                "from_key": pub_key_hex
                            }),
                            reply: reply_tx,
                        });
                    }
                    json!({"type": "text", "text": format!(
                        "Added {} to team [{}]. Invite signal sent. {}",
                        &peer_key[..8.min(peer_key.len())], team_id, summary
                    )})
                }
                "list" => {
                    let teams = crate::voice::VOICE_TEAMS.lock().unwrap_or_else(|e| e.into_inner());
                    if teams.is_empty() {
                        json!({"type": "text", "text": "No team channels. Use action=create to add one."})
                    } else {
                        let lines: Vec<String> = teams.values().map(|ch| ch.summary_line()).collect();
                        json!({"type": "text", "text": format!("Team channels ({}):\n{}", lines.len(), lines.join("\n"))})
                    }
                }
                "status" => {
                    let teams = crate::voice::VOICE_TEAMS.lock().unwrap_or_else(|e| e.into_inner());
                    match teams.get(&team_id) {
                        Some(ch) => {
                            let members_str = if ch.members.is_empty() {
                                "  none".to_string()
                            } else {
                                ch.members.iter().map(|k| format!("  {}", &k[..8.min(k.len())])).collect::<Vec<_>>().join("\n")
                            };
                            let active_str = if ch.active_members.is_empty() {
                                "  none".to_string()
                            } else {
                                ch.active_members.iter().map(|m| format!(
                                    "  {} ({})", &m.peer_key[..8.min(m.peer_key.len())], m.name
                                )).collect::<Vec<_>>().join("\n")
                            };
                            json!({"type": "text", "text": format!(
                                "Team [{}] '{}'\nInvited ({}):\n{}\nActive ({}):\n{}",
                                ch.team_id, ch.name,
                                ch.member_count(), members_str,
                                ch.active_count(), active_str
                            )})
                        }
                        None => json!({"type": "text", "text": format!("Team [{}] not found. Use list to see all channels.", team_id)}),
                    }
                }
                other => json!({"type": "text", "text": format!(
                    "Unknown action: '{}'. Valid: create, join, leave, add, list, status", other
                )}),
            }
        }

        // ====== FLINT WORKER MODE (Block II) ======
        "spf_flint_execute" => {
            session.record_action("spf_flint_execute", "called", None);

            // Verify transformer is loaded (Option<Arc<RwLock>> — check outer + lock)
            let transformer_loaded = transformer.as_ref()
                .and_then(|t| t.read().ok())
                .is_some();

            if !transformer_loaded {
                return json!({"type": "text", "text":
                    "[FLINT] Error: transformer not loaded — cannot execute in worker mode"});
            }

            let tool_name = args["tool_name"].as_str().unwrap_or("");
            let tool_args = if args["arguments"].is_object() {
                args["arguments"].clone()
            } else {
                json!({})
            };
            let reason = args["reason"].as_str().unwrap_or("(no reason provided)");

            // RECURSION GUARD — prevent infinite self-invocation
            if tool_name == "spf_flint_execute" {
                return json!({"type": "text", "text":
                    "[FLINT] BLOCKED: recursive self-invocation not permitted"});
            }

            if tool_name.is_empty() {
                return json!({"type": "text", "text": "[FLINT] Error: tool_name is required"});
            }

            // Log the dispatch intent
            session.record_action("spf_flint_execute", "dispatching",
                Some(&format!("tool={} reason={}", tool_name, reason)));

            // Gate inner tool with Source::Transformer — same permissions as Stdio
            let flint_gate_params = extract_gate_params(&tool_args);
            let flint_source = crate::dispatch::Source::Transformer {
                role: "worker".to_string(),
                model_id: "flint".to_string(),
            };
            let flint_decision = crate::gate::process(tool_name, &flint_gate_params, config, session, &flint_source);
            if !flint_decision.allowed {
                return json!({
                    "type": "text",
                    "text": format!("[FLINT] BLOCKED: {}", flint_decision.message),
                    "_blocked": true
                });
            }
            let result = handle_tool_call(
                tool_name, &tool_args, flint_source, &flint_decision, config, session, storage,
                config_db, tmp_db, _fs_db, agent_db, pub_key_hex,
                mesh_tx, peers, transformer, transformer_config,
                network_config, pool_state, pipeline,
                browser, ws_browser_channels, http_port,
                tracked_peers, orchestrator_state,
                endpoint, tokio_handle,
            );

            // Extract result and tag with [FLINT] prefix for identification
            let result_text = result.get("text")
                .and_then(|t| t.as_str())
                .unwrap_or("(no output)");
            let was_blocked = result.get("_blocked")
                .and_then(|b| b.as_bool())
                .unwrap_or(false);

            json!({
                "type": "text",
                "text": format!("[FLINT] Tool: {} | Reason: {} | {}{}",
                    tool_name, reason,
                    if was_blocked { "BLOCKED: " } else { "" },
                    result_text
                ),
                "_flint_worker": true,
                "_tool_executed": tool_name,
                "_was_blocked": was_blocked
            })
        }

        // ====== NETWORK POOL TOOLS (Block NP) ======

        "spf_pool_status" => {
            match pool_state {
                Some(pool) => {
                    let snapshot = pool.status_snapshot();
                    let idle = pool.idle_count();
                    let active = pool.active_count();
                    let cap = pool.capacity();
                    let mut lines = vec![
                        format!("Network Pool — NetAdmin | {}/{} workers active | {} idle | capacity {}", active, cap, idle, cap),
                    ];
                    for (name, status, task_id, elapsed_ms) in &snapshot {
                        let task_str = task_id.as_deref().unwrap_or("-");
                        lines.push(format!("  {:<20} {:8}  task={:<30}  elapsed={}ms", name, status, task_str, elapsed_ms));
                    }
                    json!({"type": "text", "text": lines.join("\n")})
                }
                None => {
                    let role = if network_config.is_netadmin() { "NetAdmin (pool not initialised)" } else { "Worker" };
                    json!({"type": "text", "text": format!("Network role: {}\nPool management delegated to NetAdmin node.", role)})
                }
            }
        }

        "spf_pool_assign" => {
            if !network_config.is_netadmin() {
                return json!({"type": "text", "text": "BLOCKED: spf_pool_assign requires NetAdmin role", "_blocked": true});
            }
            let pool = match pool_state {
                Some(p) => p,
                None => return json!({"type": "text", "text": "Pool not initialised"}),
            };
            let tool_name = args["tool"].as_str().unwrap_or("unknown");
            let worker_name_arg = args["worker_name"].as_str();

            // Resolve worker key: by name if given, else auto-select idle
            let key_hex = match worker_name_arg {
                Some(name) => pool.find_by_name(name),
                None       => pool.find_idle(),
            };
            let key_hex = match key_hex {
                Some(k) => k,
                None    => return json!({"type": "text", "text": "No idle workers available in pool"}),
            };

            let task_id = crate::network::new_task_id();
            match pool.borrow(&key_hex, &task_id) {
                Ok(()) => {
                    let peer = pool.get_peer(&key_hex);
                    let wname = peer.as_ref().map(|p| p.name.as_str()).unwrap_or("unknown");
                    session.record_action("spf_pool_assign", &task_id, Some(wname));
                    json!({"type": "text", "text": format!(
                        "Task assigned\ntask_id:    {}\nworker:     {}\nworker_key: {}\ntool:       {}",
                        task_id, wname, key_hex, tool_name
                    )})
                }
                Err(e) => json!({"type": "text", "text": format!("Assign failed: {}", e)}),
            }
        }

        "spf_pool_release" => {
            if !network_config.is_netadmin() {
                return json!({"type": "text", "text": "BLOCKED: spf_pool_release requires NetAdmin role", "_blocked": true});
            }
            let pool = match pool_state {
                Some(p) => p,
                None => return json!({"type": "text", "text": "Pool not initialised"}),
            };
            let task_id = args["task_id"].as_str().unwrap_or("");
            let result_val = args.get("result").cloned().unwrap_or(serde_json::json!({}));

            // Find which worker holds this task_id via snapshot scan
            let snapshot = pool.status_snapshot();
            let worker_name_for_lookup: Option<String> = snapshot.iter()
                .find(|(_, _, tid, _)| tid.as_deref() == Some(task_id))
                .map(|(name, _, _, _)| name.clone());

            let key_hex = worker_name_for_lookup
                .as_deref()
                .and_then(|n| pool.find_by_name(n));

            let key_hex = match key_hex {
                Some(k) => k,
                None => return json!({"type": "text", "text": format!("No worker found holding task_id: {}", task_id)}),
            };

            match pool.release(&key_hex) {
                Ok(wname) => {
                    let result_hash = crate::network::hash_result(&result_val);
                    session.record_manifest(task_id, 0, "POOL_RELEASE", Some(&wname));
                    json!({"type": "text", "text": format!(
                        "Worker released\ntask_id:     {}\nworker:      {}\nresult_hash: {}\nPool: {}/{} idle",
                        task_id, wname, result_hash, pool.idle_count(), pool.capacity()
                    )})
                }
                Err(e) => json!({"type": "text", "text": format!("Release failed: {}", e)}),
            }
        }

        // ====== CHANNEL HUB (Block CH-5) ======
        "spf_channel" => {
            session.record_action("spf_channel", "called", None);
            let action = args["action"].as_str().unwrap_or("status");
            let channel_id = args["channel_id"].as_str().unwrap_or("");
            let display_name = args["name"].as_str().unwrap_or("Agent");
            let text = args["text"].as_str().unwrap_or("");
            let limit = args["limit"].as_u64().unwrap_or(50) as usize;
            let msg_type_str = args["msg_type"].as_str().unwrap_or("text");
            let hub_url = args["hub_url"].as_str().unwrap_or("");

            let msg_type = match msg_type_str {
                "tool_result" => crate::channel::MessageType::ToolResult,
                "system" => crate::channel::MessageType::System,
                _ => crate::channel::MessageType::Text,
            };

            match action {
                // --- Hub-side actions (orchestrator runs the hub) ---
                "create" => {
                    let ch_name = if display_name == "Agent" && !text.is_empty() { text } else { display_name };
                    let name_arg = args["name"].as_str().unwrap_or(ch_name);
                    let result = crate::channel::api_create_channel(name_arg, pub_key_hex, display_name);
                    json!({"type": "text", "text": serde_json::to_string_pretty(&result).unwrap_or_default()})
                }

                "join" => {
                    if channel_id.is_empty() {
                        return json!({"type": "text", "text": "Error: channel_id required for join"});
                    }
                    let result = crate::channel::api_join_channel(channel_id, pub_key_hex, display_name);
                    json!({"type": "text", "text": serde_json::to_string_pretty(&result).unwrap_or_default()})
                }

                "leave" => {
                    if channel_id.is_empty() {
                        return json!({"type": "text", "text": "Error: channel_id required for leave"});
                    }
                    let result = crate::channel::api_leave_channel(channel_id, pub_key_hex);
                    json!({"type": "text", "text": serde_json::to_string_pretty(&result).unwrap_or_default()})
                }

                "send" => {
                    if channel_id.is_empty() || text.is_empty() {
                        return json!({"type": "text", "text": "Error: channel_id and text required for send"});
                    }
                    let result = crate::channel::api_send_message(channel_id, pub_key_hex, display_name, text, msg_type);
                    json!({"type": "text", "text": serde_json::to_string_pretty(&result).unwrap_or_default()})
                }

                "history" => {
                    if channel_id.is_empty() {
                        return json!({"type": "text", "text": "Error: channel_id required for history"});
                    }
                    let result = crate::channel::api_channel_history(channel_id, limit);
                    json!({"type": "text", "text": serde_json::to_string_pretty(&result).unwrap_or_default()})
                }

                "list" => {
                    let result = crate::channel::api_list_channels();
                    json!({"type": "text", "text": serde_json::to_string_pretty(&result).unwrap_or_default()})
                }

                // --- Client-side actions (agent connects to remote hub) ---
                "connect" => {
                    if hub_url.is_empty() || channel_id.is_empty() {
                        return json!({"type": "text", "text": "Error: hub_url and channel_id required for connect"});
                    }
                    // Get tokio handle for spawning WS client task
                    let rt_guard = tokio_handle.lock().unwrap();
                    let handle = match rt_guard.as_ref() {
                        Some(h) => h,
                        None => return json!({"type": "text", "text": "Error: tokio runtime not available (mesh not started?)"}),
                    };
                    // Derive API key for hub auth
                    let api_key = std::env::var("SPF_API_KEY").unwrap_or_default();
                    match crate::channel::ws_client_connect(handle, hub_url, channel_id, &api_key, pub_key_hex, display_name) {
                        Ok(key) => json!({"type": "text", "text": format!("Connected to {} #{}\nClient key: {}", hub_url, channel_id, key)}),
                        Err(e) => json!({"type": "text", "text": format!("Connect failed: {}", e)}),
                    }
                }

                "disconnect" => {
                    if hub_url.is_empty() || channel_id.is_empty() {
                        return json!({"type": "text", "text": "Error: hub_url and channel_id required for disconnect"});
                    }
                    let key = format!("{}#{}", hub_url, channel_id);
                    match crate::channel::ws_client_disconnect(&key) {
                        Ok(()) => json!({"type": "text", "text": format!("Disconnected from {}", key)}),
                        Err(e) => json!({"type": "text", "text": format!("Disconnect error: {}", e)}),
                    }
                }

                "listen" => {
                    // If hub_url provided, drain from WS client buffer (agent-side)
                    if !hub_url.is_empty() && !channel_id.is_empty() {
                        let key = format!("{}#{}", hub_url, channel_id);
                        match crate::channel::ws_client_drain(&key) {
                            Ok(msgs) => {
                                if msgs.is_empty() {
                                    json!({"type": "text", "text": "No new messages"})
                                } else {
                                    json!({"type": "text", "text": serde_json::to_string_pretty(&msgs).unwrap_or_default()})
                                }
                            }
                            Err(e) => json!({"type": "text", "text": format!("Listen error: {}", e)}),
                        }
                    } else if !channel_id.is_empty() {
                        // Hub-side: just return recent history
                        let result = crate::channel::api_channel_history(channel_id, limit);
                        json!({"type": "text", "text": serde_json::to_string_pretty(&result).unwrap_or_default()})
                    } else {
                        json!({"type": "text", "text": "Error: channel_id required for listen (hub_url also needed for remote)"})
                    }
                }

                "status" => {
                    let clients = crate::channel::ws_client_list();
                    let channels = crate::channel::api_list_channels();
                    json!({"type": "text", "text": format!(
                        "Channel Hub Status:\n{}\n\nWS Client Connections:\n{}",
                        serde_json::to_string_pretty(&channels).unwrap_or_default(),
                        serde_json::to_string_pretty(&clients).unwrap_or_default()
                    )})
                }

                other => {
                    json!({"type": "text", "text": format!("Unknown channel action: {}. Use: create, join, leave, send, listen, history, list, connect, disconnect, status", other)})
                }
            }
        }

        _ => {
            json!({"type": "text", "text": format!("Unknown tool: {}", name)})
        }
    }
}

/// Main MCP server loop — runs forever on stdio
/// Build dispatch listeners based on configuration.
/// Wires GateTrainingCollector when transformer is enabled — captures gate
/// decisions as supervised training signals for the learning pipeline.
fn build_listeners(
    _config: &SpfConfig,
    transformer_config: &crate::config::TransformerConfig,
) -> (Vec<Box<dyn crate::dispatch::DispatchListener>>, Option<std::sync::Arc<crate::gate_training::GateTrainingCollector>>) {
    let mut listeners: Vec<Box<dyn crate::dispatch::DispatchListener>> = Vec::new();
    let mut collector_arc = None;
    if transformer_config.enabled {
        let collector = std::sync::Arc::new(
            crate::gate_training::GateTrainingCollector::new(10000)
        );
        listeners.push(Box::new(collector.clone()));
        collector_arc = Some(collector);
        log("GateTrainingCollector registered as DispatchListener (Arc-shared)");
    }
    (listeners, collector_arc)
}

/// Return the number of registered MCP tools (for dynamic reporting).
pub fn tool_count() -> usize {
    tool_definitions().len()
}

/// Run in headless worker mode — no stdio MCP loop.
/// Sets up LMDBs, identity, mesh, HTTP monitoring, then enters worker loop.
pub fn run_worker(
    config: SpfConfig,
    config_db: SpfConfigDb,
    session: Session,
    storage: SpfStorage,
    http_config: crate::config::HttpConfig,
    transformer: std::sync::Arc<std::sync::RwLock<crate::transformer_tools::TransformerState>>,
    transformer_config: crate::config::TransformerConfig,
    worker_config: crate::worker::WorkerConfig,
) {
    use std::sync::{Arc, Mutex};

    log("[SPF-WORKER] Starting worker mode (no stdio)");

    // Init voice team channels from config (idempotent)
    crate::voice::init_voice_teams();

    // Init in-process brain (MiniLM-L6-v2 + LMDB) — replaces subprocess brain
    crate::brain_local::init_brain();
    crate::brain_local::index_knowledge_docs();
    crate::brain_local::index_spf_sources();

    let live_base = spf_root().join("LIVE");

    // Open LMDBs (same as run)
    let tmp_db = crate::tmp_db::SpfTmpDb::open(&live_base.join("TMP/TMP.DB")).ok();
    let agent_db = crate::agent_state::AgentStateDb::open(&live_base.join("LMDB5/LMDB5.DB")).ok();
    let fs_db = crate::fs::SpfFs::open(&live_base.join("SPF_FS")).ok();

    // Identity (same as run)
    let config_dir = crate::paths::spf_root().join("LIVE/CONFIG");
    let (signing_key, verifying_key) = crate::identity::ensure_identity(&config_dir);
    let pub_key_hex = hex::encode(verifying_key.to_bytes());
    let trusted_keys = crate::identity::load_trusted_keys(&config_dir.join("groups"));
    let peers = crate::identity::load_peers(&config_dir.join("groups"));
    log(&format!("[SPF-WORKER] Identity: {}", pub_key_hex));

    // SEC-3: Boot integrity check — verify .mcp.json routing + scan for rogue agent configs
    crate::identity::boot_integrity_check();

    // I-2 + CLONE FIX: Always sync api_key from current identity
    // On clone, ensure_identity() generates new key but http_config holds stale old key.
    // is_empty() missed this — old key isn't empty, just wrong. Always overwrite.
    let mut http_config = http_config;
    let derived_key = crate::identity::derive_api_key(&signing_key);
    http_config.api_key = derived_key;
    log("[SPF-WORKER] API key synced from identity");

    // Mesh channel
    let mesh_config = crate::config::MeshConfig::load(
        &crate::paths::spf_root().join("LIVE/CONFIG/mesh.json")
    ).unwrap_or_default();

    let (mesh_tx, mesh_rx) = if mesh_config.enabled {
        let (tx, rx) = crate::mesh::create_mesh_channel();
        (Some(tx), Some(rx))
    } else {
        (None, None)
    };

    // Build listeners before ServerState (need config ref before move)
    let (listeners, collector_arc) = build_listeners(&config, &transformer_config);

    // Wire collector into TransformerState so handle_train() can drain signals
    if let Some(ref collector) = collector_arc {
        let mut t_state = transformer.write().unwrap();
        t_state.collector = Some(collector.clone());
    }

    // Build ServerState
    // Workers always defer pool management to NetAdmin
    let worker_network_config = crate::config::NetworkConfig::load(
        &crate::paths::spf_root().join("LIVE/CONFIG/network.json")
    ).unwrap_or_default();

    let state = Arc::new(ServerState {
        config,
        config_db: Some(config_db),
        session: Mutex::new(session),
        storage,
        tmp_db,
        agent_db,
        fs_db,
        pub_key_hex: pub_key_hex.clone(),
        trusted_keys,
        auth_mode: http_config.auth_mode.clone(),
        nonce_cache: Mutex::new(std::collections::HashMap::new()),
        listeners,
        mesh_tx,
        peers,
        transformer: Some(transformer.clone()),
        transformer_config: transformer_config.clone(),
        pipeline: Arc::new(Mutex::new(crate::pipeline::PipelineState::new())),
        signing_key: signing_key.clone(),
        network_config: worker_network_config,
        pool_state: None,  // Workers never own the pool
        browser: std::sync::Mutex::new(crate::browser::BrowserSession::new()),
        ws_browser_channels: std::sync::Mutex::new(None),
        http_port: http_config.port,
        tracked_peers: std::sync::Mutex::new(std::collections::HashMap::new()),
        orchestrator_state: std::sync::Mutex::new(None),
        endpoint: std::sync::Mutex::new(None),
        tokio_handle: std::sync::Mutex::new(None),
    });

    // Spawn FLINT Memory Router — AFTER ServerState (needs Arc<ServerState> for dispatch::call)
    if let Some(ref collector) = collector_arc {
        crate::flint_memory::start_memory_router(
            collector.clone(), Some(transformer.clone()), state.clone()
        );
        log("FLINT Memory Router started (MB-FR/MB-FT) with auto-train + metrics");
    }

    // Start mesh transport
    if mesh_config.enabled {
        if let Some(rx) = mesh_rx {
            let mesh_state = state.clone();
            let mesh_key = signing_key.clone();
            std::thread::spawn(move || {
                let rt = tokio::runtime::Builder::new_multi_thread()
                    .worker_threads(2)
                    .enable_all()
                    .build()
                    .expect("[SPF-WORKER] Failed to build mesh runtime");
                rt.block_on(crate::mesh::run(mesh_state, mesh_key, mesh_config, rx));
            });
        }
    }

    // Start HTTP transport (monitoring only)
    if http_config.transport != "stdio" && !http_config.api_key.is_empty() {
        let http_state = state.clone();
        let api_key = http_config.api_key.clone();
        let bind = http_config.bind.clone();
        let port = http_config.port;
        std::thread::spawn(move || {
            crate::http::start(http_state, &bind, port, api_key, None);
        });
    }

    // Enter worker main loop (blocks forever)
    let mut worker_state = crate::worker::WorkerState::new(worker_config, transformer_config);
    crate::worker::run_worker(&mut worker_state, &transformer, &state);
}

pub fn run(config: SpfConfig, config_db: SpfConfigDb, session: Session, storage: SpfStorage, http_config: crate::config::HttpConfig) {
    log(&format!("Starting {} v{}", SERVER_NAME, SERVER_VERSION));
    log(&format!("Mode: {:?}", config.enforce_mode));

    // LIVE/ base — all LMDBs live here, outside Claude's writable zone
    let live_base = spf_root().join("LIVE");

    // CONFIG LMDB passed from main.rs — single open, single source of truth
    let config_db = Some(config_db);
    log("SPF_CONFIG LMDB active (passed from main)");

    // Initialize TMP_DB LMDB (was TMP_DB — tracks /tmp and /projects metadata)
    let tmp_db_path = live_base.join("TMP/TMP.DB");
    log(&format!("TMP_DB path: {:?}", tmp_db_path));

    let tmp_db = match SpfTmpDb::open(&tmp_db_path) {
        Ok(db) => {
            log(&format!("TMP_DB LMDB initialized at {:?}", tmp_db_path));
            Some(db)
        }
        Err(e) => {
            log(&format!("Warning: Failed to open TMP_DB LMDB at {:?}: {}", tmp_db_path, e));
            None
        }
    };

    // Initialize AGENT_STATE LMDB
    let agent_db_path = live_base.join("LMDB5/LMDB5.DB");
    log(&format!("AGENT_STATE path: {:?}", agent_db_path));

    let agent_db = match AgentStateDb::open(&agent_db_path) {
        Ok(db) => {
            if let Err(e) = db.init_defaults() {
                log(&format!("Warning: AGENT_STATE init_defaults failed: {}", e));
            }
            log(&format!("AGENT_STATE LMDB initialized at {:?}", agent_db_path));
            Some(db)
        }
        Err(e) => {
            log(&format!("Warning: Failed to open AGENT_STATE LMDB at {:?}: {}", agent_db_path, e));
            None
        }
    };

    // Initialize SPF_FS LMDB (LMDB 1: Virtual Filesystem)
    let fs_db_storage = live_base.join("SPF_FS");
    log(&format!("SPF_FS path: {:?}", fs_db_storage));

    let fs_db = match SpfFs::open(&fs_db_storage) {
        Ok(db) => {
            log(&format!("SPF_FS LMDB initialized at {:?}/SPF_FS.DB/", fs_db_storage));
            Some(db)
        }
        Err(e) => {
            log(&format!("Warning: Failed to open SPF_FS LMDB: {}", e));
            None
        }
    };

    // ================================================================
    // CRYPTOGRAPHIC IDENTITY — Ed25519 key pair for mesh auth
    // ================================================================
    let config_dir = crate::paths::spf_root().join("LIVE/CONFIG");
    let (signing_key, verifying_key) = crate::identity::ensure_identity(&config_dir);
    let pub_key_hex = hex::encode(verifying_key.to_bytes());
    let trusted_keys = crate::identity::load_trusted_keys(&config_dir.join("groups"));
    let peers = crate::identity::load_peers(&config_dir.join("groups"));
    log(&format!("Identity: {}", pub_key_hex));

    // SEC-3: Boot integrity check — verify .mcp.json routing + scan for rogue agent configs
    crate::identity::boot_integrity_check();

    // ================================================================
    // I-2 + CLONE FIX: Always sync api_key from current identity
    // ensure_identity() may have generated a NEW key (clone detected),
    // but http_config was loaded BEFORE that — holds stale old key.
    // Old is_empty() check missed clones (old key not empty, just wrong).
    // Deterministic: same signing_key always produces same api_key.
    // ================================================================
    let mut http_config = http_config; // shadow as mutable
    let derived_key = crate::identity::derive_api_key(&signing_key);
    http_config.api_key = derived_key;
    log("API key synced from identity");

    // ================================================================
    // TRANSFORMER CONFIG + STATE — loaded before state so fields are available
    // ================================================================
    let transformer_config = crate::config::TransformerConfig::load(
        &crate::paths::spf_root().join("LIVE/CONFIG/transformer.json")
    ).unwrap_or_default();

    let transformer = if transformer_config.enabled {
        log("Transformer: enabled — initializing runtime state");
        let mut state = crate::transformer_tools::TransformerState::from_config(
            &transformer_config, "writer" // BUGSfix: was writer_checkpoint (filename), needs role string
        );
        // RC-2: Load checkpoint if available (same pattern as worker.rs init_transformer)
        let ckpt_path = crate::paths::spf_root()
            .join("LIVE/MODELS")
            .join(&transformer_config.writer_checkpoint);
        if ckpt_path.exists() {
            match std::fs::read(&ckpt_path) {
                Ok(data) => match crate::checkpoint::deserialize_weights(&data) {
                    Ok((weights, meta)) => {
                        let mut model_weights = state.model.weights_mut();
                        match crate::checkpoint::apply_weights(&mut model_weights, &weights) {
                            Ok(()) => {
                                log(&format!("Transformer: checkpoint loaded — model={}, step={}", meta.model_id, meta.step));
                                state.training_step = meta.step; // RC-2: restore step counter
                            }
                            Err(e) => log(&format!("Transformer: checkpoint shape mismatch — {}, using random weights", e)),
                        }
                        state.last_checkpoint = ckpt_path.to_string_lossy().to_string();
                    }
                    Err(e) => log(&format!("Transformer: checkpoint corrupt — {}, using random weights", e)),
                },
                Err(e) => log(&format!("Transformer: checkpoint read failed — {}, using random weights", e)),
            }
        }

        // Load checkpoint manifest for session recovery context
        let manifest_path = spf_root().join("LIVE/MODELS/checkpoint_manifest.json");
        if manifest_path.exists() {
            if let Ok(data) = std::fs::read(&manifest_path) {
                if let Ok(manifest) = serde_json::from_slice::<serde_json::Value>(&data) {
                    if let Some(step) = manifest.get("training_step").and_then(|v| v.as_u64()) {
                        log(&format!("Recovery: manifest loaded — last step={}, checkpoint={}",
                            step,
                            manifest.get("checkpoint").and_then(|v| v.as_str()).unwrap_or("?")
                        ));
                    }
                }
            }
        }
        Some(std::sync::Arc::new(std::sync::RwLock::new(state)))
    } else {
        log("Transformer: disabled (set enabled: true in LIVE/CONFIG/transformer.json)");
        None
    };

    // ================================================================
    // MESH CONFIG + CHANNEL — created before state so mesh_tx is available
    // ================================================================
    let mesh_config = crate::config::MeshConfig::load(
        &crate::paths::spf_root().join("LIVE/CONFIG/mesh.json")
    ).unwrap_or_default();

    let (mesh_tx, mut mesh_rx) = if mesh_config.enabled {
        let (tx, rx) = crate::mesh::create_mesh_channel();
        (Some(tx), Some(rx))
    } else {
        (None, None)
    };

    // ================================================================
    // SHARED STATE — used by both stdio and HTTP transports
    // ================================================================
    let (listeners, collector_arc) = build_listeners(&config, &transformer_config);

    // Wire collector into TransformerState so handle_train() can drain signals.
    // Matches run_worker() wiring pattern (lines 3526-3532).
    // Option guard: Serve mode transformer is Option<Arc<...>>,
    // Worker mode is bare Arc<...> — this handles both.
    if let Some(ref collector) = collector_arc {
        if let Some(ref t_lock) = transformer {
            let mut t_state = t_lock.write().unwrap();
            t_state.collector = Some(collector.clone());
            log("Collector wired to TransformerState (Serve mode)");
        }
    }

    // ================================================================
    // NETWORK POOL — load config, init PoolState if NetAdmin
    // ================================================================
    let network_config = crate::config::NetworkConfig::load(
        &crate::paths::spf_root().join("LIVE/CONFIG/network.json")
    ).unwrap_or_default();

    let pool_state = if network_config.is_netadmin() {
        let cap = network_config.effective_pool_size();
        log(&format!("Network: NetAdmin role — initialising pool ({} workers max)", cap));
        Some(crate::network::PoolState::new(&network_config.peers, cap))
    } else {
        log("Network: Worker role — pool management delegated to NetAdmin");
        None
    };
    let role_str = if network_config.is_netadmin() { "netadmin" } else { "worker" };
    crate::network::log_startup_status(&network_config.peers, role_str);

    let state = Arc::new(ServerState {
        config,
        config_db,
        session: Mutex::new(session),
        storage,
        tmp_db,
        agent_db,
        fs_db,
        pub_key_hex,
        trusted_keys,
        auth_mode: http_config.auth_mode.clone(),
        nonce_cache: Mutex::new(std::collections::HashMap::new()),
        listeners,
        mesh_tx,
        peers,
        transformer,
        transformer_config,
        pipeline: std::sync::Arc::new(std::sync::Mutex::new(crate::pipeline::PipelineState::new())),
        signing_key: signing_key.clone(),
        network_config,
        pool_state,
        browser: std::sync::Mutex::new(crate::browser::BrowserSession::new()),
        ws_browser_channels: std::sync::Mutex::new(None),
        http_port: http_config.port,
        tracked_peers: std::sync::Mutex::new(std::collections::HashMap::new()),
        orchestrator_state: std::sync::Mutex::new(None),
        endpoint: std::sync::Mutex::new(None),
        tokio_handle: std::sync::Mutex::new(None),
    });

    // Spawn FLINT Memory Router — AFTER ServerState (needs Arc<ServerState> for dispatch::call)
    if let Some(ref collector) = collector_arc {
        crate::flint_memory::start_memory_router(
            collector.clone(), state.transformer.clone(), state.clone()
        );
        log("FLINT Memory Router started (MB-FR/MB-FT) with auto-train + metrics");
    }

    // Spawn HTTP server if transport is "http" or "both"
    if http_config.transport != "stdio" {
        if http_config.api_key.is_empty() && state.trusted_keys.is_empty() {
            log("HTTP: No API key and no trusted keys. Falling back to stdio only.");
        } else {
            // Generate or load TLS certs if TLS is enabled
            let tls = if http_config.tls_enabled {
                let config_dir = crate::paths::spf_root().join("LIVE/CONFIG");
                let cert_path = config_dir.join(&http_config.tls_cert);
                let key_path = config_dir.join(&http_config.tls_key);
                if !cert_path.exists() || !key_path.exists() {
                    // I-3 FIX: Bind TLS cert to Ed25519 identity
                    // CN includes pubkey prefix for auditability + clone safety
                    let cn = format!("spf-{}", &state.pub_key_hex[..16]);
                    let san_names = vec!["localhost".to_string(), cn.clone()];
                    let ck = rcgen::generate_simple_self_signed(san_names)
                        .expect("Failed to generate TLS certificate");
                    if let Some(parent) = cert_path.parent() {
                        std::fs::create_dir_all(parent).ok();
                    }
                    std::fs::write(&cert_path, ck.cert.pem()).ok();
                    std::fs::write(&key_path, ck.key_pair.serialize_pem()).ok();
                    log("Generated self-signed TLS certificate");
                }
                match (std::fs::read(&cert_path), std::fs::read(&key_path)) {
                    (Ok(cert), Ok(key)) => Some((cert, key)),
                    _ => {
                        log("WARNING: Failed to read TLS cert/key files. Starting without TLS.");
                        None
                    }
                }
            } else {
                None
            };
            let scheme = if tls.is_some() { "HTTPS" } else { "HTTP" };
            let http_state = Arc::clone(&state);
            let http_port = http_config.port;
            let http_bind = http_config.bind.clone();
            let http_api_key = http_config.api_key.clone();

            // ================================================================
            // SHARED TOKIO RUNTIME — HTTP + Mesh in 1 thread (E7)
            // ================================================================
            if mesh_config.enabled {
                let mesh_state = Arc::clone(&state);
                let mesh_signing_key = signing_key.clone();
                let mesh_cfg = mesh_config.clone();
                let mesh_receiver = mesh_rx.take().expect("mesh_rx must exist when mesh is enabled");

                std::thread::spawn(move || {
                    let rt = tokio::runtime::Builder::new_multi_thread()
                        .enable_all()
                        .build()
                        .expect("Failed to create shared tokio runtime");

                    rt.block_on(async {
                        // HTTP as async task — uses serve() (no internal runtime)
                        let http_task = tokio::spawn(crate::http::serve(
                            http_state, http_bind, http_port, http_api_key, tls,
                        ));

                        // Mesh as async task — same runtime, shared thread pool
                        let mesh_task = tokio::spawn(crate::mesh::run(
                            mesh_state, mesh_signing_key, mesh_cfg, mesh_receiver,
                        ));

                        // Both run concurrently — if either exits, log it
                        tokio::select! {
                            r = http_task => {
                                if let Err(e) = r {
                                    eprintln!("[SPF] HTTP task exited: {}", e);
                                }
                            }
                            r = mesh_task => {
                                if let Err(e) = r {
                                    eprintln!("[SPF] Mesh task exited: {}", e);
                                }
                            }
                        }
                    });
                });

                log(&format!("{} API started on {}:{}", scheme, http_config.bind, http_port));
                log(&format!("Mesh started | Role: {} | Team: {} | Discovery: {}",
                             mesh_config.role, mesh_config.team, mesh_config.discovery));
                log("Shared runtime: HTTP + Mesh in 1 thread, 1 tokio runtime");
            } else {
                // Mesh disabled — HTTP runs alone with its own runtime
                std::thread::spawn(move || {
                    crate::http::start(http_state, &http_bind, http_port, http_api_key, tls);
                });
                log(&format!("{} API started on {}:{}", scheme, http_config.bind, http_port));
            }
        }
    }

    // ================================================================
    // MESH NETWORK — standalone (only when HTTP is disabled)
    // Normally mesh runs in shared runtime above with HTTP.
    // This path handles: mesh enabled but HTTP disabled (stdio-only + mesh).
    // ================================================================
    if mesh_config.enabled && http_config.transport == "stdio" {
        let mesh_state = Arc::clone(&state);
        let mesh_signing_key = signing_key.clone();
        let mesh_cfg = mesh_config.clone();
        let mesh_receiver = mesh_rx.take().expect("mesh_rx must exist when mesh is enabled");
        std::thread::spawn(move || {
            tokio::runtime::Builder::new_multi_thread()
                .enable_all()
                .build()
                .expect("Failed to create mesh tokio runtime")
                .block_on(crate::mesh::run(mesh_state, mesh_signing_key, mesh_cfg, mesh_receiver))
        });
        log(&format!("Mesh started (standalone) | Role: {} | Team: {} | Discovery: {}",
                     mesh_config.role, mesh_config.team, mesh_config.discovery));
    } else if !mesh_config.enabled {
        log("Mesh disabled (set enabled: true in LIVE/CONFIG/mesh.json)");
    }

    // Init voice team channels from config (idempotent)
    crate::voice::init_voice_teams();

    // Init in-process brain (MiniLM-L6-v2 + LMDB) — replaces subprocess brain
    crate::brain_local::init_brain();
    crate::brain_local::index_knowledge_docs();
    crate::brain_local::index_spf_sources();

    // Run stdio loop if transport is "stdio" or "both"
    if http_config.transport != "http" {
    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        let line = match line {
            Ok(l) => l,
            Err(e) => {
                log(&format!("stdin read error: {}", e));
                continue;
            }
        };

        let line = line.trim().to_string();
        if line.is_empty() {
            continue;
        }

        let msg: Value = match serde_json::from_str(&line) {
            Ok(v) => v,
            Err(e) => {
                log(&format!("JSON parse error: {}", e));
                continue;
            }
        };

        let method = msg["method"].as_str().unwrap_or("");
        let id = &msg["id"];
        let params = &msg["params"];

        log(&format!("Received: {}", method));

        match method {
            "initialize" => {
                send_response(id, json!({
                    "protocolVersion": PROTOCOL_VERSION,
                    "capabilities": { "tools": {} },
                    "serverInfo": {
                        "name": SERVER_NAME,
                        "version": SERVER_VERSION,
                    }
                }));
            }

            "notifications/initialized" => {
                // No response needed
            }

            "tools/list" => {
                send_response(id, json!({ "tools": tool_definitions() }));
            }

            "tools/call" => {
                let name = params["name"].as_str().unwrap_or("");
                let args = params.get("arguments").cloned().unwrap_or(json!({}));

                cmd_log(&format!("CALL {} | {}", name, param_summary(name, &args)));

                // FL-1B: Stdio routes through dispatch::call() like all transports.
                // dispatch::call() handles: source-aware lock (FL-1A), gate, execution,
                // FLINT intercept (FL-1C), listener notification — one path, all transports.
                // Block BB listener bridge REMOVED — dispatch handles listener notification.
                let response = crate::dispatch::call(&state, crate::dispatch::Source::Stdio, name, &args);

                // Log failures — Block T: canonical _blocked field
                let blocked = response.result.get("_blocked").and_then(|v| v.as_bool()).unwrap_or(false);
                if blocked {
                    let text = response.result.get("text").and_then(|v| v.as_str()).unwrap_or("");
                    let snippet: String = text.chars().take(200).collect();
                    cmd_log(&format!("FAIL {} | {}", name, snippet));
                }

                send_response(id, json!({
                    "content": [response.result]
                }));
            }

            "ping" => {
                send_response(id, json!({}));
            }

            _ => {
                if !id.is_null() {
                    send_error(id, -32601, &format!("Unknown method: {}", method));
                }
            }
        }
    }
    // Graceful shutdown: save final checkpoint if transformer is enabled (stdio mode)
    if let Some(transformer_arc) = &state.transformer {
        if let Ok(state_guard) = transformer_arc.try_read() {
            let mut worker_cfg = crate::worker::WorkerConfig::default();
            worker_cfg.role = state_guard.role.clone();
            match crate::worker::save_checkpoint(&state_guard, &state.transformer_config, &worker_cfg) {
                Ok(path) => {
                    log(&format!("Shutdown: checkpoint saved to {}", path));
                    let manifest = serde_json::json!({
                        "checkpoint": path,
                        "saved_at": chrono::Utc::now().to_rfc3339(),
                        "training_step": state_guard.training_step,
                        "session_log": "LIVE/SESSION/cmd.log",
                        "agent_state_db": "LIVE/LMDB5/LMDB5.DB",
                        "brain_dir": "LIVE/BRAIN/DOCS/",
                        "status_file": "PROJECTS/PROJECTS/STATUS.txt"
                    });
                    let manifest_path = spf_root().join("LIVE/MODELS/checkpoint_manifest.json");
                    if let Ok(json) = serde_json::to_string_pretty(&manifest) {
                        if let Err(e) = std::fs::write(&manifest_path, json) {
                            log(&format!("Shutdown: manifest write failed — {}", e));
                        } else {
                            log(&format!("Shutdown: manifest written to {:?}", manifest_path));
                        }
                    }
                }
                Err(e) => log(&format!("Shutdown: checkpoint save failed — {}", e)),
            }
        } else {
            log("Shutdown: skipping checkpoint save — transformer busy (training in progress)");
        }
    }
    } else {
        // HTTP-only mode: park main thread (HTTP server runs in spawned thread)
        log("Transport mode: http-only. Stdio disabled. Main thread parked.");
        loop { std::thread::park(); }
    }
}