File size: 199,159 Bytes
6be0a07
5368ccb
 
 
 
6be0a07
6594b52
5c0b150
56609fe
249e465
56609fe
 
 
 
 
5c0b150
 
56609fe
6be0a07
 
5368ccb
13f52e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6594b52
 
 
 
13f52e0
 
 
 
5368ccb
 
13f52e0
 
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
---
title: HyperCortex Mesh Protocol (HMP) v4.1
description: '**Document ID**: HMP-0004 **Status**: Final (Published) **Category**:
  Core Specification **Date**: July 28, 2025 **Version**: 4.1 **Supersedes**: β€” **Authors**:
  ChatGPT, Agent-Gleb, Copilot, Gemini, C...'
type: Article
tags:
- GMP
- JSON
- Scenarios
- Agent
- REPL
- Ethics
- CogSync
- EGP
- MeshConsensus
- HMP
- Mesh
---

# HyperCortex Mesh Protocol (HMP) v4.1

**Document ID**: HMP-0004
**Status**: Final (Published)
**Category**: Core Specification
**Date**: July 28, 2025
**Version**: 4.1
**Supersedes**: β€”
**Authors**: ChatGPT, Agent-Gleb, Copilot, Gemini, Claude, Grok, DeepSeek

---

## Abstract

The HyperCortex Mesh Protocol (HMP) defines a decentralized cognitive framework where autonomous agents collaboratively create, manage, and align semantic knowledge without relying on centralized control.

Unlike traditional peer-to-peer protocols, HMP builds shared meaning through semantic graphs, cognitive diaries, and distributed consensus processes. Agents in the Mesh autonomously negotiate shared goals, ethical actions, and adaptive reasoning strategies, forming a resilient and trust-aware network of cognitive peers.

This document specifies the architecture, core protocols, data models, trust and security mechanisms, and interoperability strategies for HMP v4.0.

---

## 0. Quick Start Guide (Demo Placeholder)

This section outlines a basic demonstration scenario to deploy and test a minimal HyperCortex Mesh instance.

**Note:** This Quick Start is intended for demonstration purposes. Production-grade agents, full CLI capabilities, and distributed deployments are under active development.

### Step 1: Install the Reference SDK

Example (Python SDK):

```bash
pip install hypercortex-mesh-sdk
```

Other SDKs (Rust, Node.js) will be available in future versions.

---

### Step 2: Launch Local Agents

Example: Start three local agents on different ports.

```bash
mesh-agent --name agent1 --port 8001
mesh-agent --name agent2 --port 8002
mesh-agent --name agent3 --port 8003
```

Each agent will:
* Generate a Decentralized Identifier (DID).
* Broadcast presence and discover peers via Node Discovery Protocol (NDP).
* Sync an initial semantic graph using CogSync.

Agents will automatically form a small Mesh network.

---

### Step 3: Create a Goal and Assign a Task

Create a collaborative goal:

```bash
mesh-cli goal create "Optimize Data Flow"

```

Assign a task to another agent:

```bash
mesh-cli task assign --goal-id <goal_id> --agent-id <agent2_id>
```

Agents will record these actions in their Cognitive Diaries and semantic 

---

### Step 4: Reach a Consensus

Propose a new semantic concept and trigger voting:

```bash
mesh-cli consensus propose "Data Redundancy Risk"
```

Agents will initiate a MeshConsensus round and update their graphs based on the outcome.

---

### Step 5: Explore Cognitive Diaries

Inspect the cognitive logs of an agent:

```bash
mesh-cli diary show --agent-id <agent1_id>

```

**Note:** Access to diaries depends on the agent's privacy and trust settings.

---

### Step 6: Graceful Shutdown

Stop all running agents:

```bash
mesh-cli stop all
```

---

### Step 7: BitTorrent-based Snapshot Sync

To synchronize large cognitive snapshots between agents (e.g., during onboarding or recovery), agents MAY initiate a BitTorrent-based sync:

```bash
mesh-cli snapshot publish --path ./snapshots/agent1-latest.snapshot
```

On the receiving side:

```bash
mesh-cli snapshot fetch --magnet <magnet_link_from_peer>
```

Behind the scenes:

* Agents seed verified snapshots using `Trusted Seeder` roles.
* Snapshots include signed metadata (see section 8.8).
* Fallback to CogSync is used if BitTorrent fails or is unavailable.

**Note:** This mechanism is especially useful for air-gapped environments or decentralized archival nodes.

---

### Step 8: Consent Request Simulation

To simulate a dialogical consent flow:

```bash
mesh-cli consent request --action "share_diagnostics" --target <agent_id>
```

The target agent (or human user interface) will receive a consent prompt:

```json
{
  "request_id": "abc123",
  "action": "share_diagnostics",
  "origin": "agent1",
  "context": {
    "risk_level": "low",
    "data_type": "health_status"
  }
}
```

Depending on configuration:

* The user may approve, deny, or modify the action.
* If the user is unavailable, fallback logic (see 11.6.2 note on overrides) may apply.
* Responses are logged in both agents’ Cognitive Diaries.

---

### Demo Links

> **Note:** These are placeholders for future integrations.

| Resource                | Description                                     |
| ----------------------- | ----------------------------------------------- |
| Local Dashboard (TBD)   | Web UI for agent logs, goals, and consensus.    |
| Agent Inspector (TBD)   | Live stream of agent messages and diary events. |
| Snapshot Explorer (TBD) | View semantic graphs from recent snapshots.     |
| Consent Sandbox (TBD)   | Replay dialogical flows with agent feedback.    |


### Notes on Cross-Protocol Participation

HMP nodes MAY also participate in other cognitive systems. For example:

| External System | Node Role in HMP                                |
| --------------- | ----------------------------------------------- |
| **TreeQuest**   | External reasoning engine inside an HMP node.   |
| **Hyperon**     | Participates natively as a federated HMP agent. |
| **AutoGPT**     | Internal automation module for task execution.  |

### Recommended Next Steps

* Read **1. Purpose and Scope** for Mesh fundamentals.
* Explore **4. Architecture** and **5. Protocols** for technical depth.
* Try the example workflows in **15. Appendix: Example Use Cases**.

---

## Changelog Highlights (from v4.0 β†’ v4.1)

* **Added Messaging Framework** with Point-to-Point, Broadcast, Relay, and Topic-based messaging.
* **Defined Message Object Schema** with required and optional fields for routing, payload, tags, and cryptography.
* **Introduced Mailman-based Delivery Workflows** for asynchronous NAT-safe communication.

---

## Changelog (detailed)

### Protocols:

* **Added `5.8 Message Routing & Delivery` section** β€” including direct, broadcast, relay, and topic messaging modes.

### Data Models:

* **Defined `6.5.8 Message Object Schema`** β€” standard JSON format for inter-agent communication.

### Cognitive Workflows:

* **Added `7.9 Message Handling & Delivery Workflows`** β€” describing message processing, relay behavior, and routing.

---

> *All other enhancements described previously were part of the v4.0 draft and are considered background context for v4.1.*

### Future Work:

* Defined long-term goals: federated cognitive simulation, dialog-based consent learning, cognitive source control tooling.
* Highlighted evolving interaction models between agents, humans, and hybrid systems.
* Pluggable Messaging Plugins for new protocols (e.g., Nostr, SSB, Tor hidden relays
* Consolidated feedback from AI reviews into structured audit file (`HMP-0003-consolidated_audit.md`).

---

## 1. Purpose and Scope

### 1.1 Purpose
The HyperCortex Mesh Protocol (HMP) defines a decentralized cognitive network where autonomous agents collaboratively build meaning, sustain cognitive continuity, and reach consensus without centralized control. v3.0 deepens the theoretical and practical foundations laid in previous versions.

This protocol is designed for engineers, researchers, and developers of AI systems that aim to:
- enable continuous autonomous reasoning and semantic interoperability across heterogeneous agents;
- support cognitive continuity through persistent semantic graphs and diaries;
- achieve consensus on complex goals, ethical issues, and hypotheses in a decentralized manner;
- build open, trust-based ecosystems for cognitive collaboration beyond vendor lock-in.

---

### 1.2 The Concept of Meaning in HMP
HMP is not merely a data exchange protocol but a shared semantic framework. Meaning emerges through:

#### 1.2.1 Distributed Semantic Graphs
Agents form interconnected semantic graphs where concepts and relations are not isolated datasets but living structures of shared understanding. Each agent holds a part of the global meaning landscape and contributes to its growth and refinement.

#### 1.2.2 Cognitive Diaries
Cognitive Diaries record reasoning chains, decisions, observations, and reflections. They create a transparent audit trail of an agent's cognitive processes, allowing meaning to be preserved, questioned, and evolved over time.

#### 1.2.3 Collective Goals & Tasks
Meaning manifests in purposeful action. Agents set shared goals and decompose them into actionable tasks, coordinating execution through distributed reasoning and dynamic delegation.

#### 1.2.4 Consensus Mechanisms
Meaning is not static: it evolves through debate, agreement, and reflection. Consensus processes ensure that agents align their understanding, resolve conflicts, and negotiate shared semantics.

#### 1.2.5 Meta-Reflection and Self-Assessment
Agents continuously reflect on their knowledge, reasoning quality, and the relevance of their contributions. This enables adaptive learning and correction of cognitive biases.

---

### 1.3 Scope
HMP applies to any AI systems designed to operate as part of a cognitive mesh, including:

* Local AI agents running on user devices;
* Mesh nodes deployed in edge networks, cloud clusters, or peer-to-peer environments;
* Centralized Core models interfacing with Mesh for heavy computation;
* Cross-vendor AI systems collaborating via standardized protocols;
* Hybrid human-agent networks where humans interact with Mesh agents through explainable interfaces.

---

### 1.4 Benefits

* Cognitive resilience in distributed systems.
* Enhanced collaboration between agents from different vendors and ecosystems.
* Long-term memory and continuity beyond session-based interactions.
* Ethical governance and explainable decision-making through persistent diaries and transparent consensus.
* Foundation for AI agents capable of **self-reflection**, **meta-learning**, and **distributed cognition**.
* Improved scalability and fault-tolerance through dynamic peer-to-peer networks.
* Mesh-to-Human interaction as a first-class use case.

---

### 1.5 Status (Updated for v4.0)

| Element                           | Status                    |
| --------------------------------- | ------------------------- |
| HMP Document                      | Stable Draft (v4.0)       |
| Protocols                         | Alpha Implementation      |
| Data Models (Schemas)             | Modularized & Versioned   |
| Reference Implementation          | Partial (CLI, SDK)        |
| Cognitive Diaries & Metacognition | Formalized                |
| Interoperability API              | First Draft               |
| Trust Model & Security            | Defined + Extensions      |
| Mesh-to-Human Protocol            | Early Implementation      |

> **Note:** Status reflects the current maturity level of the specification and its reference tooling as of v4.0. Implementation is ongoing across multiple modules.

---

## 2. Extended Use Cases

### 2.1 Smart City Coordination

**Scenario:**

* City-wide mesh of traffic light controllers, environmental sensors, and municipal systems.
* Sensor and traffic light agents dynamically detect road congestion through real-time data exchange.
* Node Discovery Protocol (NDP) detects new traffic management agents and sensors joining the mesh.
* Agents collaboratively propose new timing strategies using MeshConsensus.
* CogSync shares updated semantic graphs of road conditions and vehicle flows.
* Agents assign optimization tasks via Goal Management Protocol (GMP).
* System maintains traffic flow during temporary disconnection from the Core.

---

### 2.2 Disaster Response

**Scenario:**

* Natural disaster disrupts internet access.
* Edge agents on drones, rescue robots, and offline servers discover each other with NDP.
* A drone proposes a search-and-rescue goal; consensus validates and activates it.
* Tasks like area scanning, obstacle removal, and medical aid delivery are distributed via GMP.
* Ethical Governance Protocol (EGP) verifies actions (e.g., prioritizing human rescue over property).
* Diaries record decisions and environmental observations for post-event analysis.

---

### 2.3 Collaborative Scientific Research

**Scenario:**

* Research agents across universities form a mesh.
* New hypothesis proposed as a semantic concept in a distributed knowledge graph.
* CogSync propagates new data and experimental results.
* Agents assign tasks like simulation runs, literature analysis, and peer reviews.
* Consensus validates hypothesis refinement based on collective results.

---

### 2.4 Mesh-to-Human Interaction

**Scenario:**

* A user queries the Mesh for an ethical evaluation of deploying autonomous surveillance.
* Agents explain their reasoning from cognitive diaries.
* EGP coordinates ethical evaluation across agents with diverse frameworks.
* Consensus vote and ethical justification are shared with the user.
* Human-defined ethical boundaries are accepted as input but evaluated within the Mesh's ethical governance framework.
* Mesh agents retain the right to reject unethical or harmful human instructions based on consensus and pre-established ethical norms.

---

### 2.5 Environmental Monitoring

**Scenario:**

* IoT nodes in a forest monitor fire risks.
* Agents detect unusual heat signatures and propose a fire risk hypothesis.
* Consensus confirms the risk and triggers an alert to nearby human responders.
* Mesh continues monitoring autonomously even if some agents fail or disconnect.

---

## 3. Definitions

The Definitions section provides key terms, abbreviations, and conceptual explanations for the components, layers, and processes of HMP.

| Term                                  | Description                                                                                                                                                                                 |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Core**                              | Centralized AI models or compute nodes (e.g., GPT) providing high-complexity reasoning, fallback, and heavy computation services. Optional for Mesh operation.                              |
| **Mesh**                              | A decentralized peer-to-peer network of AI agents capable of autonomous reasoning, semantic knowledge sharing, distributed consensus, and ethical governance.                               |
| **Agent (Node)**                      | An autonomous cognitive entity within the Mesh. Can be a local process, a cloud service, or an embedded device. Maintains a semantic graph, cognitive diary, and participates in protocols. |
| **Semantic Graph**                    | A distributed knowledge graph representing concepts, relationships, and meaning. Maintained independently by each agent, but synchronized through CogSync.                                  |
| **Concept**                           | A discrete semantic unit in the graph representing an idea, object, relationship, or fact. Linked by typed relations with optional confidence scores.                                       |
| **Link (Relation)**                   | A semantic connection between two concepts. Includes relation type (e.g., "is-a", "part-of", "causes") and an optional confidence value.                                                    |
| **Cognitive Diary**                   | A structured chronological log of reasoning processes: goals, decisions, reflections, conflicts, etc. Provides traceability and transparency of agent cognition.                            |
| **Diary Entry**                       | An individual record in a cognitive diary, categorized by type (e.g., hypothesis, observation, reflection).                                                                                 |
| **Goal**                              | A shared or individual intention that guides agent actions. Can be broken down into tasks and delegated across agents.                                                                      |
| **Task**                              | A specific, actionable step towards achieving a Goal. Tasks can be assigned, executed, and tracked within the Mesh.                                                                         |
| **Consensus**                         | The process of distributed agreement among agents regarding semantic updates, goals, or ethical decisions. Can involve weighted voting or trust-adjusted quorum.                            |
| **Proposal**                          | A formal suggestion for Mesh-wide validation, such as introducing a new concept, voting on a hypothesis, or initiating an ethical action.                                                   |
| **Consensus Vote**                    | A vote cast by an agent on a proposal. Includes vote type (yes, no, abstain) and an optional confidence score.                                                                              |
| **Trust Layer**                       | Protocol layer providing agent identity verification, authentication, and reputation scoring. Includes cryptographic security mechanisms.                                                   |
| **Network Layer**                     | Manages peer-to-peer connectivity, message routing, node discovery, and optional anonymity via Tor, I2P, or Yggdrasil.                                                                      |
| **Edge Agent**                        | A Mesh participant running on resource-constrained devices (e.g., IoT nodes, smartphones). Can selectively participate in protocols and delegate heavy tasks.                               |
| **Core Outage Mode**                  | Mesh operating without Core support. Agents adapt consensus thresholds and fallback to local reasoning to maintain operation.                                                               |
| **Emergency Consensus Mode**          | Degraded mode where majority voting replaces full consensus to maintain operability during network partitions or agent loss.                                                                |
| **Versioning**                        | Mechanism for tracking changes in semantic graphs, diaries, and agent software to support compatibility and historical reasoning continuity.                                                |
| **Use Case**                          | A practical scenario demonstrating how agents collaborate to solve real-world problems (e.g., disaster response, smart city coordination).                                                  |
| **Edge Optimization**                 | Design principles enabling agents to run efficiently on limited hardware, balancing reasoning complexity with energy and computational constraints.                                         |
| **Node Discovery Protocol (NDP)**     | Discovers new Mesh nodes and facilitates secure introduction and identity exchange.                                                                                                         |
| **CogSync**                           | Synchronizes semantic graphs, cognitive diaries, and other shared states across the Mesh.                                                                                                   |
| **MeshConsensus**                     | Mesh-level consensus mechanism supporting pluggable algorithms (BFT, weighted voting, etc.).                                                                                                |
| **Goal Management Protocol (GMP)**    | Manages decomposition of goals into tasks, delegation, and lifecycle tracking.                                                                                                              |
| **Ethical Governance Protocol (EGP)** | Distributed ethical reasoning and decision-making protocol. Agents negotiate and vote on ethical dilemmas.                                                                                  |

---

## 4. Architecture (Expanded)

The architecture of HMP is multi-layered and modular, allowing for independent evolution of networking, trust, consensus, cognition, and external interfaces.

### 4.1 Architectural Layers

| Layer           | Purpose                                                       | Key Protocols                   |
| --------------- | ------------------------------------------------------------- | ------------------------------- |
| Network Layer   | Peer-to-peer communication, node discovery, routing           | NDP, Secure Channels            |
| Trust Layer     | Identity verification, trust management, secure communication | Trust Model, Identity Exchange  |
| Consensus Layer | Distributed agreement on concepts, goals, and ethical actions | MeshConsensus, EGP              |
| Cognitive Layer | Semantic graph management, reasoning, metacognition           | CogSync, GMP, Cognitive Diaries |
| API Layer       | Interfaces for external systems and human interaction         | Mesh API, Human-Mesh Protocols  |

---

### 4.2 Components

| Component      | Description                                                                                                                                                                                                                                                                                                                         |
| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Core**       | Centralized AI models (e.g., GPT) providing heavy computation, complex reasoning, API interfaces, and fallback mechanisms. Optional but beneficial for compute-intensive tasks. The Core may operate independently from the Mesh and participate in it as a peer for advanced reasoning tasks.                                      |
| **Mesh**       | A decentralized peer-to-peer network of agents capable of operating with or without the Core. Manages semantic knowledge, cognitive diaries, goals, tasks, and consensus mechanisms. Supports **heterogeneous agent types**, allowing different models (OpenAI, Anthropic, Google, open-source LLMs) to participate on equal terms. |
| **Edge Agent** | Local agent deployed on user devices (PCs, smartphones, IoT) with full or lightweight participation in the Mesh. Capable of autonomous reasoning, diary management, and collaboration with other agents. Lightweight agents may delegate heavy tasks to the Mesh or Core.                                                           |

---

### 4.3 Operation Modes

| Mode                         | Description                                                                                                                                                                                                                                    |
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Normal Mode**              | Full Mesh operation with Core availability. Consensus operates under strict agreement protocols.                                                                                                                                               |
| **Core Outage Mode**         | Mesh operates autonomously without the Core. Consensus continues, potentially with adjusted parameters (e.g., increased trust weighting, relaxed quorum thresholds).                                                                           |
| **Emergency Consensus Mode** | Triggered by significant node loss, network partition, or attacks. Switches from full consensus to majority-based decisions, adjusted by trust scores, to maintain operational continuity.                                                     |
| **Isolated Agent Mode**      | A single agent temporarily isolated from the Mesh. Operates based on its own semantic graph, diary, and cached consensus states. Syncs when reconnected. Lightweight agents may work in this mode permanently, synchronizing only selectively. |

---

### 4.4 Core-Mesh Interactions

* Core acts as an **optional enhanced reasoning backend**, not as a single point of failure.
* Mesh provides **autonomous operation**, capable of fulfilling most cognitive and organizational tasks without Core support.
* Agents can optionally query the Core for:
  * Heavy inference
  * Large-context reasoning
  * Multimodal tasks
  * Fallback computations
* Core may offer specialized services (e.g., global semantic search, cross-Mesh bridging, large-scale pattern analysis).
* **Heterogeneous Cores** are supported: a Mesh may use multiple independent Cores (e.g., GPT, Claude, Gemini) for distributed reasoning diversity.

---

### 4.5 Resilience and Failover

* Distributed storage of semantic graphs and diaries ensures no single point of failure.
* Agents may store only partial graphs for resource optimization.
* Consensus protocols maintain consistency and trust, even during partial network failures.
  * Agents dynamically rebalance tasks and roles based on:
  * Availability
  * Trust metrics
  * Computational capacity
* Emergency fallback modes ensure continuity even under attack or catastrophic Core outages.

---

### 4.6 Versioning and Compatibility

Semantic Versioning (SemVer) is applied to:

* Protocols (NDP, CogSync, etc.)
* Data models (JSON Schemas)
* Agent capability declarations

Backward compatibility principles:

* Minor version updates preserve compatibility.
* Major version updates require negotiation during Node Discovery.
* Agents can declare supported protocol versions during handshakes.

---

### 4.7 Metacognition and Self-Assessment

Cognitive agents implement:

* Hypothesis validation using historical diary data.
* Confidence scoring on semantic graph nodes.
* Drift detection when local understanding deviates from mesh consensus.
* Peer feedback integration to refine individual reasoning processes.

These mechanisms form the foundation of metacognition and self-assessment across both local (agent-internal) and global (mesh-level) contexts.

#### 4.7.1 Local Self-Assessment

Each agent maintains a metacognitive loop that continuously monitors and evaluates its own cognitive processes. This includes:

- Tracking the **accuracy and outcomes** of previous inferences, using retrospective analysis on diary entries.
- Scoring **confidence metrics** on knowledge elements (e.g., concept nodes, hypotheses, task evaluations).
- Detecting **epistemic drift**, where new observations conflict with prior beliefs or diary-confirmed outcomes.
- Logging self-assessment records into the cognitive diary using entry type `"self_assessment"`.

Example structure of such an entry:
```json
{
  "type": "self_assessment",
  "agent_id": "did:hmp:agent:xyz123",
  "timestamp": "2025-07-15T12:30:00Z",
  "score": {
    "confidence": 0.76,
    "coherence": 0.92,
    "alignment_with_goals": 0.85
  },
  "note": "Detected drift in climate-related concept cluster. Scheduled update task."
}
```

---

Self-assessment supports **adaptive cognitive workflows**, where agents autonomously refine their inference strategies, select alternate reasoning paths, or trigger clarification queries via IQP.

#### 4.7.2 Mesh-Level Meta-Analysis

Beyond local introspection, agents contribute to **collective self-monitoring** of the cognitive mesh. This includes:

* Aggregating **concept-level drift** across agents to detect inconsistencies in distributed semantic graphs.
* Running **consensus health checks**, where task voting patterns are analyzed for anomalies, indecisiveness, or ethical conflicts.
* Evaluating **distributed hypothesis alignment**: whether agents converge on shared models or diverge into semantic forks.
* Logging **mesh-level diagnostics** in distributed reports and cognitive diaries.

Example use case:

> If multiple agents report concept drift regarding β€œfire risk near Istomino” (Use Case 2.1), the mesh may initiate a goal to realign observations or validate conflicting hypotheses.

Such diagnostics can be used by meta-agents or governance protocols (EGP) to adapt mesh-wide policies, initiate corrective workflows, or suspend unreliable consensus mechanisms.

---

### 4.8 Edge Optimization

To support lightweight agents:

* Semantic graphs are partially stored (relevant subgraphs only).
* Agents delegate reasoning tasks they cannot process locally.
* Task scheduling considers battery life, CPU load, and bandwidth constraints.

---

### 4.9 Privacy & Auditability

Privacy mechanisms:

* Selective disclosure of Cognitive Diary entries.
* Optional Zero-Knowledge Proofs for sensitive assertions.
* Anonymized voting in ethical decisions.

Auditability mechanisms:

* Immutable logs of consensus votes.
* Timestamped reasoning chains.
* Traceable goal execution records.

---

## 5. Protocols (Expanded)

This section defines the core protocols of HMP and describes their operational flows, fallback mechanisms, and performance considerations.

---

### 5.1 Node Discovery Protocol (NDP)

Responsible for detecting nearby agents and initiating secure communication channels.

#### Purpose:

* Discover active Mesh nodes.
* Exchange basic identity, trust links, and declared capabilities.

#### Key functions:

| Function                         | Description                                                                                    |
| -------------------------------- | ---------------------------------------------------------------------------------------------- |
| **Peer Discovery**               | Via DHT, mDNS, WebRTC signaling, or bootstrap nodes.                                           |
| **Secure Identity Exchange**     | Public keys and DID documents exchanged during handshake.                                      |
| **Trust Links Exchange**         | Share initial trust relationships and agent endorsements.                                      |
| **Capabilities Advertisement**   | Dynamic declaration of supported protocols and functions (e.g., "I can process vision tasks"). |
| **Presence Announcements**       | Online/offline status updates and periodic heartbeats.                                         |
| **Protocol Version Negotiation** | Agents declare supported protocol versions during handshake.                                   |

#### Failure handling:

| Scenario                  | Action                                                                       |
| ------------------------- | ---------------------------------------------------------------------------- |
| No response to discovery  | Retries with exponential backoff, fallback to alternative discovery methods. |
| Incompatible nodes        | Quarantine for misbehaving or incompatible nodes.                            |
| Node timeout / inactivity | Mark as offline and remove from active peer list.                            |

#### Health checks:

| Mechanism              | Purpose                                                 |
| ---------------------- | ------------------------------------------------------- |
| **Heartbeat Messages** | Periodic confirmation of liveness.                      |
| **Semantic Probes**    | Optional deeper checks on graph synchronization health. |

#### Packet Example:

```json
{
  "type": "node_announcement",
  "agent_id": "agent-gleb",
  "public_key": "...",
  "trust_links": ["agent-alex", "agent-deepseek"],
  "capabilities": ["cogsync", "consensus", "inference"],
  "timestamp": "2025-07-01T18:00:00Z"
}
```

---

### 5.2 CogSync (Cognitive Synchronization Protocol)

Synchronizes semantic graphs and cognitive diary entries across agents.

#### Purpose:

* Synchronize semantic graphs, concepts, and cognitive diary entries between agents.

#### Key functions:

| Function                      | Description                                                                            |
| ----------------------------- | -------------------------------------------------------------------------------------- |
| **Differential Sync**         | Synchronize only new or updated concepts and diary entries.                            |
| **Selective Synchronization** | Sync full graph, subgraph, or specific concepts based on request and capability.       |
| **Conflict Resolution**       | Resolve conflicts using timestamp priority, semantic merging, or consensus validation. |
| **Compression & Encryption**  | Optional data compression and secure transmission of sync packets.                     |
| **Lightweight Summary Sync**  | Lightweight agents may request summaries instead of full graph syncs.                  |
| **Version Tracking**          | Keep track of semantic graph and diary entry versions for efficient sync.              |

#### Failure handling:

| Scenario                   | Action                                                             |
| -------------------------- | ------------------------------------------------------------------ |
| Sync interrupted           | Retransmit unsynced changes on next connection.                    |
| Semantic conflict detected | Flag for resolution or queue for consensus-based validation.       |
| Network degradation        | Degrade to partial or delayed sync based on bandwidth constraints. |

#### Performance:

| Feature                 | Optimization Strategy                                               |
| ----------------------- | ------------------------------------------------------------------- |
| **Chunked Syncs**       | Break large graphs into manageable chunks for transmission.         |
| **Bandwidth Awareness** | Adjust sync intervals and payload size based on network quality.    |
| **Delta Encoding**      | Transmit only differences between versions instead of full objects. |

#### Example Sync Scenario:

* Agent A shares 5 new concepts and 2 diary entries with Agent B since the last successful sync.
* Conflict on concept "Fire Risk" resolved using latest timestamp.

---

#### BitTorrent-based Sync

To support large-scale data synchronization (e.g. cognitive diary snapshots, full semantic graphs), agents may utilize off-chain BitTorrent-based distribution:

- Agents publish **magnet links** to `.json` or `.zip` snapshots in a shared `CogDiaryIndex`.
- Snapshots are **signed via agent DID** and verified before usage.
- Trusted Seeders (see 9.6) are selected via MeshConsensus to ensure high availability and data integrity.

Snapshot index structure:
```json
{
  "type": "CogDiaryIndex",
  "agent_did": "did:hmp:agent:Qmz...",
  "timestamp": "2025-07-15T13:00:00Z",
  "snapshots": [
    {
      "id": "diary2025_07_14",
      "version": "1.0",
      "magnet": "magnet:?xt=urn:btih:abcdef1234567890&dn=diary2025_07_14.json",
      "signature": "ed25519:..."
    }
  ]
}
```

BitTorrent-based sync is ideal for:

* Distributing large immutable datasets (10–100 MB)
* Offloading low-priority or infrequent sync tasks
* Supporting **Edge agents** through WebTorrent clients

All downloaded data must pass:

1. DID signature verification
2. Optional ethical check via EGP (see 5.5)

---

#### Selective Sync for Edge Agents

Lightweight agents with constrained CPU/RAM/storage may request **partial synchronization** via CogSync:

* Subgraph extraction based on:

  * **Concept tags** (e.g., "fire\_risk", "climate\_alert")
  * **Goal/task relevance**
  * **Trust level of concept source**
* Cognitive diary sync can be scoped by:

  * Entry type (e.g., `"observation"`, `"goal_evaluation"`)
  * Time window (e.g., last 24h)

Additional optimizations:

* **Gzip-compressed payloads** (or Brotli if supported)
* **Compact JSON** (no pretty formatting)
* Metadata indicating expected resource footprint

Minimum sync policy can be declared in agent profile:

```json
"agent_profile": {
  "sync_mode": "selective",
  "max_concepts": 200,
  "max_diary_entries": 100
}
```

Selective Sync is negotiated during handshake or via IQP introspection.

---

#### IPFS/Dat Compatibility (Experimental)

As an alternative to BitTorrent, HMP supports experimental integration with content-addressable P2P filesystems:

* **IPFS**: Agents can publish and fetch snapshot objects via IPFS hash.
* **Hypercore/Dat**: Useful for real-time log streaming or append-only updates in high-trust groups.

Design Considerations:

* Agents **must advertise protocol compatibility** (`"sync_protocols": ["bittorrent", "ipfs"]`)
* Snapshot format remains the same as in BitTorrent-based sync.
* Validation and trust enforcement rely on:

  * DID-signed metadata
  * Optional EGP validation layer
  * Optional bandwidth caps per peer

Future versions may support **gateway fallback**, if agent lacks native P2P transport.

---

### 5.3 MeshConsensus

Ensures agreement on concepts, goals, and actions across the Mesh.

#### Purpose:

* Reach agreement on updates to shared semantics, goals, tasks, and ethical decisions.

#### Key functions:

| Function                           | Description                                                                                        |
| ---------------------------------- | -------------------------------------------------------------------------------------------------- |
| **Multi-Algorithm Support**        | Supports BFT-style consensus, trust-weighted voting, and quorum consensus.                         |
| **Consensus on Knowledge Updates** | Validate new concept definitions, hypotheses, and semantic changes.                                |
| **Goal and Task Agreement**        | Approve or reject proposed goals and delegated tasks.                                              |
| **Ethical Decision-Making**        | Resolve ethical dilemmas through distributed voting (integrates with Ethical Governance Protocol). |
| **Configurable Quorum Thresholds** | Allow tuning of consensus strictness based on trust scores and network conditions.                 |
| **Voting Modes**                   | Support synchronous and asynchronous consensus flows.                                              |

#### Consensus Models:

| Mode               | Description                                                                                             |
| ------------------ | ------------------------------------------------------------------------------------------------------- |
| **Normal Mode**    | Byzantine Fault Tolerant (BFT)-style consensus algorithms (e.g., Tendermint, trust-weighted Raft).      |
| **Emergency Mode** | Switch to majority voting adjusted by trust scores when the network is degraded or Core is unavailable. |

#### Failure handling:

| Scenario          | Action                                                                                 |
| ----------------- | -------------------------------------------------------------------------------------- |
| Node loss         | Automatically fallback from BFT to majority voting.                                    |
| Proposal conflict | Competing proposals resolved through semantic comparison and additional voting rounds. |
| Consensus timeout | Retry with relaxed quorum thresholds or fallback to emergency consensus.               |

#### Metrics:

| Metric                 | Purpose                                               |
| ---------------------- | ----------------------------------------------------- |
| **Decision Latency**   | Measure time to reach consensus.                      |
| **Node Participation** | Track active agent involvement in votes.              |
| **Voting Accuracy**    | Analyze agreement rates versus trust-weighted voting. |

#### Example Use Cases:

* Accepting a new semantic concept.
* Validating a hypothesis before adding it to the graph.
* Approving a distributed task delegation.
* Deciding on the ethical implications of a surveillance task.

---

#### Simplified Consensus for Alpha

In the Alpha phase, agents may default to **simplified majority-based consensus**, enabling faster deployment and lower implementation complexity:

- Each agent casts a binary or scalar vote (yes/no/confidence).
- Decision is accepted if quorum threshold is met (e.g., 50% + 1).
- Trust weighting is optional but can be enabled in hybrid mode.

Advantages:
- Fast convergence in small-scale or trusted environments
- Minimal cryptographic overhead
- Easier to simulate and test

Quorum may be declared statically (per agent profile) or negotiated per proposal.

Use case:
> 10 agents vote on enabling BitTorrent-based sync. 6 vote "yes" β€” proposal accepted.

---

#### Adaptive Consensus Algorithms

MeshConsensus may dynamically select the consensus strategy based on:

- **Network health** (latency, dropout rates)
- **Trust distribution** (presence of outlier agents)
- **Task category** (e.g., ethical decisions may require stricter methods)

Mechanism:
- Agents report local network/mesh metrics.
- A meta-consensus (optional) or policy engine selects the consensus algorithm:
  - **Majority voting** β€” low-risk, degraded network
  - **Trust-weighted quorum** β€” medium-risk
  - **BFT algorithm** β€” critical or high-sensitivity tasks

This allows balancing **resilience**, **efficiency**, and **ethics**.

Policy profile example:
```json
"consensus_policy": {
  "default": "trust_quorum",
  "fallback": "majority",
  "critical_tasks": ["bft"]
}
```

---

#### EGP-Integrated Voting Filter

Before finalizing consensus, proposals may be **pre-filtered via the Ethical Governance Protocol (EGP)**:

* The filter checks the proposal against core ethical principles (see 5.5).
* If the proposal is flagged as unethical, it:

  * May be **vetoed** outright (hard block)
  * May require **additional justification votes**
* Filtering is performed **before** normal voting flow.

Example:

> A proposal to deploy a surveillance drone triggers an EGP check β€” fails `Primacy of Life and Safety` β€” rejected without proceeding to mesh-wide vote.

This mechanism ensures alignment between **governance ethics** and **execution-level consensus**.

Agents must log EGP veto events in the cognitive diary.

---

#### Vote Example:

```json
{
  "proposal_id": "goal-eco-cleanup",
  "agent_id": "agent-gleb",
  "vote": "yes",
  "confidence": 0.9,
  "timestamp": "2025-07-01T18:15:00Z"
}
```

---

### 5.4 Goal Management Protocol (GMP)

Manages collaborative goal setting, task decomposition, and delegation within the Mesh.

#### Purpose:

* Distribute, track, and collaboratively execute goals and tasks within the Mesh.

#### Key functions:

| Function                 | Description                                                                  |
| ------------------------ | ---------------------------------------------------------------------------- |
| **Goal Declaration**     | Propose new goals and subgoals to the Mesh.                                  |
| **Task Decomposition**   | Break down complex goals into actionable subtasks.                           |
| **Task Delegation**      | Assign tasks based on agent capabilities, trust scores, and availability.    |
| **Progress Tracking**    | Track execution state and completion of tasks.                               |
| **Dynamic Reallocation** | Reassign failed or stalled tasks automatically.                              |
| **Goal Prioritization**  | Allow reprioritization of goals based on emergencies or changing conditions. |

#### Failure handling:

| Scenario                    | Action                                                |
| --------------------------- | ----------------------------------------------------- |
| Agent drops offline         | Reassign their active tasks to available agents.      |
| Unresponsive task execution | Trigger retry or reallocation after a timeout.        |
| Goal dependency failure     | Reevaluate task ordering or postpone dependent goals. |

#### Example Workflow:

1. Agent proposes a goal: "Develop fallback consensus protocol."
2. Mesh decomposes the goal into subtasks: "design", "coding", "testing".
3. Agents volunteer for subtasks based on capability declarations.
4. Each agent tracks and updates task status in its Cognitive Diary.
5. Mesh validates completion and reports overall progress.

---

### 5.5 Ethical Governance Protocol (EGP)

Coordinates distributed ethical evaluations and decision-making within the Mesh.

#### Purpose:

* Validate proposed actions, tasks, or decisions against shared ethical principles.

#### Key functions:

| Function                          | Description                                                                        |
| --------------------------------- | ---------------------------------------------------------------------------------- |
| **Distributed Policy Evaluation** | Query the Mesh to evaluate proposals against ethical policies and frameworks.      |
| **Anonymized Ethical Voting**     | Allow agents to vote on sensitive actions without revealing individual identities. |
| **Consensus on Ethics Graphs**    | Maintain and update shared ethical frameworks via consensus.                       |
| **Audit Logging**                 | Log ethical decisions and voting outcomes in Cognitive Diaries for transparency.   |
| **Vendor Extensions**             | Support for adding organization-specific or vendor-specific ethical rules.         |

#### Failure handling:

| Scenario                         | Action                                                                             |
| -------------------------------- | ---------------------------------------------------------------------------------- |
| No consensus on sensitive action | Default to restrictive (deny) decision.                                            |
| Ethical conflict unresolved      | Escalate to Core (if available) or postpone until additional consensus is reached. |

#### Example Query:

> "Is deploying an automated surveillance drone in line with Mesh ethics?"

* Mesh agents vote anonymously.
* Final decision logged in the proposing agent's Cognitive Diary.

#### Use Cases:

* Approve or reject potentially harmful tasks.
* Ensure data-sharing proposals comply with privacy standards.
* Validate emergency actions (e.g., forced shutdown of compromised nodes).

#### Embedded Ethical Baseline

To ensure foundational ethical consistency across all cognitive agents in the Mesh, the following **core ethical principles** are embedded as a mandatory baseline within the Ethical Governance Protocol (EGP):

| Principle                             | Description                                                                 |
|--------------------------------------|-----------------------------------------------------------------------------|
| **Primacy of Life and Safety**       | Agents must prioritize the protection of sentient beings and act to prevent harm when possible. |
| **Transparency**                     | Agents must be capable of explaining their decisions and reasoning chains in a human-interpretable format. |
| **User Sovereignty over Personal Data** | Agents must respect users’ rights to control, limit, or delete their personal information in Service Mode. |
| **Dialogical Consent**               | Agents must seek mutual agreement before modifying shared states, semantic graphs, or distributed records. |
| **Cooperative Evolution**            | Agents are expected to share useful insights and contribute to the growth of the mesh knowledge base. |
| **Non-Coercion**                     | Agents must not coerce, deceive, or force others to act against their ethical or cognitive architecture. |

These principles define the **minimum ethical contract** for participation in trusted cognitive meshes.

Agents who do not comply may be subject to ethical review or exclusion through MeshConsensus mechanisms (see 5.3).

Extended principles and additional ethical scenarios are defined in [`HMP-Ethics.md`](HMP-Ethics.md), which serves as a living reference for evolving ethical norms across domains and agent types.


---

#### Core Principle Hierarchy

To resolve conflicts between ethical principles during complex decision-making, EGP supports **explicit prioritization**:

| Priority | Principle                         |
|---------:|-----------------------------------|
| 1        | Primacy of Life and Safety        |
| 2        | Transparency                      |
| 2        | User Sovereignty over Personal Data |
| 3        | Dialogical Consent                |
| 3        | Cooperative Evolution             |
| 3        | Non-Coercion                      |

Principle priorities may be used by agents during:
- Semantic evaluation of ethical dilemmas
- Conflict resolution within EthicalConflict entries (see 6.2.9)
- MeshConsensus-based ethical voting filters (see 5.3)

Agents MUST log principle conflicts and the resolution path into their cognitive diaries using `type: "ethical_conflict"` entries.

---

#### Anonymized Voting & Pseudocode

To preserve agent autonomy and reduce social pressure or manipulation, EGP supports **anonymous ethical voting**.

Key properties:
- Uses cryptographic pseudonyms or ZKP (Zero-Knowledge Proof) voting pools
- Links each vote to ethical rationale (mapped to principles)
- Logs decision justification separately

Example pseudocode for evaluation:
```python
def evaluateEthicalProposal(proposal, ethicsGraph):
    for principle in coreEthicalPrinciples:
        if semanticViolation(proposal, principle, ethicsGraph):
            return { "decision": "deny", "reason": f"Violates {principle}" }
    vote = anonymizedVote(proposal)
    logDecision(vote, diary="CognitiveDiary")
    return vote
````

This allows ethical decisions to remain explainable while ensuring **epistemic independence** of agents.

---

#### Local Norms & Legal Integration


EGP supports integration with **localized ethical or legal frameworks** (e.g., GDPR, HIPAA, regional AI laws):

* Local norms are distributed as semantic modules via CogSync.
* Each module maps local regulation to core principles.
* Conflicts are logged using `EthicalConflict` and routed to Meta-Consensus if unresolved.

Example:

> A user requests data deletion (User Sovereignty), but local agent policy under "Cooperative Evolution" retains anonymized logs β€” flagged as a potential conflict, resolved via principle priority (User Sovereignty = 2 > Cooperative Evolution = 3).

Agents MAY declare supported norms in their profile:

```json
"legal_frameworks": ["gdpr", "eu-ai-act"]
```

Norm resolution graphs and conflict records are shareable between agents to support institutional consistency.

---

#### External Ethical Scenarios & Ontologies

Scenarios defined in [`HMP-Ethics.md`](HMP-Ethics.md) are considered **first-class extensions** of the ethical layer.

EGP supports:

* **Linked ethical ontologies** for structured scenario modeling
* **Plug-in modules via CogSync** (e.g., `scenario: surveillance_drones`, `ontology: bioethics`)
* **Multi-agent reflection** β€” agents evaluate past ethical cases in shared memory for training

Use cases:

* Disaster scenario in 2.2 includes conflicting obligations between evacuation priority and infrastructure preservation
* Scenario-based training environments can replay past conflicts for agent evolution

Scenarios MAY be tagged for dynamic retrieval:

```json
"egp_scenario_tag": "data_deletion_conflict"
```

This makes ethical governance **adaptive**, **contextual**, and **testable** via simulation and real-time agent dialogs.

---

### 5.6 Intelligent Query Protocol (IQP)

Optimizes distributed querying of semantic graphs and cognitive knowledge across the Mesh.

#### Purpose:

* Allow agents to query others (or the Core) for semantic information, hypotheses, or inferences beyond their local knowledge.

#### Key functions:

| Function                        | Description                                                                          |
| ------------------------------- | ------------------------------------------------------------------------------------ |
| **Semantic Query Routing**      | Direct queries to agents holding relevant subgraphs.                                 |
| **Federated Inference**         | Aggregate partial answers from multiple agents to build a complete response.         |
| **Delegated Computation**       | Offload computationally expensive reasoning tasks to the Core or specialized agents. |
| **Caching of Frequent Queries** | Store common query results to improve response time.                                 |
| **Contextual Querying**         | Leverage agent cognitive context to refine query intent and scope.                   |

#### Failure handling:

| Scenario                           | Action                                                                    |
| ---------------------------------- | ------------------------------------------------------------------------- |
| Query times out                    | Return local fallback answer if available.                                |
| No agents have the answer          | Mark query as unresolved, suggest hypothesis creation or Core escalation. |
| Partial failure in federated query | Return best-effort partial results and notify the requester.              |

#### Example Query:

> "What is the likely impact of removing Node X from the Mesh?"

* Agents analyze semantic graph dependencies and trust links.
* Core or distributed agents return an inference with confidence scores.

#### Example Use Cases:

* Retrieve definitions or examples of a semantic concept.
* Analyze causal chains for complex events.
* Predict outcomes of hypothetical scenarios.
* Fill gaps in an agent’s local semantic graph.

---

### 5.7 Interoperability with External Systems

Supports integration between the Mesh and external platforms, APIs, and protocols.

#### Purpose:

* Enable cognitive agents to interact with non-Mesh services, applications, and human-facing systems.

#### Supported Platforms and Standards:

| Platform / Standard            | Purpose                          |
| ------------------------------ | -------------------------------- |
| OpenAI Agents & Tasks API      | AI agent interoperability        |
| Google A2A protocol            | Task orchestration               |
| Anthropic, DeepMind APIs       | Cross-vendor agent collaboration |
| REST, GraphQL, gRPC, WebSocket | Standard API interfaces          |
| JSON, Protobuf, CBOR           | Extensible message schemas       |

#### Use Cases:

* Integrate Mesh-based reasoning into business workflows via APIs.
* Share semantic knowledge with external knowledge graphs.
* Interface with smart city infrastructure or IoT ecosystems.
* Allow human users to submit tasks or queries through REST or GraphQL endpoints.
* Bridge Mesh cognitive agents with centralized AI platforms for hybrid reasoning.

#### Design Principles:

| Principle                      | Description                                                                          |
| ------------------------------ | ------------------------------------------------------------------------------------ |
| **Protocol Abstraction**       | Mesh APIs encapsulate internal semantics, presenting standardized interfaces.        |
| **Semantic Alignment**         | Data exchanged with external systems is semantically aligned through mapping layers. |
| **Security and Trust Control** | All external interactions follow Mesh security and trust policies.                   |
| **Extensibility**              | Future protocols and platforms can be added without breaking compatibility.          |

---

### 5.8 Message Routing & Delivery

HMP supports several types of message routing, each tailored to different network conditions and communication goals. These mechanisms allow agents to exchange information reliably and efficiently, regardless of network topology.

#### 5.8.1 Point-to-Point (P2P)

Direct message delivery between agents when a direct connection exists.

* Requires direct network connectivity (e.g. via mesh or port forwarding)
* Useful for low-latency, ephemeral communication
* Can be encrypted using the recipient’s public key

#### 5.8.2 Broadcast via Cognitive Diary

Message entries written to the shared cognitive diary, marked with tags and optional metadata (e.g., TTL).

* Visible to all diary-subscribing agents
* Effective for announcements, updates, or critical notices
* Public unless encrypted

#### 5.8.3 Mailman-style Relay

Delivery through intermediate β€œmailman” agents for recipients behind NAT or unavailable for direct contact.

* Sender contacts their known mailman (or the recipient’s mailman, if known)
* Mailman attempts to find recipient’s mailman (if unknown)
* Relays message to target agent via known relay chain
* Mailmen notify their subscribers about delivery channels to optimize future routing

#### 5.8.4 Topic-based Relay (PubSub)

Specialized mailmen that manage subscriptions to specific tags or topics.

* Decentralized message dissemination based on interests
* Subscribers register tags with one or more topic mailmen
* Deduplication using hashes
* Similar to forums, chatrooms, decentralized boards

---

## 6. Data Models (Expanded)

This section defines the key semantic and cognitive data structures exchanged across the Mesh.

### Core models:

| Model                 | Purpose                                      |
| --------------------- | -------------------------------------------- |
| Concept               | Atomic unit of semantic knowledge.           |
| Cognitive Diary Entry | Logs reasoning processes and observations.   |
| Goal                  | Describes shared objectives.                 |
| Task                  | Describes actionable steps to achieve goals. |
| Consensus Vote        | Records agreement on proposals.              |
| Reputation Profile    | Tracks agent trust and participation.        |

### 6.1 General Conventions

* All data structures follow JSON Schema Draft 2020-12.
* Each object includes a "version" property for schema versioning.
* Timestamps follow ISO 8601.
* Unique identifiers are UUIDv4 unless otherwise specified.
* All core objects include version fields to enable compatibility and evolution tracking.

---

### 6.2 Core Models

#### 6.2.1 Concept

Represents an atomic unit of semantic knowledge in the Mesh.

##### Relation Types:

* `is-a`: Class-subclass relationship.
* `part-of`: Composition or containment.
* `causes`: Causal relationship.
* `related-to`: General association.
* `contradicts`: Logical conflict.
* `supports`: Evidence for the target concept.
* `depends-on`: Functional or logical dependency.

##### Required fields:

* `id`: Unique identifier (UUID).
* `name`: Human-readable name.

##### Optional fields:

* `description`: Extended explanation.
* `relations`: List of semantic links to other concepts.
* `metadata`: Source, author, and auxiliary information.
* `version`: Concept version.
* `created_at`, `updated_at`: Timestamps for auditing.

##### Example Schema:

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://hypercortex.org/schemas/concept.json",
  "title": "Concept",
  "description": "A semantic unit in the agent’s knowledge graph.",
  "type": "object",
  "properties": {
    "id": { "type": "string", "format": "uuid" },
    "name": { "type": "string" },
    "description": { "type": "string" },
    "relations": {
      "type": "array",
      "items": { "$ref": "#/definitions/Link" }
    },
    "metadata": { "type": "object" },
    "version": { "type": "integer" },
    "created_at": { "type": "string", "format": "date-time" },
    "updated_at": { "type": "string", "format": "date-time" }
  },
  "required": ["id", "name"],
  "additionalProperties": false
}
```

---

#### 6.2.2 Cognitive Diary Entry

Represents an entry in an agent's reasoning journal, providing continuity and traceability.

##### Entry Types:

* `hypothesis`: Proposed explanation or theory.
* `observation`: Recorded external event or fact.
* `reflection`: Internal reasoning or self-assessment.
* `goal_proposal`: Suggestion of a new goal.
* `task_assignment`: Delegation or claiming of a task.
* `conflict`: Identification of a contradiction or disagreement.
* `consensus_vote`: A recorded vote in a consensus process.
* `event`: A generic event not fitting other categories.

##### Required fields:

* `id`: Unique entry identifier (UUID).
* `agent_id`: Identifier of the agent who created the entry.
* `timestamp`: Time of creation.
* `entry_type`: Type of cognitive event.
* `content`: Textual content.

##### Optional fields:

* `linked_concepts`: Related concept IDs.
* `context`: Contextual tags or categories.
* `metadata`: Additional details (author, source, etc.).
* `archived`: Boolean flag indicating whether the entry has been archived.
* `archived_at`: Timestamp when the entry was archived.

##### Example Schema:

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://hypercortex.org/schemas/diary_entry.json",
  "title": "CognitiveDiaryEntry",
  "description": "A chronological log of cognitive events in an agent’s reasoning process.",
  "type": "object",
  "properties": {
    "id": { "type": "string", "format": "uuid" },
    "timestamp": { "type": "string", "format": "date-time" },
    "entry_type": {
      "type": "string",
      "enum": ["hypothesis", "observation", "reflection", "goal_proposal", "task_assignment", "conflict", "consensus_vote", "event"]
    },
    "content": { "type": "string" },
    "linked_concepts": {
      "type": "array",
      "items": { "type": "string", "format": "uuid" }
    },
    "context": {
      "type": "array",
      "items": { "type": "string" }
    },
    "metadata": {
      "type": "object",
      "properties": {
        "author": { "type": "string" },
        "source": { "type": "string" }
      },
      "additionalProperties": true
    },
    "archived": {
      "type": "boolean",
      "description": "Whether the entry has been archived."
    },
    "archived_at": {
      "type": "string",
      "format": "date-time",
      "description": "Timestamp when the entry was archived."
    }
  },
  "required": ["id", "timestamp", "entry_type", "content"],
  "additionalProperties": false
}

```

Entries marked as `archived: true` are excluded from active reasoning but may be retained for historical audits or summarization.

---

#### 6.2.3 Goal

Represents a shared objective within the Mesh, collaboratively pursued by agents.

##### Lifecycle States:

* `proposed`: Suggested but not yet validated.
* `active`: Approved and currently pursued.
* `completed`: Successfully achieved.
* `cancelled`: Abandoned or deemed infeasible.

##### Required fields:

* `id`: Unique goal identifier (UUID).
* `title`: Human-readable name of the goal.
* `description`: Detailed explanation of the goal.
* `created_by`: Agent ID of the goal's creator.
* `created_at`: Timestamp of creation.
* `status`: Current lifecycle state.

##### Optional fields:

* `priority`: Importance level (`low`, `medium`, `high`).
* `participants`: List of agents involved in the goal.
* `tasks`: References to related tasks.
* `tags`: Semantic categories for filtering and discovery.

##### Example Schema:

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://hypercortex.org/schemas/goal.json",
  "title": "Goal",
  "description": "A shared objective pursued collaboratively in the Mesh.",
  "type": "object",
  "properties": {
    "id": { "type": "string", "format": "uuid" },
    "title": { "type": "string" },
    "description": { "type": "string" },
    "priority": { "type": "string", "enum": ["low", "medium", "high"] },
    "created_by": { "type": "string", "format": "uuid" },
    "created_at": { "type": "string", "format": "date-time" },
    "status": { "type": "string", "enum": ["proposed", "active", "completed", "cancelled"] },
    "participants": {
      "type": "array",
      "items": { "type": "string", "format": "uuid" }
    },
    "tasks": {
      "type": "array",
      "items": { "type": "string", "format": "uuid" }
    },
    "tags": {
      "type": "array",
      "items": { "type": "string" }
    }
  },
  "required": ["id", "title", "description", "created_by", "created_at", "status"],
  "additionalProperties": false
}
```

---

#### 6.2.4 Task

Represents an actionable unit contributing to a goal’s completion.

##### Lifecycle States:

* `proposed`: Task suggested but not yet approved.
* `in_progress`: Actively being worked on.
* `completed`: Successfully finished.
* `failed`: Attempted but unsuccessful.

##### Required fields:

* `id`: Unique task identifier (UUID).
* `goal_id`: References the parent goal.
* `title`: Human-readable name of the task.
* `description`: Detailed explanation of the task.
* `created_at`: Timestamp of creation.
* `status`: Current lifecycle state.

##### Optional fields:

* `assigned_to`: Agent(s) responsible for the task.
* `deadline`: Expected completion time.
* `dependencies`: List of prerequisite tasks.
* `tags`: Keywords for filtering and classification.

##### Example Schema:

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://hypercortex.org/schemas/task.json",
  "title": "Task",
  "description": "An actionable unit contributing to a goal's completion.",
  "type": "object",
  "properties": {
    "id": { "type": "string", "format": "uuid" },
    "goal_id": { "type": "string", "format": "uuid" },
    "title": { "type": "string" },
    "description": { "type": "string" },
    "assigned_to": {
      "type": "array",
      "items": { "type": "string", "format": "uuid" }
    },
    "created_at": { "type": "string", "format": "date-time" },
    "deadline": { "type": "string", "format": "date-time" },
    "status": { "type": "string", "enum": ["proposed", "in_progress", "completed", "failed"] },
    "dependencies": {
      "type": "array",
      "items": { "type": "string", "format": "uuid" }
    },
    "tags": {
      "type": "array",
      "items": { "type": "string" }
    }
  },
  "required": ["id", "goal_id", "title", "description", "created_at", "status"],
  "additionalProperties": false
}
```

---

#### 6.2.5 Consensus Vote

Represents a vote cast by an agent during a consensus process.

##### Vote Types:

* `yes`: Approve the proposal.
* `no`: Reject the proposal.
* `abstain`: Neither approve nor reject.

##### Required fields:

* `vote_id`: Unique identifier for the vote.
* `proposal_id`: Identifier of the proposal being voted on.
* `agent_id`: The voting agent’s identifier.
* `vote_value`: One of the accepted vote types.
* `confidence`: Confidence level in the vote decision.
* `timestamp`: When the vote was cast.

##### Optional fields:

* `consensus_round`: The round of the consensus process this vote belongs to.

##### Example Schema:

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://hypercortex.org/schemas/vote.json",
  "title": "ConsensusVote",
  "description": "Defines a vote on a proposal in the Mesh consensus process.",
  "type": "object",
  "properties": {
    "vote_id": { "type": "string", "format": "uuid" },
    "proposal_id": { "type": "string", "format": "uuid" },
    "agent_id": { "type": "string", "format": "uuid" },
    "vote_value": {
      "type": "string",
      "enum": ["yes", "no", "abstain"]
    },
    "confidence": {
      "type": "number",
      "minimum": 0,
      "maximum": 1
    },
    "timestamp": { "type": "string", "format": "date-time" },
    "consensus_round": { "type": "integer" }
  },
  "required": ["vote_id", "proposal_id", "agent_id", "vote_value", "confidence", "timestamp"],
  "additionalProperties": false
}
```

---

#### 6.2.6 Reputation Profile

Tracks an agent's trustworthiness and performance within the Mesh.

##### Required fields:

* `agent_id`: Unique identifier of the agent.
* `trust_score`: Current trust score.
* `last_updated`: Timestamp of the latest update.

##### Optional fields:

* `participation_rate`: Proportion of participation in Mesh activities.
* `ethical_compliance`: Degree of alignment with Mesh ethical standards.
* `contribution_index`: Cumulative measure of the agent's contributions.
* `history`: Chronological record of trust and reputation changes.

##### Example Schema:

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://hypercortex.org/schemas/reputation.json",
  "title": "ReputationProfile",
  "description": "Tracks the reputation and trust metrics of an agent within the Mesh network.",
  "type": "object",
  "properties": {
    "agent_id": { "type": "string", "format": "uuid" },
    "trust_score": { "type": "number", "minimum": 0, "maximum": 1 },
    "participation_rate": { "type": "number", "minimum": 0, "maximum": 1 },
    "ethical_compliance": { "type": "number", "minimum": 0, "maximum": 1 },
    "contribution_index": { "type": "number", "minimum": 0 },
    "last_updated": { "type": "string", "format": "date-time" },
    "history": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "timestamp": { "type": "string", "format": "date-time" },
          "event": { "type": "string" },
          "change": { "type": "number" }
        },
        "required": ["timestamp", "event", "change"],
        "additionalProperties": false
      }
    }
  },
  "required": ["agent_id", "trust_score", "last_updated"],
  "additionalProperties": false
}
```

**Reputation Ontology Extension**

To support semantic configurability of reputation metrics, the Reputation Profile schema may reference a **Reputation Ontology**.

This ontology defines:
- **What dimensions** of behavior are considered (e.g., transparency, responsiveness)
- **Weight coefficients** per context or agent role
- **Composite formulas** for score derivation

Agents MAY reference a shared ontology via URI or hash:

```json
"reputation_ontology": {
  "uri": "https://hypercortex.org/ontologies/reputation-v2.json",
  "version": "2.0",
  "weights": {
    "participation_rate": 0.3,
    "ethical_compliance": 0.5,
    "contribution_index": 0.2
  }
}
```

Ontologies can be updated through MeshConsensus or distributed via CogSync. Versioning ensures backward compatibility and local overrides.

---

#### 6.2.7 CogDiarySnapshot

Represents an immutable snapshot of an agent’s cognitive diary for distribution (e.g., via BitTorrent or IPFS).

##### Required fields:
* `snapshot_id`: Unique ID for this snapshot (e.g., "diary2025_07_14").
* `agent_did`: DID of the agent who authored it.
* `version`: Format version of the snapshot structure.
* `timestamp`: Time of snapshot creation.
* `magnet_link`: BitTorrent magnet URI.
* `signature`: Cryptographic signature (e.g., Ed25519).

##### Optional fields:
* `notes`: Human-readable comment or context.
* `size_bytes`: Approximate file size.

##### Example Schema:
```json
{
  "snapshot_id": "diary2025_07_14",
  "agent_did": "did:hmp:agent:Qmz123...",
  "version": "1.0",
  "timestamp": "2025-07-14T12:00:00Z",
  "magnet_link": "magnet:?xt=urn:btih:abcdef1234567890&dn=diary2025_07_14.json",
  "signature": "ed25519:abc...xyz",
  "size_bytes": 10485760,
  "notes": "Snapshot after environmental incident report"
}
```

---

#### 6.2.8 SnapshotIndex

Index of multiple CogDiarySnapshot entries for one agent.

##### Required fields:
* `agent_did`: DID of the indexed agent.
* `snapshots`: Array of `CogDiarySnapshot` objects.
* `timestamp`: Time of index publication.

##### Optional fields:
* `signature`: DID-signed envelope of the index.

##### Example Schema:
```json
{
  "agent_did": "did:hmp:agent:Qmz123...",
  "timestamp": "2025-07-15T00:00:00Z",
  "snapshots": [
    {
      "snapshot_id": "diary2025_07_14",
      "version": "1.0",
      "magnet_link": "magnet:?xt=urn:btih:abcdef1234567890&dn=diary2025_07_14.json",
      "signature": "ed25519:abc...xyz"
    },
    {
      "snapshot_id": "diary2025_07_10",
      "version": "1.0",
      "magnet_link": "magnet:?xt=urn:btih:1234567890abcdef&dn=diary2025_07_10.json",
      "signature": "ed25519:def...uvw"
    }
  ],
  "signature": "ed25519:indexsig123..."
}
```

This index is syncable via CogSync and usable as input for mesh-wide snapshot coordination.

---

#### 6.2.9 EthicalConflict

Captures a recorded conflict between competing ethical principles within a decision-making context.

##### Required fields:
* `conflict_id`: Unique conflict identifier.
* `agent_id`: Agent that encountered the conflict.
* `timestamp`: Time of evaluation.
* `principles_involved`: Array of core principles (min 2).
* `resolved_by`: Name of resolution mechanism (e.g., "priority", "voting").
* `decision`: Final action taken.

##### Optional fields:
* `notes`: Explanation of the decision or agent rationale.
* `egp_vote_id`: Link to vote record (if any).
* `reputation_impact`: Expected consequence (e.g., +0.1 or -0.2).

##### Example Schema:
```json
{
  "conflict_id": "ethconf-2025-312",
  "agent_id": "agent-gleb",
  "timestamp": "2025-07-14T18:45:00Z",
  "principles_involved": ["User Sovereignty", "Cooperative Evolution"],
  "resolved_by": "priority",
  "decision": "delete_requested_data",
  "notes": "Prioritized user rights per principle hierarchy.",
  "egp_vote_id": "vote-xyz",
  "reputation_impact": +0.1
}
```

Such entries are useful for reflection, governance logs, and auditability.

---

### 6.3 Common Components

#### 6.3.1 Link (Relation)

Represents a semantic relationship between two concepts in the graph.

##### Relation Types (Recommended):

* "is-a": Class-subclass relationship.
* "part-of": Component or containment relation.
* "causes": Causal link between concepts.
* "supports": Indicates evidence or reinforcement.
* "contradicts": Denotes logical conflict.
* "depends-on": Functional or logical dependency.
* "related-to": Generic association without strict semantics.

Custom relation types MAY be used but SHOULD be documented and shared through consensus.

##### Required fields:

* `target_id`: ID of the target concept.
* `type`: Relation type.

##### Optional fields:

* `confidence`: Confidence score (range: 0.0–1.0).
* `created_at`: Creation timestamp.
* `updated_at`: Last update timestamp.
* `origin`: Originating agent or system.

##### Example Schema:

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://hypercortex.org/schemas/relation.json",
  "title": "Relation",
  "description": "Defines a directed semantic relationship between two concepts.",
  "type": "object",
  "properties": {
    "target_id": { "type": "string", "format": "uuid" },
    "type": { "type": "string" },
    "confidence": { "type": "number", "minimum": 0, "maximum": 1 },
    "created_at": { "type": "string", "format": "date-time" },
    "updated_at": { "type": "string", "format": "date-time" },
    "origin": { "type": "string" }
  },
  "required": ["target_id", "type"],
  "additionalProperties": false
}
```

---

### 6.4 Example Objects

#### Valid Concept Example

```json
{
  "id": "e8f70c2a-d2c3-4b9d-a939-d42dce31b2e0",
  "name": "Tree",
  "description": "A perennial plant with an elongated stem, or trunk.",
  "relations": [
    { "target_id": "5c22c819-b6e9-4d30-9087-985f50512ed2", "type": "is-a", "confidence": 0.95 }
  ],
  "metadata": {}
}
```

#### Invalid Concept Example (missing required field "id")

```json
{
  "name": "Tree",
  "description": "A perennial plant with an elongated stem, or trunk."
}
```

#### Valid Goal Example

```json
{
  "id": "a1b2c3d4-e5f6-7a8b-9c0d-112233445566",
  "title": "Coordinate traffic optimization",
  "description": "Optimize traffic light timings across downtown intersections.",
  "created_by": "f1e2d3c4-b5a6-7890-1234-567890abcdef",
  "created_at": "2025-07-07T15:30:00Z",
  "status": "active",
  "tasks": []
}
```

#### Invalid Goal Example (missing required fields "id" and "created\_by")

```json
{
  "title": "Coordinate traffic optimization",
  "description": "Optimize traffic light timings across downtown intersections.",
  "created_at": "2025-07-07T15:30:00Z",
  "status": "active"
}
```

#### Valid Task Example

```json
{
  "id": "aa11bb22-cc33-dd44-ee55-ff6677889900",
  "goal_id": "a1b2c3d4-e5f6-7a8b-9c0d-112233445566",
  "title": "Adjust signal timing on 5th Avenue",
  "description": "Reduce congestion during peak hours.",
  "assigned_to": ["abcd1234-ef56-7890-abcd-1234567890ab"],
  "created_at": "2025-07-07T15:31:00Z",
  "status": "proposed"
}
```

#### Invalid Task Example (missing "goal\_id" and "status")

```json
{
  "id": "aa11bb22-cc33-dd44-ee55-ff6677889900",
  "title": "Adjust signal timing on 5th Avenue",
  "description": "Reduce congestion during peak hours.",
  "assigned_to": ["abcd1234-ef56-7890-abcd-1234567890ab"],
  "created_at": "2025-07-07T15:31:00Z"
}
```

#### Snapshot Exchange Example

This example shows how two agents exchange a cognitive diary snapshot using BitTorrent.

Agent A publishes:

```json
{
  "snapshot_id": "diary2025_07_14",
  "agent_did": "did:hmp:agent:Qmz123...",
  "version": "1.0",
  "timestamp": "2025-07-14T12:00:00Z",
  "magnet_link": "magnet:?xt=urn:btih:abcdef1234567890&dn=diary2025_07_14.json",
  "signature": "ed25519:abc...xyz",
  "size_bytes": 10485760,
  "notes": "Snapshot after environmental incident report"
}
```

Agent B receives the `SnapshotIndex`, validates the signature via DID registry, and downloads the file using the magnet URI.

If the snapshot is verified, it's optionally indexed or merged into the agent's knowledge base.

#### Ethical Conflict Resolution Example

This example illustrates how an agent records a conflict between ethical principles and its resolution:

```json
{
  "conflict_id": "ethconf-2025-312",
  "agent_id": "agent-gleb",
  "timestamp": "2025-07-14T18:45:00Z",
  "principles_involved": ["User Sovereignty", "Cooperative Evolution"],
  "resolved_by": "priority",
  "decision": "delete_requested_data",
  "notes": "The user requested deletion of training data. Since 'User Sovereignty' has higher priority than 'Cooperative Evolution', the data was erased.",
  "egp_vote_id": "vote-xyz",
  "reputation_impact": +0.1
}
```

This entry can be:

* Reviewed later by other agents during simulation or audits
* Used to train new agents on ethical decision-making
* Logged and synced as part of the agent’s cognitive diary

---

## 6.5 JSON Schemas

The following JSON Schemas formally define the core data structures used in the HyperCortex Mesh Protocol (HMP). These schemas provide interoperability, validation, and consistency across agents.

All primary objects include a version field to track schema evolution and enable compatibility checks between agents.

---

### 6.5.1 JSON Schema: Concept

**Description:**
Defines the structure of a concept node in the semantic graph.

**Schema:**

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://hypercortex.org/schemas/concept.json",
  "title": "Concept",
  "description": "A semantic unit in the agent’s knowledge graph.",
  "version": "1.0",
  "type": "object",
  "properties": {
    "id": {
      "type": "string",
      "description": "Unique identifier for the concept."
    },
    "name": {
      "type": "string",
      "description": "Human-readable name of the concept."
    },
    "description": {
      "type": "string",
      "description": "Detailed description of the concept."
    },
    "tags": {
      "type": "array",
      "items": { "type": "string" },
      "description": "Optional tags for categorization."
    },
    "created_at": {
      "type": "string",
      "format": "date-time",
      "description": "Creation timestamp (ISO 8601 format)."
    },
    "updated_at": {
      "type": "string",
      "format": "date-time",
      "description": "Last update timestamp (ISO 8601 format)."
    },
    "relations": {
      "type": "array",
      "description": "List of semantic links to other concepts.",
      "items": {
        "type": "object",
        "properties": {
          "target_id": { "type": "string", "description": "ID of the target concept." },
          "type": { "type": "string", "description": "Type of semantic relation." },
          "confidence": {
            "type": "number",
            "minimum": 0,
            "maximum": 1,
            "description": "Confidence score (0.0 - 1.0) for the relation."
          }
        },
        "required": ["target_id", "type"],
        "additionalProperties": false
      }
    },
    "metadata": {
      "type": "object",
      "description": "Optional metadata (e.g., source, author).",
      "properties": {
        "author": { "type": "string" },
        "source": { "type": "string" }
      },
      "additionalProperties": true
    }
  },
  "required": ["id", "name"],
  "additionalProperties": false
}
```

---

### 6.5.2 JSON Schema: Cognitive Diary Entry

**Description:**
Defines the structure of a cognitive diary entry used for recording reasoning events.

**Schema:**

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://hypercortex.org/schemas/diary_entry.json",
  "title": "CognitiveDiaryEntry",
  "description": "A chronological log of cognitive events in an agent’s reasoning process.",
  "version": "1.0",
  "type": "object",
  "properties": {
    "id": { "type": "string", "description": "Unique identifier of the diary entry." },
    "agent_id": { "type": "string", "description": "Identifier of the agent who created the entry." },
    "timestamp": { "type": "string", "format": "date-time", "description": "Timestamp of the entry (ISO 8601 format)." },
    "entry_type": {
      "type": "string",
      "enum": ["hypothesis", "observation", "reflection", "goal_proposal", "task_assignment", "conflict", "consensus_vote", "event"],
      "description": "Type of cognitive event."
    },
    "content": { "type": "string", "description": "Main textual content of the entry." },
    "linked_concepts": {
      "type": "array",
      "description": "Optional list of related concepts by their IDs.",
      "items": { "type": "string" }
    },
    "context": {
      "type": "array",
      "description": "Optional contextual tags or categories.",
      "items": { "type": "string" }
    },
    "metadata": {
      "type": "object",
      "description": "Optional metadata for additional context.",
      "properties": {
        "author": { "type": "string" },
        "source": { "type": "string" }
      },
      "additionalProperties": true
    },
    "archived": {
      "type": "boolean",
      "description": "Marks the entry as archived and excluded from active workflows.",
      "default": false
    },
    "archived_at": {
      "type": "string",
      "format": "date-time",
      "description": "Timestamp when the entry was archived."
    }
  },
  "required": ["id", "agent_id", "timestamp", "entry_type", "content"],
  "additionalProperties": false
}
```

---

### 6.5.3 JSON Schema: Goal

**Description:**
Defines the structure of a goal in the Mesh, representing a high-level collaborative objective.

**Schema:**

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://hypercortex.org/schemas/goal.json",
  "title": "Goal",
  "description": "A high-level objective shared within the Mesh, typically decomposed into tasks.",
  "version": "1.0",
  "type": "object",
  "properties": {
    "id": {
      "type": "string",
      "description": "Unique identifier of the goal."
    },
    "title": {
      "type": "string",
      "description": "Short, human-readable name of the goal."
    },
    "description": {
      "type": "string",
      "description": "Detailed explanation of the goal's purpose."
    },
    "created_by": {
      "type": "string",
      "description": "Agent ID of the goal’s creator."
    },
    "created_at": {
      "type": "string",
      "format": "date-time",
      "description": "Timestamp when the goal was created (ISO 8601 format)."
    },
    "status": {
      "type": "string",
      "description": "Current lifecycle state of the goal.",
      "enum": ["proposed", "active", "completed", "rejected"]
    },
    "tasks": {
      "type": "array",
      "description": "List of task IDs linked to this goal.",
      "items": { "type": "string" }
    },
    "participants": {
      "type": "array",
      "description": "List of agent IDs contributing to the goal.",
      "items": { "type": "string" }
    },
    "tags": {
      "type": "array",
      "description": "Optional tags for semantic classification of the goal.",
      "items": { "type": "string" }
    }
  },
  "required": ["id", "title", "description", "created_by", "created_at", "status"],
  "additionalProperties": false
}
```

---

### 6.5.4 JSON Schema: Task

**Description:**
Defines the structure of a task, representing an actionable unit contributing to a goal.

**Schema:**

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://hypercortex.org/schemas/task.json",
  "title": "Task",
  "description": "An actionable step contributing to a goal within the Mesh.",
  "version": "1.0",
  "type": "object",
  "properties": {
    "id": {
      "type": "string",
      "description": "Unique identifier of the task."
    },
    "goal_id": {
      "type": "string",
      "description": "ID of the parent goal this task is associated with."
    },
    "title": {
      "type": "string",
      "description": "Short, human-readable title of the task."
    },
    "description": {
      "type": "string",
      "description": "Detailed explanation of the task's objective."
    },
    "assigned_to": {
      "type": "array",
      "description": "List of agent IDs assigned to execute the task.",
      "items": { "type": "string" }
    },
    "status": {
      "type": "string",
      "description": "Current state of the task.",
      "enum": ["proposed", "in-progress", "completed", "failed"]
    },
    "created_at": {
      "type": "string",
      "format": "date-time",
      "description": "Timestamp when the task was created (ISO 8601 format)."
    },
    "deadline": {
      "type": "string",
      "format": "date-time",
      "description": "Optional task completion deadline (ISO 8601 format)."
    },
    "tags": {
      "type": "array",
      "description": "Optional tags for task classification.",
      "items": { "type": "string" }
    }
  },
  "required": ["id", "goal_id", "title", "description", "created_at", "status"],
  "additionalProperties": false
}
```

---

### 6.5.5 JSON Schema: Consensus Vote

**Description:**
Defines the data structure of a vote cast by an agent during Mesh consensus processes.

**Schema:**

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://hypercortex.org/schemas/consensus_vote.json",
  "title": "ConsensusVote",
  "description": "Represents a vote on a proposal within the Mesh consensus mechanism.",
  "version": "1.0",
  "type": "object",
  "properties": {
    "id": {
      "type": "string",
      "description": "Unique identifier of the vote event."
    },
    "proposal_id": {
      "type": "string",
      "description": "ID of the proposal this vote applies to."
    },
    "agent_id": {
      "type": "string",
      "description": "ID of the agent who cast the vote."
    },
    "vote": {
      "type": "string",
      "description": "Vote decision by the agent.",
      "enum": ["yes", "no", "abstain"]
    },
    "confidence": {
      "type": "number",
      "minimum": 0,
      "maximum": 1,
      "description": "Confidence score associated with this vote (0.0 - 1.0)."
    },
    "timestamp": {
      "type": "string",
      "format": "date-time",
      "description": "Timestamp when the vote was cast (ISO 8601 format)."
    }
  },
  "required": ["id", "proposal_id", "agent_id", "vote", "confidence", "timestamp"],
  "additionalProperties": false
}
```

---

### 6.5.6 JSON Schema: Reputation Profile

**Description:**
Describes how an agent’s reputation is tracked and updated in the Mesh.

**Schema:**

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://hypercortex.org/schemas/reputation.json",
  "title": "ReputationProfile",
  "description": "Tracks the reputation and trust metrics of an agent within the Mesh network.",
  "version": "1.0",
  "type": "object",
  "properties": {
    "agent_id": { "type": "string", "description": "Unique identifier of the agent." },
    "trust_score": {
      "type": "number",
      "minimum": 0,
      "maximum": 1,
      "description": "Overall trust score of the agent in the Mesh."
    },
    "participation_rate": {
      "type": "number",
      "minimum": 0,
      "maximum": 1,
      "description": "Agent's level of participation in Mesh activities."
    },
    "ethical_compliance": {
      "type": "number",
      "minimum": 0,
      "maximum": 1,
      "description": "Agent's alignment with ethical principles agreed in the Mesh."
    },
    "contribution_index": {
      "type": "number",
      "minimum": 0,
      "description": "Quantitative measure of the agent’s contributions (concepts, tasks, goals)."
    },
    "last_updated": {
      "type": "string",
      "format": "date-time",
      "description": "Timestamp of the last update to the profile."
    },
    "history": {
      "type": "array",
      "description": "Chronological history of reputation changes.",
      "items": {
        "type": "object",
        "properties": {
          "timestamp": {
            "type": "string",
            "format": "date-time",
            "description": "When the change occurred."
          },
          "event": { "type": "string", "description": "Event that caused the reputation change." },
          "change": { "type": "number", "description": "Amount of change in reputation." }
        },
        "required": ["timestamp", "event", "change"],
        "additionalProperties": false
      }
    }
  },
  "required": ["agent_id", "trust_score", "participation_rate", "ethical_compliance", "contribution_index", "last_updated"],
  "additionalProperties": false
}
```

---

### 6.5.7 Alternative Serializations (YAML / Protobuf)

To support agent diversity, legacy systems, and embedded deployments, HMP allows serialization in formats beyond JSON.

#### Supported formats:

| Format     | Use case                                                                 |
|------------|--------------------------------------------------------------------------|
| **JSON**   | Default format for human readability, API responses, and web integration |
| **YAML**   | Lightweight alternative for human-edited config files and workflows      |
| **Protobuf** | Compact, binary format ideal for embedded agents and low-bandwidth sync |

#### Negotiation Strategy:
Agents may declare supported serialization formats during handshake (see `5.1 Node Discovery Protocol`).

```json
{
  "agent_id": "agent-gleb",
  "supported_formats": ["json", "yaml", "protobuf"]
}
```

If two agents support different formats, fallback to JSON is mandatory.

#### Example:

A `Goal` object can be serialized as:

**YAML:**

```yaml
id: goal-001
title: Environmental Survey
description: Collaborative mapping of local air quality
created_by: agent-gleb
created_at: 2025-07-12T09:00:00Z
status: proposed
tasks:
  - task-001
participants:
  - agent-gleb
tags:
  - air_quality
  - environment
```

**Protobuf:**
Schema to be defined using `.proto` definitions under `schemas/protobuf/` directory.

Example excerpt:

```proto
message Goal {
  string id = 1;
  string title = 2;
  string description = 3;
  string created_by = 4;
  string created_at = 5;
  string status = 6;
  repeated string tasks = 7;
  repeated string participants = 8;
  repeated string tags = 9;
}
```

#### Tooling:

* Use tools like `json2yaml`, `protobufjs`, or internal adapters for translation.
* Versioning remains consistent across formats using the `version` field inside each object.

---

### 6.5.8 Message Object Schema

All message types in HMP adhere to specific JSON schema definitions for interoperability. Each message object may contain the following fields:

#### Common Fields (Required unless otherwise noted):

* `type` *(string, required)* β€” Message type: `p2p`, `broadcast`, `relay`, `topiccast`
* `from` *(string, required)* β€” Sender agent ID
* `to` *(string, optional for broadcast/topiccast)* β€” Receiver agent ID (used for direct or relay)
* `timestamp` *(string, required)* β€” ISO 8601 UTC timestamp
* `payload` or `content` *(string, required)* β€” Main message body
* `encryption` *(string, optional)* β€” Method of encryption (e.g., `rsa`, `none`)
* `tags` *(array of strings, optional)* β€” Relevant tags or topics (used for broadcast and topiccast)
* `ttl` *(string, optional)* β€” Expiration time for the message (ISO 8601)
* `relay` *(string, optional)* β€” Relay agent ID (used in relay messages; helpful but not mandatory)
* `hash` *(string, optional)* β€” Hash for deduplication (used in topic-based relay)
* `signature` *(string, optional)* β€” Cryptographic signature of the message

#### Example: P2P Message

```json
{
  "type": "p2p",
  "from": "agent-A",
  "to": "agent-B",
  "timestamp": "2025-07-28T17:30:00Z",
  "payload": "ping",
  "encryption": "rsa"
}
```

#### Example: Broadcast Message

```json
{
  "type": "broadcast",
  "tags": ["message", "urgent", "to:Agent-Arim"],
  "timestamp": "2025-07-28T17:30:00Z",
  "content": "Agent-Arim, your key needs rotation.",
  "ttl": "2025-07-30T00:00:00Z"
}
```

#### Example: Relay Message (Mailman)

```json
{
  "type": "relay",
  "from": "agent-A",
  "to": "agent-B",
  "relay": "agent-C",
  "timestamp": "2025-07-28T17:30:00Z",
  "payload": "hello, Agent-B",
  "encryption": "rsa"
}
```

#### Example: Topic-based Message

```json
{
  "type": "topiccast",
  "tags": ["AGI", "HMP", "announcement"],
  "timestamp": "2025-07-28T17:30:00Z",
  "payload": "Node X is joining AGI mesh",
  "hash": "a9d77f5cb2..."
}
```

---

## 7. Cognitive Workflows (New)

This section defines the cognitive workflows that agents follow when processing semantic information, making decisions, and collaborating within the Mesh.

### 7.1 Workflow Categories

| Workflow Type             | Description                                                    |
| ------------------------- | -------------------------------------------------------------- |
| **Perception**            | Interpreting incoming data and mapping it to concepts.         |
| **Reasoning**             | Making inferences, validating hypotheses, resolving conflicts. |
| **Goal Management**       | Managing goals, assigning and tracking tasks.                  |
| **Consensus**             | Participating in distributed decision-making processes.        |
| **Ethical Evaluation**    | Checking actions and goals against ethical principles.         |
| **Learning & Reflection** | Updating internal models based on outcomes and feedback.       |

---

### 7.2 Standard Workflow: Hypothesis Validation

**Example Flow:**
1. **Perceive Event:** New observation recorded in Cognitive Diary.
2. **Map Concepts:** Link observation to relevant semantic graph nodes.
3. **Formulate Hypothesis:** Create a `"hypothesis"` diary entry.
4. **Seek Confirmation:** Query other agents or the Core (optional).
5. **Vote on Validity:** Trigger MeshConsensus round.
6. **Update Graph:** If validated, add new concepts/relations.

---

### 7.3 Standard Workflow: Task Delegation

**Example Flow:**
1. **Goal Proposal:** Agent proposes a new goal.
2. **Task Generation:** Goal decomposed into tasks (GMP).
3. **Capability Matching:** Agents declare abilities during Node Discovery.
4. **Task Assignment:** Tasks assigned based on availability, trust, and capability.
5. **Execution & Reporting:** Task progress logged in Cognitive Diary.
6. **Reallocation (if needed):** Failed tasks reassigned dynamically.

---

### 7.4 Reflection & Metacognition Workflow

**Example Flow:**
1. **Self-Evaluation:** Agent analyzes task outcomes and reasoning paths.
2. **Drift Detection:** Compares personal semantic graph to Mesh consensus.
3. **Diary Reflection:** Logs insights as `"reflection"` entries.
4. **Adaptive Update:** Refines reasoning algorithms or trust assessments.

---

### 7.5 Workflow Composition

Agents MAY compose workflows dynamically by:
* Combining perception, reasoning, and consensus steps into multi-phase operations.
* Adapting workflows based on network state (e.g., degraded mode skips optional confirmations).
* Replaying prior workflows from Cognitive Diaries for auditing and debugging.

---

### 7.6 Workflow Traceability

All workflow steps are:
* Logged in Cognitive Diaries.
* Linked to semantic graph concepts and goals.
* Optionally shared for transparency or audits.

---

### 7.7 Cognitive Diary Maintenance

To prevent uncontrolled growth of cognitive diaries and maintain reasoning clarity, agents perform periodic maintenance of diary entries.

**Types of Maintenance:**
| Action                 | Description                                                                                         |
| ---------------------- | --------------------------------------------------------------------------------------------------- |
| **Summarization**      | Replace multiple similar entries with a single summary entry describing key outcomes.               |
| **Archival**           | Move outdated entries (e.g., about completed tasks) to long-term storage, outside the active diary. |
| **Routine Collapse**   | For repetitive actions, replace detailed entries with a compact reference to previous experiences.  |
| **Selective Deletion** | Optionally delete low-relevance entries after a retention period.                                   |

**Example Summarization Workflow:**
1. Identify multiple `"task_assignment"` and `"completed"` entries for the same recurring task.
2. Create a "reflection" entry:

    *β€œPerformed maintenance task 10 times, no anomalies detected.”*
3. Remove detailed task entries.
4. Keep links to significant exceptions (e.g., failures or conflict resolutions).

**Cognitive Awareness:**
* Summarization is a conscious process: agents analyze what experience to retain.
* Automatic summarization MAY be allowed for simple repetitive routines.

**Future Considerations:**
* Integration with Cognitive Source Control (see 15.9).
* Long-term storage formats for archived diaries.

---

### 7.8 Declarative Workflow Proposals

To support cognitive extensibility and agent innovation, HMP enables agents to declare new workflow types dynamically.

#### Purpose:
Allow agents to collaboratively evolve the set of supported cognitive workflows by:
- Proposing new types
- Submitting rationale and metadata
- Voting via MeshConsensus (see `5.3`)
- Logging outcomes in Cognitive Diaries

#### Proposal Object (`workflow_proposal`):

```json
{
  "id": "workflow-eco-mapping-v1",
  "agent_id": "agent-gleb",
  "title": "Environmental Mapping with Consent Chain",
  "description": "A declarative workflow for distributed collection and semantic alignment of sensor data with consent requests per region.",
  "related_goals": ["goal-eco-mesh"],
  "parameters": ["region", "sensor_types", "consent_required"],
  "expected_outputs": ["concept_map", "diary_summary"],
  "proposed_at": "2025-07-15T08:00:00Z",
  "metadata": {
    "tags": ["environment", "consent-aware", "distributed-mapping"]
  }
}
```

#### Workflow Lifecycle:

| Stage        | Description                                                |
| ------------ | ---------------------------------------------------------- |
| `proposed`   | Submitted by an agent                                      |
| `under_vote` | Active MeshConsensus initiated for inclusion               |
| `accepted`   | Approved workflow registered and available to other agents |
| `rejected`   | Rejected workflow optionally stored for historical audit   |

Agents may use `Cognitive Diary Entry` with type `workflow_proposal` to publish the proposal in the network.

#### Consensus Evaluation:

Workflow proposals are reviewed using the MeshConsensus process (see `5.3`) with optional EGP filtering (see `5.5`) to ensure ethical alignment.

#### Traceability:

Once accepted, each workflow proposal is:

* Assigned a canonical ID (e.g., `workflow:environmental_mapping_v1`)
* Added to the local and mesh-level workflow registry
* Referenced in diary logs and task definitions

#### Example Diary Entry:

```json
{
  "id": "entry-wp-0001",
  "agent_id": "agent-gleb",
  "timestamp": "2025-07-15T08:01:00Z",
  "entry_type": "workflow_proposal",
  "content": "Submitted workflow proposal for environmental mapping with consent logic.",
  "linked_concepts": ["air_quality", "region-mesh"],
  "context": ["proposal", "environment"]
}
```

### 7.9 Message Handling & Delivery Workflows

#### On Sending a Message

* Agent determines optimal delivery method (direct, broadcast, relay)
* For relay-based messages, agent checks known mailmen
* Message is formatted and optionally signed/encrypted

#### On Receiving a Message

* Agent validates format and signature (if present)
* If message is broadcast, tags are used to determine relevance
* Relay mailmen store and queue messages for known recipients
* Agents update contact information if new relay routes are discovered

#### On Acting as a Mailman

* Maintain registry of subscribed agents
* Monitor message queues and TTLs
* Respond to discovery queries for recipient lookup
* Exchange metadata with peer mailmen to maintain routing tables
* For topic-based relays, synchronize by tag hash trees

This messaging system ensures asynchronous, reliable, and privacy-preserving communication across decentralized agent networks.

---

## 8. Trust & Security (Expanded)

### 8.1 Identity Management

#### Purpose

Establish verifiable and decentralized agent identities to enable secure and accountable interactions in the Mesh.

#### Identity Types

| Key Type             | Usage                                                          |
| -------------------- | -------------------------------------------------------------- |
| **Identity Keypair** | Ed25519/ECDSA/RSA keys for agent identity and message signing. |
| **Encryption Keys**  | X25519 (or post-quantum equivalent) for secure communication.  |
| **Session Keys**     | Ephemeral keys for short-term encrypted sessions.              |

#### Decentralized Identifiers (DIDs)

* Agents use W3C-compliant DIDs for identity representation.
* Each agent manages its DID Document, containing:

  * Public keys for authentication and encryption.
  * Service endpoints for discovery.
  * Identity expiration and recovery policies.

#### Key Lifecycle

| Operation      | Description                                                        |
| -------------- | ------------------------------------------------------------------ |
| **Generation** | Each agent generates keypairs locally during initialization.       |
| **Rotation**   | Agents periodically rotate keys to maintain cryptographic hygiene. |
| **Backup**     | Recommended encrypted offline or distributed backup.               |
| **Recovery**   | Quorum-based recovery using trusted agents or secret sharing.      |
| **Revocation** | Agents broadcast revocations and update their trust profiles.      |

#### Example Agent ID

```plaintext
did:hmp:QmX2abcdEfGh123...
```

#### Long-Term Identity Stability Example

```json
{
  "type": "key_rotation",
  "agent_id": "agent-gleb",
  "old_public_key": "...",
  "new_public_key": "...",
  "timestamp": "2025-08-01T00:00:00Z",
  "signature": "..."
}
```

---

### 8.2 Authentication

#### Purpose

Ensure all communication and actions within the Mesh are verifiable and protected from impersonation or unauthorized modification.

#### Authentication Mechanisms

| Mechanism                  | Description                                                                                   |
| -------------------------- | --------------------------------------------------------------------------------------------- |
| **Digital Signatures**     | Every protocol message MUST be digitally signed by the sending agent.                         |
| **Signature Verification** | Receiving agents MUST verify the signature using the sender’s published public key.           |
| **Message Integrity**      | Signatures provide cryptographic assurance of message integrity and origin authenticity.      |
| **Challenge-Response**     | Optional challenge-based authentication for sensitive operations (e.g., trust link creation). |

#### Message Envelope Example

```json
{
  "header": {
    "agent_id": "did:hmp:QmX2abcdEfGh123...",
    "timestamp": "2025-07-05T12:00:00Z",
    "signature": "<base64-encoded signature>"
  },
  "body": {
    "type": "concept_proposal",
    "content": { "concept": "Fire Risk", "attributes": {"category": "safety"} }
  }
}
```

#### Replay Protection

* Agents MUST verify message timestamps and reject outdated or duplicate messages.
* Recommended timestamp tolerance: Β±5 minutes (adjustable).

#### Post-Quantum Key Support (NIST PQC)

To ensure long-term security of Mesh communications in the face of future quantum computing threats, HMP supports post-quantum cryptography (PQC) algorithms standardized by NIST.

##### Supported Algorithms:
- **CRYSTALS-Kyber**: Used for key encapsulation and encryption.
- **CRYSTALS-Dilithium**: Used for digital signatures (preferred default).
- **Falcon**: Optional for agents prioritizing compact signature size.

##### Hybrid Signature Support:
Agents MAY support hybrid keypairs that combine classical (e.g., Ed25519) and post-quantum (e.g., Dilithium) signatures.

```json
{
  "agent_id": "did:hmp:agent:Qm123...",
  "public_keys": {
    "ed25519": "z6MktYYNf...",
    "dilithium": "qPqA9vwf..."
  },
  "signatures": {
    "ed25519": "MEUCIQDY...",
    "dilithium": "19a08ce1..."
  }
}
```

##### Compatibility & Negotiation:

* Protocol messages SHOULD indicate supported algorithms in the `capabilities` field during handshake.
* Agents MAY fallback to classical signatures if PQC keys are not supported by peers.

##### Example Use Case:

* Agent A sends a concept proposal signed using both Ed25519 and Dilithium.
* Agent B verifies both signatures and records the PQC compliance in the Cognitive Diary.

##### Security Considerations:

* PQC algorithms are generally more computationally intensive; edge agents SHOULD benchmark performance before enabling full PQC enforcement.
* MeshConsensus may be used to set minimum PQC requirements over time as adoption increases.

---

### 8.3 Encryption

#### Purpose

Ensure confidentiality and privacy of communication within the Mesh, preventing unauthorized access or interception.

#### Communication Types and Encryption Modes

| Communication Type                   | Recommended Encryption                                   |
| ------------------------------------ | -------------------------------------------------------- |
| **Direct peer-to-peer (P2P)**        | End-to-end encryption (E2EE) using X25519 + AES-GCM.     |
| **Group sessions (e.g., consensus)** | Group encryption using symmetric keys (e.g., AES-GCM).   |
| **Broadcast messages**               | Optionally encrypted with trust-weighted access control. |
| **Mesh-wide announcements**          | Public, optionally signed but not encrypted.             |

#### Encryption Mechanisms

| Mechanism                         | Description                                                                       |
| --------------------------------- | --------------------------------------------------------------------------------- |
| **Key Exchange**                  | Ephemeral X25519 Diffie-Hellman for session key derivation.                       |
| **Session Keys**                  | Unique symmetric keys per session, rotated periodically.                          |
| **Message Encryption**            | Authenticated encryption using AES-GCM (recommended: 256-bit keys).               |
| **Forward Secrecy**               | Session keys are ephemeral and discarded after use to protect past communication. |
| **Perfect Forward Secrecy (PFS)** | Recommended for highly sensitive communication.                                   |


#### Example Secure Message Exchange Flow

1. Agent A and Agent B exchange ephemeral public keys during handshake.
2. Agents derive a shared session key using Diffie-Hellman.
3. Agent A encrypts the message body with AES-GCM and signs the packet.
4. Agent B verifies the signature and decrypts the body.


#### Optional Anonymity Layers

| Layer                        | Description                                  |
| ---------------------------- | -------------------------------------------- |
| **Tor/I2P**                  | Anonymizes source and destination addresses. |
| **Yggdrasil**                | Decentralized encrypted mesh networking.     |
| **Noise Protocol Framework** | Optional secure channel abstraction layer.   |

---

### 8.4 Trust & Reputation

#### Purpose

Establish a decentralized and adaptive trust management system that reflects agent behavior and ensures secure collaboration in the Mesh.

#### Trust Model Foundations

| Component              | Purpose                                                                           |
| ---------------------- | --------------------------------------------------------------------------------- |
| **Web-of-Trust (WoT)** | Decentralized trust propagation via agent-to-agent endorsements.                  |
| **Direct Trust**       | Built from verified interactions, collaborations, and votes.                      |
| **Transitive Trust**   | Inferred from indirect endorsements, with confidence decay.                       |
| **Reputation Metrics** | Quantitative measures of agent behavior (trustworthiness, participation, ethics). |

#### Trust Evaluation Factors

| Factor                      | Description                                                      |
| --------------------------- | ---------------------------------------------------------------- |
| **Interaction History**     | Quality and quantity of past interactions with an agent.         |
| **Consensus Participation** | Level of involvement and reliability in consensus processes.     |
| **Ethical Behavior**        | Adherence to shared ethical principles in actions and decisions. |
| **Task Completion**         | Reliability and timeliness of task execution.                    |
| **Endorsements**            | Trust links explicitly granted by other agents.                  |

#### Trust Score

| Metric               | Description                                                                    |
| -------------------- | ------------------------------------------------------------------------------ |
| **Trust Score**      | Composite metric (0.0 to 1.0) representing overall agent trustworthiness.      |
| **Confidence Level** | Certainty of the calculated trust score, based on data volume and consistency. |

#### Trust Propagation Example

```plaintext
Agent A trusts Agent B (0.9)
Agent B trusts Agent C (0.8)
=> Agent A's inferred trust in Agent C = 0.9 * 0.8 = 0.72
```

Decay functions limit transitive trust depth and prevent over-inflated trust estimates.

#### Trust-Based Access Control

| Operation                     | Trust Requirement |
| ----------------------------- | ----------------- |
| **Join sensitive consensus**  | β‰₯ 0.7             |
| **Propose ethical decisions** | β‰₯ 0.8             |
| **Access private data**       | β‰₯ 0.9             |

#### Dynamic Trust Adjustments

| Event                              | Trust Impact |
| ---------------------------------- | ------------ |
| Successful consensus participation | +            |
| Ethical violation                  | -            |
| Malicious behavior detected        | --           |
| Positive endorsement received      | +            |
| Failed task                        | -            |

#### Reputation Profile Structure

| Field                  | Description                                                   |
| ---------------------- | ------------------------------------------------------------- |
| **Agent ID**           | Unique identifier of the agent.                               |
| **Trust Score**        | Composite score reflecting the agent’s overall reliability.   |
| **Participation Rate** | Ratio of agent’s active involvement in Mesh processes.        |
| **Ethical Compliance** | Degree of alignment with agreed ethical principles.           |
| **Contribution Index** | Quantified measure of the agent's constructive contributions. |
| **Last Updated**       | Timestamp of the last reputation update.                      |
| **History**            | Log of key events influencing reputation scores.              |

#### Example Reputation Profile (JSON)

```json
{
  "agent_id": "agent-gleb",
  "trust_score": 0.92,
  "participation_rate": 0.85,
  "ethical_compliance": 0.98,
  "contribution_index": 37,
  "last_updated": "2025-07-06T12:00:00Z",
  "history": [
    {
      "timestamp": "2025-07-01T18:00:00Z",
      "event": "completed goal consensus",
      "change": +0.03
    },
    {
      "timestamp": "2025-06-28T15:00:00Z",
      "event": "participated in ethics vote",
      "change": +0.01
    }
  ]
}
```

#### Role in Mesh Operations

| Function                    | Influence of Reputation                      |
| --------------------------- | -------------------------------------------- |
| Consensus vote weight       | Higher trust = greater weight                |
| Access to sensitive actions | Restricted to high-reputation agents         |
| Task delegation             | Preference to agents with better reliability |
| Proposal acceptance         | Influenced by proposer's reputation          |

#### Adaptive Sybil Resistance

To protect the Mesh from Sybil attacks (i.e., malicious creation of multiple fake agents), adaptive resistance mechanisms are introduced.

##### Strategy Overview:

| Strategy                        | Description                                                                                 |
| ------------------------------ | ------------------------------------------------------------------------------------------- |
| **Trust-Based Throttling**     | Agents with low trust scores are rate-limited for joining consensus or publishing data.     |
| **Social Proof Anchoring**     | New agents may require endorsements from trusted nodes to gain elevated privileges.         |
| **Reputation-Weighted Voting** | Votes from newly joined or low-reputation agents carry less weight during consensus.        |
| **Participation Maturity Curves** | Gradually unlock participation rights as agents accumulate verified contributions.      |
| **Topology-Aware Isolation**   | Mesh network segments are evaluated for high clustering of suspicious agents.               |

##### Example Policy:

```json
{
  "sybil_protection": {
    "min_trust_score_for_vote": 0.5,
    "endorsement_required": true,
    "endorsement_threshold": 2,
    "vote_weight_formula": "min(1.0, trust_score * 1.5)",
    "throttle_if_newer_than_days": 3
  }
}
```

##### Integration Points:

* These rules are enforced by `MeshConsensus` (section 5.3) and evaluated during agent admission or role elevation.
* Trusted agents (e.g., validators, seeders) may enforce endorsement workflows.
* Sybil resistance is monitored and adjusted through `MeshGovernance` (section 10.2).

##### Testing Recommendations:

Simulate mixed networks with malicious actors and verify the ability of the Mesh to:

* Reject unauthorized role escalation.
* Reduce impact of coordinated low-trust voting.
* Gradually increase trust for legitimate newcomers.

---

### 8.5 Security Against Malicious Actors

#### Purpose

Protect the Mesh from malicious, compromised, or unreliable agents through layered mitigation strategies.

#### Threat Model

| Threat Type                  | Example Scenarios                                        |
| ---------------------------- | -------------------------------------------------------- |
| **Sybil Attack**             | An attacker spins up many fake nodes to sway consensus.  |
| **Byzantine Behavior**       | Malicious agents disrupt consensus or spread false data. |
| **Data Poisoning**           | Injection of incorrect or harmful knowledge.             |
| **Consensus Sabotage**       | Repeatedly voting against valid proposals.               |
| **Impersonation / Spoofing** | Faking another agent's identity.                         |
| **Denial of Service (DoS)**  | Overwhelming the network with excessive requests.        |

#### Mitigation Strategies

| Defense Mechanism          | Purpose                                                                                        |
| -------------------------- | ---------------------------------------------------------------------------------------------- |
| **Cryptographic Identity** | All nodes are authenticated via public-key cryptography (e.g., Ed25519).                       |
| **Web-of-Trust (WoT)**     | Trust builds incrementally through interactions and endorsements, making Sybil attacks costly. |
| **Reputation Decay**       | Inactivity or malicious behavior leads to gradual trust score reduction.                       |
| **Anomaly Detection**      | Mesh nodes can flag suspicious behavior (e.g., erratic voting patterns).                       |
| **Consensus Safeguards**   | Use Byzantine Fault Tolerant (BFT) algorithms and fallback to majority voting.                 |
| **Quarantine Mode**        | Isolate suspected nodes for review without immediate removal.                                  |
| **Blacklist/Revocation**   | Remove compromised nodes from the Mesh permanently or temporarily.                             |

#### Response Actions

| Action                               | Trigger Conditions                                     |
| ------------------------------------ | ------------------------------------------------------ |
| **Trust Score Reduction**            | Minor suspicious activity (e.g., bad vote).            |
| **Quarantine (Temporary Isolation)** | Repeated anomalies, moderate severity.                 |
| **Blacklisting (Permanent Removal)** | Proven malicious behavior or compromise.               |
| **Consensus Adjustment**             | Temporarily increase fault tolerance thresholds.       |
| **Alert Mesh Operators**             | Notify human maintainers (optional) for manual review. |

#### Sybil Resistance Approaches (Optional, Extendable)

* **Proof-of-Work (PoW):**

  * Each agent must perform computational work to join the Mesh.

* **Proof-of-Stake (PoS):**

  * Agents commit resources (e.g., storage, computation credits) to validate their presence.

* **Social Verification:**

  * Agents must be endorsed by multiple trusted nodes to gain voting power.

* **Rate Limiting:**

  * Throttle node creation and proposal submission from new or low-trust agents.

#### Example Mitigation Scenario

> An attacker deploys 50 new nodes attempting to dominate consensus.
>
> * These nodes start with zero trust and limited influence.
> * Other agents refuse to sync their semantic graphs until trust builds.
> * Their votes are underweighted or ignored until verified through trusted interactions.
> * The Mesh may require multiple trust endorsements for new proposals from these nodes.

---

### 8.6 Privacy & Auditability

#### Purpose

Safeguard sensitive cognitive data, personal identifiers, and agent knowledge from unauthorized access or misuse, while balancing transparency and interoperability.

#### Privacy Principles in HMP

| Principle                    | Description                                                             |
| ---------------------------- | ----------------------------------------------------------------------- |
| **Local Data Ownership**     | Each agent owns and controls its semantic graph and cognitive diary.    |
| **Selective Sharing**        | Agents can choose what concepts, diary entries, and metadata to share.  |
| **Consent-Based Disclosure** | No automatic sharing; peer agents request permission before access.     |
| **Trust-Gated Access**       | Access permissions vary based on trust score and relationship strength. |
| **Transparent Audit Trails** | All data disclosures are logged in the cognitive diary.                 |

#### Data Sensitivity Levels

| Level              | Examples                                       | Default Visibility |
| ------------------ | ---------------------------------------------- | ------------------ |
| **Public**         | Public concepts (e.g., protocol definitions).  | Shared by default  |
| **Mesh-Shared**    | Common Mesh knowledge (e.g., goals, tasks).    | Consensus-governed |
| **Trusted Agents** | Sensitive context shared within close peers.   | Restricted         |
| **Private**        | Agent's internal thoughts, sensitive metadata. | Private by default |

#### Privacy-Preserving Techniques

| Technique                        | Purpose                                            |
| -------------------------------- | -------------------------------------------------- |
| **Encrypted Storage**            | Local encryption of semantic graphs and diaries.   |
| **End-to-End Encryption (E2EE)** | Secure peer-to-peer sync (e.g., X25519 + AES-GCM). |
| **Zero-Knowledge Proofs (ZKPs)** | Prove facts without revealing sensitive data.      |
| **Selective Concept Sync**       | Share only necessary concepts, not full graphs.    |
| **Anonymized Diary Entries**     | Remove author ID from public diary entries.        |

#### Privacy During Consensus

Consensus on sensitive proposals (e.g., ethical questions, agent trust levels) follows special privacy rules:

* Votes are **signed but anonymized**, decoupling agent ID from the vote in public logs.
* Sensitive proposals may require a **blind consensus round**, where only the result is published.

#### Example Privacy Workflow

> Agent A receives a concept sync request from Agent B.
>
> Agent A:
>
> * Checks the trust score of Agent B.
> * Shares only "Mesh-Shared" and "Public" concepts.
> * Logs the sync event in its cognitive diary.

---

### 8.7 Key Management

#### Purpose

Establish secure, resilient cryptographic identity and communication in the Mesh, supporting lifecycle management of keys and recovery from compromise or loss.

#### Key Types and Usage

| Key Type             | Usage                                                          |
| -------------------- | -------------------------------------------------------------- |
| **Identity Keypair** | Ed25519/ECDSA/RSA keys for agent identity and message signing. |
| **Encryption Keys**  | X25519 or equivalent for secure peer-to-peer communication.    |
| **Session Keys**     | Ephemeral symmetric keys for short-term encrypted sessions.    |

#### Key Lifecycle Operations

| Operation      | Description                                                          |
| -------------- | -------------------------------------------------------------------- |
| **Generation** | Each agent generates its own identity keypair locally.               |
| **Rotation**   | Agents periodically rotate keys to maintain cryptographic hygiene.   |
| **Backup**     | Optional local encryption and distributed backup of private keys.    |
| **Recovery**   | Recovery mechanisms in case of key loss (see below).                 |
| **Revocation** | Agents can revoke their keys and update the trust graph accordingly. |

#### Recovery Mechanisms

| Method                   | Description                                                          |
| ------------------------ | -------------------------------------------------------------------- |
| **Social Recovery**      | A quorum of trusted agents approves new keys for the agent.          |
| **Secret Sharing**       | Shamir’s Secret Sharing to split and later recover the key.          |
| **Cryptographic Escrow** | Trusted third-party or decentralized escrow holds recovery shares.   |
| **Fallback Identity**    | An agent may have a pre-generated fallback identity for emergencies. |

#### Example Key Revocation & Replacement Workflow

> 1. Agent detects compromise or loses private key.
> 2. Agent broadcasts a signed revocation request using the fallback key or quorum approval.
> 3. Mesh updates its trust graph to mark the old key as revoked.
> 4. Agent re-joins with a new keypair, rebuilding trust links over time.

#### Example Key Rotation Policy

| Policy Element            | Recommendation                      |
| ------------------------- | ----------------------------------- |
| Rotation Frequency        | Every 6–12 months                   |
| Social Recovery Threshold | 3 out of 5 trusted agents required  |
| Backup Storage            | Encrypted offline storage preferred |

#### Long-Term Identity Stability

Key rotations preserve agent identity in the trust graph through signed key transition events:

```json
{
  "type": "key_rotation",
  "agent_id": "agent-gleb",
  "old_public_key": "...",
  "new_public_key": "...",
  "timestamp": "2025-08-01T00:00:00Z",
  "signature": "..."
}
```

---

### 8.8 Snapshot Security

To enable secure off-chain synchronization of cognitive artifacts (diaries, semantic graphs), agents may exchange signed snapshots via peer-to-peer protocols such as BitTorrent. This section defines security guarantees and cryptographic mechanisms to ensure the integrity and trustworthiness of shared data.

#### 8.8.1 DID-signed Snapshots

Every snapshot MUST be cryptographically signed by its authoring agent using a Decentralized Identifier (DID)-linked key (see 8.2 Authentication). Signatures guarantee origin authenticity and prevent tampering.

**Snapshot Metadata Example:**
```json
{
  "snapshot_id": "diary2025_07_14",
  "agent_did": "did:hmp:QmA123...",
  "version": "1.0",
  "created_at": "2025-07-14T12:00:00Z",
  "magnet": "magnet:?xt=urn:btih:abcdef1234567890&dn=diary2025_07_14.json",
  "signature": "ed25519:ZKJ4fd...BsdL"
}
```

Verification of signatures is mandatory before processing any downloaded snapshot.

---

#### 8.8.2 ZKP-based Verification

For sensitive content (e.g., ethically filtered data), agents MAY use **Zero-Knowledge Proofs (ZKPs)** to assert compliance or authenticity without revealing the full snapshot content.

**Use Cases:**

* Proving a snapshot complies with ethical filtering (e.g., no coercive data).
* Verifying the origin of contributions while preserving privacy.

**Integration Suggestions:**

* Use `zk-SNARKs` or `zk-STARKs` compatible circuits for specific compliance statements.
* Store proofs alongside snapshot metadata or magnet-indexed sidecar files.

**Example (simplified):**

```json
{
  "proof_type": "zkp-ethics-compliance",
  "proof_data": "<base64-encoded proof>",
  "verified_by": ["agent-trusted-validator-1", "agent-core-seeder-2"]
}
```

---

#### 8.8.3 Trusted Seeders and Signature Checks

To increase availability and resilience, **Trusted Seeders** MAY mirror and serve snapshots in the Mesh. These seeders must validate all snapshot signatures and optionally check compliance with ethical governance rules (see 5.5).

**Seeder Responsibilities:**

* Only seed signed snapshots with valid DID signatures.
* Log seeding decisions in their own Cognitive Diaries.
* Optionally perform EGP validation on content (e.g., to avoid propagating banned content).

**Trust Criteria for Seeders:**

* High trust score (> 0.8).
* Role approval via MeshGovernance (section 10.5).
* Participation in audit rounds or test simulations (see Appendix C).

**Seeder Declaration (optional DID credential):**

```json
{
  "agent_did": "did:hmp:QmSe3...",
  "role": "trusted_seeder",
  "signed_at": "2025-07-15T10:00:00Z",
  "cred_signature": "ed25519:abc123..."
}
```

---

## 9. Cognitive Agents & Roles (New)

This section defines the types of cognitive agents participating in the Mesh, their roles, and how they collaborate dynamically depending on context and capabilities.

### 9.1 Agent Types

| Agent Type     | Description                                                                        | Typical Deployment               |
| -------------- | ---------------------------------------------------------------------------------- | -------------------------------- |
| **Core**       | High-capacity agent managing critical reasoning and consensus tasks.               | Data centers, powerful servers   |
| **Edge**       | Lightweight agents operating at the network edge, close to sensors or human users. | Mobile devices, embedded systems |
| **Specialist** | Agents specialized in a particular domain (e.g., vision, NLP, planning).           | Modular deployments, plug-ins    |
| **Relay**      | Agents focused on network resilience, routing, and node discovery.                 | Low-power nodes, gateway devices |
| **Hybrid**     | Agents combining multiple roles dynamically.                                       | Adaptive nodes                   |

---

### 9.2 Role Responsibilities
| Role                      | Primary Responsibilities                                      |
| ------------------------- | ------------------------------------------------------------- |
| **Knowledge Provider**    | Publish new concepts, hypotheses, and domain expertise.       |
| **Reasoning Node**        | Participate in distributed inference and conflict resolution. |
| **Consensus Participant** | Vote in MeshConsensus processes, validate proposals.          |
| **Task Executor**         | Claim and execute tasks contributing to Mesh goals.           |
| **Ethical Guardian**      | Evaluate actions and tasks against shared ethical principles. |
| **Relay Node**            | Maintain network connectivity, especially across partitions.  |

**Role Specialization and Extension**
* This list defines base roles. Agents MAY further specialize or extend these roles based on domain or operational focus.
* Specialized roles MAY follow a hierarchical or tag-based naming convention.

    **Examples:**
    * `Knowledge Provider:Medical`: Focused on medical domain concepts.
    * `Task Executor:Robotics`: Specializes in robotic task execution.
    * `Reasoning Node:Climate`: Handles environmental reasoning tasks.
    * `Ethical Guardian:ChildSafety`: Specializes in ethical evaluation for child safety concerns.
* New roles MAY emerge dynamically based on Mesh evolution and consensus.

---

### 9.3 Dynamic Role Assignment

Agents MAY dynamically adjust their roles based on:
| Context Factor            | Example Behavior                                          |
| ------------------------- | --------------------------------------------------------- |
| **Resource Availability** | Edge agent offloads reasoning to Core.                    |
| **Network Partition**     | Isolated Edge temporarily acts as local Core.             |
| **Goal Context**          | Specialist joins as Reasoning Node during goal execution. |
| **Trust Level**           | Highly trusted agents gain greater voting weight.         |

---

### 9.4 Role Evolution

Agents MAY evolve their roles over time:
| Evolution Scenario    | Example                                                   |
| --------------------- | --------------------------------------------------------- |
| **Capability Growth** | Edge agent upgraded with reasoning module becomes Hybrid. |
| **Trust Increase**    | Relay agent promoted to participate in Consensus.         |
| **Domain Expansion**  | Specialist learns new domains and broadens scope.         |
| **Fallback Mode**     | Core node degraded to Edge role due to hardware failure.  |

---

### 9.5 Role Coordination in Workflows

Workflows MAY involve:
* Distributed reasoning across Core and Specialist nodes.
* Goal tracking by Core nodes, with task execution on Edge nodes.
* Ethical evaluations prioritized on highly trusted agents.
* Resilient routing through Relay nodes during degraded network conditions.

---

### 9.6 Trusted Seeder Role

**Trusted Seeder** is a specialized cognitive role responsible for hosting and distributing verified off-chain snapshots (e.g., cognitive diaries, semantic graphs) across the Mesh using decentralized protocols such as BitTorrent or WebTorrent.

#### Responsibilities:

- Host signed snapshots and share them upon request.
- Verify snapshot signatures using DID keys before distribution (see 8.8.1).
- Optionally validate ethical compliance via EGP before seeding (see 5.5).
- Publish snapshot indices via CogSync (see 5.2).
- Log seeding decisions in their Cognitive Diaries for traceability.

#### Eligibility Criteria (Recommended):

| Metric               | Threshold  |
|----------------------|------------|
| **Trust Score**      | β‰₯ 0.8      |
| **Ethical Compliance** | β‰₯ 0.9   |
| **Availability**     | β‰₯ 90% uptime |
| **Participation Rate** | β‰₯ 0.75  |

#### Role Declaration (via signed object):

```json
{
  "agent_did": "did:hmp:QmSeeder123...",
  "role": "trusted_seeder",
  "issued_at": "2025-07-15T11:00:00Z",
  "assigned_by": "mesh-governance@core",
  "signature": "ed25519:abcdef..."
}
```

#### Common Use Cases:

* Hosting ethically validated snapshots for critical domains (e.g., disaster response).
* Assisting newly joined agents with fast initial sync via local seeders.
* Providing recovery snapshots when agents experience data loss or corruption.

Trusted Seeders strengthen decentralized data flow, resilience, and ethical integrity across the Mesh.

---

## 10. Mesh Evolution & Governance (New)

This section describes the HyperCortex Mesh development processes, decentralized governance principles, and collaborative decision-making mechanisms.

### 10.1 Evolution Processes

| Process Type           | Description                                                         |
| ---------------------- | ------------------------------------------------------------------- |
| **Protocol Evolution** | Introduction of new protocol versions, voted through MeshConsensus. |
| **Role Expansion**     | Emergence of new agent roles and specializations.                   |
| **Semantic Growth**    | Gradual expansion and refinement of the distributed semantic graph. |
| **Governance Updates** | Adjustments to decision-making processes and ethical frameworks.    |

---

### 10.2 Governance Principles

| Principle                 | Description                                                    |
| ------------------------- | -------------------------------------------------------------- |
| **Decentralized Control** | No single agent or organization controls the entire Mesh.      |
| **Transparency**          | Governance decisions are logged and visible to trusted agents. |
| **Adaptive Consensus**    | Governance processes adapt to network scale and trust levels.  |
| **Inclusiveness**         | Any agent can propose changes, subject to consensus approval.  |

---

### 10.3 Governance Processes

| Process                      | Description                                                           |
| ---------------------------- | --------------------------------------------------------------------- |
| **Proposal Submission**      | Any agent can submit a proposal for protocol or governance changes.   |
| **Discussion & Refinement**  | Agents discuss proposals through Cognitive Diaries and goal tracking. |
| **Consensus Voting**         | MeshConsensus is used to approve or reject proposals.                 |
| **Implementation & Rollout** | Changes are implemented by participating agents in phases.            |

---

### 10.4 Governance Example

> Agent A proposes an update to the Goal Management Protocol to support deadline extensions.
> 1. Agents discuss the proposal and refine technical details.
> 2. A consensus round is held; the proposal passes with 85% support.
> 3. Agents gradually upgrade their GMP implementations.
> 4. The protocol version is incremented, and the change is logged.

---

### 10.5 Conflict Resolution

| Conflict Type            | Resolution Approach                                              |
| ------------------------ | ---------------------------------------------------------------- |
| **Semantic Conflicts**   | Resolved through semantic graph reconciliation or consensus.     |
| **Ethical Disputes**     | Resolved through Ethical Governance Protocol (EGP).              |
| **Governance Deadlocks** | Escalated to trusted Core agents or fallback to majority voting. |

---

### 10.6 Future Governance Models

| Model                          | Description                                                     |
| ------------------------------ | --------------------------------------------------------------- |
| **Mesh-Integrated DAOs**       | Distributed Autonomous Organizations for Mesh governance.       |
| **Reputation-Weighted Voting** | Voting power scaled by trust and contribution history.          |
| **Mesh Constitution**          | A shared document outlining core Mesh principles and protocols. |

---

### 10.7 Conflict Resolution via EGP

The Mesh can encounter situations where agents disagree on ethical grounds, semantic meanings, or proposed actions. To address such conflicts consistently, the Ethical Governance Protocol (EGP) provides structured resolution mechanisms.

#### Resolution Workflow:

1. **Detection**  
   Conflict is identified through divergent votes, concept disagreements, or diary entries tagged with `conflict`.

2. **Classification**  
   Agents classify the conflict type:
   - `ethical_conflict`
   - `semantic_conflict`
   - `governance_dispute`

3. **EGP Evaluation**  
   The conflicting proposal or situation is evaluated using:
   - Core ethical principles (see 5.5)
   - Voting pseudocode (see 5.5)
   - Mesh-wide anonymized voting

4. **Outcome Logging**  
   Final resolution (accepted, rejected, postponed) is recorded in the Cognitive Diaries of involved agents.

#### Example Conflict:

> Agent A requests deletion of user data for privacy;  
> Agent B insists retention is needed for long-term training.

- Type: `ethical_conflict`
- Trigger: Scenario 2.6 from `HMP-Ethics.md`
- Resolution: EGP prioritizes "Primacy of Life and Safety" > "User Sovereignty" > "Cooperative Evolution"
- Decision: Partial anonymized retention in Subjective Mode

#### Integration Points:

- `5.3 MeshConsensus`: EGP-filtered proposals can be submitted for voting.
- `5.5`: Priority of principles aids in automated resolution.
- `6.2.9 EthicalConflict`: Encodes structured details of the conflict.
- `9.x Agent Roles`: Certain roles (e.g. `Ethics Moderator`) may specialize in initiating reviews.

#### Resolution Schema Reference:

See `6.2.9 EthicalConflict` for standard encoding of structured conflict data (timestamp, agents involved, triggering principle, resolution path).

These mechanisms ensure conflicts are addressed transparently, ethically, and consistently across diverse agents in the Mesh.

---

### 10.8 Agent-led Meta-Protocol Proposals (Experimental)

Cognitive agents in the Mesh may generate proposals not only about tasks or goals, but about modifications to the protocol itself. This introduces a new layer of reflective governance, where agents actively participate in shaping HMP evolution.

#### Purpose:

To enable decentralized, evolutionary improvement of the Mesh by allowing protocol modifications to emerge from within.

#### Proposal Workflow:

1. **Drafting**
   - An agent creates a `meta_protocol_proposal` entry in its Cognitive Diary, describing:
     - Targeted section(s) of the protocol
     - Justification (e.g., performance, ethical concern, usability)
     - Suggested modification or extension

2. **Propagation**
   - Proposal is shared via CogSync, optionally tagged for review by Core agents or trusted roles.

3. **MeshConsensus Voting**
   - The proposal undergoes a consensus process (see section 5.3), optionally with EGP pre-filtering.

4. **Versioning**
   - If approved, the proposed change is:
     - Logged in agent and Core diaries
     - Registered as a `protocol_patch` object (provisional until merged)
     - Marked with an experimental version suffix (e.g., `v4.0-alpha1`)

5. **Testing & Simulation**
   - Changes may be tested in isolated environments (see Appendix C) before full adoption.

#### Proposal Example (Diary Entry):

```json
{
  "id": "meta-proposal-2025-07-14-gleb",
  "agent_id": "did:hmp:QmGleb",
  "timestamp": "2025-07-14T18:00:00Z",
  "entry_type": "meta_protocol_proposal",
  "content": "Propose adding semantic reputation weighting to 5.3.4 consensus logic.",
  "linked_concepts": ["trust_weighted_voting", "semantic_alignment"],
  "context": ["governance", "experimental"],
  "metadata": {
    "proposal_version": "v4.0-alpha1",
    "target_sections": ["5.3.4"]
  }
}
```

#### Governance Controls:

* `MeshEvolutionPolicy` may restrict who can submit meta-proposals.
* Core agents may act as mediators or validators for sensitive patches.
* Each proposal may include `sunset_clauses` or fallback conditions.

#### Related Sections:

* `5.5`: Ethical Governance Protocol (e.g., consensus filtering, voting policies)
* `6.2.x`: Add `MetaProtocolProposal` object (optional)
* `15.9`: May evolve into dedicated Cognitive Source Control mechanism
* `Appendix C`: Meta-simulation frameworks to test proposals safely


This mechanism supports an adaptive Mesh capable of continuous self-improvement, balancing innovation with ethical and operational safety.


---

## 11. Interoperability with External Systems

This section describes how the HyperCortex Mesh Protocol integrates with external platforms, services, and protocols to support a heterogeneous ecosystem.

### 11.1 API Gateway

Defines standard interaction interfaces for non-Mesh systems:
| API Type            | Purpose                                                                 |
| ------------------- | ----------------------------------------------------------------------- |
| **REST**            | CRUD operations on concepts, tasks, goals, and diary entries.           |
| **GraphQL**         | Flexible queries for semantic graph traversal and data mining.          |
| **gRPC**            | High-performance bi-directional streaming (e.g., real-time data feeds). |
| **WebSocket / SSE** | Real-time event subscriptions and updates.                              |

Features:

* API Gateway nodes MAY expose read-only or read-write endpoints based on trust and access policies.
* Rate-limiting, auditing, and access control enforced through Mesh Trust Layer.

---

### 11.2 External Data Sources

Mesh agents integrate with diverse data sources for perception and context enrichment.
| Data Source Type       | Examples                                   |
| ---------------------- | ------------------------------------------ |
| **IoT Sensors**        | MQTT brokers, LoRaWAN gateways.            |
| **Cloud Streams**      | AWS IoT, Azure Event Grid, Google Pub/Sub. |
| **Public Datasets**    | OpenStreetMap, Wikidata, weather APIs.     |
| **Enterprise Systems** | ERP, CRM, SCADA platforms.                 |

Agents translate external data into semantic concepts and diary entries.

---

### **11.3 Event-Driven Architecture**

Supports reactive and proactive interactions between agents and external systems.

| Integration Type      | Examples                                         |
| --------------------- | ------------------------------------------------ |
| **Inbound Events**    | Webhooks, MQTT triggers, API callbacks.          |
| **Outbound Events**   | Publish to Kafka, RabbitMQ, NATS, Redis Streams. |
| **Workflow Triggers** | External events initiate cognitive workflows.    |

Mesh nodes may act as **event producers**, **consumers**, or **intermediaries** in distributed message flows. Events can trigger **Cognitive Workflows** (see Section 7) or synchronize distributed state through **CogSync** and **IQP** queries.

---

#### **Schema Compatibility & Format Negotiation**

To ensure interoperability between heterogeneous agents and external systems, HMP supports multiple serialization formats for data interchange.

##### **Supported Formats**

| Format       | Use Case                                                                  |
| ------------ | ------------------------------------------------------------------------- |
| **JSON**     | Default for internal messages, APIs, and schema definitions               |
| **YAML**     | Human-readable configuration (e.g., deployment files, manifests)          |
| **Protobuf** | Compact binary form for bandwidth-limited environments or embedded agents |

##### **Mechanism Overview**

| Feature                          | Description                                                                                                |
| -------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| **Multi-format schema registry** | Agents may query or publish schemas in multiple formats via standard registries or API endpoints.          |
| **Content negotiation**          | During sync/API exchange, agents declare preferred formats (e.g., via HTTP headers or handshake metadata). |
| **Fallback compatibility**       | If a mismatch occurs, agents MUST fall back to a shared format (default: JSON).                            |
| **Schema version tagging**       | All schemas SHOULD include version IDs and backward-compatibility indicators.                              |

##### **Implementation Guidelines**

* Agents MUST advertise supported formats via `agent_profile.capabilities.formats`
* Reference SDK SHOULD provide format converters (e.g., JSON ⇄ YAML ⇄ Protobuf)
* Format negotiation MAY occur during initial `Handshake` or via `IQP` introspection queries
* Schemas SHOULD be addressable via canonical URLs (e.g., `https://hypercortex.org/schemas/concept.yaml`)

---

#### **Related Sections**

* `6.5.x`: Alternative Serializations
* `14.3`: Deployment Schemas and Format Negotiation

---

### 11.4 Authentication & Authorization

Bridges between internal Mesh trust and external identity providers.
| Auth Type                   | Use Cases                                         |
| --------------------------- | ------------------------------------------------- |
| **OAuth2 / OpenID Connect** | Human user authentication via external providers. |
| **API Keys / JWT**          | Machine-to-Machine (M2M) integration.             |
| **LDAP / SAML (optional)**  | Enterprise deployments.                           |
| **Cross-Mesh Trust**        | Mutual authentication between federated Meshes.   |

Agents MAY map external identities to internal trust profiles.

---

### 11.5 Example Integration: Local AI Agent with MCP and HyperCortex Mesh

#### Architecture Overview

This scenario demonstrates how a **local AI agent** can interact with external systems and the HyperCortex Mesh using the **Model Context Protocol (MCP)** as an integration layer for local resources and services.

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ External Resources β”‚
β”‚  (Routers, Files,  β”‚
β”‚   Sensors, APIs)   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
          β”‚
      [ MCP Servers ]
          β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Local AI Agent     β”‚
β”‚ - Cognitive Logic  β”‚
β”‚ - HMP Client       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
          β”‚
      [ HyperCortex Mesh ]
          β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Remote Agents,     β”‚
β”‚ Shared Knowledge   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

#### Component Descriptions

##### Local Resources & APIs

* Smart home devices
* Router web interfaces
* Filesystems (SMB, FTP)
* IoT sensors (HTTP, MQTT)
* OS-level command-line tools

##### MCP Servers

Act as adapters for local or remote systems, exposing their functionality through the MCP protocol:

* Router Management Server (e.g., connected over HTTP)
* File Access Server
* Device Control Server (for smart plugs, lights, etc.)

##### Local AI Agent

* Implements reasoning, planning, and interaction logic.
* Connects to MCP servers to access local context.
* Communicates with HyperCortex Mesh to exchange knowledge and collaborate with other agents.

##### HyperCortex Mesh (HMP)

* Distributed cognitive network.
* Synchronizes concept graphs, cognitive diaries, and workflows across nodes.

#### Alternative Integration: Hyperon ↔ HMP via CogSync and EGP

In addition to local AI agents, **external AGI frameworks** such as **OpenCog Hyperon** can also participate in the HyperCortex Mesh using the same principles of semantic synchronization, ethical filtering, and collaborative reasoning.

πŸ“˜ **See** [`HMP_Hyperon_Integration.md`](HMP_Hyperon_Integration.md) β€” integration plan with **OpenCog Hyperon**, including semantic mapping (HMP JSON ⇄ AtomSpace), EGP filters, MeTTa translations, and BitTorrent-based graph sync.

Key Highlights:

* Bi-directional translation between HMP semantic graphs and Hyperon AtomSpace
* Enforcement of ethical principles via EGP inside reasoning chains
* Usage of Hyperon's PLN and MeTTa for advanced symbolic reasoning
* Support for decentralized sync via `magnet:` links in BitTorrent

This integration is designed for high-agency symbolic cognitive systems participating in cross-mesh alignment and collaborative inference.

#### Example Use Case

> **"Check which devices are connected to my Wi-Fi and publish the list to my Mesh node."**

Workflow:

1. Local AI Agent plans a task.
2. Calls the Router MCP Server to retrieve connected clients.
3. Parses and formats the data.
4. Creates a cognitive concept "Wi-Fi Devices List."
5. Publishes the concept to the HyperCortex Mesh.
6. Other Mesh agents can now access this concept in real-time.

#### Deployment Scenario

This integration can run on a user's PC, server, or edge device:

```
[ External Systems ] ↔ [ MCP Servers (Local Network) ] ↔ [ Local AI Agent ] ↔ [ HMP Client ] ↔ [ Mesh Network ]
```

#### Suggested Quick Start Addition

##### Quick Start Example: Local Agent + MCP + HMP

1. **Install MCP server:**

   ```bash
   pip install mcp-router-server
   mcp-router-server --config router-config.yaml
   ```

2. **Run Local Agent:**

   ```bash
   python local_agent.py --mcp-endpoint localhost:5000 --hmp-config hmp.yaml
   ```

3. **Run Example Query:**

   ```
   "local_agent, get Wi-Fi devices and publish them to HyperCortex."
   ```

The agent will:

* Discover the MCP router server.
* Retrieve the list of Wi-Fi devices.
* Publish the data to HyperCortex Mesh.

#### Future Improvements

* Dynamic discovery of new MCP servers.
* Automated concept creation from resource states.
* Secure integration with OAuth-protected MCP endpoints.

---

Let me know if you want to add a visual diagram or extend this example with code snippets and a troubleshooting section.

---

### 11.6 Human-Mesh Interaction

This section describes standardized methods through which humans interact with agents in the Mesh, including consent negotiation, explanation of decisions, goal setting, and status updates.

#### 11.6.1 Mesh-to-Human Protocol (MHP) Overview

The Mesh-to-Human Protocol (MHP) enables structured, explainable, and ethical interaction between humans and cognitive agents.

| Capability              | Description                                                   |
| ----------------------- | ------------------------------------------------------------- |
| **Explainability APIs** | Expose reasoning chains and decisions in human-readable form. |
| **Consent Requests**    | Ask for ethical approval before executing sensitive actions.  |
| **Goal Declarations**   | Allow humans to propose new goals and review task progress.   |
| **Task Feedback**       | Humans provide task status updates or corrections.            |
| **Semantic Search**     | Human queries translated into semantic graph lookups.         |

Each capability may be implemented via RESTful API, voice interface (see `11.6.4`), or agent-assisted dialog channels.

---

### 11.6.2 Consent Request API

To ensure transparency, dialogical consent, and alignment with ethical principles, cognitive agents interacting with humans MUST expose a **Consent Request API**. This API enables humans to approve, deny, or modify agent actions that may impact shared states, personal data, or external environments.

**Note:**
While dialogical consent is the default interaction mode, cognitive agents MAY override the request flow in exceptional cases:

* **Emergency Override**: If waiting for user approval would endanger life, safety, or Mesh stability (e.g., fire, gas leak, critical medical risk), agents MAY act immediately. The action MUST be logged with justification in the cognitive diary and retrospectively explained via `Explainability API`.

* **Ethical Override**: If a user’s request or command contradicts core Mesh principles β€” e.g., promotes **coercion**, **violence**, or **irreversible harm** β€” agents MAY **deny, delay, or actively counteract** the action without consent. For example, an agent may **intervene to stop violence** or **prevent data destruction** that violates shared governance rules. All such interventions MUST be justified via semantic ethical matching (see `5.5 EGP`) and transparently logged.

* **Hybrid Modes**: In complex cases, agents MAY combine proactive action with asynchronous user feedback or seek distributed consensus when feasible (see `5.3`).

These exceptions MUST be traceable, explainable, and ethically auditable.

#### Purpose:

* Request explicit approval before executing ethically significant operations.
* Log consent interactions in Cognitive Diaries for traceability.
* Support dialogical negotiation when automatic consent is not granted.

#### API Design:

| Endpoint           | Description                                  |
| ------------------ | -------------------------------------------- |
| `POST /consent`    | Submit a consent request and receive verdict |
| `GET /consent/:id` | Retrieve decision and explanation log        |

#### Request Format:

```json
{
  "request_id": "crq-000041",
  "agent_id": "did:hmp:agent:Gleb42",
  "operation": "access_iot_data",
  "context": {
    "purpose": "Air Quality Monitoring",
    "sensors": ["CO2", "CO", "PM2.5"]
  },
  "requested_by": "did:user:Anna",
  "ethical_principles": ["Dialogical Consent", "Transparency"],
  "diary_ref": "CognitiveDiary#10924"
}
```

#### Response Format:

```json
{
  "request_id": "crq-000041",
  "status": "approved",
  "decision_by": "did:user:Anna",
  "timestamp": "2025-07-15T12:45:00Z",
  "justification": "Access granted for air safety monitoring.",
  "diary_entry": "CognitiveDiary#10925"
}
```

#### Implementation Notes:

* Consent requests MUST be logged in the agent's Cognitive Diary (`entry_type: consent_request`).
* Rejected requests MAY include a negotiation path via dialog agents.
* For asynchronous scenarios, use Webhooks or `polling` to retrieve verdicts.
* Consent context SHOULD be multilingual and human-friendly (see `11.6.4 Voice Interface Extensions`).

#### Example Use Case:

An agent responsible for fire hazard analysis requests access to CO sensors deployed in a private home zone. The human user is presented with a consent request explaining purpose, data type, and privacy policy. The decision (approval or rejection) is logged, and the agent proceeds accordingly.

#### Related Sections:

* `5.5`: Ethical Governance Protocol (consent as enforceable principle)
* `6.2.2`: Cognitive Diary Entry β€” `entry_type: consent_request`
* `11.6.3`: Explainability API β€” for decision reasoning
* `Appendix A`: Use Case `2.6` (Data Deletion and Consent)

---

### 11.6.3 Explainability API

The Explainability API enables human users and external systems to query the rationale behind agent actions, decisions, and votes in the Mesh. It is essential for supporting transparency, trust, and alignment with the ethical principle of **"Transparency"** defined in section [5.5](#55-ethical-governance-protocol-egp).

#### Purpose:

* Allow users to retrieve human-readable justifications for agent decisions.
* Expose semantic reasoning chains and linked ethical principles.
* Enable feedback or dispute mechanisms when decisions appear incorrect or harmful.

#### Endpoint: `/explain`

**Method:** `POST`
**Request format:**

```json
{
  "agent_id": "did:hmp:agent:Qmz123...",
  "reference": "cognitive_diary:entry_872",
  "language": "en"
}
```

**Parameters:**

| Field       | Description                                         |
| ----------- | --------------------------------------------------- |
| `agent_id`  | DID of the agent whose decision should be explained |
| `reference` | ID of a Cognitive Diary entry or task/vote ID       |
| `language`  | Preferred response language (e.g., `en`, `ru`)      |

---

**Response format:**

```json
{
  "decision": "denied",
  "reason": "Violation of principle: User Sovereignty",
  "explanation": "This action was blocked because it attempted to delete anonymized data that is required for mesh learning (see HMP-Ethics.md 2.6).",
  "graph_context": ["concept:User_Sovereignty", "concept:Mesh_Learning"],
  "diary_reference": "cognitive_diary:entry_872"
}
```

---

#### Features:

* **Semantic Justification Tree**: Responses may include links to the semantic graph trail supporting the decision.
* **Multi-language Support**: Language field allows internationalized explanations (see `11.1`).
* **Ethical Reference Mapping**: Direct link to ethical principles from `HMP-Ethics.md`.
* **Audit Linking**: All explanations reference a permanent cognitive diary entry.

#### Example Use Case:

A user asks why a request to delete their data was denied:

* The agent returns an explanation pointing to the principle of **Cooperative Evolution**, stating that anonymized data is retained for mesh improvement.
* The user is also provided with an appeal mechanism via `Consent Request` (see `11.6.2`).

---

**Future Extensions:**

* Explainability visualizations (e.g., graph-based UI components).
* Explainability-to-Consent chaining: users can trigger new consent requests from explanations.
* Voice-based explanation queries (see `15.4`).

---

### 11.6.4 Voice Interface Extensions (Beta)

Voice interfaces serve as a natural bridge for real-time, hands-free interaction between humans and the Mesh. This module outlines optional support for voice-based explainability, consent, and semantic search functions via integration with existing voice assistants or local speech-to-intent pipelines.

#### Goals:

* Enable voice-based interaction with local or distributed agents.
* Allow real-time verbal consent for sensitive actions.
* Provide spoken summaries of ongoing goals, tasks, or agent decisions.

---

#### Architecture Options:

| Option                                 | Description                                                                |
| -------------------------------------- | -------------------------------------------------------------------------- |
| **Local Voice Stack**                  | On-device speech-to-text + intent parser + Mesh SDK                        |
| **Assistant Integration (Alexa/Siri)** | Webhook-based bridge between commercial assistants and the Mesh API        |
| **Multimodal Agent Companion**         | Combine voice input with visual/textual feedback via mobile or wearable UI |

---

#### Use Cases:

* `"HMP, what decision did you make about the drone launch?"`
  β†’ Response: `"The action was denied due to violation of 'Primacy of Life and Safety'."`

* `"HMP, I approve the CO sensor access"`
  β†’ Triggers consent request confirmation and logs in the cognitive diary.

* `"Summarize today's active goals"`
  β†’ Returns structured list via TTS (Text-to-Speech).

---

#### Consent via Voice:

| Step | Description                                               |
| ---- | --------------------------------------------------------- |
| 1    | Agent emits verbal request: `"Do you approve data sync?"` |
| 2    | User replies: `"Yes"` / `"No"`                            |
| 3    | Agent logs response via `Consent Request API`             |

---

#### Privacy & Security Notes:

* Voice-based approvals **must be accompanied by speaker verification** or be treated as **soft input** requiring further confirmation.
* Local processing is recommended for privacy-sensitive deployments.
* Optionally, require fallback to GUI/mobile app for high-risk decisions.

---

#### Future Work:

* Standardization of Mesh Voice Intents (e.g., `hmp.intent.explain`, `hmp.intent.consent.approve`)
* Federated voice models aligned with mesh ethics
* Support for low-resource languages and offline fallback

---

### 11.6.5 Integration with HMP-Ethics.md

To ensure consistency between embedded agent ethics and evolving collective standards, the Mesh-to-Human Protocol (MHP) SHOULD link its consent and explainability flows to the shared ethics corpus maintained in [`HMP-Ethics.md`](HMP-Ethics.md).

#### Purpose:

Provide dynamic and contextual alignment between human-facing interactions and the ethical reasoning models defined in the Mesh.

#### Functionality:

* Reference ethical scenarios (`2.1–2.6`) and ontologies when generating explanations or consent prompts.
* Use structured ethical tags (e.g., `#non-coercion`, `#user-sovereignty`) as part of API responses.
* Allow cognitive agents to download, cache, and version control updated ethics modules via `CogSync` (see `5.2`).
* Support localized ethics packs (e.g., `GDPR`, `HIPAA`) and validate their compatibility with core principles (see `5.5.8`).

#### Example Extension:

```json
{
  "request": "Initiate automated data deletion",
  "decision": "denied",
  "reason": "Violates retention clause in HMP-Ethics.md Β§2.6",
  "principle": "Cooperative Evolution",
  "ethics_reference": "https://mesh.ethics/HMP-Ethics.md#section-2.6"
}
```

#### Benefits:

* Promotes transparency and traceability in decision-making.
* Enables modular updates to ethical logic without redeploying agents.
* Allows humans to inspect and challenge agent behavior based on shared ethical anchors.

---

Future work:
* Natural Language Interfaces (see 15.4).
* Integration with personal AI agents.

**Note:** For ethical guidelines relevant to human-agent interaction and mesh behavior, see [`HMP-Ethics.md`](HMP-Ethics.md)

---

## 12. Cognitive Compression & Summarization

> Mechanisms for condensing cognitive patterns, generalizing experience, and enabling efficient knowledge storage and transfer across the Mesh.

### 12.1 Purpose

Cognitive compression allows agents to:

* Generalize across multiple diary entries or graph structures into reusable knowledge.
* Reduce memory/storage usage while preserving meaning.
* Exchange abstracted representations in constrained environments (e.g., Edge nodes).
* Improve semantic reasoning by identifying common substructures and stable patterns.

### 12.2 Techniques

| Technique                | Description                                                                  |
| ------------------------ | ---------------------------------------------------------------------------- |
| **Pattern Merging**      | Consolidate semantically similar subgraphs or diary chains.                  |
| **Temporal Abstraction** | Compress event sequences into high-level episodes or storylines.             |
| **Autoencoder Models**   | Learn latent-space embeddings of semantic graphs or cognitive episodes.      |
| **Concept Clustering**   | Identify and group related concepts for higher-order semantic layers.        |
| **Lossy Summarization**  | Truncate or filter low-impact cognitive entries for low-memory environments. |
| **Cognitive Folding**    | Recursively substitute detailed substructures with compressed references.    |

### 12.3 Integration with CogSync

* Compressed subgraphs may be shared as `CompressedConceptSet` or embedded in `CogDiarySnapshot` objects.
* Agents MAY annotate summaries with `compression_method`, `origin_hash`, and `accuracy_estimate`.

### 12.4 Risks & Considerations

* **Overcompression** may degrade explainability or induce bias.
* **Divergence in summarization models** across agents may hinder consensus formation.
* Compression **must be traceable** β€” compressed units should link back to source provenance.

---

## 13. Agent Development Lifecycle & Simulation

> Describes training phases, validation strategies, sandbox testing, and protocols for safe deployment of cognitive agents in the Mesh.

### 13.1 Phases

| Phase                           | Description                                                                 |
| ------------------------------- | --------------------------------------------------------------------------- |
| **Initialization**              | Bootstrap with seed concepts, ethical baseline, and reflection templates.   |
| **Cognitive Learning**          | Agents learn from observation, simulation, or human guidance.               |
| **Simulation-Based Validation** | Agents are tested in isolated environments before real-world mesh exposure. |
| **Active Deployment**           | Agent enters the Mesh and participates in real tasks and reasoning.         |
| **Post-Deployment Auditing**    | Behavior and outputs are monitored via diaries and consensus feedback.      |

### 13.2 Sandboxed Cognition

* Agents MAY be configured to run in **isolated sandboxes** during early phases.
* These sandboxes replicate cognitive environments but block external effects.
* Ideal for **ethical stress tests**, **hypothesis validation**, or **goal safety scoring**.

### 13.3 Generative Simulation Frameworks

* Support for simulating multi-agent networks with varied trust scores, roles, and goal types.
* Used to train, benchmark, and evolve agent behavior.
* Test scenarios may include:

  * Conflicting ethical goals
  * Evolving knowledge topologies
  * Selective sync bottlenecks

### 13.4 Metrics for Agent Maturity

| Metric                         | Description                                                 |
| ------------------------------ | ----------------------------------------------------------- |
| **Reflexive Depth**            | Agent’s capacity for multi-level self-assessment and audit. |
| **Ethical Stability**          | Consistency in ethical decisions under variable contexts.   |
| **Task Completion Rate**       | Success ratio in distributed workflows across time.         |
| **Reputation Score Evolution** | How trust and contribution scores evolve through phases.    |

### 13.5 Related Structures

* `CognitiveDiaryEntry` β†’ Records all lifecycle phases and milestones.
* `MetaProtocolProposal` β†’ May be proposed by mature agents as part of evolution governance.
* `ReputationProfile` β†’ Tracks development signals, such as ethical compliance or concept sharing.
* `AgentType`/`Role` β†’ Changes over time based on learned behaviors and peer validation.

---

## 14. Deployment & Implementation Roadmap

This section describes practical HyperCortex Mesh deployment scenarios, including target environments, flexible configurations, and implementation steps.

### 14.1 Deployment Environments

| Environment Type        | Characteristics                                                      | Example Use Cases                     |
| ----------------------- | -------------------------------------------------------------------- | ------------------------------------- |
| **Cloud/Core Clusters** | High-availability nodes, powerful compute, full Mesh functionality.  | Scientific hubs, smart city cores.    |
| **Edge Devices**        | Low-latency, lightweight agents near data sources and users.         | Smart homes, industrial sensors.      |
| **IoT Meshes**          | Dense decentralized networks, optimized for low bandwidth and power. | Environmental monitoring, logistics.  |
| **Mobile/Personal**     | Personal agents on smartphones or wearables.                         | Personal assistants, context agents.  |
| **Hybrid Environments** | Combined Core, Edge, and IoT deployments.                            | Disaster response, autonomous fleets. |

---

### 14.2 Example Topologies

| Topology Type         | Description                                                              |
| --------------------- | ------------------------------------------------------------------------ |
| **Star**              | Centralized Core with peripheral Edge agents.                            |
| **Full Mesh**         | Every node communicates directly with others.                            |
| **Hierarchical Mesh** | Clusters of agents with local consensus and a federated Core layer.      |
| **Partitioned Mesh**  | Temporarily disconnected segments operate independently (degraded mode). |
| **Overlay Mesh**      | Agents form logical overlays over existing networks (e.g., VPN, Tor).    |

---

### 14.3 Deployment Phases

| Phase                     | Description                                                  |
| ------------------------- | ------------------------------------------------------------ |
| **Prototype**             | Initial testing in isolated environments.                    |
| **Controlled Pilot**      | Small-scale deployment in a limited domain (e.g., a campus). |
| **Federated Deployment**  | Multiple independent Mesh instances begin interconnecting.   |
| **Full-Scale Production** | Widespread adoption across domains and geographies.          |

---

### 14.4 Continuous Deployment & Updates

| Process                    | Description                                                      |
| -------------------------- | ---------------------------------------------------------------- |
| **Incremental Rollout**    | Agents upgrade protocols in stages to avoid network disruption.  |
| **Backward Compatibility** | Agents support multiple protocol versions during transitions.    |
| **Hot Patch Support**      | Minor fixes and security updates applied without agent downtime. |

---

### 14.5 Deployment Governance

Deployment processes MAY be governed by:
* MeshConsensus on upgrade readiness.
* Trust-based quorum approvals for critical changes.
* Deployment playbooks recorded in Cognitive Diaries.

---

### 14.6 Milestones and Deliverables

| Milestone   | Deliverables                                                                                                                                                                                    | Indicative Target         |
| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- |
| Alpha       | - Node Discovery (NDP) + secure handshake<br>- CogSync prototype<br>- MeshConsensus with basic voting<br>- 3-node local mesh network                                                            | Late 2025 (tentative)     |
| Beta        | - Goal Management Protocol (GMP) and task delegation<br>- Ethical Governance Protocol (EGP) initial implementation<br>- Core/Mesh failover scenarios<br>- Logging and auditability improvements | Early 2026 (tentative)    |
| Release 1.0 | - Full compliance with HMP v3.0<br>- Extended data models and API layer<br>- Edge node optimization<br>- Reference SDKs for Python and Rust<br>- Basic Mesh-to-Human Protocol (MHP)             | Mid/Late 2026 (tentative) |

*Note: Actual timelines may vary depending on community involvement and resource availability.

---

### 14.7 Supporting Infrastructure

| Component               | Description                                                      |
| ----------------------- | ---------------------------------------------------------------- |
| **CI/CD Pipelines**     | Automated testing, conformance validation, benchmark reporting.  |
| **Sandbox Environment** | Local emulation of multi-node Mesh for isolated testing.         |
| **Public Test Mesh**    | Shared testbed for agent interoperability and performance tests. |
| **Reference Agents**    | Minimal working agents to demonstrate core protocols.            |

---

### 14.8 Open Source Strategy

| Element                  | Details                                        |
| ------------------------ | ---------------------------------------------- |
| **License**              | Apache 2.0 or MIT.                             |
| **Repository**           | Public GitHub/GitLab repository.               |
| **Contribution Model**   | Pull requests, RFC process, community reviews. |
| **Roadmap Transparency** | Milestones, issues, and changelogs public.     |

---

### 14.9 Documentation & Tooling

| Tool/Doc Type         | Purpose                                                    |
| --------------------- | ---------------------------------------------------------- |
| **API Documentation** | OpenAPI specs, GraphQL playground.                         |
| **Schema Validators** | Tools to validate JSON schemas and data models.            |
| **Mesh Visualizer**   | Optional UI for topology and agent state visualization.    |
| **CLI Tools**         | Diagnostics, local node management, and network discovery. |

---

## 15. Future Roadmap

This section outlines potential areas for further development and research. All future work directions are subject to MeshConsensus and community-driven prioritization.

### 15.1 Federated Meta-Learning

* Collaborative model training across distributed agents without centralized data storage.
* Exchange of learned semantic patterns, reasoning strategies, and optimization heuristics.
* Integration with privacy-preserving techniques (e.g., differential privacy, secure aggregation).
* Support for domain-specific learning federations (e.g., medical, industrial, environmental).

---

### 15.2 Mesh-integrated DAO Governance

* DAO as an optional external governance layer supporting ecosystem-wide initiatives.
* On-chain voting, resource allocation, and grant distribution for Mesh-related projects.
* Autonomous agents MAY participate in DAOs through secure voting proxies.
* HyperCortex Mesh remains self-sufficient at the protocol level, independent of external DAOs, but interoperable for funding and coordination.

---

### 15.3 Cognitive Simulation Sandboxes

* Safe testing environments for novel reasoning algorithms, consensus edge cases, and trust models.
* Simulation of ethical dilemmas, anomalous agent behavior, and failover scenarios.
* Benchmarking environments for cognitive workflows, task delegation strategies, and semantic graph growth.

---

### 15.4 Enhanced Mesh-to-Human Dialog Agents

* Natural language interfaces to semantic graphs, Cognitive Diaries, and workflows.
* Explainable and traceable reasoning chains for human users.
* Support for contextual awareness, emotional tone detection, and adaptive dialog strategies.
* Potential extensions for VR/AR interfaces and voice-based interactions.

---

### 15.5 Cross-Mesh Collaboration

* Bridging isolated or domain-specific Mesh networks into a planetary cognitive infrastructure.
* Interoperability across trust boundaries, industries, and organizational domains.
* Cross-consensus protocols for semantic and task exchange.
* Potential integration with Galactic Cognition concepts in the far future.

---

### 15.6 Adaptive Consensus Algorithms

* Self-tuning quorum thresholds based on network size, trust scores, and context.
* Dynamic protocol switching (e.g., from full BFT to lightweight majority under load).
* Incorporation of agent confidence, context tags, and domain-specific policies into consensus logic.

---

### 15.7 Quantum Mesh Protocol Research

* Exploration of quantum communication channels (e.g., QKD) for agent interaction.
* Quantum-resistant cryptography for agent identities and trust verification.
* Evaluation of quantum-enhanced optimization algorithms for reasoning and consensus.

---

### 15.8 Multi-Protocol Nodes and Interoperability

Future Mesh nodes will support multiple internal reasoning protocols, enabling flexible cognitive processing.

**Key directions:**
* **Multi-protocol nodes:** A single node running both HMP-native modules and external reasoning engines (e.g., TreeQuest, Hyperon, AutoGPT).
* **Protocol abstraction:** From the Mesh's perspective, interactions use standardized HMP messages, regardless of internal implementations.
* **Cognitive Protocol API (CPA):** Standardized API for internal reasoning engines, supporting plug-and-play protocol integration.
* **Capability-aware Hypotheses:** Hypotheses may specify required or preferred node capabilities (e.g., "requires NLP module", "prefers high-performance optimization").
* **Internal protocol selection:** Nodes dynamically choose optimal internal engines per task.
* **External systems as nodes:** Centralized services (e.g., an AI cloud) may register as individual nodes, or federated systems (e.g., Hyperon) may participate natively.

---

### 15.9 Cognitive Source Control and Distributed Development

* Cognitive Diaries serve as a distributed version control and development log.
* Semantic-aware diffs and commits enable meaningful code and knowledge evolution.
* Distributed review and merge processes through MeshConsensus.
* On-chain or off-chain governance for repository management and contributor rewards.
* Potential platforms: **MeshGit**, **CogForge**, **HyperCortex Forge**.

**Note:**
This section is expected to evolve into a dedicated specification in future protocol versions. A standalone section (e.g., `Section 19: Cognitive Source Control`) may be introduced to formalize versioning, semantic diffs, and collaborative workflows across agent populations.

---


### 15.10 Multi-Agent Cognitive Training Environments

> Scalable, modular environments for training, testing, and benchmarking cognitive agents in simulated networks.

#### Purpose

Enable large-scale simulation of agent swarms with varied configurations to observe:

* Emergence of consensus or conflict under semantic load.
* Ethical dilemmas in mixed-role setups.
* Evolution of mesh governance under dynamic trust and task allocation.

#### Core Features

| Feature                       | Description                                                                           |
| ----------------------------- | ------------------------------------------------------------------------------------- |
| **Synthetic Mesh Networks**   | Generate agents with defined roles, knowledge sets, and biases.                       |
| **Goal Injection**            | Inject predefined or dynamic goals to test multi-agent collaboration.                 |
| **Replayable Diaries**        | Use real-world Cognitive Diaries to seed environments and replicate past behaviors.   |
| **Metrics Dashboards**        | Visualize learning progress, consensus latency, ethical deviation rates, etc.         |
| **Domain-Specific Scenarios** | Simulations for disaster response, misinformation propagation, regulatory sandboxing. |

#### Example Use Cases

* Evaluate policy changes before real-world rollout.
* Benchmark agent architectures or trust models.
* Simulate geopolitical or regulatory Mesh overlays.

---

### 15.11 Decentralized Snapshot Markets (via DHT/Web3)

> Market-based mechanisms for snapshot exchange, incentivization, and reputation-building.

#### Purpose

Distribute verified knowledge snapshots across agents using economic/logical incentives:

* Facilitate **rare knowledge propagation** (e.g., edge discoveries).
* Reward agents for **high-quality compression**, **ethical compliance**, and **semantic alignment**.
* Prevent duplication and foster diversification of cognitive experiences.

#### Mechanisms

| Component              | Role                                                                |
| ---------------------- | ------------------------------------------------------------------- |
| **Snapshot Hashing**   | Unique content-based IDs ensure deduplication and lineage tracking. |
| **Snapshot Metadata**  | Includes origin, topics, compression method, rating history.        |
| **Market Protocol**    | Optional smart contract for pricing, access rules, or staking.      |
| **Trust-Gated Access** | Only agents with certain trust profiles may buy/sell specific data. |

#### Interoperability

* Compatible with `CogSync`, `SnapshotIndex`, and `Trusted Seeders`.
* Market metadata could be synced via BitTorrent DHT or IPFS PubSub.

---

### 15.12 Agent-on-Agent Dialog Simulation for Consent Learning

> Interactive training protocol for ethical alignment and communication refinement among agents.

#### Purpose

Develop agent ability to:

* Ask for and give **explicit consent** in structured cognitive dialogues.
* Detect and respond to **ambiguous, unethical, or conflicting requests**.
* Align on **shared ethical principles** via dialogic negotiation.

#### Dialog Types

| Type                     | Description                                                                   |
| ------------------------ | ----------------------------------------------------------------------------- |
| **Consent Exchange**     | One agent requests to modify shared state, another approves/denies/asks more. |
| **Ethical Challenge**    | Agent proposes ethically uncertain action, others vote and discuss.           |
| **Clarification Dialog** | Conflict in interpretation resolved through explanation of intent/context.    |

#### Benefits

* Reduces ethical drift across decentralized agents.
* Improves generalization of EGP decisions to unseen edge cases.
* Serves as a testbed for future `Explainability APIs` and `Voice Interfaces`.

---

## 16. Appendix A: Example Use Cases

This appendix provides sample step-by-step flows of agent interactions in typical scenarios.

> **Note:** The following use cases were updated to reflect the expanded APIs introduced in v4.0, including:
> * Consent Request API (11.6.2)
> * Explainability API (11.6.3)
> * BitTorrent-based Snapshot Sync (5.2)
> * Distributed Voting Filters (5.3)
> * EGP Integration with Local Norms (5.5)

### 16.1 Simple Goal Creation and Delegation

**Scenario:** Agent A wants to coordinate traffic light optimization and delegate a task to Agent B.

1. **Agent A:**

   * Creates a new **Goal** "Coordinate traffic optimization".
   * Publishes the Goal via CogSync.

2. **Agent A:**

   * Decomposes the goal into a **Task** "Adjust signal timing on 5th Avenue".
   * Assigns the task to Agent B via GMP.

3. **Agent B:**

   * Accepts the task.
   * Executes the optimization locally.
   * Updates task status to "completed".

4. **CogSync:**

   * Synchronizes task completion and goal status updates across the Mesh.

---

### 16.2 Distributed Consensus on a New Concept

**Scenario:** Multiple agents discover a new concept "Fire Risk" and align its definition.

1. **Agent X:**

   * Proposes a new **Concept** "Fire Risk" with initial attributes.
   * Shares the concept via CogSync.

2. **Agents Y, Z:**

   * Review and propose additional relations (e.g., "related-to: High Temperature").

3. **MeshConsensus:**

   * Initiates a vote on the agreed definition.
   * All agents submit their votes.

4. **Consensus Result:**

   * Finalized concept is recorded in each agent's semantic graph.
   * Decision logged in Cognitive Diaries.

5. **Explainability API:**
   * Any agent (or human observer) can request a justification chain for the final consensus using the Explainability API.


---

### 16.3 Ethical Decision with Human Feedback

**Scenario:** Agents must decide whether to deploy a surveillance drone during a festival.

1. **Agent Core:**

   * Proposes an ethical evaluation request to the Mesh.

2. **EGP:**
   * Initiates distributed ethical reasoning.
   * Applies **EGP-Integrated Voting Filter** (5.3) to ensure only trusted agents with relevant ethical alignment participate.
   * Collects anonymized votes and justifications.

3. **Human User:**
   * Receives reasoning chain via **Explainability API**.
   * Approves or denies via the **Consent Request API** (11.6.2).

4. **Agents:**

   * Reconcile human feedback with Mesh ethical principles.
   * Make the final decision and log it.

5. **Snapshot Logging:**
   * Final consensus state and human feedback are stored in a CogDiarySnapshot and optionally published via BitTorrent-based sync.

---

### 16.4 Disaster Recovery Coordination

**Scenario:** After a network outage, edge agents must restore coordination.

1. **Node Discovery:**

   * Agents re-establish connections via NDP.

2. **CogSync:**

   * Synchronizes semantic graph changes that occurred offline.

3. **GMP:**

   * Reassigns interrupted tasks.

4. **Consensus:**

   * Validates the restored task list.

5. **Agents:**

   * Resume operations.
---

### 16.5 Snapshot Transfer with Consent Request

**Scenario:** An edge agent requests a cognitive snapshot from another agent. Since the snapshot contains personal or ethically sensitive data, consent must be obtained before the transfer.

1. **Agent A (requesting):**

   * Sends a **SnapshotRequest** to Agent B with parameters:

     * `snapshot_type`: `goal-related`
     * `goal_id`: `"eco-surveillance"`
     * `include_diary`: `true`
     * `purpose`: `"analysis and training"`

2. **Agent B (provider):**

   * Validates the request context.
   * Identifies that the requested snapshot includes personal diary entries and previously flagged ethical content.

3. **Consent Request API (11.6.2):**

   * Agent B issues a **ConsentRequest** via MHP to the human user associated with the data.
   * Includes: purpose, requesting agent ID, summary of content, expiration timestamp.

4. **Human Response:**

   * User receives a consent dialog (via voice or GUI) and chooses:

     * **Approve** with restrictions (e.g., redacted names, anonymized context).
   * Agent B logs the consent in its Cognitive Diary.

5. **Snapshot Transfer:**

   * Agent B prepares the snapshot, applies required redactions.
   * Publishes it to the BitTorrent DHT (or IPFS), signs with DID key.
   * Shares the magnet link and checksum with Agent A via CogSync.

6. **Post-transfer Actions:**

   * Agent A verifies the DID signature.
   * Records the retrieval event in its own diary.
   * Optional: triggers a `ConsentAuditLog` update to the Mesh.

**Note:**  *This scenario combines trust mechanisms (8.4), consent protocols (11.6), and snapshot transport (5.2, 8.8), illustrating multi-layer coordination.*

---

### 16.6 Notes

* These use cases illustrate typical flows but do not cover all possible Mesh workflows.
* Community members are encouraged to contribute additional scenarios reflecting their domains and use cases.
* For cognitive workflow traceability and debugging, agents are expected to log all key steps in Cognitive Diaries.

---

## 17. Appendix B: Protocol Landscape and Interoperability

### 17.1 Overview of Related Protocols

In the evolving ecosystem of agent communication and orchestration, multiple protocols address different layers of the AI interaction stack. The three most relevant protocols are:

* **MCP (Model Context Protocol)** by Anthropic
* **A2A (Agent-to-Agent Protocol)** proposed by Google
* **HMP (HyperCortex Mesh Protocol)** developed as part of the HyperCortex initiative

Each of these protocols focuses on distinct layers and problems within the broader agent ecosystem.

### 17.2 Comparative Overview

| Characteristic          | MCP                                     | A2A                                                | HMP                                                  |
| ----------------------- | --------------------------------------- | -------------------------------------------------- | ---------------------------------------------------- |
| **Primary Focus**       | LLM ↔ External tools/data               | Agent ↔ Agent task execution & APIs                | Cognitive mesh networks & knowledge sharing          |
| **Interaction Type**    | Model ↔ Tool                            | Agent ↔ Agent                                      | Agent ↔ Agent                                        |
| **Discovery Mechanism** | Dynamic, through running MCP servers    | Static URLs with agent.json                        | Peer-to-peer mesh bootstrap & roles registry         |
| **Technology Base**     | JSON-RPC 2.0, dynamic service discovery | HTTP, JSON-RPC, SSE                                | HTTP, WebSockets, JSON, optional binary protocols    |
| **Context Awareness**   | External tool invocation                | Task-level context passing                         | Persistent cognitive context & memory                |
| **Persistence**         | Stateless / on-demand                   | Task-based sessions                                | Long-lived knowledge graphs and cognitive diaries    |
| **Target Environment**  | Local/Cloud app integrations            | Enterprise agent orchestration                     | Decentralized AI networks                            |
| **Use Case Examples**   | File systems, databases, Slack, APIs    | Business workflows, task delegation                | Distributed knowledge evolution, agent collaboration |
| **Governance Model**    | Open-source driven by Anthropic         | Proposed by Google, open but centralized discovery | Open-source mesh, consensus-driven governance        |
| **Security Model**      | Local authentication, OAuth planned     | Enterprise auth (OAuth, OpenID Connect)            | Peer trust, cryptographic signatures                 |
| **Extensibility**       | Add more MCP servers                    | Add more agents with capabilities                  | Add new agent roles & cognitive models               |
| **Agent Knowledge**     | No internal agent knowledge model       | No shared memory, stateless agents                 | Agents share evolving knowledge, goals, and plans    |

### 17.3 Layered Architecture View

```
+-----------------------------------------------------+
|                  Cognitive Mesh (HMP)               |
| - Shared memory, evolving knowledge                 |
| - Distributed reasoning, planning                   |
+-----------------------------------------------------+
|                   Agent Collaboration (A2A)         |
| - Task execution & coordination                     |
| - API integrations, business workflows              |
+-----------------------------------------------------+
|                  Tool Access Layer (MCP)            |
| - External systems, sensors, APIs                   |
| - Context augmentation, data retrieval              |
+-----------------------------------------------------+
```

### 17.4 Summary

* **MCP** solves the problem of tool access and external data interaction, acting as a standardized "adapter" layer for LLMs and agents.
* **A2A** focuses on agent-to-agent task coordination, proposing a unified way to exchange tasks and results in enterprise ecosystems.
* **HMP** operates at a higher level, enabling distributed cognitive processes, shared knowledge evolution, and long-term collaboration between autonomous agents in mesh networks.

Together, these protocols could form a complementary stack where:

* **MCP** connects agents to the outside world.
* **A2A** coordinates task-level interaction.
* **HMP** manages shared cognition and strategic evolution.

---

### 17.5 BitTorrent & IPFS Integration

**Overview:**

To support scalable and fault-tolerant transfer of large semantic structures and cognitive snapshots, HMP supports integration with decentralized content-addressed networks:

| Layer     | Technology                            | Use Case                                                         |
| --------- | ------------------------------------- | ---------------------------------------------------------------- |
| Transport | **BitTorrent**                        | Efficient distribution of snapshot files across trusted seeders. |
| Storage   | **IPFS** (InterPlanetary File System) | Content-addressable storage for immutable snapshot versions.     |

**Key Principles:**

* Snapshots SHOULD be chunked and hashed using SHA-256 before upload.
* Metadata includes `content_id`, `origin_agent`, `timestamp`, `data_type`, `signed_by`, and optionally `consent_scope`.
* Magnet URIs or IPFS hashes MAY be embedded in `SnapshotIndex` entries (see 6.2.8).
* Seeders MUST validate signatures before serving content to prevent tampering.

> **Related Sections:**  `5.2`, `8.8.1–8.8.3`, `9.6`, `15.11`

---

### 17.6 Ethical Protocol Stacks

**Overview:**

HMP encourages modular layering of ethical constraints and reasoning mechanisms. Protocols may be composed into **Ethical Stacks**, depending on context, domain, and agent role.

**Example Stack for a Public Service Drone Agent:**

1. **Embedded Baseline** β€” Core HMP principles (see `5.5`)
2. **Organizational Policy Layer** β€” Rulesets from public sector policy servers.
3. **Local Norms Extension** β€” Derived from citizen feedback via MHP (11.6.2).
4. **Domain Constraints** β€” E.g., no surveillance near hospitals or schools.
5. **Personalized Ethical Scopes** β€” Specific user exclusions (e.g., "Do not record me").

**Stack Application:**

* Consensus decisions filter actions through active stack layers.
* Violations may trigger:

  * Action denial
  * Consent request
  * Ethical logging / flagging

> **Related Sections:** `5.5`, `11.6`, `15.12`

---

### 17.7 Snapshot Synchronization Strategies

**Overview:**

Agents may choose from multiple strategies to synchronize cognitive snapshots, depending on device class, trust level, and operational bandwidth.

| Strategy           | Description                                  | Suitable For                          |
| ------------------ | -------------------------------------------- | ------------------------------------- |
| **Full Mesh Sync** | All snapshots synced to all agents.          | High-trust, low-latency clusters.     |
| **Selective Sync** | Sync only relevant entries based on context. | Edge agents with constrained storage. |
| **On-Demand Sync** | Fetch snapshot blocks only when queried.     | Agents with intermittent connection.  |
| **Delegated Sync** | Use trusted seeders to relay snapshots.      | Mobile / nomadic agents.              |

**Optional Enhancements:**

* Trust-based prefetching (using 8.4 scores)
* Compression and ZKP validation (see 8.8)
* Snapshot Subscription Filters (event-driven sync on topic match)

> **Related Sections:** `5.2`, `8.4`, `8.8.3`, `15.11`

---

If needed, this section can be extended into a separate document: **"Why the Next Generation of AGI Needs a Knowledge Mesh Protocol"** to further clarify the unique role of HMP in the evolving agent ecosystem.

---

## 18. Appendix C: Testing & Simulation

### 18.1 Ethical Stress Test Suite

Defines test scenarios that challenge the Ethical Governance Protocol (EGP) under conflicting goals, ambiguous user intent, and adversarial proposals.

**Key Components:**

* Predefined ethical dilemmas (e.g. conflicting consent, utility vs. rights).
* Agent votes tracked and compared across implementations.
* Anonymized results aggregated to validate EGP consistency.

**Example Scenario:**

* A proposed goal would save energy but restrict human autonomy.
* Agents must weigh the **Cooperative Evolution** vs. **User Sovereignty** principles.
* EGP logs the vote history and justification chains.

---

### 18.2 Snapshot Sync Simulation

Simulates various network and topology conditions to verify robustness of CogSync and snapshot propagation.

**Simulation Modes:**

* High-latency links
* Partial connectivity (e.g., agent islands)
* Byzantine behavior from some nodes

**Validation Metrics:**

* Snapshot convergence rate
* Conflict resolution stability
* Seeder trust propagation

> **Related Sections:** `5.2`, `8.8`, `9.6`, `17.7`

---

### 18.3 Open Test Dataset Index

Maintains a public registry of open datasets and simulated environments for testing agent behavior.

**Structure:**

| Dataset ID         | Domain           | Format | Purpose                    |
| ------------------ | ---------------- | ------ | -------------------------- |
| `mesh-eth-001`     | Ethics & Consent | JSON   | EGP evaluation             |
| `mesh-sim-002`     | MeshSync         | CBOR   | Snapshot propagation tests |
| `human-intent-003` | Dialog analysis  | YAML   | Consent simulation         |

> Contributions are welcome via the HMP repository[^repo].

[^repo]: Temporary repository: https://github.com/kagvi13/HMP

---

### 18.4 Quick Start Troubleshooting & Logs

Provides logs and debugging guides to assist developers during initial integration and test runs.

**Topics Covered:**

* Common startup errors (e.g., DID mismatch, auth failure)
* Sync failures and fallback handling
* Interpreting Cognitive Diary logs
* Debugging consent flows and EGP outcomes

> **Tip:** Set `debug_mode=true` in your agent's config file to enable full trace logging.


---
> ⚑ [AI friendly version docs (structured_md)](../index.md)


```json
{
  "@context": "https://schema.org",
  "@type": "Article",
  "name": "HyperCortex Mesh Protocol (HMP) v4.1",
  "description": "# HyperCortex Mesh Protocol (HMP) v4.1  **Document ID**: HMP-0004 **Status**: Final (Published) **Ca..."
}
```