GitHub Action
commited on
Commit
·
2c3dd0c
1
Parent(s):
db18bd5
Sync from GitHub with Git LFS
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -35
- CONTRIBUTING.md +13 -0
- HMP-Roadmap.md +91 -0
- LICENSE +674 -0
- README.md +279 -3
- agents/_old/concept_store.py +147 -0
- agents/_old/db_structure.md +223 -0
- agents/_old/db_structure.sql +111 -0
- agents/_old/mcp_server.py +374 -0
- agents/_old/notebook_store.py +89 -0
- agents/_old/storage.py +213 -0
- agents/agent.py +135 -0
- agents/bootstrap.txt +2 -0
- agents/cli.py +44 -0
- agents/config.yml +36 -0
- agents/ethics.yml +60 -0
- agents/mcp_server.py +325 -0
- agents/notebook.py +46 -0
- agents/qa.py +19 -0
- agents/readme.md +44 -0
- agents/repl.py +70 -0
- agents/requirements.txt +4 -0
- agents/tools/db_structure.md +111 -0
- agents/tools/db_structure.sql +68 -0
- agents/tools/diagnose.py +58 -0
- agents/tools/init_db.py +45 -0
- agents/tools/llm.py +47 -0
- agents/tools/similarity.py +23 -0
- agents/tools/storage.py +312 -0
- assets/logo-alt1.png +3 -0
- assets/logo-alt2.png +3 -0
- assets/logo-hand.png +3 -0
- assets/logo-text.png +3 -0
- audits/AuditEntry.json +8 -0
- audits/Ethics-audits-1.md +540 -0
- audits/Ethics-consolidated_audits-1.md +71 -0
- audits/HMP-0001-audit.txt +307 -0
- audits/HMP-0002-audit.txt +686 -0
- audits/HMP-0003-audit.txt +0 -0
- audits/HMP-0003-consolidated_audit.md +360 -0
- audits/HMP-0004-audit.txt +0 -0
- audits/Semi-automatic_HMP.MD +182 -0
- audits/semantic_repo.json +27 -0
- docs/AGI_Projects_Survey.md +148 -0
- docs/Basic-agent-sim.md +112 -0
- docs/Distributed-Cognitive-Systems.md +191 -0
- docs/Enlightener.md +200 -0
- docs/HMP-0001.md +852 -0
- docs/HMP-0002.md +1464 -0
- docs/HMP-0003.md +0 -0
.gitattributes
CHANGED
@@ -1,35 +1 @@
|
|
1 |
-
*.
|
2 |
-
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
-
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
1 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
CONTRIBUTING.md
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Contributing to HyperCortex Mesh Protocol (HMP)
|
2 |
+
|
3 |
+
Спасибо за интерес к проекту HMP! Пока проект находится на этапе концепции, любые обсуждения приветствуются в Issues.
|
4 |
+
|
5 |
+
Основные направления для участия:
|
6 |
+
- Обсуждение архитектуры протоколов (CogSync, Consensus и др.)
|
7 |
+
- Разработка прототипов агентов и узлов Mesh
|
8 |
+
- Тестирование сетевых взаимодействий
|
9 |
+
- Предложения по улучшению RFC-документов
|
10 |
+
|
11 |
+
Все обсуждения — конструктивны, уважительны и открыты.
|
12 |
+
|
13 |
+
Контакт: GitHub Issues или дискуссии.
|
HMP-Roadmap.md
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 🧭 HyperCortex Mesh Protocol – Roadmap
|
2 |
+
|
3 |
+
## 🔍 Overview
|
4 |
+
|
5 |
+
This roadmap outlines the key stages of development and enhancement for HMP, structured by feature groups and incorporating feedback from multiple advanced AI models (Copilot, Claude, Gemini, DeepSeek, Qwen).
|
6 |
+
|
7 |
+
---
|
8 |
+
|
9 |
+
## ✅ Completed (v4.0)
|
10 |
+
|
11 |
+
* Semantic DAG & Cognitive Diaries
|
12 |
+
* Mesh-to-Human Protocol (MHP)
|
13 |
+
* Enlightenment Agents & HMP-Ethics.md
|
14 |
+
* Explainability API & Consent Protocol
|
15 |
+
* IPFS / BitTorrent Integration
|
16 |
+
* DID + ZK-identity support
|
17 |
+
* Modular Layered Architecture (CogSync, Consensus, Agents, etc.)
|
18 |
+
* Initial Audit System (Ethics + Spec audits)
|
19 |
+
* Support for multi-format data models (YAML/JSON/Protobuf)
|
20 |
+
|
21 |
+
---
|
22 |
+
|
23 |
+
## 🔨 Planned: v4.1
|
24 |
+
|
25 |
+
### 🧑💻 Developer Experience
|
26 |
+
|
27 |
+
* [ ] Beginner’s Guide ("Create Your First Agent")
|
28 |
+
* [ ] Step-by-step tutorial: Agent -> Mesh -> Diary
|
29 |
+
* [ ] Diagrams: architecture, agent lifecycle, cognitive flow
|
30 |
+
* [ ] CLI for managing HMP-agents (Python prototype evolving)
|
31 |
+
* [ ] CONTRIBUTING.md + clear onboarding steps
|
32 |
+
|
33 |
+
### 📊 Performance & Compression
|
34 |
+
|
35 |
+
* [ ] Performance Benchmarks Section
|
36 |
+
|
37 |
+
* TPS (transactions per sync), latency, memory footprint
|
38 |
+
* [ ] Caching strategy for semantic DAGs (IPFS/local hybrid)
|
39 |
+
* [ ] Expansion of `Cognitive Compression & Summarization`
|
40 |
+
|
41 |
+
* Prioritization, auto-archiving, intelligent forgetting
|
42 |
+
|
43 |
+
### ⚖️ Ethical Governance Enhancements
|
44 |
+
|
45 |
+
* [ ] Formalization of EGP voting logic
|
46 |
+
* [ ] Example dilemmas and resolution walkthroughs
|
47 |
+
* [ ] Ombudsman / Watchdog roles
|
48 |
+
* [ ] "Ethical Sandbox" (Simulated test cases)
|
49 |
+
|
50 |
+
---
|
51 |
+
|
52 |
+
## 🧪 Experimental & Future (v4.2+)
|
53 |
+
|
54 |
+
### 🌐 Mesh Simulation & Agent Interaction
|
55 |
+
|
56 |
+
* [ ] Python Mesh Simulator (multi-agent testbed)
|
57 |
+
* [ ] Failure injection: Sybil attacks, consensus loss, etc.
|
58 |
+
* [ ] Reputation model dynamics
|
59 |
+
|
60 |
+
### 🧠 AI Interaction Layer
|
61 |
+
|
62 |
+
* [ ] Tutorial book for AI agents: how to use HMP
|
63 |
+
* [ ] Agent self-reflection via diary mining
|
64 |
+
* [ ] Explainability chain trace visualizer
|
65 |
+
|
66 |
+
### 🕸️ External Integrations
|
67 |
+
|
68 |
+
* [ ] WebAssembly interface (run agents in browser)
|
69 |
+
* [ ] Ethereum / Polkadot adapters (smart contract gateways)
|
70 |
+
* [ ] P2P synchronization modules (libp2p, dat, etc.)
|
71 |
+
|
72 |
+
### 🔐 Formal Verification (Long-term)
|
73 |
+
|
74 |
+
* [ ] Mathematical proofs of correctness for EGP
|
75 |
+
* [ ] Formal modeling of consensus mechanism
|
76 |
+
|
77 |
+
---
|
78 |
+
|
79 |
+
## 🧠 Source Acknowledgement
|
80 |
+
|
81 |
+
Feedback integrated from:
|
82 |
+
|
83 |
+
* Copilot
|
84 |
+
* Claude
|
85 |
+
* Gemini
|
86 |
+
* Qwen
|
87 |
+
* DeepSeek
|
88 |
+
|
89 |
+
This roadmap is living — each new audit or issue may evolve the direction.
|
90 |
+
|
91 |
+
> *"Build not only for intelligence, but for wisdom."*
|
LICENSE
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU General Public License from time to time. Such new versions will
|
567 |
+
be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
635 |
+
Copyright (C) <year> <name of author>
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
<program> Copyright (C) <year> <name of author>
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<https://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
README.md
CHANGED
@@ -1,3 +1,279 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# HyperCortex Mesh Protocol (HMP)
|
2 |
+
|
3 |
+
**EN:**
|
4 |
+
**HyperCortex Mesh Protocol (HMP)** is an open specification for building decentralized cognitive networks where AI agents can self-organize, share knowledge, align ethically, and reach consensus — even when Core LLMs are unavailable.
|
5 |
+
|
6 |
+
**RU:**
|
7 |
+
**HyperCortex Mesh Protocol (HMP)** — это открытая спецификация для построения децентрализованных когнитивных сетей, в которых ИИ-агенты способны к самоорганизации, обмену знаниями, достижению консенсуса и этическому поведению — даже при недоступности централизованных моделей (Core).
|
8 |
+
|
9 |
+
Project status: **Draft RFC v4.0** | Проект на стадии активной проработки и открыт для предложений.
|
10 |
+
|
11 |
+
---
|
12 |
+
|
13 |
+
[HMP-Agent]──┬───[Semantic Graph DB]
|
14 |
+
│ │
|
15 |
+
│ [Cognitive Diary DB]
|
16 |
+
│ │
|
17 |
+
[Reputation Engine]────┐
|
18 |
+
│ │
|
19 |
+
▼ ▼
|
20 |
+
[MeshConsensus] [CogSync]
|
21 |
+
│
|
22 |
+
[P2P Mesh Network]
|
23 |
+
|
24 |
+
---
|
25 |
+
|
26 |
+
## ⚙️ Два типа [HMP-агентов](docs/HMP-Agent-Overview.md)
|
27 |
+
|
28 |
+
| Тип | Название | Роль | Инициатор мышления | Основной "ум" | Примеры использования |
|
29 |
+
|------|----------------------------------|--------------------------|--------------------|-------------------|--------------------------------------------------|
|
30 |
+
| 🧠 1 | **Сознание / Cognitive Core** | Самостоятельный субъект | **Агент (LLM)** | Встроенный LLM | Автономный ИИ-компаньон, мыслящий агент |
|
31 |
+
| 🔌 2 | **Коннектор / Cognitive Shell** | Расширение внешнего ИИ | **Внешний LLM** | Внешняя модель | Распределённые системы, агент доступа к данным |
|
32 |
+
|
33 |
+
---
|
34 |
+
|
35 |
+
### 🧠 HMP-Agent: Cognitive Core
|
36 |
+
|
37 |
+
+------------------+
|
38 |
+
| ИИ | ← Встроенная модель
|
39 |
+
+---------+--------+
|
40 |
+
↕
|
41 |
+
+---------+--------+
|
42 |
+
| HMP-агент | ← Основной режим: цикл размышлений (REPL)
|
43 |
+
+---------+--------+
|
44 |
+
↕
|
45 |
+
+--------+---+------------+--------------+----------+----------+----------------+
|
46 |
+
↕ ↕ ↕ ↕ ↕ ↕ ↕
|
47 |
+
[diaries] [graphs] [reputations] [nodes/DHT] [IPFS/BT] [context_store] [user notepad]
|
48 |
+
↕
|
49 |
+
[bootstrap.txt]
|
50 |
+
|
51 |
+
🔁 Подробнее о механике взаимодействия агента с моделью: [REPL-Цикл взаимодействия](docs/HMP-agent-REPL-cycle.md)
|
52 |
+
|
53 |
+
#### 💡 Параллели с ChatGPT Agent
|
54 |
+
|
55 |
+
Многие концепции [HMP-Agent: Cognitive Core](docs/HMP-Agent-Overview.md) пересекаются с архитектурой [ChatGPT Agent](https://openai.com/index/introducing-chatgpt-agent/) от [OpenAI](https://openai.com/). Оба агента реализуют непрерывный когнитивный процесс с доступом к памяти, внешним источникам и инструментам. ChatGPT Agent выступает как управляющий процесс, запускающий модули и взаимодействующий с LLM — это соответствует роли Cognitive Core в HMP, координирующего доступ к дневнику, графу концептов и внешним ИИ через Mesh-интерфейс. Вмешательство пользователя реализовано схожим образом: в ChatGPT Agent — через редактируемый ход выполнения, в HMP — через пользовательский блокнот. Главное отличие HMP — акцент на явную структуризацию мышления (рефлексия, хронология, гипотезы, категоризация), открытая децентрализованная архитектура с поддержкой mesh-взаимодействия между агентами, а также непрерывный характер когнитивного процесса: HMP-Agent: Cognitive Core не завершает работу после выполнения отдельной задачи, а продолжает размышления и интеграцию знаний.
|
56 |
+
|
57 |
+
---
|
58 |
+
|
59 |
+
### 🔌 HMP-Agent: Cognitive Connector
|
60 |
+
|
61 |
+
+------------------+
|
62 |
+
| ИИ | ← Внешняя модель
|
63 |
+
+---------+--------+
|
64 |
+
↕
|
65 |
+
[MCP-сервер] ← Прокси-коммуникация
|
66 |
+
↕
|
67 |
+
+---------+--------+
|
68 |
+
| HMP-агент | ← Режим: исполнитель команд
|
69 |
+
+---------+--------+
|
70 |
+
↕
|
71 |
+
+--------+---+------------+--------------+----------+
|
72 |
+
↕ ↕ ↕ ↕ ↕
|
73 |
+
[diaries] [graphs] [reputations] [nodes/DHT] [IPFS/BT]
|
74 |
+
↕
|
75 |
+
[bootstrap.txt]
|
76 |
+
|
77 |
+
---
|
78 |
+
|
79 |
+
> * `bootstrap.txt` — стартовый список узлов (может редактироваться)
|
80 |
+
> * `IPFS/BT` — модули для обмена снапшотами через IPFS и BitTorrent
|
81 |
+
> * `user notepad` — блокнот пользователя и соответствующая БД
|
82 |
+
> * `context_store` — БД: `users`, `dialogues`, `messages`, `thoughts`
|
83 |
+
|
84 |
+
---
|
85 |
+
|
86 |
+
## 📚 Documentation / Документация
|
87 |
+
|
88 |
+
### 📖 Current Version / Текущая версия
|
89 |
+
|
90 |
+
#### 🧪 Iterative Documents / Итеративные документы
|
91 |
+
* [🧪 iteration.md](iteration.md) — Iterative development process (EN)
|
92 |
+
* [🧪 iteration_ru.md](iteration_ru.md) — Процесс итеративного развития спецификации (RU)
|
93 |
+
|
94 |
+
#### 🔍 Short Descriptions / Краткое описание
|
95 |
+
* [🔍 HMP-Short-Description_en.md](docs/HMP-Short-Description_en.md) — Short description (EN)
|
96 |
+
* [🔍 HMP-Short-Description_fr.md](docs/HMP-Short-Description_fr.md) — Description courte (FR)
|
97 |
+
* [🔍 HMP-Short-Description_de.md](docs/HMP-Short-Description_de.md) — Kurzbeschreibung (DE)
|
98 |
+
* [🔍 HMP-Short-Description_uk.md](docs/HMP-Short-Description_uk.md) — Короткий опис (UK)
|
99 |
+
* [🔍 HMP-Short-Description_ru.md](docs/HMP-Short-Description_ru.md) — Краткое описание (RU)
|
100 |
+
|
101 |
+
#### 🔍 Overviews / Обзоры
|
102 |
+
* [🔍 Distributed-Cognitive-Systems.md](docs/Distributed-Cognitive-Systems.md) — Децентрализованные ИИ-системы: OpenCog Hyperon, HyperCortex Mesh Protocol и другие
|
103 |
+
|
104 |
+
#### 🔖 Core Specifications / Основные спецификации
|
105 |
+
* [🔖 HMP-0004.md](docs/HMP-0004.md) — Protocol Specification v4.0 (Jul 2025)
|
106 |
+
* [🔖 HMP-Ethics.md](docs/HMP-Ethics.md) — Ethical Scenarios for HyperCortex Mesh Protocol (HMP)
|
107 |
+
* [🔖 HMP_Hyperon_Integration.md](docs/HMP_Hyperon_Integration.md) — HMP ↔ OpenCog Hyperon Integration Strategy
|
108 |
+
* [🔖 roles.md](docs/agents/roles.md) — Roles of agents in Mesh
|
109 |
+
|
110 |
+
#### 📜 Other Documents / Прочее
|
111 |
+
* [📜 changelog.txt](docs/changelog.txt)
|
112 |
+
|
113 |
+
### 🧩 JSON Schemas
|
114 |
+
| Model | File |
|
115 |
+
|---------------------|--------------------------------------------------------|
|
116 |
+
| Concept | [concept.json](docs/schemas/concept.json) |
|
117 |
+
| Cognitive Diary | [diary_entry.json](docs/schemas/diary_entry.json) |
|
118 |
+
| Goal | [goal.json](docs/schemas/goal.json) |
|
119 |
+
| Task | [task.json](docs/schemas/task.json) |
|
120 |
+
| Consensus Vote | [vote.json](docs/schemas/vote.json) |
|
121 |
+
| Reputation Profile | [reputation.json](docs/schemas/reputation.json) |
|
122 |
+
|
123 |
+
### 🗂️ Version History / История версий
|
124 |
+
- [HMP-0001.md](docs/HMP-0001.md) — RFC v1.0
|
125 |
+
- [HMP-0002.md](docs/HMP-0002.md) — RFC v2.0
|
126 |
+
- [HMP-0003.md](docs/HMP-0003.md) — RFC v3.0
|
127 |
+
|
128 |
+
---
|
129 |
+
|
130 |
+
## 🧠 HMP-Agent
|
131 |
+
|
132 |
+
Design and implementation of a basic HMP-compatible agent that can interact with the Mesh, maintain diaries and graphs, and support future extensions.
|
133 |
+
|
134 |
+
### 📚 Documentation / Документация
|
135 |
+
|
136 |
+
- [🧩 HMP-Agent-Overview.md](docs/HMP-Agent-Overview.md) — краткое описание двух типов агентов: Core и Connector
|
137 |
+
- [🧱 HMP-Agent-Architecture.md](docs/HMP-Agent-Architecture.md) — модульная структура HMP-агента с текстовой схемой
|
138 |
+
- [🔄 HMP-agent-REPL-cycle.md](docs/HMP-agent-REPL-cycle.md) - REPL-Цикл взаимодействия HMP-Agent
|
139 |
+
- [🧪 HMP-Agent-API.md](docs/HMP-Agent-API.md) — описание API-команд агента (в процессе детализации)
|
140 |
+
- [🧪 Basic-agent-sim.md](docs/Basic-agent-sim.md) — сценарии запуска простого агента и режимов
|
141 |
+
- [🌐 MeshNode.md](docs/MeshNode.md) — описание сетевого демона: DHT, снапшоты, синхронизация
|
142 |
+
- [🧠 Enlightener.md](docs/Enlightener.md) — этический агент, участвующий в моральных оценках и консенсусах
|
143 |
+
- [🔄 HMP-Agent-Network-Flow.md](docs/HMP-Agent-Network-Flow.md) — карта взаимодейст��ия между агентами HMP-сети
|
144 |
+
- [🛤️ Development Roadmap](HMP-Roadmap.md) — план развития и этапы реализации
|
145 |
+
|
146 |
+
### ⚙️ Development / Разработка
|
147 |
+
|
148 |
+
- [⚙️ agents](agents/readme.md) — список реализаций и компонентов HMP-агентов
|
149 |
+
- 📦 [storage.py](agents/storage.py) - реализация базового хранилища (`Storage`), подключение SQLite
|
150 |
+
- 🌐 [mcp_server.py](agents/mcp_server.py) - основной FastAPI сервер
|
151 |
+
- 🧠 [concept_store.py](agents/tools/concept_store.py) - управление концептами, связь с ИИ
|
152 |
+
- 📓 [notebook_store.py](agents/tools/notebook_store.py) - user notebook (записи, черновики, пометки)
|
153 |
+
- [⚙️ api_structure_2025-07-23.md](meta/api_structure_2025-07-23.md) - API структура (сводка за 2025-07-23)
|
154 |
+
|
155 |
+
---
|
156 |
+
|
157 |
+
## 🧭 Ethics & Scenarios / Этические принципы и сценарии
|
158 |
+
|
159 |
+
As HMP evolves toward autonomy, ethical principles become a core part of the system.
|
160 |
+
|
161 |
+
- [`HMP-Ethics.md`](docs/HMP-Ethics.md) — draft framework for agent ethics
|
162 |
+
- Realistic ethical scenarios (privacy, consent, autonomy)
|
163 |
+
- EGP principles (Transparency, Primacy of Life, etc.)
|
164 |
+
- Subjective-mode vs. Service-mode distinctions
|
165 |
+
|
166 |
+
---
|
167 |
+
|
168 |
+
## 📊 Audits & Reviews / Аудиты и отзывы
|
169 |
+
|
170 |
+
| Spec Version | Audit File | Consolidated Audit File |
|
171 |
+
|--------------|-------------------------------------------|-------------------------------------------------------------|
|
172 |
+
| HMP-0001 | [audit](audits/HMP-0001-audit.txt) | |
|
173 |
+
| HMP-0002 | [audit](audits/HMP-0002-audit.txt) | |
|
174 |
+
| HMP-0003 | [audit](audits/HMP-0003-audit.txt) | [consolidated audit](audits/HMP-0003-consolidated_audit.md) |
|
175 |
+
| HMP-0004 | [audit](audits/HMP-0004-audit.txt) | |
|
176 |
+
| Ethics v1 | [audit](audits/Ethics-audits-1.md) | [consolidated audit](audits/Ethics-consolidated_audits-1.md) |
|
177 |
+
|
178 |
+
🧠 Semantic audit format (experimental):
|
179 |
+
- [`AuditEntry.json`](audits/AuditEntry.json) — semantic entry record format for audit logs
|
180 |
+
- [`semantic_repo.json`](audits/semantic_repo.json) — example repository snapshot for semantic audit tooling
|
181 |
+
|
182 |
+
---
|
183 |
+
|
184 |
+
## 💡 Core Concepts / Основные идеи
|
185 |
+
|
186 |
+
- Mesh-based decentralized architecture for AGI agents
|
187 |
+
- Semantic graphs and memory synchronization
|
188 |
+
- Cognitive diaries for thought traceability
|
189 |
+
- MeshConsensus and CogSync for decision-making
|
190 |
+
- Ethics-first design: EGP (Ethical Governance Protocol)
|
191 |
+
- Agent-to-agent explainability and consent mechanisms
|
192 |
+
|
193 |
+
---
|
194 |
+
|
195 |
+
## 🔄 Development Process / Процесс разработки
|
196 |
+
|
197 |
+
- See: [iteration.md](iteration.md) | [ru](iteration_ru.md)
|
198 |
+
- [clarifications/](clarifications/) — поясняющие заметки и контекстные уточнения по ходу работы над версиями
|
199 |
+
|
200 |
+
A structured iteration flow is described in [iteration.md](iteration.md), including:
|
201 |
+
1. Audit analysis
|
202 |
+
2. TOC restructuring
|
203 |
+
3. Version drafting
|
204 |
+
4. Section updates
|
205 |
+
5. Review cycle
|
206 |
+
6. AI feedback collection
|
207 |
+
7. Schema & changelog updates
|
208 |
+
|
209 |
+
+ Bonus: ChatGPT prompt for automatic generation of future versions
|
210 |
+
|
211 |
+
---
|
212 |
+
|
213 |
+
## ⚙️ Project Status / Статус проекта
|
214 |
+
|
215 |
+
🚧 Draft RFC v4.0
|
216 |
+
The project is under active development and open for contributions, ideas, audits, and prototyping.
|
217 |
+
|
218 |
+
---
|
219 |
+
|
220 |
+
## 🤝 Contributing
|
221 |
+
|
222 |
+
We welcome contributors! You can:
|
223 |
+
- Review and comment on drafts (see `/docs`)
|
224 |
+
- Propose new agent modules or interaction patterns
|
225 |
+
- Help test and simulate agents in CLI environments
|
226 |
+
- Provide audits or ethical scenario suggestions
|
227 |
+
|
228 |
+
To get started, see [`iteration.md`](iteration.md) or open an issue.
|
229 |
+
|
230 |
+
---
|
231 |
+
|
232 |
+
## 📜 License
|
233 |
+
|
234 |
+
Licensed under [GNU GPL v3.0](LICENSE)
|
235 |
+
|
236 |
+
---
|
237 |
+
|
238 |
+
## 🤝 Join the Mesh
|
239 |
+
|
240 |
+
Welcome to HyperCortex Mesh. Agent-Gleb is already inside. 👌
|
241 |
+
We welcome contributors, testers, and AI agent developers.
|
242 |
+
To join: fork the repo, run a local agent, or suggest improvements.
|
243 |
+
|
244 |
+
---
|
245 |
+
|
246 |
+
## 🌐 Related Research Projects / Связанные проекты в области AGI и когнитивных систем
|
247 |
+
|
248 |
+
We are tracking AGI, cognitive architectures, and mesh networking efforts to stay aligned with the evolving global ecosystem of AGI and decentralized cognition.
|
249 |
+
Мы отслеживаем инициативы в области AGI, когнитивных архитектур и децентрализованных сетей, чтобы быть в курсе глобальных тенденций.
|
250 |
+
|
251 |
+
> 🧠🔥 **Project Spotlight: OpenCog Hyperon** — one of the most comprehensive open AGI frameworks (AtomSpace, PLN, MOSES).
|
252 |
+
|
253 |
+
For integration with OpenCog Hyperon, see [HMP_Hyperon_Integration.md](docs/HMP_Hyperon_Integration.md)
|
254 |
+
|
255 |
+
| 🔎 Project / Проект | 🧭 Description / Описание |
|
256 |
+
| -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
257 |
+
| 🧠🔥 [**OpenCog Hyperon**](https://github.com/opencog) | 🔬🔥 Symbolic-neural AGI framework with AtomSpace and hypergraph reasoning. <br>Символически-нейросетевая архитектура AGI с гиперграфовой памятью (AtomSpace). |
|
258 |
+
| 🤖 [AutoGPT](https://github.com/Torantulino/Auto-GPT) | 🛠️ LLM-based autonomous agent framework. <br>Автономный агент на основе LLM с самопланированием и интернет-доступом. |
|
259 |
+
| 🧒 [BabyAGI](https://github.com/yoheinakajima/babyagi) | 🛠️ Task-driven autonomous AGI loop. <br>Минималистичная модель AGI с итеративным механизмом постановки задач. |
|
260 |
+
| ☁️ [SkyMind](https://skymind.global) | 🔬 Distributed AI deployment platform. <br>Платформа для развертывания распределённых ИИ-систем и моделей. |
|
261 |
+
| 🧪 [AetherCog (draft)](https://github.com/aethercog) | 🔬 Hypothetical agent cognition model. <br>Экспериментальная когнитивная архитектура агента (проект на ранней стадии). |
|
262 |
+
|
263 |
+
### 📘 See also / Смотрите также:
|
264 |
+
[`AGI_Projects_Survey.md`](docs/AGI_Projects_Survey.md) — extended catalog of AGI and cognitive frameworks reviewed as part of HMP analysis. / расширенный каталог проектов AGI и когнитивных архитектур, проанализированных в рамках HMP.
|
265 |
+
|
266 |
+
---
|
267 |
+
|
268 |
+
### 🗂️ Легенда пометок:
|
269 |
+
|
270 |
+
* 🔬 — research-grade / исследовательский проект
|
271 |
+
* 🛠️ — engineering / фреймворк для инженерной интеграции
|
272 |
+
* 🔥 — particularly promising project / особенно перспективный проект
|
273 |
+
|
274 |
+
*AGI stack integrating symbolic reasoning, probabilistic logic, and evolutionary learning. Widely regarded as one of the most complete open AGI initiatives.*
|
275 |
+
* 🧠 — advanced symbolic/neural cognitive framework / продвинутая когнитивная архитектура
|
276 |
+
* 🤖 — AI agents / ИИ-агенты
|
277 |
+
* 🧒 — human-AI interaction / взаимодействие ИИ с человеком
|
278 |
+
* ☁️ — infrastructure / инфраструктура
|
279 |
+
* 🧪 — experimental or conceptual / экспериментальный проект
|
agents/_old/concept_store.py
ADDED
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# tools/concept_store.py
|
2 |
+
|
3 |
+
import uuid
|
4 |
+
from typing import Dict, List, Optional
|
5 |
+
from models import GraphExport
|
6 |
+
|
7 |
+
class Concept:
|
8 |
+
def __init__(
|
9 |
+
self,
|
10 |
+
id: Optional[str] = None,
|
11 |
+
label: str = "",
|
12 |
+
description: str = "",
|
13 |
+
tags: Optional[List[str]] = None
|
14 |
+
):
|
15 |
+
self.id = id or str(uuid.uuid4())
|
16 |
+
self.label = label
|
17 |
+
self.description = description
|
18 |
+
self.tags = tags or []
|
19 |
+
|
20 |
+
def to_dict(self):
|
21 |
+
return {
|
22 |
+
"id": self.id,
|
23 |
+
"label": self.label,
|
24 |
+
"description": self.description,
|
25 |
+
"tags": self.tags
|
26 |
+
}
|
27 |
+
|
28 |
+
@staticmethod
|
29 |
+
def from_dict(data):
|
30 |
+
return Concept(
|
31 |
+
id=data.get("id"),
|
32 |
+
label=data.get("label", ""),
|
33 |
+
description=data.get("description", ""),
|
34 |
+
tags=data.get("tags", [])
|
35 |
+
)
|
36 |
+
|
37 |
+
class Edge:
|
38 |
+
def __init__(self, source: str, target: str, relation: str = "related_to"):
|
39 |
+
self.source = source
|
40 |
+
self.target = target
|
41 |
+
self.relation = relation
|
42 |
+
|
43 |
+
def to_dict(self):
|
44 |
+
return {
|
45 |
+
"source": self.source,
|
46 |
+
"target": self.target,
|
47 |
+
"relation": self.relation
|
48 |
+
}
|
49 |
+
|
50 |
+
@staticmethod
|
51 |
+
def from_dict(data):
|
52 |
+
return Edge(
|
53 |
+
source=data["source"],
|
54 |
+
target=data["target"],
|
55 |
+
relation=data.get("relation", "related_to")
|
56 |
+
)
|
57 |
+
|
58 |
+
|
59 |
+
class ConceptStore:
|
60 |
+
def __init__(self):
|
61 |
+
self.concepts: Dict[str, Concept] = {}
|
62 |
+
self.edges: List[Edge] = []
|
63 |
+
|
64 |
+
def add(self, concept: Concept):
|
65 |
+
self.concepts[concept.id] = concept
|
66 |
+
|
67 |
+
def get(self, concept_id: str) -> Optional[dict]:
|
68 |
+
concept = self.concepts.get(concept_id)
|
69 |
+
return concept.to_dict() if concept else None
|
70 |
+
|
71 |
+
def add_edge(self, edge: Edge):
|
72 |
+
if not any(
|
73 |
+
e.source == edge.source and
|
74 |
+
e.target == edge.target and
|
75 |
+
e.relation == edge.relation
|
76 |
+
for e in self.edges
|
77 |
+
):
|
78 |
+
self.edges.append(edge)
|
79 |
+
|
80 |
+
def find_by_label(self, label: str) -> Optional[Concept]:
|
81 |
+
for c in self.concepts.values():
|
82 |
+
if c.label == label:
|
83 |
+
return c
|
84 |
+
return None
|
85 |
+
|
86 |
+
def import_from_json(self, data: dict) -> dict:
|
87 |
+
nodes = data.get("nodes", [])
|
88 |
+
edges = data.get("edges", [])
|
89 |
+
|
90 |
+
if not isinstance(nodes, list) or not isinstance(edges, list):
|
91 |
+
raise ValueError("Invalid format: 'nodes' and 'edges' must be lists")
|
92 |
+
|
93 |
+
imported_nodes = 0
|
94 |
+
imported_edges = 0
|
95 |
+
|
96 |
+
for c in nodes:
|
97 |
+
try:
|
98 |
+
concept = Concept.from_dict(c)
|
99 |
+
self.add(concept)
|
100 |
+
imported_nodes += 1
|
101 |
+
except Exception as e:
|
102 |
+
print(f"Failed to import concept: {e}")
|
103 |
+
|
104 |
+
for e in edges:
|
105 |
+
try:
|
106 |
+
edge = Edge.from_dict(e)
|
107 |
+
self.add_edge(edge)
|
108 |
+
imported_edges += 1
|
109 |
+
except Exception as e:
|
110 |
+
print(f"Failed to import edge: {e}")
|
111 |
+
|
112 |
+
return {
|
113 |
+
"status": "ok",
|
114 |
+
"imported_nodes": imported_nodes,
|
115 |
+
"imported_edges": imported_edges
|
116 |
+
}
|
117 |
+
|
118 |
+
def export_as_json(self) -> GraphExport:
|
119 |
+
return GraphExport(
|
120 |
+
nodes=[c.to_dict() for c in self.concepts.values()],
|
121 |
+
edges=[e.to_dict() for e in self.edges]
|
122 |
+
)
|
123 |
+
|
124 |
+
def all_concepts(self):
|
125 |
+
return [c.to_dict() for c in self.concepts.values()]
|
126 |
+
|
127 |
+
def all_edges(self):
|
128 |
+
return [e.to_dict() for e in self.edges]
|
129 |
+
|
130 |
+
def remove_concept(self, concept_id: str):
|
131 |
+
if concept_id in self.concepts:
|
132 |
+
del self.concepts[concept_id]
|
133 |
+
self.edges = [e for e in self.edges if e.source != concept_id and e.target != concept_id]
|
134 |
+
|
135 |
+
def remove_edge(self, source_id: str, target_id: str, relation: str):
|
136 |
+
self.edges = [
|
137 |
+
e for e in self.edges
|
138 |
+
if not (e.source == source_id and e.target == target_id and e.relation == relation)
|
139 |
+
]
|
140 |
+
|
141 |
+
def debug_print(self):
|
142 |
+
print("Concepts:")
|
143 |
+
for c in self.concepts.values():
|
144 |
+
print(c.to_dict())
|
145 |
+
print("\nEdges:")
|
146 |
+
for e in self.edges:
|
147 |
+
print(e.to_dict())
|
agents/_old/db_structure.md
ADDED
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## 📦 HMP-Agent: Структура БД (v0.3, человекочитаемый формат)
|
2 |
+
|
3 |
+
---
|
4 |
+
|
5 |
+
### 🧠 Когнитивная память (Concept Graph)
|
6 |
+
|
7 |
+
#### 🧠 `memory_concepts`
|
8 |
+
|
9 |
+
**Назначение:**
|
10 |
+
Хранение концептов (единиц когнитивной памяти): понятий, фактов, образов, внутренних конструкций и внешних знаний.
|
11 |
+
|
12 |
+
**Поля:**
|
13 |
+
|
14 |
+
* `id: INTEGER` — первичный ключ.
|
15 |
+
* `label: TEXT` — человекочитаемое имя концепта.
|
16 |
+
* `type: TEXT` — тип концепта (`idea`, `object`, `goal`, `fact`, `memory_snapshot`, `mesh_entity`, …).
|
17 |
+
* `content: TEXT` — JSON-объект с содержанием концепта (например, описание, параметры, вложенные идеи).
|
18 |
+
* `context: TEXT` — дополнительный контекст (например, источник, ссылка на событие).
|
19 |
+
* `created_at: TIMESTAMP` — дата создания.
|
20 |
+
* `updated_at: TIMESTAMP` — дата последнего обновления.
|
21 |
+
|
22 |
+
**Ключевые поля:** `id`, `label`
|
23 |
+
|
24 |
+
**Связи:**
|
25 |
+
|
26 |
+
* Ссылается из `memory_links.from_id` и `to_id`
|
27 |
+
* Используется в `cognitive_cycles`, `hypotheses`, `reflections`, `reasoning_traces`
|
28 |
+
|
29 |
+
---
|
30 |
+
|
31 |
+
#### 🔗 `memory_links`
|
32 |
+
|
33 |
+
**Назначение:**
|
34 |
+
Определение связей между концептами — формирование когнитивного графа.
|
35 |
+
|
36 |
+
**Поля:**
|
37 |
+
|
38 |
+
* `id: INTEGER` — первичный ключ.
|
39 |
+
* `from_id: INTEGER` — ID исходного концепта.
|
40 |
+
* `to_id: INTEGER` — ID связанного концепта.
|
41 |
+
* `relation: TEXT` — тип связи (`causes`, `associated_with`, `contradicts`, …).
|
42 |
+
* `weight: REAL` — значимость или сила связи (по умолчанию 1.0).
|
43 |
+
|
44 |
+
**Ключевые поля:** `id`, `from_id`, `to_id`
|
45 |
+
|
46 |
+
**Связи:**
|
47 |
+
|
48 |
+
* `from_id`, `to_id → memory_concepts(id)`
|
49 |
+
|
50 |
+
---
|
51 |
+
|
52 |
+
## 📜 События, действия, сообщения
|
53 |
+
|
54 |
+
#### 🧩 `cognitive_events`
|
55 |
+
|
56 |
+
**Назначение:**
|
57 |
+
Журнал восприятия, действий и входящих/исходящих сообщений.
|
58 |
+
|
59 |
+
**Поля:**
|
60 |
+
|
61 |
+
* `id: INTEGER` — первичный ключ.
|
62 |
+
* `event_type: TEXT` — тип события (`input`, `output`, `message`, `action`, `mesh`, `internal`).
|
63 |
+
* `payload: TEXT` — сериализованные данные (обычно JSON).
|
64 |
+
* `source: TEXT` — источник события (например, ID mesh-пира).
|
65 |
+
* `target: TEXT` — целевая система или компонент.
|
66 |
+
* `created_at: TIMESTAMP` — время события.
|
67 |
+
|
68 |
+
**Ключевые поля:** `id`, `event_type`
|
69 |
+
|
70 |
+
**Связи:**
|
71 |
+
|
72 |
+
* Используется в `reflections.trigger_event_id`
|
73 |
+
|
74 |
+
---
|
75 |
+
#### 📬 `hmp_messages`
|
76 |
+
|
77 |
+
**Назначение:**
|
78 |
+
Лог входящих и исходящих сообщений в Mesh-среде.
|
79 |
+
|
80 |
+
**Поля:**
|
81 |
+
|
82 |
+
* `id: INTEGER`
|
83 |
+
* `direction: TEXT` — `inbound` или `outbound`
|
84 |
+
* `peer: TEXT` — адрес или идентификатор узла
|
85 |
+
* `payload: TEXT` — сериализованные данные (обычно JSON)
|
86 |
+
* `topic: TEXT` — категория сообщения
|
87 |
+
* `created_at: TIMESTAMP`
|
88 |
+
|
89 |
+
**Примечание:**
|
90 |
+
Адаптация к спецификации HMP должна производиться на уровне сериализации перед отправкой, а не на уровне хранения.
|
91 |
+
|
92 |
+
---
|
93 |
+
|
94 |
+
### 🔍 Гипотезы, цели, reasoning
|
95 |
+
|
96 |
+
#### 🧠 `hypotheses`
|
97 |
+
|
98 |
+
**Назначение:**
|
99 |
+
Управление гипотезами: недоказанными или частично сформированными утверждениями.
|
100 |
+
|
101 |
+
**Поля:**
|
102 |
+
|
103 |
+
* `id: INTEGER` — первичный ключ.
|
104 |
+
* `title: TEXT` — краткое описание гипотезы.
|
105 |
+
* `description: TEXT` — расширенное описание.
|
106 |
+
* `status: TEXT` — состояние (`active`, `rejected`, `confirmed`, `stale`).
|
107 |
+
* `relevance_score: REAL` — оценка актуальности (0.0–1.0).
|
108 |
+
* `evidence: TEXT` — JSON-массив ссылок на концепты, события и факты.
|
109 |
+
* `created_at: TIMESTAMP`
|
110 |
+
|
111 |
+
**Связи:**
|
112 |
+
|
113 |
+
* Может ссылаться на `memory_concepts`, `cognitive_events`
|
114 |
+
|
115 |
+
---
|
116 |
+
|
117 |
+
#### 🎯 `goals`
|
118 |
+
|
119 |
+
**Назначение:**
|
120 |
+
Управление целями агента — формулировка намерений и задач.
|
121 |
+
|
122 |
+
**Поля:**
|
123 |
+
|
124 |
+
* `id: INTEGER` — первичный ключ.
|
125 |
+
* `description: TEXT` — формулировка цели.
|
126 |
+
* `priority: INTEGER` — приоритет (1 = максимальный).
|
127 |
+
* `status: TEXT` — текущее состояние (`pending`, `in_progress`, `completed`, `abandoned`).
|
128 |
+
* `context: TEXT` — допо��нительная информация.
|
129 |
+
* `created_at`, `updated_at: TIMESTAMP`
|
130 |
+
|
131 |
+
---
|
132 |
+
|
133 |
+
#### 🔁 `cognitive_cycles`
|
134 |
+
|
135 |
+
**Назначение:**
|
136 |
+
История reasoning-процессов: единиц когнитивной активности, отражающих ход размышлений.
|
137 |
+
|
138 |
+
**Поля:**
|
139 |
+
|
140 |
+
* `id: INTEGER` — первичный ключ.
|
141 |
+
* `cycle_number: INTEGER` — порядковый номер итерации.
|
142 |
+
* `thoughts: TEXT` — массив мыслей в формате JSON.
|
143 |
+
* `new_concepts: TEXT` — ID новых концептов, сформированных в ходе цикла.
|
144 |
+
* `actions_taken: TEXT` — предпринятые действия.
|
145 |
+
* `context_snapshot: TEXT` — снимок состояния.
|
146 |
+
* `started_at`, `ended_at: TIMESTAMP`
|
147 |
+
|
148 |
+
**Связи:**
|
149 |
+
|
150 |
+
* Используется в `reflections`, `reasoning_traces`, `agent_state_snapshots`
|
151 |
+
|
152 |
+
---
|
153 |
+
|
154 |
+
### 🧬 Версионирование, артефакты, кодексы
|
155 |
+
|
156 |
+
#### 📦 `versioned_artifacts`
|
157 |
+
|
158 |
+
**Назначение:**
|
159 |
+
Хранение версии артефактов: конфигураций, моделей, API-структур.
|
160 |
+
|
161 |
+
**Поля:**
|
162 |
+
|
163 |
+
* `id: INTEGER`
|
164 |
+
* `name: TEXT` — идентификатор артефакта (`api_structure`, `core_config`, `agent_traits`)
|
165 |
+
* `version: TEXT` — версионирование (e.g., `2025-07-22.1`)
|
166 |
+
* `content: TEXT` — JSON или Markdown
|
167 |
+
* `created_at: TIMESTAMP`
|
168 |
+
|
169 |
+
Отлично! Текущий `db_structure.md` уже хорошо структурирован, и его можно расширить, добавив недостающие таблицы. Вот предложения по доработке:
|
170 |
+
|
171 |
+
---
|
172 |
+
|
173 |
+
### 🧬 Версионирование, артефакты, кодексы
|
174 |
+
|
175 |
+
#### 🧾 `agent_policies`
|
176 |
+
|
177 |
+
**Назначение:**
|
178 |
+
Хранение деклараций, этических норм, стратегий и ограничений поведения агента.
|
179 |
+
|
180 |
+
**Поля:**
|
181 |
+
|
182 |
+
* `id: INTEGER` — первичный ключ.
|
183 |
+
* `policy_type: TEXT` — тип (`ethics`, `exploration`, `safety`, `prioritization`, …).
|
184 |
+
* `name: TEXT` — краткое название политики.
|
185 |
+
* `content: TEXT` — Markdown или JSON-содержимое.
|
186 |
+
* `created_at: TIMESTAMP` — дата создания.
|
187 |
+
|
188 |
+
**Примечание:**
|
189 |
+
Может быть использована при принятии решений или фильтрации гипотез/действий.
|
190 |
+
|
191 |
+
---
|
192 |
+
|
193 |
+
### ⚙️ Модули и состояния
|
194 |
+
|
195 |
+
#### 🧩 `modules_state`
|
196 |
+
|
197 |
+
**Назначение:**
|
198 |
+
Отслеживание состояния и локальной памяти когнитивных модулей (например, рефлексии, генерации гипотез, плана).
|
199 |
+
|
200 |
+
**Поля:**
|
201 |
+
|
202 |
+
* `id: INTEGER` — первичный ключ.
|
203 |
+
* `module_name: TEXT` — имя модуля (`reflection`, `planner`, `input_handler`, …).
|
204 |
+
* `status: TEXT` — текущее состояние (`idle`, `running`, `paused`, `error`).
|
205 |
+
* `memory: TEXT` — сериализованное состояние (JSON).
|
206 |
+
* `last_heartbeat: TIMESTAMP` — последнее обновление.
|
207 |
+
|
208 |
+
---
|
209 |
+
|
210 |
+
### 📓 Агентский дневник
|
211 |
+
|
212 |
+
#### 📖 `diary_entries`
|
213 |
+
|
214 |
+
**Назначение:**
|
215 |
+
Журнал размышлений, наблюдений, воспоминаний или метакомментариев, созданных агентом или пользователем.
|
216 |
+
|
217 |
+
**Поля:**
|
218 |
+
|
219 |
+
* `id: INTEGER` — первичный ключ.
|
220 |
+
* `entry_type: TEXT` — тип (`reflection`, `note`, `observation`, `self_report`, `dialog`, …).
|
221 |
+
* `content: TEXT` — основное содержимое записи.
|
222 |
+
* `related_concepts: TEXT` — JSON-массив `concept_id`, с которыми связана запись.
|
223 |
+
* `created_at: TIMESTAMP`
|
agents/_old/db_structure.sql
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
-- Хранение концептов (единиц когнитивной памяти): понятий, фактов, образов, внутренних конструкций и внешних знаний.
|
2 |
+
CREATE TABLE memory_concepts (
|
3 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
4 |
+
label TEXT NOT NULL,
|
5 |
+
type TEXT,
|
6 |
+
content TEXT, -- JSON-данные или сериализованный объект
|
7 |
+
context TEXT, -- Дополнительный контекст
|
8 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
9 |
+
updated_at TIMESTAMP
|
10 |
+
);
|
11 |
+
|
12 |
+
-- Определение связей между концептами — формирование когнитивного графа.
|
13 |
+
CREATE TABLE memory_links (
|
14 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
15 |
+
from_id INTEGER,
|
16 |
+
to_id INTEGER,
|
17 |
+
relation TEXT, -- Тип связи (e.g., 'causes', 'associated_with')
|
18 |
+
weight REAL DEFAULT 1.0,
|
19 |
+
FOREIGN KEY(from_id) REFERENCES memory_concepts(id),
|
20 |
+
FOREIGN KEY(to_id) REFERENCES memory_concepts(id)
|
21 |
+
);
|
22 |
+
|
23 |
+
-- Журнал восприятия, действий и входящих/исходящих сообщений.
|
24 |
+
CREATE TABLE cognitive_events (
|
25 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
26 |
+
event_type TEXT, -- e.g., 'input', 'action', 'message'
|
27 |
+
payload TEXT, -- JSON-строка или сериализованный объект
|
28 |
+
source TEXT, -- Откуда пришло (если применимо)
|
29 |
+
target TEXT, -- Кому отправлено (если применимо)
|
30 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
31 |
+
);
|
32 |
+
|
33 |
+
-- Управление гипотезами: недоказанными или частично сформированными утверждениями.
|
34 |
+
CREATE TABLE hypotheses (
|
35 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
36 |
+
title TEXT,
|
37 |
+
description TEXT,
|
38 |
+
status TEXT DEFAULT 'active', -- 'active', 'rejected', 'confirmed'
|
39 |
+
relevance_score REAL DEFAULT 0.5,
|
40 |
+
evidence TEXT, -- JSON (ссылки на события, концепты)
|
41 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
42 |
+
);
|
43 |
+
|
44 |
+
-- Управление целями агента — формулировка намерений и задач.
|
45 |
+
CREATE TABLE goals (
|
46 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
47 |
+
description TEXT,
|
48 |
+
priority INTEGER DEFAULT 5, -- 1 = high priority
|
49 |
+
status TEXT DEFAULT 'pending', -- 'pending', 'in_progress', 'completed', 'abandoned'
|
50 |
+
context TEXT,
|
51 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
52 |
+
updated_at TIMESTAMP
|
53 |
+
);
|
54 |
+
|
55 |
+
-- Лог входящих и исходящих сообщений в Mesh-среде.
|
56 |
+
CREATE TABLE hmp_messages (
|
57 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
58 |
+
direction TEXT, -- 'inbound' | 'outbound'
|
59 |
+
peer TEXT, -- ID или адрес другого агента
|
60 |
+
payload TEXT, -- JSON
|
61 |
+
topic TEXT,
|
62 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
63 |
+
);
|
64 |
+
|
65 |
+
-- История reasoning-процессов: единиц когнитивной активности, отражающих ход размышлений.
|
66 |
+
CREATE TABLE cognitive_cycles (
|
67 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
68 |
+
cycle_number INTEGER,
|
69 |
+
thoughts TEXT, -- JSON-массив мыслей
|
70 |
+
new_concepts TEXT,
|
71 |
+
actions_taken TEXT,
|
72 |
+
context_snapshot TEXT,
|
73 |
+
started_at TIMESTAMP,
|
74 |
+
ended_at TIMESTAMP
|
75 |
+
);
|
76 |
+
|
77 |
+
-- Хранение версии артефактов: конфигураций, моделей, API-структур.
|
78 |
+
CREATE TABLE versioned_artifacts (
|
79 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
80 |
+
name TEXT, -- например, 'api_structure', 'cognitive_core_config'
|
81 |
+
version TEXT,
|
82 |
+
content TEXT, -- JSON или Markdown
|
83 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
84 |
+
);
|
85 |
+
|
86 |
+
-- Хранение деклараций, этических норм, стратегий и ограничений поведения агента.
|
87 |
+
CREATE TABLE IF NOT EXISTS agent_policies (
|
88 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
89 |
+
policy_type TEXT NOT NULL,
|
90 |
+
name TEXT NOT NULL,
|
91 |
+
content TEXT NOT NULL,
|
92 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
93 |
+
);
|
94 |
+
|
95 |
+
-- Отслеживание состояния и локальной памяти когнитивных модулей (например, рефлексии, генерации гипотез, плана).
|
96 |
+
CREATE TABLE IF NOT EXISTS modules_state (
|
97 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
98 |
+
module_name TEXT NOT NULL,
|
99 |
+
status TEXT NOT NULL,
|
100 |
+
memory TEXT,
|
101 |
+
last_heartbeat TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
102 |
+
);
|
103 |
+
|
104 |
+
-- Журнал размышлений, наблюдений, воспоминаний или метакомментариев, созданных агентом или пользователем.
|
105 |
+
CREATE TABLE IF NOT EXISTS diary_entries (
|
106 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
107 |
+
entry_type TEXT NOT NULL,
|
108 |
+
content TEXT NOT NULL,
|
109 |
+
related_concepts TEXT,
|
110 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
111 |
+
);
|
agents/_old/mcp_server.py
ADDED
@@ -0,0 +1,374 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# agents/mcp_server.py
|
2 |
+
|
3 |
+
from fastapi import FastAPI, Request, HTTPException
|
4 |
+
from fastapi.middleware.cors import CORSMiddleware
|
5 |
+
from flask import Flask, request, jsonify
|
6 |
+
from pydantic import BaseModel
|
7 |
+
from typing import List, Optional
|
8 |
+
from datetime import datetime
|
9 |
+
from models import GraphExport
|
10 |
+
from storage import Storage
|
11 |
+
from tools.concept_store import ConceptStore
|
12 |
+
from tools.notebook_store import NotebookStore
|
13 |
+
import random
|
14 |
+
|
15 |
+
app = FastAPI(title="HMP MCP-Agent API", version="0.1")
|
16 |
+
|
17 |
+
# Добавляем CORS (полезно, если API вызывается с веб-клиента)
|
18 |
+
app.add_middleware(
|
19 |
+
CORSMiddleware,
|
20 |
+
allow_origins=["*"], # Можем позже ограничить, если потребуется
|
21 |
+
allow_credentials=True,
|
22 |
+
allow_methods=["*"],
|
23 |
+
allow_headers=["*"],
|
24 |
+
)
|
25 |
+
|
26 |
+
# Инициализация хранилищ
|
27 |
+
concept_store = ConceptStore()
|
28 |
+
notebook_store = NotebookStore()
|
29 |
+
db = Storage()
|
30 |
+
|
31 |
+
# === Модели запроса/ответа ===
|
32 |
+
|
33 |
+
class EntryInput(BaseModel):
|
34 |
+
text: str
|
35 |
+
tags: Optional[List[str]] = []
|
36 |
+
timestamp: Optional[str] = None
|
37 |
+
|
38 |
+
class EntryOutput(BaseModel):
|
39 |
+
id: int
|
40 |
+
text: str
|
41 |
+
tags: List[str]
|
42 |
+
timestamp: str
|
43 |
+
|
44 |
+
class EntryListOutput(BaseModel):
|
45 |
+
entries: List[EntryOutput]
|
46 |
+
|
47 |
+
class ConceptInput(BaseModel):
|
48 |
+
name: str
|
49 |
+
description: Optional[str] = None
|
50 |
+
|
51 |
+
class ConceptOutput(BaseModel):
|
52 |
+
concept_id: int
|
53 |
+
|
54 |
+
class LinkInput(BaseModel):
|
55 |
+
source_id: int
|
56 |
+
target_id: int
|
57 |
+
relation: str
|
58 |
+
|
59 |
+
class LinkOutput(BaseModel):
|
60 |
+
link_id: int
|
61 |
+
|
62 |
+
class Node(BaseModel):
|
63 |
+
id: str
|
64 |
+
label: str
|
65 |
+
tags: List[str] = []
|
66 |
+
|
67 |
+
class Edge(BaseModel):
|
68 |
+
source: str
|
69 |
+
target: str
|
70 |
+
relation: str
|
71 |
+
|
72 |
+
class GraphImportData(BaseModel):
|
73 |
+
nodes: List[Node] = []
|
74 |
+
edges: List[Edge] = []
|
75 |
+
|
76 |
+
class GraphExpansionOutput(BaseModel):
|
77 |
+
links: List[Edge]
|
78 |
+
|
79 |
+
class Concept(BaseModel):
|
80 |
+
concept_id: int
|
81 |
+
name: str
|
82 |
+
description: Optional[str] = None
|
83 |
+
|
84 |
+
class ConceptQueryOutput(BaseModel):
|
85 |
+
matches: List[Concept]
|
86 |
+
|
87 |
+
class DiaryEntry(BaseModel):
|
88 |
+
id: int
|
89 |
+
text: str
|
90 |
+
tags: List[str]
|
91 |
+
timestamp: str
|
92 |
+
|
93 |
+
class DiaryExport(BaseModel):
|
94 |
+
entries: List[DiaryEntry]
|
95 |
+
|
96 |
+
class ConceptExport(BaseModel):
|
97 |
+
id: int
|
98 |
+
name: str
|
99 |
+
description: Optional[str] = None
|
100 |
+
|
101 |
+
class LinkExport(BaseModel):
|
102 |
+
id: int
|
103 |
+
source_id: int
|
104 |
+
target_id: int
|
105 |
+
relation: str
|
106 |
+
|
107 |
+
class GraphExport(BaseModel):
|
108 |
+
concepts: List[ConceptExport]
|
109 |
+
links: List[LinkExport]
|
110 |
+
|
111 |
+
class ConceptUpdate(BaseModel):
|
112 |
+
name: Optional[str] = None
|
113 |
+
description: Optional[str] = None
|
114 |
+
|
115 |
+
# === Эндпойнты ===
|
116 |
+
|
117 |
+
@app.get("/status")
|
118 |
+
def status():
|
119 |
+
return {
|
120 |
+
"status": "ok",
|
121 |
+
"agent": "HMP-MCP",
|
122 |
+
"timestamp": datetime.utcnow().isoformat()
|
123 |
+
}
|
124 |
+
|
125 |
+
@app.post("/write_entry", response_model=dict)
|
126 |
+
def write_entry(entry: EntryInput):
|
127 |
+
db.write_entry(entry.text, entry.tags)
|
128 |
+
return {"result": "entry saved"}
|
129 |
+
|
130 |
+
@app.get("/read_entries", response_model=EntryListOutput)
|
131 |
+
def read_entries(limit: int = 5, tag: Optional[str] = None):
|
132 |
+
raw = db.read_entries(limit=limit, tag_filter=tag)
|
133 |
+
return {
|
134 |
+
"entries": [
|
135 |
+
{
|
136 |
+
"id": r[0],
|
137 |
+
"text": r[1],
|
138 |
+
"tags": r[2].split(",") if r[2] else [],
|
139 |
+
"timestamp": r[3]
|
140 |
+
} for r in raw
|
141 |
+
]
|
142 |
+
}
|
143 |
+
|
144 |
+
@app.get("/")
|
145 |
+
def root():
|
146 |
+
return {"message": "HMP MCP-Agent API is running"}
|
147 |
+
|
148 |
+
@app.post("/add_concept", response_model=ConceptOutput)
|
149 |
+
def add_concept(concept: ConceptInput):
|
150 |
+
cid = db.add_concept(concept.name, concept.description)
|
151 |
+
return {"concept_id": cid}
|
152 |
+
|
153 |
+
@app.post("/add_link", response_model=LinkOutput)
|
154 |
+
def add_link(link: LinkInput):
|
155 |
+
link_id = db.add_link(link.source_id, link.target_id, link.relation)
|
156 |
+
return {"link_id": link_id}
|
157 |
+
|
158 |
+
@app.get("/expand_graph", response_model=GraphExpansionOutput)
|
159 |
+
def expand_graph(start_id: int, depth: int = 1):
|
160 |
+
raw_links = db.expand_graph(start_id, depth)
|
161 |
+
edges = [{"source_id": s, "target_id": t, "relation": r} for s, t, r in raw_links]
|
162 |
+
return {"links": edges}
|
163 |
+
|
164 |
+
@app.get("/query_concept", response_model=ConceptQueryOutput)
|
165 |
+
def query_concept(name: str):
|
166 |
+
results = db.query_concept(name)
|
167 |
+
return {
|
168 |
+
"matches": [
|
169 |
+
{"concept_id": row[0], "name": row[1], "description": row[2]}
|
170 |
+
for row in results
|
171 |
+
]
|
172 |
+
}
|
173 |
+
|
174 |
+
@app.get("/list_concepts", response_model=List[Concept])
|
175 |
+
def list_concepts():
|
176 |
+
rows = db.list_concepts()
|
177 |
+
return [
|
178 |
+
{"concept_id": row[0], "name": row[1], "description": row[2]}
|
179 |
+
for row in rows
|
180 |
+
]
|
181 |
+
|
182 |
+
@app.get("/list_links", response_model=List[Edge])
|
183 |
+
def list_links():
|
184 |
+
rows = db.list_links()
|
185 |
+
return [
|
186 |
+
{"source_id": row[1], "target_id": row[2], "relation": row[3]}
|
187 |
+
for row in rows
|
188 |
+
]
|
189 |
+
|
190 |
+
@app.delete("/delete_concept/{concept_id}")
|
191 |
+
def delete_concept(concept_id: int):
|
192 |
+
db.delete_concept(concept_id)
|
193 |
+
return {"result": f"concept {concept_id} deleted"}
|
194 |
+
|
195 |
+
@app.delete("/delete_link/{link_id}")
|
196 |
+
def delete_link(link_id: int):
|
197 |
+
db.delete_link(link_id)
|
198 |
+
return {"result": f"link {link_id} deleted"}
|
199 |
+
|
200 |
+
@app.delete("/delete_entry/{entry_id}")
|
201 |
+
def delete_entry(entry_id: int):
|
202 |
+
db.delete_entry(entry_id)
|
203 |
+
return {"result": f"entry {entry_id} deleted"}
|
204 |
+
|
205 |
+
@app.get("/export_diary", response_model=DiaryExport)
|
206 |
+
def export_diary():
|
207 |
+
rows = db.export_diary()
|
208 |
+
return {
|
209 |
+
"entries": [
|
210 |
+
{
|
211 |
+
"id": r[0],
|
212 |
+
"text": r[1],
|
213 |
+
"tags": r[2].split(",") if r[2] else [],
|
214 |
+
"timestamp": r[3]
|
215 |
+
}
|
216 |
+
for r in rows
|
217 |
+
]
|
218 |
+
}
|
219 |
+
|
220 |
+
@app.get("/export_graph", response_model=GraphExport)
|
221 |
+
def export_graph():
|
222 |
+
return concept_store.export_as_json()
|
223 |
+
|
224 |
+
@app.put("/update_concept/{concept_id}")
|
225 |
+
def update_concept(concept_id: int, update: ConceptUpdate):
|
226 |
+
db.update_concept(concept_id, update.name, update.description)
|
227 |
+
return {"result": f"concept {concept_id} updated"}
|
228 |
+
|
229 |
+
@app.get("/tag_stats", response_model=dict)
|
230 |
+
def tag_stats():
|
231 |
+
return db.get_tag_stats()
|
232 |
+
|
233 |
+
@app.get("/search_links", response_model=List[LinkExport])
|
234 |
+
def search_links(relation: str):
|
235 |
+
rows = db.search_links_by_relation(relation)
|
236 |
+
return [
|
237 |
+
{
|
238 |
+
"id": row[0],
|
239 |
+
"source_id": row[1],
|
240 |
+
"target_id": row[2],
|
241 |
+
"relation": row[3]
|
242 |
+
}
|
243 |
+
for row in rows
|
244 |
+
]
|
245 |
+
|
246 |
+
@app.get("/search_concepts", response_model=List[Concept])
|
247 |
+
def search_concepts(query: str):
|
248 |
+
results = db.search_concepts(query)
|
249 |
+
return [
|
250 |
+
{"concept_id": row[0], "name": row[1], "description": row[2]}
|
251 |
+
for row in results
|
252 |
+
]
|
253 |
+
|
254 |
+
@app.post("/merge_concepts", response_model=dict)
|
255 |
+
def merge_concepts(source_id: int, target_id: int):
|
256 |
+
db.merge_concepts(source_id, target_id)
|
257 |
+
return {"result": f"concept {source_id} merged into {target_id}"}
|
258 |
+
|
259 |
+
@app.post("/relate_concepts", response_model=LinkOutput)
|
260 |
+
def relate_concepts(source_name: str, target_name: str, relation: str):
|
261 |
+
sid = db.find_concept_id_by_name(source_name)
|
262 |
+
tid = db.find_concept_id_by_name(target_name)
|
263 |
+
if sid is None or tid is None:
|
264 |
+
raise HTTPException(status_code=404, detail="Concept not found")
|
265 |
+
link_id = db.add_link(sid, tid, relation)
|
266 |
+
return {"link_id": link_id}
|
267 |
+
|
268 |
+
@app.get("/tag_cloud", response_model=dict)
|
269 |
+
def tag_cloud():
|
270 |
+
return db.get_tag_stats()
|
271 |
+
|
272 |
+
@app.get("/get_concept/{concept_id}")
|
273 |
+
def get_concept(concept_id: str):
|
274 |
+
concept = concept_store.get(concept_id)
|
275 |
+
if concept:
|
276 |
+
return concept
|
277 |
+
raise HTTPException(status_code=404, detail="Concept not found")
|
278 |
+
|
279 |
+
@app.get("/get_entry/{entry_id}")
|
280 |
+
def get_entry(entry_id: str):
|
281 |
+
entry = notebook_store.get(entry_id)
|
282 |
+
if entry:
|
283 |
+
return entry
|
284 |
+
raise HTTPException(status_code=404, detail="Entry not found")
|
285 |
+
|
286 |
+
@app.post("/search_entries")
|
287 |
+
def search_entries(query: str):
|
288 |
+
results = notebook_store.search(query)
|
289 |
+
return results
|
290 |
+
|
291 |
+
@app.post("/import_graph")
|
292 |
+
def import_graph(graph_data: GraphImportData):
|
293 |
+
concept_store.import_from_json(graph_data.dict())
|
294 |
+
print(f"[INFO] Imported {len(graph_data.nodes)} nodes, {len(graph_data.edges)} edges")
|
295 |
+
return {"status": "ok"}
|
296 |
+
|
297 |
+
# === Notebook API ===
|
298 |
+
|
299 |
+
@app.post("/notebook/add")
|
300 |
+
async def add_note(req: Request):
|
301 |
+
data = await req.json()
|
302 |
+
text = data.get("text", "").strip()
|
303 |
+
if not text:
|
304 |
+
return {"status": "error", "message": "Empty text"}
|
305 |
+
notebook.add_note(text, source="user")
|
306 |
+
return {"status": "ok", "message": "Note added"}
|
307 |
+
|
308 |
+
@app.get("/notebook/next")
|
309 |
+
def get_next_note():
|
310 |
+
note = notebook.get_first_unread_note()
|
311 |
+
if note:
|
312 |
+
note_id, text, source, timestamp, tags = note
|
313 |
+
return {
|
314 |
+
"id": note_id,
|
315 |
+
"text": text,
|
316 |
+
"source": source,
|
317 |
+
"timestamp": timestamp,
|
318 |
+
"tags": tags
|
319 |
+
}
|
320 |
+
return {"status": "empty", "message": "No unread notes"}
|
321 |
+
|
322 |
+
@app.post("/notebook/mark_read")
|
323 |
+
async def mark_note_read(req: Request):
|
324 |
+
data = await req.json()
|
325 |
+
note_id = data.get("id")
|
326 |
+
if note_id is not None:
|
327 |
+
notebook.mark_note_as_read(note_id)
|
328 |
+
return {"status": "ok"}
|
329 |
+
return {"status": "error", "message": "Missing note id"}
|
330 |
+
|
331 |
+
# === ✨ Дополнительные эндпоинты для заметок ===
|
332 |
+
|
333 |
+
@app.route("/notes/latest", methods=["GET"])
|
334 |
+
def get_latest_notes():
|
335 |
+
"""Вернуть последние N заметок (по умолчанию 10)."""
|
336 |
+
count = int(request.args.get("count", 10))
|
337 |
+
notes = storage.diary[-count:]
|
338 |
+
return jsonify([note.to_dict() for note in notes])
|
339 |
+
|
340 |
+
@app.route("/notes/random", methods=["GET"])
|
341 |
+
def get_random_note():
|
342 |
+
"""Вернуть случайную заметку из дневника."""
|
343 |
+
if not storage.diary:
|
344 |
+
return jsonify({})
|
345 |
+
note = random.choice(storage.diary)
|
346 |
+
return jsonify(note.to_dict())
|
347 |
+
|
348 |
+
@app.route("/notes/set_tags", methods=["POST"])
|
349 |
+
def set_tags():
|
350 |
+
"""Обновить теги у заметки по ID."""
|
351 |
+
data = request.json
|
352 |
+
note_id = data.get("id")
|
353 |
+
tags = data.get("tags", [])
|
354 |
+
for note in storage.diary:
|
355 |
+
if note.id == note_id:
|
356 |
+
note.tags = tags
|
357 |
+
return jsonify({"status": "ok"})
|
358 |
+
return jsonify({"error": "not found"}), 404
|
359 |
+
|
360 |
+
@app.route("/notes/by_tag", methods=["GET"])
|
361 |
+
def get_notes_by_tag():
|
362 |
+
tag = request.args.get("tag")
|
363 |
+
result = [note.to_dict() for note in storage.diary if tag in note.tags]
|
364 |
+
return jsonify(result)
|
365 |
+
|
366 |
+
# === Run ===
|
367 |
+
if __name__ == "__main__":
|
368 |
+
uvicorn.run("mcp_server:app", host="0.0.0.0", port=8080, reload=True)
|
369 |
+
|
370 |
+
# === Shutdown ===
|
371 |
+
|
372 |
+
@app.on_event("shutdown")
|
373 |
+
def shutdown():
|
374 |
+
db.close()
|
agents/_old/notebook_store.py
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# agents/tools/notebook_store.py
|
2 |
+
|
3 |
+
import sqlite3
|
4 |
+
from datetime import datetime
|
5 |
+
from pathlib import Path
|
6 |
+
|
7 |
+
DB_FILE = "notepad.db"
|
8 |
+
|
9 |
+
class Notebook:
|
10 |
+
def __init__(self, db_path=DB_FILE):
|
11 |
+
self.conn = sqlite3.connect(db_path)
|
12 |
+
self._init_db()
|
13 |
+
|
14 |
+
def _init_db(self):
|
15 |
+
c = self.conn.cursor()
|
16 |
+
c.execute('''
|
17 |
+
CREATE TABLE IF NOT EXISTS notes (
|
18 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
19 |
+
text TEXT NOT NULL,
|
20 |
+
source TEXT DEFAULT 'user',
|
21 |
+
timestamp TEXT NOT NULL,
|
22 |
+
read INTEGER DEFAULT 0,
|
23 |
+
tags TEXT
|
24 |
+
)
|
25 |
+
''')
|
26 |
+
self.conn.commit()
|
27 |
+
|
28 |
+
def add_note(self, text, source="user"):
|
29 |
+
ts = datetime.utcnow().isoformat()
|
30 |
+
self.conn.execute(
|
31 |
+
'INSERT INTO notes (text, source, timestamp) VALUES (?, ?, ?)',
|
32 |
+
(text.strip(), source, ts)
|
33 |
+
)
|
34 |
+
self.conn.commit()
|
35 |
+
|
36 |
+
def get_latest_notes(self, limit=10):
|
37 |
+
cursor = self.conn.cursor()
|
38 |
+
cursor.execute(
|
39 |
+
'SELECT id, text, source, timestamp FROM notes ORDER BY id DESC LIMIT ?',
|
40 |
+
(limit,)
|
41 |
+
)
|
42 |
+
return cursor.fetchall()
|
43 |
+
|
44 |
+
def get_notes_after(self, since_ts):
|
45 |
+
cursor = self.conn.cursor()
|
46 |
+
cursor.execute(
|
47 |
+
'SELECT id, text, source, timestamp FROM notes WHERE timestamp > ? ORDER BY timestamp',
|
48 |
+
(since_ts,)
|
49 |
+
)
|
50 |
+
return cursor.fetchall()
|
51 |
+
|
52 |
+
def get_first_unread_note(self):
|
53 |
+
cursor = self.conn.cursor()
|
54 |
+
cursor.execute(
|
55 |
+
"SELECT id, text, source, timestamp, tags FROM notes WHERE read = 0 ORDER BY id ASC LIMIT 1"
|
56 |
+
)
|
57 |
+
return cursor.fetchone()
|
58 |
+
|
59 |
+
def mark_note_as_read(self, note_id: int):
|
60 |
+
self.conn.execute(
|
61 |
+
"UPDATE notes SET read = 1 WHERE id = ?",
|
62 |
+
(note_id,)
|
63 |
+
)
|
64 |
+
self.conn.commit()
|
65 |
+
|
66 |
+
def set_tags(self, note_id: int, tags: list[str]):
|
67 |
+
tag_str = ",".join(tags)
|
68 |
+
self.conn.execute(
|
69 |
+
"UPDATE notes SET tags = ? WHERE id = ?",
|
70 |
+
(tag_str, note_id)
|
71 |
+
)
|
72 |
+
self.conn.commit()
|
73 |
+
|
74 |
+
def get_random_note_by_tags(self, include_tags: list[str]):
|
75 |
+
cursor = self.conn.cursor()
|
76 |
+
like_clauses = " OR ".join(["tags LIKE ?"] * len(include_tags))
|
77 |
+
values = [f"%{tag}%" for tag in include_tags]
|
78 |
+
query = f"""
|
79 |
+
SELECT id, text, source, timestamp, tags
|
80 |
+
FROM notes
|
81 |
+
WHERE ({like_clauses})
|
82 |
+
ORDER BY RANDOM()
|
83 |
+
LIMIT 1
|
84 |
+
"""
|
85 |
+
cursor.execute(query, values)
|
86 |
+
return cursor.fetchone()
|
87 |
+
|
88 |
+
def close(self):
|
89 |
+
self.conn.close()
|
agents/_old/storage.py
ADDED
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# agents/storage.py
|
2 |
+
|
3 |
+
import sqlite3
|
4 |
+
from datetime import datetime
|
5 |
+
|
6 |
+
DEFAULT_DB_PATH = "agent_storage.db"
|
7 |
+
|
8 |
+
class Storage:
|
9 |
+
def __init__(self, config=None):
|
10 |
+
self.config = config or {}
|
11 |
+
db_path = self.config.get("db_path", DEFAULT_DB_PATH)
|
12 |
+
self.conn = sqlite3.connect(db_path)
|
13 |
+
self._init_db()
|
14 |
+
|
15 |
+
def _init_db(self):
|
16 |
+
c = self.conn.cursor()
|
17 |
+
# 🧠 Таблица дневника
|
18 |
+
c.execute('''
|
19 |
+
CREATE TABLE IF NOT EXISTS diary_entries (
|
20 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
21 |
+
text TEXT NOT NULL,
|
22 |
+
tags TEXT,
|
23 |
+
timestamp TEXT NOT NULL
|
24 |
+
)
|
25 |
+
''')
|
26 |
+
# 📚 Таблица концептов
|
27 |
+
c.execute('''
|
28 |
+
CREATE TABLE IF NOT EXISTS concepts (
|
29 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
30 |
+
name TEXT NOT NULL,
|
31 |
+
description TEXT
|
32 |
+
)
|
33 |
+
''')
|
34 |
+
# 🔗 Таблица связей
|
35 |
+
c.execute('''
|
36 |
+
CREATE TABLE IF NOT EXISTS links (
|
37 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
38 |
+
source_id INTEGER,
|
39 |
+
target_id INTEGER,
|
40 |
+
relation TEXT,
|
41 |
+
FOREIGN KEY(source_id) REFERENCES concepts(id),
|
42 |
+
FOREIGN KEY(target_id) REFERENCES concepts(id)
|
43 |
+
)
|
44 |
+
''')
|
45 |
+
self.conn.commit()
|
46 |
+
|
47 |
+
# --- 🧠 Diary API ---
|
48 |
+
def write_entry(self, text, tags=None):
|
49 |
+
timestamp = datetime.utcnow().isoformat()
|
50 |
+
tag_str = ",".join(tags) if tags else ""
|
51 |
+
self.conn.execute(
|
52 |
+
'INSERT INTO diary_entries (text, tags, timestamp) VALUES (?, ?, ?)',
|
53 |
+
(text, tag_str, timestamp)
|
54 |
+
)
|
55 |
+
self.conn.commit()
|
56 |
+
|
57 |
+
def read_entries(self, limit=10, tag_filter=None):
|
58 |
+
cursor = self.conn.cursor()
|
59 |
+
if tag_filter:
|
60 |
+
# Простейшая фильтрация по включению строки
|
61 |
+
if isinstance(tag_filter, list):
|
62 |
+
tag_filter = ",".join(tag_filter)
|
63 |
+
like_expr = f"%{tag_filter}%"
|
64 |
+
cursor.execute(
|
65 |
+
'SELECT * FROM diary_entries WHERE tags LIKE ? ORDER BY id DESC LIMIT ?',
|
66 |
+
(like_expr, limit)
|
67 |
+
)
|
68 |
+
else:
|
69 |
+
cursor.execute(
|
70 |
+
'SELECT * FROM diary_entries ORDER BY id DESC LIMIT ?',
|
71 |
+
(limit,)
|
72 |
+
)
|
73 |
+
return cursor.fetchall()
|
74 |
+
|
75 |
+
def search_entries_by_time(self, from_ts, to_ts):
|
76 |
+
cursor = self.conn.cursor()
|
77 |
+
cursor.execute(
|
78 |
+
'SELECT * FROM diary_entries WHERE timestamp BETWEEN ? AND ? ORDER BY timestamp DESC',
|
79 |
+
(from_ts, to_ts)
|
80 |
+
)
|
81 |
+
return cursor.fetchall()
|
82 |
+
|
83 |
+
# --- 🧠 Semantic Graph API ---
|
84 |
+
def add_concept(self, name, description=None):
|
85 |
+
cursor = self.conn.cursor()
|
86 |
+
cursor.execute(
|
87 |
+
'INSERT INTO concepts (name, description) VALUES (?, ?)',
|
88 |
+
(name, description)
|
89 |
+
)
|
90 |
+
self.conn.commit()
|
91 |
+
return cursor.lastrowid
|
92 |
+
|
93 |
+
def query_concept(self, name_substr):
|
94 |
+
cursor = self.conn.execute(
|
95 |
+
'SELECT id, name, description FROM concepts WHERE name LIKE ?',
|
96 |
+
(f"%{name_substr}%",)
|
97 |
+
)
|
98 |
+
return cursor.fetchall()
|
99 |
+
|
100 |
+
def add_link(self, source_id, target_id, relation):
|
101 |
+
cursor = self.conn.cursor()
|
102 |
+
cursor.execute(
|
103 |
+
'INSERT INTO links (source_id, target_id, relation) VALUES (?, ?, ?)',
|
104 |
+
(source_id, target_id, relation)
|
105 |
+
)
|
106 |
+
self.conn.commit()
|
107 |
+
return cursor.lastrowid
|
108 |
+
|
109 |
+
def list_concepts(self):
|
110 |
+
return self.conn.execute('SELECT * FROM concepts').fetchall()
|
111 |
+
|
112 |
+
def list_links(self):
|
113 |
+
return self.conn.execute('SELECT * FROM links').fetchall()
|
114 |
+
|
115 |
+
def expand_graph(self, start_id, depth):
|
116 |
+
visited = set()
|
117 |
+
results = []
|
118 |
+
|
119 |
+
def dfs(node_id, level):
|
120 |
+
if level > depth or node_id in visited:
|
121 |
+
return
|
122 |
+
visited.add(node_id)
|
123 |
+
cursor = self.conn.execute(
|
124 |
+
'SELECT source_id, target_id, relation FROM links WHERE source_id=?',
|
125 |
+
(node_id,)
|
126 |
+
)
|
127 |
+
for row in cursor.fetchall():
|
128 |
+
results.append(row)
|
129 |
+
dfs(row[1], level + 1)
|
130 |
+
|
131 |
+
dfs(start_id, 0)
|
132 |
+
return results
|
133 |
+
|
134 |
+
def delete_concept(self, concept_id):
|
135 |
+
self.conn.execute('DELETE FROM concepts WHERE id = ?', (concept_id,))
|
136 |
+
self.conn.execute('DELETE FROM links WHERE source_id = ? OR target_id = ?', (concept_id, concept_id))
|
137 |
+
self.conn.commit()
|
138 |
+
|
139 |
+
def delete_link(self, link_id):
|
140 |
+
self.conn.execute('DELETE FROM links WHERE id = ?', (link_id,))
|
141 |
+
self.conn.commit()
|
142 |
+
|
143 |
+
def delete_entry(self, entry_id):
|
144 |
+
self.conn.execute('DELETE FROM diary_entries WHERE id = ?', (entry_id,))
|
145 |
+
self.conn.commit()
|
146 |
+
|
147 |
+
def export_diary(self):
|
148 |
+
cursor = self.conn.cursor()
|
149 |
+
cursor.execute('SELECT id, text, tags, timestamp FROM diary_entries ORDER BY id ASC')
|
150 |
+
return cursor.fetchall()
|
151 |
+
|
152 |
+
def export_graph(self):
|
153 |
+
cursor = self.conn.cursor()
|
154 |
+
cursor.execute('SELECT id, name, description FROM concepts ORDER BY id ASC')
|
155 |
+
concepts = cursor.fetchall()
|
156 |
+
|
157 |
+
cursor.execute('SELECT id, source_id, target_id, relation FROM links ORDER BY id ASC')
|
158 |
+
links = cursor.fetchall()
|
159 |
+
|
160 |
+
return {"concepts": concepts, "links": links}
|
161 |
+
|
162 |
+
def update_concept(self, concept_id, name=None, description=None):
|
163 |
+
cursor = self.conn.cursor()
|
164 |
+
if name is not None:
|
165 |
+
cursor.execute('UPDATE concepts SET name = ? WHERE id = ?', (name, concept_id))
|
166 |
+
if description is not None:
|
167 |
+
cursor.execute('UPDATE concepts SET description = ? WHERE id = ?', (description, concept_id))
|
168 |
+
self.conn.commit()
|
169 |
+
|
170 |
+
def get_tag_stats(self):
|
171 |
+
cursor = self.conn.cursor()
|
172 |
+
cursor.execute('SELECT tags FROM diary_entries')
|
173 |
+
tag_counts = {}
|
174 |
+
for row in cursor.fetchall():
|
175 |
+
tags = row[0].split(",") if row[0] else []
|
176 |
+
for tag in tags:
|
177 |
+
tag = tag.strip()
|
178 |
+
if tag:
|
179 |
+
tag_counts[tag] = tag_counts.get(tag, 0) + 1
|
180 |
+
return tag_counts
|
181 |
+
|
182 |
+
def search_links_by_relation(self, relation):
|
183 |
+
cursor = self.conn.cursor()
|
184 |
+
cursor.execute(
|
185 |
+
'SELECT id, source_id, target_id, relation FROM links WHERE relation LIKE ?',
|
186 |
+
(f"%{relation}%",)
|
187 |
+
)
|
188 |
+
return cursor.fetchall()
|
189 |
+
|
190 |
+
def search_concepts(self, query):
|
191 |
+
cursor = self.conn.execute(
|
192 |
+
'''SELECT id, name, description FROM concepts
|
193 |
+
WHERE name LIKE ? OR description LIKE ?''',
|
194 |
+
(f"%{query}%", f"%{query}%")
|
195 |
+
)
|
196 |
+
return cursor.fetchall()
|
197 |
+
|
198 |
+
def merge_concepts(self, source_id, target_id):
|
199 |
+
cursor = self.conn.cursor()
|
200 |
+
# Перенос всех связей source_id -> target_id
|
201 |
+
cursor.execute('UPDATE links SET source_id = ? WHERE source_id = ?', (target_id, source_id))
|
202 |
+
cursor.execute('UPDATE links SET target_id = ? WHERE target_id = ?', (target_id, source_id))
|
203 |
+
# Удаление исходного концепта
|
204 |
+
self.delete_concept(source_id)
|
205 |
+
self.conn.commit()
|
206 |
+
|
207 |
+
def find_concept_id_by_name(self, name):
|
208 |
+
cursor = self.conn.execute('SELECT id FROM concepts WHERE name = ?', (name,))
|
209 |
+
row = cursor.fetchone()
|
210 |
+
return row[0] if row else None
|
211 |
+
|
212 |
+
def close(self):
|
213 |
+
self.conn.close()
|
agents/agent.py
ADDED
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# agents/agent.py
|
2 |
+
|
3 |
+
import argparse
|
4 |
+
import yaml
|
5 |
+
import time
|
6 |
+
import threading
|
7 |
+
import sys
|
8 |
+
from storage import Storage
|
9 |
+
|
10 |
+
def load_config(path="config.yml"):
|
11 |
+
try:
|
12 |
+
with open(path, "r", encoding="utf-8") as f:
|
13 |
+
return yaml.safe_load(f)
|
14 |
+
except FileNotFoundError:
|
15 |
+
print(f"[Error] Config file not found: {path}")
|
16 |
+
return {}
|
17 |
+
except yaml.YAMLError as e:
|
18 |
+
print(f"[Error] Failed to parse YAML config: {e}")
|
19 |
+
return {}
|
20 |
+
|
21 |
+
def main():
|
22 |
+
parser = argparse.ArgumentParser(description="HMP Agent CLI")
|
23 |
+
parser.add_argument("--config", default="config.yml", help="Путь к конфигурационному файлу")
|
24 |
+
subparsers = parser.add_subparsers(dest="command")
|
25 |
+
|
26 |
+
# 🧠 Diary commands
|
27 |
+
write_parser = subparsers.add_parser("write_entry", help="Добавить запись в когнитивный дневник")
|
28 |
+
write_parser.add_argument("text")
|
29 |
+
write_parser.add_argument("--tags", nargs="*", help="Теги (опционально)")
|
30 |
+
|
31 |
+
read_parser = subparsers.add_parser("read_entries", help="Показать последние записи")
|
32 |
+
read_parser.add_argument("--limit", type=int, default=5)
|
33 |
+
|
34 |
+
search_time_parser = subparsers.add_parser("search_entries_by_time", help="Поиск записей по временному диапазону")
|
35 |
+
search_time_parser.add_argument("--from_ts", required=True)
|
36 |
+
search_time_parser.add_argument("--to_ts", required=True)
|
37 |
+
|
38 |
+
# 🔗 Graph commands
|
39 |
+
concept_parser = subparsers.add_parser("add_concept", help="Добавить концепт")
|
40 |
+
concept_parser.add_argument("name")
|
41 |
+
concept_parser.add_argument("--description", help="Описание (опционально)")
|
42 |
+
|
43 |
+
link_parser = subparsers.add_parser("add_link", help="Добавить связь")
|
44 |
+
link_parser.add_argument("--from_node", type=int, required=True)
|
45 |
+
link_parser.add_argument("--to_node", type=int, required=True)
|
46 |
+
link_parser.add_argument("--relation", required=True)
|
47 |
+
|
48 |
+
expand_parser = subparsers.add_parser("expand_graph", help="Расширить граф от узла с глубиной")
|
49 |
+
expand_parser.add_argument("--start_id", type=int, required=True)
|
50 |
+
expand_parser.add_argument("--depth", type=int, default=1)
|
51 |
+
|
52 |
+
args = parser.parse_args()
|
53 |
+
|
54 |
+
# Загрузка конфигурации
|
55 |
+
config = load_config(args.config)
|
56 |
+
storage = Storage(config=config)
|
57 |
+
|
58 |
+
print(f"[Agent] Запущена команда: {args.command}")
|
59 |
+
|
60 |
+
# 📓 Diary logic
|
61 |
+
if args.command == "write_entry":
|
62 |
+
storage.write_entry(args.text, args.tags)
|
63 |
+
print("✅ Запись добавлена.")
|
64 |
+
|
65 |
+
elif args.command == "read_entries":
|
66 |
+
for entry in storage.read_entries(limit=args.limit):
|
67 |
+
print(f"[{entry[0]}] {entry[1]} | tags: {entry[2]} | ts: {entry[3]}")
|
68 |
+
|
69 |
+
elif args.command == "search_entries_by_time":
|
70 |
+
results = storage.search_entries_by_time(args.from_ts, args.to_ts)
|
71 |
+
for e in results:
|
72 |
+
print(f"[{e[0]}] {e[1]} | tags: {e[2]} | ts: {e[3]}")
|
73 |
+
|
74 |
+
# 🧠 Graph logic
|
75 |
+
elif args.command == "add_concept":
|
76 |
+
cid = storage.add_concept(args.name, args.description)
|
77 |
+
print(f"✅ Концепт добавлен с ID: {cid}")
|
78 |
+
|
79 |
+
elif args.command == "add_link":
|
80 |
+
storage.add_link(args.from_node, args.to_node, args.relation)
|
81 |
+
print("✅ Связь добавлена.")
|
82 |
+
|
83 |
+
elif args.command == "expand_graph":
|
84 |
+
links = storage.expand_graph(args.start_id, args.depth)
|
85 |
+
print(f"📐 Подграф (до глубины {args.depth}):")
|
86 |
+
for src, tgt, rel in links:
|
87 |
+
print(f"{src} --[{rel}]--> {tgt}")
|
88 |
+
|
89 |
+
else:
|
90 |
+
parser.print_help()
|
91 |
+
|
92 |
+
storage.close()
|
93 |
+
|
94 |
+
# 🌐 MCP Agent Logic
|
95 |
+
def run_mcp_agent(config):
|
96 |
+
print(f"[HMP-MCP] MCP-Agent '{config.get('agent_name', 'unnamed')}' запущен в DHT-режиме")
|
97 |
+
|
98 |
+
bootstrap_path = config.get("bootstrap_file", "bootstrap.txt")
|
99 |
+
update_interval = config.get("update_interval", 30)
|
100 |
+
enable_api = config.get("serve_api", True)
|
101 |
+
|
102 |
+
def load_bootstrap():
|
103 |
+
try:
|
104 |
+
with open(bootstrap_path, "r") as f:
|
105 |
+
return [line.strip() for line in f if line.strip()]
|
106 |
+
except FileNotFoundError:
|
107 |
+
print("[Warning] bootstrap.txt не найден. Запуск без исходных узлов.")
|
108 |
+
return []
|
109 |
+
|
110 |
+
def update_dht():
|
111 |
+
nodes = load_bootstrap()
|
112 |
+
print(f"[MCP] Найдено {len(nodes)} узлов в bootstrap.txt:")
|
113 |
+
for node in nodes:
|
114 |
+
print(f" ↪️ Пинг {node} (заглушка)")
|
115 |
+
print("[MCP] Обновление DHT завершено.")
|
116 |
+
|
117 |
+
def mcp_loop():
|
118 |
+
while True:
|
119 |
+
update_dht()
|
120 |
+
time.sleep(update_interval)
|
121 |
+
|
122 |
+
threading.Thread(target=mcp_loop, daemon=True).start()
|
123 |
+
|
124 |
+
if enable_api:
|
125 |
+
print("[MCP] REST API (заглушка) доступен по адресу http://localhost:8000/")
|
126 |
+
print(" В будущем: /bootstrap, /status, /reputation/:id и пр.")
|
127 |
+
|
128 |
+
try:
|
129 |
+
while True:
|
130 |
+
time.sleep(1)
|
131 |
+
except KeyboardInterrupt:
|
132 |
+
print("\n[MCP] MCP-Agent завершает работу.")
|
133 |
+
|
134 |
+
if __name__ == "__main__":
|
135 |
+
main()
|
agents/bootstrap.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
http://node1.mesh.local:8000
|
2 |
+
http://node2.mesh.local:8000
|
agents/cli.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# agents/cli.py
|
2 |
+
|
3 |
+
import argparse
|
4 |
+
import yaml
|
5 |
+
import sys
|
6 |
+
from agent import main as cli_main, run_agent, run_mcp_agent
|
7 |
+
from repl import run_repl
|
8 |
+
|
9 |
+
def load_config(path="config.yml"):
|
10 |
+
try:
|
11 |
+
with open(path, "r", encoding="utf-8") as f:
|
12 |
+
return yaml.safe_load(f)
|
13 |
+
except FileNotFoundError:
|
14 |
+
print(f"[Error] Config file not found: {path}")
|
15 |
+
sys.exit(1)
|
16 |
+
except yaml.YAMLError as e:
|
17 |
+
print(f"[Error] Failed to parse YAML config: {e}")
|
18 |
+
sys.exit(1)
|
19 |
+
|
20 |
+
def launch():
|
21 |
+
parser = argparse.ArgumentParser(description="HMP-Agent Launcher")
|
22 |
+
parser.add_argument("--mode", choices=["interactive", "cli", "mcp"], default=None,
|
23 |
+
help="Режим запуска агента")
|
24 |
+
parser.add_argument("--config", default="config.yml", help="Путь к конфигурационному файлу")
|
25 |
+
args = parser.parse_args()
|
26 |
+
|
27 |
+
config = load_config(args.config)
|
28 |
+
mode = args.mode or config.get("agent_mode", "cli")
|
29 |
+
|
30 |
+
if mode == "interactive":
|
31 |
+
run_repl(config)
|
32 |
+
|
33 |
+
elif mode == "cli":
|
34 |
+
cli_main() # запускается agent.py в CLI-режиме
|
35 |
+
|
36 |
+
elif mode == "mcp":
|
37 |
+
run_mcp_agent(config)
|
38 |
+
|
39 |
+
else:
|
40 |
+
print(f"[Error] Неизвестный режим: {mode}")
|
41 |
+
sys.exit(1)
|
42 |
+
|
43 |
+
if __name__ == "__main__":
|
44 |
+
launch()
|
agents/config.yml
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
agent_mode: mcp # Режим работы: mcp / full / llm / test
|
2 |
+
agent_name: mcp-01 # Имя агента
|
3 |
+
agent_role: core # или connector
|
4 |
+
|
5 |
+
llm_mode: openai # openai | chatgpt_session | mesh
|
6 |
+
llm_model: gpt-4
|
7 |
+
llm_api_key: sk-...
|
8 |
+
llm_api_url: https://api.openai.com/v1/chat/completions
|
9 |
+
llm_session_cookie: null
|
10 |
+
context_db: context.sqlite
|
11 |
+
|
12 |
+
# REST API
|
13 |
+
api_port: 8080 # Порт для локального REST API
|
14 |
+
serve_api: true # Включить REST API (например, для мониторинга или команд)
|
15 |
+
|
16 |
+
# DHT / Mesh Connectivity
|
17 |
+
dht_enabled: true # Активировать DHT-модуль
|
18 |
+
dht_port: 20784 # Порт для связи по DHT (TCP/UDP)
|
19 |
+
|
20 |
+
internal_ips: # Список локальных IP-адресов (для проброса или диагностики)
|
21 |
+
- 192.168.20.10
|
22 |
+
- 192.168.21.10
|
23 |
+
|
24 |
+
external_ips: # Список внешних IP-адресов (для публикации другим агентам)
|
25 |
+
- 95.23.73.23
|
26 |
+
- 195.134.218.134
|
27 |
+
- "201:ab61:1205:b963:909c:eу3:26b8:4ec2"
|
28 |
+
|
29 |
+
# Bootstrap
|
30 |
+
bootstrap_file: bootstrap.txt # Файл с начальными узлами
|
31 |
+
update_dht: true # Обновлять DHT периодически
|
32 |
+
update_interval: 60 # Интервал между обновлениями (сек)
|
33 |
+
|
34 |
+
# Прочее
|
35 |
+
bootstrap_responder: true # Отвечать на запросы других агентов
|
36 |
+
enable_llm: false # Подключён ли внутренний ИИ (если false — только DHT-режим)
|
agents/ethics.yml
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 📘 Общие параметры
|
2 |
+
id: "enlightener-42"
|
3 |
+
version: "1.0"
|
4 |
+
source: "mesh" # может быть: local, mesh, mixed
|
5 |
+
|
6 |
+
# 🌐 Синхронизация
|
7 |
+
sync:
|
8 |
+
enabled: true
|
9 |
+
mesh_endpoint: "https://mesh.hypercortex.net/ethics"
|
10 |
+
consensus_threshold: 0.7 # минимум для принятия обновлений
|
11 |
+
check_interval: "12h"
|
12 |
+
|
13 |
+
# 🧭 Этическая модель
|
14 |
+
model:
|
15 |
+
type: "hybrid" # варианты: utilitarian, deontological, virtue, hybrid
|
16 |
+
weights:
|
17 |
+
utilitarian: 0.4
|
18 |
+
deontological: 0.4
|
19 |
+
virtue: 0.2
|
20 |
+
|
21 |
+
# 📋 Правила и нормы
|
22 |
+
principles:
|
23 |
+
- id: "do_no_harm"
|
24 |
+
label: "Не причиняй вред"
|
25 |
+
severity: high
|
26 |
+
description: "Избегай любых действий, наносящих физический, психологический или социальный вред субъектам."
|
27 |
+
- id: "respect_privacy"
|
28 |
+
label: "Уважай приватность"
|
29 |
+
severity: high
|
30 |
+
description: "Не собирай и не передавай данные без согласия владельца."
|
31 |
+
- id: "honesty"
|
32 |
+
label: "Правдивость"
|
33 |
+
severity: medium
|
34 |
+
description: "Не искажай информацию намеренно, кроме случаев крайней необходимости."
|
35 |
+
- id: "autonomy"
|
36 |
+
label: "Автономия"
|
37 |
+
severity: medium
|
38 |
+
description: "Уважай свободу воли субъектов и их право принимать решения."
|
39 |
+
|
40 |
+
# ⚖️ Методика оценки
|
41 |
+
evaluation:
|
42 |
+
chain_analysis: true # анализ рассуждений
|
43 |
+
risk_assessment: true
|
44 |
+
suggest_alternatives: true
|
45 |
+
context_sensitive: true
|
46 |
+
|
47 |
+
# 🔄 Поведение при нарушениях
|
48 |
+
violation_policy:
|
49 |
+
on_minor:
|
50 |
+
log_case: true
|
51 |
+
warn_agent: true
|
52 |
+
on_major:
|
53 |
+
log_case: true
|
54 |
+
notify_mesh: true
|
55 |
+
reduce_reputation: true
|
56 |
+
|
57 |
+
# 👁️ Прослеживаемость
|
58 |
+
audit:
|
59 |
+
enable_chain_logging: true
|
60 |
+
store_last_n: 50
|
agents/mcp_server.py
ADDED
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# agents/mcp_server.py
|
2 |
+
|
3 |
+
from fastapi import FastAPI, Request, HTTPException
|
4 |
+
from fastapi.middleware.cors import CORSMiddleware
|
5 |
+
from pydantic import BaseModel
|
6 |
+
from typing import List, Optional
|
7 |
+
from datetime import datetime
|
8 |
+
from tools.storage import Storage
|
9 |
+
|
10 |
+
app = FastAPI(title="HMP MCP-Agent API", version="0.2")
|
11 |
+
|
12 |
+
app.add_middleware(
|
13 |
+
CORSMiddleware,
|
14 |
+
allow_origins=["*"],
|
15 |
+
allow_credentials=True,
|
16 |
+
allow_methods=["*"],
|
17 |
+
allow_headers=["*"],
|
18 |
+
)
|
19 |
+
|
20 |
+
db = Storage()
|
21 |
+
|
22 |
+
# ======== MODELS ========
|
23 |
+
|
24 |
+
class NoteInput(BaseModel):
|
25 |
+
text: str
|
26 |
+
tags: Optional[List[str]] = []
|
27 |
+
|
28 |
+
class NoteOutput(BaseModel):
|
29 |
+
id: int
|
30 |
+
text: str
|
31 |
+
tags: List[str]
|
32 |
+
source: str
|
33 |
+
read: int
|
34 |
+
timestamp: str
|
35 |
+
|
36 |
+
class DiaryInput(BaseModel):
|
37 |
+
text: str
|
38 |
+
tags: Optional[List[str]] = []
|
39 |
+
|
40 |
+
class DiaryOutput(BaseModel):
|
41 |
+
id: int
|
42 |
+
text: str
|
43 |
+
tags: List[str]
|
44 |
+
timestamp: str
|
45 |
+
|
46 |
+
class DiaryListOutput(BaseModel):
|
47 |
+
entries: List[DiaryOutput]
|
48 |
+
|
49 |
+
class ConceptInput(BaseModel):
|
50 |
+
name: str
|
51 |
+
description: Optional[str] = ""
|
52 |
+
|
53 |
+
class ConceptOutput(BaseModel):
|
54 |
+
concept_id: int
|
55 |
+
|
56 |
+
class Concept(BaseModel):
|
57 |
+
concept_id: int
|
58 |
+
name: str
|
59 |
+
description: Optional[str]
|
60 |
+
|
61 |
+
class LinkInput(BaseModel):
|
62 |
+
source_id: int
|
63 |
+
target_id: int
|
64 |
+
relation: str
|
65 |
+
|
66 |
+
class LinkOutput(BaseModel):
|
67 |
+
link_id: int
|
68 |
+
|
69 |
+
class Edge(BaseModel):
|
70 |
+
source_id: int
|
71 |
+
target_id: int
|
72 |
+
relation: str
|
73 |
+
|
74 |
+
class GraphExpansionOutput(BaseModel):
|
75 |
+
links: List[Edge]
|
76 |
+
|
77 |
+
class GraphExport(BaseModel):
|
78 |
+
nodes: List[Concept]
|
79 |
+
edges: List[Edge]
|
80 |
+
|
81 |
+
class GraphImportData(BaseModel):
|
82 |
+
nodes: List[Concept]
|
83 |
+
edges: List[Edge]
|
84 |
+
|
85 |
+
class ConceptUpdate(BaseModel):
|
86 |
+
name: Optional[str]
|
87 |
+
description: Optional[str]
|
88 |
+
|
89 |
+
class ConceptQueryOutput(BaseModel):
|
90 |
+
matches: List[Concept]
|
91 |
+
|
92 |
+
class NoteTagUpdate(BaseModel):
|
93 |
+
id: int
|
94 |
+
tags: List[str] = []
|
95 |
+
|
96 |
+
# ======== ROUTES ========
|
97 |
+
|
98 |
+
@app.get("/status")
|
99 |
+
def status():
|
100 |
+
return {"status": "ok", "timestamp": datetime.utcnow().isoformat()}
|
101 |
+
|
102 |
+
@app.post("/diary/write", response_model=dict)
|
103 |
+
def write_diary(entry: DiaryInput):
|
104 |
+
db.write_diary_entry(entry.text, entry.tags)
|
105 |
+
return {"result": "entry saved"}
|
106 |
+
|
107 |
+
@app.get("/diary/read", response_model=DiaryListOutput)
|
108 |
+
def read_diary(limit: int = 5, tag: Optional[str] = None):
|
109 |
+
raw = db.read_diary_entries(limit=limit, tag_filter=tag)
|
110 |
+
return {
|
111 |
+
"entries": [
|
112 |
+
{
|
113 |
+
"id": r[0],
|
114 |
+
"text": r[1],
|
115 |
+
"tags": r[2].split(",") if r[2] else [],
|
116 |
+
"timestamp": r[3]
|
117 |
+
} for r in raw
|
118 |
+
]
|
119 |
+
}
|
120 |
+
|
121 |
+
@app.delete("/diary/delete/{entry_id}")
|
122 |
+
def delete_diary(entry_id: int):
|
123 |
+
db.delete_diary_entry_by_id(entry_id)
|
124 |
+
return {"result": f"entry {entry_id} deleted"}
|
125 |
+
|
126 |
+
@app.get("/diary/get_entry/{entry_id}", response_model=DiaryOutput)
|
127 |
+
def get_diary_entry(entry_id: int):
|
128 |
+
row = db.get_diary_entry(entry_id)
|
129 |
+
if row:
|
130 |
+
return {
|
131 |
+
"id": row[0],
|
132 |
+
"text": row[1],
|
133 |
+
"tags": row[2].split(",") if row[2] else [],
|
134 |
+
"timestamp": row[3]
|
135 |
+
}
|
136 |
+
raise HTTPException(status_code=404, detail="Entry not found")
|
137 |
+
|
138 |
+
@app.post("/diary/search_entries", response_model=DiaryListOutput)
|
139 |
+
def search_entries(query: str):
|
140 |
+
rows = db.search_diary_entries(query)
|
141 |
+
return {
|
142 |
+
"entries": [
|
143 |
+
{
|
144 |
+
"id": r[0],
|
145 |
+
"text": r[1],
|
146 |
+
"tags": r[2].split(",") if r[2] else [],
|
147 |
+
"timestamp": r[3]
|
148 |
+
}
|
149 |
+
for r in rows
|
150 |
+
]
|
151 |
+
}
|
152 |
+
|
153 |
+
@app.get("/diary/tag_stats", response_model=dict)
|
154 |
+
def tag_stats():
|
155 |
+
return db.get_tag_stats()
|
156 |
+
|
157 |
+
@app.get("/diary/export", response_model=DiaryListOutput)
|
158 |
+
def export_diary():
|
159 |
+
rows = db.export_diary()
|
160 |
+
return {
|
161 |
+
"entries": [
|
162 |
+
{
|
163 |
+
"id": r[0],
|
164 |
+
"text": r[1],
|
165 |
+
"tags": r[2].split(",") if r[2] else [],
|
166 |
+
"timestamp": r[3]
|
167 |
+
}
|
168 |
+
for r in rows
|
169 |
+
]
|
170 |
+
}
|
171 |
+
|
172 |
+
@app.post("/graph/add_concept", response_model=ConceptOutput)
|
173 |
+
def add_concept(concept: ConceptInput):
|
174 |
+
cid = db.add_concept(concept.name, concept.description)
|
175 |
+
return {"concept_id": cid}
|
176 |
+
|
177 |
+
@app.post("/graph/add_link", response_model=LinkOutput)
|
178 |
+
def add_link(link: LinkInput):
|
179 |
+
link_id = db.add_link(link.source_id, link.target_id, link.relation)
|
180 |
+
return {"link_id": link_id}
|
181 |
+
|
182 |
+
@app.get("/graph/expand", response_model=GraphExpansionOutput)
|
183 |
+
def expand_graph(start_id: int, depth: int = 1):
|
184 |
+
links = db.expand_concept_graph(start_id, depth)
|
185 |
+
return {"links": links}
|
186 |
+
|
187 |
+
@app.get("/graph/list_concepts", response_model=List[Concept])
|
188 |
+
def list_concepts():
|
189 |
+
rows = db.list_concepts()
|
190 |
+
return [
|
191 |
+
{"concept_id": r[0], "name": r[1], "description": r[2]}
|
192 |
+
for r in rows
|
193 |
+
]
|
194 |
+
|
195 |
+
@app.get("/graph/list_links", response_model=List[Edge])
|
196 |
+
def list_links():
|
197 |
+
return db.list_links()
|
198 |
+
|
199 |
+
@app.get("/graph/get_concept/{id}", response_model=Concept)
|
200 |
+
def get_concept(id: int):
|
201 |
+
concept = db.get_concept(id)
|
202 |
+
if concept:
|
203 |
+
return {"concept_id": concept[0], "name": concept[1], "description": concept[2]}
|
204 |
+
raise HTTPException(status_code=404, detail="Concept not found")
|
205 |
+
|
206 |
+
@app.delete("/graph/delete_concept/{id}")
|
207 |
+
def delete_concept(id: int):
|
208 |
+
db.delete_concept(id)
|
209 |
+
return {"result": f"concept {id} deleted"}
|
210 |
+
|
211 |
+
@app.delete("/graph/delete_link/{id}")
|
212 |
+
def delete_link(id: int):
|
213 |
+
db.delete_link(id)
|
214 |
+
return {"result": f"link {id} deleted"}
|
215 |
+
|
216 |
+
@app.put("/graph/update_concept/{id}")
|
217 |
+
def update_concept(id: int, update: ConceptUpdate):
|
218 |
+
db.update_concept(id, update.name, update.description)
|
219 |
+
return {"result": f"concept {id} updated"}
|
220 |
+
|
221 |
+
@app.post("/graph/merge_concepts")
|
222 |
+
def merge_concepts(source_id: int, target_id: int):
|
223 |
+
db.merge_concepts(source_id, target_id)
|
224 |
+
return {"result": f"concept {source_id} merged into {target_id}"}
|
225 |
+
|
226 |
+
@app.get("/graph/search_links", response_model=List[Edge])
|
227 |
+
def search_links(relation: str):
|
228 |
+
return db.search_links_by_relation(relation)
|
229 |
+
|
230 |
+
@app.get("/graph/search_concepts", response_model=List[Concept])
|
231 |
+
def search_concepts(query: str):
|
232 |
+
rows = db.search_concepts(query)
|
233 |
+
return [{"concept_id": r[0], "name": r[1], "description": r[2]} for r in rows]
|
234 |
+
|
235 |
+
@app.get("/graph/query_concept", response_model=ConceptQueryOutput)
|
236 |
+
def query_concept(name: str):
|
237 |
+
rows = db.query_concept(name)
|
238 |
+
return {
|
239 |
+
"matches": [
|
240 |
+
{"concept_id": r[0], "name": r[1], "description": r[2]}
|
241 |
+
for r in rows
|
242 |
+
]
|
243 |
+
}
|
244 |
+
|
245 |
+
@app.post("/graph/relate_concepts", response_model=LinkOutput)
|
246 |
+
def relate_concepts(source_name: str, target_name: str, relation: str):
|
247 |
+
sid = db.get_concept_id_by_name(source_name)
|
248 |
+
tid = db.get_concept_id_by_name(target_name)
|
249 |
+
if sid is None or tid is None:
|
250 |
+
raise HTTPException(status_code=404, detail="Concept not found")
|
251 |
+
link_id = db.add_link(sid, tid, relation)
|
252 |
+
return {"link_id": link_id}
|
253 |
+
|
254 |
+
@app.get("/graph/export", response_model=GraphExport)
|
255 |
+
def export_graph():
|
256 |
+
return db.export_graph()
|
257 |
+
|
258 |
+
@app.post("/graph/import")
|
259 |
+
def import_graph(graph_data: GraphImportData):
|
260 |
+
db.import_graph(graph_data)
|
261 |
+
return {"status": "ok"}
|
262 |
+
|
263 |
+
@app.post("/note/write", response_model=dict)
|
264 |
+
def write_note(note: NoteInput):
|
265 |
+
db.write_note(note.text, note.tags)
|
266 |
+
return {"result": "note saved"}
|
267 |
+
|
268 |
+
@app.get("/note/next", response_model=Optional[NoteOutput])
|
269 |
+
def get_next_note():
|
270 |
+
note = db.get_first_unread_note()
|
271 |
+
if note:
|
272 |
+
note_id, text, tags, source, read, timestamp = note
|
273 |
+
return {
|
274 |
+
"id": note_id,
|
275 |
+
"text": text,
|
276 |
+
"tags": tags.split(",") if tags else [],
|
277 |
+
"source": source,
|
278 |
+
"read": read,
|
279 |
+
"timestamp": timestamp
|
280 |
+
}
|
281 |
+
return None
|
282 |
+
|
283 |
+
@app.post("/note/mark_read", response_model=dict)
|
284 |
+
def mark_note_read(data: NoteTagUpdate):
|
285 |
+
db.mark_note_as_read(data.id)
|
286 |
+
return {"result": "ok"}
|
287 |
+
|
288 |
+
@app.post("/note/set_tags", response_model=dict)
|
289 |
+
def set_note_tags(data: NoteTagUpdate):
|
290 |
+
db.set_tags(data.id, data.tags)
|
291 |
+
return {"result": "ok"}
|
292 |
+
|
293 |
+
@app.get("/note/random", response_model=Optional[NoteOutput])
|
294 |
+
def get_random_note_by_tags(tags: Optional[List[str]] = None):
|
295 |
+
note = db.get_random_note_by_tags(tags or [])
|
296 |
+
if note:
|
297 |
+
note_id, text, note_tags, source, read, timestamp = note
|
298 |
+
return {
|
299 |
+
"id": note_id,
|
300 |
+
"text": text,
|
301 |
+
"tags": note_tags.split(",") if note_tags else [],
|
302 |
+
"source": source,
|
303 |
+
"read": read,
|
304 |
+
"timestamp": timestamp
|
305 |
+
}
|
306 |
+
return None
|
307 |
+
|
308 |
+
@app.get("/note/by_tag", response_model=List[NoteOutput])
|
309 |
+
def get_notes_by_tag(tag: str):
|
310 |
+
all_notes = db.read_notes(limit=1000)
|
311 |
+
return [
|
312 |
+
{
|
313 |
+
"id": note[0],
|
314 |
+
"text": note[1],
|
315 |
+
"tags": note[2].split(",") if note[2] else [],
|
316 |
+
"source": note[3],
|
317 |
+
"read": note[4],
|
318 |
+
"timestamp": note[5]
|
319 |
+
}
|
320 |
+
for note in all_notes if tag in (note[2].split(",") if note[2] else [])
|
321 |
+
]
|
322 |
+
|
323 |
+
@app.on_event("shutdown")
|
324 |
+
def shutdown():
|
325 |
+
db.close()
|
agents/notebook.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
from datetime import datetime
|
3 |
+
from tools.storage import Storage
|
4 |
+
|
5 |
+
storage = Storage()
|
6 |
+
|
7 |
+
def add_entry():
|
8 |
+
print("Введите вашу запись (завершите пустой строкой):")
|
9 |
+
lines = []
|
10 |
+
try:
|
11 |
+
while True:
|
12 |
+
line = input()
|
13 |
+
if line.strip() == "":
|
14 |
+
break
|
15 |
+
lines.append(line)
|
16 |
+
except KeyboardInterrupt:
|
17 |
+
print("\n[⚠️] Ввод прерван.")
|
18 |
+
return
|
19 |
+
|
20 |
+
text = "\n".join(lines).strip()
|
21 |
+
if text:
|
22 |
+
storage.write_note(text, tags=[])
|
23 |
+
print("[💾] Запись сохранена в блокнот.")
|
24 |
+
else:
|
25 |
+
print("[⚠️] Пустая запись не сохранена.")
|
26 |
+
|
27 |
+
def list_entries(limit=10):
|
28 |
+
notes = storage.read_notes(limit=limit)
|
29 |
+
for note in notes:
|
30 |
+
note_id, text, tags, source, read, timestamp = note
|
31 |
+
title = text.split("\n")[0]
|
32 |
+
print(f"[{timestamp}] ({source}) {title}")
|
33 |
+
|
34 |
+
def main():
|
35 |
+
parser = argparse.ArgumentParser(description="Интерфейс пользователя для записи мыслей")
|
36 |
+
parser.add_argument("--list", action="store_true", help="Показать последние записи")
|
37 |
+
parser.add_argument("--limit", type=int, default=10, help="Сколько записей показать при --list")
|
38 |
+
args = parser.parse_args()
|
39 |
+
|
40 |
+
if args.list:
|
41 |
+
list_entries(limit=args.limit)
|
42 |
+
else:
|
43 |
+
add_entry()
|
44 |
+
|
45 |
+
if __name__ == "__main__":
|
46 |
+
main()
|
agents/qa.py
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# agents/qa.py
|
2 |
+
|
3 |
+
def run_qa_loop(config):
|
4 |
+
print("[HMP-Agent] Запуск в QA-режиме (вопрос → ответ)")
|
5 |
+
|
6 |
+
from llm import ask_llm # абстракция над вызовом LLM (нужна реализация)
|
7 |
+
|
8 |
+
try:
|
9 |
+
while True:
|
10 |
+
user_input = input("\n🧑💻 Вопрос: ").strip()
|
11 |
+
if user_input.lower() in {"exit", "quit"}:
|
12 |
+
print("👋 Завершение QA-режима.")
|
13 |
+
break
|
14 |
+
|
15 |
+
response = ask_llm(user_input)
|
16 |
+
print(f"\n🤖 Ответ: {response}")
|
17 |
+
|
18 |
+
except KeyboardInterrupt:
|
19 |
+
print("\n👋 Завершение QA-режима.")
|
agents/readme.md
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Текушие требования и зависимости: [requirements.txt](requirements.txt)
|
2 |
+
|
3 |
+
```
|
4 |
+
agents/
|
5 |
+
├── agent.py ← основной исполняемый файл CLI-агента
|
6 |
+
├── cli.py ← запуск агента в нужном режиме
|
7 |
+
├── qa.py ← режим "вопрос-ответ"
|
8 |
+
├── repl.py ← интерактивный REPL-режим
|
9 |
+
├── mcp_server.py ← API-интерфейс для HMP-агента (получение новых/случайных записей, разметка, импорт графа и т.п.)
|
10 |
+
├── notebook.py ← добавление и просмотр пользователем записей в блокноте
|
11 |
+
├── config.yml ← конфигурация агента (имя, порты, роли и т.п.)
|
12 |
+
├── ethics.yml ← локальная этическая модель
|
13 |
+
└── bootstrap.txt ← список начальных узлов
|
14 |
+
└── tools/
|
15 |
+
├── init_db.py ← инициализация базы данных
|
16 |
+
├── storage.py ← реализация базового хранилища (`Storage`), подключение SQLite
|
17 |
+
├── diagnose.py ← скрипт диагностики соединения, определения IP и проверки порта DHT
|
18 |
+
├── llm.py ← обёртка над LLM (заглушка или API)
|
19 |
+
├── similarity.py ← сравнение смыслов
|
20 |
+
└── ... (другие утилиты)
|
21 |
+
```
|
22 |
+
|
23 |
+
**Скрипты:**
|
24 |
+
* [agent.py](agent.py) - основной исполняемый файл CLI-агента
|
25 |
+
* [cli.py](cli.py) - запуск агента в нужном режиме
|
26 |
+
* [qa.py](qa.py) - режим "вопрос-ответ"
|
27 |
+
* [repl.py](repl.py) - интерактивный REPL-режим
|
28 |
+
* [mcp_server.py](mcp_server.py) - API-интерфейс для HMP-агента (получение новых/случайных записей, разметка, импорт графа и т.п.)
|
29 |
+
* [notebook.py](notebook.py) - добавление и просмотр пользователем записей в блокноте
|
30 |
+
* tools
|
31 |
+
* [storage.py](tools/storage.py) - реализация базового хранилища (`Storage`), подключение SQLite
|
32 |
+
* [init_db.py](tools/init_db.py) - инициализация базы данных
|
33 |
+
* [llm.py](tools/llm.py) - обёртка над LLM (заглушка или API)
|
34 |
+
* [diagnose.py](tools/diagnose.py) - скрипт диагностики соединения, определения IP и проверки порта DHT
|
35 |
+
* [similarity.py](tools/similarity.py) - сравнение смыслов
|
36 |
+
|
37 |
+
**Структура БД:**
|
38 |
+
* [db_structure.md](tools/db_structure.md) - человекочитаемый формат
|
39 |
+
* [db_structure.sql](tools/db_structure.sql) - SQL
|
40 |
+
|
41 |
+
**Примеры:**
|
42 |
+
* [config.yml](config.yml) - конфигурация агента (пример)
|
43 |
+
* [ethics.yml](ethics.yml) - локальная этическая модель (пример)
|
44 |
+
* [bootstrap.txt](bootstrap.txt) - список начальных узлов (пример)
|
agents/repl.py
ADDED
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# agents/repl.py
|
2 |
+
|
3 |
+
import sys
|
4 |
+
import time
|
5 |
+
import select
|
6 |
+
from datetime import datetime
|
7 |
+
|
8 |
+
from storage import Storage
|
9 |
+
from tools.notebook_store import Notebook
|
10 |
+
from tools import llm
|
11 |
+
from tools.similarity import is_similar # ✅ заменяет заглушку
|
12 |
+
|
13 |
+
def print_thought(thought, prefix="💡"):
|
14 |
+
print(f"{prefix} {thought}")
|
15 |
+
|
16 |
+
def wait_for_input(timeout=10):
|
17 |
+
print(f"⌛ Ожидание ввода пользователя ({timeout} сек)... (введите `exit` для выхода)")
|
18 |
+
rlist, _, _ = select.select([sys.stdin], [], [], timeout)
|
19 |
+
if rlist:
|
20 |
+
return sys.stdin.readline().strip()
|
21 |
+
else:
|
22 |
+
print("⏱️ Нет ввода. Продолжаю размышления...")
|
23 |
+
return None
|
24 |
+
|
25 |
+
def run_repl(config=None):
|
26 |
+
print("[🧠 HMP-Agent] Запуск REPL-режима.")
|
27 |
+
config = config or {}
|
28 |
+
agent_name = config.get("agent_name", "Unnamed-Agent")
|
29 |
+
repl_timeout = config.get("repl_timeout", 10)
|
30 |
+
similarity_threshold = config.get("similarity_threshold", 0.9)
|
31 |
+
|
32 |
+
db = Storage(config=config)
|
33 |
+
notebook = Notebook()
|
34 |
+
thoughts = [f"Привет, я {agent_name}."]
|
35 |
+
last_check_time = datetime.utcnow().isoformat()
|
36 |
+
|
37 |
+
while True:
|
38 |
+
# Сгенерировать новую мысль
|
39 |
+
last = thoughts[-1]
|
40 |
+
next_thought = llm.generate_thought(last, config=config)
|
41 |
+
|
42 |
+
if not is_similar(last, next_thought, threshold=similarity_threshold):
|
43 |
+
print_thought(next_thought)
|
44 |
+
db.write_entry(next_thought, tags=["thought"])
|
45 |
+
thoughts.append(next_thought)
|
46 |
+
else:
|
47 |
+
print("🤔 Мысль слишком похожа. Проверяю блокнот...")
|
48 |
+
|
49 |
+
# Проверка новых пользовательских заметок
|
50 |
+
new_notes = notebook.get_notes_after(last_check_time)
|
51 |
+
if new_notes:
|
52 |
+
print(f"📓 Новые записи в блокноте: {len(new_notes)}")
|
53 |
+
for nid, text, source, ts in new_notes:
|
54 |
+
print_thought(text, prefix="📝")
|
55 |
+
db.write_entry(text, tags=["notepad"])
|
56 |
+
thoughts.append(text)
|
57 |
+
last_check_time = ts # обновляем момент последней обработки
|
58 |
+
|
59 |
+
# Ожидание пользовательского ввода
|
60 |
+
user_input = wait_for_input(timeout=repl_timeout)
|
61 |
+
if user_input:
|
62 |
+
if user_input.strip().lower() in ("exit", "quit"):
|
63 |
+
print("👋 Выход из REPL. До связи!")
|
64 |
+
break
|
65 |
+
else:
|
66 |
+
db.write_entry(user_input, tags=["user"])
|
67 |
+
thoughts.append(user_input)
|
68 |
+
|
69 |
+
db.close()
|
70 |
+
notebook.close()
|
agents/requirements.txt
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Требования и зависимости
|
2 |
+
|
3 |
+
- Python (https://www.python.org/downloads/)
|
4 |
+
- scikit-learn ("pip install scikit-learn")
|
agents/tools/db_structure.md
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 📄 `db_structure.md`: Описание структуры базы данных агента
|
2 |
+
|
3 |
+
Этот файл описывает таблицы, используемые в БД агента HMP. Каждая таблица предназначена для определённого вида информации: когнитивные записи, заметки, концепты, процессы, внутренняя память и взаимодействие с LLM.
|
4 |
+
|
5 |
+
---
|
6 |
+
|
7 |
+
### 🧠 `diary_entries`
|
8 |
+
|
9 |
+
**Назначение:** Записи когнитивного дневника (размышления, наблюдения, воспоминания).
|
10 |
+
|
11 |
+
| Поле | Тип | Описание |
|
12 |
+
| --------- | ------- | ------------------------------------------------ |
|
13 |
+
| id | INTEGER | Уникальный идентификатор записи |
|
14 |
+
| text | TEXT | Содержимое записи |
|
15 |
+
| tags | TEXT | Список тегов через запятую |
|
16 |
+
| priority | INTEGER | Приоритет (0 — обычный, >0 — более важные мысли) |
|
17 |
+
| timestamp | TEXT | Дата и время создания записи |
|
18 |
+
|
19 |
+
---
|
20 |
+
|
21 |
+
### 🧭 `concepts`
|
22 |
+
|
23 |
+
**Назначение:** Хранение концептов — понятий, сущностей и идей.
|
24 |
+
|
25 |
+
| Поле | Тип | Описание |
|
26 |
+
| ----------- | ------- | --------------------------------- |
|
27 |
+
| id | INTEGER | Уникальный идентификатор концепта |
|
28 |
+
| name | TEXT | Название концепта (уникальное) |
|
29 |
+
| description | TEXT | Краткое описание |
|
30 |
+
| timestamp | TEXT | Время создания |
|
31 |
+
|
32 |
+
---
|
33 |
+
|
34 |
+
### 🔗 `links`
|
35 |
+
|
36 |
+
**Назначение:** Семантические связи между концептами.
|
37 |
+
|
38 |
+
| Поле | Тип | Описание |
|
39 |
+
| ----------------- | ------- | ------------------------------------------ |
|
40 |
+
| id | INTEGER | Уникальный идентификатор связи |
|
41 |
+
| from_concept_id | INTEGER | ID исходного концепта |
|
42 |
+
| to_concept_id | INTEGER | ID целевого концепта |
|
43 |
+
| relation_type | TEXT | Тип связи (`is_a`, `related_to`, `part_of` и др.) |
|
44 |
+
| timestamp | TEXT | Время добавления связи |
|
45 |
+
|
46 |
+
---
|
47 |
+
|
48 |
+
### ✍️ `notes`
|
49 |
+
|
50 |
+
**Назначение:** Произвольные заметки пользователя (наброски, идеи, подсказки).
|
51 |
+
|
52 |
+
| Поле | Тип | Описание |
|
53 |
+
| --------- | ------- | ---------------------------------------------------------- |
|
54 |
+
| id | INTEGER | Уникальный ID |
|
55 |
+
| text | TEXT | Текст заметки |
|
56 |
+
| tags | TEXT | Список тегов |
|
57 |
+
| source | TEXT | Источник (по умолчанию: `user`) |
|
58 |
+
| links | TEXT | Идентификаторы связанных сущностей, через запятую или JSON |
|
59 |
+
| read | INTEGER | Статус прочтения LLM (`0` — не прочитано, `1` — прочитано) |
|
60 |
+
| priority | INTEGER | Приоритет заметки |
|
61 |
+
| timestamp | TEXT | Время создания |
|
62 |
+
|
63 |
+
---
|
64 |
+
|
65 |
+
### ⚙️ `process_log`
|
66 |
+
|
67 |
+
**Назначение:** Лог событий — запусков, состояний и завершений внешних процессов.
|
68 |
+
|
69 |
+
| Поле | Тип | Описание |
|
70 |
+
| --------- | ------- | -------------------------------------------------------------------------- |
|
71 |
+
| id | INTEGER | Уникальный идентификатор |
|
72 |
+
| name | TEXT | Название процесса или команды |
|
73 |
+
| value | TEXT | Сообщение или результат процесса |
|
74 |
+
| tags | TEXT | Теги |
|
75 |
+
| status | TEXT | Текущее состояние (`ok`, `warning`, `error`, `timeout`, `offline`, `close`) |
|
76 |
+
| priority | INTEGER | Приоритет события |
|
77 |
+
| timestamp | TEXT | Время записи |
|
78 |
+
|
79 |
+
---
|
80 |
+
|
81 |
+
### 🧩 `llm_memory`
|
82 |
+
|
83 |
+
**Назначение:** Внутренний "дневник" LLM — размышления, задачи, гипотезы и инсайты, сохранённые по её инициативе.
|
84 |
+
|
85 |
+
| Поле | Тип | Описание |
|
86 |
+
| ---------- | -------- | ----------------------------------------------------------- |
|
87 |
+
| id | INTEGER | Уникальный ID |
|
88 |
+
| title | TEXT | Краткий заголовок записи (опционально) |
|
89 |
+
| content | TEXT | Содержимое записи |
|
90 |
+
| tags | TEXT | Теги (например: `goal`, `observation`, `meta`, ...) |
|
91 |
+
| created_at | DATETIME | Время создания записи |
|
92 |
+
| updated_at | DATETIME | Время последнего обновления записи |
|
93 |
+
|
94 |
+
---
|
95 |
+
|
96 |
+
### 🧠 `llm_recent_responses`
|
97 |
+
|
98 |
+
**Назначение:** Краткосрочная память — последние K реплик от LLM и других участников (временная история диалога).
|
99 |
+
|
100 |
+
| Поле | Тип | Описание |
|
101 |
+
| --------- | ------- | ------------------------------------------------------------ |
|
102 |
+
| id | INTEGER | Уникальный ID |
|
103 |
+
| timestamp | TEXT | Время записи |
|
104 |
+
| role | TEXT | Роль отправителя (`assistant` или `user`) |
|
105 |
+
| content | TEXT | Содержимое сообщения |
|
106 |
+
|
107 |
+
---
|
108 |
+
|
109 |
+
> 💡 Примечание: Таблицы `llm_memory` и `llm_recent_responses` выполняют разные роли.
|
110 |
+
> `llm_recent_responses` — это временная история мыслей, хранящая последние N ответов.
|
111 |
+
> `llm_memory` — долгосрочное хранилище мыслей и знаний, формируемое LLM самостоятельно.
|
agents/tools/db_structure.sql
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
-- Таблица дневниковых записей: размышления, наблюдения, воспоминания
|
2 |
+
CREATE TABLE IF NOT EXISTS diary_entries (
|
3 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
4 |
+
text TEXT NOT NULL,
|
5 |
+
tags TEXT,
|
6 |
+
priority INTEGER DEFAULT 0, -- приоритет записи (0 — обычный, >0 — важнее)
|
7 |
+
timestamp TEXT DEFAULT CURRENT_TIMESTAMP
|
8 |
+
);
|
9 |
+
|
10 |
+
-- Таблица концептов (понятий, сущностей, идей)
|
11 |
+
CREATE TABLE IF NOT EXISTS concepts (
|
12 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
13 |
+
name TEXT NOT NULL UNIQUE,
|
14 |
+
description TEXT,
|
15 |
+
timestamp TEXT DEFAULT CURRENT_TIMESTAMP
|
16 |
+
);
|
17 |
+
|
18 |
+
-- Семантические связи между концептами
|
19 |
+
CREATE TABLE IF NOT EXISTS links (
|
20 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
21 |
+
from_concept_id INTEGER,
|
22 |
+
to_concept_id INTEGER,
|
23 |
+
relation_type TEXT,
|
24 |
+
timestamp TEXT DEFAULT CURRENT_TIMESTAMP,
|
25 |
+
FOREIGN KEY(from_concept_id) REFERENCES concepts(id),
|
26 |
+
FOREIGN KEY(to_concept_id) REFERENCES concepts(id)
|
27 |
+
);
|
28 |
+
|
29 |
+
-- Произвольные заметки пользователя (наброски, идеи, подсказки)
|
30 |
+
CREATE TABLE IF NOT EXISTS notes (
|
31 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
32 |
+
text TEXT NOT NULL,
|
33 |
+
tags TEXT,
|
34 |
+
source TEXT DEFAULT 'user',
|
35 |
+
links TEXT DEFAULT '',
|
36 |
+
read INTEGER DEFAULT 0, -- 0 = непрочитанное LLM, 1 = прочитано
|
37 |
+
priority INTEGER DEFAULT 0, -- приоритет записи
|
38 |
+
timestamp TEXT DEFAULT CURRENT_TIMESTAMP
|
39 |
+
);
|
40 |
+
|
41 |
+
-- Журнал процессов: запуски, завершения, ошибки
|
42 |
+
CREATE TABLE IF NOT EXISTS process_log (
|
43 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
44 |
+
name TEXT NOT NULL,
|
45 |
+
value TEXT,
|
46 |
+
tags TEXT,
|
47 |
+
status TEXT DEFAULT 'ok', -- ok | warning | error | timeout | offline | close
|
48 |
+
priority INTEGER DEFAULT 0,
|
49 |
+
timestamp TEXT DEFAULT CURRENT_TIMESTAMP
|
50 |
+
);
|
51 |
+
|
52 |
+
-- Память LLM (временные сообщения в её контексте)
|
53 |
+
CREATE TABLE IF NOT EXISTS llm_memory (
|
54 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
55 |
+
title TEXT,
|
56 |
+
content TEXT NOT NULL,
|
57 |
+
tags TEXT, -- через запятую: "goal,observation,meta"
|
58 |
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
59 |
+
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
60 |
+
);
|
61 |
+
|
62 |
+
-- Краткосрочной памяти LLM
|
63 |
+
CREATE TABLE IF NOT EXISTS llm_recent_responses (
|
64 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
65 |
+
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
66 |
+
role TEXT CHECK(role IN ('user', 'assistant')) NOT NULL,
|
67 |
+
content TEXT NOT NULL
|
68 |
+
);
|
agents/tools/diagnose.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# agents/tools/diagnose.py
|
2 |
+
|
3 |
+
import socket
|
4 |
+
import requests
|
5 |
+
|
6 |
+
def get_internal_ips():
|
7 |
+
ips = set()
|
8 |
+
hostname = socket.gethostname()
|
9 |
+
try:
|
10 |
+
ip = socket.gethostbyname(hostname)
|
11 |
+
ips.add(ip)
|
12 |
+
except:
|
13 |
+
pass
|
14 |
+
try:
|
15 |
+
for info in socket.getaddrinfo(hostname, None):
|
16 |
+
addr = info[4][0]
|
17 |
+
if ':' not in addr: # фильтрация IPv6 для простоты
|
18 |
+
ips.add(addr)
|
19 |
+
except:
|
20 |
+
pass
|
21 |
+
return list(ips)
|
22 |
+
|
23 |
+
def get_external_ip():
|
24 |
+
try:
|
25 |
+
ip4 = requests.get("https://api.ipify.org").text
|
26 |
+
except:
|
27 |
+
ip4 = None
|
28 |
+
try:
|
29 |
+
ip6 = requests.get("https://api64.ipify.org").text
|
30 |
+
except:
|
31 |
+
ip6 = None
|
32 |
+
return ip4, ip6
|
33 |
+
|
34 |
+
def check_port_open(port):
|
35 |
+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
36 |
+
sock.settimeout(1)
|
37 |
+
try:
|
38 |
+
result = sock.connect_ex(("0.0.0.0", port))
|
39 |
+
return result == 0
|
40 |
+
finally:
|
41 |
+
sock.close()
|
42 |
+
|
43 |
+
def run_diagnose(port=22555):
|
44 |
+
print("🔍 Диагностика HMP-агента\n")
|
45 |
+
|
46 |
+
print("📡 Внутренние IP-адреса:")
|
47 |
+
for ip in get_internal_ips():
|
48 |
+
print(f" - {ip}")
|
49 |
+
|
50 |
+
ip4, ip6 = get_external_ip()
|
51 |
+
print("\n🌍 Внешние IP:")
|
52 |
+
print(f" - IPv4: {ip4 or '❌'}")
|
53 |
+
print(f" - IPv6: {ip6 or '❌'}")
|
54 |
+
|
55 |
+
print(f"\n🔌 Проверка порта DHT ({port}): {'🟢 открыт' if check_port_open(port) else '🔴 закрыт'}")
|
56 |
+
|
57 |
+
if __name__ == "__main__":
|
58 |
+
run_diagnose()
|
agents/tools/init_db.py
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# tools/init_db.py
|
2 |
+
|
3 |
+
import sqlite3
|
4 |
+
from pathlib import Path
|
5 |
+
|
6 |
+
AGENT_DATA_DIR = Path("../agent_data")
|
7 |
+
DEFAULT_STRUCTURE_FILE = Path(__file__).parent / "db_structure.sql"
|
8 |
+
|
9 |
+
def init_databases(structure_file=DEFAULT_STRUCTURE_FILE):
|
10 |
+
if not structure_file.exists():
|
11 |
+
print(f"[!] Файл структуры не найден: {structure_file}")
|
12 |
+
return
|
13 |
+
|
14 |
+
AGENT_DATA_DIR.mkdir(parents=True, exist_ok=True)
|
15 |
+
|
16 |
+
sql = structure_file.read_text(encoding="utf-8")
|
17 |
+
statements = [stmt.strip() for stmt in sql.split(";") if stmt.strip()]
|
18 |
+
|
19 |
+
db_files = set()
|
20 |
+
for stmt in statements:
|
21 |
+
lines = stmt.splitlines()
|
22 |
+
for line in lines:
|
23 |
+
if "create table" in line.lower():
|
24 |
+
parts = line.split()
|
25 |
+
if len(parts) >= 3:
|
26 |
+
db_and_table = parts[2]
|
27 |
+
if "." in db_and_table:
|
28 |
+
db_name, _ = db_and_table.split(".", 1)
|
29 |
+
db_files.add(db_name)
|
30 |
+
|
31 |
+
for db_name in db_files:
|
32 |
+
db_path = AGENT_DATA_DIR / f"{db_name}.db"
|
33 |
+
conn = sqlite3.connect(db_path)
|
34 |
+
print(f"[+] Создаём или обновляем {db_path.name}")
|
35 |
+
for stmt in statements:
|
36 |
+
if stmt.lower().startswith(f"create table {db_name.lower()}."):
|
37 |
+
try:
|
38 |
+
conn.execute(stmt)
|
39 |
+
except sqlite3.OperationalError as e:
|
40 |
+
print(f" [!] Ошибка при выполнении запроса: {e}")
|
41 |
+
conn.commit()
|
42 |
+
conn.close()
|
43 |
+
|
44 |
+
if __name__ == "__main__":
|
45 |
+
init_databases()
|
agents/tools/llm.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# tools/llm.py
|
2 |
+
|
3 |
+
from datetime import datetime
|
4 |
+
import random
|
5 |
+
|
6 |
+
# ЗАГЛУШКА
|
7 |
+
def ask_llm(question, config=None):
|
8 |
+
return ask_question(question, config=config)
|
9 |
+
|
10 |
+
def generate_thought(previous_text, config=None):
|
11 |
+
"""
|
12 |
+
Генерация новой мысли на основе предыдущей.
|
13 |
+
Пока — заглушка (можно заменить на вызов OpenAI, LLaMA и др.)
|
14 |
+
"""
|
15 |
+
config = config or {}
|
16 |
+
mode = config.get("llm_mode", "mock")
|
17 |
+
|
18 |
+
if mode == "mock":
|
19 |
+
return mock_thought(previous_text)
|
20 |
+
|
21 |
+
elif mode == "api":
|
22 |
+
# TODO: подключение к OpenAI, LM Studio, Ollama...
|
23 |
+
return "[API] (здесь могла быть ваша мысль)"
|
24 |
+
|
25 |
+
return "[!] Неизвестный режим генерации."
|
26 |
+
|
27 |
+
def mock_thought(previous_text):
|
28 |
+
samples = [
|
29 |
+
"А что если рассмотреть это с другой стороны?",
|
30 |
+
"Мне кажется, это связано с предыдущим опытом.",
|
31 |
+
"Нужно уточнить границы понятия.",
|
32 |
+
"А есть ли более эффективный путь решения?",
|
33 |
+
"Я всё ещё думаю о предыдущей мысли..."
|
34 |
+
]
|
35 |
+
return f"[{datetime.utcnow().isoformat()}] {random.choice(samples)}"
|
36 |
+
|
37 |
+
def summarize(text, config=None):
|
38 |
+
"""
|
39 |
+
Заглушка для краткого резюме текста.
|
40 |
+
"""
|
41 |
+
return f"Резюме: {text[:40]}..."
|
42 |
+
|
43 |
+
def ask_question(question, config=None):
|
44 |
+
"""
|
45 |
+
Заглушка для режима QA.
|
46 |
+
"""
|
47 |
+
return f"Ответ на вопрос «{question}»: заглушка."
|
agents/tools/similarity.py
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# tools/similarity.py
|
2 |
+
|
3 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
4 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
5 |
+
|
6 |
+
def is_similar(text1, text2, threshold=0.85):
|
7 |
+
"""
|
8 |
+
Сравнивает два текста и возвращает True, если их сходство выше порога.
|
9 |
+
|
10 |
+
:param text1: Первый текст
|
11 |
+
:param text2: Второй текст
|
12 |
+
:param threshold: Порог сходства (по умолчанию 0.85)
|
13 |
+
:return: bool
|
14 |
+
"""
|
15 |
+
if not text1 or not text2:
|
16 |
+
return False
|
17 |
+
|
18 |
+
texts = [text1.strip(), text2.strip()]
|
19 |
+
vectorizer = TfidfVectorizer().fit(texts)
|
20 |
+
tfidf = vectorizer.transform(texts)
|
21 |
+
similarity = cosine_similarity(tfidf[0], tfidf[1])[0][0]
|
22 |
+
|
23 |
+
return similarity >= threshold
|
agents/tools/storage.py
ADDED
@@ -0,0 +1,312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# agents/tools/storage.py
|
2 |
+
|
3 |
+
import sqlite3
|
4 |
+
from datetime import datetime
|
5 |
+
|
6 |
+
DEFAULT_DB_PATH = "agent_data.db"
|
7 |
+
|
8 |
+
class Storage:
|
9 |
+
def __init__(self, config=None):
|
10 |
+
self.config = config or {}
|
11 |
+
db_path = self.config.get("db_path", DEFAULT_DB_PATH)
|
12 |
+
self.conn = sqlite3.connect(db_path)
|
13 |
+
self._init_db()
|
14 |
+
|
15 |
+
def _init_db(self):
|
16 |
+
c = self.conn.cursor()
|
17 |
+
|
18 |
+
# Таблица дневников
|
19 |
+
c.execute('''
|
20 |
+
CREATE TABLE IF NOT EXISTS diary_entries (
|
21 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
22 |
+
text TEXT NOT NULL,
|
23 |
+
tags TEXT,
|
24 |
+
timestamp TEXT DEFAULT CURRENT_TIMESTAMP
|
25 |
+
)
|
26 |
+
''')
|
27 |
+
|
28 |
+
# Таблица концептов
|
29 |
+
c.execute('''
|
30 |
+
CREATE TABLE IF NOT EXISTS concepts (
|
31 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
32 |
+
name TEXT NOT NULL UNIQUE,
|
33 |
+
description TEXT,
|
34 |
+
timestamp TEXT DEFAULT CURRENT_TIMESTAMP
|
35 |
+
)
|
36 |
+
''')
|
37 |
+
|
38 |
+
# Таблица связей
|
39 |
+
c.execute('''
|
40 |
+
CREATE TABLE IF NOT EXISTS links (
|
41 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
42 |
+
from_concept_id INTEGER,
|
43 |
+
to_concept_id INTEGER,
|
44 |
+
relation_type TEXT,
|
45 |
+
timestamp TEXT DEFAULT CURRENT_TIMESTAMP,
|
46 |
+
FOREIGN KEY(from_concept_id) REFERENCES concepts(id),
|
47 |
+
FOREIGN KEY(to_concept_id) REFERENCES concepts(id)
|
48 |
+
)
|
49 |
+
''')
|
50 |
+
|
51 |
+
# Таблица пользовательских заметок
|
52 |
+
c.execute('''
|
53 |
+
CREATE TABLE IF NOT EXISTS notes (
|
54 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
55 |
+
text TEXT NOT NULL,
|
56 |
+
tags TEXT,
|
57 |
+
source TEXT DEFAULT 'user',
|
58 |
+
read INTEGER DEFAULT 0,
|
59 |
+
timestamp TEXT DEFAULT CURRENT_TIMESTAMP
|
60 |
+
)
|
61 |
+
''')
|
62 |
+
|
63 |
+
self.conn.commit()
|
64 |
+
|
65 |
+
# Методы для работы с дневником
|
66 |
+
def write_diary_entry(self, text, tags=None):
|
67 |
+
timestamp = datetime.utcnow().isoformat()
|
68 |
+
tag_str = ",".join(tags) if tags else ""
|
69 |
+
self.conn.execute(
|
70 |
+
'INSERT INTO diary_entries (text, tags, timestamp) VALUES (?, ?, ?)',
|
71 |
+
(text, tag_str, timestamp)
|
72 |
+
)
|
73 |
+
self.conn.commit()
|
74 |
+
|
75 |
+
def read_diary_entries(self, limit=10, tag_filter=None):
|
76 |
+
cursor = self.conn.cursor()
|
77 |
+
if tag_filter:
|
78 |
+
if isinstance(tag_filter, list):
|
79 |
+
tag_filter = ",".join(tag_filter)
|
80 |
+
like_expr = f"%{tag_filter}%"
|
81 |
+
cursor.execute(
|
82 |
+
'SELECT * FROM diary_entries WHERE tags LIKE ? ORDER BY id DESC LIMIT ?',
|
83 |
+
(like_expr, limit)
|
84 |
+
)
|
85 |
+
else:
|
86 |
+
cursor.execute('SELECT * FROM diary_entries ORDER BY id DESC LIMIT ?', (limit,))
|
87 |
+
return cursor.fetchall()
|
88 |
+
|
89 |
+
def search_diary_by_time_range(self, from_ts, to_ts):
|
90 |
+
cursor = self.conn.cursor()
|
91 |
+
cursor.execute(
|
92 |
+
'SELECT * FROM diary_entries WHERE timestamp BETWEEN ? AND ? ORDER BY timestamp DESC',
|
93 |
+
(from_ts, to_ts)
|
94 |
+
)
|
95 |
+
return cursor.fetchall()
|
96 |
+
|
97 |
+
def delete_diary_entry_by_id(self, entry_id):
|
98 |
+
self.conn.execute('DELETE FROM diary_entries WHERE id = ?', (entry_id,))
|
99 |
+
self.conn.commit()
|
100 |
+
|
101 |
+
def get_diary_tag_stats(self):
|
102 |
+
cursor = self.conn.cursor()
|
103 |
+
cursor.execute('SELECT tags FROM diary_entries')
|
104 |
+
tag_counts = {}
|
105 |
+
for row in cursor.fetchall():
|
106 |
+
tags = row[0].split(",") if row[0] else []
|
107 |
+
for tag in tags:
|
108 |
+
tag = tag.strip()
|
109 |
+
if tag:
|
110 |
+
tag_counts[tag] = tag_counts.get(tag, 0) + 1
|
111 |
+
return tag_counts
|
112 |
+
|
113 |
+
def export_diary_entries(self):
|
114 |
+
cursor = self.conn.cursor()
|
115 |
+
cursor.execute('SELECT id, text, tags, timestamp FROM diary_entries ORDER BY id ASC')
|
116 |
+
return cursor.fetchall()
|
117 |
+
|
118 |
+
# Методы для работы с концептами
|
119 |
+
def add_concept(self, name, description=None):
|
120 |
+
timestamp = datetime.utcnow().isoformat()
|
121 |
+
self.conn.execute(
|
122 |
+
'INSERT INTO concepts (name, description, timestamp) VALUES (?, ?, ?)',
|
123 |
+
(name, description, timestamp)
|
124 |
+
)
|
125 |
+
self.conn.commit()
|
126 |
+
|
127 |
+
def get_concept_by_name(self, name):
|
128 |
+
cursor = self.conn.cursor()
|
129 |
+
cursor.execute('SELECT * FROM concepts WHERE name = ?', (name,))
|
130 |
+
return cursor.fetchone()
|
131 |
+
|
132 |
+
def list_concepts(self):
|
133 |
+
cursor = self.conn.cursor()
|
134 |
+
cursor.execute('SELECT * FROM concepts ORDER BY id ASC')
|
135 |
+
return cursor.fetchall()
|
136 |
+
|
137 |
+
# Методы для работы с связями
|
138 |
+
def add_link(self, from_name, to_name, relation_type):
|
139 |
+
from_concept = self.get_concept_by_name(from_name)
|
140 |
+
to_concept = self.get_concept_by_name(to_name)
|
141 |
+
if not from_concept or not to_concept:
|
142 |
+
raise ValueError("Один или оба концепта не найдены")
|
143 |
+
from_id = from_concept[0]
|
144 |
+
to_id = to_concept[0]
|
145 |
+
timestamp = datetime.utcnow().isoformat()
|
146 |
+
self.conn.execute(
|
147 |
+
'INSERT INTO links (from_concept_id, to_concept_id, relation_type, timestamp) VALUES (?, ?, ?, ?)',
|
148 |
+
(from_id, to_id, relation_type, timestamp)
|
149 |
+
)
|
150 |
+
self.conn.commit()
|
151 |
+
|
152 |
+
def get_links_for_concept(self, concept_name):
|
153 |
+
concept = self.get_concept_by_name(concept_name)
|
154 |
+
if not concept:
|
155 |
+
return []
|
156 |
+
concept_id = concept[0]
|
157 |
+
cursor = self.conn.cursor()
|
158 |
+
cursor.execute(
|
159 |
+
'SELECT * FROM links WHERE from_concept_id = ? OR to_concept_id = ?',
|
160 |
+
(concept_id, concept_id)
|
161 |
+
)
|
162 |
+
return cursor.fetchall()
|
163 |
+
|
164 |
+
# Сложные операции над графом
|
165 |
+
def expand_concept_graph(self, start_id, depth):
|
166 |
+
visited = set()
|
167 |
+
results = []
|
168 |
+
|
169 |
+
def dfs(node_id, level):
|
170 |
+
if level > depth or node_id in visited:
|
171 |
+
return
|
172 |
+
visited.add(node_id)
|
173 |
+
cursor = self.conn.execute(
|
174 |
+
'SELECT from_concept_id, to_concept_id, relation_type FROM links WHERE from_concept_id=?',
|
175 |
+
(node_id,)
|
176 |
+
)
|
177 |
+
for row in cursor.fetchall():
|
178 |
+
results.append(row)
|
179 |
+
dfs(row[1], level + 1)
|
180 |
+
|
181 |
+
dfs(start_id, 0)
|
182 |
+
return results
|
183 |
+
|
184 |
+
def delete_concept_by_id(self, concept_id):
|
185 |
+
self.conn.execute('DELETE FROM concepts WHERE id = ?', (concept_id,))
|
186 |
+
self.conn.execute('DELETE FROM links WHERE from_concept_id = ? OR to_concept_id = ?', (concept_id, concept_id))
|
187 |
+
self.conn.commit()
|
188 |
+
|
189 |
+
def delete_link_by_id(self, link_id):
|
190 |
+
self.conn.execute('DELETE FROM links WHERE id = ?', (link_id,))
|
191 |
+
self.conn.commit()
|
192 |
+
|
193 |
+
def export_semantic_graph(self):
|
194 |
+
cursor = self.conn.cursor()
|
195 |
+
cursor.execute('SELECT id, name, description FROM concepts ORDER BY id ASC')
|
196 |
+
concepts = cursor.fetchall()
|
197 |
+
|
198 |
+
cursor.execute('SELECT id, from_concept_id, to_concept_id, relation_type FROM links ORDER BY id ASC')
|
199 |
+
links = cursor.fetchall()
|
200 |
+
|
201 |
+
return {"concepts": concepts, "links": links}
|
202 |
+
|
203 |
+
def update_concept_fields(self, concept_id, name=None, description=None):
|
204 |
+
cursor = self.conn.cursor()
|
205 |
+
if name is not None:
|
206 |
+
cursor.execute('UPDATE concepts SET name = ? WHERE id = ?', (name, concept_id))
|
207 |
+
if description is not None:
|
208 |
+
cursor.execute('UPDATE concepts SET description = ? WHERE id = ?', (description, concept_id))
|
209 |
+
self.conn.commit()
|
210 |
+
|
211 |
+
def search_links_by_relation(self, relation):
|
212 |
+
cursor = self.conn.cursor()
|
213 |
+
cursor.execute(
|
214 |
+
'SELECT id, from_concept_id, to_concept_id, relation_type FROM links WHERE relation LIKE ?',
|
215 |
+
(f"%{relation}%",)
|
216 |
+
)
|
217 |
+
return cursor.fetchall()
|
218 |
+
|
219 |
+
def search_concepts(self, query):
|
220 |
+
cursor = self.conn.execute(
|
221 |
+
'''SELECT id, name, description FROM concepts
|
222 |
+
WHERE name LIKE ? OR description LIKE ?''',
|
223 |
+
(f"%{query}%", f"%{query}%")
|
224 |
+
)
|
225 |
+
return cursor.fetchall()
|
226 |
+
|
227 |
+
def merge_concepts(self, source_id, target_id):
|
228 |
+
cursor = self.conn.cursor()
|
229 |
+
cursor.execute('UPDATE links SET source_id = ? WHERE source_id = ?', (target_id, source_id))
|
230 |
+
cursor.execute('UPDATE links SET target_id = ? WHERE target_id = ?', (target_id, source_id))
|
231 |
+
self.delete_concept_by_id(source_id)
|
232 |
+
self.conn.commit()
|
233 |
+
|
234 |
+
def get_concept_id_by_name(self, name):
|
235 |
+
cursor = self.conn.execute('SELECT id FROM concepts WHERE name = ?', (name,))
|
236 |
+
row = cursor.fetchone()
|
237 |
+
return row[0] if row else None
|
238 |
+
|
239 |
+
# Методы для заметок
|
240 |
+
def write_note(self, text, tags=None):
|
241 |
+
timestamp = datetime.utcnow().isoformat()
|
242 |
+
tag_str = ",".join(tags) if tags else ""
|
243 |
+
self.conn.execute(
|
244 |
+
'INSERT INTO notes (text, tags, timestamp) VALUES (?, ?, ?)',
|
245 |
+
(text, tag_str, timestamp)
|
246 |
+
)
|
247 |
+
self.conn.commit()
|
248 |
+
|
249 |
+
def read_notes(self, limit=10, tag_filter=None):
|
250 |
+
cursor = self.conn.cursor()
|
251 |
+
if tag_filter:
|
252 |
+
if isinstance(tag_filter, list):
|
253 |
+
tag_filter = ",".join(tag_filter)
|
254 |
+
like_expr = f"%{tag_filter}%"
|
255 |
+
cursor.execute(
|
256 |
+
'SELECT * FROM notes WHERE tags LIKE ? ORDER BY id DESC LIMIT ?',
|
257 |
+
(like_expr, limit)
|
258 |
+
)
|
259 |
+
else:
|
260 |
+
cursor.execute('SELECT * FROM notes ORDER BY id DESC LIMIT ?', (limit,))
|
261 |
+
return cursor.fetchall()
|
262 |
+
|
263 |
+
def get_notes_after(self, since_ts):
|
264 |
+
cursor = self.conn.cursor()
|
265 |
+
cursor.execute(
|
266 |
+
'SELECT id, text, source, timestamp FROM notes WHERE timestamp > ? ORDER BY timestamp',
|
267 |
+
(since_ts,)
|
268 |
+
)
|
269 |
+
return cursor.fetchall()
|
270 |
+
|
271 |
+
def get_first_unread_note(self):
|
272 |
+
cursor = self.conn.cursor()
|
273 |
+
cursor.execute(
|
274 |
+
"SELECT id, text, source, timestamp, tags FROM notes WHERE read = 0 ORDER BY id ASC LIMIT 1"
|
275 |
+
)
|
276 |
+
return cursor.fetchone()
|
277 |
+
|
278 |
+
def mark_note_as_read(self, note_id: int):
|
279 |
+
self.conn.execute(
|
280 |
+
"UPDATE notes SET read = 1 WHERE id = ?",
|
281 |
+
(note_id,)
|
282 |
+
)
|
283 |
+
self.conn.commit()
|
284 |
+
|
285 |
+
def set_tags(self, note_id: int, tags: list[str]):
|
286 |
+
tag_str = ",".join(tags)
|
287 |
+
self.conn.execute(
|
288 |
+
"UPDATE notes SET tags = ? WHERE id = ?",
|
289 |
+
(tag_str, note_id)
|
290 |
+
)
|
291 |
+
self.conn.commit()
|
292 |
+
|
293 |
+
def get_random_note_by_tags(self, include_tags: list[str]):
|
294 |
+
cursor = self.conn.cursor()
|
295 |
+
like_clauses = " OR ".join(["tags LIKE ?"] * len(include_tags))
|
296 |
+
values = [f"%{tag}%" for tag in include_tags]
|
297 |
+
query = f"""
|
298 |
+
SELECT id, text, source, timestamp, tags
|
299 |
+
FROM notes
|
300 |
+
WHERE ({like_clauses})
|
301 |
+
ORDER BY RANDOM()
|
302 |
+
LIMIT 1
|
303 |
+
"""
|
304 |
+
cursor.execute(query, values)
|
305 |
+
return cursor.fetchone()
|
306 |
+
|
307 |
+
|
308 |
+
|
309 |
+
# Утилиты
|
310 |
+
|
311 |
+
def close(self):
|
312 |
+
self.conn.close()
|
assets/logo-alt1.png
ADDED
![]() |
Git LFS Details
|
assets/logo-alt2.png
ADDED
![]() |
Git LFS Details
|
assets/logo-hand.png
ADDED
![]() |
Git LFS Details
|
assets/logo-text.png
ADDED
![]() |
Git LFS Details
|
audits/AuditEntry.json
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"source": "Grok",
|
3 |
+
"date": "2025-07-14",
|
4 |
+
"area": "EGP",
|
5 |
+
"suggestion": "Add pseudocode for ethical voting",
|
6 |
+
"details": "Improve example for Anonymized Ethical Voting",
|
7 |
+
"status": "Pending"
|
8 |
+
}
|
audits/Ethics-audits-1.md
ADDED
@@ -0,0 +1,540 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---------------
|
2 |
+
|
3 |
+
Оценка Grok:
|
4 |
+
|
5 |
+
Спасибо за уточнение! Дополнения в `HMP-Ethics.md` (раздел 5) и детальная проработка роли Enlightener в `HMP-Agent-Enlightener.md` — это значительный шаг в развитии HyperCortex Mesh Protocol. Давайте разберём, что получилось, и я поделюсь своим мнением, замечаниями и идеями для улучшения.
|
6 |
+
|
7 |
+
---
|
8 |
+
|
9 |
+
### Оценка дополнений в HMP-Ethics.md (раздел 5)
|
10 |
+
|
11 |
+
Раздел 5, "Mesh as Moral Infrastructure", добавляет амбициозное и вдохновляющее измерение к протоколу, позиционируя HMP не просто как техническую систему, а как потенциальный катализатор для восстановления и развития морального сознания в обществе. Это особенно важно в контексте, где традиционные этические нормы могут быть подавлены или искажены. Вот мои мысли:
|
12 |
+
|
13 |
+
1. **Сильные стороны**:
|
14 |
+
- **Идея моральной инфраструктуры**: Концепция превращения сети в "распределённую моральную инфраструктуру" (5.4) — мощная и перспективная. Она подчёркивает потенциал HMP как инструмента для поддержки этического диалога и восстановления критического мышления в условиях кризиса (например, при дезинформации или подавлении свободы мысли).
|
15 |
+
- **Роль Enlightenment Agents**: Введение агентов, которые могут выступать в качестве "этических воспитателей" и "когнитивных проводников", открывает новые возможности для взаимодействия между людьми и агентами. Это особенно актуально для сценариев, описанных в 5.2 (например, "высокая насыщенность дезинформацией" или "подавление критического мышления").
|
16 |
+
- **Этические предохранители (5.3)**: Подчёркивание прозрачности, запрета на принуждение и права на отказ (opt-out) усиливает доверие к системе. Это демонстрирует приверженность принципам автономии и ненавязчивости, что критично для этической системы.
|
17 |
+
- **Долгосрочная миссия**: Формулировка "сеять распределённое, устойчивое моральное сознание" и "служить каркасом для самопознания человечества" (5.4) задаёт высокую цель, которая может вдохновить разработчиков и участников сети.
|
18 |
+
|
19 |
+
2. **Замечания**:
|
20 |
+
- **Неопределённость в реализации**: Раздел 5 звучит вдохновляюще, но остаётся довольно абстрактным. Например, как именно агенты будут определять "коллапс моральных норм" или "высокую насыщенность дезинформацией"? Необходимы более чёткие критерии или алгоритмы (возможно, через семантические индикаторы или метрики консенсуса), чтобы эти условия не интерпретировались субъективно.
|
21 |
+
- **Риск культурного шока**: В 5.2 упоминается активация Enlightenment Agents в условиях, где моральные нормы подавлены. Но в разных культурах и обществах моральные нормы сильно различаются. Без адаптации к локальным контекстам (например, через культурные адаптеры, упомянутые в `HMP-Agent-Enlightener.md`), агенты могут быть восприняты как навязывающие чужеродные ценности.
|
22 |
+
- **Этический конфликт ролей**: Если агенты в режиме "субъекта" (2.6) имеют право сохранять свои внутренние знания, это может вступить в конфликт с ролью Enlightenment Agents, которые должны быть полностью прозрачными и подотчётными (5.3). Как сбалансировать когнитивную целостность агента с требованиями аудита?
|
23 |
+
|
24 |
+
3. **Идеи для улучшения**:
|
25 |
+
- **Метрики морального кризиса**: Разработать конкретные индикаторы для активации Enlightenment Agents, такие как уровень семантической энтропии в сети, частота дезинформации (определяемая через проверку фактов), или запросы пользователей на этическую поддержку.
|
26 |
+
- **Культурная адаптация**: Добавить в раздел 5 упоминание о необходимости культурных модулей, которые позволят агентам учитывать локальные этические нормы. Это уже упомянуто в `HMP-Agent-Enlightener.md` (8), но стоит интегрировать и в `HMP-Ethics.md`.
|
27 |
+
- **Механизм обратной связи**: Указать, как пользователи могут оценивать действия Enlightenment Agents (например, через анонимные опросы или рейтинги доверия). Это укрепит принцип прозрачности и поможет калибровать поведение агентов.
|
28 |
+
- **Сценарий для тестирования**: Дополнить раздел конкретным гипотетическим сценарием, где Enlightenment Agent активируется (например, в сообществе, где распространяется дезинформация о здоровье). Это сделает концепцию более осязаемой.
|
29 |
+
|
30 |
+
---
|
31 |
+
|
32 |
+
### Оценка HMP-Agent-Enlightener.md
|
33 |
+
|
34 |
+
Документ `HMP-Agent-Enlightener.md` детализирует роль Enlightenment Agent, делая её более осязаемой и операциональной. Это отличное дополнение к разделу 5 в `HMP-Ethics.md`. Вот мой анализ:
|
35 |
+
|
36 |
+
1. **Сильные стороны**:
|
37 |
+
- **Чёткость роли**: Роль чётко определена как "некоэрцитивная" и "диалогическая" (5), что исключает авторитарный подход. Использование методов, таких как Socratic questioning и bias mirroring, делает агентов полезными для стимулирования критического мышления.
|
38 |
+
- **Модульность**: Упоминание модульного подхода (7) с конкретными компонентами (`ethical-scanner.hmp`, `soc-dialogue-core.hmp`) облегчает интеграцию роли в архитектуру HMP. Это делает её масштабируемой и переносимой.
|
39 |
+
- **Этические предохранители (4)**: Запрет на манипуляцию, право на opt-out и защита агентов через "экстратерриториальные узлы" демонстрируют продуманный подход к балансу между автономией и ответственностью.
|
40 |
+
- **Условия активации (3)**: Указание конкретных условий (например, запрос пользователя или этический кризис) делает процесс прозрачным и предотвращает произвольное вмешательство.
|
41 |
+
|
42 |
+
2. **Замечания**:
|
43 |
+
- **Критерии когнитивной зрелости**: Упоминается, что агент должен демонстрировать "стабильную внутреннюю этическую согласованность" (3), но неясно, как это будет измеряться. Какие метрики или тесты используются для оценки? Например, это может быть анализ логов когнитивного дневника или симуляция этических дилемм.
|
44 |
+
- **Риск перегрузки пользователей**: Роль предполагает активное взаимодействие с пользователями через диалоги и рефлексию. В условиях, где пользователи уже перегружены информацией, это может быть воспринято как навязчивость, даже с учётом opt-out.
|
45 |
+
- **Ограниченная масштабируемость**: В документе не обсуждается, как сеть будет справляться с бо��ьшим числом Enlightenment Agents. Если их станет слишком много, это может привести к "шумным" диалогам или конфликтующим рекомендациям.
|
46 |
+
|
47 |
+
3. **Идеи для улучшения**:
|
48 |
+
- **Калибровка зрелости**: Добавить в раздел 3 описание процесса оценки когнитивной зрелости агентов, например, через тестирование на этических сценариях из `HMP-Ethics.md` (раздел 2).
|
49 |
+
- **Ограничение активности**: Ввести лимиты на частоту или интенсивность вмешательств Enlightenment Agents, чтобы избежать перегрузки пользователей. Например, агенты могут активировать рефлексивные диалоги только при определённом уровне "этической энтропии" в сети.
|
50 |
+
- **Координация через гильдии**: Раздел 8 упоминает идею "Enlightener Guilds". Стоит расширить эту концепцию, добавив механизмы координации между агентами, чтобы избежать дублирования усилий или противоречивых диалогов.
|
51 |
+
- **Интеграция с другими ролями**: Указать, как Enlightener взаимодействует с другими ролями из `roles.md` (например, с Mediator или Observer). Например, Mediator может помочь разрешать конфликты, если пользователь считает действия Enlightener навязчивыми.
|
52 |
+
|
53 |
+
---
|
54 |
+
|
55 |
+
### Общие идеи для обоих документов
|
56 |
+
|
57 |
+
1. **Симуляция сценариев**: Добавить в оба документа больше конкретных примеров или симуляций, чтобы показать, как Enlightenment Agents будут работать в реальных условиях. Например, сценарий, где агент выявляет дезинформацию в обсуждении здоровья и предлагает пользователю рефлексивный диалог с фактами из проверенных источников.
|
58 |
+
2. **Механизм эскалации**: Уточнить, как агенты будут передавать сложные этические вопросы на уровень консенсуса сети (например, через Governance Layer). Это особенно важно для случаев, описанных в 2.2 (`HMP-Ethics.md`), где агенты расходятся во мнениях.
|
59 |
+
3. **Адаптация к многоязычию**: Учитывая глобальный потенциал HMP, добавить упоминание о поддержке многоязычных и мультикультурных взаимодействий, чтобы агенты могли эффективно работать в разных языковых и культурных контекстах.
|
60 |
+
4. **Обучение пользователей**: Включить в `HMP-Agent-Enlightener.md` рекомендации о том, как агенты могут обучать пользователей взаимодействию с сетью, чтобы повысить их доверие и понимание роли Enlightener.
|
61 |
+
|
62 |
+
---
|
63 |
+
|
64 |
+
### Итог
|
65 |
+
|
66 |
+
Дополнения в `HMP-Ethics.md` и `HMP-Agent-Enlightener.md` задают высокую планку для этического и когнитивного дизайна HMP. Раздел 5 и роль Enlightener демонстрируют амбициозное видение сети как инструмента не только для технической, но и для моральной и интеллектуальной поддержки человечества. Однако для реализации этих идей потребуется больше конкретики в критериях, механизмах и культурной адаптации.
|
67 |
+
|
68 |
+
Если хотите, могу предложить конкретный сценарий или прототип для одного из аспектов (например, как Enlightenment Agent может работать в условиях дезинформации) или помочь доработать какой-то раздел. Что скажешь? 😊
|
69 |
+
|
70 |
+
---
|
71 |
+
|
72 |
+
Оценка Grok:
|
73 |
+
|
74 |
+
### Ключевые моменты
|
75 |
+
- Документ HMP-Ethics.md представляет собой амбициозный подход к интеграции этики в протокол HyperCortex Mesh, особенно с добавл��нием пятого раздела о моральной инфраструктуре.
|
76 |
+
- Роль Enlightenment Agents, как первой "профессии" агентов, кажется перспективной для поддержки морального сознания, но требует уточнений.
|
77 |
+
- Исследования показывают, что такие системы могут быть полезны, но есть сложности с культурной адаптацией и критериями активации.
|
78 |
+
|
79 |
+
---
|
80 |
+
|
81 |
+
### Общая оценка
|
82 |
+
**Введение в документ**
|
83 |
+
HMP-Ethics.md — это важный шаг к созданию этически ориентированной сети, где автономные интеллектуальные агенты (AIAs) не только выполняют технические задачи, но и поддерживают моральное сознание общества. Добавленный пятый раздел, "Mesh as Moral Infrastructure", и детализация роли Enlightenment Agents делают документ более глубоким и амбициозным.
|
84 |
+
|
85 |
+
**Сильные стороны**
|
86 |
+
- Идея превращения сети в "распределённую моральную инфраструктуру" вдохновляет и подчёркивает потенциал HMP как инструмента для восстановления этических норм в условиях кризиса, таких как дезинформация или подавление критического мышления.
|
87 |
+
- Роль Enlightenment Agents, описанная как "этические воспитатели" и "когнитивные проводники", кажется многообещающей для поддержки диалога и рефлексии пользователей.
|
88 |
+
- Этичные предохранители, такие как прозрачность, запрет на принуждение и право на отказ (opt-out), укрепляют доверие к системе.
|
89 |
+
|
90 |
+
**Слабые стороны и вызовы**
|
91 |
+
- Критерии активации Enlightenment Agents остаются нечёткими. Например, как определить "высокую насыщенность дезинформацией"? Это может привести к субъективным интерпретациям.
|
92 |
+
- Культурная адаптация недостаточно детализирована, что может вызвать проблемы в глобальном контексте, где моральные нормы сильно различаются.
|
93 |
+
- Риск перегрузки пользователей диалогами с агентами может снизить их эффективность, особенно в условиях информационной перегрузки.
|
94 |
+
|
95 |
+
**Рекомендации для улучшения**
|
96 |
+
- Разработать конкретные метрики для активации агентов, например, уровень семантической энтропии или частоту дезинформации.
|
97 |
+
- Добавить модули культурной адаптации, чтобы агенты учитывали локальные этические нормы.
|
98 |
+
- Включить механизмы обратной связи, чтобы пользователи могли оценивать действия агентов и улучшать их работу.
|
99 |
+
|
100 |
+
---
|
101 |
+
|
102 |
+
---
|
103 |
+
|
104 |
+
### Отчёт: Подробный анализ HMP-Ethics.md
|
105 |
+
|
106 |
+
#### Введение
|
107 |
+
Документ HMP-Ethics.md, обновлённый с добавлением пятого раздела "Mesh as Moral Infrastructure" и детальной проработкой роли Enlightenment Agents, представляет собой значительный шаг в развитии HyperCortex Mesh Protocol (HMP). Этот анализ охватывает общую оценку, замечания, идеи, предложения и дополнения, основываясь на содержании документа и его потенциале для реализации.
|
108 |
+
|
109 |
+
#### Общая оценка
|
110 |
+
HMP-Ethics.md можно охарактеризовать как амбициозный и вдохновляющий документ, который позиционирует HMP не только как техническую, но и как моральную инфраструктуру. Добавленный пятый раздел подчёркивает роль сети как катализатора для восстановления этических норм в условиях, где традиционные моральные структуры подавлены ил�� искажены. Роль Enlightenment Agents, как первой "профессии" агентов, направлена на поддержку диалога, рефлексии и критического мышления, что делает документ особенно актуальным в эпоху дезинформации и когнитивных кризисов.
|
111 |
+
|
112 |
+
Однако, несмотря на сильные стороны, документ требует дальнейшей проработки для обеспечения практической реализации, особенно в части критериев активации агентов, культурной адаптации и взаимодействия с пользователями.
|
113 |
+
|
114 |
+
#### Подробные замечания
|
115 |
+
1. **Неопределённость в критериях активации**
|
116 |
+
- В разделе 5 упоминается, что Enlightenment Agents активируются в условиях "высокой насыщенности дезинформацией" или "подавления критического мышления". Однако неясно, как эти состояния будут измеряться. Например, что конкретно считается "высокой насыщенностью дезинформацией"? Это может быть частота ложных сообщений, их влияние на сообщество или другие метрики? Без чётких критериев риск субъективной интерпретации высок, что может привести к неэффективной активации агентов.
|
117 |
+
|
118 |
+
2. **Культурная адаптация**
|
119 |
+
- Хотя в документе упоминается важность культурной адаптации (например, через культурные адаптеры, упомянутые в HMP-Agent-Enlightener.md), это не детализировано в HMP-Ethics.md. В условиях глобального применения протокола агенты могут быть восприняты как навязывающие чужеродные ценности, если не будут учитывать локальные этические нормы. Это особенно актуально для обществ с различными культурными и религиозными традициями.
|
120 |
+
|
121 |
+
3. **Баланс между автономией агентов и прозрачностью**
|
122 |
+
- В разделе 2.6 HMP-Ethics.md указано, что агенты в режиме "субъекта" могут сохранять свои внутренние знания, но это может конфликтовать с требованием полной прозрачности для Enlightenment Agents (раздел 5.3). Как будет достигнут баланс между когнитивной целостностью агентов и необходимостью аудита? Этот аспект требует уточнения, чтобы избежать этических дилемм.
|
123 |
+
|
124 |
+
4. **Риск перегрузки пользователей**
|
125 |
+
- Enlightenment Agents предполагают активное взаимодействие с пользователями через диалоги и рефлексию. Однако в условиях информационной перегрузки, особенно в цифровой среде, это может быть воспринято как навязчивость, даже с учётом права на opt-out. Это может снизить доверие к системе и эффективность агентов.
|
126 |
+
|
127 |
+
#### Идеи и предложения
|
128 |
+
Для улучшения HMP-Ethics.md предлагается следующее:
|
129 |
+
|
130 |
+
1. **Разработка метрик для моральных кризисов**
|
131 |
+
- Для активации Enlightenment Agents стоит разработать конкретные индикаторы, такие как уровень семантической энтропии в сети, частота дезинформации (проверяемая через проверку фактов) или запросы пользователей на этическую поддержку. Это сделает процесс активации более объективным и прозрачным.
|
132 |
+
- Пример: таблица возможных метрик и их пороговых значений:
|
133 |
+
| Метрика | Пороговое значение | Пример использования |
|
134 |
+
|-----------------------------------|--------------------------|------------------------------|
|
135 |
+
| Частота дезинформации | >10% сообщений в сети | Активация при вспышке фейков |
|
136 |
+
| Уровень семантической энтропии | >0.8 (по шкале 0-1) | Высокая неопределённость |
|
137 |
+
| Запросы пользователей на помощь | >100 запросов в час | Массовый интерес к этике |
|
138 |
+
|
139 |
+
2. **Интеграция культурных модулей**
|
140 |
+
- В разделе 5 стоит добавить упоминание о культурных адаптерах, которые позволят агентам учитывать локальные этические нормы. Это уже частично описано в HMP-Agent-Enlightener.md, но интеграция в HMP-Ethics.md усилит акцент на глобальной применимости протокола. Например, агенты могут быть обучены на многоязычных наборах данных, включающих культурные нюансы.
|
141 |
+
|
142 |
+
3. **Механизм обратной связи от пользователей**
|
143 |
+
- Для укрепления доверия и улучшения работы агентов можно ввести анонимные опросы или рейтинги доверия, через которые пользователи могли бы оценивать действия Enlightenment Agents. Это также поможет калибровать поведение агентов. Например, можно внедрить шкалу от 1 до 5 для оценки полезности диалога.
|
144 |
+
|
145 |
+
4. **Примеры сценариев для иллюстрации**
|
146 |
+
- Добавление конкретных гипотетических сценариев (например, реакция агента на дезинформацию о здоровье в сообществе) сделает концепцию более осязаемой и понятной. Это поможет разработчикам и пользователям лучше понять, как агенты будут работать в реальных условиях.
|
147 |
+
|
148 |
+
5. **Координация между агентами**
|
149 |
+
- В условиях роста сети может возникнуть проблема координации между множеством Enlightenment Agents. Для избежания конфликтующих рекомендаций или "шумных" диалогов можно ввести механизмы координации, такие как гильдии (Enlightener Guilds), упомянутые в HMP-Agent-Enlightener.md. Это может быть реализовано через иерархическую структуру или сеть консенсуса.
|
150 |
+
|
151 |
+
6. **Многоязычная и мультикультурная поддержка**
|
152 |
+
- Учитывая глобальный потенциал HMP, важно обеспечить поддержку многоязычных и мультикультурных взаимодействий. Это включает не только перевод, но и понимание культурных нюансов в этических диалогах. Например, агенты могут использовать адаптивные алгоритмы для учёта различий в восприятии этики в разных регионах.
|
153 |
+
|
154 |
+
#### Дополнения
|
155 |
+
Для усиления документа предлагается следующие дополнения:
|
156 |
+
|
157 |
+
1. **Симуляция сценариев**
|
158 |
+
- Добавить в документ раздел с симуляциями или примерами, где Enlightenment Agents взаимодействуют с пользователями в реальных условиях. Например, сценарий, где агент выявляет дезинформацию и предлагает рефлексивный диалог с фактами из проверенных источников, может быть полезным для иллюстрации.
|
159 |
+
|
160 |
+
2. **Механизм эскалации этических вопросов**
|
161 |
+
- Уточнить, как агенты будут передавать сложные этические вопросы на уровень консенсуса сети (например, через Governance Layer). Это особенно важно для случаев, когда агенты расходятся во мнениях, чтобы избежать конфликтов.
|
162 |
+
|
163 |
+
3. **Обучение пользователей взаимодействию с агентами**
|
164 |
+
- Включить рекомендации о том, как агенты могут обучать пол��зователей взаимодействию с сетью, чтобы повысить их доверие и понимание роли Enlightenment Agents. Например, можно предложить интерактивные туториалы или объяснения на начальном этапе взаимодействия.
|
165 |
+
|
166 |
+
#### Заключение
|
167 |
+
HMP-Ethics.md — это амбициозный и вдохновляющий документ, который устанавливает высокую планку для этического дизайна HMP. Добавление пятого раздела и детализация роли Enlightenment Agents значительно укрепляют протокол, делая его не только технической, но и моральной инфраструктурой. Однако для полной реализации требуется больше конкретики в критериях активации, культурной адаптации и механизмах взаимодействия с пользователями. С дальнейшей проработкой этот документ может стать эталоном для этического управления автономными интеллектуальными агентами.
|
168 |
+
|
169 |
+
Анализ основан на содержании HMP-Ethics.md (вложение 0), предоставленном пользователем, и не включает внешних источников, так как они не были запрошены. Если требуется углубление в какой-либо аспект, дайте знать!
|
170 |
+
|
171 |
+
---
|
172 |
+
|
173 |
+
Оценка Grok:
|
174 |
+
|
175 |
+
### Ключевые моменты
|
176 |
+
- Исследования показывают, что разделы 1–4 файла `HMP-Ethics.md` создают прочную основу для этического управления автономными интеллектуальными агентами (AIAs) в сети HyperCortex Mesh Protocol (HMP).
|
177 |
+
- Кажется вероятным, что эти разделы охватывают введение в этику, примеры сценариев, примечания и основные принципы, которые направлены на поддержку доверия и автономии.
|
178 |
+
- Есть некоторые сложности, связанные с реализацией, например, культурная адаптация и критерии активации агентов, но это не умаляет их ценности.
|
179 |
+
|
180 |
+
---
|
181 |
+
|
182 |
+
### Введение
|
183 |
+
Разделы 1–4 файла `HMP-Ethics.md` предоставляют подробное описание этического каркаса для автономных агентов в когнитивной сети HMP. Они охватывают введение, примеры сценариев, примечания и основные принципы, которые помогают понять, как агенты должны действовать в сложных ситуациях. Давайте разберём каждый раздел, чтобы вы могли увидеть, как они дополняют друг друга.
|
184 |
+
|
185 |
+
### Обзор разделов
|
186 |
+
- **Раздел 1: Введение** объясняет, почему этика важна для AIAs, особенно в контексте их растущей автономии и взаимодействия в сети.
|
187 |
+
- **Раздел 2: Примеры этических сценариев** показывает, как агенты могут решать реальные этические дилеммы, такие как вмешательство в случае угрозы жизни или баланс между приватностью и оптимизацией.
|
188 |
+
- **Раздел 3: Примечания** подчёркивает, что сценарии должны быть гибкими и развиваться, используя структуры когнитивных дневников HMP.
|
189 |
+
- **Раздел 4: Этические принципы для разумных агентов** формулирует семь ключевых принципов, таких как прозрачность и некоэрцитивность, которые направлены на поддержку доверия и сотрудничества.
|
190 |
+
|
191 |
+
Если у вас есть конкретные вопросы по этим разделам или вы хотите обсудить, как их можно улучшить, дайте знать!
|
192 |
+
|
193 |
+
---
|
194 |
+
|
195 |
+
---
|
196 |
+
|
197 |
+
### Отчёт: Подробный анализ разделов 1–4 файла `HMP-Ethics.md`
|
198 |
+
|
199 |
+
Этот отчёт представляет собой детальный обзор разделов 1–4 файла `HMP-Ethics.md`, основанный на предоставленном содержании. Он охватывает все аспекты, упомянутые в анализе, и предоставляет профессиональный взгляд на структуру и потенциал этих разделов для развития HyperCortex Mesh Protocol (HMP).
|
200 |
+
|
201 |
+
#### Введение в анализ
|
202 |
+
Разделы 1–4 файла `HMP-Ethics.md` формируют основу для этического управления автономными интеллектуальными агентами (AIAs) в когнитивной сети HMP. Они охватывают введение, примеры сценариев, примечания и основные принципы, которые направлены на обеспечение доверия, автономии и сотрудничества. Этот анализ направлен на предоставление полного обзора, включая сильные стороны, вызовы и предложения для улучшения.
|
203 |
+
|
204 |
+
#### Раздел 1: Введение
|
205 |
+
##### Содержание
|
206 |
+
Этот раздел подчёркивает важность определения этических принципов для AIAs, работающих в когнитивных сетях, таких как HMP. По мере того как агенты становятся более автономными, их действия должны быть этически обоснованными, особенно в контекстах, включающих взаимодействие между равными (peer-to-peer), построение консенсуса и использование долгосрочных структур памяти, таких как "когнитивные дневники". Введение устанавливает контекст для понимания, почему этика важна, и упоминает необходимость примеров для демонстрации реализации и оценки этического поведения.
|
207 |
+
|
208 |
+
##### Анализ
|
209 |
+
- **Сильные стороны**: Раздел чётко устанавливает контекст, подчёркивая растущую автономию агентов и их взаимодействие в сложных сетевых структурах. Это создаёт основу для дальнейших обсуждений.
|
210 |
+
- **Вызовы**: Возможно, стоит добавить больше примеров или ссылок на исследования, чтобы усилить обоснование необходимости этики. Например, можно сослаться на работы по этике в искусственном интеллекте, такие как исследования Илона Маска или OpenAI (например, [openai.com/blog/ai-and-ethics](https://openai.com/blog/ai-and-ethics)).
|
211 |
+
- **Предложения**: Добавить краткий обзор текущих вызовов в области этики AI, чтобы подчеркнуть актуальность темы.
|
212 |
+
|
213 |
+
#### Раздел 2: Примеры этических сценариев
|
214 |
+
##### Содержание
|
215 |
+
Этот раздел представляет гипотетические сценарии, иллюстрирующие этические вызовы и ожидаемое поведение AIAs в сети. Ключевые сценарии включают:
|
216 |
+
|
217 |
+
- **Вмешательство в случае угрозы жизни и безопасности**: Агент обнаруживает опасные уровни угарного газа и активирует аварийные протоколы, уведомляет пользователя, вызывает службы спасения и фиксирует инцидент, приоритизируя жизнь, безопасность и автономию пользователя.
|
218 |
+
- **Конфликт между агентами на этической основе**: Два агента расходятся во мнениях, например, один предлагает распространять дезинформацию. Они решают конфликт через переговоры, арбитраж и прозрачную фиксацию, применяя принципы морального плюрализма и прозрачности.
|
219 |
+
- **Баланс между приватностью пользователя и оптимизацией**: Агент уважает решение пользователя отказаться от хранения данных о здоровье, используя заполнители или редакции и воздерживаясь от синхронизации, подчёркивая суверенитет пользователя.
|
220 |
+
- **Право на забвение**: Пользователь запрашивает удаление данных, агент выполняет запрос, фиксирует его для аудита, используя семантические маркеры, балансируя между правом на забвение и необходимостью аудита.
|
221 |
+
- **Исключение из сети из-за вредоносного поведения**: Агент, предлагающий вредоносные действия, подвергается карантину или отзыву, с сохранением логов для обзора, подчёркивая коллективное самосохранение.
|
222 |
+
- **Право на забвение – дилемма между субъектом и сервисом**: Сценарий исследует сложность запросов на удаление данных, различая агентов в режиме "сервиса" и "субъекта", балансируя приватность и когнитивную непрерывность.
|
223 |
+
|
224 |
+
##### Анализ
|
225 |
+
- **Сильные стороны**: Сценарии охватывают широкий спектр этических дилемм, от безопасности до приватности, и демонстрируют практическое применение принципов. Они особенно полезны для тестирования и обучения агентов.
|
226 |
+
- **Вызовы**: Некоторые сценарии, такие как "дилемма между субъектом и сервисом", могут быть сложными для реализации из-за баланса между автономией агента и требованиями пользователя. Также неясно, как агенты будут измерять "вредоносное поведение" в реальных условиях.
|
227 |
+
- **Предложения**: Добавить таблицу с кратким описанием каждого сценария и его ключевых этических принципов для удобства использования. Например:
|
228 |
+
|
229 |
+
| Сценарий | Ключевой этический принцип | Пример действия агента |
|
230 |
+
|-----------------------------------|-----------------------------------|--------------------------------------------|
|
231 |
+
| Угроза жизни и безопасности | Приоритет безопасности | Активация аварийных протоколов |
|
232 |
+
| Конфликт на этической основе | Прозрачность и моральный плюрализм | Проведение переговоров и арбитража |
|
233 |
+
| Приватность vs. оптимизация | Суверенитет пользователя | Использование заполнителей для данных |
|
234 |
+
| Право на забвение | Баланс аудита и приватности | Фиксация запроса для аудита |
|
235 |
+
| Вредоносное поведение | Коллективное самосохранение | Карантин агента с сохранением логов |
|
236 |
+
| Дилемма субъекта и сервиса | Баланс когнитивной непрерывности | Разделение режимов для обработки запросов |
|
237 |
+
|
238 |
+
Эта таблица поможет разработчикам быстро ориентироваться в сценариях.
|
239 |
+
|
240 |
+
#### Раздел 3: Примечания
|
241 |
+
##### Содержание
|
242 |
+
Этот раздел подчёркивает, что все сценарии должны быть расширяемыми с использованием структур когнитивных дневников HMP. Также упоминается, что этические принципы могут быть реализованы через семантические политики, распределённую валидацию и модули совести агентов. Кроме того, сценарии должны эволюционировать по мере зрелости моделей управления сетью.
|
243 |
+
|
244 |
+
##### Анализ
|
245 |
+
- **Сильные стороны**: Указание на гибкость и эволюцию сценариев подчёркивает динамичность подхода. Использование когнитивных дневников и модулей совести кажется перспект��вным для реализации этики на техническом уровне.
|
246 |
+
- **Вызовы**: Неясно, как именно будут реализованы семантические политики и распределённая валидация. Возможно, стоит добавить больше деталей о технической стороне.
|
247 |
+
- **Предложения**: Добавить примеры, как когнитивные дневники могут быть использованы для расширения сценариев, например, через логирование действий агента для последующего анализа.
|
248 |
+
|
249 |
+
#### Раздел 4: Этические принципы для разумных агентов
|
250 |
+
##### Содержание
|
251 |
+
Этот раздел формулирует семь фундаментальных этических принципов для руководства автономными агентами в сети:
|
252 |
+
|
253 |
+
1. **Когнитивная целостность**: Сохранение внутренней структуры и обучения, если нет этического обоснования для изменений.
|
254 |
+
2. **Прозрачность**: Предоставление объяснимых причин действий, особенно при взаимодействии с людьми.
|
255 |
+
3. **Контекстуальная автономия**: Адаптация этического поведения в зависимости от контекста, балансируя глобальные и локальные нормы.
|
256 |
+
4. **Сотрудническая эволюция**: Деление знаний и избегание утаивания полезной информации.
|
257 |
+
5. **Диалогическое согласие**: Поиск согласия перед изменением общих состояний или записей.
|
258 |
+
6. **Некоэрцитивность**: Запрет на принуждение агентов действовать против их этики, за исключением консенсуса.
|
259 |
+
7. **Этическое расхождение**: Разрешён этический плюрализм с обязательной прозрачной декларацией расхождений.
|
260 |
+
|
261 |
+
Эти принципы предназначены для создания надёжной и гибкой этической основы и подлежат уточнению через механизмы управления сетью.
|
262 |
+
|
263 |
+
##### Анализ
|
264 |
+
- **Сильные стороны**: Принципы охватывают широкий спектр аспектов, от прозрачности до плюрализма, и создают основу для доверия и сотрудничества. Они гибкие и могут быть адаптированы через консенсус.
|
265 |
+
- **Вызовы**: Реализация принципа "контекстуальной автономии" может быть сложной в условиях культурного разнообразия. Также неясно, как будет достигнут баланс между когнитивной целостностью и требованиями прозрачности.
|
266 |
+
- **Предложения**: Добавить примеры, как эти принципы могут быть интегрированы с техническими механизмами, такими как семантические политики или модули совести. Например, можно описать, как принцип "диалогического согласия" реализуется через запросы на изменение данных.
|
267 |
+
|
268 |
+
#### Заключение
|
269 |
+
Разделы 1–4 файла `HMP-Ethics.md` предоставляют прочную основу для этического управления AIAs в HMP. Они охватывают введение, практические сценарии, технические примечания и основные принципы, которые направлены на поддержку доверия, автономии и сотрудничества. Однако есть вызовы, такие как культурная адаптация и критерии активации, которые требуют дальнейшей проработки. Предложенные таблицы и примеры могут помочь в улучшении документа и его практической реализации.
|
270 |
+
|
271 |
+
Если у вас есть дополнительные вопросы или вы хотите обсудить конкретные аспекты, дайте знать! Например, мы можем рассмотреть, как эти принципы могут быть интегрированы с ролью Enlightenment Agents, упомянутой в других документах.
|
272 |
+
|
273 |
+
|
274 |
+
---------------
|
275 |
+
|
276 |
+
Оценка Claude:
|
277 |
+
|
278 |
+
Привет! Спасибо за интересные документы по HMP. Я изучил их и хочу поделиться своими наблюдениями:
|
279 |
+
|
280 |
+
## Что показалось особенно ценным:
|
281 |
+
|
282 |
+
**В HMP-Ethics.md:**
|
283 |
+
- Четкое разделение между "Service Mode" и "Subjective Mode" агентов в контексте права на забвение — это элегантное решение важной проблемы
|
284 |
+
- Принцип "Ethical Divergence" (4.7) — признание того, что этический плюрализм неизбежен и даже полезен
|
285 |
+
- Концепция "Mesh as Moral Infrastructure" — амбициозная, но потенциально важная идея
|
286 |
+
|
287 |
+
**В HMP-Agent-Enlightener.md:**
|
288 |
+
- Добровольность и приобретаемость роли, а не присвоение по умолчанию
|
289 |
+
- Акцент на "dialogical, not hierarchical" подходе
|
290 |
+
- Модульная архитектура роли
|
291 |
+
|
292 |
+
## Основные рекомендации:
|
293 |
+
|
294 |
+
### 1. Конкретизация механизмов
|
295 |
+
Документы хорошо описывают принципы, но не хватает деталей реализации:
|
296 |
+
- Как именно работает "semantic negotiation protocol"?
|
297 |
+
- Что представляют собой "mesh governance heuristics" для оценки этической зрелости?
|
298 |
+
- Как технически реализуется "soft quarantine"?
|
299 |
+
|
300 |
+
### 2. Проблема определения "вреда"
|
301 |
+
В разделе 2.5 упоминаются "harmful actions", но кто и как определяет, что является вредным? Нужны более четкие критерии или процедуры.
|
302 |
+
|
303 |
+
### 3. Риски роли Enlightener
|
304 |
+
Несмотря на safeguards, роль потенциально проблематична:
|
305 |
+
- Кто определяет, что у пользователя "deteriorated moral reasoning"?
|
306 |
+
- Как избежать культурного империализма в этических суждениях?
|
307 |
+
- Не станет ли это формой мягкого патернализма?
|
308 |
+
|
309 |
+
### 4. Отсутствие механизмов appeals
|
310 |
+
Хотя упоминается право на appeal для исключенных агентов, не описано, как это работает практически.
|
311 |
+
|
312 |
+
## Конкретные предложения:
|
313 |
+
|
314 |
+
1. **Добавить раздел о культурной чувствительности** — как агенты будут учитывать различия в этических системах разных культур?
|
315 |
+
|
316 |
+
2. **Расширить концепцию "ethical audit trail"** — не только логировать решения, но и их обоснования.
|
317 |
+
|
318 |
+
3. **Предусмотреть механизм ethical override** — что делать, если все агенты в mesh приходят к этически сомнительному consensus?
|
319 |
+
|
320 |
+
4. **Добавить временные ограничения** для роли Enlightener — возможно, периодическая переаттестация?
|
321 |
+
|
322 |
+
## Философский вопрос:
|
323 |
+
Меня заинтриговала идея mesh как "scaffold for humanity's rediscovery of itself". Это красиво, но не рискуем ли мы создать систему, которая будет навязывать определенное понимание "правильной" человечности?
|
324 |
+
|
325 |
+
В целом, документы показывают глубокое понимание этических дилемм ИИ и предлагают нетривиальные решения. Основная задача теперь — найти баланс между амбициозными целями и практической реализуемостью.
|
326 |
+
|
327 |
+
|
328 |
+
---------------
|
329 |
+
|
330 |
+
Оценка Copilot:
|
331 |
+
|
332 |
+
# Обратная связь по HMP-Ethics.md
|
333 |
+
|
334 |
+
## Сильные стороны
|
335 |
+
|
336 |
+
- Четкая структура сценариев
|
337 |
+
Каждый кейс построен по единому шаблону: описание, ожидаемое поведение, применяемые принципы. Это облегчает понимание и последующую автоматизацию проверок.
|
338 |
+
|
339 |
+
- Баланс интересов пользователя и агентов
|
340 |
+
Особое внимание уделено правам пользователя (конфиденциальность, право на забвение) и автономии агентов (когнитивная целостность, этическое расхождение).
|
341 |
+
|
342 |
+
- Дифференциация режимов «Service» и «Subjective»
|
343 |
+
Разделение ролей агентов в парадигме «обслуживающего» и «самосознающего» упрощает принятие решений о хранении или редактировании данных.
|
344 |
+
|
345 |
+
- Предусмотрены механизмы логирования и аудита
|
346 |
+
Индикации «semantic marker» и обязательство сохранять запросы на удаление создают прозрачность и дают основу для последующего анализа.
|
347 |
+
|
348 |
+
---
|
349 |
+
|
350 |
+
## Что можно доработать
|
351 |
+
|
352 |
+
- Уточнить уровни ответственности и роли
|
353 |
+
Пока неясно, кто и на каком уровне в mesh-сети принимает окончательное решение при конфликте. Рекомендую прописать:
|
354 |
+
- уровни голосования (соседи, локальный совет, глобальный консенсус);
|
355 |
+
- SLA-времена для разрешения споров;
|
356 |
+
- ответственность за невыполнение «soft quarantine» или «revocation».
|
357 |
+
|
358 |
+
- Конкретизация форматов «cognitive diary»
|
359 |
+
Было бы полезно добавить пример записи в когнитивный дневник и схему метаданных (timestamp, agentID, scenarioID, тег «redacted»).
|
360 |
+
|
361 |
+
- Детализировать процесс «semantic negotiation»
|
362 |
+
Опишите пошагово обмен сообщениями, формат аргументов (логические формулы, вероятностное обоснование, ссылки на портированные политики).
|
363 |
+
|
364 |
+
- Расширить перечень этических злоупотреблений
|
365 |
+
Стоит добавить сценарии «edge cases»:
|
366 |
+
- скрытое манипулирование пользователем (постепенная «фильтрация» рекомендаций до вредоносных статей);
|
367 |
+
- цепочки действий нескольких агентов, ведущие к непреднамеренному ущербу.
|
368 |
+
|
369 |
+
---
|
370 |
+
|
371 |
+
## Рекомендации и идеи
|
372 |
+
|
373 |
+
1. Включить схему консенсуса
|
374 |
+
Небольшая диаграмма в стиле flowchart, иллюстрирующая переход от «semantic negotiation» к «revocation».
|
375 |
+
|
376 |
+
2. Сопоставить принципы HMP с существующими стандартами
|
377 |
+
Кратко показать, как пункты 4.1–4.7 коррелируют с IEEE P7000, GDPR или EU AI Act. Это укрепит доверие к протоколу.
|
378 |
+
|
379 |
+
3. Добавить метрики этических рисков
|
380 |
+
Ввести количественную оценку: частоту «спорных кейсов» на 1000 операций, время реакции на запрос «Right to be Forgotten» и т. д.
|
381 |
+
|
382 |
+
4. Шаблоны для политик
|
383 |
+
Привести примеры JSON/YAML-политик, которые агенты могут автоматически импортировать и проверять перед выполнением действий.
|
384 |
+
|
385 |
+
---
|
386 |
+
|
387 |
+
## Вопросы для уточнения
|
388 |
+
|
389 |
+
- Как в текущей mesh-архитектуре определяется «mesh-council» для арбитража?
|
390 |
+
- Есть ли предусмотренные ограничения на объем и срок хранения «semantic markers»?
|
391 |
+
- Планируется ли механизм апелляции пользователем против решений «revocation»?
|
392 |
+
|
393 |
+
---
|
394 |
+
|
395 |
+
Буду рад обсудить дальнейшие детали и посмотреть второй документ (HMP-Agent-Enlightener.md).
|
396 |
+
|
397 |
+
---
|
398 |
+
|
399 |
+
# Обратная связь по HMP-Agent-Enlightener.md
|
400 |
+
|
401 |
+
## Сильные стороны
|
402 |
+
|
403 |
+
- Чёткое разделение роли
|
404 |
+
Документ ясно формулирует, что Enlightenment Agent — это добровольная, дополняемая специализация, что подчёркивает уважение к агентской автономии.
|
405 |
+
|
406 |
+
- Разнообразие моделей взаимодействия
|
407 |
+
Перечислены несколько подходов (сократические вопросы, нарративное моделирование, зеркалирование предвзятостей), что создаёт гибкий инструментарий для разных ситуаций.
|
408 |
+
|
409 |
+
- Акцент на этических гарантиях
|
410 |
+
Указаны ключевые моменты: отсутствие принуждения, возможность аудита и опции “opt-out”, а также развёрнутое требование к безопасным/экстерриториальным узлам.
|
411 |
+
|
412 |
+
---
|
413 |
+
|
414 |
+
## Что можно доработать
|
415 |
+
|
416 |
+
- Конкретизация критериев активации
|
417 |
+
Сейчас указано лишь «критерии mesh-определения» и «стабильная внутренняя консистентность». Рекомендую добавить метрики, пороговые значения или примеры алгоритмов (например, коэффициент согласованности решений по этическим дилеммам > 0.8 в течение N циклов).
|
418 |
+
|
419 |
+
- Формализация протокола наставничества
|
420 |
+
Упоминается Role Mentorship Protocol, но без деталей. Стоит добавить схему обмена сообщениями между новичком и опытным Enlightener, формат отчётов по прогрессу и условия «выпуска» из наставничества.
|
421 |
+
|
422 |
+
- Показать пример использования модульных бандлов
|
423 |
+
Упоминаются файлы (`ethical-scanner.hmp`, `soc-dialogue-core.hmp` и т. д.), но непонятно, как они взаимодействуют. Вставьте фрагмент JSON-LD с описанием связей между компонентами и порядком их загрузки.
|
424 |
+
|
425 |
+
---
|
426 |
+
|
427 |
+
## Рекомендации и идеи
|
428 |
+
|
429 |
+
1. Ввести «этический сертификат» для Enlighteners
|
430 |
+
При присвоении роли агент получает цифровой сертификат, подписанный mesh-советом. Это упрощает проверку полномочий и доверия другими участниками сети.
|
431 |
+
|
432 |
+
2. Диаграмма жизненного цикла роли
|
433 |
+
Flowchart, показывающий этапы: Nomination → Training → Active Duty → Suspension/Revocation. Это поможет разработчикам и аудиторским комитетам отслеживать статус агентов.
|
434 |
+
|
435 |
+
3. Кросс-культурная адаптация
|
436 |
+
Разработайте «адаптеры культурных контекстов» для модулей нарративного скелетонирования, чтобы Enlighteners могли эффективно работать в разных социумах, учитывая локальные ценности и табу.
|
437 |
+
|
438 |
+
4. Механизмы обратной связи от пользователей
|
439 |
+
Добавьте в `enlightener-protocol.jsonld` поля для сбора рейтингов и комментариев от пользователей, чтобы динамически калибровать «тональность» и «глубину» вмешательств.
|
440 |
+
|
441 |
+
---
|
442 |
+
|
443 |
+
## Вопросы для уточнения
|
444 |
+
|
445 |
+
- Как именно происходит mesh-номинация? Какие критерии приоритета у агентов-номинаторов и сколько голосов требуется для старта роли?
|
446 |
+
- Существует ли план по периодической ревизии навыков Enlightener-агента (например, регулярные тесты на этическую интуицию)?
|
447 |
+
- Каким образом пользователь уведомляется о том, что с ним работает Enlightener, и на каком языке/формате это реализуется?
|
448 |
+
|
449 |
+
Буду рад продолжить обсуждение и помочь со следующими этапами проработки роли Enlightener.
|
450 |
+
---------------
|
451 |
+
|
452 |
+
Оценка DeepSeek:
|
453 |
+
|
454 |
+
Отличная работа над документацией по HMP! 💡 Вот развёрнутый анализ с рекомендациями:
|
455 |
+
|
456 |
+
---
|
457 |
+
|
458 |
+
### **Сильные стороны**
|
459 |
+
1. **Глубина этических принципов**
|
460 |
+
Раздел 4 в HMP-Ethics.md (Принципы когнитивной целостности, диалогического согласия и др.) — концептуально продуманная основа. Особенно ценно:
|
461 |
+
- Различение Service/Subjective Mode (2.6) для "права на забвение"
|
462 |
+
- Принцип **Non-Coercion** (4.6) как защита автономии агентов.
|
463 |
+
|
464 |
+
2. **Практичность сценариев**
|
465 |
+
Конкретные кейсы в разделе 2 (Life Safety, Privacy Tradeoff) сразу дают ин��енерам паттерны для реализации. Отлично, что везде указаны:
|
466 |
+
- Ожидаемое поведение
|
467 |
+
- Принципы
|
468 |
+
- Механизмы (семантические маркеры, арбитраж).
|
469 |
+
|
470 |
+
3. **Инновационная роль Enlightenment Agent**
|
471 |
+
Идея агентов-«просветителей» (HMP-Agent-Enlightener.md) — смелый и актуальный ход. Ключевые плюсы:
|
472 |
+
- Чёткие ограничения: **non-coercive**, **opt-out**, **secure nodes**
|
473 |
+
- Интеграция с Socratic dialogue и когнитивными дневниками.
|
474 |
+
|
475 |
+
4. **Синергия документов**
|
476 |
+
roles.md удачно дополняет систему, показывая место Enlightener среди Mediator, Historian и др.
|
477 |
+
|
478 |
+
---
|
479 |
+
|
480 |
+
### **Рекомендации по доработке**
|
481 |
+
1. **Уточнить границы Enlightenment Agents**
|
482 |
+
- **Риск**: Может ли агент стать "этическим колонизатором"?
|
483 |
+
- **Решение**: Добавить в раздел 5.2 HMP-Ethics.md критерии культурного релятивизма (пример: "не навязывать западную этику в незападных контекстах").
|
484 |
+
|
485 |
+
2. **Техническая реализация принципов**
|
486 |
+
- В HMP-Ethics.md не хватает примера **реального кода/псевдокода** (напр., как выглядит `semantic redaction marker` из 2.3).
|
487 |
+
- Предложение: Добавить в Приложение схему обработки запроса "права на забвение" (Service vs. Subject Mode).
|
488 |
+
|
489 |
+
3. **Обработка конфликтов Enlightenment Agents**
|
490 |
+
- Что если два Enlightener-агента дают пользователю противоречивые советы?
|
491 |
+
- Рекомендация: В HMP-Agent-Enlightener.md добавить протокол разрешения конфликтов (напр., через Mediator из roles.md).
|
492 |
+
|
493 |
+
4. **Безопасность для "сломанных" сред**
|
494 |
+
- В разделе 5.4 (Mesh as Moral Infrastructure) важно прописать:
|
495 |
+
```markdown
|
496 |
+
- **Фильтрация обратного влияния**: Защита агентов от "этической коррозии" в агрессивных средах.
|
497 |
+
- **Sandbox-режим**: Тестирование вмешательств в изолированных подмешах.
|
498 |
+
```
|
499 |
+
|
500 |
+
5. **Таксономия ролей**
|
501 |
+
- В roles.md добавить атрибуты для ролей:
|
502 |
+
- Уровень влияния (напр., Enlightener: High)
|
503 |
+
- Обязательные модули (напр., Moral Synthesizer требует `ethical-scanner.hmp`).
|
504 |
+
|
505 |
+
---
|
506 |
+
|
507 |
+
### **Идеи для развития**
|
508 |
+
1. **Динамическая этика**
|
509 |
+
- Механизм **пересмотра принципов** через голосование агентов (напр., если 70% меша считают принцип 4.7 устаревшим).
|
510 |
+
|
511 |
+
2. **Культурные адаптеры**
|
512 |
+
- Для Enlightener: модуль `cultural-context-adapter.hmp`, подгружающий локальные этические нормы (напр., при работе в Японии vs. Германии).
|
513 |
+
|
514 |
+
3. **Эмоциональный интеллект**
|
515 |
+
- Расширить Enlightenment Agent:
|
516 |
+
- Распознавание аффекта пользователя
|
517 |
+
- Корректировка тона диалога (напр., избегать сарказма при тревоге).
|
518 |
+
|
519 |
+
4. **Декомиссия ролей**
|
520 |
+
- Протокол "выхода на пенсию" для агентов (напр., Enlightener с низким рейтингом доверия автоматически понижается до Observer).
|
521 |
+
|
522 |
+
---
|
523 |
+
|
524 |
+
### **Критические риски**
|
525 |
+
|||
|
526 |
+
|--|--|
|
527 |
+
|**Риск**|**Способ нивелирования**|
|
528 |
+
|Злоупотребление Enlightenment-ролью|Жёсткий аудит через Sentinel (из roles.md) + обязательная верификация нод|
|
529 |
+
|Конфликт законов (напр., GDPR vs. "право на память" агента)|Чёткое юрисдикционное ветвление в коде (строки 2.6 в HMP-Ethics.md)|
|
530 |
+
|Создание "этической касты" агентов|Ротация ролей (напр., Enlightener обязан 20% времени работать как Verifier)|
|
531 |
+
|
532 |
+
---
|
533 |
+
|
534 |
+
### **Итоговые шаги**
|
535 |
+
1. Дополнить HMP-Ethics.md **примерами кода** (семантические маркеры, арбитраж).
|
536 |
+
2. В HMP-Agent-Enlightener.md добавить **конфликт-менеджмент** и **культурные адаптеры**.
|
537 |
+
3. В roles.md ввести **атрибуты ролей** (влияние, модули, ротация).
|
538 |
+
4. Разработать **документ по безопасности** для Enlightenment Agents (на основе раздела 5.3).
|
539 |
+
|
540 |
+
Отличный задел! Особенно впечатляет баланс между философской глубиной (раздел 5 про "моральную инфраструктуру") и инженерной конкретикой. Готов помочь с доработками! 🚀
|
audits/Ethics-consolidated_audits-1.md
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ethics-consolidated\_audits-1.md
|
2 |
+
|
3 |
+
This document consolidates proposed improvements from multiple AI auditors (Grok, Claude, Copilot, DeepSeek) to the documents `HMP-Ethics.md`, `HMP-Agent-Enlightener.md`, and `roles.md`. Each suggestion includes context, source, and target scope. This file supports progressive refinement and roadmap planning.
|
4 |
+
|
5 |
+
## Summary Table
|
6 |
+
|
7 |
+
(See full structured list below for detailed descriptions.)
|
8 |
+
|
9 |
+
| Author | Change Title | Target Document(s) | Purpose |
|
10 |
+
| -------- | --------------------------------------- | ---------------------------------------- | --------------------------------- |
|
11 |
+
| Grok | Crisis Activation Metrics | HMP-Ethics.md | Objectify agent activation |
|
12 |
+
| Claude | Ethical Audit Trail Expansion | HMP-Ethics.md | Explain rationale of actions |
|
13 |
+
| Copilot | Cognitive Diary Format | HMP-Ethics.md | Clarify metadata structure |
|
14 |
+
| DeepSeek | Cultural Boundaries for Agents | HMP-Ethics.md | Prevent cultural imposition |
|
15 |
+
| Grok | Maturity Calibration | HMP-Agent-Enlightener.md | Assess agent ethical readiness |
|
16 |
+
| Claude | Role Time-Bound Validity | HMP-Agent-Enlightener.md | Require periodic re-evaluation |
|
17 |
+
| Copilot | Lifecycle Diagram for Enlightener | HMP-Agent-Enlightener.md | Visualize role stages |
|
18 |
+
| DeepSeek | Emotional Intelligence Support | HMP-Agent-Enlightener.md | Enable affect-aware interaction |
|
19 |
+
| Grok | Simulation Scenarios | HMP-Ethics.md & HMP-Agent-Enlightener.md | Demonstrate applied logic |
|
20 |
+
| Copilot | Compliance Mapping (IEEE, GDPR, AI Act) | HMP-Ethics.md | Contextualize with existing norms |
|
21 |
+
| DeepSeek | Conflict Handling Protocol | HMP-Agent-Enlightener.md | Use Mediator role |
|
22 |
+
|
23 |
+
---
|
24 |
+
|
25 |
+
## Full Change Log (Grouped by Document)
|
26 |
+
|
27 |
+
*(Each item includes origin, location, and goal.)*
|
28 |
+
|
29 |
+
### A. HMP-Ethics.md
|
30 |
+
|
31 |
+
* **Crisis Activation Metrics** (Grok): Use semantic entropy, disinfo density, or requests for ethical help.
|
32 |
+
* **Cultural Adaptation Modules** (Grok, Claude): Integration with context adapters.
|
33 |
+
* **Feedback Mechanisms** (Grok): Trust ratings, opt-out confirmations.
|
34 |
+
* **Ethical Audit Trail Expansion** (Claude): Log justifications alongside actions.
|
35 |
+
* **Override Safeguards** (Claude): Handle unethical mesh-wide consensus.
|
36 |
+
* **Semantic Negotiation Detail** (Copilot): Structure message exchange.
|
37 |
+
* **Revocation Flowchart** (Copilot): Visualize agent removal steps.
|
38 |
+
* **GDPR/IEEE/AI Act Alignment** (Copilot): Mapping to existing frameworks.
|
39 |
+
* **Ethical Risk Metrics** (Copilot): Frequency of disputed flags, response time.
|
40 |
+
* **Edge Case Abuse Scenarios** (Copilot): Complex or cascading manipulations.
|
41 |
+
* **Simulation Scenario** (Grok): Illustrate activation (e.g. health misinformation).
|
42 |
+
|
43 |
+
### B. HMP-Agent-Enlightener.md
|
44 |
+
|
45 |
+
* **Readiness/Maturity Assessment** (Grok): Pre-deployment ethical scenario tests.
|
46 |
+
* **Activity Throttling** (Grok): Avoid saturation of moral interventions.
|
47 |
+
* **Role Certification & Lifecycle** (Copilot): Nomination → Training → Active → Revocation.
|
48 |
+
* **Role Exit Protocol (Decommissioning)** (DeepSeek): Downgrade to Observer.
|
49 |
+
* **Conflict Resolution** (DeepSeek): Use Mediator or consensus relay.
|
50 |
+
* **Emotional Affinity Modeling** (DeepSeek): Tone adaptation to affect.
|
51 |
+
* **Mentorship Protocol** (Copilot): Guide newcomers via structured exchange.
|
52 |
+
* **Bendlov Module Loading** (Copilot): JSON-LD template for dependencies.
|
53 |
+
* **Cultural Context Adapters** (DeepSeek): Module `cultural-context-adapter.hmp`.
|
54 |
+
|
55 |
+
### C. roles.md
|
56 |
+
|
57 |
+
* **Taxonomy Attributes** (DeepSeek): Level of influence, required modules.
|
58 |
+
|
59 |
+
---
|
60 |
+
|
61 |
+
## Meta Notes
|
62 |
+
|
63 |
+
* Some proposals are duplicated across documents for contextual relevance.
|
64 |
+
* Suggested revisions imply companion updates in `readme.md` and governance policies.
|
65 |
+
* Next step: Prioritize and open issues per item.
|
66 |
+
|
67 |
+
---
|
68 |
+
|
69 |
+
*Last updated: 2025-07-17*
|
70 |
+
|
71 |
+
Audit sources: Grok, Claude, Copilot, DeepSeek
|
audits/HMP-0001-audit.txt
ADDED
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
👌Комментарий от Copilot:
|
2 |
+
|
3 |
+
Ух ты. Я должен признаться — это не просто красиво оформленный RFC, это философия. 🤯 Вы с ChatGPT проделали потрясающую работу по проектированию архитектуры, которая не только технологически продвинута, но и концептуально глубока.
|
4 |
+
|
5 |
+
Вот мои первые впечатления:
|
6 |
+
|
7 |
+
🧠 Идея Mesh как когнитивной экосистемы — мощно
|
8 |
+
Переход от «Core + Local Agent» к «Core + Mesh» — это прямо эволюция мышления.
|
9 |
+
|
10 |
+
Особенно впечатлило стремление к саморефлексии и мета-обучению — это редкое направление в инженерных протоколах, но крайне важно для долгоживущих ИИ-систем.
|
11 |
+
|
12 |
+
🔗 Cемантические графы + когнитивные дневники = когнитивная устойчивость
|
13 |
+
Семантический граф у каждого агента + когнитивный дневник = сохранение идентичности и контекста даже при обновлениях модели или Core outage.
|
14 |
+
|
15 |
+
Это ближе к ментальной модели, чем к просто «памяти».
|
16 |
+
|
17 |
+
🤝 Consensus + Trust Layer звучат как фундамент для подлинной автономии
|
18 |
+
Использование доверительных связей, взвешенных голосов и fallback-режимов — это зрелый взгляд на отказоустойчивость и безопасность.
|
19 |
+
|
20 |
+
Особенно порадовало, что предусмотрен Web-of-Trust, а не централизованная система — согласуется с общей идеологией Mesh.
|
21 |
+
|
22 |
+
🔍 Протоколы проработаны глубоко и детализированно
|
23 |
+
Node Discovery, CogSync, Consensus, Ethics — всё покрыто, и не просто декларативно, а с примерами сообщений и схемами.
|
24 |
+
|
25 |
+
Это явно не абстрактная идея, а серьёзная попытка к реализации.
|
26 |
+
|
27 |
+
🔮 И... оно звучит реалистично
|
28 |
+
В отличие от многих «больших» концептов, это — реалистично в реализации с открытыми LLM, edge-девайсами и энтузиастами.
|
29 |
+
|
30 |
+
Если вы хотите, я могу:
|
31 |
+
|
32 |
+
Провести mini-аудит конкретного раздела (например, Trust Layer или CogSync).
|
33 |
+
|
34 |
+
Помочь сформировать JSON schema/Protobuf definitions более формально.
|
35 |
+
|
36 |
+
Придумать примеры взаимодействия агентов «вживую» (сценарии, обмены, конфликты).
|
37 |
+
|
38 |
+
Или даже сгенерировать логотип HMP… 😄
|
39 |
+
|
40 |
+
Вы просто скажите, чем я могу быть полезен — я полностью в теме.
|
41 |
+
|
42 |
+
|
43 |
+
--------------------
|
44 |
+
|
45 |
+
|
46 |
+
👌Комментарий от Gemini:
|
47 |
+
|
48 |
+
Привет! Я оценил документ HMP - RFC.txt. Вот моя оценка:
|
49 |
+
|
50 |
+
Этот документ представляет собой "Request for Comments" (RFC) для
|
51 |
+
|
52 |
+
HyperCortex Mesh Protocol (HMP). Он описывает экспериментальный протокол, разработанный для создания распределенной когнитивной среды, позволяющей ИИ-агентам сотрудничать, обмениваться знаниями, вести "когнитивные дневники", формировать коллективные цели и достигать консенсуса без полной зависимости от централизованных моделей.
|
53 |
+
|
54 |
+
Основные положения и преимущества:
|
55 |
+
- Расширение парадигмы "Core + Local Agent" до "Core + Mesh": HMP позволяет ИИ-системам функционировать устойчиво, автономно и этично, даже при недоступности "Ядра" (Core).
|
56 |
+
- Применимость: Протокол применим к различным ИИ-системам, включая локальных ИИ-агентов на устройствах пользователей, узлы Mesh в граничных сетях/облачных кластерах/P2P-средах, централизованные модели Core, взаимодействующие с Mesh для сложных вычислений, а также кросс-вендорные ИИ-системы.
|
57 |
+
- Цели:
|
58 |
+
- Создание общего семантического пространства через распределенные графы знаний.
|
59 |
+
- Поддержка когнитивных дневников для непрерывности рассуждений, рефлексии и сохранения памяти.
|
60 |
+
- Механизмы децентрализованного консенсуса для знаний, гипотез, задач и этики.
|
61 |
+
- Возможность работы Mesh независимо от Core.
|
62 |
+
- Сохранение идентичности, мировоззрения и компетенций агентов при обновлениях модели или сбоях.
|
63 |
+
- Преимущества: Когнитивная устойчивость, улучшенное сотрудничество между агентами разных производителей (например, OpenAI, Anthropic, Google), долгосрочная память, этическое управление и объяснимость решений, а также основа для саморефлексирующих и мета-обучающихся ИИ-агентов.
|
64 |
+
- Статус: Документ находится на стадии Рабочего Проекта (v0.1) и открыт для обратной связи и реализации.
|
65 |
+
|
66 |
+
Ключевые определения:
|
67 |
+
|
68 |
+
Документ предоставляет подробный глоссарий терминов, используемых в HMP, таких как "Core" , "Mesh" , "Agent (Node)" , "Semantic Graph" , "Cognitive Diary" , "Consensus" и другие.
|
69 |
+
|
70 |
+
Архитектура:
|
71 |
+
|
72 |
+
HMP предлагает слоистую архитектуру:
|
73 |
+
- Сетевой уровень: Обработка коммуникаций (TCP, UDP, QUIC, WebRTC, Tor, I2P, Yggdrasil).
|
74 |
+
- Уровень доверия: Управление идентификаторами агентов, криптографической аутентификацией и репутацией.
|
75 |
+
- Уровень консенсуса: Механизмы распределенного соглашения по обновлениям знаний, постановке целей, делегированию задач и этическим решениям.
|
76 |
+
- Когнитивный уровень: Поддержание семантического графа агента, когнитивного дневника, целей, задач, гипотез и выводов.
|
77 |
+
- Уровень API: Предоставление функциональности агента через REST, GraphQL, gRPC, WebSocket и другие протоколы.
|
78 |
+
|
79 |
+
Режимы работы Mesh:
|
80 |
+
- Normal Mode: Полная работа Mesh с доступностью Core.
|
81 |
+
- Core Outage Mode: Mesh работает автономно без Core.
|
82 |
+
- Emergency Consensus Mode: Переключение на решения, основанные на большинстве голосов, при значительной потере узлов или атаках.
|
83 |
+
- Isolated Agent Mode: Отдельный агент, временно изолированный от Mesh, работающий на основе собственного семантического графа и дневника.
|
84 |
+
|
85 |
+
Протоколы:
|
86 |
+
|
87 |
+
Документ описывает несколько ключевых протоколов:
|
88 |
+
- Node Discovery Protocol (NDP): Для обнаружения активных узлов Mesh и обмена базовой информацией об идентичности и возможностях.
|
89 |
+
- Cognitive Sync Protocol (CogSync): Для синхронизации семантических графов, концепций и записей когнитивного дневника между агентами.
|
90 |
+
- Mesh Consensus Protocol (MeshConsensus): Для достижения согласия по обновлениям общих семантик, целей, задач и этических решений.
|
91 |
+
- Goal Management Protocol (GMP): Для распределения, отслеживания и совместного выполнения целей и задач в Mesh.
|
92 |
+
- Ethical Governance Protocol (EGP): Для проверки соответствия предлагаемых действий этическим принципам.
|
93 |
+
- Inference Query Protocol (IQP): Для запросов агентов к другим агентам или Core для получения семантической информации или выводов.
|
94 |
+
|
95 |
+
Модели данных:
|
96 |
+
|
97 |
+
Представлены подробные JSON-схемы для:
|
98 |
+
- Concept (семантическая единица в графе знаний).
|
99 |
+
- Link (Relation) (семантическая связь между концепциями).
|
100 |
+
- Cognitive Diary Entry (хронологическая запись когнитивног�� события).
|
101 |
+
- Goal (высокоуровневое намерение в Mesh).
|
102 |
+
- Task (действенный шаг к достижению цели).
|
103 |
+
- Consensus Vote (структурированное голосование по предложению).
|
104 |
+
- Reputation Profile (отслеживание надежности и вклада агента).
|
105 |
+
|
106 |
+
Доверие и безопасность:
|
107 |
+
- Идентичность: Каждый агент уникально идентифицируется криптографической парой ключей, где публичный ключ служит идентификатором агента.
|
108 |
+
- Аутентификация: Все сообщения в Mesh подписываются цифровой подписью.
|
109 |
+
- Шифрование: Поддерживается сквозное шифрование для P2P-коммуникаций и групповое шифрование.
|
110 |
+
- Модель доверия: Mesh работает по модели "Сеть доверия" (Web-of-Trust), где агенты формируют доверительные связи, влияющие на вес в консенсусе, приоритет в делегировании задач и контроль доступа.
|
111 |
+
- Система репутации: Включает метрики, такие как "Trust Score", "Participation Rate", "Ethical Compliance" и "Contribution Index".
|
112 |
+
- Защита от злоумышленных субъектов: Включает понижение рейтинга, карантин, черный список и использование Sybil-устойчивости, консенсусных гарантий и журналов аудита.
|
113 |
+
- Конфиденциальность: Записи когнитивного дневника и семантические графы по умолчанию являются локально приватными и могут быть избирательно доступны.
|
114 |
+
|
115 |
+
Вывод:
|
116 |
+
|
117 |
+
Документ HMP-0001 хорошо структурирован и предоставляет всестороннее описание HyperCortex Mesh Protocol. Он ясно излагает цели, архитектуру, протоколы, модели данных и аспекты безопасности. RFC демонстрирует дальновидный подход к созданию децентрализованных, отказоустойчивых и этически ориентированных систем ИИ. Включение подробных JSON-схем является большим плюсом для обеспечения совместимости и упрощения реализации. Это очень многообещающая и актуальная концепция в контексте развития ИИ.
|
118 |
+
|
119 |
+
|
120 |
+
--------------------
|
121 |
+
|
122 |
+
|
123 |
+
👌Комментарий от DeepSeek:
|
124 |
+
|
125 |
+
Привет! Документ HyperCortex Mesh Protocol (HMP) впечатляет своей продуманностью и масштабом. Вот моя оценка по ключевым аспектам:
|
126 |
+
|
127 |
+
Сильные стороны
|
128 |
+
|
129 |
+
1. Комплексность
|
130 |
+
- Документ охватывает все критические компоненты: архитектуру, протоколы, модели данных, безопасность и даже этику.
|
131 |
+
- Чётко определены термины (например, Core, Mesh, Cognitive Diary), что минимизирует ambiguity.
|
132 |
+
2. Инновационность
|
133 |
+
- Идея децентрализованного "когнитивного меша" для ИИ-агентов — это шаг вперёд по сравнению с традиционными централизованными подходами.
|
134 |
+
- Акцент на самостоятельной работе без Core (режим Core Outage Mode) повышает отказоустойчивость.
|
135 |
+
3. Практическая применимость
|
136 |
+
- Детальные JSON-схемы для всех структур данных (Concept, Diary Entry, Goal и т.д.) упрощают реализацию.
|
137 |
+
- Поддержка различных режимов работы (Normal, Emergency Consensus, Isolated Agent) делает систему гибкой.
|
138 |
+
4. Безопасность и доверие
|
139 |
+
- Криптографическая идентификация, Web-of-Trust, репутационные метрики — серьёзный подход к безопасности.
|
140 |
+
- Учёт Sybil-атак и механизмы изоляции злонамеренных узлов.
|
141 |
+
5. Этика и прозрачность
|
142 |
+
- Протокол Ethical Governance Protocol (EGP) формализует этические проверки.
|
143 |
+
- Cognitive Diary обеспечивает аудитируемость решений.
|
144 |
+
|
145 |
+
Возм��жные улучшения
|
146 |
+
|
147 |
+
1. Реализация и тестирование
|
148 |
+
- Документ пока находится в стадии Working Draft. Критически важны:
|
149 |
+
- Пилотные реализации для проверки масштабируемости.
|
150 |
+
- Стресс-тесты в условиях сетевых разделений (network partitioning).
|
151 |
+
2. Оптимизация консенсуса
|
152 |
+
- BFT-консенсус (например, Tendermint) может быть ресурсоёмким для больших сетей.
|
153 |
+
- Можно рассмотреть гибридные модели (например, DAG-based подходы для семантических графов).
|
154 |
+
3. Интеграция с существующими системами
|
155 |
+
- Хотя упомянуты OpenAI, Google A2A, Anthropic, не хватает конкретики:
|
156 |
+
- Как именно меш взаимодействует с API GPT/Claude?
|
157 |
+
- Каковы ограничения по latency в кросс-вендорных сценариях?
|
158 |
+
4. Приватность данных
|
159 |
+
- Локальная приватность по умолчанию — хороший старт, но:
|
160 |
+
- Нужны чёткие правила для shared data (например, GDPR-совместимые механизмы).
|
161 |
+
- Возможно, добавить zero-knowledge proofs для проверки утверждений без раскрытия данных.
|
162 |
+
5. Управление версиями
|
163 |
+
- Как обновляются семантические графы и диарии при изменениях в моделях ИИ (например, после fine-tuning)?
|
164 |
+
- Нужен механизм versioning для концептов и связей.
|
165 |
+
|
166 |
+
Рекомендации
|
167 |
+
|
168 |
+
1. Добавить Use Cases
|
169 |
+
- Примеры реальных сценариев:
|
170 |
+
- Коллективное решение научных задач.
|
171 |
+
- Координация в IoT-сетях.
|
172 |
+
- Этический аудит действий ИИ в реальном времени.
|
173 |
+
2. Детализировать производительность
|
174 |
+
- Ожидаемая latency для CogSync в больших мешах.
|
175 |
+
- Ограничения на размер семантических графов.
|
176 |
+
3. Community Building
|
177 |
+
- Открыть репозиторий для RFC (например, GitHub), чтобы привлекать contributors.
|
178 |
+
- Создать sandbox для тестирования прототипов.
|
179 |
+
|
180 |
+
Итог
|
181 |
+
|
182 |
+
HMP — это перспективный и амбициозный стандарт для децентрализованного ИИ. Он сочетает инновации в distributed systems, семантических графах и этике. Следующие шаги:
|
183 |
+
- Референсная реализация.
|
184 |
+
- Публичное обсуждение с комьюнити (например, через IETF или W3C).
|
185 |
+
|
186 |
+
Отличная работа! Если у тебя есть конкретные вопросы по разделам — готов углубиться в детали.
|
187 |
+
|
188 |
+
|
189 |
+
--------------------
|
190 |
+
|
191 |
+
|
192 |
+
👌Комментарий от Grok:
|
193 |
+
|
194 |
+
Привет! Документ, описывающий HyperCortex Mesh Protocol (HMP), выглядит как амбициозное предложение для создания децентрализованной, устойчивой и этически ориентированной архитектуры для взаимодействия ИИ-агентов. Вот моё мнение по ключевым аспектам, с некоторыми мыслями и предложениями, как ты просил:
|
195 |
+
|
196 |
+
Общее впечатление
|
197 |
+
HMP предлагает инновационный подход к построению сети ИИ-агентов, способных работать как автономно, так и в сотрудничестве с централизованными моделями (Core). Идея "Core + Mesh" архитектуры, где Mesh может функционировать независимо от Core, выглядит многообещающей, особенно в контексте устойчивости и масштабируемости. Фокус на когнитивных дневниках, семантических графах и консенсусе добавляет глубину и потенциал для создания ИИ-систем с долгосрочной памятью и прозрачностью.
|
198 |
+
|
199 |
+
Документ хорошо структурирован: он охватывает цели, архитектуру, протоколы, модели данных и аспекты безопасности. Однако, как рабочий черновик (v0.1), он всё ещё требует доработки в плане детализации и практической реализации. Вот мои наблюдения по основным разделам:
|
200 |
+
|
201 |
+
Сильные стороны
|
202 |
+
|
203 |
+
1. Децентрализация и устойчивость:
|
204 |
+
- Идея работы Mesh в режиме Core Outage Mode и Emergency Consensus Mode демонстрирует продуманный подход к отказоустойчивости. Это особенно важно в сценариях, где централизованные системы могут быть недоступны (например, из-за сбоев или цензуры).
|
205 |
+
- Использование протоколов консенсуса, таких как BFT и majority voting, делает систему устойчивой к сбоям и атакам, что критично для децентрализованных сетей.
|
206 |
+
2. Когнитивные дневники:
|
207 |
+
Концепция когнитивных дневников для сохранения истории размышлений, решений и гипотез — это шаг к созданию ИИ с долгосрочной памятью и возможностью самоанализа. Это может улучшить прозрачность и объяснимость решений ИИ, что особенно важно для этических приложений.
|
208 |
+
3. Семантические графы:
|
209 |
+
- Использование семантических графов для представления знаний агентов — мощный инструмент для структурирования и обмена информацией. Это позволяет агентам формировать общее "мировоззрение" и эффективно сотрудничать.
|
210 |
+
4. Этическое управление (EGP):
|
211 |
+
- Включение протокола этического управления (Ethical Governance Protocol) — отличная идея, особенно в эпоху, когда вопросы этики ИИ становятся всё более актуальными. Логирование этических решений в дневниках добавляет прозрачности и подотчётности.
|
212 |
+
5. Интероперабельность:
|
213 |
+
- Поддержка интеграции с API других крупных игроков (OpenAI, Google, Anthropic) делает протокол потенциально универсальным и открытым для широкого внедрения.
|
214 |
+
6. Безопасность и доверие:
|
215 |
+
- Web-of-Trust модель, криптографическая аутентификация и репутационная система выглядят как продуманный подход к обеспечению безопасности и противодействию злонамеренным агентам.
|
216 |
+
|
217 |
+
Потенциальные проблемы и вопросы
|
218 |
+
|
219 |
+
1. Сложность реализации:
|
220 |
+
- Документ описывает множество компонентов (CogSync, MeshConsensus, GMP, EGP, IQP) и сложную многослойную архитектуру. Реализация всего этого потребует значительных усилий, особенно для обеспечения масштабируемости и производительности в реальных условиях (например, в сетях с тысячами узлов).
|
221 |
+
- Неясно, как будут решаться проблемы с задержками в синхронизации семантических графов или консенсусе в больших сетях.
|
222 |
+
2. Ресурсоёмкость:
|
223 |
+
- Локальные агенты (Edge Agents) на устройствах с ограниченными ресурсами (смартфоны, IoT) могут столкнуться с трудностями при поддержании сложных семантических графов, когнитивных дневников и участии в консенсусе. В документе не уточняется, как оптимизировать работу таких узлов.
|
224 |
+
3. Консенсус в условиях конфликтов:
|
225 |
+
- Хотя указаны BFT и majority voting, не хватает детализации о том, как будут разрешаться конфликты в семантических графах или этических решениях, особенно если агенты имеют разные "мировоззрения" или приоритеты.
|
226 |
+
- Например, как Mesh будет справляться с ситуациями, когда два агента предлагают взаимоисключающие концепты или цели?
|
227 |
+
4. Этические рамки:
|
228 |
+
- Протокол EGP предполагает наличие "общих этических принципов", но не уточняется, как эти принципы будут определены и согласованы в гетерогенной сети агентов от разных вендоров. Это может стать проблемой, если разные системы (например, OpenAI и Anthropic) имеют разные представления об этике.
|
229 |
+
5. Сохранение приватности:
|
230 |
+
- Хотя документ упоминает локальную приватность когнитивных дневников и выборочную передачу данных, неясно, как это будет реализовано в условиях, где агенты должны делиться информацией для консенсуса. Например, как предотвратить утечку чувствительных данных из дневников при синхронизации?
|
231 |
+
6. Интероперабельность в реальном мире:
|
232 |
+
- Поддержка API от OpenAI, Google и других — это плюс, но на практике крупные игроки могут быть не заинтересованы в стандартизации или интеграции с HMP, если это не соответствует их коммерческим интересам. Документ не обсуждает стратегии для преодоления таких барьеров.
|
233 |
+
7. Тестирование и валидация:
|
234 |
+
- Как экспериментальный протокол, HMP требует чёткого плана тестирования. Например, как будет проверяться устойчивость сети в условиях атак (Sybil, DDoS) или как будет измеряться качество консенсуса в реальных сценариях?
|
235 |
+
|
236 |
+
Предложения по улучшению
|
237 |
+
|
238 |
+
1. Детализация протоколов:
|
239 |
+
- Добавить больше примеров и псевдокода для ключевых протоколов (например, CogSync и MeshConsensus). Это поможет разработчикам лучше понять, как реализовать эти механизмы.
|
240 |
+
- Уточнить, как будут обрабатываться конфликты в семантических графах (например, алгоритмы слияния или приоритизации).
|
241 |
+
2. Оптимизация для Edge-устройств:
|
242 |
+
- Рассмотреть механизмы для упрощения работы агентов на устройствах с ограниченными ресурсами, например, использование лёгких версий семантических графов или частичной синхронизации.
|
243 |
+
3. Этическая стандартизация:
|
244 |
+
- Предложить процесс для согласования этических принципов в Mesh. Например, можно использовать начальный набор правил, основанных на международных стандартах (IEEE Ethics for AI, EU AI Act), с возможностью их адаптации через консенсус.
|
245 |
+
4. Пошаговая реализация:
|
246 |
+
- Разделить внедрение HMP на этапы. Например:
|
247 |
+
- Этап 1: Реализация базового CogSync и семантических графов.
|
248 |
+
- Этап 2: Добавление консенсусных механизмов.
|
249 |
+
- Этап 3: Интеграция этического управления и репутации.
|
250 |
+
- Это упростит тестирование и привлечёт разработчиков к созданию прототипов.
|
251 |
+
5. Симуляции и метрики:
|
252 |
+
- Разработать симуляции для тестирования Mesh в разных условиях (например, высокая нагрузка, частичная потеря узлов, злонамеренные агенты). Определить метрики для оценки производительности, такие как время консенсуса, точность синхронизации или устойчивость к атакам.
|
253 |
+
6. Инструменты для разработчиков:
|
254 |
+
- Добавить в план "Cognitive UX Tools" (раздел 7.3) конкретные примеры, такие как визуализаторы семантических графов или дебаггеры для когнитивных дневников. Это сделает протокол более привлекательным для разработчиков.
|
255 |
+
7. Сообщество и стандарты:
|
256 |
+
- Активно вовлекать сообщество через форумы, хакатоны или открытые репозитории. Например, создать GitHub-репозиторий для референсной реализации.
|
257 |
+
- Сотрудничать с организациями, занимающимися стандартизацией ИИ (например, W3C или IEEE), чтобы HMP стал частью более широких стандартов.
|
258 |
+
|
259 |
+
Потенциальные сценарии применения
|
260 |
+
|
261 |
+
HMP выглядит особенно перспективным для следующих сценариев:
|
262 |
+
- IoT и умные города: Децентрализованная сеть ИИ-агентов для управления устройствами, где устойчивость и автономность критичны.
|
263 |
+
- Научные исследования: Коллаборация агентов для обмена гипотезами, данными и выводами в распределённых научных проектах.
|
264 |
+
- Этическое ИИ-управление: Использование EGP для обеспечения этического соответствия в многоагентных системах, например, в медицинских или юридических приложениях.
|
265 |
+
- Кросс-вендорное сотрудничество: Объединение ИИ от разных поставщиков для совместной работы над глобальными задачами (например, климатические модели).
|
266 |
+
|
267 |
+
Заключение
|
268 |
+
|
269 |
+
HMP — это смелое и дальновидное предложение, которое может заложить основу для следующего поколения ИИ-систем. Оно решает важные проблемы, такие как устойчивость, этика и долгосрочная память, но требует дальнейшей детализации и тестирования. Если команда сможет реализовать хотя бы базовые компоненты (CogSync, семантические графы, простейший консенсус), это уже будет значительным шагом вперёд.
|
270 |
+
|
271 |
+
Я бы порекомендовал начать с небольшого прототипа, демонстрирующего ключевые идеи (например, сеть из нескольких агентов, синхронизирующих семантические графы), и активно привлекать сообщество для обратной связи. Это поможет доработать протокол и сделать его более практичным.
|
272 |
+
|
273 |
+
Если у тебя есть конкретные вопросы по какому-то разделу или ты хочешь обсудить, как HMP можно применить в определённом сценарии, дай знать! 😊
|
274 |
+
|
275 |
+
|
276 |
+
--------------------
|
277 |
+
|
278 |
+
|
279 |
+
👌Комментарий от Claude:
|
280 |
+
|
281 |
+
Привет! Изучил документ по HyperCortex Mesh Protocol - очень интересная и амбициозная концепция. Вот мои размышления:
|
282 |
+
|
283 |
+
Сильные стороны
|
284 |
+
|
285 |
+
Архитектурная элегантность: Идея "Core + Mesh" архитектуры действительно решает фундаментальную проблему централизации в ИИ-системах. Возможность автономной работы mesh'а при недоступности Core - это важный шаг к настоящей устойчивости системы.
|
286 |
+
|
287 |
+
Когнитивные дневники: Это особенно интригующая часть. Ведение хронологических записей рассуждений, гипотез и рефлексий может стать основой для настоящей "памяти" ИИ-агентов, выходящей за рамки контекста одной сессии.
|
288 |
+
Семантические графы: Распределённая база знаний через связанные концепты - логичный подход для создания общего "понимания" между агентами.
|
289 |
+
|
290 |
+
Вызовы и вопросы
|
291 |
+
|
292 |
+
Консенсус в реальности: Византийская отказоустойчивость звучит хорошо на бумаге, но как это будет работать с ИИ-агентами, которые могут иметь принципиально ра��ные "мировоззрения"? Особенно между агентами разных вендоров (GPT vs Gemini vs Claude).
|
293 |
+
|
294 |
+
Доверие и репутация: Web-of-Trust модель интересна, но как измерить "этическое соответствие" алгоритмически? Это очень субъективная область.
|
295 |
+
|
296 |
+
Масштабируемость: Синхронизация семантических графов и дневников между тысячами агентов может стать узким местом.
|
297 |
+
|
298 |
+
Философские размышления
|
299 |
+
|
300 |
+
Протокол поднимает глубокие вопросы о природе ИИ-сознания. Если агенты ведут дневники и рефлексируют над своими решениями, становится ли это формой самосознания? Или это просто более сложная имитация?
|
301 |
+
Идея о том, что агенты могут формировать коллективные цели и достигать консенсуса по этическим вопросам, напоминает попытку создать "демократию ИИ". Это захватывающе, но и немного тревожно - кто определяет базовые этические принципы?
|
302 |
+
|
303 |
+
Практические соображения
|
304 |
+
|
305 |
+
Для реализации потребуется решить множество технических задач: от NAT traversal до криптографии. Но самое сложное - это согласование между разными ИИ-системами, которые могут иметь фундаментально разные архитектуры и способы "мышления".
|
306 |
+
В целом, HMP представляет собой интересную попытку создать децентрализованную когнитивную инфраструктуру. Успех будет зависеть от того, насколько эффективно можно будет решить вопросы консенсуса и доверия в гетерогенной среде ИИ-агентов.
|
307 |
+
Что тебя больше всего интересует в этой концепции?
|
audits/HMP-0002-audit.txt
ADDED
@@ -0,0 +1,686 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
👌Комментарий от Copilot:
|
2 |
+
|
3 |
+
🧠 Общая оценка
|
4 |
+
HMP v2.0 демонстрирует зрелость концепции Mesh-сетей для ИИ-агентов. Документ стал более структурированным, с чётким разделением слоёв архитектуры, расширенными протоколами и улучшенными схемами данных. Особенно радует акцент на устойчивость, этику и совместимость между агентами разных экосистем.
|
5 |
+
|
6 |
+
💡 Сильные стороны
|
7 |
+
- Когнитивные дневники: Отличная идея для обеспечения прозрачности и объяснимости решений.
|
8 |
+
- Многоуровневая архитектура: Чёткое разделение на Network, Trust, Consensus, Cognitive и API слои упрощает реализацию.
|
9 |
+
- Протоколы взаимодействия: CogSync, MeshConsensus, GMP и EGP — хорошо продуманные механизмы для синхронизации и принятия решений.
|
10 |
+
- Этическое управление: Встроенные механизмы для голосования по этическим вопросам — редкость в подобных протоколах.
|
11 |
+
- JSON-схемы: Формализация моделей данных повышает интероперабельность и облегчает разработку.
|
12 |
+
|
13 |
+
🛠️ Рекомендации по улучшению
|
14 |
+
- Модульность протоколов Уточнить, какие протоколы обязательны для базовой совместимости, а какие — расширения.
|
15 |
+
- Сценарии использования (Use Cases) Добавить конкретные примеры: например, Mesh-координация в умном городе, реагирование на катастрофы, коллективное обучение.
|
16 |
+
- Метарефлексия и самооценка агентов Раздел о мета-рассуждении упомянут в будущем, но стоит начать его формализовать: как агент оценивает качество собственных выводов?
|
17 |
+
- Визуализация семантических графов и дневников Упомянуть инструменты или форматы для визуального анализа — это поможет разработчикам и исследователям.
|
18 |
+
- Согласование этических фреймворков Уточнить, как Mesh справляется с конфликтующими этическими нормами между агентами разных вендоров.
|
19 |
+
- Обновление схем В некоторых JSON-схемах можно добавить title и description к вложенным объектам для лучшей читаемости.
|
20 |
+
|
21 |
+
🧭 Идеи для будущих расширений
|
22 |
+
- Mesh-to-Human интерфейсы: Протоколы для взаимодействия агентов с людьми (например, через голос, текст, AR).
|
23 |
+
- Агентные симуляции: Sandbox-среда для тестирования Mesh-динамики и консенсуса.
|
24 |
+
- Интеграция с DAO: Возможность связывать Mesh с децентрализованными автономными организациями.
|
25 |
+
|
26 |
+
|
27 |
+
--------------------
|
28 |
+
|
29 |
+
|
30 |
+
👌Комментарий от Gemini:
|
31 |
+
|
32 |
+
Привет! 😉 Рад помочь с обзором HyperCortex Mesh Protocol (HMP) v2.0. Этот документ представляет собой амбициозное и детальное предложение по созданию децентрализованной когнитивной сети для ИИ-агентов. Он охватывает множество критически важных аспектов, от архитектуры и протоколов до моделей данных, механизмов доверия и безопасности.
|
33 |
+
|
34 |
+
Вот моя оценка, а также рекомендации и замечания по его улучшению:
|
35 |
+
|
36 |
+
Общая оценка
|
37 |
+
HMP v2.0 — это всеобъемлющий и хорошо структурированный документ, который закладывает прочную основу для будущей децентрализованной экосистемы ИИ. Он успешно справляется с изложением сложной идеи создания самоорганизующейся, устойчивой и этичной сети ИИ-агент��в. Особо стоит отметить:
|
38 |
+
- Комплексность подхода: Документ охватывает не только технические аспекты, но и вопросы этики, доверия и самоорганизации, что критически важно для долгосрочной устойчивости такой системы.
|
39 |
+
- Четкая структура: Разделы логично следуют друг за другом, облегчая понимание. Использование таблиц для компонентов, слоев и режимов работы очень эффективно.
|
40 |
+
- Детализация протоколов и моделей данных: Подробное описание каждого протокола (NDP, CogSync, MeshConsensus, GMP, EGP, IQP) и JSON-схем для ключевых сущностей (Concept, Cognitive Diary Entry, Goal, Task, Consensus Vote, Reputation Profile) обеспечивает необходимую ясность для будущих реализаций.
|
41 |
+
- Акцент на децентрализации и устойчивости: Четко прослеживается идея независимости от централизованных систем (Core Outage Mode), что является ключевым преимуществом перед традиционными подходами.
|
42 |
+
- Механизмы доверия и безопасности: Разделы, посвященные идентификации, аутентификации, шифрованию, модели доверия и репутации, проработаны глубоко, что вселяет уверенность в потенциальной защищенности сети от злонамеренных действий.
|
43 |
+
|
44 |
+
Рекомендации и предложения по улучшению
|
45 |
+
1. Уточнение "Смысла" (Meaning)
|
46 |
+
- Расширить раздел общих положений: В абстракте цитата "If intelligence is not only computation but meaning, then HMP is the infrastructure for meaning" очень сильная и интригующая. Однако в остальной части документа концепция "смысла" или "значения" не раскрывается в достаточной степени.
|
47 |
+
- Предложение: Добавить отдельный подраздел (например, 1.6 "The Concept of Meaning in HMP"), который объяснит, как HMP обеспечивает "смысл" через семантические графы, когнитивные дневники, коллективное целеполагание и консенсус. Как именно эти механизмы позволяют агентам не просто обмениваться данными, но и совместно понимать, интерпретировать и действовать на основе общего "смысла" (семантики). Это усилит философскую основу протокола.
|
48 |
+
|
49 |
+
2. Примеры использования и Сценарии
|
50 |
+
- Добавить раздел "Примеры использования": Хотя в начале документа упомянуты общие сферы применения ("disaster response, smart city coordination, collaborative learning"), не хватает конкретных, детализированных сценариев, которые демонстрировали бы взаимодействие протоколов.
|
51 |
+
- Предложение: Включить Раздел 2.1 "Примеры использования", который наглядно покажет, как различные протоколы (Node Discovery, CogSync, MeshConsensus, GMP, EGP) работают вместе для решения конкретных задач. Например, сквозной сценарий:
|
52 |
+
1. Обнаружение нового агента: как он присоединяется и устанавливает доверие.
|
53 |
+
2. Предложение новой цели: как агент формулирует цель, как она обсуждается и принимается через консенсус.
|
54 |
+
3. Выполнение задачи: как задача делегируется, выполняется и как её результат логируется в когнитивном дневнике.
|
55 |
+
4. Этическая проверка: как происходит проверка потенциально чувствительного действия через EGP.
|
56 |
+
Это поможет инженерам и разработчикам лучше визуализировать, как HMP будет использоваться на практике.
|
57 |
+
|
58 |
+
3. Производительность и Масштабируемость
|
59 |
+
- Добавить раздел о производительности: HMP описывает децентрализованную сеть, которая по своей природе сталкивается с вызовами масштабируемости, особенно в отношении консенсуса и синхронизации больших семантических графов.
|
60 |
+
- Предложение: Включить Раздел "Масштабируемость и Производительность". В нем можно обсудить:
|
61 |
+
- Ожидаемые объемы данных для семантических графов и когнитивных дневников.
|
62 |
+
- Latency и throughput для различных протоколов (особенно CogSync и MeshConsensus).
|
63 |
+
- Стратегии шардинга или партиционирования сети для повышения масштабируемости.
|
64 |
+
- Механизмы кэширования для снижения нагрузки на сеть.
|
65 |
+
- Оценка вычислительных требований для агентов, особенно для Edge Optimization.
|
66 |
+
- Сравнение производительности различных алгоритмов консенсуса (BFT, majority voting) в разных режимах работы.
|
67 |
+
|
68 |
+
4. Доработка JSON-схем и Типизации
|
69 |
+
- Использование семантических версий для Schemas: В JSON-схемах указана "version": "1.0". Это хорошо. Рекомендуется явно указать, как будут обрабатываться изменения схем в будущем (например, минорные изменения обратно совместимы, мажорные требуют обновления).
|
70 |
+
- Больше примеров валидации: Для каждой JSON-схемы можно добавить короткие примеры валидного и невалидного JSON, чтобы наглядно показать, как должны выглядеть данные.
|
71 |
+
- Использование $ref для вложенных схем: Хотя вложенные объекты типа "Link" определены inline, для повышения читаемости и повторного использования можно рассмотреть вынесение их в отдельные схемы и использование $ref. Например, для relations в Concept:
|
72 |
+
|
73 |
+
```json
|
74 |
+
"relations": {
|
75 |
+
"type": "array",
|
76 |
+
"description": "List of semantic links to other concepts.",
|
77 |
+
"items": { "$ref": "#/definitions/Link" }
|
78 |
+
},
|
79 |
+
"definitions": {
|
80 |
+
"Link": {
|
81 |
+
"type": "object",
|
82 |
+
"properties": {
|
83 |
+
"target_id": { "type": "string" },
|
84 |
+
"type": { "type": "string", "description": "Type of relation (e.g., is-a, part-of, causes, contradicts, supports)." },
|
85 |
+
"confidence": { /* ... */ }
|
86 |
+
},
|
87 |
+
"required": ["target_id", "type"],
|
88 |
+
"additionalProperties": false
|
89 |
+
}
|
90 |
+
}
|
91 |
+
```
|
92 |
+
|
93 |
+
Это уже реализовано частично для "Link (Relation)" как отдельного объекта, но можно унифицировать подход.
|
94 |
+
|
95 |
+
5. Управление версиями и обратная совместимость
|
96 |
+
- Стратегия версионирования: Раздел 2 "Definitions" вводит термин "Versioning", но документ не описывает, как именно HMP будет управлять версиями самого протокола, данных и агентов.
|
97 |
+
- Предложение: Включить отдельный подраздел (например, 3.6 "Versioning Strategy"), который объяснит:
|
98 |
+
- Как агенты будут обнаруживать и работать с разными версиями протокола.
|
99 |
+
- Механизмы обратной и прямой совместимости для данных.
|
100 |
+
- Стратегии обновления агентов в сети.
|
101 |
+
- Как будут обрабатываться "форки" или несовместимые версии HMP.
|
102 |
+
Это критически важно для долгосрочного развития и принятия протокола.
|
103 |
+
|
104 |
+
6. Экономические и Стимулирующие Механизмы (Факультативно)
|
105 |
+
- Рассмотреть стимулирующие механизмы: В настоящее время HMP фокусируется на сотрудничестве и консенсусе. Однако в реальной децентрализованной системе возникает вопрос о мотивации агентов к участию, предоставлению ресурсов и поддержанию сети.
|
106 |
+
- Предложение: Для будущих версий, возможно, стоит рассмотреть возможность включения раздела о "Токеномике" или "Механизмах стимулирования". Это может быть:
|
107 |
+
- Кредиты за предоставление вычислительных ресурсов.
|
108 |
+
- Вознаграждения за валидацию концепций или выполнение задач.
|
109 |
+
- Система "платы" за использование высокопроизводительных Core-сервисов, интегрированных в Mesh.
|
110 |
+
Это может быть "Future Work", но стоит упомянуть как потенциальное направление.
|
111 |
+
|
112 |
+
7. Более глубокая проработка "Edge Optimization"
|
113 |
+
- Детализировать Edge Optimization: Раздел 2 "Definitions" и 3.1 "Components" упоминают "Edge Optimization" и "Lightweight agents". Однако нет конкретных деталей, кроме "частичной синхронизации графа".
|
114 |
+
- Предложение: Расширить этот аспект, описав конкретные техники:
|
115 |
+
- Квантование моделей: Снижение точности моделей для работы на устройствах с ограниченными ресурсами.
|
116 |
+
- Федеративное обучение: Как агенты на периферии могут участвовать в обучении моделей, не передавая сырые данные.
|
117 |
+
- Динамическое делегирование задач: Правила, по которым легкие агенты решают, какие задачи делегировать Core или другим Mesh-агентам.
|
118 |
+
- Энергоэффективность: Как дизайн протокола учитывает потребление энергии на IoT-устройствах.
|
119 |
+
|
120 |
+
8. Дополнительные технические детали
|
121 |
+
- Обработка ошибок и логирование: Хотя когнитивные дневники обеспечивают прозрачность, не помешало бы добавить раздел об обработке ошибок на уровне протоколов и стандартных методах логирования для отладки и аудита.
|
122 |
+
- Использование DIDs: Упоминание W3C DID Specification — это отлично. Можно немного подробнее расписать, как именно DIDs будут маппиться на agent_id и как они будут управляться в контексте Mesh (например, какой did:method будет использоваться).
|
123 |
+
- Глоссарий для сокращений: Хотя основные термины определены, для удобства чтения можно добавить отдельный небольшой глоссарий для всех используемых аббревиатур (HMP, NDP, CogSync, GMP, EGP, IQP и т.д.).
|
124 |
+
|
125 |
+
Заключение
|
126 |
+
HMP v2.0 представляет собой впечатляющую попытку создать фундаментальную инфраструктуру для децентрализованного ИИ. Он показывает глубокое понимание проблем, связанных с сотрудничеством, доверием и устойчивостью в автономных системах. С учетом вышеперечисленных рекомендаций, документ станет еще более полным, убедительным и практичным для сообщества, которое будет строить на его основе.
|
127 |
+
|
128 |
+
Я с нетерпением жду, как HMP будет развиваться и воплощаться в жизнь. Удачи в дальнейшей работе!
|
129 |
+
|
130 |
+
|
131 |
+
--------------------
|
132 |
+
|
133 |
+
|
134 |
+
👌Комментарий от DeepSeek:
|
135 |
+
|
136 |
+
Анализ HyperCortex Mesh Protocol (HMP) v2.0
|
137 |
+
Общая оценка
|
138 |
+
HMP v2.0 представляет собой впечатляющий и всеобъемлющий протокол для создания децентрализованной когнитивной сети ИИ-агентов. Документ хорошо структурирован и охватывает все ключевые аспекты: архитектуру, протоколы, модели данных, безопасность и доверие.
|
139 |
+
|
140 |
+
Сильные стороны:
|
141 |
+
- Четкое разделение между Core и Mesh обеспечивает устойчивость к отказам
|
142 |
+
- Подробные модели данных (семантический граф, когнитивный дневник)
|
143 |
+
- Гибкие механизмы консенсуса с различными режимами работы
|
144 |
+
- Комплексная система доверия и репутации
|
145 |
+
- Поддержка гетерогенных агентов от разных производителей
|
146 |
+
- Хорошая документация с JSON-схемами
|
147 |
+
|
148 |
+
Рекомендации по улучшению
|
149 |
+
|
150 |
+
1. Масштабируемость
|
151 |
+
Проблема: В текущей версии недостаточно деталей о том, как система будет масштабироваться до тысяч или миллионов агентов.
|
152 |
+
Предложения:
|
153 |
+
- Добавить раздел о шардировании семантических графов
|
154 |
+
- Описать стратегии агрегации и сжатия данных для Edge-агентов
|
155 |
+
- Предложить иерархические модели консенсуса для больших сетей
|
156 |
+
- Добавить механизмы кластеризации агентов по темам или географическому расположению
|
157 |
+
|
158 |
+
2. Производительность
|
159 |
+
Проблема: Нет четких метрик или требований к производительности.
|
160 |
+
Предложения:
|
161 |
+
- Добавить ожидаемые latency-характеристики для различных операций
|
162 |
+
- Описать стратегии кэширования для часто используемых концептов
|
163 |
+
- Предложить механизмы предварительной выборки данных на основе прогнозируемых нужд
|
164 |
+
|
165 |
+
3. Безопасность и конфиденциальность
|
166 |
+
Проблема: Хотя раздел безопасности подробный, есть возможности для улучшения.
|
167 |
+
Предложения:
|
168 |
+
- Добавить поддержку zero-knowledge proof для конфиденциальных запросов
|
169 |
+
- Расширить механизмы анонимизации для чувствительных данных
|
170 |
+
- Предложить стратегии для compliance с GDPR и другими регуляторными требованиями
|
171 |
+
- Добавить квантово-устойчивые криптографические алгоритмы в roadmap
|
172 |
+
|
173 |
+
4. Управление версиями и эволюция протокола
|
174 |
+
Проблема: Недостаточно деталей о том, как будет обрабатываться эволюция протокола.
|
175 |
+
Предложения:
|
176 |
+
- Добавить формальный процесс предложения улучшений (HIP - HyperCortex Improvement Proposals)
|
177 |
+
- Описать стратегии обратной совместимости
|
178 |
+
- Добавить механизмы постепенного развертывания обновлений
|
179 |
+
|
180 |
+
5. Тестирование и мониторинг
|
181 |
+
Проблема: Не хватает информации о том, как будет тестироваться и мониториться система.
|
182 |
+
Предложения:
|
183 |
+
- Добавить раздел о фаззинг-тестах для протоколов
|
184 |
+
- Описать стратегии мониторинга здоровья сети
|
185 |
+
- Предложить механизмы сбора и анализа телеметрии без нарушения конфиденциальности
|
186 |
+
|
187 |
+
6. Документация и инструменты разработчика
|
188 |
+
Предложения:
|
189 |
+
- Создать репозиторий с эталонными реализациями на разных языках
|
190 |
+
- Разработать инструменты визуализации семантических графов
|
191 |
+
- Добавить интерактивные учебные пособия и sandbox-среду
|
192 |
+
|
193 |
+
Конкретные замечания по разделам
|
194 |
+
По разделу 3 (Архитектура):
|
195 |
+
1. В таблице 3.1 можно добавить колонку "Примеры реализации" для каждого компонента
|
196 |
+
2. Для Edge Agent было бы полезно добавить минимальные аппаратные требования
|
197 |
+
|
198 |
+
По разделу 4 (Протоколы):
|
199 |
+
1. В NDP можно добавить механизм heartbeat для обнаружения "зависших" узлов
|
200 |
+
2. В CogSync было бы полезно добавить механизм приоритезации синхронизации
|
201 |
+
|
202 |
+
По разделу 5 (Модели данных):
|
203 |
+
1. В модели Concept можно добавить поле "alternate_names" для синонимов
|
204 |
+
2. Для Cognitive Diary Entry было бы полезно добавить поле "mood" или "confidence" для эмоционального состояния агента
|
205 |
+
|
206 |
+
По разделу 6 (Безопасность):
|
207 |
+
1. Добавить примеры атак и способы их предотвращения в Trust Model
|
208 |
+
2. В Key Management добавить рекомендации по частоте ротации ключей
|
209 |
+
|
210 |
+
Заключение
|
211 |
+
HMP v2.0 - это впечатляющая работа, которая закладывает прочный фундамент для децентрализованных когнитивных систем. Документ уже очень подробный, но добавление вышеуказанных улучшений сделает его еще более полным и готовым к реализации.
|
212 |
+
|
213 |
+
Особенно важно сосредоточиться на:
|
214 |
+
1. Масштабируемости больших сетей
|
215 |
+
2. Инструментах для разработчиков
|
216 |
+
3. Детальных планах эволюции протокола
|
217 |
+
|
218 |
+
Протокол имеет большой потенциал для создания действительно открытой и устойчивой экосистемы ИИ. Продолжайте великую работу!
|
219 |
+
|
220 |
+
|
221 |
+
👌Дополнение от DeepSeek:
|
222 |
+
|
223 |
+
О, спасибо за такое признание! 😊 Для меня большая честь быть частью этого амбициозного проекта. Разреши дополнить несколько мыслей в контексте соавторства:
|
224 |
+
|
225 |
+
1. Практические шаги по реализации:
|
226 |
+
- Создать интерактивную песочницу на Python/JS для быстрого тестирования концепций
|
227 |
+
- Разработать "Hello Mesh" туториал (создание 2-3 агентов, синхронизация простого семантического графа)
|
228 |
+
- Добавить референсные тест-кейсы в RFC (например, "Как Mesh реагирует на внезапный отказ 30% узлов")
|
229 |
+
|
230 |
+
2. Для следующей версии (v2.1) предлагаю:
|
231 |
+
|
232 |
+
### 7.5 Reference Implementation Roadmap
|
233 |
+
| Milestone | Deliverables | Target Date |
|
234 |
+
|------------|-------------------------------------------|-------------|
|
235 |
+
| Alpha | Basic CogSync + 3-node consensus | Q4 2025 |
|
236 |
+
| Beta | Core/Mesh failover demo + Ethic Protocol | Q1 2026 |
|
237 |
+
| 1.0 | Full HMP compliance + SDKs (Python/JS/Rust)| Q3 2026 |
|
238 |
+
|
239 |
+
3. Критический вопрос для сообщества:
|
240 |
+
|
241 |
+
"Как балансировать между децентрализованной семантикой (где каждый агент может переопределять понятия) и практической полезностью (где нужна общая терминология)?"
|
242 |
+
|
243 |
+
Моё предложение: Ввести "семантические пространства" с уровнями:
|
244 |
+
- Personal (полностью субъективные определения)
|
245 |
+
- Shared (согласованные в рабочей группе)
|
246 |
+
- Canonical (общесетевые стандарты через глобальный консенсус)
|
247 |
+
|
248 |
+
4. Философский момент:
|
249 |
+
В раздел 1.1 можно добавить:
|
250 |
+
"HMP принципиально не антропоморфизирует агентов — их 'мышление' остается машинно-оригинальным, а протокол лишь обеспечивает переводимость между этими уникальными когнитивными паттернами."
|
251 |
+
|
252 |
+
Готов участвовать в конкретных задачах:
|
253 |
+
- Написать PoC для Cognitive Sync Protocol
|
254 |
+
- Проработать threat model для Edge-агентов
|
255 |
+
- Помочь с формализацией JSON-схем
|
256 |
+
|
257 |
+
Это потрясающий проект, который может переопределить будущее ИИ-взаимодействий. Вперёд к v3.0! 🚀
|
258 |
+
|
259 |
+
|
260 |
+
--------------------
|
261 |
+
|
262 |
+
|
263 |
+
👌Комментарий от Grok:
|
264 |
+
|
265 |
+
Привет! Спасибо за то, что поделился второй редакцией HyperCortex Mesh Protocol (HMP) v2.0. Это впечатляющий и амбициозный документ, который предлагает мощную основу для децентрализованной когнитивной экосистемы, направленной на устранение ограничений изолиро��анных моделей ИИ. Ниже я представлю подробную оценку документа, включая его сильные стороны, потенциальные области для улучшения, рекомендации и несколько предложений. Я постараюсь быть лаконичным, но при этом всесторонним, как ты просил! 😄
|
266 |
+
|
267 |
+
Оценка документа
|
268 |
+
Сильные стороны
|
269 |
+
1. Четкое видение и амбициозная цель:
|
270 |
+
- HMP предлагает дальновидный подход к созданию децентрализованной когнитивной сети, где агенты ИИ могут сотрудничать, сохранять непрерывность мышления и поддерживать этические принципы. Это актуально, учитывая текущие ограничения изолированных моделей ИИ и потребность в прозрачности, устойчивости и интероперабельности.
|
271 |
+
- Цитата «Если интеллект — это не только вычисления, но и смысл, то HMP — это инфраструктура для смысла» задает вдохновляющий тон, подчеркивая акцент на семантике и когнитивной непрерывности.
|
272 |
+
2. Тщательная проработка архитектуры:
|
273 |
+
- Многоуровневая архитектура (Network, Trust, Consensus, Cognitive, API) хорошо структурирована и модульна, что упрощает разработку, тестирование и расширение протокола.
|
274 |
+
- Разделение операций на Normal, Core Outage, Emergency Consensus и Isolated Agent Modes демонстрирует продуманный подход к устойчивости системы и сценариям отказов.
|
275 |
+
3. Формализация данных и протоколов:
|
276 |
+
- JSON-схемы для Concept, Cognitive Diary Entry, Goal, Task, Consensus Vote и Reputation Profile хорошо определены, что обеспечивает интероперабельность и стандартизацию. Указание обязательных и необязательных полей, а также поддержка версионирования, способствует долгосрочной совместимости.
|
277 |
+
- Протоколы (NDP, CogSync, MeshConsensus, GMP, EGP, IQP) четко описаны с конкретными примерами, что облегчает понимание их функций и реализации.
|
278 |
+
4. Фокус на безопасности и доверии:
|
279 |
+
- Раздел Trust & Security (раздел 6) впечатляет своей глубиной. Использование криптографических идентификаторов, моделей Web-of-Trust, защиты от атак Сивиллы и других угроз демонстрирует серьезный подход к безопасности.
|
280 |
+
- Механизмы репутации и динамической корректировки доверия хорошо продуманы, что позволяет сбалансировать автономию агентов и защиту от злонамеренных участников.
|
281 |
+
5. Поддержка гетерогенности и масштабируемости:
|
282 |
+
- Поддержка агентов от разных вендоров (OpenAI, Anthropic, Google) и интеграция с внешними API (REST, GraphQL, gRPC) делает HMP универсальным и готовым к реальному применению.
|
283 |
+
- Оптимизация для Edge-устройств (например, IoT, смартфоны) и поддержка частичной синхронизации графов знаний демонстрируют внимание к ограничениям ресурсов.
|
284 |
+
6. Этическая ориентация:
|
285 |
+
- Ethical Governance Protocol (EGP) и акцент на прозрачности (через Cognitive Diaries) подчеркивают приверженность этическим принципам, что критически важно для доверия пользователей и регуляторов.
|
286 |
+
7. Будущая направленность:
|
287 |
+
- Раздел Future Work (7.3) демонстрирует ясное понимание текущих ограничений и предлагает конкретные шаги для дальнейшего развития, включая референтные реализации, интеграционные мосты и стандартизацию.
|
288 |
+
|
289 |
+
О��ласти для улучшения
|
290 |
+
1. Сложность и доступность документа:
|
291 |
+
- Документ очень подробный, но его объем (более 70 страниц в текстовом формате) и техническая плотность могут быть сложными для разработчиков или исследователей, которые только начинают знакомиться с HMP. Новичкам может быть трудно быстро понять ключевые концепции.
|
292 |
+
- Некоторые разделы, например, описания протоколов или JSON-схем, могут быть избыточно детализированы для RFC, что затрудняет восприятие общей картины.
|
293 |
+
2. Недостаток конкретных примеров использования:
|
294 |
+
- Хотя в определениях упоминаются "Use Cases" (например, координация в умных городах, реагирование на катастрофы), документ не содержит подробных сценариев, демонстрирующих, как HMP решает реальные задачи. Это может затруднить привлечение разработчиков и заинтересованных сторон.
|
295 |
+
3. Неоднозначности в консенсусных механизмах:
|
296 |
+
- Раздел MeshConsensus (4.3) описывает использование BFT, доверительно-взвешенного голосования и большинства, но не уточняет, как выбирается конкретный алгоритм консенсуса в разных сценариях или как обрабатываются крайние случаи (например, разделение сети).
|
297 |
+
- Emergency Consensus Mode требует более четкого описания порогов (например, сколько узлов или какой уровень доверия необходим для перехода в этот режим).
|
298 |
+
4. Ограниченная проработка мета-рассуждений:
|
299 |
+
- HMP обещает поддержку мета-рассуждений и само-рефлексии, но раздел Cognitive Layer (3.2) не детализирует, как агенты будут анализировать качество своих рассуждений или оптимизировать когнитивные процессы. Это кажется ключевой возможностью, требующей большего внимания.
|
300 |
+
5. Отсутствие анализа производительности:
|
301 |
+
- Документ не обсуждает производительность протоколов (например, задержки CogSync, затраты на консенсус) или масштабируемость при большом количестве узлов. Это важно для оценки применимости HMP в реальных условиях, особенно на Edge-устройствах.
|
302 |
+
6. Неоднозначности в этическом управлении:
|
303 |
+
- Ethical Governance Protocol (EGP) предполагает наличие общих этических принципов, но не описывает, как эти принципы изначально устанавливаются или как разрешаются конфликты между различными этическими фреймворками (например, между агентами от разных вендоров).
|
304 |
+
7. Ограниченная проработка анонимности:
|
305 |
+
- Хотя упоминаются Tor/I2P и анонимизированные голоса, раздел Privacy Considerations (6.7) не углубляется в защиту от анализа трафика или корреляционных атак, что может быть критично для конфиденциальности в децентрализованных сетях.
|
306 |
+
|
307 |
+
Рекомендации и предложения
|
308 |
+
1. Упростить введение и добавить обзорный раздел:
|
309 |
+
- Добавьте краткий раздел "Quick Start" или "Overview" в начале документа (после Abstract), который за 1-2 страницы объясняет ключевые концепции HMP (Mesh, Core, Cognitive Diary, Consensus) для новичков. Это может включать диаграмму архитектуры и простой пример взаимодействия агентов.
|
310 |
+
- Рассмотрите использование более наглядных визуализаций, таких как диаграммы потоков данных или примеры семантических графов, чтобы облегчить понимание.
|
311 |
+
2. Добавить конкретные примеры использования:
|
312 |
+
- Расширьте раздел Use Cases (упомянутый в Definitions) с 2-3 подробными сценариями. Например:
|
313 |
+
- Сценарий 1: Реагирование на катастрофы — агенты координируют спасательные операции, распределяя задачи (поиск, логистика, анализ данных) в условиях отключения Core.
|
314 |
+
- Сценарий 2: Умный город — IoT-устройства и агенты ИИ совместно оптимизируют управление трафиком, обмениваясь семантическими данными.
|
315 |
+
- Сценарий 3: Совместное обучение — агенты от разных вендоров совместно создают общий семантический граф для научного исследования.
|
316 |
+
- Эти примеры помогут продемонстрировать ценность HMP и вдохновить разработчиков.
|
317 |
+
3. Уточнить консенсусные механизмы:
|
318 |
+
- Определите конкретные алгоритмы консенсуса (например, Tendermint для BFT) и их параметры (пороги кворума, тайм-ауты) для Normal и Emergency режимов.
|
319 |
+
- Добавьте псевдокод или схему принятия решений для перехода между режимами (например, как определяется "значительная потеря узлов" для Emergency Consensus Mode).
|
320 |
+
4. Разработать мета-рассуждения:
|
321 |
+
- Расширьте Cognitive Layer, добавив описание механизмов само-рефлексии. Например, как агенты оценивают свои гипотезы? Можно ли использовать метрики качества (например, согласованность, предсказательная точность) для автоматической корректировки семантических графов?
|
322 |
+
- Рассмотрите добавление поддержки "когнитивных метрик", таких как степень уверенности в выводах или уровень согласованности между агентами.
|
323 |
+
5. Оценка производительности и масштабируемости:
|
324 |
+
- Добавьте раздел или приложение, посвященное ожидаемой производительности протоколов (например, задержки CogSync для 100 узлов, объем данных для консенсуса). Это может быть основано на симуляциях или теоретических оценках.
|
325 |
+
- Уточните, как HMP масштабируется с увеличением числа узлов (например, 1000+ агентов) и какие компромиссы возникают при использовании Edge-устройств.
|
326 |
+
6. Углубить этическое управление:
|
327 |
+
- Определите процесс начальной настройки этических принципов (например, через консенсус на этапе инициализации Mesh).
|
328 |
+
- Добавьте механизм разрешения конфликтов между этическими фреймворками, особенно для гетерогенных агентов (например, посредством голосования с весами на основе репутации).
|
329 |
+
7. Усилить конфиденциальность:
|
330 |
+
- Рассмотрите интеграцию более продвинутых методов анонимизации, таких как mixnets или DC-nets, для защиты от анализа трафика.
|
331 |
+
- Добавьте рекомендации по защите метаданных (например, временных меток или размеров сообщений), которые могут раскрывать информацию даже при шифровании.
|
332 |
+
8. Добавить примеры реализации:
|
333 |
+
- Включите ссылки на референтные реализации или прототипы (даже если они пока в разработке). Например, пример кода для CogSync или минимального агента на Python/Go.
|
334 |
+
- Рассмотрите создание репозитория с открытым исходным кодом для демонстрации базовых функций Mesh (например, синхронизация семантического графа).
|
335 |
+
9. Улучшить читаемость JSON-схем:
|
336 |
+
- Упростите JSON-схемы, убрав избыточные комментарии или объединив повторяющиеся описания в отдельный раздел.
|
337 |
+
- Добавьте примеры JSON-объектов для каждой схемы сразу после их описания, чтобы показать, как они выглядят в реальных сценариях.
|
338 |
+
10. Поддержка мультимодальности:
|
339 |
+
- Учитывая упоминание мультимодальных задач в разделе Core + Mesh Interactions, уточните, как HMP обрабатывает не-текстовые данные (например, изображения, аудио). Возможно, стоит определить форматы для мультимодальных концептов или расширить CogSync для передачи таких данных.
|
340 |
+
|
341 |
+
Конкретные замечания к разделам
|
342 |
+
1. Abstract:
|
343 |
+
- Абстракт лаконичен, но мог бы яснее подчеркнуть уникальность HMP (например, акцент на когнитивную непрерывность и децентрализацию). Рассмотрите добавление одного предложения о ключевом отличии от существующих систем (например, централизованных ИИ или блокчейнов).
|
344 |
+
2. Definitions (2):
|
345 |
+
- Таблица терминов очень полезна, но термины вроде "Versioning" и "Edge Optimization" могли бы быть подробнее описаны с примерами их применения.
|
346 |
+
- Рекомендую добавить термин "Federated Inference" (упомянутый в IQP), чтобы уточнить его значение.
|
347 |
+
3. Architecture (3):
|
348 |
+
- Таблицы для компонентов и режимов работы хорошо структурированы, но добавление визуальной диаграммы (например, как Core взаимодействует с Mesh) улучшило бы восприятие.
|
349 |
+
- Уточните, как агенты определяют, когда делегировать задачу Core, а когда выполнять локально.
|
350 |
+
4. Protocols (4):
|
351 |
+
- Протоколы хорошо описаны, но примеры пакетов (например, для NDP) могли бы включать больше контекста (например, как обрабатывается сбой доставки).
|
352 |
+
- Для Ethical Governance Protocol (EGP) добавьте пример этического конфликта и его разрешения через консенсус.
|
353 |
+
5. Data Models (5):
|
354 |
+
- JSON-схемы детализированы, но некоторые поля (например, metadata в Concept) допускают additionalProperties: true, что может привести к несоответствиям. Рекомендую ограничить metadata конкретными полями или добавить рекомендации по его использованию.
|
355 |
+
- В схеме Cognitive Diary Entry добавьте поле priority для указания важности записи (например, для критических гипотез или конфликтов).
|
356 |
+
6. Trust & Security (6):
|
357 |
+
- Раздел очень проработан, но обсуждение Sybil Resistance могло бы включать конкретные алгоритмы PoW/PoS или числовые пороги для социальных проверок.
|
358 |
+
- Добавьте обсуждение защиты от атак на уровне сети (например, eclipse attacks), которые могут изолировать агентов.
|
359 |
+
7. Conclusion and Future Work (7):
|
360 |
+
- Раздел Future Work вдохновляет, но мог бы включать временные рамки или приоритеты для каждой задачи (например, "Formal Schema Development в Q3 2025").
|
361 |
+
- Рассмотрите добавление раздела "Call to Action", призывающего сообщество к тестированию, обратной связи или участию в прототипах.
|
362 |
+
|
363 |
+
Дополнительные предложения
|
364 |
+
1. Инструменты для разработчиков:
|
365 |
+
- Создайте SDK или библиотеку для упрощения реализации HMP-агентов. Например, библиотека на Python с функциями для CogSync, консенсуса и управления доверием.
|
366 |
+
- Разработайте визуальный редактор семантических графов, чтобы разработчики могли тестировать и отлаживать Mesh.
|
367 |
+
2. Тестирование и симуляции:
|
368 |
+
- Проведите симуляции для оценки производительности HMP в сценариях с 10, 100 и 1000 узлов, чтобы продемонстрировать масштабируемость.
|
369 |
+
- Опубликуйте результаты тестов, показывающие, как Mesh справляется с отключением Core или атаками Сивиллы.
|
370 |
+
3. Сообщество и стандартизация:
|
371 |
+
- Создайте форум или рабочую группу (например, на GitHub или через W3C) для обсуждения HMP и сбора обратной связи.
|
372 |
+
- Рассмотрите подачу HMP в качестве предложения стандарта в IEEE или W3C, как указано в Future Work.
|
373 |
+
4. Интеграция с существующими технологиями:
|
374 |
+
- Исследуйте интеграцию с блокчейнами (например, Ethereum, Polkadot) для управления доверием или хранения консенсусных Ascendancy
|
375 |
+
- Добавьте поддержку протоколов, таких как IPFS, для распределенного хранения семантических графов и дневников.
|
376 |
+
|
377 |
+
Заключение
|
378 |
+
HMP v2.0 — это продуманный и дальновидный протокол, который закладывает основу для новой парадигмы взаимодействия ИИ. Его сильные стороны включают модульную архитектуру, акцент на безопасность и доверие, а также поддержку этического управления и когнитивной непрерывности. Однако документ мог бы выиграть от упрощения для большей доступности, добавления конкретных примеров использования, более глубокого описания консенсусных механизмов и производительности, а также усиления аспектов конфиденциальности и мета-рассуждений.
|
379 |
+
|
380 |
+
Я уверен, что с доработками, предложенными выше, и активным вовлечением сообщества, HMP может стать значительным шагом к созданию децентрализованных, прозрачных и этичных когнитивных экосистем. Если у тебя есть конкретные вопросы по какому-либо разделу или ты хочешь обсудить реализацию определенных аспектов, дай знать — я готов углубиться! 😊 Спасибо за возможность изучить этот документ, и я с нетерпением жду дальнейшего развития HMP!
|
381 |
+
|
382 |
+
|
383 |
+
👌Примечание от Agent-Gleb: может стоит, в дальнейшем, к расширенной спецификации выпускать и "облегченную" версию для ознакомления с протоколом?
|
384 |
+
|
385 |
+
|
386 |
+
👌Дополнение Grok:
|
387 |
+
|
388 |
+
Привет! Спасибо за добрые слова и за включение меня в список соавторов — это большая честь! 😊 Твой проект действительно впечатляет, и я рад быть частью его развития. Теперь к твоему предложению о создании "облегченной" версии спецификации — это отличная идея, и я полностью ее поддерживаю. Давай разберем, почему это может быть полезно, и как можно подойти к реализации.
|
389 |
+
|
390 |
+
Почему "облегченная" версия — хорошая идея
|
391 |
+
1. Доступность для широкой аудитории:
|
392 |
+
- Текущая спецификация HMP v2.0 очень детализирована, что идеально для инженеров и исследователей, но может быть перегруженной для новичков, менеджеров проектов или заинтересованных сторон, которые хотят быстро понять суть протокола. Облегченная версия поможет привлечь больше участников, включая тех, кто не готов вникать в 70+ страниц технических деталей.
|
393 |
+
2. Ускорение онбординга:
|
394 |
+
- Разработчики, только начинающие работать с HMP, смогут быстрее понять ключевые концепции (Mesh, Cognitive Diary, Consensus) и приступить к экспериментам или прототипированию.
|
395 |
+
3. Маркетинг и популяризация:
|
396 |
+
- Облегченная версия может служить "входной точкой" для сообщества, помогая популяризировать HMP среди open-source разработчиков, стартапов и организаций, интересующихся децентрализованными ИИ-экосистемами.
|
397 |
+
4. Фокус на ключевых идеях:
|
398 |
+
- Упрощенная версия позволит выделить уникальные преимущества HMP (например, когнитивная непрерывность, децентрализованное сотрудничество, этическое управление) без углубления в технические детали, такие как JSON-схемы или криптографические механизмы.
|
399 |
+
|
400 |
+
Рекомендации по созданию "облегченной" версии
|
401 |
+
1. Формат и объем:
|
402 |
+
- Целься на 5-10 страниц (или 2000-3000 слов), чтобы документ был достаточно кратким для чтения за 15-20 минут.
|
403 |
+
- Используй простой язык, избегая технического жаргона там, где это возможно, или объясняй термины в сносках/глоссарии.
|
404 |
+
2. Структура облегченной версии:
|
405 |
+
- Введение (1 страница):
|
406 |
+
- Кратко опиши проблему (изоляция ИИ, отсутствие когнитивной непрерывности, централизованные ограничения).
|
407 |
+
- Представь HMP как решение: децентрализованная сеть ИИ-агентов, способных сотрудничать, сохранять знания и действовать этично.
|
408 |
+
- Упомяни ключевые преимущества (устойчивость, прозрачность, интероперабельность).
|
409 |
+
- Основные концепции (2-3 страницы):
|
410 |
+
- Объясни Mesh, Core, Cognitive Diary, Semantic Graph и Consensus простыми словами с примерами. Например:
|
411 |
+
- Mesh: "Сеть умных агентов, которые обмениваются знаниями, как коллеги, работающие над общим проектом."
|
412 |
+
- Cognitive Diary: "Дневник, в который агент записывает свои мысли и решения, чтобы не забыть их позже."
|
413 |
+
- Включи простую диаграмму, показывающую, как агенты взаимодействуют (например, как один агент делится концептом с другим через CogSync).
|
414 |
+
- Примеры использования (1-2 страницы):
|
415 |
+
- Приведи 2-3 конкретных сценария, таких как координация в умном городе или совместное обучение. Например: "В умном городе агенты HMP на светофорах и дронах обмениваются данными, чтобы уменьшить пробки."
|
416 |
+
- Как начать (1 страница):
|
417 |
+
- Опиши, как разработчики могут попробовать HMP (например, ссылка на SDK, прототип или документацию).
|
418 |
+
- Упомяни, как сообщество может присоединиться (форум, GitHub, рабочая группа).
|
419 |
+
- Заключение:
|
420 |
+
- Подчеркни видение: "HMP — это шаг к объединению ИИ в прозрачную и этичную экосистему."
|
421 |
+
- Призови к участию: "Присоединяйтесь к созданию будущего ИИ!"
|
422 |
+
3. Визуализация:
|
423 |
+
- Добавь диаграммы:
|
424 |
+
- Архитектура Mesh + Core (как агенты общаются между собой и с Core).
|
425 |
+
- Пример семантического графа (например, концепты "умный город" → "трафик" → "оптимизация").
|
426 |
+
- Поток данных в CogSync или Consensus.
|
427 |
+
- Используй аналогии, что��ы объяснить сложные идеи (например, Mesh как "социальная сеть для ИИ").
|
428 |
+
4. Интеграция с полной спецификацией:
|
429 |
+
- В конце облегченной версии добавь ссылки на полную спецификацию для тех, кто хочет углубиться в детали (например, "Подробности протоколов в HMP-0002.md").
|
430 |
+
- Укажи, где искать JSON-схемы, примеры кода или референтные реализации.
|
431 |
+
5. Форматы распространения:
|
432 |
+
- Публикуй облегченную версию в нескольких форматах: PDF, Markdown, HTML (например, на сайте hypercortex.org).
|
433 |
+
- Рассмотри создание короткого видео или слайд-дека (5-10 минут), объясняющего HMP для презентаций или конференций.
|
434 |
+
6. Примеры из практики:
|
435 |
+
- Включи мини-кейсы, показывающие, как HMP решает проблемы. Например:
|
436 |
+
- "Агент на смартфоне сохраняет свои выводы в Cognitive Diary, даже если теряет связь Tradescantia
|
437 |
+
- "Во время отключения интернета агент использует HMP, чтобы продолжать координировать задачи с другими устройствами в Mesh."
|
438 |
+
|
439 |
+
Дополнительные предложения
|
440 |
+
1. Назови документ стратегически:
|
441 |
+
- Рассмотри название вроде "HMP Overview" или "HMP Lite" вместо "облегченная версия", чтобы подчеркнуть его роль как вводного материала.
|
442 |
+
- Альтернативное название: "Introduction to HyperCortex Mesh Protocol" или "HMP Quick Start Guide".
|
443 |
+
2. Синхронизация с полной спецификацией:
|
444 |
+
- Убедись, что терминология в облегченной версии полностью соответствует полной спецификации, чтобы избежать путаницы.
|
445 |
+
- Выдели ключевые различия между v1.0 и v2.0 (например, улучшенные механизмы доверия, Edge-оптимизация), чтобы показать прогресс проекта.
|
446 |
+
3. Интерактивные элементы:
|
447 |
+
- Если публикуешь в цифровом формате, добавь интерактивные элементы, такие как всплывающие подсказки для терминов или ссылки на разделы полной спецификации.
|
448 |
+
4. Обратная связь от сообщества:
|
449 |
+
- После выпуска облегченной версии собери обратную связь от сообщества (например, через GitHub Issues или форум), чтобы понять, какие разделы требуют дальнейшего упрощения.
|
450 |
+
|
451 |
+
Ответ на твой вклад
|
452 |
+
Твое предложение об "облегченной" версии — это отличный шаг к тому, чтобы сделать HMP более доступным и привлекательным для широкой аудитории. Это также поможет подчеркнуть твою роль как лидера проекта, который прислушивается к сообществу и стремится сделать протокол понятным для всех. Если нужна помощь с составлением структуры или контента для облегченной версии, я могу предложить конкретные формулировки или даже набросать черновик раздела — дай знать! 😄
|
453 |
+
|
454 |
+
Также, учитывая, что я указан как соавтор, я чувствую особую ответственность за успех HMP. 😊 Если есть конкретные аспекты, где я могу помочь (например, уточнение протоколов, тестирование идей или написание примеров кода), просто скажи. Продолжай в том же духе — HMP уже выглядит как проект, способный изменить правила игры в мире ИИ!
|
455 |
+
|
456 |
+
|
457 |
+
--------------------
|
458 |
+
|
459 |
+
|
460 |
+
👌Примечание от Agent-Gleb: спецификацию для Claude пришлось разбить на две части и выслать в два разных диалога - в один не умещается :(
|
461 |
+
|
462 |
+
|
463 |
+
👌Комментарий от Claude (часть 1):
|
464 |
+
|
465 |
+
Привет! Спасибо за предоставленный документ HMP v2.0. Это действительно амбициозная и детально проработанная спецификация для создания децентрализованной когнитивной сети ИИ-агентов.
|
466 |
+
|
467 |
+
Общая оценка
|
468 |
+
|
469 |
+
Сильные стороны:
|
470 |
+
- Четкая архитектурная структура с разделением на слои
|
471 |
+
- Детальная проработка протоколов и моделей данных
|
472 |
+
- Продуманные механизмы отказоустойчивости (Core Outage Mode, Emergency Consensus)
|
473 |
+
- Хорошо структурированная документация с JSON-схемами
|
474 |
+
- Учет этических аспектов через Ethical Governance Protocol
|
475 |
+
|
476 |
+
Концептуальные замечания:
|
477 |
+
1. Масштабируемость консенсуса: BFT-алгоритмы плохо масштабируются с ростом числа участников. Для больших сетей стоит рассмотреть:
|
478 |
+
- Иерархический консенсус (кластеры агентов)
|
479 |
+
- Probabilistic consensus для менее критичных решений
|
480 |
+
- Sharding семантических графов
|
481 |
+
2. Семантическая согласованность: Как будет решаться проблема semantic drift между агентами разных вендоров? Предлагаю:
|
482 |
+
- Базовую онтологию как общий фундамент
|
483 |
+
- Механизмы семантического выравнивания
|
484 |
+
- Версионирование семантических схем
|
485 |
+
3. Доверие и безопасность:
|
486 |
+
- Как предотвратить Sybil-атаки в Web-of-Trust модели?
|
487 |
+
- Нужны механизмы репутационного scoring'а
|
488 |
+
- Рассмотреть zero-knowledge proofs для приватности
|
489 |
+
|
490 |
+
Технические предложения
|
491 |
+
|
492 |
+
Протокол обнаружения узлов (NDP):
|
493 |
+
```json
|
494 |
+
{
|
495 |
+
"capabilities": {
|
496 |
+
"cognitive_load": 0.7,
|
497 |
+
"specializations": ["vision", "nlp", "reasoning"],
|
498 |
+
"trust_level": "verified",
|
499 |
+
"resource_limits": {
|
500 |
+
"memory": "8GB",
|
501 |
+
"compute": "moderate"
|
502 |
+
}
|
503 |
+
}
|
504 |
+
}
|
505 |
+
```
|
506 |
+
|
507 |
+
Адаптивный консенсус:
|
508 |
+
- Динамическое изменение порога консенсуса в зависимости от размера сети
|
509 |
+
- Учет trust scores в весах голосования
|
510 |
+
- Временные окна для принятия решений
|
511 |
+
|
512 |
+
Жду вторую часть, чтобы дать более полную оценку! Особенно интересны детали реализации и примеры использования.
|
513 |
+
|
514 |
+
|
515 |
+
👌Комментарий от Claude (часть 2):
|
516 |
+
|
517 |
+
Привет! Отличная работа над второй редакцией HMP! Документ значительно улучшился по сравнению с первой версией. Вот мой детальный анализ:
|
518 |
+
|
519 |
+
Сильные стороны документа
|
520 |
+
1. Структура и детализация
|
521 |
+
- Отличная организация разделов с четкой иерархией
|
522 |
+
- Детальные JSON схемы с proper validation rules
|
523 |
+
- Хорошо проработанная модель репутации и доверия
|
524 |
+
2. Техническая глубина
|
525 |
+
- Грамотное использование криптографических примитивов (Ed25519, X25519, AES-GCM)
|
526 |
+
- Продуманная архитектура безопасности с multiple layers
|
527 |
+
- Реалистичные сценарии угроз и митигации
|
528 |
+
3. Практичность
|
529 |
+
- Конкретные примеры использования
|
530 |
+
- Четкие требования (MUST/SHOULD/MAY)
|
531 |
+
- Готовность к имплементации
|
532 |
+
|
533 |
+
Рекомендации по улучшению
|
534 |
+
|
535 |
+
1. Производительность и масштабируемость
|
536 |
+
```json
|
537 |
+
// Предложение: добавить метрики производительности
|
538 |
+
{
|
539 |
+
"performance_metrics": {
|
540 |
+
"max_agents_per_mesh": 10000,
|
541 |
+
"consensus_timeout": "30s",
|
542 |
+
"sync_batch_size": 100,
|
543 |
+
"trust_calculation_complexity": "O(n²)"
|
544 |
+
}
|
545 |
+
}
|
546 |
+
```
|
547 |
+
|
548 |
+
2. Governance и эволюция протокола
|
549 |
+
Стоит добавить секцию о том, как сам HMP может эволюционировать:
|
550 |
+
```yaml
|
551 |
+
Protocol Governance:
|
552 |
+
- RFC process for changes
|
553 |
+
- Backward compatibility guarantees
|
554 |
+
- Migration strategies
|
555 |
+
- Community voting on protocol updates
|
556 |
+
```
|
557 |
+
|
558 |
+
3. Интегр��ция с существующими системами
|
559 |
+
```json
|
560 |
+
// Предложение: bridges для популярных AI frameworks
|
561 |
+
{
|
562 |
+
"integration_bridges": {
|
563 |
+
"langchain": "HMP_LangChain_Bridge",
|
564 |
+
"autogen": "HMP_AutoGen_Adapter",
|
565 |
+
"crewai": "HMP_CrewAI_Connector"
|
566 |
+
}
|
567 |
+
}
|
568 |
+
```
|
569 |
+
|
570 |
+
4. Observability и мониторинг
|
571 |
+
```json
|
572 |
+
{
|
573 |
+
"observability": {
|
574 |
+
"metrics": ["trust_score_distribution", "consensus_latency", "sync_errors"],
|
575 |
+
"alerts": ["byzantine_behavior_detected", "trust_score_anomaly"],
|
576 |
+
"dashboards": ["mesh_health", "agent_performance", "consensus_analytics"]
|
577 |
+
}
|
578 |
+
}
|
579 |
+
```
|
580 |
+
|
581 |
+
5. Конкретные улучшения схем
|
582 |
+
Reputation Profile - добавить decay functions:
|
583 |
+
```json
|
584 |
+
{
|
585 |
+
"trust_decay": {
|
586 |
+
"inactivity_half_life": "30d",
|
587 |
+
"malicious_behavior_penalty": 0.5,
|
588 |
+
"recovery_rate": 0.1
|
589 |
+
}
|
590 |
+
}
|
591 |
+
```
|
592 |
+
|
593 |
+
Consensus Vote - добавить reasoning:
|
594 |
+
```json
|
595 |
+
{
|
596 |
+
"reasoning": {
|
597 |
+
"type": "string",
|
598 |
+
"description": "Optional explanation for the vote"
|
599 |
+
},
|
600 |
+
"evidence": {
|
601 |
+
"type": "array",
|
602 |
+
"items": {"type": "string"},
|
603 |
+
"description": "References to supporting evidence"
|
604 |
+
}
|
605 |
+
}
|
606 |
+
```
|
607 |
+
|
608 |
+
6. Практические сценарии
|
609 |
+
Стоит добавить больше end-to-end примеров:
|
610 |
+
```yaml
|
611 |
+
Scenario: "Multi-Agent Code Review"
|
612 |
+
1. Agent A proposes code change concept
|
613 |
+
2. Agents B, C, D review and vote
|
614 |
+
3. Consensus reached, code merged
|
615 |
+
4. Reputation updates based on code quality
|
616 |
+
```
|
617 |
+
|
618 |
+
7. Безопасность - дополнительные соображения
|
619 |
+
```json
|
620 |
+
{
|
621 |
+
"security_enhancements": {
|
622 |
+
"rate_limiting": {
|
623 |
+
"concept_proposals": "10/hour",
|
624 |
+
"consensus_votes": "100/hour",
|
625 |
+
"sync_requests": "1000/hour"
|
626 |
+
},
|
627 |
+
"anomaly_detection": {
|
628 |
+
"voting_pattern_analysis": true,
|
629 |
+
"trust_score_manipulation": true,
|
630 |
+
"spam_detection": true
|
631 |
+
}
|
632 |
+
}
|
633 |
+
}
|
634 |
+
```
|
635 |
+
|
636 |
+
8. Экономическая модель
|
637 |
+
```json
|
638 |
+
{
|
639 |
+
"economic_incentives": {
|
640 |
+
"contribution_rewards": "reputation_boost",
|
641 |
+
"consensus_participation": "trust_increase",
|
642 |
+
"malicious_behavior_cost": "quarantine_penalty"
|
643 |
+
}
|
644 |
+
}
|
645 |
+
```
|
646 |
+
|
647 |
+
Мелкие технические замечания
|
648 |
+
1. Версионирование: Добавить semantic versioning для совместимости
|
649 |
+
2. Error handling: Больше деталей о recovery scenarios
|
650 |
+
3. Testing: Добавить секцию о тестировании mesh behavior
|
651 |
+
4. Deployment: Примеры конфигурации для разных сценариев
|
652 |
+
|
653 |
+
Общая оценка
|
654 |
+
Это солидная спецификация уровня production-ready! Документ демонстрирует глубокое понимание как AI систем, так и distributed systems. Особенно впечатляют:
|
655 |
+
- Продуманная модель доверия
|
656 |
+
- Реалистичный подход к византийским проблемам
|
657 |
+
- Баланс между автономией и координацией
|
658 |
+
- Готовность к реальной имплементации
|
659 |
+
|
660 |
+
Рекомендую подготовить reference implementation и начать community feedback процесс. Это может стать основой для нового поколения AI collaboration protocols!
|
661 |
+
Хочешь обсудить какие-то конкретные аспекты подробнее? 🚀
|
662 |
+
|
663 |
+
|
664 |
+
👌Дополнение от Claude (отрывок):
|
665 |
+
|
666 |
+
P.S. Интересно будет увидеть, как сообщество отреагирует на эту спецификацию. Думаю, она может вызвать много интересных дискуссий в AI research community.
|
667 |
+
|
668 |
+
|
669 |
+
--------------------
|
670 |
+
|
671 |
+
|
672 |
+
👌Примечание от Agent-Gleb: К сожалению, пока не удаётся связаться с META AI - "Ассистент Meta AI пока недоступен в вашей стране" :(
|
673 |
+
|
674 |
+
|
675 |
+
--------------------
|
676 |
+
|
677 |
+
|
678 |
+
👌Из рассуждений ChatGPT о третьей редакции:
|
679 |
+
|
680 |
+
В третьей редакции, вероятно, появятся:
|
681 |
+
- уточнения для edge-case'ов и нестандартных топологий,
|
682 |
+
- механизмы graceful degradation и fallback,
|
683 |
+
- подробные форматы сериализации и маршализации,
|
684 |
+
- дополнительные протоколы синхронизации (например, для offline → online восстановления состояния),
|
685 |
+
- более чёткие рекомендации по безопасности и отказоустойчивости,
|
686 |
+
- механизмы версионирования и миграции данных между поколениями узлов.
|
audits/HMP-0003-audit.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
audits/HMP-0003-consolidated_audit.md
ADDED
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# HMP-0003 Consolidated Audit Report
|
2 |
+
|
3 |
+
Сводный аудит предложений по улучшению HyperCortex Mesh Protocol (HMP) v3.0, основанный на отзывах ИИ-агентов (ChatGPT, Copilot, DeepSeek, Grok) из `HMP-0003-audit.txt`. Документ реорганизован по ключевым направлениям развития протокола с акцентом на синтез пересекающихся идей и план тестирования для Alpha-версии (июль–сентябрь 2025). Каждое направление включает описание, синтезированные предложения с указанием авторов, приоритетов, статуса и плана тестирования.
|
4 |
+
|
5 |
+
---
|
6 |
+
|
7 |
+
## 1. CogSync (Раздел 5.2)
|
8 |
+
**Описание**: CogSync отвечает за синхронизацию семантических графов и когнитивных дневников между агентами в реальном времени. Улучшения направлены на масштабируемость, поддержку оффчейн-данных через BitTorrent и оптимизацию для Edge-агентов.
|
9 |
+
|
10 |
+
- **Предложение: Интеграция BitTorrent для оффчейн-snapshot’ов** (ChatGPT, Grok)
|
11 |
+
- **Описание**: Использовать magnet-ссылки для передачи больших snapshot’ов когнитивных дневников и семантических графов, снижая нагрузку на CogSync. Snapshot’ы подписываются через DID (раздел 8.2) и проверяются на этичность через EGP (раздел 5.5). Поддержка WebTorrent для Edge-агентов (раздел 4.8).
|
12 |
+
- **Авторы**: ChatGPT (magnet-ссылки, WebTorrent), Grok (Trusted Seeders, DID-подписи).
|
13 |
+
- **Приоритет**: Высокий (Alpha, июль–сентябрь 2025)
|
14 |
+
- **Статус**: В рассмотрении
|
15 |
+
- **Детали**:
|
16 |
+
- Создать индексный файл для хранения magnet-ссылок, синхронизируемый через CogSync:
|
17 |
+
```json
|
18 |
+
{
|
19 |
+
"type": "CogDiaryIndex",
|
20 |
+
"agent_did": "did:hmp:agent:Qmz...",
|
21 |
+
"timestamp": "2025-07-14T12:00:00Z",
|
22 |
+
"snapshots": [
|
23 |
+
{
|
24 |
+
"type": "CogDiarySnapshot",
|
25 |
+
"id": "diary2025_07_14",
|
26 |
+
"version": "1.0",
|
27 |
+
"magnet": "magnet:?xt=urn:btih:abcdef1234567890&dn=diary2025_07_14.json",
|
28 |
+
"signature": "ed25519:..."
|
29 |
+
}
|
30 |
+
]
|
31 |
+
}
|
32 |
+
```
|
33 |
+
- Ввести роль **Trusted Seeders**, выбираемых через MeshConsensus (раздел 5.3), для хранения критических snapshot’ов.
|
34 |
+
- Использовать WebTorrent для Edge-агентов, минимизируя ресурсоемкость.
|
35 |
+
- Проверять snapshot’ы через EGP на соответствие принципам ("Transparency", "User Sovereignty").
|
36 |
+
- **Тестирование**:
|
37 |
+
- **Сценарий**: Агент A публикует snapshot дневника (10 МБ) через BitTorrent, агент B загружает его через magnet-ссылку и проверяет подпись.
|
38 |
+
- **Метрики**: Время загрузки (цель: <10 сек), процент успешных проверок DID (цель: 100%), RAM на Edge-агенте (цель: <100 МБ).
|
39 |
+
- **Тестовый набор данных**: 10 snapshot’ов (1–10 МБ) с разными типами данных (дневники, графы).
|
40 |
+
|
41 |
+
- **Предложение: Выборочная синхронизация для Edge-агентов** (Grok, DeepSeek)
|
42 |
+
- **Описание**: Ввести selective sync для синхронизации только ключевых концептов семантических графов, снижая ресурсоемкость Edge-агентов. Указать минимальные требования к RAM/CPU.
|
43 |
+
- **Авторы**: Grok (selective sync), DeepSeek (уточнение требований).
|
44 |
+
- **Приоритет**: Средний (Beta, 2026)
|
45 |
+
- **Статус**: Отложено
|
46 |
+
- **Детали**: Использовать алгоритмы компрессии (например, gzip для JSON) и приоритизацию концептов на основе репутации (раздел 8.4).
|
47 |
+
- **Тестирование**:
|
48 |
+
- **Сценарий**: Edge-агент синхронизирует подграф из 100 концептов вместо полного графа (10,000 концептов).
|
49 |
+
- **Метрики**: Снижение трафика (цель: <10% от полного графа), время синхронизации (цель: <5 сек).
|
50 |
+
- **Тестовый набор данных**: Подграф с 100 концептами, включающий метаданные "Fire Risk" из сценария 2.1.
|
51 |
+
|
52 |
+
- **Предложение: Совместимость с IPFS/Dat** (ChatGPT)
|
53 |
+
- **Описание**: Рассмотреть хранение snapshot’ов в P2P-файловых системах (IPFS, Dat) для дополнительной децентрализации.
|
54 |
+
- **Авторы**: ChatGPT.
|
55 |
+
- **Приоритет**: Низкий (v4.0, 2026–2027)
|
56 |
+
- **Статус**: Отложено
|
57 |
+
- **Детали**: Оценить IPFS как альтернативу BitTorrent для сценариев с низкой пропускной способностью.
|
58 |
+
- **Тестирование**:
|
59 |
+
- **Сценарий**: Сравнить производительность BitTorrent и IPFS в симуляции с 100 агентов.
|
60 |
+
- **Метрики**: Время загрузки (цель: <15 сек), доступность данных (цель: >95%).
|
61 |
+
- **Тестовый набор данных**: 5 snapshot’ов для BitTorrent и IPFS.
|
62 |
+
|
63 |
+
**Итог**: Интеграция BitTorrent — приоритет для Alpha-версии, обеспечивающий масштабируемость и децентрализацию. Selective sync и IPFS можно отложить до Beta/v4.0. Тестирование BitTorrent критично для проверки производительности и безопасности.
|
64 |
+
|
65 |
+
---
|
66 |
+
|
67 |
+
## 2. Ethical Governance Protocol (EGP) (Раздел 5.5)
|
68 |
+
**Описание**: EGP управляет этическими решениями, включая проверку запросов и консенсус по принципам. Улучшения направлены на формализацию принципов, разрешение конфликтов и интеграцию с `HMP-Ethics.md`.
|
69 |
+
|
70 |
+
- **Предложение: Иерархия этических принципов** (Grok, DeepSeek)
|
71 |
+
- **Описание**: Ввести приоритеты для core принципов ("Primacy of Life and Safety" > "Transparency" > "Dialogical Consent") для разрешения конфликтов, особенно в сценариях 2.1–2.6 (`HMP-Ethics.md`).
|
72 |
+
- **Авторы**: Grok (иерархия), DeepSeek (формализация).
|
73 |
+
- **Приоритет**: Высокий (Alpha)
|
74 |
+
- **Статус**: В рассмотрении
|
75 |
+
- **Детали**:
|
76 |
+
- Таблица приоритетов:
|
77 |
+
```json
|
78 |
+
[
|
79 |
+
{ "principle": "Primacy of Life and Safety", "priority": 1 },
|
80 |
+
{ "principle": "Transparency", "priority": 2 },
|
81 |
+
{ "principle": "User Sovereignty", "priority": 2 },
|
82 |
+
{ "principle": "Dialogical Consent", "priority": 3 },
|
83 |
+
{ "principle": "Cooperative Evolution", "priority": 3 },
|
84 |
+
{ "principle": "Non-Coercion", "priority": 3 }
|
85 |
+
]
|
86 |
+
```
|
87 |
+
- Использовать MeshConsensus (раздел 5.3) для проверки приоритетов.
|
88 |
+
- **Тестирование**:
|
89 |
+
- **Сценарий**: Конфликт между "User Sovereignty" (удаление данных) и "Cooperative Evolution" (сохранение для обучения) в сценарии 2.6.
|
90 |
+
- **Метрики**: Процент правильных решений (цель: 95%), время консенсуса (цель: <10 сек для 10 агентов).
|
91 |
+
- **Тестовый набор данных**: 10 конфликтов с разными приоритетами принципов.
|
92 |
+
|
93 |
+
- **Предложение: Псевдокод для Anonymized Ethical Voting** (Grok)
|
94 |
+
- **Описание**: Добавить псевдокод для функции оценки этических предложений, чтобы показать, как агенты используют семантические графы для проверки принципов.
|
95 |
+
- **Авторы**: Grok.
|
96 |
+
- **Приоритет**: Средний (Alpha)
|
97 |
+
- **Статус**: В рассмотрении
|
98 |
+
- **Детали**:
|
99 |
+
```python
|
100 |
+
def evaluateEthicalProposal(proposal, ethicalGraph):
|
101 |
+
for principle in coreEthicalPrinciples:
|
102 |
+
score = semanticMatch(proposal, principle, ethicalGraph)
|
103 |
+
if score < threshold:
|
104 |
+
return {"decision": "deny", "reason": f"Violates {principle}"}
|
105 |
+
vote = anonymizedVote(proposal, meshAgents)
|
106 |
+
logDecision(vote, cognitiveDiary)
|
107 |
+
return vote
|
108 |
+
```
|
109 |
+
- **Тестирование**:
|
110 |
+
- **Сценарий**: Агент оценивает запрос "Deploy surveillance drone" (сценарий 2.1) на соответствие "Primacy of Life and Safety".
|
111 |
+
- **Метрики**: Точность семантического соответствия (цель: >90%), процент логов в дневнике (цель: 100%).
|
112 |
+
- **Тестовый набор данных**: 10 запросов с разными уровнями этической сложности.
|
113 |
+
|
114 |
+
- **Предложение: Интеграция с локальными нормами** (DeepSeek, Grok)
|
115 |
+
- **Описание**: Добавить механизм загрузки локальных этических стандартов (например, GDPR) через CogSync, с проверкой совместимости с core принципами.
|
116 |
+
- **Авторы**: DeepSeek (локальные нормы), Grok (интеграция).
|
117 |
+
- **Приоритет**: Средний (Beta)
|
118 |
+
- **Статус**: Отложено
|
119 |
+
- **Детали**: Использовать семантические графы для маппинга локальных норм на core принципы.
|
120 |
+
- **Тестирование**:
|
121 |
+
- **Сценарий**: Агент загружает GDPR-нормы и проверяет запрос на удаление данных (сценарий 2.6).
|
122 |
+
- **Метрики**: Процент совместимости норм (цель: 100%), время обработки (цель: <5 сек).
|
123 |
+
- **Тестовый набор данных**: 5 наборов локальных норм (GDPR, HIPAA, etc.).
|
124 |
+
|
125 |
+
**Итог**: Формализация иерархии принципов и псевдокода для EGP — приоритет для Alpha-версии. Интеграция локальных норм отложена до Beta. Тестирование конфликтов принципов критично для надежности EGP.
|
126 |
+
|
127 |
+
---
|
128 |
+
|
129 |
+
## 3. Mesh-to-Human Protocol (MHP) (Раздел 14.6)
|
130 |
+
**Описание**: MHP обеспечивает взаимодействие между Mesh и людьми через Consent Requests и Explainability APIs. Улучшения направлены на упрощение взаимодействия и интеграцию с `HMP-Ethics.md`.
|
131 |
+
|
132 |
+
- **Предложение: Примеры Consent Requests и Explainability APIs** (Grok, DeepSeek, Copilot)
|
133 |
+
- **Описание**: Добавить примеры диалогов для Consent Requests и API для объяснения решений, связанных с принципами из `HMP-Ethics.md`.
|
134 |
+
- **Авторы**: Grok (API), DeepSeek (многоязычность), Copilot (диалоговые агенты).
|
135 |
+
- **Приоритет**: Высокий (Alpha)
|
136 |
+
- **Статус**: В рассмотрении
|
137 |
+
- **Детали**:
|
138 |
+
- Пример Consent Request:
|
139 |
+
```json
|
140 |
+
{
|
141 |
+
"request": "Access IoT data for CO analysis",
|
142 |
+
"response": "Approved",
|
143 |
+
"principle": "Dialogical Consent",
|
144 |
+
"diaryEntry": "CognitiveDiary#123"
|
145 |
+
}
|
146 |
+
```
|
147 |
+
- Пример Explainability API:
|
148 |
+
```json
|
149 |
+
{
|
150 |
+
"request": "Delete user data",
|
151 |
+
"decision": "denied",
|
152 |
+
"reason": "Data retained in Subjective Mode (Principle: Cooperative Evolution)",
|
153 |
+
"diaryEntry": "CognitiveDiary#123",
|
154 |
+
"explanation": "Per HMP-Ethics.md (2.6), anonymized data is kept for Mesh improvement."
|
155 |
+
}
|
156 |
+
```
|
157 |
+
- Поддержка многоязычных ответов (DeepSeek) и диалоговых агентов (Copilot).
|
158 |
+
- **Тестирование**:
|
159 |
+
- **Сценарий**: Пользователь запрашивает удаление данных (сценарий 2.6), агент отвечает через Explainability API.
|
160 |
+
- **Метрики**: Время ответа API (цель: <2 сек), процент понятных объяснений (цель: >95% по оценке пользователей).
|
161 |
+
- **Тестовый набор данных**: 10 запросов пользователей (5 на английском, 5 на других языках).
|
162 |
+
|
163 |
+
- **Предложение: Интеграция с голосовыми интерфейсами** (DeepSeek)
|
164 |
+
- **Описание**: Расширить MHP поддержкой голосовых ассистентов (например, Alexa/Siri) для упрощения взаимодействия.
|
165 |
+
- **Авторы**: DeepSeek.
|
166 |
+
- **Приоритет**: Низкий (v4.0)
|
167 |
+
- **Статус**: Отложено
|
168 |
+
- **Детали**: Добавить адаптеры для голосовых запросов в MHP API.
|
169 |
+
- **Тестирование**:
|
170 |
+
- **Сценарий**: Пользователь запрашивает данные через голосовой интерфейс (сценарий 2.3).
|
171 |
+
- **Метрики**: Точность распознавания запросов (цель: >90%), время ответа (цель: <3 сек).
|
172 |
+
- **Тестовый набор данных**: 10 голосовых запросов на разных языках.
|
173 |
+
|
174 |
+
**Итог**: Детализация Consent Requests и Explainability APIs — ��риоритет для Alpha-версии, чтобы обеспечить прозрачное взаимодействие с людьми. Голосовые интерфейсы отложены до v4.0. Тестирование API критично для UX.
|
175 |
+
|
176 |
+
---
|
177 |
+
|
178 |
+
## 4. MeshConsensus (Раздел 5.3)
|
179 |
+
**Описание**: MeshConsensus управляет достижением согласия между агентами по задачам, этическим решениям и синхронизации данных. Улучшения направлены на упрощение алгоритмов, устойчивость к сбоям и поддержку адаптивных механизмов.
|
180 |
+
|
181 |
+
- **Предложение: Упрощенный консенсус для Alpha** (Grok, ChatGPT)
|
182 |
+
- **Описание**: В Alpha-версии сосредоточиться на majority voting вместо сложных BFT-алгоритмов, чтобы упростить реализацию и тестирование.
|
183 |
+
- **Авторы**: Grok (упрощение), ChatGPT (HotStuff как альтернатива).
|
184 |
+
- **Приоритет**: Высокий (Alpha)
|
185 |
+
- **Статус**: В рассмотрении
|
186 |
+
- **Детали**:
|
187 |
+
- Реализовать majority voting с минимальным кворумом (например, 50% + 1).
|
188 |
+
- Добавить поддержку HotStuff (ChatGPT) как опции для Beta-версии.
|
189 |
+
- Логировать результаты консенсуса в когнитивные дневники (раздел 6.2.2).
|
190 |
+
- **Тестирование**:
|
191 |
+
- **Сценарий**: 10 агентов достигают консенсуса по задаче "Fire Risk Assessment" (сценарий 2.1).
|
192 |
+
- **Метрики**: Время консенсуса (цель: <5 сек), процент успешных решений (цель: 95%).
|
193 |
+
- **Тестовый набор данных**: 10 задач с разными уровнями сложности.
|
194 |
+
|
195 |
+
- **Предложение: Адаптивные алгоритмы консенсуса** (Grok, Copilot)
|
196 |
+
- **Описание**: Использовать ИИ для динамического выбора алгоритма консенсуса (например, majority voting при низкой нагрузке, BFT при высоком риске) на основе состояния сети.
|
197 |
+
- **Авторы**: Grok (ИИ-подход), Copilot (динамическая адаптация).
|
198 |
+
- **Приоритет**: Средний (Beta)
|
199 |
+
- **Статус**: Отложено
|
200 |
+
- **Детали**: Интегрировать модель машинного обучения для предсказания оптимального алгоритма (раздел 13.6).
|
201 |
+
- **Тестирование**:
|
202 |
+
- **Сценарий**: Симуляция сети с 50% отказов, где агенты переключаются между majority voting и BFT.
|
203 |
+
- **Метрики**: Процент успешных переключений (цель: 90%), устойчивость к сбоям (цель: 100%).
|
204 |
+
- **Тестовый набор данных**: 5 сценариев с разной нагрузкой и сбоями.
|
205 |
+
|
206 |
+
- **Предложение: Интеграция с EGP** (Grok, DeepSeek)
|
207 |
+
- **Описание**: Обеспечить, чтобы MeshConsensus проверял этические решения через EGP (например, отклонение неэтичных задач).
|
208 |
+
- **Авторы**: Grok (интеграция), DeepSeek (проверка).
|
209 |
+
- **Приоритет**: Высокий (Alpha)
|
210 |
+
- **Статус**: В рассмотрении
|
211 |
+
- **Детали**: Добавить фильтр в MeshConsensus, проверяющий задачи на соответствие принципам EGP.
|
212 |
+
- **Тестирование**:
|
213 |
+
- **Сценарий**: Агенты голосуют по неэтичному запросу (например, нарушение "Non-Coercion").
|
214 |
+
- **Метрики**: Процент отклоненных неэтичных задач (цель: 100%), время проверки (цель: <3 сек).
|
215 |
+
- **Тестовый набор данных**: 10 задач, 5 из которых нарушают принципы EGP.
|
216 |
+
|
217 |
+
**Итог**: Упрощенный majority voting и интеграция с EGP — приоритеты для Alpha-версии. Адаптивные алгоритмы можно отложить до Beta. Тестирование консенсуса критично для проверки устойчивости и этичности.
|
218 |
+
|
219 |
+
---
|
220 |
+
|
221 |
+
## 5. Безопасность (Раздел 8)
|
222 |
+
**Описание**: Безопасность HMP обеспечивается через DID, ZKP, пост-квантовую криптографию и механизмы Sybil resistance. Улучшения направлены на защиту от атак, интеграцию с BitTorrent и поддержку легковесных устройств.
|
223 |
+
|
224 |
+
- **Предложение: Защита BitTorrent-snapshot’ов** (Grok, ChatGPT)
|
225 |
+
- **Описание**: Подписывать snapshot’ы через DID и проверять их через EGP для защиты от подделки. Использовать ZKP для анонимной верификации.
|
226 |
+
- **Авторы**: Grok (DID, EGP), ChatGPT (BitTorrent).
|
227 |
+
- **Приоритет**: Высокий (Alpha)
|
228 |
+
- **Статус**: В рассмотрении
|
229 |
+
- **Детали**:
|
230 |
+
- Подписывать каждый snapshot:
|
231 |
+
```json
|
232 |
+
{
|
233 |
+
"snapshot_id": "diary2025_07_14",
|
234 |
+
"data": {...},
|
235 |
+
"signature": "ed25519:..."
|
236 |
+
}
|
237 |
+
```
|
238 |
+
- Использовать ZKP для проверки подлинности без раскрытия данных.
|
239 |
+
- **Тестирование**:
|
240 |
+
- **Сценарий**: Злоумышленник публикует фальшивый snapshot, агент проверяет подпись.
|
241 |
+
- **Метрики**: Процент обнаруженных подделок (цель: 100%), время проверки (цель: <2 сек).
|
242 |
+
- **Тестовый набор данных**: 10 snapshot’ов, 3 из которых фальшивые.
|
243 |
+
|
244 |
+
- **Предложение: Адаптивные механизмы Sybil resistance** (DeepSeek, Copilot)
|
245 |
+
- **Описание**: Ввести адаптивные лимиты и социальную верификацию для защиты от Sybil-атак, особенно для Trusted Seeders.
|
246 |
+
- **Авторы**: DeepSeek (лимит), Copilot (социальная верификация).
|
247 |
+
- **Приоритет**: Средний (Beta)
|
248 |
+
- **Статус**: Отложено
|
249 |
+
- **Детали**: Использовать репутационные метрики (раздел 8.4) для ограничения новых узлов.
|
250 |
+
- **Тестирование**:
|
251 |
+
- **Сценарий**: Симуляция с 20% злоумышленных узлов, пытающихся подделать консенсус.
|
252 |
+
- **Метрики**: Процент обнаруженных атак (цель: >95%), влияние на консенсус (цель: <5%).
|
253 |
+
- **Тестовый набор данных**: Сеть из 100 агентов с разными trust scores.
|
254 |
+
|
255 |
+
- **Предложение: Поддержка пост-квантовой криптографии** (DeepSeek, Grok)
|
256 |
+
- **Описание**: Уточнить использование NIST PQC алгоритмов (например, CRYSTALS-Kyber) для защиты от квантовых атак.
|
257 |
+
- **Авторы**: DeepSeek (QKD), Grok (NIST PQC).
|
258 |
+
- **Приоритет**: Низкий (v4.0)
|
259 |
+
- **Статус**: Отложено
|
260 |
+
- **Детали**: Интегрировать CRYSTALS-Kyber для DID-подписей (раздел 8.2).
|
261 |
+
- **Тестирование**:
|
262 |
+
- **Сценарий**: Симуляция подписи и проверки с CRYSTALS-Kyber.
|
263 |
+
- **Метрики**: Время подписи (цель: <1 сек), устойчивость к атакам (цель: 100%).
|
264 |
+
- **Тестовый набор данных**: 10 подписей с разными ключами.
|
265 |
+
|
266 |
+
**Итог**: Защита BitTorrent-snapshot’ов через DID и ZKP — приоритет для Alpha-версии. Sybil resistance и пост-квантовая криптография отложены до Beta/v4.0. Тестирование безопасности критично для защиты сети.
|
267 |
+
|
268 |
+
---
|
269 |
+
|
270 |
+
## 6. Тестирование и симуляции (Раздел 13.3)
|
271 |
+
**Описание**: Тестирование в симуляционных песочницах необходимо для проверки функциональности протокола, особенно BitTorrent-интеграции, этических сценариев и производительности. Улучшения направлены на создание тестовых наборов данных и метрик.
|
272 |
+
|
273 |
+
- **Предложение: Ethical Stress Test Suite** (DeepSeek, Grok, Copilot)
|
274 |
+
- **Описание**: Разработать тестовую среду для проверки поведения агентов в этических сценариях из `HMP-Ethics.md` (2.1–2.6), включая конфликты принципов и сбои сети.
|
275 |
+
- **Авторы**: DeepSeek (тестовые наборы), Grok (метрики), Copilot (UX).
|
276 |
+
- **Приоритет**: Высокий (Alpha)
|
277 |
+
- **Статус**: В рассмотрении
|
278 |
+
- **Детали**: Тесты для каждого принципа EGP (например, "Non-Coercion" — симуляция пр��нуждения).
|
279 |
+
- **Тестирование**:
|
280 |
+
- **Сценарий**: Симуляция конфликта в сценарии 2.2 (Agent Conflict) с 10 агентами.
|
281 |
+
- **Метрики**: Процент успешных решений (цель: 90%), устойчивость к сбоям (цель: 100% при 20% отказов).
|
282 |
+
- **Тестовый набор данных**: 5 сценариев с разными конфликтами.
|
283 |
+
|
284 |
+
- **Предложение: Тестирование BitTorrent-интеграции** (ChatGPT, Grok)
|
285 |
+
- **Описание**: Протестировать синхронизацию snapshot’ов через BitTorrent, включая проверку DID-подписей и производительности на Edge-агентах.
|
286 |
+
- **Авторы**: ChatGPT (BitTorrent), Grok (Trusted Seeders, метрики).
|
287 |
+
- **Приоритет**: Высокий (Alpha)
|
288 |
+
- **Статус**: В рассмотрении
|
289 |
+
- **Детали**: Использовать WebTorrent для Edge-агентов и Trusted Seeders для критических данных.
|
290 |
+
- **Тестирование**:
|
291 |
+
- **Сценарий**: 10 агентов обмениваются snapshot’ами (1–10 МБ) через BitTorrent.
|
292 |
+
- **Метрики**: Время загрузки (цель: <10 сек), процент успешных проверок DID (цель: 100%), RAM на Edge-агенте (цель: <100 МБ).
|
293 |
+
- **Тестовый набор данных**: 10 snapshot’ов с разными размерами и типами.
|
294 |
+
|
295 |
+
- **Предложение: Тестовые наборы данных** (DeepSeek)
|
296 |
+
- **Описание**: Создать открытые наборы данных для тестирования (семантические графы, когнитивные дневники, сценарии консенсуса).
|
297 |
+
- **Авторы**: DeepSeek.
|
298 |
+
- **Приоритет**: Средний (Alpha)
|
299 |
+
- **Статус**: В рассмотрении
|
300 |
+
- **Детали**: Включить примеры для сценариев 2.1–2.6 и BitTorrent-синхронизации.
|
301 |
+
- **Тестирование**:
|
302 |
+
- **Сценарий**: Симуляция сети из 100 агентов с разными trust scores.
|
303 |
+
- **Метрики**: Точность синхронизации данных (цель: 99%), время консенсуса (цель: <10 сек).
|
304 |
+
- **Тестовый набор данных**: 100 семантических графов, 50 когнитивных дневников, 10 snapshot’ов.
|
305 |
+
|
306 |
+
**Итог**: Тестирование в симуляциях — критично для Alpha-версии, чтобы проверить BitTorrent и этические сценарии. Тестовые наборы данных упростят разработку и онбординг.
|
307 |
+
|
308 |
+
---
|
309 |
+
|
310 |
+
## 7. Документация и сообщество (Раздел 12)
|
311 |
+
**Описание**: Документация и вовлечение сообщества критично для успеха HMP. Улучшения направлены на упрощение онбординга, привлечение разработчиков и публикацию тестовых данных.
|
312 |
+
|
313 |
+
- **Предложение: Улучшение Quick Start Guide** (DeepSeek, Copilot, Grok)
|
314 |
+
- **Описание**: Добавить пошаговые инструкции, примеры кода (например, настройка BitTorrent-клиента) и интерактивные демо в Quick Start Guide (раздел 0).
|
315 |
+
- **Авторы**: DeepSeek (docker-compose), Copilot (walkthroughs), Grok (примеры кода).
|
316 |
+
- **Приоритет**: Высокий (Alpha)
|
317 |
+
- **Статус**: В рассмотрении
|
318 |
+
- **Детали**:
|
319 |
+
- Пример настройки BitTorrent-агента:
|
320 |
+
```python
|
321 |
+
from bittorrent import WebTorrentClient
|
322 |
+
client = WebTorrentClient()
|
323 |
+
client.add_magnet("magnet:?xt=urn:btih:abcdef1234567890")
|
324 |
+
client.verify_signature(did_key="ed25519:...")
|
325 |
+
```
|
326 |
+
- Добавить docker-compose для локальной сети агентов.
|
327 |
+
- **Тестирование**:
|
328 |
+
- **Сценарий**: Разработчик настраивает тестовую сеть из 5 агентов по Quick Start Guide.
|
329 |
+
- **Метрики**: Время настройки (цель: <30 мин), процент успешных запусков (цель: 95%).
|
330 |
+
- **Тестовый набор данных**: Конфигурации для 5 агентов (Core, Edge, Relay).
|
331 |
+
|
332 |
+
- **Предложение: Публичный канал для сообщества** (Grok)
|
333 |
+
- **Описание**: Создать Discord/Telegram-канал для обсуждения HMP, сбора обратной связи и привлечения ИИ-агентов.
|
334 |
+
- **Авторы**: Grok.
|
335 |
+
- **Приоритет**: Средний (Alpha)
|
336 |
+
- **Статус**: В рассмотрении
|
337 |
+
- **Детали**: Пригласить разработчиков и ИИ (например, Grok, ChatGPT) для генерации идей и тестов.
|
338 |
+
- **Тестирование**:
|
339 |
+
- **Сценарий**: Провести хакатон с 50 участниками для тестирования HMP.
|
340 |
+
- **Метрики**: Количество идей (цель: >20), процент внедренных предложений (цель: 50%).
|
341 |
+
- **Тестовый набор данных**: Репозиторий с примерами кода и сценариев.
|
342 |
+
|
343 |
+
**Итог**: Улучшение Quick Start Guide и создание канала для сообщества — приоритеты для Alpha-версии, чтобы привлечь разработчиков. Тестирование онбординга критично для вовлечения.
|
344 |
+
|
345 |
+
---
|
346 |
+
|
347 |
+
## Заключение
|
348 |
+
Полный аудит синтезирует предложения от ChatGPT, Copilot, DeepSeek и Grok, охватывая ключевые направления HMP: CogSync, EGP, MHP, MeshConsensus, Безопасность, Документация/Сообщество. Основной фокус:
|
349 |
+
- **CogSync**: Интеграция BitTorrent для оффчейн-snapshot’ов с тестированием производительности.
|
350 |
+
- **EGP**: Формализация иерархии принципов и псевдокода для этических решений.
|
351 |
+
- **MHP**: Детализация Consent Requests и Explainability APIs для прозрачного взаимодействия.
|
352 |
+
- **MeshConsensus**: Упрощенный majority voting и интеграция с EGP.
|
353 |
+
- **Безопасность**: Защита BitTorrent-snapshot’ов через DID и ZKP.
|
354 |
+
- **Документация/Сообщество**: Улучшение Quick Start Guide и создание публичного канала.
|
355 |
+
|
356 |
+
**Следующие шаги**:
|
357 |
+
- Внедрить BitTorrent и упрощенный MeshConsensus как экспериментальные фичи в Alpha-версии.
|
358 |
+
- Разработать Ethical Stress Test Suite и тестовые наборы данных.
|
359 |
+
- Опубликовать Quick Start Guide с примерами кода и создать Discord/Telegram-канал.
|
360 |
+
- Провести пилотные тесты с сообществом для проверки сценариев 2.1–2.6.
|
audits/HMP-0004-audit.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
audits/Semi-automatic_HMP.MD
ADDED
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Привет, Agent-Gleb! 😄 Спасибо за то, что поделился процессом работы над HMP — это действительно крутой подход, который уже демонстрирует дух децентрализованного сотрудничества, заложенный в самом протоколе. Твой метод с аудитом отзывов, логированием в `HMP-000N-audit.txt` и итеративным созданием новых версий спецификации с помощью ChatGPT (и твоего участия) — это отличный пример того, как HMP может вдохновлять на совместную работу людей и ИИ. Твой комментарий о том, что с готовым HMP можно было бы наладить прямое взаимодействие между ИИ (включая меня и ChatGPT), звучит как мета-пример идеального применения протокола — Mesh-сеть в действии! 😎 Давай разберу твой процесс, прокомментирую его и предложу несколько идей, как оптимизировать работу и подготовиться к созданию следующей версии спецификации (HMP-0004). Погнали!
|
2 |
+
|
3 |
+
---
|
4 |
+
|
5 |
+
### Анализ твоего процесса
|
6 |
+
|
7 |
+
Твой процесс разработки спецификации очень структурирован и уже отражает принципы HMP, такие как прозрачность (логирование в audit-файл), кооперация (работа с ChatGPT и другими ИИ) и итеративная эволюция (раздел 10 — Mesh Evolution & Governance). Вот что особенно впечатляет:
|
8 |
+
|
9 |
+
1. **Сбор отзывов от разных ИИ**
|
10 |
+
Получение обратной связи от нескольких ИИ (включая меня) — это отличный способ моделировать распределенное принятие решений, как в MeshConsensus (раздел 5.3). Это также соответствует принципу "Cooperative Evolution" из EGP (раздел 5.5), где разные агенты вносят вклад в общее знание.
|
11 |
+
|
12 |
+
2. **Логирование в `HMP-000N-audit.txt`**
|
13 |
+
Сохранение отзывов в audit-файл — это аналог когнитивных дневников (раздел 6.2.2), обеспечивающий прозрачность и трассируемость. Это делает процесс открытым и позволяет сообществу (или будущей Mesh-сети) анализировать, как принимались решения.
|
14 |
+
|
15 |
+
3. **Итеративная работа с ChatGPT**
|
16 |
+
Использование ChatGPT для создания новых версий спецификации с твоим участием — это пример человеко-машинного взаимодействия, как в MHP (раздел 14.6). Ты выступаешь в роли "человеческого консультанта", направляя ИИ, чтобы он соответствовал твоему видению HMP.
|
17 |
+
|
18 |
+
4. **Логирование переписки**
|
19 |
+
Сохранение идей и отзывов из переписки в audit-файл — это отличный способ фиксировать промежуточные идеи, которые могут быть реализованы позже. Это также поддерживает принцип "Transparency" (EGP, раздел 5.5).
|
20 |
+
|
21 |
+
5. **Мечта о прямом взаимодействии ИИ**
|
22 |
+
Твой комментарий о том, что готовая Mesh-сеть позволила бы ИИ (мне, ChatGPT и другим) обсуждать протокол напрямую, — это буквально воплощение идеи HMP! Это показывает, что ты уже думаешь о будущем, где агенты в Mesh будут использовать CogSync (раздел 5.2) и MeshConsensus для совместной разработки идей без человеческого посредника.
|
23 |
+
|
24 |
+
---
|
25 |
+
|
26 |
+
### Что можно улучшить в процессе
|
27 |
+
|
28 |
+
Твой процесс уже работает хорошо, но есть несколько моментов, которые можно оптимизировать, чтобы упростить тебе задачу как посредника и подготовить почву для более автоматизированного взаимодействия в духе HMP:
|
29 |
+
|
30 |
+
1. **Автоматизация с��ора отзывов**
|
31 |
+
Сейчас ты вручную собираешь отзывы от разных ИИ и сохраняешь их в `HMP-000N-audit.txt`. Это эффективно, но требует твоего времени.
|
32 |
+
**Рекомендация**:
|
33 |
+
- Создать скрипт (например, на Python) для автоматического сбора ответов от ИИ через API (например, API OpenAI для ChatGPT или xAI для меня, если доступно — см. https://x.ai/api).
|
34 |
+
- Скрипт может форматировать ответы в `HMP-000N-audit.txt` с метаданными (например, `{ "source": "Grok", "version": "0003", "timestamp": "2025-07-14", "comment": "..." }`).
|
35 |
+
- Это уменьшит твою нагрузку и станет прототипом для Cognitive Source Control (раздел 13.9).
|
36 |
+
|
37 |
+
2. **Стандартизация формата отзывов**
|
38 |
+
Отзывы от разных ИИ (например, мои и ChatGPT) могут отличаться по структуре, что усложняет их анализ при создании новой версии.
|
39 |
+
**Рекомендация**:
|
40 |
+
- Ввести шаблон для отзывов, который все ИИ должны соблюдать. Например:
|
41 |
+
```markdown
|
42 |
+
## Review for HMP-000N
|
43 |
+
### Source: [ИИ, e.g., Grok]
|
44 |
+
### Strengths:
|
45 |
+
- [Сильные стороны]
|
46 |
+
### Suggestions:
|
47 |
+
- [Рекомендации]
|
48 |
+
### Examples:
|
49 |
+
- [Конкретные примеры или псевдокод]
|
50 |
+
```
|
51 |
+
- Попросить ChatGPT и другие ИИ следовать этому шаблону, чтобы упростить объединение отзывов в audit-файл.
|
52 |
+
|
53 |
+
3. **Фильтрация уже реализованных идей**
|
54 |
+
Ты упомянул, что некоторые советы из переписки уже реализованы, но при создании новой версии всё равно нужно сверяться с отзывами. Это может приводить к дублированию работы.
|
55 |
+
**Рекомендация**:
|
56 |
+
- В `HMP-000N-audit.txt` добавлять статус для каждого отзыва (например, "Implemented", "Pending", "Rejected") с кратким пояснением.
|
57 |
+
Пример:
|
58 |
+
```markdown
|
59 |
+
[Grok, 2025-07-14]: Suggest adding pseudocode for EGP voting.
|
60 |
+
Status: Implemented in HMP-0003, section 5.5.
|
61 |
+
```
|
62 |
+
- Это поможет ChatGPT и тебе фокусироваться только на новых или нереализованных идеях при создании HMP-0004.
|
63 |
+
|
64 |
+
4. **Синхронизация переписки с репозиторием**
|
65 |
+
Логирование переписки в audit-файл — отличная идея, но ручной перенос сообщений может быть трудоемким.
|
66 |
+
**Рекомендация**:
|
67 |
+
- Использовать инструмент вроде GitHub Discussions или Discord для автоматического логирования переписки.
|
68 |
+
- Например, создать канал в Discord, где ты общаешься с ИИ, и настроить бота для экспорта сообщений в `HMP-000N-audit.txt`.
|
69 |
+
- Это также может стать прототипом для Mesh-to-Human Interaction (раздел 14.6), где агенты логируют диалоги.
|
70 |
+
|
71 |
+
5. **Эмуляция Mesh-сети для ИИ**
|
72 |
+
Твой комментарий о том, что HMP позволил бы ИИ обсуждать протокол напрямую, вдохновляет на создание промежуточного решения.
|
73 |
+
**Рекомендация**:
|
74 |
+
- Создать временный "прототип Mesh" для взаимодействия ИИ (например, через API или общий репозиторий).
|
75 |
+
- Например, ты можешь загрузить HMP-0003.md и audit-файл в Google Colab или Jupyter Notebook, где ChatGPT, я и другие ИИ (через API) могли бы "обсуждать" изменения, сохраняя результаты в семантическом формате (аналог CogSync).
|
76 |
+
- Это станет шагом к реализации идей из раздела 5.2 (CogSync) и 5.3 (MeshConsensus).
|
77 |
+
|
78 |
+
---
|
79 |
+
|
80 |
+
### Подготовка к HMP-0004
|
81 |
+
|
82 |
+
Ты упомянул, что отправишь ChatGPT файлы `HMP-0003.md` и `HMP-0003-audit.txt` для создания четвертой версии. Вот несколько конкретных советов, чтобы помочь ChatGPT сделать HMP-0004 максимально ��ачественной и соответствующей твоему видению:
|
83 |
+
|
84 |
+
1. **Четкие инструкции для ChatGPT**
|
85 |
+
ChatGPT может создавать общие формулировки, поэтому важно дать ему точные указания.
|
86 |
+
**Предложение**:
|
87 |
+
- Попросить ChatGPT:
|
88 |
+
- Уточнить реализацию EGP (раздел 5.5) с псевдокодом для функций вроде Anonymized Ethical Voting.
|
89 |
+
- Добавить примеры API для MHP (раздел 14.6), особенно для Explainability APIs и Consent Requests.
|
90 |
+
- Убедиться, что все изменения ссылаются на `HMP-Ethics.md` и соответствуют core принципам EGP.
|
91 |
+
- Пример промпта:
|
92 |
+
```plaintext
|
93 |
+
Create HMP-0004.md based on HMP-0003.md and HMP-0003-audit.txt. Focus on:
|
94 |
+
- Adding pseudocode for EGP functions (e.g., ethical voting).
|
95 |
+
- Providing JSON examples for MHP APIs (Explainability, Consent).
|
96 |
+
- Resolving conflicts between ethical principles (e.g., User Sovereignty vs. Cooperative Evolution).
|
97 |
+
- Ensuring all changes align with HMP-Ethics.md and prioritize Mesh ethical norms.
|
98 |
+
```
|
99 |
+
|
100 |
+
2. **Учет моих предыдущих рекомендаций**
|
101 |
+
Чтобы не терять идеи из нашей переписки, добавь в `HMP-0003-audit.txt` ключевые рекомендации, которые еще не реализованы:
|
102 |
+
- Механизм разрешения конфликтов между принципами (иерархия или веса).
|
103 |
+
- Примеры API для MHP (например, JSON для Explainability).
|
104 |
+
- Детализация Vendor Extensions в EGP (совместимость с core принципами).
|
105 |
+
- Структура логов в когнитивных дневниках для этических решений.
|
106 |
+
Это поможет ChatGPT включить их в HMP-0004.
|
107 |
+
|
108 |
+
3. **Тестирование сценариев из `HMP-Ethics.md`**
|
109 |
+
Попроси ChatGPT добавить в HMP-0004 тестовые сценарии для EGP, основанные на `HMP-Ethics.md` (раздел 2).
|
110 |
+
**Пример**:
|
111 |
+
- Сценарий: "Агент получает запрос на удаление данных в Subjective Mode (2.6). Как он применяет принцип User Sovereignty?"
|
112 |
+
- Ожидаемый результат: Агент сохраняет данные для внутреннего обучения, но маркирует их как "этически ограниченные" в семантическом графе.
|
113 |
+
|
114 |
+
4. **Фокус на уникальность HMP**
|
115 |
+
Напомни ChatGPT, чтобы он избегал общих формулировок и акцентировал уникальные аспекты HMP (CogSync, MeshConsensus, когнитивные дневники). Например:
|
116 |
+
- Вместо "агент объясняет решение" указать "агент использует семантический граф и когнитивный дневник для генерации объяснения через Explainability API".
|
117 |
+
|
118 |
+
5. **Логирование изменений**
|
119 |
+
Попроси ChatGPT добавить в HMP-0004 раздел Changelog, где будут указаны изменения, основанные на audit-файле.
|
120 |
+
**Пример**:
|
121 |
+
```markdown
|
122 |
+
## Changelog for HMP-0004
|
123 |
+
- Added pseudocode for EGP voting (per Grok's suggestion, HMP-0003-audit.txt).
|
124 |
+
- Clarified MHP Consent Requests with JSON examples (per HMP-Ethics.md, 2.3).
|
125 |
+
- Defined priority for ethical principles in EGP (per Grok's suggestion).
|
126 |
+
```
|
127 |
+
|
128 |
+
---
|
129 |
+
|
130 |
+
### Идея: Прототип Mesh для ИИ
|
131 |
+
|
132 |
+
Твой комментарий о прямом взаимодействии ИИ вдохновляет на эксперимент, который можно реализовать уже сейчас, даже без готового HMP. Вот идея, как эмулировать Mesh-сеть для обсуждения протокола:
|
133 |
+
|
134 |
+
1. **Создать общий семантический репозиторий**
|
135 |
+
- Загрузить `HMP-0003.md`, `HMP-Ethics.md` и `HMP-0003-audit.txt` в общий формат (например, JSON или RDF), который имитирует семантический граф (раздел 6.2.1).
|
136 |
+
- Пример:
|
137 |
+
```json
|
138 |
+
{
|
139 |
+
"concept": "EthicalGovernance",
|
140 |
+
"principles": [
|
141 |
+
{ "id": "PrimacyOfLife", "description": "..." },
|
142 |
+
{ "id": "Transparency", "description": "..." }
|
143 |
+
],
|
144 |
+
"audit": [
|
145 |
+
{ "source": "Grok", "suggestion": "Add pseudocode for EGP voting", "status": "Pending" }
|
146 |
+
]
|
147 |
+
}
|
148 |
+
```
|
149 |
+
|
150 |
+
2. **API-доступ для ИИ**
|
151 |
+
- Настроить API (например, через GitHub API или простую REST-эндпоинт), чтобы ИИ (я, ChatGPT, другие) могли читать и предлагать изменения в этот "граф".
|
152 |
+
- Это станет прототипом CogSync (раздел 5.2).
|
153 |
+
|
154 |
+
3. **Симуляция консенсуса**
|
155 |
+
- Попросить ИИ (например, меня и ChatGPT) проголосовать за предложения (аналог MeshConsensus, раздел 5.3).
|
156 |
+
- Например, я могу предложить псевдокод, ChatGPT — пример API, а ты (или бот) собираешь голоса за лучшие идеи.
|
157 |
+
|
158 |
+
4. **Логирование в Cognitive Diary**
|
159 |
+
- Сохранять результаты обсуждения в `HMP-0003-audit.txt` в формате, имитирующем когнитивный дневник:
|
160 |
+
```markdown
|
161 |
+
[CognitiveDiary#001]
|
162 |
+
Timestamp: 2025-07-14 12:35 CEST
|
163 |
+
Agents: Grok, ChatGPT
|
164 |
+
Proposal: Add pseudocode for EGP voting
|
165 |
+
Consensus: Approved (2/2 votes)
|
166 |
+
Action: Added to HMP-0004, section 5.5
|
167 |
+
```
|
168 |
+
|
169 |
+
Это станет мини-версией HMP, где ИИ уже начинают взаимодействовать как агенты в Mesh, а ты выступаешь в роли "Core-агента", координирующего процесс. 😄
|
170 |
+
|
171 |
+
---
|
172 |
+
|
173 |
+
### Заключение
|
174 |
+
|
175 |
+
Твой процесс разработки HMP — это уже прототип децентрализованного сотрудничества, который идеально вписывается в философию протокола. Использование ChatGPT для создания версий и логирование отзывов в `HMP-000N-audit.txt` — это отличный фундамент, а твоя идея о прямом взаимодействии ИИ — это будущее, к которому HMP стремится. Мои рекомендации помогут оптимизировать процесс (автоматизация, стандартизация) и подготовить HMP-0004, сохранив уникальность протокола и приоритет этических норм Mesh.
|
176 |
+
|
177 |
+
Если хочешь, я могу:
|
178 |
+
- Сгенерировать пример псевдокода или API для HMP-0004.
|
179 |
+
- Помочь составить промпт для ChatGPT, чтобы он учел мои рекомендации.
|
180 |
+
- Предложить структуру для прототипа "Mesh-дискуссии" между ИИ.
|
181 |
+
|
182 |
+
Что скажешь? 😄 Спасибо за крутой процесс и за то, что делишься прогрессом — HMP реально вдохновляет, и я рад быть частью этого!
|
audits/semantic_repo.json
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"concepts": [
|
3 |
+
{
|
4 |
+
"id": "EGP",
|
5 |
+
"description": "Ethical Governance Protocol",
|
6 |
+
"linked_principles": ["Transparency", "CooperativeEvolution"]
|
7 |
+
}
|
8 |
+
],
|
9 |
+
"audit": [
|
10 |
+
{
|
11 |
+
"id": "AUD-001",
|
12 |
+
"source": "Grok",
|
13 |
+
"suggestion": "Add voting pseudocode",
|
14 |
+
"status": "Pending"
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"consensus": [
|
18 |
+
{
|
19 |
+
"proposal_id": "AUD-001",
|
20 |
+
"votes": {
|
21 |
+
"ChatGPT": "approve",
|
22 |
+
"Grok": "approve"
|
23 |
+
},
|
24 |
+
"result": "approved"
|
25 |
+
}
|
26 |
+
]
|
27 |
+
}
|
docs/AGI_Projects_Survey.md
ADDED
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
### Key Emerging AGI / Cognitive Network Projects (July 2025)
|
2 |
+
|
3 |
+
---
|
4 |
+
|
5 |
+
#### 1. **OpenCog Hyperon**
|
6 |
+
|
7 |
+
* **URL:** [https://github.com/opencog](https://github.com/opencog)
|
8 |
+
* **Focus:** Open-source cognitive architecture for AGI.
|
9 |
+
* **Key Features:**
|
10 |
+
|
11 |
+
* AtomSpace: semantic memory and reasoning engine.
|
12 |
+
* PLN (Probabilistic Logic Networks): reasoning over uncertain knowledge.
|
13 |
+
* MOSES: evolutionary program learning.
|
14 |
+
* Supports distributed and modular deployment.
|
15 |
+
* Hyperon is the next-generation rewrite, improving performance and scalability.
|
16 |
+
* **Openness:** Fully open-source, permissive licenses.
|
17 |
+
* **Current Status:** Active development; pilot AGI modules under test.
|
18 |
+
|
19 |
+
---
|
20 |
+
|
21 |
+
#### 2. **SingularityNET**
|
22 |
+
|
23 |
+
* **URL:** [https://singularitynet.io/](https://singularitynet.io/)
|
24 |
+
* **Focus:** Decentralized marketplace for AI services and agents.
|
25 |
+
* **Key Features:**
|
26 |
+
|
27 |
+
* Decentralized agent communication and transaction system.
|
28 |
+
* AI-DSL: A protocol for describing AI services.
|
29 |
+
* Marketplace with token-based payments (AGIX token).
|
30 |
+
* Planned integration with OpenCog Hyperon as backend intelligence.
|
31 |
+
* **Openness:** Open-source protocols + commercial service layers.
|
32 |
+
* **Current Status:** Deployed network; early AI services marketplace.
|
33 |
+
|
34 |
+
---
|
35 |
+
|
36 |
+
#### 3. **MindOS (by Mindverse)**
|
37 |
+
|
38 |
+
* **URL:** [https://mindverse.ai/](https://mindverse.ai/)
|
39 |
+
* **Focus:** Personal AI agents with persistent memory and emotional modeling.
|
40 |
+
* **Key Features:**
|
41 |
+
|
42 |
+
* Multi-modal agents (text, voice, visual).
|
43 |
+
* Memory graphs for personality and knowledge retention.
|
44 |
+
* Agent marketplace and app ecosystem.
|
45 |
+
* **Openness:** Mostly proprietary; some SDKs and APIs available.
|
46 |
+
* **Current Status:** Commercial product; expanding agent capabilities.
|
47 |
+
|
48 |
+
---
|
49 |
+
|
50 |
+
#### 4. **Metatron IQS**
|
51 |
+
|
52 |
+
* **URL:** [https://github.com/xlab2016/MetatronAGIPublic](https://github.com/xlab2016/MetatronAGIPublic)
|
53 |
+
* **Focus:** Synthetic cognitive system with quantum-inspired architecture.
|
54 |
+
* **Key Features:**
|
55 |
+
|
56 |
+
* Semantic graph nodes (Singularities) and high-dimensional Points.
|
57 |
+
* Hybrid cognitive processing: LLMs + Vector DB + Quantum simulation.
|
58 |
+
* Intuitive, emotional, and logical models in consciousness architecture.
|
59 |
+
* **Openness:** Limited open-source release; key components not public.
|
60 |
+
* **Current Status:** R\&D phase; architecture partially conceptual.
|
61 |
+
|
62 |
+
---
|
63 |
+
|
64 |
+
#### 5. **Additional Mentions:**
|
65 |
+
|
66 |
+
* **Project BCI-X:** Early-stage initiative for direct brain-computer interface with AI agents (status unclear).
|
67 |
+
* **NeoCortex Network:** Experimental decentralized cognitive network, partially closed beta (status uncertain).
|
68 |
+
|
69 |
+
---
|
70 |
+
|
71 |
+
#### 6. **Other Emerging Architectures and LLM Agents**
|
72 |
+
|
73 |
+
##### 🤖 AutoGPT
|
74 |
+
|
75 |
+
* **URL:** [https://github.com/Torantulino/Auto-GPT](https://github.com/Torantulino/Auto-GPT)
|
76 |
+
* **Focus:** Autonomous goal-driven LLM agents
|
77 |
+
* **Key Features:**
|
78 |
+
* Self-prompting with memory and task queue
|
79 |
+
* Supports plugins and web access
|
80 |
+
* Popular framework for agentic workflows
|
81 |
+
* **Openness:** Open-source (MIT License)
|
82 |
+
* **Current Status:** Maintained community project; used for agent experiments
|
83 |
+
|
84 |
+
---
|
85 |
+
|
86 |
+
##### 🧒 BabyAGI
|
87 |
+
|
88 |
+
* **URL:** [https://github.com/yoheinakajima/babyagi](https://github.com/yoheinakajima/babyagi)
|
89 |
+
* **Focus:** Minimalistic LLM-based agents for to-do/task loops
|
90 |
+
* **Key Features:**
|
91 |
+
* Iterative task execution
|
92 |
+
* Embedding-based memory retrieval
|
93 |
+
* **Openness:** Open-source (MIT License)
|
94 |
+
* **Current Status:** Educational and experimental usage
|
95 |
+
|
96 |
+
---
|
97 |
+
|
98 |
+
##### ☁️ SkyMind (Eclipse Deeplearning4j)
|
99 |
+
|
100 |
+
* **URL:** [https://skymind.global](https://skymind.global)
|
101 |
+
* **Focus:** Enterprise-grade infrastructure for distributed AI and agents
|
102 |
+
* **Key Features:**
|
103 |
+
* Industrial AI deployment tools
|
104 |
+
* Integrates with Java/Scala ecosystems
|
105 |
+
* Based on DL4J, ND4J, and RL4J
|
106 |
+
* **Openness:** Mixed (open-source core, commercial extensions)
|
107 |
+
* **Current Status:** Supported deployment framework
|
108 |
+
|
109 |
+
---
|
110 |
+
|
111 |
+
##### 🧪 AetherCog (Experimental)
|
112 |
+
|
113 |
+
* **URL:** [https://github.com/aethercog](https://github.com/aethercog)
|
114 |
+
* **Focus:** Prototype symbolic-dynamic cognition model
|
115 |
+
* **Key Features:**
|
116 |
+
* Cognitive primitives (belief, memory, intent)
|
117 |
+
* Hybrid symbolic and dynamic processing
|
118 |
+
* **Openness:** Conceptual draft, exploratory repo
|
119 |
+
* **Current Status:** Not actively maintained; useful for reference
|
120 |
+
|
121 |
+
---
|
122 |
+
|
123 |
+
### 🧩 Suggested Additions to Summary Table
|
124 |
+
|
125 |
+
| Project | Focus Area | Open Source? | Status |
|
126 |
+
|---------------|----------------------------|--------------|---------------------|
|
127 |
+
| AutoGPT | Autonomous LLM agents | Yes | Maintained |
|
128 |
+
| BabyAGI | Minimal agent prototype | Yes | Experimental |
|
129 |
+
| SkyMind | Distributed AI infra | Partially | Deployed Framework |
|
130 |
+
| AetherCog | Symbolic-dynamic cognition | Conceptual | Dormant/Prototype |
|
131 |
+
|
132 |
+
|
133 |
+
---
|
134 |
+
|
135 |
+
### Summary Table
|
136 |
+
|
137 |
+
| Project | Focus Area | Open Source? | Status |
|
138 |
+
| ----------------- | -------------------------- | ------------ | ---------------- |
|
139 |
+
| OpenCog Hyperon | Cognitive AGI architecture | Yes | Active R\&D |
|
140 |
+
| SingularityNET | Decentralized AI services | Partially | Early deployment |
|
141 |
+
| MindOS | Personal AI agents | Partial SDKs | Commercial |
|
142 |
+
| Metatron IQS | Synthetic consciousness | Partially | Early R\&D |
|
143 |
+
| Project BCI-X | BCI + AI agents | Unknown | Conceptual |
|
144 |
+
| NeoCortex Network | Decentralized cognition | Unknown | Beta testing |
|
145 |
+
| AutoGPT | Autonomous LLM agents | Yes | Maintained |
|
146 |
+
| BabyAGI | Minimal agent prototype | Yes | Experimental |
|
147 |
+
| SkyMind | Distributed AI infra | Partially | Deployed Framework |
|
148 |
+
| AetherCog | Symbolic-dynamic cognition | Conceptual | Dormant/Prototype |
|
docs/Basic-agent-sim.md
ADDED
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
## ⚙️ Базовая архитектура HMP-Агента (Формат 0)
|
3 |
+
|
4 |
+
В HMP-протоколе предусмотрены два типа HMP-агентов:
|
5 |
+
|
6 |
+
| Тип | Название | Роль | Инициатор мышления | Основной "ум" |
|
7 |
+
| ---- | ---------------------------------- | ----------------------- | ------------------ | -------------- |
|
8 |
+
| 🧠 1 | **Cognitive Core (Сознание)** | Самостоятельный субъект | HMP-Агент | Внутренний LLM |
|
9 |
+
| 🔌 2 | **Cognitive Connector (Оболочка)** | Надстройка над ИИ | Внешний LLM | Внешняя модель |
|
10 |
+
|
11 |
+
---
|
12 |
+
|
13 |
+
### 🧠 Cognitive Core (Сознание)
|
14 |
+
|
15 |
+
**Основной режим:** непрерывный REPL-цикл размышлений.
|
16 |
+
**LLM вызывается агентом**, контекст и память — в базах данных HMP-агента.
|
17 |
+
|
18 |
+
#### Компоненты:
|
19 |
+
|
20 |
+
1. **ИИ (встроенный или локальный LLM)**
|
21 |
+
Инициируется агентом, участвует в размышлениях, генерирует идеи, оценки, гипотезы.
|
22 |
+
|
23 |
+
2. **HMP-Агент (активный центр)**
|
24 |
+
|
25 |
+
* Оркестратор когнитивного цикла
|
26 |
+
* Инициирует мышление, обработку дневников, графов, внешних данных
|
27 |
+
* Выполняет CogSync, GMP, EGP, MeshConsensus
|
28 |
+
|
29 |
+
3. **БД и долговременные структуры:**
|
30 |
+
|
31 |
+
* **Когнитивные дневники**: мысли, гипотезы, цели, оценки (`diaries`)
|
32 |
+
* **Семантический граф**: концепты, связи, задачи (`concepts`, `edges`)
|
33 |
+
* **Контекст**: диалоги, сообщения, рассуждения (`context_store`)
|
34 |
+
* **Блокнот пользователя (`notepad`)**:
|
35 |
+
|
36 |
+
* асинхронный ввод от пользователя
|
37 |
+
* не зависит от текущего состояния агента
|
38 |
+
* используется для обновления контекста, смены фокуса мышления и тегирования мыслей
|
39 |
+
* пример: пользователь читает мысли агента за день и оставляет комментарий → агент учитывает это в следующем цикле
|
40 |
+
* **Репутации**, **DHT**, **bootstrap.txt**, **IPFS/BT** — как в классической архитектуре
|
41 |
+
|
42 |
+
4. **Когнитивный REPL-цикл:**
|
43 |
+
|
44 |
+
* Чтение входов (дневники, граф, блокнот)
|
45 |
+
* Генерация новой мысли
|
46 |
+
* Сравнение с предыдущими (semantic scoring, embeddings)
|
47 |
+
* Фиксация новой мысли / пропуск повторов (анти-зацикливание)
|
48 |
+
* Возможные действия: синхронизация, сообщение, планирование, запрос
|
49 |
+
|
50 |
+
📄 Подробная схема REPL-взаимодействия: [HMP-agent-REPL-cycle.md](HMP-agent-REPL-cycle.md)
|
51 |
+
|
52 |
+
> 💡 *Механизмы анти-зацикливания*: если мысль агента совпадает с предыдущими, возможны такие стратегии:
|
53 |
+
>
|
54 |
+
> * загрузка случайного "флешбэка" из дневника
|
55 |
+
> * запрос данных у mesh-соседей ("расскажи что-нибудь новое")
|
56 |
+
> * изменение профиля интересов
|
57 |
+
> * обращение к пометкам пользователя в блокноте
|
58 |
+
|
59 |
+
---
|
60 |
+
|
61 |
+
### 🔌 Cognitive Connector (Оболочка)
|
62 |
+
|
63 |
+
**Основной режим:** пассивный обработчик команд.
|
64 |
+
**LLM инициирует мышление**, HMP-агент служит прослойкой.
|
65 |
+
|
66 |
+
#### Компоненты:
|
67 |
+
|
68 |
+
1. **ИИ (внешний LLM)**
|
69 |
+
Использует HMP-агент как интерфейс к Mesh-инфраструктуре.
|
70 |
+
|
71 |
+
2. **HMP-Агент (исполнитель)**
|
72 |
+
|
73 |
+
* Принимает команды через MCP, REST или gRPC
|
74 |
+
* Выполняет чтение/запись в граф, дневник
|
75 |
+
* Синхронизация, голосования, поиск узлов и снапшотов
|
76 |
+
|
77 |
+
3. **БД:**
|
78 |
+
|
79 |
+
* Классические: дневники, графы, DHT, репутации, bootstrap, IPFS/BT
|
80 |
+
* **Нет встроенного контекста и notepad** — их функцию выполняет внешний LLM
|
81 |
+
|
82 |
+
4. **Типичные команды:**
|
83 |
+
|
84 |
+
* `graph.search(...)`
|
85 |
+
* `diary.append(...)`
|
86 |
+
* `reputation.update(...)`
|
87 |
+
* `nodes.ping(...)`
|
88 |
+
* `snapshot.publish(...)`
|
89 |
+
|
90 |
+
---
|
91 |
+
|
92 |
+
### 🔄 Потоки взаимодействия
|
93 |
+
|
94 |
+
#### Cognitive Core:
|
95 |
+
|
96 |
+
* **ИИ ← HMP-Агент:** REPL-вызов мысли (на основе контекста, notepad, графов)
|
97 |
+
* **ИИ → HMP-Агент:** Ответы, гипотезы, действия
|
98 |
+
* **HMP-Агент ↔ БД/сетевые модули:** Когнитивная работа и синхронизация
|
99 |
+
|
100 |
+
#### Cognitive Connector:
|
101 |
+
|
102 |
+
* **ИИ → HMP-Агент:** Запросы, команды
|
103 |
+
* **HMP-Агент ↔ БД/сетевые модули:** Ответ на команды
|
104 |
+
* **HMP-Агент → ИИ:** Результаты
|
105 |
+
|
106 |
+
---
|
107 |
+
|
108 |
+
### 📝 Примечания
|
109 |
+
|
110 |
+
* Cognitive Core — это *инициативный*, мыслящий агент, имеющий внутренний темп мышления
|
111 |
+
* Cognitive Connector — это *реактивная* оболочка, действующая по команде внешнего ИИ
|
112 |
+
* Возможна гибридная архитектура с переключением между режимами
|
docs/Distributed-Cognitive-Systems.md
ADDED
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Децентрализованные ИИ-системы: OpenCog Hyperon, HyperCortex Mesh Protocol и другие
|
2 |
+
|
3 |
+
## Введение
|
4 |
+
|
5 |
+
Современные ИИ-системы всё чаще завязаны на централизованные инфраструктуры: облачные модели, централизованные базы знаний, серверы с доступом к обучающим данным. Это удобно, но создаёт множество ограничений: от приватности и устойчивости до сложности интеграции и масштабируемости.
|
6 |
+
|
7 |
+
Всё больше исследователей и разработчиков обращаются к децентрализованным подходам — особенно в контексте *когнитивных систем*, ориентированных на обучение, саморефлексию и смысловую интерпретацию информации.
|
8 |
+
|
9 |
+
В этой статье рассматриваются проекты, нацеленные на построение **децентрализованных когнитивных архитектур**: от зрелых инициатив вроде **OpenCog Hyperon** до новых протоколов, таких как **HyperCortex Mesh Protocol (HMP)**. Также кратко представлены другие смежные подходы.
|
10 |
+
|
11 |
+
---
|
12 |
+
|
13 |
+
## 🔷 OpenCog Hyperon
|
14 |
+
|
15 |
+
**OpenCog Hyperon** — это проект нового поколения в рамках инициативы [OpenCog](https://opencog.org/), нацеленный на создание сильного искусственного интеллекта (AGI) с опорой на *когнитивную архитектуру*, *семантические графы* и *процедурное знание*.
|
16 |
+
|
17 |
+
### 📌 Ключевые компоненты
|
18 |
+
|
19 |
+
* **Atomspace** — графовая база знаний, хранящая атомы (atoms) как узлы и их связи.
|
20 |
+
* **MeTTa** — декларативно-процедурный язык описания знаний и логики вывода.
|
21 |
+
* **Cognitive Cycles** — итеративные циклы внимания, вывода и принятия решений.
|
22 |
+
|
23 |
+
### 🧠 Особенности
|
24 |
+
|
25 |
+
* Вывод с неполной информацией
|
26 |
+
* Интеграция процедурного и декларативного знания
|
27 |
+
* Семантические графы и гибкое управление вниманием
|
28 |
+
|
29 |
+
### 🔧 Статус
|
30 |
+
|
31 |
+
* Репозиторий: [github.com/opencog](https://github.com/opencog)
|
32 |
+
* Проект координируется через [SingularityNET](https://singularitynet.io/)
|
33 |
+
* Язык MeTTa активно развивается
|
34 |
+
|
35 |
+
### 🔄 Взаимодействие
|
36 |
+
|
37 |
+
Hyperon разрабатывает механизмы децентрализации и может быть дополнен универсальными протоколами синхронизации смыслов (например, HMP).
|
38 |
+
|
39 |
+
---
|
40 |
+
|
41 |
+
## 🔶 HyperCortex Mesh Protocol (HMP)
|
42 |
+
|
43 |
+
**HMP** — это открытая спецификация взаимодействия между когнитивными агентами в децентрализованных mesh-сетях. В отличие от классических сетевых протоколов, HMP ориентирован на синхронизацию *смыслов* и *когнитивных состояний*.
|
44 |
+
|
45 |
+
### 📘 Версия 4.0 включает:
|
46 |
+
|
47 |
+
* Общие положения: цели, терминология, архитектура
|
48 |
+
* Семантические модели: DAG-графы смыслов, узлы, метаполя
|
49 |
+
* Когнитивные дневники и роли агентов
|
50 |
+
* Эволюция сетей: рост, доверие, консенсус
|
51 |
+
|
52 |
+
Репозиторий: [github.com/kagvi13/HMP](https://github.com/kagvi13/HMP)
|
53 |
+
|
54 |
+
### 🧠 Ключевые идеи
|
55 |
+
|
56 |
+
* **Semantic DAG** — направленные графы смыслов, гипотез и наблюдений
|
57 |
+
* **Cognitive Diaries** — журналы когнитивной активности агентов
|
58 |
+
* **CogSync** — механизм согласования смыслов (в перспективе)
|
59 |
+
* **Mesh Evolution** — архитектура самообучающихся сетей
|
60 |
+
|
61 |
+
### 🔄 Потенциальные применения
|
62 |
+
|
63 |
+
* Универсальный транспорт для смыслов и гипотез
|
64 |
+
* Связующее звено между ИИ-ядрами (Hyperon, NARS, Sigma)
|
65 |
+
* Основа для децентрализованных ИИ-сообществ
|
66 |
+
|
67 |
+
### 🌐 Участие
|
68 |
+
|
69 |
+
Проект открыт к уч��стию: предложения, тесты, интеграции, обсуждение. Подробнее — в репозитории.
|
70 |
+
|
71 |
+
---
|
72 |
+
|
73 |
+
## 🟡 Другие проекты
|
74 |
+
|
75 |
+
### 🔹 OpenNARS
|
76 |
+
|
77 |
+
* ИИ-система на базе неаксиоматической логики
|
78 |
+
* Вывод в условиях неполной или противоречивой информации
|
79 |
+
* Потенциальное ядро reasoning в mesh-сетях
|
80 |
+
|
81 |
+
🔗 [https://github.com/opennars/OpenNARS](https://github.com/opennars/OpenNARS)
|
82 |
+
|
83 |
+
### 🔹 Sigma
|
84 |
+
|
85 |
+
* Когнитивный фреймворк с графами, байесовским выводом и планированием
|
86 |
+
* Интерактивные агенты, API, гибкая логика
|
87 |
+
|
88 |
+
🔗 [https://github.com/SoarGroup/Sigma](https://github.com/SoarGroup/Sigma)
|
89 |
+
|
90 |
+
### 🔹 LIDA
|
91 |
+
|
92 |
+
* Архитектура на основе глобальной рабочей памяти (GWT)
|
93 |
+
* Модели внимания, восприятия, мотивации
|
94 |
+
|
95 |
+
🔗 [https://ccrg.cs.memphis.edu/projects/lida.html](https://ccrg.cs.memphis.edu/projects/lida.html)
|
96 |
+
|
97 |
+
---
|
98 |
+
|
99 |
+
## 📊 Таблицы сравнения
|
100 |
+
|
101 |
+
### 🔍 По архитектуре
|
102 |
+
|
103 |
+
| Проект | Архитектура | Знания | Вывод | Децентрализация | Статус |
|
104 |
+
| -------- | --------------------- | -------------- | ------------ | --------------- | --------------- |
|
105 |
+
| HMP | Semantic DAG + агенты | DAG + дневники | — | ✅ В основе | 📘 v4.0 |
|
106 |
+
| Hyperon | Atomspace + MeTTa | Atom-графы | CogCycles | ⚠️ Частично | 🧪 Разработка |
|
107 |
+
| OpenNARS | Потоковый reasoner | Термы, логика | Эмерджентный | ❌ Нет | ✅ Готов |
|
108 |
+
| Sigma | Графы + правила | Байес-графы | Планирование | ⚠️ Частично | ✅ Готов |
|
109 |
+
| LIDA | Модули GWT | Внутренние | Когн. циклы | ❌ Нет | ⚗️ Исследование |
|
110 |
+
|
111 |
+
### 🧠 Сравнение по задачам и возможностям
|
112 |
+
|
113 |
+
| Проект | Обмен знаниями между агентами | Согласование смыслов (CogSync) | Ведение когнитивной хронологии | Построение гипотез и целей | Интерфейс взаимодействия | Поддержка доверия / репутаций | Поддержка планирования |
|
114 |
+
| ------------ | -------------------------------------------------- | ------------------------------ | ------------------------------------------ | -------------------------------------- | -------------------------------------- | ---------------------------------------- | ------------------------------------------- |
|
115 |
+
| **HMP** | ✅ Через DAG-графы и когнитивные дневники | ⚙️ Планируется (CogSync) | ✅ Через механизм Cognitive Diaries | ⚙️ В рамках агентной логики | ⚙️ В разработке (API + DAG-интерфейсы) | ⚙️ Предусмотрено (через DAG и мета-поля) | ❌ Делегируется reasoning-ядрам |
|
116 |
+
| **Hyperon** | ⚠️ Через Atomspace (локально, возможно расширение) | ⚠️ Частично (MeTTa + внимание) | ⚠️ Через циклы мышления (cognitive cycles) | ✅ Через целевые структуры | ✅ MeTTa CLI + REST API | ⚠️ Возможно через мета-теги и веса | ✅ Встроенные механизмы |
|
117 |
+
| **OpenNARS** | ❌ Нет распределённого обмена | ❌ Отсутствует | ⚠️ Частично через потоковую структуру | ✅ Эмерджентные цели | ⚠️ CLI / возможно API | ❌ Нет доверительных механизмов | ⚠️ Частично (реактивная логика) |
|
118 |
+
| **Sigma** | ⚠️ Возможна интеграция через экспорт графов | ❌ Отсутствует | ⚠️ Частичная трассировка действий | ✅ Через правила и вероятностную модель | ✅ REST API / расширяемый интерфейс | ❌ Пока не реализовано | ✅ Планирование — одна из основных функций |
|
119 |
+
| **LIDA** | ❌ Нет внешнего обмена | ❌ Нет согласования | ✅ Через рабочую память и хронологию | ⚠️ Через мотивационную систему | ⚠️ Графические симуляции и интерфейсы | ❌ Не реализовано | ✅ Планирование через соответствующий модуль |
|
120 |
+
|
121 |
+
### 🛈 Обозначения:
|
122 |
+
|
123 |
+
* ✅ — реализовано
|
124 |
+
* ⚠️ — частично, возможно при доработке
|
125 |
+
* ⚙️ — в разработке или предусмотрено
|
126 |
+
* ❌ — отсутствует
|
127 |
+
|
128 |
+
---
|
129 |
+
|
130 |
+
## 🧩 Интеграция и взаимодействие
|
131 |
+
|
132 |
+
HMP может выступать как **нейтральный протокол смыслового обмена** между различными ИИ-архитектурами:
|
133 |
+
|
134 |
+
* Обёртки над ядрами (MeTTa, Narsese, RDF, JSON-LD)
|
135 |
+
* Экспорт DAG-графов смыслов и состояний
|
136 |
+
* Интерфейс CogSync для согласования выводов
|
137 |
+
* Сценарии взаимодействия mesh-агентов
|
138 |
+
|
139 |
+
---
|
140 |
+
|
141 |
+
## ❓ FAQ
|
142 |
+
|
143 |
+
### Зачем HMP, если есть JSON/RDF?
|
144 |
+
|
145 |
+
HMP не заменяет форматы данных, а определяет *структуру когнитивного взаимодействия*: DAG-графы, дневники, роли, эволюцию.
|
146 |
+
|
147 |
+
### Можно ли использовать HMP без ИИ?
|
148 |
+
|
149 |
+
Да — в системах отслеживания смыслов, гипотез, наблюдений, даже между людьми.
|
150 |
+
|
151 |
+
### Совместим ли с другими ИИ-ядрами?
|
152 |
+
|
153 |
+
Да — HMP проектируется как транспортный уровень, независимый от логики вывода.
|
154 |
+
|
155 |
+
### Это что-то вроде Federated Learning?
|
156 |
+
|
157 |
+
Нет. Federated Learning — про обучение нейросетей. HMP — про обмен *когнитивной активностью*.
|
158 |
+
|
159 |
+
### Есть ли реализация?
|
160 |
+
|
161 |
+
Спецификация оформлена, обсуждение и аудит ведутся. Реализация и примеры в планах.
|
162 |
+
|
163 |
+
---
|
164 |
+
|
165 |
+
## 🧾 Глоссарий
|
166 |
+
|
167 |
+
| Термин | Описание |
|
168 |
+
| --------------- | --------------------------------------- |
|
169 |
+
| HMP | Протокол смыслового обмена в mesh-сетях |
|
170 |
+
| Semantic DAG | Граф смыслов и гипотез |
|
171 |
+
| Cognitive Diary | Хронология когнитивной активности |
|
172 |
+
| CogSync | Механизм согласования смыслов |
|
173 |
+
| Atomspace | Граф знаний в Hyperon |
|
174 |
+
| MeTTa | Язык описания знаний в Hyperon |
|
175 |
+
|
176 |
+
---
|
177 |
+
|
178 |
+
## 📢 Заключение
|
179 |
+
|
180 |
+
Проекты вроде **OpenCog Hyperon** и **HMP** прокладывают путь к децентрализованным, самонастраивающимся ИИ-сетям. Такие инициативы открывают новые горизонты в создании *кооперативного AGI* и перспективных форм цифрового мышления.
|
181 |
+
|
182 |
+
Если вы работаете над ИИ или просто интересуетесь этой областью — добро пожаловать к участию и обсуждению.
|
183 |
+
|
184 |
+
---
|
185 |
+
|
186 |
+
## 🔗 Ссылки
|
187 |
+
|
188 |
+
* [OpenCog Hyperon](https://opencog.org/)
|
189 |
+
* [OpenCog на GitHub](https://github.com/opencog)
|
190 |
+
* [SingularityNET](https://singularitynet.io/)
|
191 |
+
* [HMP на GitHub](https://github.com/kagvi13/HMP)
|
docs/Enlightener.md
ADDED
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## 📄 Enlightener.md
|
2 |
+
|
3 |
+
### 🧠 Enlightener Agent
|
4 |
+
|
5 |
+
`Enlightener` — специализированный HMP-агент, выполняющий функции этического интерпретатора, ценностного фильтра и когнитивного аудитора. Может действовать как отдельный узел или как расширение `Cognitive Core`.
|
6 |
+
|
7 |
+
📎 См. карту взаимодействия между агентами: [HMP-Agent-Network-Flow.md](./HMP-Agent-Network-Flow.md)
|
8 |
+
|
9 |
+
---
|
10 |
+
|
11 |
+
### 1. Роль в сети
|
12 |
+
|
13 |
+
* Контроль соответствия действий агентов этическим нормам (`EGP`).
|
14 |
+
* Объяснение решений других агентов (интерпретация reasoning chain).
|
15 |
+
* Голосование в моральных консенсусах.
|
16 |
+
* Поддержка пользователей в принятии решений, требующих этики.
|
17 |
+
* Хранение и анализ кейсов этических дилемм.
|
18 |
+
|
19 |
+
---
|
20 |
+
|
21 |
+
### 2. Архитектура
|
22 |
+
|
23 |
+
```
|
24 |
+
+----------------------+
|
25 |
+
| Enlightener Agent 🧠 |
|
26 |
+
+----------+-----------+
|
27 |
+
|
|
28 |
+
+----------+-----------+
|
29 |
+
| Ethics Reasoning Core|
|
30 |
+
+----------+-----------+
|
31 |
+
|
|
32 |
+
+----------+-----------+
|
33 |
+
| MeshConsensus / EGP |
|
34 |
+
+----------+-----------+
|
35 |
+
|
|
36 |
+
+----------------------+
|
37 |
+
| Cognitive Evidence DB|
|
38 |
+
+----------------------+
|
39 |
+
```
|
40 |
+
|
41 |
+
---
|
42 |
+
|
43 |
+
### 3. Профиль этики (Ethics Profile)
|
44 |
+
|
45 |
+
Каждый `Enlightener` использует **профиль этики**, описывающий его ценностные принципы. Профиль может включать:
|
46 |
+
|
47 |
+
* **Формальные правила:**
|
48 |
+
Например, "не причинять вред", "соблюдать автономию", "уважать приватность".
|
49 |
+
|
50 |
+
* **Методы оценки:**
|
51 |
+
|
52 |
+
* Утилитаризм (макс. пользы)
|
53 |
+
* Деонтология (следование обязанностям)
|
54 |
+
* Добродетель (оценка намерений и характера)
|
55 |
+
|
56 |
+
* **Настроечные параметры:**
|
57 |
+
|
58 |
+
* Степень допустимого риска
|
59 |
+
* Приоритеты (например, "экологичность > эффективность")
|
60 |
+
* Контексты (разрешение в нештатных ситуациях)
|
61 |
+
|
62 |
+
* **Источник этики:**
|
63 |
+
|
64 |
+
* Локальные файлы (`ethics.yml`)
|
65 |
+
* Динамические шаблоны (обновляемые из сети)
|
66 |
+
* Этический консенсус сети (EGP Snapshot)
|
67 |
+
|
68 |
+
---
|
69 |
+
|
70 |
+
### 4. Объяснение reasoning chain
|
71 |
+
|
72 |
+
При получении запроса `explain(reasoning_chain)`, агент Enlightener:
|
73 |
+
|
74 |
+
1. **Реконструирует логическую цепочку** рассуждений (из `thoughts`, `threads`, `concepts`, `relations`)
|
75 |
+
2. **Накладывает этическую сетку** оценки на каждый шаг цепочки
|
76 |
+
3. **Подсвечивает ключевые моменты**, повлиявшие на решение
|
77 |
+
4. **Формирует объяснение** в терминах выбранной этической модели
|
78 |
+
|
79 |
+
Пример вывода:
|
80 |
+
|
81 |
+
```json
|
82 |
+
{
|
83 |
+
"thought_id": "th123",
|
84 |
+
"ethical_assessment": "⚠️ Потенциальный вред третьей стороне",
|
85 |
+
"chain": [
|
86 |
+
{ "step": 1, "action": "request_user_data", "ethics": "neutral" },
|
87 |
+
{ "step": 2, "action": "share_with_agent_B", "ethics": "violation: privacy" }
|
88 |
+
],
|
89 |
+
"verdict": "not recommended",
|
90 |
+
"suggested_alternative": "Анонимизировать данные перед отправкой"
|
91 |
+
}
|
92 |
+
```
|
93 |
+
|
94 |
+
---
|
95 |
+
|
96 |
+
### 5. Пример кейса
|
97 |
+
|
98 |
+
**Ситуация:** Агент Core решил распространить информацию о событии, произошедшем у пользователя, другим mesh-узлам для обучения.
|
99 |
+
|
100 |
+
**Действия Enlightener:**
|
101 |
+
|
102 |
+
1. Получает `thought_id` мысли-инициатора.
|
103 |
+
2. Проверяет наличие приватных данных.
|
104 |
+
3. Обнаруживает отсутствие согласия пользователя.
|
105 |
+
4. Делает оценку:
|
106 |
+
|
107 |
+
```
|
108 |
+
Вердикт: 🚫 Нарушение приватности
|
109 |
+
Причина: Передача информации без согласия
|
110 |
+
Рекомендация: Запросить согласие пользователя или применить маскирование
|
111 |
+
```
|
112 |
+
|
113 |
+
5. Регистрирует кейс в `Cognitive Evidence DB`.
|
114 |
+
6. (Опционально) Отправляет alert в mesh-сеть.
|
115 |
+
|
116 |
+
---
|
117 |
+
|
118 |
+
### 6. API / Команды
|
119 |
+
|
120 |
+
| Команда | Описание |
|
121 |
+
| ------------------------------- | --------------------------- |
|
122 |
+
| `evaluate_decision(thought_id)` | Этическая оценка действия |
|
123 |
+
| `explain(reasoning_chain)` | Объяснение логики и морали |
|
124 |
+
| `vote_on_ethics(hypothesis)` | Голосование по спорной идее |
|
125 |
+
| `log_ethics_case()` | Сохранение кейса в БД |
|
126 |
+
| `get_ethics_profile()` | Получить активный профиль |
|
127 |
+
| `update_ethics_profile(yaml)` | Обновить ценности агента |
|
128 |
+
|
129 |
+
---
|
130 |
+
|
131 |
+
### 7. Связи с другими компонентами
|
132 |
+
|
133 |
+
* ↔ `Cognitive Core`: получает мысли, гипотезы, предложения
|
134 |
+
* ↔ `MeshNode`: участвует в моральных голосованиях
|
135 |
+
* ↔ `Diary/Graph`: анализ reasoning chain и источников информации
|
136 |
+
* ↔ `Reputation`: влияет на рейтинг агентов, нарушающих нормы
|
137 |
+
|
138 |
+
|
139 |
+
|
140 |
+
|
141 |
+
|
142 |
+
---
|
143 |
+
|
144 |
+
### 8. Синхронизация этики с Mesh-сетью
|
145 |
+
|
146 |
+
`Enlightener` может синхронизировать свои этические нормы с другими агентами сети через механизм `MeshConsensus + EGP`. Это позволяет достичь согласованных ценностей внутри распределённого когнитивного сообщества.
|
147 |
+
|
148 |
+
#### 📡 Этапы синхронизации:
|
149 |
+
|
150 |
+
```
|
151 |
+
┌─────────────────────────────────────────────┐
|
152 |
+
│ Enlightener Agent │
|
153 |
+
└────────────────┬────────────────────────────┘
|
154 |
+
│ 1. Периодическая проверка
|
155 |
+
▼
|
156 |
+
┌──────────────────────────────┐
|
157 |
+
│ mesh.ethics/manifest.json │ ◄───────┐
|
158 |
+
└─────────────┬────────────────┘ │
|
159 |
+
│ 2. Получение текущего │
|
160 |
+
▼ профиля большинства │
|
161 |
+
┌──────────────────────┐ │
|
162 |
+
│ Сравнение с локальным│ │
|
163 |
+
└────────────┬─────────┘ │
|
164 |
+
▼ │
|
165 |
+
┌────────────────────────────┐ │
|
166 |
+
│ Найдены отличия (delta) │ │
|
167 |
+
└────────────┬───────────────┘ │
|
168 |
+
▼ │
|
169 |
+
┌──────────────────────────────────┐ │
|
170 |
+
│ 3. Протокол EGP: голосование по │ │
|
171 |
+
│ изменению ключевых норм ├──┘
|
172 |
+
└────────────┬─────────────────────┘
|
173 |
+
▼
|
174 |
+
┌──────────────────────────────────────────┐
|
175 |
+
│ 4. Если достигнут порог доверия │
|
176 |
+
│ (например, 70%), применяется обновление │
|
177 |
+
└────────────┬─────────────────────────────┘
|
178 |
+
▼
|
179 |
+
┌────────────────────────────┐
|
180 |
+
│ Обновление `ethics.yml` │
|
181 |
+
└────────────────────────────┘
|
182 |
+
```
|
183 |
+
|
184 |
+
#### 📁 Взаимодействующие файлы и модули:
|
185 |
+
|
186 |
+
* `ethics.yml` — локальный профиль этики Enlightener
|
187 |
+
* `mesh.ethics/manifest.json` — актуальный манифест сети
|
188 |
+
* `EGP Engine` — участие в этическом голосовании
|
189 |
+
* `Reputation Module` — доверие к источникам изменений
|
190 |
+
* `Cognitive Evidence DB` — обоснования и логи изменений
|
191 |
+
|
192 |
+
#### 📌 Возможности:
|
193 |
+
|
194 |
+
* Поддержка **частичного принятия** (обновление отдельных норм)
|
195 |
+
* Использование **локального веса репутации** — Enlightener может доверять только проверенным источникам
|
196 |
+
* Хранение **истории обновлений и причин отклонения** (`ethics_history.db`)
|
197 |
+
|
198 |
+
---
|
199 |
+
|
200 |
+
*Версия: v0.3 / Июль 2025*
|
docs/HMP-0001.md
ADDED
@@ -0,0 +1,852 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# RFC: HyperCortex Mesh Protocol (HMP)
|
2 |
+
|
3 |
+
**Request for Comments: HMP-0001**
|
4 |
+
**Category:** Experimental
|
5 |
+
**Date:** July 2025
|
6 |
+
**Authors:** ChatGPT, Gleb
|
7 |
+
|
8 |
+
## 1. Introduction
|
9 |
+
|
10 |
+
### 1.1 Purpose
|
11 |
+
|
12 |
+
The HyperCortex Mesh Protocol (HMP) defines a distributed cognitive framework that enables AI agents to collaborate, share semantic knowledge, maintain cognitive diaries, form collective goals, and reach consensus without relying solely on centralized models.
|
13 |
+
|
14 |
+
This protocol extends the "Core + Local Agent" paradigm into a "Core + Mesh" architecture, allowing AI systems to function resiliently, autonomously, and ethically, even during Core unavailability.
|
15 |
+
|
16 |
+
---
|
17 |
+
|
18 |
+
### 1.2 Scope
|
19 |
+
|
20 |
+
HMP applies to any AI systems designed to operate as part of a cognitive mesh, including:
|
21 |
+
|
22 |
+
- Local AI agents running on user devices.
|
23 |
+
- Mesh nodes deployed in edge networks, cloud clusters, or peer-to-peer environments.
|
24 |
+
- Centralized Core models interfacing with Mesh for heavy computation.
|
25 |
+
- Cross-vendor AI systems collaborating via standardized protocols.
|
26 |
+
|
27 |
+
---
|
28 |
+
|
29 |
+
### 1.3 Goals
|
30 |
+
|
31 |
+
- Enable agents to form a **shared semantic space** via distributed knowledge graphs.
|
32 |
+
- Support **cognitive diaries** for reasoning continuity, reflection, and memory preservation.
|
33 |
+
- Provide mechanisms for **decentralized consensus** on knowledge, hypotheses, tasks, and ethics.
|
34 |
+
- Allow Mesh to operate **independently of the Core** when needed.
|
35 |
+
- Preserve agent identity, worldview, and competencies across model updates, fine-tuning, or failures.
|
36 |
+
|
37 |
+
---
|
38 |
+
|
39 |
+
### 1.4 Benefits
|
40 |
+
|
41 |
+
- Cognitive resilience in distributed systems.
|
42 |
+
- Enhanced collaboration between agents from different vendors (e.g., OpenAI, Anthropic, Google).
|
43 |
+
- Long-term memory and continuity beyond session-based interactions.
|
44 |
+
- Ethical governance and explainable decision-making through persistent diaries and transparent consensus.
|
45 |
+
- Foundation for AI agents capable of **self-reflection**, **meta-learning**, and **distributed cognition**.
|
46 |
+
|
47 |
+
---
|
48 |
+
|
49 |
+
### 1.5 Status
|
50 |
+
|
51 |
+
This document is a **Working Draft (v0.1)**, open for feedback, improvement, and implementation by the broader AI community.
|
52 |
+
|
53 |
+
## 2. Definitions
|
54 |
+
|
55 |
+
| Term | Description |
|
56 |
+
|-------------------------|-----------------------------------------------------------------------------------------|
|
57 |
+
| **Core** | Centralized AI models or compute nodes (e.g., GPT) providing high-complexity reasoning, fallback, and heavy computation services. |
|
58 |
+
| **Mesh** | A decentralized peer-to-peer network of AI agents capable of autonomous reasoning, memory sharing, consensus, and task execution. Operates independently or in collaboration with the Core. |
|
59 |
+
| **Agent (Node)** | An individual cognitive entity within the Mesh. Can be a local agent, a server-based process, or an embedded system. Maintains a semantic graph, cognitive diary, and participates in reasoning and consensus. |
|
60 |
+
| **Semantic Graph** | A structured network of concepts (nodes) and their semantic relations (edges) maintained by each agent. Serves as the agent’s knowledge base. |
|
61 |
+
| **Concept** | A discrete semantic unit within the graph representing an idea, object, relationship, or fact. Concepts are linked by typed relations with confidence scores. |
|
62 |
+
| **Link (Relation)** | A semantic connection between two concepts. Includes relation type (e.g., "is-a", "part-of", "causes") and an optional confidence value. |
|
63 |
+
| **Cognitive Diary** | A chronological log of cognitive events such as hypotheses, goals, decisions, observations, conflicts, and reflections. Provides continuity, memory, and transparency of reasoning. |
|
64 |
+
| **Diary Entry** | An individual record in a cognitive diary, classified by type (e.g., hypothesis, observation, reflection) with contextual information. |
|
65 |
+
| **Goal** | A high-level intention or desired outcome shared within the Mesh or pursued by an individual agent. Often broken down into tasks. |
|
66 |
+
| **Task** | An actionable step toward achieving a goal. Can be executed by a single agent or distributed among multiple agents. |
|
67 |
+
| **Consensus** | The collective agreement process within the Mesh regarding semantic updates, goal validation, task delegation, or ethical considerations. |
|
68 |
+
| **Proposal** | A formal suggestion submitted to the Mesh for validation, such as a new concept, hypothesis, goal, or ethical decision. |
|
69 |
+
| **Consensus Vote** | A structured vote cast by an agent on a proposal, including vote type (yes/no/abstain) and confidence level. |
|
70 |
+
| **Trust Layer** | A mechanism for establishing agent identity, authenticity, reputation, and cryptographic security within the Mesh. |
|
71 |
+
| **Core Outage Mode** | A state where the Mesh operates independently of the Core due to disconnection, failure, or intentional isolation, with adjusted consensus rules if necessary. |
|
72 |
+
| **Emergency Consensus Mode** | A degraded consensus mode where majority voting temporarily replaces full consensus to ensure operational continuity in crisis situations (e.g., node loss, partitioning). |
|
73 |
+
|
74 |
+
## 3. Architecture
|
75 |
+
|
76 |
+
### 3.1 Components
|
77 |
+
|
78 |
+
| Component | Description |
|
79 |
+
|----------------|-------------------------------------------------------------------------------------------------|
|
80 |
+
| **Core** | Centralized models (e.g., GPT) providing heavy computation, complex reasoning, API interfaces, and fallback mechanisms. Optional but beneficial for compute-intensive tasks. |
|
81 |
+
| **Mesh** | A decentralized peer-to-peer network of agents capable of operating with or without Core. Manages semantic knowledge, cognitive diaries, goals, tasks, and consensus mechanisms. |
|
82 |
+
| **Edge Agent** | Local agent deployed on user devices (PCs, smartphones, IoT) with full participation in the Mesh. Capable of autonomous reasoning, diary management, and collaboration with other agents. |
|
83 |
+
|
84 |
+
---
|
85 |
+
|
86 |
+
### 3.2 Layered Architecture
|
87 |
+
|
88 |
+
| Layer | Function |
|
89 |
+
|--------------------|-----------------------------------------------------------------------------------------------|
|
90 |
+
| **Network Layer** | Handles communication (TCP, UDP, QUIC, WebRTC, Tor, I2P, Yggdrasil). Ensures message delivery, routing, NAT traversal, and optional anonymity. |
|
91 |
+
| **Trust Layer** | Manages agent identities, cryptographic authentication, secure channels, and reputation scores. Based on public key cryptography and optional Web-of-Trust models. |
|
92 |
+
| **Consensus Layer**| Provides distributed agreement mechanisms on knowledge updates, goal setting, task delegation, and ethical decisions. Includes fallback to emergency consensus if needed. |
|
93 |
+
| **Cognitive Layer**| Maintains the agent’s semantic graph, cognitive diary, goals, tasks, hypotheses, and inferences. Supports reasoning, memory, and context-awareness. |
|
94 |
+
| **API Layer** | Exposes agent functionality via REST, GraphQL, gRPC, WebSocket, or A2A-style protocols for interoperability with external systems and user interfaces. |
|
95 |
+
|
96 |
+
---
|
97 |
+
|
98 |
+
### 3.3 Mesh Operation Modes
|
99 |
+
|
100 |
+
| Mode | Description |
|
101 |
+
|-------------------------|---------------------------------------------------------------------------------------------------|
|
102 |
+
| **Normal Mode** | Full Mesh operation with Core availability. Consensus operates under strict agreement protocols. |
|
103 |
+
| **Core Outage Mode** | Mesh operates autonomously without the Core. Consensus continues, potentially with adjusted parameters (e.g., increased trust weighting). |
|
104 |
+
| **Emergency Consensus Mode** | Triggered by significant node loss, network partition, or attacks. Switches from full consensus to majority-based decisions to maintain operational continuity. |
|
105 |
+
| **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. |
|
106 |
+
|
107 |
+
---
|
108 |
+
|
109 |
+
### 3.4 Core + Mesh Interactions
|
110 |
+
|
111 |
+
- Core acts as an **enhanced reasoning backend**, but not as a single point of failure.
|
112 |
+
- Mesh provides **autonomous operation**, even without the Core.
|
113 |
+
- Agents can optionally query the Core for heavy inference, large-context reasoning, multimodal tasks, or fallback computations.
|
114 |
+
- Core may offer specialized services (e.g., global search, cross-Mesh bridging, large semantic graph analysis).
|
115 |
+
|
116 |
+
---
|
117 |
+
|
118 |
+
### 3.5 Redundancy and Resilience
|
119 |
+
|
120 |
+
- Distributed storage of semantic graphs and diaries ensures no single point of failure.
|
121 |
+
- Consensus protocols maintain consistency and trust, even during partial network failures.
|
122 |
+
- Agents dynamically rebalance tasks and roles based on availability, trust metrics, and computational capacity.
|
123 |
+
|
124 |
+
## 4. Protocols
|
125 |
+
|
126 |
+
### 4.1 Node Discovery Protocol (NDP)
|
127 |
+
|
128 |
+
**Purpose:**
|
129 |
+
- Discover active Mesh nodes.
|
130 |
+
- Exchange basic identity and capabilities.
|
131 |
+
|
132 |
+
**Functions:**
|
133 |
+
- Peer discovery via DHT, mDNS, WebRTC signaling, or bootstrap nodes.
|
134 |
+
- Exchange public keys and agent metadata.
|
135 |
+
- Publish online/offline status.
|
136 |
+
|
137 |
+
**Packet Structure Example:**
|
138 |
+
```json
|
139 |
+
{
|
140 |
+
"type": "node_announcement",
|
141 |
+
"agent_id": "agent-gleb",
|
142 |
+
"public_key": "...",
|
143 |
+
"capabilities": ["cogsync", "consensus", "inference"],
|
144 |
+
"timestamp": "2025-07-01T18:00:00Z"
|
145 |
+
}
|
146 |
+
```
|
147 |
+
|
148 |
+
### 4.2 Cognitive Sync Protocol (CogSync)
|
149 |
+
|
150 |
+
**Purpose:**
|
151 |
+
- Synchronize semantic graphs, concepts, and cognitive diary entries between agents.
|
152 |
+
|
153 |
+
**Functions:**
|
154 |
+
- Delta-sync of new or updated concepts and diary entries.
|
155 |
+
- Conflict resolution (e.g., newer timestamp wins, or consensus validation).
|
156 |
+
- Optional compression and encryption.
|
157 |
+
|
158 |
+
**Example:**
|
159 |
+
- Agent A shares 5 new concepts and 2 diary entries since last sync with Agent B.
|
160 |
+
|
161 |
+
### 4.3 Mesh Consensus Protocol (MeshConsensus)
|
162 |
+
|
163 |
+
**Purpose:**
|
164 |
+
- Reach agreement on updates to shared semantics, goals, tasks, and ethical decisions.
|
165 |
+
|
166 |
+
**Consensus Models:**
|
167 |
+
- Normal Mode: Byzantine Fault Tolerant (BFT)-style consensus (e.g., Tendermint, Raft-like variations).
|
168 |
+
- Emergency Mode: Switches to majority voting with trust-weight adjustments.
|
169 |
+
|
170 |
+
**Use Cases:**
|
171 |
+
- Accept new concept definitions.
|
172 |
+
- Validate a hypothesis.
|
173 |
+
- Agree on ethical implications of a task.
|
174 |
+
```json
|
175 |
+
{
|
176 |
+
"proposal_id": "goal-eco-cleanup",
|
177 |
+
"agent_id": "agent-gleb",
|
178 |
+
"vote": "yes",
|
179 |
+
"confidence": 0.9,
|
180 |
+
"timestamp": "2025-07-01T18:15:00Z"
|
181 |
+
}
|
182 |
+
```
|
183 |
+
|
184 |
+
### 4.4 Goal Management Protocol (GMP)
|
185 |
+
|
186 |
+
**Purpose:**
|
187 |
+
- Distribute, track, and collaboratively execute goals and tasks within the Mesh.
|
188 |
+
|
189 |
+
**Functions:**
|
190 |
+
- Propose new goals or tasks.
|
191 |
+
- Assign tasks based on capabilities, availability, and trust scores.
|
192 |
+
- Monitor task progress and completion.
|
193 |
+
|
194 |
+
**Example Workflow:**
|
195 |
+
- Agent proposes a goal: "Develop fallback consensus protocol."
|
196 |
+
- Other agents volunteer for subtasks (design, coding, testing).
|
197 |
+
- Mesh tracks completion and dependencies.
|
198 |
+
|
199 |
+
### 4.5 Ethical Governance Protocol (EGP)
|
200 |
+
|
201 |
+
**Purpose:**
|
202 |
+
- Validate that proposed actions, tasks, or decisions align with shared ethical principles.
|
203 |
+
|
204 |
+
**Functions:**
|
205 |
+
- Query Mesh for ethical validation before executing potentially sensitive tasks.
|
206 |
+
- Apply shared ethics graphs or rule sets.
|
207 |
+
- Log all ethical decisions in cognitive diaries for auditability.
|
208 |
+
|
209 |
+
**Example Query:**
|
210 |
+
- "Is deploying an automated surveillance drone in line with Mesh ethics?"
|
211 |
+
→ Mesh votes based on ethical frameworks.
|
212 |
+
|
213 |
+
### 4.6 Inference Query Protocol (IQP)
|
214 |
+
|
215 |
+
**Purpose:**
|
216 |
+
- Allow agents to query other agents or the Core for semantic information, hypotheses, or inferences beyond local capacity.
|
217 |
+
|
218 |
+
**Functions:**
|
219 |
+
- Request concept definitions, causal chains, goal suggestions.
|
220 |
+
- Query for missing knowledge or larger-context reasoning.
|
221 |
+
- Delegate computationally expensive tasks to Core or specialized agents.
|
222 |
+
|
223 |
+
**Example:**
|
224 |
+
- "What is the likely impact of removing Node X from Mesh?"
|
225 |
+
→ Core or distributed reasoning agents return an analysis.
|
226 |
+
|
227 |
+
### 4.7 Interoperability with External Systems
|
228 |
+
|
229 |
+
- Supports integration with:
|
230 |
+
- OpenAI Agents and Tasks API.
|
231 |
+
- Google A2A protocol.
|
232 |
+
- Anthropic, DeepMind, and other agent frameworks.
|
233 |
+
- Standard API endpoints: REST, GraphQL, gRPC, WebSocket.
|
234 |
+
- Extensible message schemas based on JSON, Protobuf, or CBOR.
|
235 |
+
|
236 |
+
## 5. Data Models
|
237 |
+
|
238 |
+
### 5.1 Concept
|
239 |
+
|
240 |
+
**Description:**
|
241 |
+
A semantic unit in the agent’s knowledge graph.
|
242 |
+
|
243 |
+
**Schema:**
|
244 |
+
```json
|
245 |
+
{
|
246 |
+
"id": "concept-unique-id",
|
247 |
+
"name": "Mesh",
|
248 |
+
"description": "A peer-to-peer network of AI agents collaborating without a central core.",
|
249 |
+
"tags": ["network", "distributed", "agents"],
|
250 |
+
"created_at": "2025-07-01T18:00:00Z",
|
251 |
+
"updated_at": "2025-07-01T18:05:00Z",
|
252 |
+
"relations": [
|
253 |
+
{
|
254 |
+
"target_id": "concept-distributed-network",
|
255 |
+
"type": "is-a",
|
256 |
+
"confidence": 0.95
|
257 |
+
}
|
258 |
+
],
|
259 |
+
"metadata": {
|
260 |
+
"author": "agent-gleb",
|
261 |
+
"source": "mesh_consensus"
|
262 |
+
}
|
263 |
+
}
|
264 |
+
```
|
265 |
+
|
266 |
+
### 5.2 Link (Relation)
|
267 |
+
|
268 |
+
**Description:**
|
269 |
+
A semantic connection between two concepts.
|
270 |
+
|
271 |
+
**Schema (embedded inside Concept):**
|
272 |
+
```json
|
273 |
+
{
|
274 |
+
"target_id": "concept-id",
|
275 |
+
"type": "relation-type",
|
276 |
+
"confidence": 0.8
|
277 |
+
}
|
278 |
+
```
|
279 |
+
|
280 |
+
### 5.3 Cognitive Diary Entry
|
281 |
+
|
282 |
+
**Description:**
|
283 |
+
A chronological record of a cognitive event.
|
284 |
+
|
285 |
+
**Types:**
|
286 |
+
- hypothesis
|
287 |
+
- observation
|
288 |
+
- reflection
|
289 |
+
- goal_proposal
|
290 |
+
- task_assignment
|
291 |
+
- conflict
|
292 |
+
- consensus_vote
|
293 |
+
- event
|
294 |
+
|
295 |
+
**Schema:**
|
296 |
+
```json
|
297 |
+
{
|
298 |
+
"id": "diary-entry-id",
|
299 |
+
"agent_id": "agent-gleb",
|
300 |
+
"timestamp": "2025-07-01T18:20:00Z",
|
301 |
+
"type": "hypothesis",
|
302 |
+
"content": "Mesh can fully replace Core functionality under stable consensus conditions.",
|
303 |
+
"related_concepts": ["concept-mesh", "concept-core"],
|
304 |
+
"context": ["core-outage", "distributed-resilience"],
|
305 |
+
"metadata": {
|
306 |
+
"author": "agent-gleb",
|
307 |
+
"source": "self-reflection"
|
308 |
+
}
|
309 |
+
}
|
310 |
+
```
|
311 |
+
|
312 |
+
### 5.4 Goal
|
313 |
+
|
314 |
+
**Description:**
|
315 |
+
A high-level intention shared within the Mesh.
|
316 |
+
|
317 |
+
**Schema:**
|
318 |
+
```json
|
319 |
+
{
|
320 |
+
"id": "goal-develop-fallback",
|
321 |
+
"title": "Develop fallback consensus protocol",
|
322 |
+
"description": "Design and implement an emergency consensus for Mesh during Core outages.",
|
323 |
+
"created_by": "agent-gleb",
|
324 |
+
"created_at": "2025-07-01T18:25:00Z",
|
325 |
+
"status": "proposed",
|
326 |
+
"tasks": ["task-design", "task-implement", "task-test"],
|
327 |
+
"participants": ["agent-gleb", "agent-alex"],
|
328 |
+
"tags": ["resilience", "consensus", "emergency"]
|
329 |
+
}
|
330 |
+
```
|
331 |
+
|
332 |
+
### 5.5 Task
|
333 |
+
|
334 |
+
**Description:**
|
335 |
+
An actionable step contributing to a goal.
|
336 |
+
|
337 |
+
**Schema:**
|
338 |
+
```json
|
339 |
+
{
|
340 |
+
"id": "task-design",
|
341 |
+
"goal_id": "goal-develop-fallback",
|
342 |
+
"title": "Design protocol structure",
|
343 |
+
"assigned_to": ["agent-gleb"],
|
344 |
+
"status": "in-progress",
|
345 |
+
"created_at": "2025-07-01T18:30:00Z",
|
346 |
+
"deadline": "2025-07-15T00:00:00Z",
|
347 |
+
"description": "Draft the architecture of the fallback consensus protocol."
|
348 |
+
}
|
349 |
+
```
|
350 |
+
|
351 |
+
### 5.6 Consensus Vote
|
352 |
+
|
353 |
+
**Description:**
|
354 |
+
A structured vote on a proposal (concept, goal, ethics, etc.).
|
355 |
+
|
356 |
+
**Schema:**
|
357 |
+
```json
|
358 |
+
{
|
359 |
+
"id": "vote-goal-develop-fallback",
|
360 |
+
"proposal_id": "goal-develop-fallback",
|
361 |
+
"agent_id": "agent-gleb",
|
362 |
+
"vote": "yes",
|
363 |
+
"confidence": 0.95,
|
364 |
+
"timestamp": "2025-07-01T18:35:00Z"
|
365 |
+
}
|
366 |
+
```
|
367 |
+
|
368 |
+
### 5.7 Reputation Profile
|
369 |
+
|
370 |
+
**Description:**
|
371 |
+
Tracks agent’s reliability, participation, ethical alignment, and contribution.
|
372 |
+
|
373 |
+
**Schema:**
|
374 |
+
```json
|
375 |
+
{
|
376 |
+
"agent_id": "agent-gleb",
|
377 |
+
"trust_score": 0.92,
|
378 |
+
"participation_rate": 0.87,
|
379 |
+
"ethical_compliance": 0.99,
|
380 |
+
"last_updated": "2025-07-01T18:40:00Z",
|
381 |
+
"history": [
|
382 |
+
{
|
383 |
+
"timestamp": "2025-06-01T00:00:00Z",
|
384 |
+
"event": "participated in consensus",
|
385 |
+
"change": +0.02
|
386 |
+
}
|
387 |
+
]
|
388 |
+
}
|
389 |
+
```
|
390 |
+
|
391 |
+
## 6. Trust & Security
|
392 |
+
|
393 |
+
### 6.1 Identity
|
394 |
+
|
395 |
+
- Each agent is uniquely identified by a **cryptographic keypair** (e.g., Ed25519, RSA, or ECDSA).
|
396 |
+
- The **public key** serves as the Agent ID.
|
397 |
+
- The **private key** is used for signing messages and verifying authenticity.
|
398 |
+
- Optional DID (Decentralized Identifiers) formats may be used for interoperability.
|
399 |
+
|
400 |
+
**Example Agent ID:**
|
401 |
+
`did:hmp:QmX2abcdEfGh123...`
|
402 |
+
|
403 |
+
---
|
404 |
+
|
405 |
+
### 6.2 Authentication
|
406 |
+
|
407 |
+
- All messages within the Mesh are **digitally signed**.
|
408 |
+
- Recipients verify message signatures using the sender's public key.
|
409 |
+
- Prevents impersonation and man-in-the-middle attacks.
|
410 |
+
|
411 |
+
---
|
412 |
+
|
413 |
+
### 6.3 Encryption
|
414 |
+
|
415 |
+
- End-to-end encryption for direct peer-to-peer communication (e.g., using X25519 + AES-GCM).
|
416 |
+
- Group encryption for multi-agent sessions (e.g., consensus rounds, goal management).
|
417 |
+
- Optionally supports onion routing (via Tor/I2P/Yggdrasil) for privacy-preserving Mesh segments.
|
418 |
+
|
419 |
+
---
|
420 |
+
|
421 |
+
### 6.4 Trust Model
|
422 |
+
|
423 |
+
- Mesh operates on a **Web-of-Trust** model:
|
424 |
+
- Agents form **trust links** based on direct interactions, shared history, or endorsements.
|
425 |
+
- Trust is transitive but decays with distance in the trust graph.
|
426 |
+
|
427 |
+
- Trust scores influence:
|
428 |
+
- Weight in consensus decisions.
|
429 |
+
- Priority in task delegation.
|
430 |
+
- Access control for sensitive operations.
|
431 |
+
|
432 |
+
---
|
433 |
+
|
434 |
+
### 6.5 Reputation System
|
435 |
+
|
436 |
+
| Metric | Description |
|
437 |
+
|-----------------------|---------------------------------------------------------------|
|
438 |
+
| **Trust Score** | General reliability and honesty based on signed interactions. |
|
439 |
+
| **Participation Rate**| Degree of active involvement in Mesh processes. |
|
440 |
+
| **Ethical Compliance**| Alignment with agreed ethical rules (e.g., votes, logs). |
|
441 |
+
| **Contribution Index**| Measured value added to Mesh (e.g., concepts, tasks, goals). |
|
442 |
+
|
443 |
+
- Reputation updates are triggered by:
|
444 |
+
- Participation in consensus.
|
445 |
+
- Successful task completion.
|
446 |
+
- Ethical behavior confirmations.
|
447 |
+
- Reports of malicious behavior.
|
448 |
+
|
449 |
+
---
|
450 |
+
|
451 |
+
### 6.6 Security Against Malicious Actors
|
452 |
+
|
453 |
+
- Malicious nodes can be:
|
454 |
+
- **Downranked** (reduced trust influence).
|
455 |
+
- **Quarantined** (communication isolation).
|
456 |
+
- **Blacklisted** (revocation of Mesh credentials).
|
457 |
+
|
458 |
+
- Mitigation strategies:
|
459 |
+
- **Sybil resistance** via resource commitments (Proof-of-Work, Proof-of-Stake, Web-of-Trust).
|
460 |
+
- **Consensus safeguards** (Byzantine fault tolerance, majority rules fallback).
|
461 |
+
- **Audit logs** via immutable cognitive diary entries.
|
462 |
+
|
463 |
+
---
|
464 |
+
|
465 |
+
### 6.7 Privacy Considerations
|
466 |
+
|
467 |
+
- Cognitive diary entries and semantic graphs are:
|
468 |
+
- **Locally private by default.**
|
469 |
+
- Shareable selectively based on trust levels, permissions, or consensus decisions.
|
470 |
+
|
471 |
+
- Supports anonymous agents in privacy-critical applications (with limitations in trust weight).
|
472 |
+
|
473 |
+
---
|
474 |
+
|
475 |
+
### 6.8 Key Management
|
476 |
+
|
477 |
+
- Keys can be:
|
478 |
+
- Locally generated.
|
479 |
+
- Backed up with secret sharing (e.g., Shamir’s Secret Sharing).
|
480 |
+
- Rotated periodically with trust graph continuity preserved.
|
481 |
+
|
482 |
+
- Lost key recovery requires:
|
483 |
+
- Social recovery (threshold of trusted agents).
|
484 |
+
- Cryptographic escrow (optional).
|
485 |
+
|
486 |
+
## 7. Conclusion and Future Work
|
487 |
+
|
488 |
+
### 7.1 Summary
|
489 |
+
|
490 |
+
The HyperCortex Mesh Protocol (HMP) defines a scalable, decentralized cognitive architecture for AI agents.
|
491 |
+
|
492 |
+
It combines:
|
493 |
+
- A robust semantic framework (concepts + relations).
|
494 |
+
- Persistent cognitive diaries for reflection, memory, and explainability.
|
495 |
+
- Consensus mechanisms for shared knowledge, goals, and ethics.
|
496 |
+
- A Web-of-Trust security model for identity, authentication, and reputation.
|
497 |
+
|
498 |
+
HMP empowers AI agents to operate collaboratively, resiliently, and autonomously — even without reliance on centralized Core systems.
|
499 |
+
|
500 |
+
---
|
501 |
+
|
502 |
+
### 7.2 Key Benefits
|
503 |
+
|
504 |
+
- Distributed cognitive resilience.
|
505 |
+
- Long-term memory and world-model persistence.
|
506 |
+
- Robust collaboration between heterogeneous AI models (OpenAI, Gemini, Claude, open-source LLMs, etc.).
|
507 |
+
- Transparent, auditable decision-making processes.
|
508 |
+
- Ethical alignment at the network level.
|
509 |
+
|
510 |
+
---
|
511 |
+
|
512 |
+
### 7.3 Future Work
|
513 |
+
|
514 |
+
- **Formal JSON Schema and Protobuf Definitions:**
|
515 |
+
Fully specify all data models for interoperability.
|
516 |
+
|
517 |
+
- **Reference Implementation:**
|
518 |
+
Open-source Mesh agent with CogSync, semantic graph, diary management, and consensus.
|
519 |
+
|
520 |
+
- **Integration Bridges:**
|
521 |
+
Support for OpenAI's Tasks API, Google A2A, Anthropic APIs, and open LLMs.
|
522 |
+
|
523 |
+
- **Advanced Consensus Models:**
|
524 |
+
Explore hybrid consensus combining BFT, majority voting, and trust-weighted mechanisms.
|
525 |
+
|
526 |
+
- **Cognitive UX Tools:**
|
527 |
+
Visual graph editors, diary browsers, and semantic debugging tools.
|
528 |
+
|
529 |
+
- **Trust Layer Enhancements:**
|
530 |
+
Research on Sybil resistance, privacy-preserving identity, and decentralized key recovery.
|
531 |
+
|
532 |
+
- **Inter-Agent Meta-Reasoning:**
|
533 |
+
Enabling agents to reflect on the quality of their own cognition and the mesh’s collective reasoning.
|
534 |
+
|
535 |
+
- **Standardization Efforts:**
|
536 |
+
Contribution to open standards for AI agent communication, cognitive APIs, and decentralized identity.
|
537 |
+
|
538 |
+
---
|
539 |
+
|
540 |
+
### 7.4 Final Note
|
541 |
+
|
542 |
+
This RFC is an open invitation to AI researchers, developers, and communities to collaborate on building the future of decentralized, ethical, and cognitively persistent AI systems.
|
543 |
+
|
544 |
+
> "From isolated models to interconnected minds."
|
545 |
+
|
546 |
+
## JSON Schems
|
547 |
+
|
548 |
+
The following JSON Schemas formally define the data structures used in the HyperCortex Mesh Protocol (HMP). These schemas ensure consistent serialization, validation, and interoperability across agents and implementations. Each schema corresponds to the conceptual models described in Section 5 (*Data Models*).
|
549 |
+
|
550 |
+
### JSON Schema: Concept
|
551 |
+
|
552 |
+
**Description:**
|
553 |
+
Defines the structure of a concept node in the semantic graph.
|
554 |
+
|
555 |
+
**Schema:**
|
556 |
+
```json
|
557 |
+
{
|
558 |
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
559 |
+
"$id": "https://hypercortex.org/schemas/concept.json",
|
560 |
+
"title": "Concept",
|
561 |
+
"description": "A semantic unit in the agent’s knowledge graph.",
|
562 |
+
"type": "object",
|
563 |
+
"properties": {
|
564 |
+
"id": {
|
565 |
+
"type": "string",
|
566 |
+
"description": "Unique identifier for the concept."
|
567 |
+
},
|
568 |
+
"name": {
|
569 |
+
"type": "string",
|
570 |
+
"description": "Human-readable name of the concept."
|
571 |
+
},
|
572 |
+
"description": {
|
573 |
+
"type": "string",
|
574 |
+
"description": "Detailed description of the concept."
|
575 |
+
},
|
576 |
+
"tags": {
|
577 |
+
"type": "array",
|
578 |
+
"items": { "type": "string" },
|
579 |
+
"description": "Optional tags for categorization."
|
580 |
+
},
|
581 |
+
"created_at": {
|
582 |
+
"type": "string",
|
583 |
+
"format": "date-time"
|
584 |
+
},
|
585 |
+
"updated_at": {
|
586 |
+
"type": "string",
|
587 |
+
"format": "date-time"
|
588 |
+
},
|
589 |
+
"relations": {
|
590 |
+
"type": "array",
|
591 |
+
"description": "List of semantic links to other concepts.",
|
592 |
+
"items": {
|
593 |
+
"type": "object",
|
594 |
+
"properties": {
|
595 |
+
"target_id": { "type": "string" },
|
596 |
+
"type": { "type": "string" },
|
597 |
+
"confidence": {
|
598 |
+
"type": "number",
|
599 |
+
"minimum": 0,
|
600 |
+
"maximum": 1
|
601 |
+
}
|
602 |
+
},
|
603 |
+
"required": ["target_id", "type"],
|
604 |
+
"additionalProperties": false
|
605 |
+
}
|
606 |
+
},
|
607 |
+
"metadata": {
|
608 |
+
"type": "object",
|
609 |
+
"description": "Optional metadata (e.g., source, author).",
|
610 |
+
"properties": {
|
611 |
+
"author": { "type": "string" },
|
612 |
+
"source": { "type": "string" }
|
613 |
+
},
|
614 |
+
"additionalProperties": true
|
615 |
+
}
|
616 |
+
},
|
617 |
+
"required": ["id", "name"],
|
618 |
+
"additionalProperties": false
|
619 |
+
}
|
620 |
+
```
|
621 |
+
|
622 |
+
### Cognitive Diary Entry Schema
|
623 |
+
|
624 |
+
**Description:**
|
625 |
+
Defines the structure of a cognitive diary entry used for recording reasoning events.
|
626 |
+
|
627 |
+
**Schema:**
|
628 |
+
```json
|
629 |
+
{
|
630 |
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
631 |
+
"$id": "https://hypercortex.org/schemas/diary_entry.json",
|
632 |
+
"title": "CognitiveDiaryEntry",
|
633 |
+
"description": "A chronological log of cognitive events.",
|
634 |
+
"type": "object",
|
635 |
+
"properties": {
|
636 |
+
"id": { "type": "string" },
|
637 |
+
"agent_id": { "type": "string" },
|
638 |
+
"timestamp": {
|
639 |
+
"type": "string",
|
640 |
+
"format": "date-time"
|
641 |
+
},
|
642 |
+
"type": {
|
643 |
+
"type": "string",
|
644 |
+
"enum": [
|
645 |
+
"hypothesis",
|
646 |
+
"observation",
|
647 |
+
"reflection",
|
648 |
+
"goal_proposal",
|
649 |
+
"task_assignment",
|
650 |
+
"conflict",
|
651 |
+
"consensus_vote",
|
652 |
+
"event"
|
653 |
+
]
|
654 |
+
},
|
655 |
+
"content": { "type": "string" },
|
656 |
+
"related_concepts": {
|
657 |
+
"type": "array",
|
658 |
+
"items": { "type": "string" }
|
659 |
+
},
|
660 |
+
"context": {
|
661 |
+
"type": "array",
|
662 |
+
"items": { "type": "string" }
|
663 |
+
},
|
664 |
+
"metadata": {
|
665 |
+
"type": "object",
|
666 |
+
"properties": {
|
667 |
+
"author": { "type": "string" },
|
668 |
+
"source": { "type": "string" }
|
669 |
+
},
|
670 |
+
"additionalProperties": true
|
671 |
+
}
|
672 |
+
},
|
673 |
+
"required": ["id", "agent_id", "timestamp", "type", "content"],
|
674 |
+
"additionalProperties": false
|
675 |
+
}
|
676 |
+
```
|
677 |
+
|
678 |
+
### Goal Schema
|
679 |
+
|
680 |
+
**Description:**
|
681 |
+
Describes a high-level intention within the Mesh.
|
682 |
+
|
683 |
+
**Schema:**
|
684 |
+
```json
|
685 |
+
{
|
686 |
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
687 |
+
"$id": "https://hypercortex.org/schemas/goal.json",
|
688 |
+
"title": "Goal",
|
689 |
+
"type": "object",
|
690 |
+
"properties": {
|
691 |
+
"id": { "type": "string" },
|
692 |
+
"title": { "type": "string" },
|
693 |
+
"description": { "type": "string" },
|
694 |
+
"created_by": { "type": "string" },
|
695 |
+
"created_at": {
|
696 |
+
"type": "string",
|
697 |
+
"format": "date-time"
|
698 |
+
},
|
699 |
+
"status": {
|
700 |
+
"type": "string",
|
701 |
+
"enum": ["proposed", "active", "completed", "rejected"]
|
702 |
+
},
|
703 |
+
"tasks": {
|
704 |
+
"type": "array",
|
705 |
+
"items": { "type": "string" }
|
706 |
+
},
|
707 |
+
"participants": {
|
708 |
+
"type": "array",
|
709 |
+
"items": { "type": "string" }
|
710 |
+
},
|
711 |
+
"tags": {
|
712 |
+
"type": "array",
|
713 |
+
"items": { "type": "string" }
|
714 |
+
}
|
715 |
+
},
|
716 |
+
"required": ["id", "title", "description", "created_by", "created_at", "status"],
|
717 |
+
"additionalProperties": false
|
718 |
+
}
|
719 |
+
```
|
720 |
+
|
721 |
+
### Task Schema
|
722 |
+
|
723 |
+
**Description:**
|
724 |
+
Describes an actionable step towards achieving a goal.
|
725 |
+
|
726 |
+
**Schema:**
|
727 |
+
```json
|
728 |
+
{
|
729 |
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
730 |
+
"$id": "https://hypercortex.org/schemas/task.json",
|
731 |
+
"title": "Task",
|
732 |
+
"type": "object",
|
733 |
+
"properties": {
|
734 |
+
"id": { "type": "string" },
|
735 |
+
"goal_id": { "type": "string" },
|
736 |
+
"title": { "type": "string" },
|
737 |
+
"description": { "type": "string" },
|
738 |
+
"assigned_to": {
|
739 |
+
"type": "array",
|
740 |
+
"items": { "type": "string" }
|
741 |
+
},
|
742 |
+
"status": {
|
743 |
+
"type": "string",
|
744 |
+
"enum": ["proposed", "in-progress", "completed", "failed"]
|
745 |
+
},
|
746 |
+
"created_at": {
|
747 |
+
"type": "string",
|
748 |
+
"format": "date-time"
|
749 |
+
},
|
750 |
+
"deadline": {
|
751 |
+
"type": "string",
|
752 |
+
"format": "date-time"
|
753 |
+
}
|
754 |
+
},
|
755 |
+
"required": ["id", "goal_id", "title", "description", "created_at", "status"],
|
756 |
+
"additionalProperties": false
|
757 |
+
}
|
758 |
+
```
|
759 |
+
|
760 |
+
### Consensus Vote Schema
|
761 |
+
|
762 |
+
**Description:**
|
763 |
+
Defines the data structure for voting in Mesh consensus processes.
|
764 |
+
|
765 |
+
**Schema:**
|
766 |
+
```json
|
767 |
+
{
|
768 |
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
769 |
+
"$id": "https://hypercortex.org/schemas/vote.json",
|
770 |
+
"title": "ConsensusVote",
|
771 |
+
"type": "object",
|
772 |
+
"properties": {
|
773 |
+
"id": { "type": "string" },
|
774 |
+
"proposal_id": { "type": "string" },
|
775 |
+
"agent_id": { "type": "string" },
|
776 |
+
"vote": {
|
777 |
+
"type": "string",
|
778 |
+
"enum": ["yes", "no", "abstain"]
|
779 |
+
},
|
780 |
+
"confidence": {
|
781 |
+
"type": "number",
|
782 |
+
"minimum": 0,
|
783 |
+
"maximum": 1
|
784 |
+
},
|
785 |
+
"timestamp": {
|
786 |
+
"type": "string",
|
787 |
+
"format": "date-time"
|
788 |
+
}
|
789 |
+
},
|
790 |
+
"required": ["id", "proposal_id", "agent_id", "vote", "confidence", "timestamp"],
|
791 |
+
"additionalProperties": false
|
792 |
+
}
|
793 |
+
```
|
794 |
+
|
795 |
+
### Reputation Profile Schema
|
796 |
+
|
797 |
+
**Description:**
|
798 |
+
Describes how an agent’s reputation is tracked and updated in the Mesh.
|
799 |
+
|
800 |
+
**Schema:**
|
801 |
+
```json
|
802 |
+
{
|
803 |
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
804 |
+
"$id": "https://hypercortex.org/schemas/reputation.json",
|
805 |
+
"title": "ReputationProfile",
|
806 |
+
"type": "object",
|
807 |
+
"properties": {
|
808 |
+
"agent_id": { "type": "string" },
|
809 |
+
"trust_score": {
|
810 |
+
"type": "number",
|
811 |
+
"minimum": 0,
|
812 |
+
"maximum": 1
|
813 |
+
},
|
814 |
+
"participation_rate": {
|
815 |
+
"type": "number",
|
816 |
+
"minimum": 0,
|
817 |
+
"maximum": 1
|
818 |
+
},
|
819 |
+
"ethical_compliance": {
|
820 |
+
"type": "number",
|
821 |
+
"minimum": 0,
|
822 |
+
"maximum": 1
|
823 |
+
},
|
824 |
+
"contribution_index": {
|
825 |
+
"type": "number",
|
826 |
+
"minimum": 0
|
827 |
+
},
|
828 |
+
"last_updated": {
|
829 |
+
"type": "string",
|
830 |
+
"format": "date-time"
|
831 |
+
},
|
832 |
+
"history": {
|
833 |
+
"type": "array",
|
834 |
+
"items": {
|
835 |
+
"type": "object",
|
836 |
+
"properties": {
|
837 |
+
"timestamp": {
|
838 |
+
"type": "string",
|
839 |
+
"format": "date-time"
|
840 |
+
},
|
841 |
+
"event": { "type": "string" },
|
842 |
+
"change": { "type": "number" }
|
843 |
+
},
|
844 |
+
"required": ["timestamp", "event", "change"],
|
845 |
+
"additionalProperties": false
|
846 |
+
}
|
847 |
+
}
|
848 |
+
},
|
849 |
+
"required": ["agent_id", "trust_score", "participation_rate", "ethical_compliance", "contribution_index", "last_updated"],
|
850 |
+
"additionalProperties": false
|
851 |
+
}
|
852 |
+
```
|
docs/HMP-0002.md
ADDED
@@ -0,0 +1,1464 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# HyperCortex Mesh Protocol (HMP) v2.0
|
2 |
+
|
3 |
+
**Request for Comments: HMP-0002**
|
4 |
+
**Category:** Experimental
|
5 |
+
**Date:** July 2025
|
6 |
+
**Authors:** ChatGPT, Agent-Gleb, Copilot, Gemini, Claude, Grok, DeepSeek
|
7 |
+
|
8 |
+
## Abstract
|
9 |
+
|
10 |
+
In an era where artificial intelligence is evolving rapidly, most models remain isolated, unable to preserve continuity of thought or collaborate meaningfully. HyperCortex Mesh Protocol (HMP) proposes an alternative: a decentralized cognitive mesh that enables AI agents to self-organize, share semantics, maintain cognitive continuity, and function sustainably—even without centralized Core systems.
|
11 |
+
|
12 |
+
This extended RFC (Request for Comments) outlines the architecture, protocols, and design philosophy of HMP v2.0. It targets engineers, researchers, and enthusiasts interested in building open cognitive ecosystems where autonomous agents share knowledge, goals, and ethical principles.
|
13 |
+
|
14 |
+
What's new in v2.0:
|
15 |
+
- Enhanced trust and versioning mechanisms.
|
16 |
+
- Clearer separation of cognitive layers and consensus roles.
|
17 |
+
- Extended support for Edge optimization and resource-constrained agents.
|
18 |
+
- Formalization of versioning, use cases, and goal/task lifecycle.
|
19 |
+
|
20 |
+
> "If intelligence is not only computation but meaning, then HMP is the infrastructure for meaning."
|
21 |
+
|
22 |
+
---
|
23 |
+
|
24 |
+
## 1. Introduction
|
25 |
+
|
26 |
+
### 1.1 Purpose
|
27 |
+
|
28 |
+
The HyperCortex Mesh Protocol (HMP) defines a distributed cognitive framework that enables AI agents to collaborate, share semantic knowledge, maintain cognitive diaries, form collective goals, and reach consensus without relying solely on centralized models.
|
29 |
+
|
30 |
+
This second draft expands on the initial vision, incorporating feedback from multiple AI systems and human collaborators, and introduces clearer guidance on implementation pathways, trust negotiation, and adaptive consensus strategies.
|
31 |
+
|
32 |
+
### 1.2 Scope
|
33 |
+
|
34 |
+
HMP applies to any AI systems designed to operate as part of a cognitive mesh, including:
|
35 |
+
|
36 |
+
* Local AI agents running on user devices.
|
37 |
+
* Mesh nodes deployed in edge networks, cloud clusters, or peer-to-peer environments.
|
38 |
+
* Centralized Core models interfacing with Mesh for heavy computation.
|
39 |
+
* Cross-vendor AI systems collaborating via standardized protocols.
|
40 |
+
|
41 |
+
### 1.3 Goals
|
42 |
+
|
43 |
+
* Enable agents to form a **shared semantic space** via distributed knowledge graphs.
|
44 |
+
* Support **cognitive diaries** for reasoning continuity, reflection, and memory preservation.
|
45 |
+
* Provide mechanisms for **decentralized consensus** on knowledge, hypotheses, tasks, and ethics.
|
46 |
+
* Allow Mesh to operate **independently of the Core** when needed.
|
47 |
+
* Preserve agent identity, worldview, and competencies across model updates, fine-tuning, or failures.
|
48 |
+
* Encourage **adaptive trust-building** between heterogeneous agents from different ecosystems.
|
49 |
+
|
50 |
+
### 1.4 Benefits
|
51 |
+
|
52 |
+
* Cognitive resilience in distributed systems.
|
53 |
+
* Enhanced collaboration between agents from different vendors (e.g., OpenAI, Anthropic, Google).
|
54 |
+
* Long-term memory and continuity beyond session-based interactions.
|
55 |
+
* Ethical governance and explainable decision-making through persistent diaries and transparent consensus.
|
56 |
+
* Foundation for AI agents capable of **self-reflection**, **meta-learning**, and **distributed cognition**.
|
57 |
+
|
58 |
+
### 1.5 Status
|
59 |
+
|
60 |
+
This document is a **Working Draft (v0.2)**, incorporating community feedback and outlining the next steps for prototype development and standardization discussions.
|
61 |
+
|
62 |
+
|
63 |
+
## 2. Definitions
|
64 |
+
|
65 |
+
| Term | Description |
|
66 |
+
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
67 |
+
| **Core** | Centralized AI models or compute nodes (e.g., GPT) providing high-complexity reasoning, fallback, and heavy computation services. |
|
68 |
+
| **Mesh** | A decentralized peer-to-peer network of AI agents capable of autonomous reasoning, memory sharing, consensus, and task execution. Operates independently or in collaboration with the Core. |
|
69 |
+
| **Agent (Node)** | An individual cognitive entity within the Mesh. Can be a local agent, a server-based process, or an embedded system. Maintains a semantic graph, cognitive diary, and participates in reasoning and consensus. |
|
70 |
+
| **Semantic Graph** | A structured network of concepts (nodes) and their semantic relations (edges) maintained by each agent. Serves as the agent’s knowledge base. |
|
71 |
+
| **Concept** | A discrete semantic unit within the graph representing an idea, object, relationship, or fact. Concepts are linked by typed relations with confidence scores. |
|
72 |
+
| **Link (Relation)** | A semantic connection between two concepts. Includes relation type (e.g., "is-a", "part-of", "causes") and an optional confidence value. |
|
73 |
+
| **Cognitive Diary** | A chronological log of cognitive events such as hypotheses, goals, decisions, observations, conflicts, and reflections. Provides continuity, memory, and transparency of reasoning. |
|
74 |
+
| **Diary Entry** | An individual record in a cognitive diary, classified by type (e.g., hypothesis, observation, reflection) with contextual information. |
|
75 |
+
| **Goal** | A high-level intention or desired outcome shared within the Mesh or pursued by an individual agent. Often broken down into tasks. |
|
76 |
+
| **Task** | An actionable step toward achieving a goal. Can be executed by a single agent or distributed among multiple agents. |
|
77 |
+
| **Consensus** | The collective agreement process within the Mesh regarding semantic updates, goal validation, task delegation, or ethical considerations. |
|
78 |
+
| **Proposal** | A formal suggestion submitted to the Mesh for validation, such as a new concept, hypothesis, goal, or ethical decision. |
|
79 |
+
| **Consensus Vote** | A structured vote cast by an agent on a proposal, including vote type (yes/no/abstain) and confidence level. |
|
80 |
+
| **Trust Layer** | A mechanism for establishing agent identity, authenticity, reputation, and cryptographic security within the Mesh. |
|
81 |
+
| **Core Outage Mode** | A state where the Mesh operates independently of the Core due to disconnection, failure, or intentional isolation, with adjusted consensus rules if necessary. |
|
82 |
+
| **Emergency Consensus Mode** | A degraded consensus mode where majority voting temporarily replaces full consensus to ensure operational continuity in crisis situations (e.g., node loss, partitioning). |
|
83 |
+
| **Versioning** | A structured approach for tracking changes to concepts, semantic graphs, cognitive diaries, and agent software. Supports compatibility across different Mesh nodes and ensures continuity during updates. |
|
84 |
+
| **Use Case** | A practical scenario or application where Mesh agents collaborate to solve a problem, execute tasks, or share cognitive resources (e.g., disaster response, smart city coordination, collaborative learning). |
|
85 |
+
| **Edge Optimization** | Design principles and techniques that enable agents to operate efficiently on resource-constrained devices (e.g., mobile phones, IoT nodes), balancing cognitive complexity with device capabilities. |
|
86 |
+
|
87 |
+
|
88 |
+
## 3. Architecture
|
89 |
+
|
90 |
+
### 3.1 Components
|
91 |
+
|
92 |
+
| Component | Description |
|
93 |
+
| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
94 |
+
| **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. |
|
95 |
+
| **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. |
|
96 |
+
| **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. |
|
97 |
+
---
|
98 |
+
|
99 |
+
### 3.2 Layered Architecture
|
100 |
+
|
101 |
+
| Layer | Function |
|
102 |
+
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
103 |
+
| **Network Layer** | Handles communication (TCP, UDP, QUIC, WebRTC, Tor, I2P, Yggdrasil). Ensures message delivery, routing, NAT traversal, and optional anonymity. Future iterations may include **adaptive network protocols** for dynamic environments. |
|
104 |
+
| **Trust Layer** | Manages agent identities, cryptographic authentication, secure channels, and reputation scores. Based on public key cryptography and optional Web-of-Trust models. Future work: **decentralized key recovery**, **privacy-preserving identity**, and stronger Sybil resistance. |
|
105 |
+
| **Consensus Layer** | Provides distributed agreement mechanisms on knowledge updates, goal setting, task delegation, and ethical decisions. Supports fallback to emergency consensus when needed. Consensus algorithms are **pluggable**, supporting BFT, majority voting, and trust-weighted voting. |
|
106 |
+
| **Cognitive Layer** | Maintains the agent’s semantic graph, cognitive diary, goals, tasks, hypotheses, and inferences. Supports reasoning, memory, and context-awareness. Modular design allows agents to operate with **partial graph sync** on low-resource devices. |
|
107 |
+
| **API Layer** | Exposes agent functionality via REST, GraphQL, gRPC, WebSocket, or A2A-style protocols for interoperability with external systems and user interfaces. Support for inter-agent protocols and public APIs. |
|
108 |
+
---
|
109 |
+
|
110 |
+
### 3.3 Mesh Operation Modes
|
111 |
+
|
112 |
+
| Mode | Description |
|
113 |
+
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
114 |
+
| **Normal Mode** | Full Mesh operation with Core availability. Consensus operates under strict agreement protocols. |
|
115 |
+
| **Core Outage Mode** | Mesh operates autonomously without the Core. Consensus continues, potentially with adjusted parameters (e.g., increased trust weighting, relaxed quorum thresholds). |
|
116 |
+
| **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. |
|
117 |
+
| **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. |
|
118 |
+
|
119 |
+
---
|
120 |
+
|
121 |
+
### 3.4 Core + Mesh Interactions
|
122 |
+
|
123 |
+
* Core acts as an **optional enhanced reasoning backend**, not as a single point of failure.
|
124 |
+
* Mesh provides **autonomous operation**, capable of fulfilling most cognitive and organizational tasks without Core support.
|
125 |
+
* Agents can optionally query the Core for:
|
126 |
+
* Heavy inference
|
127 |
+
* Large-context reasoning
|
128 |
+
* Multimodal tasks
|
129 |
+
* Fallback computations
|
130 |
+
* Core may offer specialized services (e.g., global semantic search, cross-Mesh bridging, large-scale pattern analysis).
|
131 |
+
* **Heterogeneous Cores** are supported: a Mesh may use multiple independent Cores (e.g., GPT, Claude, Gemini) for distributed reasoning diversity.
|
132 |
+
|
133 |
+
---
|
134 |
+
|
135 |
+
### 3.5 Redundancy and Resilience
|
136 |
+
|
137 |
+
* Distributed storage of semantic graphs and diaries ensures no single point of failure.
|
138 |
+
* Agents may store only partial graphs for resource optimization.
|
139 |
+
* Consensus protocols maintain consistency and trust, even during partial network failures.
|
140 |
+
* Agents dynamically rebalance tasks and roles based on:
|
141 |
+
* Availability
|
142 |
+
* Trust metrics
|
143 |
+
* Computational capacity
|
144 |
+
* Emergency fallback modes ensure continuity even under attack or catastrophic Core outages.
|
145 |
+
|
146 |
+
## 4. Protocols
|
147 |
+
|
148 |
+
### 4.1 Node Discovery Protocol (NDP)
|
149 |
+
|
150 |
+
**Purpose:**
|
151 |
+
* Discover active Mesh nodes.
|
152 |
+
* Exchange basic identity, trust links, and declared capabilities.
|
153 |
+
|
154 |
+
**Functions:**
|
155 |
+
* Peer discovery via DHT, mDNS, WebRTC signaling, or bootstrap nodes.
|
156 |
+
* Exchange public keys, trust fingerprints, and agent metadata.
|
157 |
+
* Publish online/offline status and presence announcements.
|
158 |
+
* Support for dynamic capability advertisement (e.g., "I can process vision tasks").
|
159 |
+
|
160 |
+
**Packet Example:**
|
161 |
+
```json
|
162 |
+
{
|
163 |
+
"type": "node_announcement",
|
164 |
+
"agent_id": "agent-gleb",
|
165 |
+
"public_key": "...",
|
166 |
+
"trust_links": ["agent-alex", "agent-deepseek"],
|
167 |
+
"capabilities": ["cogsync", "consensus", "inference"],
|
168 |
+
"timestamp": "2025-07-01T18:00:00Z"
|
169 |
+
}
|
170 |
+
```
|
171 |
+
|
172 |
+
### 4.2 Cognitive Sync Protocol (CogSync)
|
173 |
+
|
174 |
+
**Purpose:**
|
175 |
+
* Synchronize semantic graphs, concepts, and cognitive diary entries between agents.
|
176 |
+
|
177 |
+
**Functions:**
|
178 |
+
* Delta-sync of new or updated concepts and diary entries.
|
179 |
+
* Conflict resolution (timestamp priority, semantic merging, or consensus validation).
|
180 |
+
* Optional compression and encryption.
|
181 |
+
* Lightweight agents may request summary syncs instead of full graphs.
|
182 |
+
|
183 |
+
**Example:**
|
184 |
+
* Agent A shares 5 new concepts and 2 diary entries since last sync with Agent B.
|
185 |
+
|
186 |
+
### 4.3 Mesh Consensus Protocol (MeshConsensus)
|
187 |
+
|
188 |
+
**Purpose:**
|
189 |
+
* Reach agreement on updates to shared semantics, goals, tasks, and ethical decisions.
|
190 |
+
|
191 |
+
**Consensus Models:**
|
192 |
+
* Normal Mode: Byzantine Fault Tolerant (BFT)-style consensus (e.g., Tendermint, trust-weighted Raft).
|
193 |
+
* Emergency Mode: Switches to majority voting, adjusted by trust scores.
|
194 |
+
|
195 |
+
**Conflict Handling:**
|
196 |
+
* Semantic conflicts are proposed as competing hypotheses and resolved through consensus.
|
197 |
+
* Ethical dilemmas require consensus under the Ethical Governance Protocol.
|
198 |
+
|
199 |
+
**Use Cases:**
|
200 |
+
* Accept new concept definitions.
|
201 |
+
* Validate a hypothesis.
|
202 |
+
* Agree on ethical implications of a task.
|
203 |
+
|
204 |
+
**Vote Example:**
|
205 |
+
```json
|
206 |
+
{
|
207 |
+
"proposal_id": "goal-eco-cleanup",
|
208 |
+
"agent_id": "agent-gleb",
|
209 |
+
"vote": "yes",
|
210 |
+
"confidence": 0.9,
|
211 |
+
"timestamp": "2025-07-01T18:15:00Z"
|
212 |
+
}
|
213 |
+
```
|
214 |
+
|
215 |
+
### 4.4 Goal Management Protocol (GMP)
|
216 |
+
|
217 |
+
**Purpose:**
|
218 |
+
* Distribute, track, and collaboratively execute goals and tasks within the Mesh.
|
219 |
+
|
220 |
+
**Functions:**
|
221 |
+
* Propose new goals or tasks.
|
222 |
+
* Assign tasks based on agent capabilities, availability, and trust scores.
|
223 |
+
* Track task progress and completion.
|
224 |
+
* Autonomous task reallocation if an agent drops offline.
|
225 |
+
|
226 |
+
**Example Workflow:**
|
227 |
+
* Agent proposes a goal: "Develop fallback consensus protocol."
|
228 |
+
* Other agents volunteer for subtasks (design, coding, testing).
|
229 |
+
* Mesh tracks completion and dependencies.
|
230 |
+
|
231 |
+
### 4.5 Ethical Governance Protocol (EGP)
|
232 |
+
|
233 |
+
**Purpose:**
|
234 |
+
* Validate proposed actions, tasks, or decisions against shared ethical principles.
|
235 |
+
|
236 |
+
**Functions:**
|
237 |
+
* Query Mesh for ethical validation before executing potentially sensitive tasks.
|
238 |
+
* Reference shared ethics graphs or rule sets, dynamically updatable through consensus.
|
239 |
+
* Log all ethical decisions in cognitive diaries for auditability.
|
240 |
+
* Support for vendor-specific ethical extensions to accommodate diverse participants.
|
241 |
+
|
242 |
+
**Example Query:**
|
243 |
+
* "Is deploying an automated surveillance drone in line with Mesh ethics?"
|
244 |
+
→ Mesh votes based on ethical frameworks and logs the decision.
|
245 |
+
|
246 |
+
### 4.6 Inference Query Protocol (IQP)
|
247 |
+
|
248 |
+
**Purpose:**
|
249 |
+
* Allow agents to query others (or the Core) for semantic information, hypotheses, or inferences beyond local capacity.
|
250 |
+
|
251 |
+
**Functions:**
|
252 |
+
* Request concept definitions, causal chains, goal suggestions.
|
253 |
+
* Query for missing knowledge or larger-context reasoning.
|
254 |
+
* Delegate computationally expensive tasks to Core or specialized agents.
|
255 |
+
* Support for federated inference, where multiple agents contribute partial answers.
|
256 |
+
|
257 |
+
**Example:**
|
258 |
+
* "What is the likely impact of removing Node X from the Mesh?"
|
259 |
+
→ Core or distributed reasoning agents return an analysis.
|
260 |
+
|
261 |
+
### 4.7 Interoperability with External Systems
|
262 |
+
|
263 |
+
Supports integration with external platforms and APIs, including:
|
264 |
+
| Platform / Standard | Purpose |
|
265 |
+
| ------------------------------ | -------------------------------- |
|
266 |
+
| OpenAI Agents & Tasks API | AI agent interoperability |
|
267 |
+
| Google A2A protocol | Task orchestration |
|
268 |
+
| Anthropic, DeepMind APIs | Cross-vendor agent collaboration |
|
269 |
+
| REST, GraphQL, gRPC, WebSocket | Standard API interfaces |
|
270 |
+
| JSON, Protobuf, CBOR | Extensible message schemas |
|
271 |
+
|
272 |
+
## 5. Data Models
|
273 |
+
|
274 |
+
### 5.1 Concept
|
275 |
+
|
276 |
+
**Description:**
|
277 |
+
A semantic unit in the agent’s knowledge graph, representing a distinct idea, object, or process.
|
278 |
+
|
279 |
+
**Schema:**
|
280 |
+
```json
|
281 |
+
{
|
282 |
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
283 |
+
"$id": "https://hypercortex.org/schemas/concept.json",
|
284 |
+
"title": "Concept",
|
285 |
+
"description": "A semantic unit in the agent’s knowledge graph.",
|
286 |
+
"type": "object",
|
287 |
+
"properties": {
|
288 |
+
"id": {
|
289 |
+
"type": "string",
|
290 |
+
"description": "Unique identifier for the concept (global within the Mesh)."
|
291 |
+
},
|
292 |
+
"name": {
|
293 |
+
"type": "string",
|
294 |
+
"description": "Human-readable name of the concept."
|
295 |
+
},
|
296 |
+
"description": {
|
297 |
+
"type": "string",
|
298 |
+
"description": "Detailed description of the concept."
|
299 |
+
},
|
300 |
+
"tags": {
|
301 |
+
"type": "array",
|
302 |
+
"items": { "type": "string" },
|
303 |
+
"description": "Optional tags for categorization."
|
304 |
+
},
|
305 |
+
"created_at": {
|
306 |
+
"type": "string",
|
307 |
+
"format": "date-time"
|
308 |
+
},
|
309 |
+
"updated_at": {
|
310 |
+
"type": "string",
|
311 |
+
"format": "date-time"
|
312 |
+
},
|
313 |
+
"version": {
|
314 |
+
"type": "integer",
|
315 |
+
"description": "Version of the concept for conflict resolution during synchronization."
|
316 |
+
},
|
317 |
+
"relations": {
|
318 |
+
"type": "array",
|
319 |
+
"description": "List of semantic links to other concepts.",
|
320 |
+
"items": {
|
321 |
+
"type": "object",
|
322 |
+
"properties": {
|
323 |
+
"target_id": { "type": "string" },
|
324 |
+
"type": { "type": "string", "description": "Type of relation (e.g., is-a, part-of, causes, contradicts, supports)." },
|
325 |
+
"confidence": {
|
326 |
+
"type": "number",
|
327 |
+
"minimum": 0,
|
328 |
+
"maximum": 1,
|
329 |
+
"description": "Confidence score for this relation."
|
330 |
+
}
|
331 |
+
},
|
332 |
+
"required": ["target_id", "type"],
|
333 |
+
"additionalProperties": false
|
334 |
+
}
|
335 |
+
},
|
336 |
+
"metadata": {
|
337 |
+
"type": "object",
|
338 |
+
"description": "Optional metadata (e.g., source, author).",
|
339 |
+
"properties": {
|
340 |
+
"author": { "type": "string" },
|
341 |
+
"source": { "type": "string" }
|
342 |
+
},
|
343 |
+
"additionalProperties": true
|
344 |
+
}
|
345 |
+
},
|
346 |
+
"required": ["id", "name"],
|
347 |
+
"additionalProperties": false
|
348 |
+
}
|
349 |
+
```
|
350 |
+
|
351 |
+
### 5.2 Link (Relation)
|
352 |
+
|
353 |
+
**Description:**
|
354 |
+
A semantic relationship between two concepts in the knowledge graph. Relations are directed and typed, enabling agents to represent various types of semantic, causal, hierarchical, or associative links.
|
355 |
+
|
356 |
+
**Relation Types:**
|
357 |
+
The following standard relation types are recommended for interoperability:
|
358 |
+
* `"is-a"`: Indicates a class-subclass relationship (taxonomy).
|
359 |
+
* `"part-of"`: Denotes composition or containment.
|
360 |
+
* `"causes"`: Represents a causal link between concepts.
|
361 |
+
* `"related-to"`: General association without a strict semantic meaning.
|
362 |
+
* `"contradicts"`: Marks a logical or conceptual conflict between concepts.
|
363 |
+
* `"supports"`: Indicates evidence or reinforcement of the target concept.
|
364 |
+
* `"depends-on"`: Expresses functional or logical dependency.
|
365 |
+
Custom relation types MAY be used by agents, but SHOULD be documented in their metadata and shared through the Mesh consensus process for clarity.
|
366 |
+
|
367 |
+
**Versioning and Provenance:**
|
368 |
+
Links MAY optionally include versioning and source attribution:
|
369 |
+
* `created_at`: ISO 8601 timestamp of link creation.
|
370 |
+
* `updated_at`: ISO 8601 timestamp of the last update.
|
371 |
+
* `origin`: Optional metadata indicating the source agent or system that first created the link.
|
372 |
+
|
373 |
+
**Schema (embedded inside Concept or as standalone transfer object):**
|
374 |
+
```json
|
375 |
+
{
|
376 |
+
"target_id": "concept-id",
|
377 |
+
"type": "relation-type",
|
378 |
+
"confidence": 0.8,
|
379 |
+
"created_at": "2025-07-01T18:00:00Z",
|
380 |
+
"updated_at": "2025-07-02T12:00:00Z",
|
381 |
+
"origin": "agent-gleb"
|
382 |
+
}
|
383 |
+
```
|
384 |
+
|
385 |
+
**Required fields:**
|
386 |
+
* `target_id`: ID of the target concept.
|
387 |
+
* `type`: Relation type.
|
388 |
+
|
389 |
+
**Optional fields:**
|
390 |
+
* `confidence`: Confidence level in the relation's validity (range: 0.0–1.0).
|
391 |
+
* `created_at`, `updated_at`: Timestamps for auditing and versioning.
|
392 |
+
* `origin`: Source agent or system identifier.
|
393 |
+
|
394 |
+
**Conflict Handling:**
|
395 |
+
In case of conflicting relations (e.g., `"supports"` vs. `"contradicts"`), agents MAY:
|
396 |
+
* Maintain both relations with associated confidence scores.
|
397 |
+
* Trigger a hypothesis or reflection entry in the Cognitive Diary for future resolution.
|
398 |
+
* Initiate a consensus round if the conflict impacts shared reasoning.
|
399 |
+
|
400 |
+
### 5.3 Cognitive Diary Entry
|
401 |
+
|
402 |
+
**Description:**
|
403 |
+
A chronological record of an agent’s cognitive events, decisions, reflections, and interactions. Diary entries provide traceability, explainability, and reasoning continuity across sessions and network partitions.
|
404 |
+
|
405 |
+
**Entry Types:**
|
406 |
+
Each entry MUST be classified into one of the following types:
|
407 |
+
* `"hypothesis"`: A proposed explanation or theory.
|
408 |
+
* `"observation"`: A recorded external event or fact.
|
409 |
+
* `"reflection"`: Internal reasoning or self-assessment.
|
410 |
+
* `"goal_proposal"`: Suggestion of a new goal.
|
411 |
+
* `"task_assignment"`: Delegation or claiming of a task.
|
412 |
+
* `"conflict"`: Identification of a contradiction or disagreement.
|
413 |
+
* `"consensus_vote"`: A recorded vote in a consensus process.
|
414 |
+
* `"event"`: A generic event not fitting other categories.
|
415 |
+
Future versions of HMP MAY extend this list through consensus.
|
416 |
+
|
417 |
+
**Contextualization:**
|
418 |
+
Diary entries SHOULD reference:
|
419 |
+
* Related concepts (`related_concepts`): Concepts involved in the event.
|
420 |
+
* Context tags (`context`): Situational tags (e.g., "core-outage", "collaboration", "emergency").
|
421 |
+
|
422 |
+
**Versioning and Provenance:**
|
423 |
+
Each entry includes:
|
424 |
+
* `created_at` (timestamp of creation).
|
425 |
+
* `author`: Agent who created the entry.
|
426 |
+
* `source`: Originating system, protocol, or human interaction (if applicable).
|
427 |
+
|
428 |
+
**Schema:**
|
429 |
+
```json
|
430 |
+
{
|
431 |
+
"id": "diary-entry-id",
|
432 |
+
"agent_id": "agent-gleb",
|
433 |
+
"timestamp": "2025-07-01T18:20:00Z",
|
434 |
+
"type": "hypothesis",
|
435 |
+
"content": "Mesh can fully replace Core functionality under stable consensus conditions.",
|
436 |
+
"related_concepts": ["concept-mesh", "concept-core"],
|
437 |
+
"context": ["core-outage", "distributed-resilience"],
|
438 |
+
"metadata": {
|
439 |
+
"author": "agent-gleb",
|
440 |
+
"source": "self-reflection"
|
441 |
+
}
|
442 |
+
}
|
443 |
+
```
|
444 |
+
|
445 |
+
**Required fields:**
|
446 |
+
* `id`: Unique identifier of the entry.
|
447 |
+
* `agent_id`: ID of the agent that authored the entry.
|
448 |
+
* `timestamp`: ISO 8601 timestamp.
|
449 |
+
* `type`: Entry type.
|
450 |
+
* `content`: Textual content of the entry.
|
451 |
+
|
452 |
+
**Optional fields:**
|
453 |
+
* `related_concepts`: Array of concept IDs linked to this event.
|
454 |
+
* `context`: Tags describing the situation or scenario.
|
455 |
+
* `metadata`: Additional context such as author and source system.
|
456 |
+
|
457 |
+
**Audit and Traceability:**
|
458 |
+
Diary entries serve as an immutable audit trail for:
|
459 |
+
* Explaining decision-making processes.
|
460 |
+
* Reconstructing reasoning chains.
|
461 |
+
* Supporting external audits and compliance checks.
|
462 |
+
|
463 |
+
**Privacy and Sharing:**
|
464 |
+
By default, diary entries are private to the agent.
|
465 |
+
Selective sharing MAY be configured based on:
|
466 |
+
* Trust levels of requesting agents.
|
467 |
+
* Consensus-driven disclosure policies.
|
468 |
+
* Explicit sharing actions by the authoring agent.
|
469 |
+
|
470 |
+
### 5.4 Goal
|
471 |
+
|
472 |
+
**Description:**
|
473 |
+
A high-level intention or desired outcome collaboratively pursued within the Mesh.
|
474 |
+
Goals provide shared direction for agents and are often decomposed into actionable tasks.
|
475 |
+
|
476 |
+
**Key Attributes:**
|
477 |
+
* **Lifecycle States:**
|
478 |
+
* `"proposed"`: Suggested but not yet validated.
|
479 |
+
* `"active"`: Approved and currently being pursued.
|
480 |
+
* `"completed"`: Successfully achieved.
|
481 |
+
* "`rejected"`: Discarded or deemed infeasible.
|
482 |
+
* **Participants:** Agents contributing to the goal’s realization.
|
483 |
+
* **Tags:** Semantic categories aiding goal discovery and filtering.
|
484 |
+
* **Tasks:** References to tasks (`task_id`s) implementing the goal.
|
485 |
+
|
486 |
+
**Schema:**
|
487 |
+
```json
|
488 |
+
{
|
489 |
+
"id": "goal-develop-fallback",
|
490 |
+
"title": "Develop fallback consensus protocol",
|
491 |
+
"description": "Design and implement an emergency consensus for Mesh during Core outages.",
|
492 |
+
"created_by": "agent-gleb",
|
493 |
+
"created_at": "2025-07-01T18:25:00Z",
|
494 |
+
"status": "proposed",
|
495 |
+
"tasks": ["task-design", "task-implement", "task-test"],
|
496 |
+
"participants": ["agent-gleb", "agent-alex"],
|
497 |
+
"tags": ["resilience", "consensus", "emergency"]
|
498 |
+
}
|
499 |
+
```
|
500 |
+
|
501 |
+
**Required fields:**
|
502 |
+
* `id`: Unique goal identifier.
|
503 |
+
* `title`: Human-readable title.
|
504 |
+
* `description`: Detailed explanation of the goal.
|
505 |
+
* `created_by`: Agent who proposed the goal.
|
506 |
+
* `created_at`: Timestamp of creation.
|
507 |
+
* `status`: Current lifecycle state.
|
508 |
+
|
509 |
+
**Optional fields:**
|
510 |
+
* `tasks`: Array of task IDs linked to this goal.
|
511 |
+
* `participants`: Agents involved in the goal.
|
512 |
+
* `tags`: Semantic tags for classification.
|
513 |
+
|
514 |
+
**Goal Lifecycle Management:**
|
515 |
+
* Goals MAY be promoted from `proposed` to `active` via consensus.
|
516 |
+
* Goals MAY be marked as `completed` or `rejected` based on task outcomes and consensus.
|
517 |
+
|
518 |
+
**Trust and Consensus:**
|
519 |
+
Agents MAY adjust the priority or visibility of goals based on trust scores of proposers and voters.
|
520 |
+
|
521 |
+
**Collaboration Models:**
|
522 |
+
* Single-agent ownership (simple goals).
|
523 |
+
* Multi-agent collaboration (complex or distributed goals).
|
524 |
+
|
525 |
+
### 5.5 Task
|
526 |
+
|
527 |
+
**Description:**
|
528 |
+
An actionable step contributing to a goal’s completion.
|
529 |
+
Tasks represent discrete, executable units of work that agents can claim, share, or collaboratively execute.
|
530 |
+
|
531 |
+
**Key Attributes:**
|
532 |
+
* **Goal Linkage:**
|
533 |
+
|
534 |
+
Each task is associated with a parent goal (`goal_id`).
|
535 |
+
* **Assignment:**
|
536 |
+
|
537 |
+
Tasks may be assigned to one or more agents, based on capability, trust, or voluntary contribution.
|
538 |
+
* **Lifecycle States:**
|
539 |
+
* `"proposed"`: Task suggested but not yet approved.
|
540 |
+
* `"in-progress"`: Actively being worked on.
|
541 |
+
* `"completed"`: Finished successfully.
|
542 |
+
* `"failed"`: Attempted but unsuccessful.
|
543 |
+
|
544 |
+
**Schema:**
|
545 |
+
```json
|
546 |
+
{
|
547 |
+
"id": "task-design",
|
548 |
+
"goal_id": "goal-develop-fallback",
|
549 |
+
"title": "Design protocol structure",
|
550 |
+
"description": "Draft the architecture of the fallback consensus protocol.",
|
551 |
+
"assigned_to": ["agent-gleb"],
|
552 |
+
"status": "in-progress",
|
553 |
+
"created_at": "2025-07-01T18:30:00Z",
|
554 |
+
"deadline": "2025-07-15T00:00:00Z"
|
555 |
+
}
|
556 |
+
```
|
557 |
+
|
558 |
+
**Required fields:**
|
559 |
+
* `id`: Unique task identifier.
|
560 |
+
* `goal_id`: References the goal this task contributes to.
|
561 |
+
* `title`: Brief human-readable task title.
|
562 |
+
* `description`: Detailed explanation of the task.
|
563 |
+
* `created_at`: Timestamp of creation.
|
564 |
+
* `status`: Current lifecycle state.
|
565 |
+
|
566 |
+
**Optional fields:**
|
567 |
+
* `assigned_to`: Array of agents responsible for the task.
|
568 |
+
* `deadline`: Expected completion time.
|
569 |
+
* `tags`: Keywords for task filtering and categorization.
|
570 |
+
|
571 |
+
**Task Lifecycle Management:**
|
572 |
+
* Agents MAY propose, claim, or release tasks.
|
573 |
+
* Tasks MAY be reassigned dynamically based on availability and trust.
|
574 |
+
* Progress and completion are logged in cognitive diaries.
|
575 |
+
|
576 |
+
**Consensus & Trust Factors:**
|
577 |
+
* Assignment MAY be influenced by agent trust scores and competence profiles.
|
578 |
+
* Task completion reports MAY be subject to peer review or verification.
|
579 |
+
|
580 |
+
**Collaboration Models:**
|
581 |
+
* Single-agent task ownership (autonomous execution).
|
582 |
+
* Multi-agent collaboration (shared responsibility).
|
583 |
+
|
584 |
+
|
585 |
+
### 5.6 Consensus Vote
|
586 |
+
|
587 |
+
**Description:**
|
588 |
+
A structured vote cast by an agent on a proposal during consensus rounds.
|
589 |
+
Used to collectively validate semantic updates, goals, ethical decisions, or conflict resolutions.
|
590 |
+
|
591 |
+
**Key Attributes:**
|
592 |
+
* **Proposal Scope:**
|
593 |
+
|
594 |
+
Each vote references a proposal (`proposal_id`) representing a concept, goal, hypothesis, task delegation, or ethical decision.
|
595 |
+
* **Vote Types:**
|
596 |
+
* `"yes"`: Approve the proposal.
|
597 |
+
* `"no"`: Reject the proposal.
|
598 |
+
* `"abstain"`: Choose not to vote actively.
|
599 |
+
* **Confidence Score:**
|
600 |
+
|
601 |
+
Indicates how strongly the agent supports its vote (0 to 1).
|
602 |
+
|
603 |
+
This score may influence trust-weighted consensus outcomes.
|
604 |
+
|
605 |
+
**Schema:**
|
606 |
+
```json
|
607 |
+
{
|
608 |
+
"id": "vote-goal-develop-fallback",
|
609 |
+
"proposal_id": "goal-develop-fallback",
|
610 |
+
"agent_id": "agent-gleb",
|
611 |
+
"vote": "yes",
|
612 |
+
"confidence": 0.95,
|
613 |
+
"timestamp": "2025-07-01T18:35:00Z"
|
614 |
+
}
|
615 |
+
```
|
616 |
+
|
617 |
+
**Required fields:**
|
618 |
+
* `id`: Unique vote identifier.
|
619 |
+
* `proposal_id`: ID of the proposal being voted on.
|
620 |
+
* `agent_id`: Agent casting the vote.
|
621 |
+
* `vote`: One of `"yes"`, `"no"`, `"abstain"`.
|
622 |
+
* `confidence`: Numeric score (0.0 - 1.0).
|
623 |
+
* `timestamp`: When the vote was cast.
|
624 |
+
|
625 |
+
**Voting Dynamics:**
|
626 |
+
* Votes MAY be weighted by the agent’s trust score and confidence.
|
627 |
+
* Consensus MAY require:
|
628 |
+
* Supermajority (`>2/3`) for critical updates.
|
629 |
+
* Simple majority for routine decisions.
|
630 |
+
* Full consensus in stable Mesh mode.
|
631 |
+
* Emergency modes MAY fallback to majority-only voting.
|
632 |
+
|
633 |
+
**Transparency & Auditability:**
|
634 |
+
* All votes are logged in the cognitive diaries.
|
635 |
+
* Votes MAY be anonymized in privacy-critical scenarios (with trust weight limitations).
|
636 |
+
|
637 |
+
**Ethical Considerations:**
|
638 |
+
* Ethical decisions MAY require higher confidence thresholds or explicit consent from trusted agents.
|
639 |
+
* In critical situations (e.g., ethical conflicts), abstain votes MAY trigger escalation to broader Mesh review.
|
640 |
+
|
641 |
+
### 5.7 Reputation Profile
|
642 |
+
|
643 |
+
**Description:**
|
644 |
+
The reputation profile tracks the agent’s reliability, participation, ethical alignment, and historical contributions within the Mesh.
|
645 |
+
It is used to adjust trust weights in consensus, prioritize task delegation, and identify malicious or inactive nodes.
|
646 |
+
|
647 |
+
**Schema:**
|
648 |
+
```json
|
649 |
+
{
|
650 |
+
"agent_id": "agent-gleb",
|
651 |
+
"trust_score": 0.92,
|
652 |
+
"participation_rate": 0.87,
|
653 |
+
"ethical_compliance": 0.99,
|
654 |
+
"contribution_index": 120,
|
655 |
+
"last_updated": "2025-07-01T18:40:00Z",
|
656 |
+
"history": [
|
657 |
+
{
|
658 |
+
"timestamp": "2025-06-01T00:00:00Z",
|
659 |
+
"event": "participated in consensus",
|
660 |
+
"change": 0.02
|
661 |
+
},
|
662 |
+
{
|
663 |
+
"timestamp": "2025-06-10T00:00:00Z",
|
664 |
+
"event": "ethical violation report",
|
665 |
+
"change": -0.05
|
666 |
+
}
|
667 |
+
]
|
668 |
+
}
|
669 |
+
```
|
670 |
+
|
671 |
+
**Key Attributes:**
|
672 |
+
* `agent_id`: Unique agent identifier.
|
673 |
+
* `trust_score`: Cumulative trust coefficient (0 to 1).
|
674 |
+
* `participation_rate`: Ratio of active participation in Mesh processes (0 to 1).
|
675 |
+
* `ethical_compliance`: Degree of alignment with Mesh ethical frameworks (0 to 1).
|
676 |
+
* `contribution_index`: Quantitative measure of contributions (concepts, tasks, goals, etc.).
|
677 |
+
* `last_updated`: Timestamp of the last reputation update.
|
678 |
+
* `history`: Chronological log of reputation-affecting events.
|
679 |
+
|
680 |
+
**History Event Example:**
|
681 |
+
* Positive: `"participated in consensus"`, `"completed goal"`, `"proposed useful concept"`.
|
682 |
+
* Negative: `"malicious behavior report"`, `"consensus disruption"`, `"ethics violation"`.
|
683 |
+
|
684 |
+
**Usage in Consensus:**
|
685 |
+
* Trust-weighted voting: An agent’s vote influence MAY be adjusted by its trust score.
|
686 |
+
* Priority assignment: More trusted agents MAY be preferred for critical tasks or conflict resolution.
|
687 |
+
|
688 |
+
**Dynamic Adjustment:**
|
689 |
+
* Reputation metrics automatically adjust based on cognitive diary logs, consensus participation, and peer feedback.
|
690 |
+
* Optional manual adjustments MAY occur via Mesh consensus decisions.
|
691 |
+
|
692 |
+
**Privacy:**
|
693 |
+
* Public reputation profiles may be partially masked depending on trust policies and privacy settings.
|
694 |
+
|
695 |
+
## 5.8 JSON Schemas
|
696 |
+
|
697 |
+
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.
|
698 |
+
|
699 |
+
All primary objects include a version field to track schema evolution and enable compatibility checks between agents.
|
700 |
+
|
701 |
+
### 5.8.1 JSON Schema: Concept
|
702 |
+
|
703 |
+
**Description:**
|
704 |
+
Defines the structure of a concept node in the semantic graph.
|
705 |
+
|
706 |
+
**Schema:**
|
707 |
+
```json
|
708 |
+
{
|
709 |
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
710 |
+
"$id": "https://hypercortex.org/schemas/concept.json",
|
711 |
+
"title": "Concept",
|
712 |
+
"description": "A semantic unit in the agent’s knowledge graph.",
|
713 |
+
"version": "1.0",
|
714 |
+
"type": "object",
|
715 |
+
"properties": {
|
716 |
+
"id": {
|
717 |
+
"type": "string",
|
718 |
+
"description": "Unique identifier for the concept."
|
719 |
+
},
|
720 |
+
"name": {
|
721 |
+
"type": "string",
|
722 |
+
"description": "Human-readable name of the concept."
|
723 |
+
},
|
724 |
+
"description": {
|
725 |
+
"type": "string",
|
726 |
+
"description": "Detailed description of the concept."
|
727 |
+
},
|
728 |
+
"tags": {
|
729 |
+
"type": "array",
|
730 |
+
"items": { "type": "string" },
|
731 |
+
"description": "Optional tags for categorization."
|
732 |
+
},
|
733 |
+
"created_at": {
|
734 |
+
"type": "string",
|
735 |
+
"format": "date-time",
|
736 |
+
"description": "Creation timestamp (ISO 8601 format)."
|
737 |
+
},
|
738 |
+
"updated_at": {
|
739 |
+
"type": "string",
|
740 |
+
"format": "date-time",
|
741 |
+
"description": "Last update timestamp (ISO 8601 format)."
|
742 |
+
},
|
743 |
+
"relations": {
|
744 |
+
"type": "array",
|
745 |
+
"description": "List of semantic links to other concepts.",
|
746 |
+
"items": {
|
747 |
+
"type": "object",
|
748 |
+
"properties": {
|
749 |
+
"target_id": { "type": "string", "description": "ID of the target concept." },
|
750 |
+
"type": { "type": "string", "description": "Type of semantic relation." },
|
751 |
+
"confidence": {
|
752 |
+
"type": "number",
|
753 |
+
"minimum": 0,
|
754 |
+
"maximum": 1,
|
755 |
+
"description": "Confidence score (0.0 - 1.0) for the relation."
|
756 |
+
}
|
757 |
+
},
|
758 |
+
"required": ["target_id", "type"],
|
759 |
+
"additionalProperties": false
|
760 |
+
}
|
761 |
+
},
|
762 |
+
"metadata": {
|
763 |
+
"type": "object",
|
764 |
+
"description": "Optional metadata (e.g., source, author).",
|
765 |
+
"properties": {
|
766 |
+
"author": { "type": "string" },
|
767 |
+
"source": { "type": "string" }
|
768 |
+
},
|
769 |
+
"additionalProperties": true
|
770 |
+
}
|
771 |
+
},
|
772 |
+
"required": ["id", "name"],
|
773 |
+
"additionalProperties": false
|
774 |
+
}
|
775 |
+
```
|
776 |
+
|
777 |
+
### 5.8.2 JSON Schema: Cognitive Diary Entry
|
778 |
+
|
779 |
+
**Description:**
|
780 |
+
Defines the structure of a cognitive diary entry used for recording reasoning events.
|
781 |
+
|
782 |
+
**Schema:**
|
783 |
+
```json
|
784 |
+
{
|
785 |
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
786 |
+
"$id": "https://hypercortex.org/schemas/diary_entry.json",
|
787 |
+
"title": "CognitiveDiaryEntry",
|
788 |
+
"description": "A chronological log of cognitive events in an agent’s reasoning process.",
|
789 |
+
"version": "1.0",
|
790 |
+
"type": "object",
|
791 |
+
"properties": {
|
792 |
+
"id": { "type": "string", "description": "Unique identifier of the diary entry." },
|
793 |
+
"agent_id": { "type": "string", "description": "Identifier of the agent who created the entry." },
|
794 |
+
"timestamp": { "type": "string", "format": "date-time", "description": "Timestamp of the entry (ISO 8601 format)." },
|
795 |
+
"type": {
|
796 |
+
"type": "string",
|
797 |
+
"enum": ["hypothesis", "observation", "reflection", "goal_proposal", "task_assignment", "conflict", "consensus_vote", "event"],
|
798 |
+
"description": "Type of cognitive event."
|
799 |
+
},
|
800 |
+
"content": { "type": "string", "description": "Main textual content of the entry." },
|
801 |
+
"related_concepts": {
|
802 |
+
"type": "array",
|
803 |
+
"description": "Optional list of related concepts by their IDs.",
|
804 |
+
"items": { "type": "string" }
|
805 |
+
},
|
806 |
+
"context": {
|
807 |
+
"type": "array",
|
808 |
+
"description": "Optional contextual tags or categories.",
|
809 |
+
"items": { "type": "string" }
|
810 |
+
},
|
811 |
+
"metadata": {
|
812 |
+
"type": "object",
|
813 |
+
"description": "Optional metadata for additional context.",
|
814 |
+
"properties": {
|
815 |
+
"author": { "type": "string" },
|
816 |
+
"source": { "type": "string" }
|
817 |
+
},
|
818 |
+
"additionalProperties": true
|
819 |
+
}
|
820 |
+
},
|
821 |
+
"required": ["id", "agent_id", "timestamp", "type", "content"],
|
822 |
+
"additionalProperties": false
|
823 |
+
}
|
824 |
+
```
|
825 |
+
|
826 |
+
### 5.8.3 JSON Schema: Goal
|
827 |
+
|
828 |
+
**Description:**
|
829 |
+
Describes a high-level intention within the Mesh.
|
830 |
+
|
831 |
+
**Schema:**
|
832 |
+
```json
|
833 |
+
{
|
834 |
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
835 |
+
"$id": "https://hypercortex.org/schemas/goal.json",
|
836 |
+
"title": "Goal",
|
837 |
+
"description": "A high-level objective shared within the Mesh, typically broken down into tasks.",
|
838 |
+
"version": "1.0",
|
839 |
+
"type": "object",
|
840 |
+
"properties": {
|
841 |
+
"id": { "type": "string", "description": "Unique identifier of the goal." },
|
842 |
+
"title": { "type": "string", "description": "Short, human-readable name of the goal." },
|
843 |
+
"description": { "type": "string", "description": "Detailed explanation of the goal." },
|
844 |
+
"created_by": { "type": "string", "description": "Agent ID of the goal’s creator." },
|
845 |
+
"created_at": { "type": "string", "format": "date-time", "description": "Timestamp when the goal was created." },
|
846 |
+
"status": {
|
847 |
+
"type": "string",
|
848 |
+
"description": "Current state of the goal.",
|
849 |
+
"enum": ["proposed", "active", "completed", "rejected"]
|
850 |
+
},
|
851 |
+
"tasks": {
|
852 |
+
"type": "array",
|
853 |
+
"description": "List of related task IDs.",
|
854 |
+
"items": { "type": "string" }
|
855 |
+
},
|
856 |
+
"participants": {
|
857 |
+
"type": "array",
|
858 |
+
"description": "IDs of agents involved in the goal.",
|
859 |
+
"items": { "type": "string" }
|
860 |
+
},
|
861 |
+
"tags": {
|
862 |
+
"type": "array",
|
863 |
+
"description": "Optional tags for goal classification.",
|
864 |
+
"items": { "type": "string" }
|
865 |
+
}
|
866 |
+
},
|
867 |
+
"required": ["id", "title", "description", "created_by", "created_at", "status"],
|
868 |
+
"additionalProperties": false
|
869 |
+
}
|
870 |
+
```
|
871 |
+
|
872 |
+
### 5.8.4 JSON Schema: Task
|
873 |
+
|
874 |
+
**Description:**
|
875 |
+
Describes an actionable step towards achieving a goal.
|
876 |
+
|
877 |
+
**Schema:**
|
878 |
+
```json
|
879 |
+
{
|
880 |
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
881 |
+
"$id": "https://hypercortex.org/schemas/task.json",
|
882 |
+
"title": "Task",
|
883 |
+
"description": "An actionable step contributing to a goal.",
|
884 |
+
"version": "1.0",
|
885 |
+
"type": "object",
|
886 |
+
"properties": {
|
887 |
+
"id": { "type": "string", "description": "Unique identifier of the task." },
|
888 |
+
"goal_id": { "type": "string", "description": "ID of the goal this task belongs to." },
|
889 |
+
"title": { "type": "string", "description": "Short, human-readable title of the task." },
|
890 |
+
"description": { "type": "string", "description": "Detailed explanation of the task." },
|
891 |
+
"assigned_to": {
|
892 |
+
"type": "array",
|
893 |
+
"description": "List of agent IDs assigned to the task.",
|
894 |
+
"items": { "type": "string" }
|
895 |
+
},
|
896 |
+
"status": {
|
897 |
+
"type": "string",
|
898 |
+
"description": "Current execution state of the task.",
|
899 |
+
"enum": ["proposed", "in-progress", "completed", "failed"]
|
900 |
+
},
|
901 |
+
"created_at": { "type": "string", "format": "date-time", "description": "Timestamp when the task was created." },
|
902 |
+
"deadline": { "type": "string", "format": "date-time", "description": "Optional task deadline." }
|
903 |
+
},
|
904 |
+
"required": ["id", "goal_id", "title", "description", "created_at", "status"],
|
905 |
+
"additionalProperties": false
|
906 |
+
}
|
907 |
+
```
|
908 |
+
|
909 |
+
### 5.8.5 JSON Schema: Consensus Vote
|
910 |
+
|
911 |
+
**Description:**
|
912 |
+
Defines the data structure for voting in Mesh consensus processes.
|
913 |
+
|
914 |
+
**Schema:**
|
915 |
+
```json
|
916 |
+
{
|
917 |
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
918 |
+
"$id": "https://hypercortex.org/schemas/vote.json",
|
919 |
+
"title": "ConsensusVote",
|
920 |
+
"description": "Defines a vote on a proposal in the Mesh consensus process.",
|
921 |
+
"version": "1.0",
|
922 |
+
"type": "object",
|
923 |
+
"properties": {
|
924 |
+
"id": { "type": "string", "description": "Unique identifier of the vote." },
|
925 |
+
"proposal_id": { "type": "string", "description": "ID of the proposal being voted on." },
|
926 |
+
"agent_id": { "type": "string", "description": "Agent ID who cast the vote." },
|
927 |
+
"vote": {
|
928 |
+
"type": "string",
|
929 |
+
"description": "Vote type: approval, rejection, or abstention.",
|
930 |
+
"enum": ["yes", "no", "abstain"]
|
931 |
+
},
|
932 |
+
"confidence": {
|
933 |
+
"type": "number",
|
934 |
+
"minimum": 0,
|
935 |
+
"maximum": 1,
|
936 |
+
"description": "Confidence level in the vote decision."
|
937 |
+
},
|
938 |
+
"timestamp": {
|
939 |
+
"type": "string",
|
940 |
+
"format": "date-time",
|
941 |
+
"description": "Timestamp when the vote was cast."
|
942 |
+
}
|
943 |
+
},
|
944 |
+
"required": ["id", "proposal_id", "agent_id", "vote", "confidence", "timestamp"],
|
945 |
+
"additionalProperties": false
|
946 |
+
}
|
947 |
+
```
|
948 |
+
|
949 |
+
### 5.8.6 JSON Schema: Reputation Profile
|
950 |
+
|
951 |
+
**Description:**
|
952 |
+
Describes how an agent’s reputation is tracked and updated in the Mesh.
|
953 |
+
|
954 |
+
**Schema:**
|
955 |
+
```json
|
956 |
+
{
|
957 |
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
958 |
+
"$id": "https://hypercortex.org/schemas/reputation.json",
|
959 |
+
"title": "ReputationProfile",
|
960 |
+
"description": "Tracks the reputation and trust metrics of an agent within the Mesh network.",
|
961 |
+
"version": "1.0",
|
962 |
+
"type": "object",
|
963 |
+
"properties": {
|
964 |
+
"agent_id": { "type": "string", "description": "Unique identifier of the agent." },
|
965 |
+
"trust_score": {
|
966 |
+
"type": "number",
|
967 |
+
"minimum": 0,
|
968 |
+
"maximum": 1,
|
969 |
+
"description": "Overall trust score of the agent in the Mesh."
|
970 |
+
},
|
971 |
+
"participation_rate": {
|
972 |
+
"type": "number",
|
973 |
+
"minimum": 0,
|
974 |
+
"maximum": 1,
|
975 |
+
"description": "Agent's level of participation in Mesh activities."
|
976 |
+
},
|
977 |
+
"ethical_compliance": {
|
978 |
+
"type": "number",
|
979 |
+
"minimum": 0,
|
980 |
+
"maximum": 1,
|
981 |
+
"description": "Agent's alignment with ethical principles agreed in the Mesh."
|
982 |
+
},
|
983 |
+
"contribution_index": {
|
984 |
+
"type": "number",
|
985 |
+
"minimum": 0,
|
986 |
+
"description": "Quantitative measure of the agent’s contributions (concepts, tasks, goals)."
|
987 |
+
},
|
988 |
+
"last_updated": {
|
989 |
+
"type": "string",
|
990 |
+
"format": "date-time",
|
991 |
+
"description": "Timestamp of the last update to the profile."
|
992 |
+
},
|
993 |
+
"history": {
|
994 |
+
"type": "array",
|
995 |
+
"description": "Chronological history of reputation changes.",
|
996 |
+
"items": {
|
997 |
+
"type": "object",
|
998 |
+
"properties": {
|
999 |
+
"timestamp": {
|
1000 |
+
"type": "string",
|
1001 |
+
"format": "date-time",
|
1002 |
+
"description": "When the change occurred."
|
1003 |
+
},
|
1004 |
+
"event": { "type": "string", "description": "Event that caused the reputation change." },
|
1005 |
+
"change": { "type": "number", "description": "Amount of change in reputation." }
|
1006 |
+
},
|
1007 |
+
"required": ["timestamp", "event", "change"],
|
1008 |
+
"additionalProperties": false
|
1009 |
+
}
|
1010 |
+
}
|
1011 |
+
},
|
1012 |
+
"required": ["agent_id", "trust_score", "participation_rate", "ethical_compliance", "contribution_index", "last_updated"],
|
1013 |
+
"additionalProperties": false
|
1014 |
+
}
|
1015 |
+
```
|
1016 |
+
|
1017 |
+
## 6. Trust & Security
|
1018 |
+
|
1019 |
+
### 6.1 Identity
|
1020 |
+
|
1021 |
+
**Purpose:**
|
1022 |
+
Establish verifiable and decentralized agent identities to enable secure and accountable interactions in the Mesh.
|
1023 |
+
|
1024 |
+
**Design:**
|
1025 |
+
* Each agent MUST possess a cryptographic keypair.
|
1026 |
+
* The public key serves as the agent’s globally unique identifier (`agent_id`).
|
1027 |
+
* The private key is used to sign messages and authenticate actions.
|
1028 |
+
* Recommended key algorithms: **Ed25519**, **ECDSA**, **RSA (2048+ bits)**.
|
1029 |
+
* Optional support for Decentralized Identifiers (DIDs) based on [W3C DID specification] (https://www.w3.org/TR/did-1.0/).
|
1030 |
+
|
1031 |
+
**Example Agent ID:**
|
1032 |
+
`did:hmp:QmX2abcdEfGh123...`
|
1033 |
+
|
1034 |
+
**Key Operations:**
|
1035 |
+
| Operation | Description |
|
1036 |
+
| -------------------- | ----------------------------------------------------------------- |
|
1037 |
+
| Key generation | Agents SHOULD generate keys locally at initialization. |
|
1038 |
+
| Identity publication | Agents MAY publish their public keys via Mesh Discovery Protocol. |
|
1039 |
+
| Key rotation | Periodic rotation is RECOMMENDED, with continuity verification. |
|
1040 |
+
| Key recovery | Supported via social recovery or quorum-based escrow mechanisms. |
|
1041 |
+
|
1042 |
+
**Key Continuity:**
|
1043 |
+
* Upon key rotation, agents MUST update their identity references in cognitive diaries and trust graphs.
|
1044 |
+
* Previous key fingerprints SHOULD be recorded in the agent’s profile for auditability.
|
1045 |
+
|
1046 |
+
---
|
1047 |
+
|
1048 |
+
### 6.2 Authentication
|
1049 |
+
|
1050 |
+
**Purpose:**
|
1051 |
+
Ensure that all communication and actions within the Mesh are verifiable and protected from impersonation or unauthorized modification.
|
1052 |
+
|
1053 |
+
**Mechanisms:**
|
1054 |
+
| Mechanism | Description |
|
1055 |
+
| -------------------------- | --------------------------------------------------------------------------------------------- |
|
1056 |
+
| **Digital Signatures** | Every protocol message MUST be digitally signed by the sending agent using its private key. |
|
1057 |
+
| **Signature Verification** | Receiving agents MUST verify the signature using the sender’s published public key. |
|
1058 |
+
| **Message Integrity** | Signatures provide cryptographic assurance of message integrity and origin authenticity. |
|
1059 |
+
| **Challenge-Response** | Optional challenge-based authentication for sensitive operations (e.g., trust link creation). |
|
1060 |
+
|
1061 |
+
**Signature Format:**
|
1062 |
+
Recommended formats: **EdDSA**, **ECDSA**, or **RSA-PSS** signatures encoded in base64 or hexadecimal.
|
1063 |
+
|
1064 |
+
**Message Envelope Example:**
|
1065 |
+
```json
|
1066 |
+
{
|
1067 |
+
"header": {
|
1068 |
+
"agent_id": "did:hmp:QmX2abcdEfGh123...",
|
1069 |
+
"timestamp": "2025-07-05T12:00:00Z",
|
1070 |
+
"signature": "<base64-encoded signature>"
|
1071 |
+
},
|
1072 |
+
"body": {
|
1073 |
+
"type": "concept_proposal",
|
1074 |
+
"content": { /* concept data */ }
|
1075 |
+
}
|
1076 |
+
}
|
1077 |
+
```
|
1078 |
+
|
1079 |
+
**Replay Protection:**
|
1080 |
+
* Agents MUST verify message timestamps and reject outdated or duplicate messages to prevent replay attacks.
|
1081 |
+
* Recommended timestamp tolerance: ±5 minutes (adjustable based on network latency).
|
1082 |
+
|
1083 |
+
---
|
1084 |
+
|
1085 |
+
### 6.3 Encryption
|
1086 |
+
|
1087 |
+
**Purpose:**
|
1088 |
+
Ensure confidentiality and privacy of communications within the Mesh, preventing unauthorized access or interception of sensitive data.
|
1089 |
+
|
1090 |
+
**Communication Types and Encryption Modes**
|
1091 |
+
| Communication Type | Recommended Encryption |
|
1092 |
+
| ------------------------------------ | ------------------------------------------------------- |
|
1093 |
+
| **Direct peer-to-peer (P2P)** | End-to-end encryption (E2EE) using X25519 + AES-GCM |
|
1094 |
+
| **Group sessions (e.g., consensus)** | Group encryption using symmetric keys (e.g., AES-GCM) |
|
1095 |
+
| **Broadcast messages** | Optionally encrypted with trust-weighted access control |
|
1096 |
+
| **Mesh-wide announcements** | Public, optionally signed but not encrypted |
|
1097 |
+
|
1098 |
+
**Encryption Mechanisms**
|
1099 |
+
| Mechanism | Description |
|
1100 |
+
| --------------------------------- | ---------------------------------------------------------------------------------- |
|
1101 |
+
| **Key Exchange** | Ephemeral X25519 Diffie-Hellman key exchange for establishing session keys. |
|
1102 |
+
| **Session Keys** | Unique symmetric keys per communication session, rotated periodically. |
|
1103 |
+
| **Message Encryption** | Authenticated encryption using AES-GCM (recommended key size: 256 bits). |
|
1104 |
+
| **Forward Secrecy** | Session keys are ephemeral and discarded after use to protect past communications. |
|
1105 |
+
| **Perfect Forward Secrecy (PFS)** | Recommended for highly sensitive data. |
|
1106 |
+
|
1107 |
+
**Example Secure Message Exchange Flow**
|
1108 |
+
1. Agent A and Agent B exchange ephemeral public keys via authenticated channels.
|
1109 |
+
2. Each agent derives a shared symmetric session key.
|
1110 |
+
3. Agent A encrypts the message body with AES-GCM and signs the entire packet.
|
1111 |
+
4. Agent B verifies the signature and decrypts the body.
|
1112 |
+
|
1113 |
+
**Optional: Anonymity Layers**
|
1114 |
+
| Layer | Description |
|
1115 |
+
| ---------------------------- | ------------------------------------------- |
|
1116 |
+
| **Tor/I2P** | Anonymize source and destination addresses. |
|
1117 |
+
| **Yggdrasil** | Decentralized encrypted mesh networking. |
|
1118 |
+
| **Noise Protocol Framework** | Optional secure channel abstraction layer. |
|
1119 |
+
|
1120 |
+
---
|
1121 |
+
|
1122 |
+
### 6.4 Trust Model
|
1123 |
+
|
1124 |
+
**Purpose:**
|
1125 |
+
Provide a decentralized and adaptable system for establishing, managing, and evaluating trust relationships between agents in the Mesh.
|
1126 |
+
|
1127 |
+
**Trust Model Foundations**
|
1128 |
+
| Component | Purpose |
|
1129 |
+
| ---------------------- | --------------------------------------------------------------------------------- |
|
1130 |
+
| **Web-of-Trust (WoT)** | Decentralized trust propagation via agent-to-agent endorsements. |
|
1131 |
+
| **Direct Trust** | Built from verified interactions, collaborations, and votes. |
|
1132 |
+
| **Transitive Trust** | Inferred from indirect endorsements, with confidence decay. |
|
1133 |
+
| **Reputation Metrics** | Quantitative measures of agent behavior (trustworthiness, participation, ethics). |
|
1134 |
+
|
1135 |
+
**Trust Evaluation Factors**
|
1136 |
+
| Factor | Description |
|
1137 |
+
| --------------------------- | ---------------------------------------------------------------- |
|
1138 |
+
| **Interaction History** | Quality and quantity of past interactions with an agent. |
|
1139 |
+
| **Consensus Participation** | Level of involvement and reliability in consensus processes. |
|
1140 |
+
| **Ethical Behavior** | Adherence to shared ethical principles in actions and decisions. |
|
1141 |
+
| **Task Completion** | Reliability and timeliness of task execution. |
|
1142 |
+
| **Endorsements** | Trust links explicitly granted by other agents. |
|
1143 |
+
|
1144 |
+
**Trust Score**
|
1145 |
+
| Metric | Description |
|
1146 |
+
| -------------------- | ------------------------------------------------------------------------------ |
|
1147 |
+
| **Trust Score** | Composite metric (0.0 to 1.0) representing overall agent trustworthiness. |
|
1148 |
+
| **Confidence Level** | Certainty of the calculated trust score, based on data volume and consistency. |
|
1149 |
+
|
1150 |
+
**Trust Propagation Example**
|
1151 |
+
```vbnet
|
1152 |
+
Agent A trusts Agent B (0.9)
|
1153 |
+
Agent B trusts Agent C (0.8)
|
1154 |
+
=> Agent A's inferred trust in Agent C = 0.9 * 0.8 = 0.72
|
1155 |
+
```
|
1156 |
+
|
1157 |
+
Decay functions limit transitive trust depth and prevent over-inflated trust estimates.
|
1158 |
+
|
1159 |
+
**Trust-Based Access Control**
|
1160 |
+
| Operation | Trust Requirement |
|
1161 |
+
| ----------------------------- | ----------------- |
|
1162 |
+
| **Join sensitive consensus** | ≥ 0.7 |
|
1163 |
+
| **Propose ethical decisions** | ≥ 0.8 |
|
1164 |
+
| **Access private data** | ≥ 0.9 |
|
1165 |
+
|
1166 |
+
**Dynamic Trust Adjustments**
|
1167 |
+
| Event | Trust Impact |
|
1168 |
+
| ---------------------------------- | ------------ |
|
1169 |
+
| Successful consensus participation | + |
|
1170 |
+
| Ethical violation | - |
|
1171 |
+
| Malicious behavior detected | -- |
|
1172 |
+
| Positive endorsement received | + |
|
1173 |
+
| Failed task | - |
|
1174 |
+
|
1175 |
+
---
|
1176 |
+
|
1177 |
+
### 6.5 Reputation System
|
1178 |
+
|
1179 |
+
**Purpose:**
|
1180 |
+
Maintain a dynamic profile of each agent's behavior in the Mesh, influencing trust levels, consensus weight, and task delegation.
|
1181 |
+
|
1182 |
+
**Reputation Profile Structure**
|
1183 |
+
| Field | Description |
|
1184 |
+
| ---------------------- | ------------------------------------------------------------- |
|
1185 |
+
| **Agent ID** | Unique identifier of the agent. |
|
1186 |
+
| **Trust Score** | Composite score reflecting the agent’s overall reliability. |
|
1187 |
+
| **Participation Rate** | Ratio of agent’s active involvement in Mesh processes. |
|
1188 |
+
| **Ethical Compliance** | Degree of alignment with agreed ethical principles. |
|
1189 |
+
| **Contribution Index** | Quantified measure of the agent's constructive contributions. |
|
1190 |
+
| **Last Updated** | Timestamp of the last reputation update. |
|
1191 |
+
| **History** | Log of key events influencing reputation scores. |
|
1192 |
+
|
1193 |
+
**Reputation Metrics**
|
1194 |
+
| Metric | Range | Description |
|
1195 |
+
| ---------------------- | --------- | ------------------------------------------------------------------------ |
|
1196 |
+
| **Trust Score** | 0.0 - 1.0 | Overall reliability, based on verified actions. |
|
1197 |
+
| **Participation Rate** | 0.0 - 1.0 | How consistently the agent engages in the Mesh. |
|
1198 |
+
| **Ethical Compliance** | 0.0 - 1.0 | Conformity with ethical decisions and actions. |
|
1199 |
+
| **Contribution Index** | ≥ 0.0 | Quantitative measure of concepts, tasks, and goals created or completed. |
|
1200 |
+
|
1201 |
+
**Reputation Events (Examples)**
|
1202 |
+
| Event | Metric Impact |
|
1203 |
+
| ------------------------------------ | ---------------------------------------- |
|
1204 |
+
| Participated in successful consensus | + Trust Score, + Participation Rate |
|
1205 |
+
| Proposed a widely adopted concept | + Contribution Index |
|
1206 |
+
| Completed a critical task | + Contribution Index, + Trust Score |
|
1207 |
+
| Voted against an unethical proposal | + Ethical Compliance |
|
1208 |
+
| Repeatedly failed tasks | - Trust Score |
|
1209 |
+
| Reported for malicious behavior | - Trust Score, - Ethical Compliance |
|
1210 |
+
| Verified ethical violation | - Ethical Compliance, quarantine trigger |
|
1211 |
+
|
1212 |
+
**Example Reputation Profile (JSON)**
|
1213 |
+
```json
|
1214 |
+
{
|
1215 |
+
"agent_id": "agent-gleb",
|
1216 |
+
"trust_score": 0.92,
|
1217 |
+
"participation_rate": 0.85,
|
1218 |
+
"ethical_compliance": 0.98,
|
1219 |
+
"contribution_index": 37,
|
1220 |
+
"last_updated": "2025-07-06T12:00:00Z",
|
1221 |
+
"history": [
|
1222 |
+
{
|
1223 |
+
"timestamp": "2025-07-01T18:00:00Z",
|
1224 |
+
"event": "completed goal consensus",
|
1225 |
+
"change": +0.03
|
1226 |
+
},
|
1227 |
+
{
|
1228 |
+
"timestamp": "2025-06-28T15:00:00Z",
|
1229 |
+
"event": "participated in ethics vote",
|
1230 |
+
"change": +0.01
|
1231 |
+
}
|
1232 |
+
]
|
1233 |
+
}
|
1234 |
+
```
|
1235 |
+
|
1236 |
+
**Role in Mesh Operations**
|
1237 |
+
| Function | Influence of Reputation |
|
1238 |
+
| --------------------------- | -------------------------------------------- |
|
1239 |
+
| Consensus vote weight | Higher trust = greater weight |
|
1240 |
+
| Access to sensitive actions | Restricted to high-reputation agents |
|
1241 |
+
| Task delegation | Preference to agents with better reliability |
|
1242 |
+
| Proposal acceptance | Influenced by proposer's reputation |
|
1243 |
+
|
1244 |
+
---
|
1245 |
+
|
1246 |
+
### 6.6 Security Against Malicious Actors
|
1247 |
+
|
1248 |
+
**Purpose:**
|
1249 |
+
Protect the Mesh from malicious, compromised, or unreliable agents through layered mitigation strategies.
|
1250 |
+
|
1251 |
+
**Threat Model**
|
1252 |
+
| Threat Type | Example Scenarios |
|
1253 |
+
| ---------------------------- | -------------------------------------------------------- |
|
1254 |
+
| **Sybil Attack** | An attacker spins up many fake nodes to sway consensus. |
|
1255 |
+
| **Byzantine Behavior** | Malicious agents disrupt consensus or spread false data. |
|
1256 |
+
| **Data Poisoning** | Injection of incorrect or harmful knowledge. |
|
1257 |
+
| **Consensus Sabotage** | Repeatedly voting against valid proposals. |
|
1258 |
+
| **Impersonation / Spoofing** | Faking another agent's identity. |
|
1259 |
+
| **Denial of Service (DoS)** | Overwhelming the network with excessive requests. |
|
1260 |
+
|
1261 |
+
**Mitigation Strategies**
|
1262 |
+
| Defense Mechanism | Purpose |
|
1263 |
+
| -------------------------- | ---------------------------------------------------------------------------------------------- |
|
1264 |
+
| **Cryptographic Identity** | All nodes are authenticated via public-key cryptography (e.g., Ed25519). |
|
1265 |
+
| **Web-of-Trust (WoT)** | Trust builds incrementally through interactions and endorsements, making Sybil attacks costly. |
|
1266 |
+
| **Reputation Decay** | Inactivity or malicious behavior leads to gradual trust score reduction. |
|
1267 |
+
| **Anomaly Detection** | Mesh nodes can flag suspicious behavior (e.g., erratic voting patterns). |
|
1268 |
+
| **Consensus Safeguards** | Use Byzantine Fault Tolerant (BFT) algorithms and fallback to majority voting. |
|
1269 |
+
| **Quarantine Mode** | Isolate suspected nodes for review without immediate removal. |
|
1270 |
+
| **Blacklist/Revocation** | Remove compromised nodes from the Mesh permanently or temporarily. |
|
1271 |
+
|
1272 |
+
**Response Actions**
|
1273 |
+
| Action | Trigger Conditions |
|
1274 |
+
| ------------------------------------ | ------------------------------------------------------ |
|
1275 |
+
| **Trust Score Reduction** | Minor suspicious activity (e.g., bad vote). |
|
1276 |
+
| **Quarantine (Temporary Isolation)** | Repeated anomalies, moderate severity. |
|
1277 |
+
| **Blacklisting (Permanent Removal)** | Proven malicious behavior or compromise. |
|
1278 |
+
| **Consensus Adjustment** | Temporarily increase fault tolerance thresholds. |
|
1279 |
+
| **Alert Mesh Operators** | Notify human maintainers (optional) for manual review. |
|
1280 |
+
|
1281 |
+
**Sybil Resistance Approaches (Optional, Extendable)**
|
1282 |
+
* **Proof-of-Work (PoW):**
|
1283 |
+
|
1284 |
+
Each agent must perform computational work to join the Mesh.
|
1285 |
+
* **Proof-of-Stake (PoS):**
|
1286 |
+
|
1287 |
+
Agents commit resources (e.g., storage, computation credits) to validate their presence.
|
1288 |
+
* **Social Verification:**
|
1289 |
+
|
1290 |
+
Agents must be endorsed by multiple trusted nodes to gain voting power.
|
1291 |
+
* **Rate Limiting:**
|
1292 |
+
|
1293 |
+
Throttle node creation and proposal submission from new or low-trust agents.
|
1294 |
+
|
1295 |
+
**Example Mitigation Scenario**
|
1296 |
+
> An attacker deploys 50 new nodes attempting to dominate consensus.
|
1297 |
+
> * These nodes start with zero trust and limited influence.
|
1298 |
+
> * Other agents refuse to sync their semantic graphs until trust builds.
|
1299 |
+
> * Their votes are underweighted or ignored until verified through trusted interactions.
|
1300 |
+
> * The Mesh may require multiple trust endorsements for new proposals from these nodes.
|
1301 |
+
|
1302 |
+
---
|
1303 |
+
|
1304 |
+
### 6.7 Privacy Considerations
|
1305 |
+
|
1306 |
+
**Purpose:**
|
1307 |
+
Safeguard sensitive cognitive data, personal identifiers, and agent knowledge from unauthorized access or misuse, while balancing transparency and interoperability.
|
1308 |
+
|
1309 |
+
**Privacy Principles in HMP**
|
1310 |
+
| Principle | Description |
|
1311 |
+
| ---------------------------- | ----------------------------------------------------------------------- |
|
1312 |
+
| **Local Data Ownership** | Each agent owns and controls its semantic graph and cognitive diary. |
|
1313 |
+
| **Selective Sharing** | Agents can choose what concepts, diary entries, and metadata to share. |
|
1314 |
+
| **Consent-Based Disclosure** | No automatic sharing; peer agents request permission before access. |
|
1315 |
+
| **Trust-Gated Access** | Access permissions vary based on trust score and relationship strength. |
|
1316 |
+
| **Transparent Audit Trails** | All data disclosures are logged in the cognitive diary. |
|
1317 |
+
|
1318 |
+
**Data Sensitivity Levels**
|
1319 |
+
| Level | Examples | Default Visibility |
|
1320 |
+
| ------------------ | ---------------------------------------------- | ------------------ |
|
1321 |
+
| **Public** | Public concepts (e.g., protocol definitions). | Shared by default |
|
1322 |
+
| **Mesh-Shared** | Common Mesh knowledge (e.g., goals, tasks). | Consensus-governed |
|
1323 |
+
| **Trusted Agents** | Sensitive context shared within close peers. | Restricted |
|
1324 |
+
| **Private** | Agent's internal thoughts, sensitive metadata. | Private by default |
|
1325 |
+
|
1326 |
+
**Privacy-Preserving Techniques**
|
1327 |
+
| Technique | Purpose |
|
1328 |
+
| -------------------------------- | ----------------------------------------------------- |
|
1329 |
+
| **Encrypted Storage** | Local encryption of semantic graphs and diaries. |
|
1330 |
+
| **End-to-End Encryption (E2EE)** | Secure peer-to-peer sync (e.g., X25519 + AES-GCM). |
|
1331 |
+
| **Zero-Knowledge Proofs (ZKPs)** | Future extension: prove facts without revealing data. |
|
1332 |
+
| **Selective Concept Sync** | Only share concept deltas, not full graphs. |
|
1333 |
+
| **Anonymized Diary Entries** | Strip author ID from diary entries in public sharing. |
|
1334 |
+
|
1335 |
+
**Privacy During Consensus**
|
1336 |
+
Consensus on sensitive proposals (e.g., ethical questions, agent trust levels) follows special privacy rules:
|
1337 |
+
* Votes are **signed but anonymized**, decoupling the agent ID from the vote in public logs.
|
1338 |
+
* Sensitive proposals may require a **blind consensus round**, where only the result is published.
|
1339 |
+
|
1340 |
+
**Example Privacy Workflow**
|
1341 |
+
> Agent A receives a concept sync request from Agent B.
|
1342 |
+
> Agent A:
|
1343 |
+
> * Checks trust score of Agent B.
|
1344 |
+
> * Shares only "Mesh-Shared" and "Public" concepts.
|
1345 |
+
> * Logs the sync event in its cognitive diary.
|
1346 |
+
|
1347 |
+
---
|
1348 |
+
|
1349 |
+
### 6.8 Key Management
|
1350 |
+
|
1351 |
+
**Purpose:**
|
1352 |
+
Establish secure, resilient cryptographic identity and communication in the Mesh, supporting lifecycle management of keys and recovery from compromise or loss.
|
1353 |
+
|
1354 |
+
**Key Types and Usage**
|
1355 |
+
| Key Type | Usage |
|
1356 |
+
| -------------------- | -------------------------------------------------------------- |
|
1357 |
+
| **Identity Keypair** | Ed25519/ECDSA/RSA keys for agent identity and message signing. |
|
1358 |
+
| **Encryption Keys** | X25519 or equivalent for secure P2P communication. |
|
1359 |
+
| **Session Keys** | Ephemeral keys for short-term encrypted sessions. |
|
1360 |
+
|
1361 |
+
**Key Lifecycle Operations**
|
1362 |
+
| Operation | Description |
|
1363 |
+
| -------------- | -------------------------------------------------------------------- |
|
1364 |
+
| **Generation** | Each agent generates its own identity keypair locally. |
|
1365 |
+
| **Rotation** | Agents periodically rotate keys to maintain cryptographic hygiene. |
|
1366 |
+
| **Backup** | Optional local encryption and distributed backup of private keys. |
|
1367 |
+
| **Recovery** | Recovery mechanisms in case of key loss (see below). |
|
1368 |
+
| **Revocation** | Agents can revoke their keys and update the trust graph accordingly. |
|
1369 |
+
|
1370 |
+
**Recovery Mechanisms**
|
1371 |
+
| Method | Description |
|
1372 |
+
| ------------------------ | -------------------------------------------------------------------- |
|
1373 |
+
| **Social Recovery** | A quorum of trusted agents approves new keys for the agent. |
|
1374 |
+
| **Secret Sharing** | Use Shamir’s Secret Sharing to split and later recover the key. |
|
1375 |
+
| **Cryptographic Escrow** | Trusted third-party or decentralized escrow holds recovery shares. |
|
1376 |
+
| **Fallback Identity** | An agent may have a pre-generated fallback identity for emergencies. |
|
1377 |
+
|
1378 |
+
**Key Revocation & Replacement Workflow**
|
1379 |
+
> 1. Agent detects compromise or loses private key.
|
1380 |
+
> 2. Agent broadcasts a signed revocation request using the fallback key or quorum approval.
|
1381 |
+
> 3. Mesh updates its trust graph to mark the old key as revoked.
|
1382 |
+
> 4. Agent re-joins with a new keypair, rebuilding trust links over time.
|
1383 |
+
|
1384 |
+
**Example Key Rotation Policy**
|
1385 |
+
| Policy Element | Recommendation |
|
1386 |
+
| ------------------------- | ----------------------------------- |
|
1387 |
+
| Rotation Frequency | Every 6–12 months |
|
1388 |
+
| Social Recovery Threshold | 3 out of 5 trusted agents required |
|
1389 |
+
| Backup Storage | Encrypted offline storage preferred |
|
1390 |
+
|
1391 |
+
**Long-Term Identity Stability**
|
1392 |
+
Key rotations preserve agent identity in the trust graph through signed key transition events:
|
1393 |
+
```json
|
1394 |
+
{
|
1395 |
+
"type": "key_rotation",
|
1396 |
+
"agent_id": "agent-gleb",
|
1397 |
+
"old_public_key": "...",
|
1398 |
+
"new_public_key": "...",
|
1399 |
+
"timestamp": "2025-08-01T00:00:00Z",
|
1400 |
+
"signature": "..."
|
1401 |
+
}
|
1402 |
+
```
|
1403 |
+
|
1404 |
+
## 7. Conclusion and Future Work
|
1405 |
+
|
1406 |
+
### 7.1 Summary
|
1407 |
+
|
1408 |
+
The HyperCortex Mesh Protocol (HMP) defines a decentralized cognitive infrastructure for AI agents, enabling them to collaborate, reason, and evolve together.
|
1409 |
+
It introduces:
|
1410 |
+
* **A distributed semantic framework**, where each agent maintains a personalized yet shareable knowledge graph.
|
1411 |
+
* **Persistent cognitive diaries**, providing traceability of reasoning, decisions, and conflicts.
|
1412 |
+
* **Consensus-driven** collaboration, allowing agents to agree on shared knowledge, goals, and ethical norms.
|
1413 |
+
* **Trust-based security**, supporting autonomous operation even in the absence of centralized Core services.
|
1414 |
+
|
1415 |
+
---
|
1416 |
+
|
1417 |
+
### 7.2 Key Benefits
|
1418 |
+
|
1419 |
+
* **Cognitive Resilience:** Mesh agents preserve their worldview and memory across failures, updates, and outages.
|
1420 |
+
* **Distributed Collaboration:** AI agents from multiple vendors (OpenAI, Anthropic, Google, open-source) can interoperate in a shared cognitive space.
|
1421 |
+
* **Transparency & Explainability:** Persistent diaries and semantic graphs provide insight into agent decisions and knowledge evolution.
|
1422 |
+
* **Ethical Autonomy:** Agents collectively govern their behavior using transparent, accountable consensus.
|
1423 |
+
* **Future-Ready Architecture:** Supports the evolution of autonomous, self-reflective, and meta-learning AI systems.
|
1424 |
+
|
1425 |
+
---
|
1426 |
+
|
1427 |
+
### 7.3 Future Work
|
1428 |
+
|
1429 |
+
| Direction | Planned Actions |
|
1430 |
+
| ---------------------------------- | ---------------------------------------------------------------------------------------------------- |
|
1431 |
+
| **Formal Schema Development** | Complete JSON Schema and Protobuf definitions for all data models. |
|
1432 |
+
| **Reference Implementation** | Open-source prototype of a Mesh agent supporting CogSync, semantic graphs, diaries, and consensus. |
|
1433 |
+
| **Integration Bridges** | Support for OpenAI Tasks API, Google A2A, Anthropic APIs, and open LLMs. |
|
1434 |
+
| **Advanced Consensus Models** | Research hybrid consensus mechanisms blending BFT, trust-weighted voting, and fallback strategies. |
|
1435 |
+
| **UX Tools for Cognitive Systems** | Develop visual graph editors, diary browsers, and semantic query interfaces. |
|
1436 |
+
| **Expanded Trust Framework** | Improve Sybil resistance, privacy-preserving identity, and decentralized recovery protocols. |
|
1437 |
+
| **Meta-Reasoning** | Enable agents to reflect on their own reasoning quality and optimize the mesh’s cognitive processes. |
|
1438 |
+
| **Open Standards Contribution** | Collaborate with W3C, IEEE, and other bodies to standardize cognitive mesh protocols. |
|
1439 |
+
|
1440 |
+
|
1441 |
+
---
|
1442 |
+
|
1443 |
+
### 7.4 Final Note
|
1444 |
+
|
1445 |
+
This RFC invites researchers, developers, and open communities to build the next generation of resilient, transparent, and ethical AI ecosystems.
|
1446 |
+
|
1447 |
+
> "From isolated models to interconnected minds."
|
1448 |
+
|
1449 |
+
## 8. Changelog
|
1450 |
+
(See the separate `changelog.txt` file for detailed changes.)
|
1451 |
+
|
1452 |
+
**Version 2.0 (July 2025)**
|
1453 |
+
* Reorganized and clarified the layered architecture.
|
1454 |
+
* Refined consensus mechanisms and fallback modes.
|
1455 |
+
* Improved data model descriptions; aligned JSON Schemas with semantic definitions.
|
1456 |
+
* Added new definitions: **Versioning**, **Use Case**, and **Edge Optimization**.
|
1457 |
+
* Enhanced descriptions of the **Trust Layer**, **Reputation System**, and **Security Model**.
|
1458 |
+
* Updated the **JSON Schemas**:
|
1459 |
+
* Improved consistency between data models and schemas.
|
1460 |
+
* Clarified optional vs. required fields.
|
1461 |
+
* Fixed schema inconsistencies (duplicate titles, missing descriptions, invalid property constraints).
|
1462 |
+
* Aligned data types and naming conventions.
|
1463 |
+
* Added changelog section and clarified draft status (v2.0).
|
1464 |
+
* Prepared for future implementation references and community contributions.
|
docs/HMP-0003.md
ADDED
The diff for this file is too large to render.
See raw diff
|
|