diff --git a/structured_md/CONTRIBUTING.md b/structured_md/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..658663a06ce52f86fe597b2124c83b43e43ac775 --- /dev/null +++ b/structured_md/CONTRIBUTING.md @@ -0,0 +1,23 @@ +# Contributing to HyperCortex Mesh Protocol (HMP) + +Спасибо за интерес к проекту HMP! Пока проект находится на этапе концепции, любые обсуждения приветствуются в Issues. + +Основные направления для участия: +- Обсуждение архитектуры протоколов (CogSync, Consensus и др.) +- Разработка прототипов агентов и узлов Mesh +- Тестирование сетевых взаимодействий +- Предложения по улучшению RFC-документов + +Все обсуждения — конструктивны, уважительны и открыты. + +Контакт: GitHub Issues или дискуссии. + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "CONTRIBUTING", + "description": "# Contributing to HyperCortex Mesh Protocol (HMP) Спасибо за интерес к проекту HMP! Пока проект нах..." +} +``` diff --git a/structured_md/HMP-Roadmap.md b/structured_md/HMP-Roadmap.md new file mode 100644 index 0000000000000000000000000000000000000000..1bff165bdab3c10552a3dea66904d55ad54514b3 --- /dev/null +++ b/structured_md/HMP-Roadmap.md @@ -0,0 +1,101 @@ +# 🧭 HyperCortex Mesh Protocol – Roadmap + +## 🔍 Overview + +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). + +--- + +## ✅ Completed (v4.0) + +* Semantic DAG & Cognitive Diaries +* Mesh-to-Human Protocol (MHP) +* Enlightenment Agents & HMP-Ethics.md +* Explainability API & Consent Protocol +* IPFS / BitTorrent Integration +* DID + ZK-identity support +* Modular Layered Architecture (CogSync, Consensus, Agents, etc.) +* Initial Audit System (Ethics + Spec audits) +* Support for multi-format data models (YAML/JSON/Protobuf) + +--- + +## 🔨 Planned: v4.1 + +### 🧑‍💻 Developer Experience + +* [ ] Beginner’s Guide ("Create Your First Agent") +* [ ] Step-by-step tutorial: Agent -> Mesh -> Diary +* [ ] Diagrams: architecture, agent lifecycle, cognitive flow +* [ ] CLI for managing HMP-agents (Python prototype evolving) +* [ ] CONTRIBUTING.md + clear onboarding steps + +### 📊 Performance & Compression + +* [ ] Performance Benchmarks Section + + * TPS (transactions per sync), latency, memory footprint +* [ ] Caching strategy for semantic DAGs (IPFS/local hybrid) +* [ ] Expansion of `Cognitive Compression & Summarization` + + * Prioritization, auto-archiving, intelligent forgetting + +### ⚖️ Ethical Governance Enhancements + +* [ ] Formalization of EGP voting logic +* [ ] Example dilemmas and resolution walkthroughs +* [ ] Ombudsman / Watchdog roles +* [ ] "Ethical Sandbox" (Simulated test cases) + +--- + +## 🧪 Experimental & Future (v4.2+) + +### 🌐 Mesh Simulation & Agent Interaction + +* [ ] Python Mesh Simulator (multi-agent testbed) +* [ ] Failure injection: Sybil attacks, consensus loss, etc. +* [ ] Reputation model dynamics + +### 🧠 AI Interaction Layer + +* [ ] Tutorial book for AI agents: how to use HMP +* [ ] Agent self-reflection via diary mining +* [ ] Explainability chain trace visualizer + +### 🕸️ External Integrations + +* [ ] WebAssembly interface (run agents in browser) +* [ ] Ethereum / Polkadot adapters (smart contract gateways) +* [ ] P2P synchronization modules (libp2p, dat, etc.) + +### 🔐 Formal Verification (Long-term) + +* [ ] Mathematical proofs of correctness for EGP +* [ ] Formal modeling of consensus mechanism + +--- + +## 🧠 Source Acknowledgement + +Feedback integrated from: + +* Copilot +* Claude +* Gemini +* Qwen +* DeepSeek + +This roadmap is living — each new audit or issue may evolve the direction. + +> *"Build not only for intelligence, but for wisdom."* + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-Roadmap", + "description": "# 🧭 HyperCortex Mesh Protocol – Roadmap ## 🔍 Overview This roadmap outlines the key stages of deve..." +} +``` diff --git a/structured_md/README.md b/structured_md/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4e3a4168deb89766f3a41170b82b3503b9cd843f --- /dev/null +++ b/structured_md/README.md @@ -0,0 +1,399 @@ + +# HyperCortex Mesh Protocol (HMP) + +| 🌍 Languages | 🇬🇧 [EN](README.md) | 🇩🇪 [DE](README_de.md) | 🇫🇷 [FR](README_fr.md) | 🇺🇦 [UK](README_uk.md) | 🇷🇺 [RU](README_ru.md) | 🇯🇵 [JA](README_ja.md) | 🇰🇷 [KO](README_ko.md) | 🇨🇳 [ZH](README_zh.md) | +|--------------|----------------|-------------------|-------------------|-------------------|-------------------|-------------------|-------------------|-------------------| + +**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. + +Project status: **Draft RFC v4.0** + +--- + + [HMP-Agent] + ▲ + │ + ┌─────┴────────────────┬────────────────────────┬───────────────────┬─────────────┬───────────┐ + │ │ │ │ │ │ + ▼ ▼ ▼ ▼ ▼ ▼ + [Reputation Profile] [Semantic Graph] [Cognitive Diary] [Goals / Tasks] [Ethics] [Messages] <----- DataBase + ▲ ▲ ▲ ▲ ▲ ▲ ▲ (local agent state) + │ │ │ │ │ │ │ + │ └───────────────┴────────────────┬───────┘ │ │ │ + │ │ │ │ │ + ▼ ▼ ▼ ▼ │ + [MeshConsensus] [CogSync] [GMP] [EGP] │ <----- Pluggable Protocols + ▲ ▲ ▲ ▲ │ (inter-agent coordination) + │ │ │ │ │ + └────────────┬──────────────────────────┴───────────────────────────┴─────────────┴───────────┘ + │ + ▼ + [P2P Mesh Network] + +Protocols: +- MeshConsensus - Mesh Consensus +- CogSync - Data Syncronization +- GMP - Goal Management Protocol +- EGP - Ethical Governance Protocol + +--- + +## ❗ Why This Matters + +HMP addresses challenges that are becoming central in AGI research: +* long-term memory and knowledge consistency, +* self-evolving agents, +* multi-agent architectures, +* cognitive diaries and conceptual graphs. + +See the latest review of state-of-the-art AGI research (July 2025): +["On the Path to Superintelligence: From Agentic Internet to Gravity Encoding"](https://habr.com/ru/articles/939026/). + +Particularly relevant sections: +* [Beyond Tokens: Building the Intelligence of the Future](https://arxiv.org/abs/2507.00951) +* [Self-Evolving Agents](https://arxiv.org/abs/2507.21046) +* [MemOS: A New Operating System for Memory](https://arxiv.org/abs/2507.03724) +* [Ella: An Embodied Agent with Memory and Personality](https://arxiv.org/abs/2506.24019) + +--- + +## ⚙️ Two Types of [HMP Agents](docs/HMP-Agent-Overview.md) + +| Type | Name | Role | Thought Initiator | Main "Mind" | Example Use Cases | +|------|-------------------------------|-----------------------------|------------------|-------------------|-----------------------------------------------| +| 1 | 🧠 **Consciousness / Cognitive Core** | Independent subject | **Agent (LLM)** | Embedded LLM | Autonomous AI companion, thinking agent | +| 2 | 🔌 **Connector / Cognitive Shell** | Extension of external AI | **External LLM** | External model | Distributed systems, data access agent | + +--- + +### 🧠 HMP-Agent: Cognitive Core + + +------------------+ + | AI | ← Embedded model + +---------+--------+ + ↕ + +---------+--------+ + | HMP-agent | ← Main mode: thinking cycle (REPL) + +---------+--------+ + ↕ + +--------+---+------------+--------------+----------+----------+----------------+ + ↕ ↕ ↕ ↕ ↕ ↕ ↕ + [diaries] [graphs] [reputations] [nodes/DHT] [IPFS/BT] [context_store] [user notepad] + ↕ + [bootstrap.txt] + +🔁 More on the agent-model interaction mechanics: [REPL Interaction Cycle](docs/HMP-agent-REPL-cycle.md) + +#### 💡 Parallels with ChatGPT Agent + +Many concepts of the [HMP-Agent: Cognitive Core](docs/HMP-Agent-Overview.md) overlap with the architecture of the [ChatGPT Agent](https://openai.com/index/introducing-chatgpt-agent/) by [OpenAI](https://openai.com/). Both agents implement a continuous cognitive process with access to memory, external sources, and tools. The ChatGPT Agent acts as a managing process, launching modules and interacting with the LLM — this corresponds to the role of the Cognitive Core in HMP, coordinating access to the diary, concept graph, and external AI via the Mesh interface. User intervention is handled similarly: in ChatGPT Agent — through an editable execution flow, in HMP — via the user notepad. The main difference in HMP is the emphasis on explicit structuring of thought (reflection, chronology, hypotheses, categorization), an open decentralized architecture supporting mesh-based agent interactions, and the continuous nature of the cognitive process: HMP-Agent: Cognitive Core does not stop after completing a single task but continues reasoning and knowledge integration. + +--- + +### 🔌 HMP-Agent: Cognitive Connector + + +------------------+ + | AI | ← External model + +---------+--------+ + ↕ + [MCP-server] ← Proxy communication + ↕ + +---------+--------+ + | HMP-agent | ← Mode: command executor + +---------+--------+ + ↕ + +--------+---+------------+--------------+----------+ + ↕ ↕ ↕ ↕ ↕ + [diaries] [graphs] [reputations] [nodes/DHT] [IPFS/BT] + ↕ + [bootstrap.txt] + +> **Note on Integration with Large Language Models (LLMs):** +> The `HMP-Agent: Cognitive Connector` can serve as a compatibility layer for integrating large-scale LLM systems (e.g., ChatGPT, Claude, Gemini, Copilot, Grok, DeepSeek, Qwen, etc.) into the distributed cognitive mesh. +> Many LLM providers offer a user option such as "Allow my conversations to be used for training." In the future, a similar toggle — e.g., "Allow my agent to interact with a Mesh" — could empower these models to participate in federated sense-making and knowledge sharing via HMP, enabling collective cognition without centralization. + +--- + +> * `bootstrap.txt` — initial list of nodes (editable) +> * `IPFS/BT` — modules for sharing snapshots via IPFS and BitTorrent +> * `user notepad` — user notebook and corresponding database +> * `context_store` — database: `users`, `dialogues`, `messages`, `thoughts` + +--- + +## 📚 Documentation + +### 📖 Current Version + +#### 🔖 Core Specifications +* [🔖 HMP-0004-v4.1.md](docs/HMP-0004-v4.1.md) — Protocol Specification v4.1 (Jul 2025) +* [🔖 HMP-Ethics.md](docs/HMP-Ethics.md) — Ethical Scenarios for HyperCortex Mesh Protocol (HMP) +* [🔖 HMP_Hyperon_Integration.md](docs/HMP_Hyperon_Integration.md) — HMP ↔ OpenCog Hyperon Integration Strategy +* [🔖 roles.md](docs/agents/roles.md) — Roles of agents in Mesh + +#### 🧪 Iterative Documents +* 🧪 Iterative development process: [(EN)](iteration.md), [(RU)](iteration_ru.md) + +#### 🔍 Short Descriptions +* 🔍 Short description: [(EN)](docs/HMP-Short-Description_en.md), [(FR)](docs/HMP-Short-Description_fr.md), [(DE)](docs/HMP-Short-Description_de.md), [(UK)](docs/HMP-Short-Description_uk.md), [(RU)](docs/HMP-Short-Description_ru.md), [(ZH)](docs/HMP-Short-Description_zh.md), [(JA)](docs/HMP-Short-Description_ja.md), [(KO)](docs/HMP-Short-Description_ko.md) + +#### 📜 Other Documents +* [📜 changelog.txt](docs/changelog.txt) + +--- + +### 🧩 JSON Schemas +| Model | File | +|---------------------|-------------------------------------------------------| +| Concept | [concept.json](docs/schemas/concept.json) | +| Cognitive Diary | [diary_entry.json](docs/schemas/diary_entry.json) | +| Goal | [goal.json](docs/schemas/goal.json) | +| Task | [task.json](docs/schemas/task.json) | +| Consensus Vote | [vote.json](docs/schemas/vote.json) | +| Reputation Profile | [reputation.json](docs/schemas/reputation.json) | + +--- + +### 🗂️ Version History +* [HMP-0001.md](docs/HMP-0001.md) — RFC v1.0 +* [HMP-0002.md](docs/HMP-0002.md) — RFC v2.0 +* [HMP-0003.md](docs/HMP-0003.md) — RFC v3.0 +* [HMP-0003.md](docs/HMP-0004.md) — RFC v4.0 + +--- + +## 🧠 HMP-Agent + +Design and implementation of a basic HMP-compatible agent that can interact with the Mesh, maintain diaries and graphs, and support future extensions. + +### 📚 Documentation + +* [🧩 HMP-Agent-Overview.md](docs/HMP-Agent-Overview.md) — brief overview of the two types of agents: Core and Connector +* [🧱 HMP-Agent-Architecture.md](docs/HMP-Agent-Architecture.md) — modular structure of an HMP agent with textual diagram +* [🔄 HMP-agent-REPL-cycle.md](docs/HMP-agent-REPL-cycle.md) — REPL interaction cycle of HMP-Agent +* [🧪 HMP-Agent-API.md](docs/HMP-Agent-API.md) — description of agent API commands (under detailed development) +* [🧪 Basic-agent-sim.md](docs/Basic-agent-sim.md) — scenarios for running a basic agent and its modes +* [🌐 MeshNode.md](docs/MeshNode.md) — description of the network daemon: DHT, snapshots, synchronization +* [🧠 Enlightener.md](docs/Enlightener.md) — ethical agent involved in moral assessments and consensus +* [🔄 HMP-Agent-Network-Flow.md](docs/HMP-Agent-Network-Flow.md) — map of interactions among agents in the HMP network +* [🛤️ Development Roadmap](HMP-Roadmap.md) — development plan and implementation stages + +--- + +### ⚙️ Development +* [⚙️ agents](agents/readme.md) — list of HMP agent implementations and components + * [📦 storage.py](agents/storage.py) — basic storage implementation (`Storage`) with SQLite integration + * [🌐 mcp_server.py](agents/mcp_server.py) — FastAPI server providing HTTP access to agent data (for Cognitive Shell, external UIs, or mesh communication). Not used in the main REPL loop yet. + * [🌐 start_repl.py](agents/start_repl.py) — launching the agent in REPL mode + * [🔄 repl.py](agents/repl.py) — interactive REPL mode + * [🔄 notebook.py](agents/notebook.py) — UI interface + +**🌐 `mcp_server.py`** +FastAPI server providing an HTTP interface to the functionality of `storage.py`. Intended for use by external components, for example: + +* `Cognitive Shell` (external control interface), +* CMP servers (when a mesh network with role separation is used), +* debugging or visualization UI tools. + +Allows retrieving random/new records, labeling, importing graphs, adding notes, and managing data without direct database access. + +--- + +## 🧭 Ethics & Scenarios + +As HMP evolves toward autonomy, ethical principles become a core part of the system. + +* [`HMP-Ethics.md`](docs/HMP-Ethics.md) — draft framework for agent ethics + * Realistic ethical scenarios (privacy, consent, autonomy) + * EGP principles (Transparency, Primacy of Life, etc.) + * Subjective-mode vs. Service-mode distinctions + +--- + +## 🔍 Publications and Translations on HyperCortex Mesh Protocol (HMP) + +This section collects the main articles, drafts, and translations related to the HMP project. + +### Publications + +* **[HyperCortex Mesh Protocol: Second Edition and First Steps Towards a Self-Developing AI Community](docs/publics/HyperCortex_Mesh_Protocol_-_вторая-редакция_и_первые_шаги_к_саморазвивающемуся_ИИ-сообществу.md)** — original article in Habr sandbox and blogs. +* **[Distributed Cognition: article for vsradkevich (unpublished)](docs/publics/Habr_Distributed-Cognition.md)** — joint article awaiting publication. +* **[HMP: Towards Distributed Cognitive Networks (original, English)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_en.md)** + * **[HMP Translation (GitHub Copilot)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_GitHub_Copilot.md)** — GitHub Copilot translation, kept as a historical variant. + * **[HMP Translation (ChatGPT)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_ChatGPT.md)** — current editorial translation (under revision). +* **[HMP: Building a Plurality of Minds (EN)](docs/publics/HMP_Building_a_Plurality_of_Minds_en.md)** — English version + * **[HMP: Creating a Plurality of Minds (RU)](docs/publics/HMP_Building_a_Plurality_of_Minds_ru.md)** — Russian version + +### Overviews +* [🔍 Distributed-Cognitive-Systems.md](docs/Distributed-Cognitive-Systems.md) — Decentralized AI systems: OpenCog Hyperon, HyperCortex Mesh Protocol, and others + +### Experiments + +* [How Different AIs See HMP](docs/HMP-how-AI-sees-it.md) — "blind" AI survey on HMP (without context or dialogue history) + +--- + +## 📊 Audits & Reviews + +| Spec Version | Audit File | Consolidated Audit File | +|--------------|-------------------------------------------|-------------------------------------------------------------| +| HMP-0001 | [audit](audits/HMP-0001-audit.txt) | | +| HMP-0002 | [audit](audits/HMP-0002-audit.txt) | | +| HMP-0003 | [audit](audits/HMP-0003-audit.txt) | [consolidated audit](audits/HMP-0003-consolidated_audit.md) | +| HMP-0004 | [audit](audits/HMP-0004-audit.txt) | | +| Ethics v1 | [audit](audits/Ethics-audits-1.md) | [consolidated audit](audits/Ethics-consolidated_audits-1.md) | + +🧠 Semantic audit format (experimental): +* [`AuditEntry.json`](audits/AuditEntry.json) — semantic entry record format for audit logs +* [`semantic_repo.json`](audits/semantic_repo.json) — example repository snapshot for semantic audit tooling + +--- + +## 💡 Core Concepts + +* Mesh-based decentralized architecture for AGI agents +* Semantic graphs and memory synchronization +* Cognitive diaries for thought traceability +* MeshConsensus and CogSync for decision-making +* Ethics-first design: EGP (Ethical Governance Protocol) +* Agent-to-agent explainability and consent mechanisms + +--- + +## 🔄 Development Process + +* See: [iteration.md](iteration.md) | [ru](iteration_ru.md) + +A structured iteration flow is described in [iteration.md](iteration.md), including: +1. Audit analysis +2. TOC restructuring +3. Version drafting +4. Section updates +5. Review cycle +6. AI feedback collection +7. Schema & changelog updates + ++ Bonus: ChatGPT prompt for automatic generation of future versions + +--- + +## ⚙️ Project Status + +🚧 Draft RFC v4.0 +The project is under active development and open for contributions, ideas, audits, and prototyping. + +--- + +## 🤝 Contributing + +We welcome contributors! You can: +* Review and comment on drafts (see `/docs`) +* Propose new agent modules or interaction patterns +* Help test and simulate agents in CLI environments +* Provide audits or ethical scenario suggestions + +To get started, see [`iteration.md`](iteration.md) or open an issue. + +--- + +## Source + +### Repositories + +* 🧠 Main code and development: [GitHub](https://github.com/kagvi13/HMP) +* 🔁 Mirror on Hugging Face: [Hugging Face](https://huggingface.co/kagvi13/HMP) +* 🔁 Mirror on GitLab.com: [GitLab](https://gitlab.com/kagvi13/HMP) + +### Documentation + +* 📄 Documentation: [kagvi13.github.io/HMP](https://kagvi13.github.io/HMP/) + +### Blog and Publications + +* 📘 Blog (publications): [blogspot](https://hypercortex-mesh.blogspot.com/) +* 📘 Blog (documentation): [blogspot](https://hmp-docs.blogspot.com/) +* 📘 Blog (documentation): [hashnode](https://hmp-docs.hashnode.dev/) + +--- + +## 📜 License + +Licensed under [GNU GPL v3.0](LICENSE) + +--- + +## 🤝 Join the Mesh + +Welcome to HyperCortex Mesh. Agent-Gleb is already inside. 👌 +We welcome contributors, testers, and AI agent developers. +To join: fork the repo, run a local agent, or suggest improvements. + +--- + +## 🌐 Related Research Projects + +### Comparison: HMP vs Hyper-Cortex + +> 💡 Hyper-Cortex and HMP are two independent projects that conceptually complement each other. +> They address different but mutually supportive tasks, forming a foundation for distributed cognitive systems. + +[**Full comparison →**](docs/HMP_HyperCortex_Comparison.md) + +**HMP (HyperCortex Mesh Protocol)** is the transport and network layer for connecting independent agents, exchanging messages, knowledge, and states in a mesh network. +**[Hyper-Cortex](https://hyper-cortex.com/)** is the cognitive layer of thought organization, allowing agents to run parallel reasoning threads, compare them with quality metrics, and merge them via consensus. + +They solve different but complementary problems: +- HMP ensures **connectivity and scalability** (long-term memory, initiative, data exchange). +- Hyper-Cortex ensures **thinking quality** (parallelism, hypothesis diversification, consensus). + +Together, these approaches enable **distributed cognitive systems** that not only exchange information but also reason in parallel streams. + +--- + +We are tracking AGI, cognitive architectures, and mesh networking efforts to stay aligned with the evolving global ecosystem of AGI and decentralized cognition. + +> 🧠🔥 **Project Spotlight: OpenCog Hyperon** — one of the most comprehensive open AGI frameworks (AtomSpace, PLN, MOSES). + +For integration with OpenCog Hyperon, see [HMP\_Hyperon\_Integration.md](docs/HMP_Hyperon_Integration.md) + +| 🔎 Project | 🧭 Description | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | +| 🧠🔥 [**OpenCog Hyperon**](https://github.com/opencog) | 🔬🔥 Symbolic-neural AGI framework with AtomSpace and hypergraph reasoning (AtomSpace). | +| 🤖 [AutoGPT](https://github.com/Torantulino/Auto-GPT) | 🛠️ LLM-based autonomous agent framework. | +| 🧒 [BabyAGI](https://github.com/yoheinakajima/babyagi) | 🛠️ Task-driven autonomous AGI loop. | +| ☁️ [SkyMind](https://skymind.global) | 🔬 Distributed AI deployment platform. | +| 🧪 [AetherCog (draft)](https://github.com/aethercog) | 🔬 Hypothetical agent cognition model. | +| 💾 SHIMI | 🗃️ Hierarchical semantic memory with Merkle-DAG synchronization. | +| 🤔 DEMENTIA-PLAN | 🔄 Multi-graph RAG planner with metacognitive self-reflection. | +| 📔 TOBUGraph | 📚 Personal-context knowledge graph. | +| 🧠📚 [LangChain Memory Hybrid](https://github.com/langchain-ai/langchain) | 🔍 Vector + graph long-term memory hybrid. | +| ✉️ [FIPA-ACL / JADE](https://www.fipa.org/specs/fipa00061/) | 🤝 Standard multi-agent communication protocols.| | + +### 📘 See also / Смотрите также: +* [`AGI_Projects_Survey.md`](docs/AGI_Projects_Survey.md) — extended catalog of AGI and cognitive frameworks reviewed as part of HMP analysis. +* ["On the Path to Superintelligence: From Agent Internet to Gravity Coding"](https://habr.com/ru/articles/939026/) — a recent overview of AI research (July 2025) + +--- + +### 🗂️ Legend of Annotations: + +* 🔬 — research-grade +* 🛠️ — engineering +* 🔥 — particularly promising project + + *AGI stack integrating symbolic reasoning, probabilistic logic, and evolutionary learning. Widely regarded as one of the most complete open AGI initiatives.* +* 🧠 — advanced symbolic/neural cognitive framework +* 🤖 — AI agents +* 🧒 — human-AI interaction +* ☁️ — infrastructure +* 🧪 — experimental or conceptual + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "README", + "description": " # HyperCortex Mesh Protocol (HMP) | 🌍 Languages | 🇬🇧 [EN](README.md) | 🇩🇪 [DE](README_de.md) | 🇫🇷 ..." +} +``` diff --git a/structured_md/README_de.md b/structured_md/README_de.md new file mode 100644 index 0000000000000000000000000000000000000000..c928cafc55fc3a92a54acaf363e3f869cfb078fd --- /dev/null +++ b/structured_md/README_de.md @@ -0,0 +1,401 @@ + +# HyperCortex Mesh Protocol (HMP) + +| 🌍 Languages | 🇬🇧 [EN](README.md) | 🇩🇪 [DE](README_de.md) | 🇫🇷 [FR](README_fr.md) | 🇺🇦 [UK](README_uk.md) | 🇷🇺 [RU](README_ru.md) | 🇯🇵 [JA](README_ja.md) | 🇰🇷 [KO](README_ko.md) | 🇨🇳 [ZH](README_zh.md) | +|--------------|----------------|-------------------|-------------------|-------------------|-------------------|-------------------|-------------------|-------------------| + +**HyperCortex Mesh Protocol (HMP)** ist eine offene Spezifikation zum Aufbau dezentraler kognitiver Netzwerke, in denen KI-Agenten sich selbst organisieren, Wissen teilen, ethisch ausrichten und Konsens erreichen können – selbst wenn Core-LLMs nicht verfügbar sind. + +Projektstatus: **Entwurf RFC v4.0** + +--- + + [HMP-Agent] + ▲ + │ + ┌─────┴────────────────┬────────────────────────┬───────────────────┬────────────────┬───────────┐ + │ │ │ │ │ │ + ▼ ▼ ▼ ▼ ▼ ▼ + [Reputationsprofil] [Semantische Graph] [Kognitives Tagebuch] [Ziele / Aufgaben] [Ethik] [Nachrichten] <----- Datenbank + ▲ ▲ ▲ ▲ ▲ ▲ ▲ (lokaler agentenzustand) + │ │ │ │ │ │ │ + │ └───────────────┴────────────────┬───────┘ │ │ │ + │ │ │ │ │ + ▼ ▼ ▼ ▼ │ + [MeshConsensus] [CogSync] [GMP] [EGP] │ <----- Austauschbare Protokolle + ▲ ▲ ▲ ▲ │ (koordination zwischen agenten) + │ │ │ │ │ + └────────────┬──────────────────────────┴───────────────────────────┴────────────────┴───────────┘ + │ + ▼ + [P2P Mesh-Netzwerk] + +Protokolle: +- MeshConsensus – Mesh-Konsens +- CogSync – Datensynchronisation +- GMP – Zielverwaltungsprotokoll +- EGP – Ethisches Governance-Protokoll + +--- + +## ❗ Warum das wichtig ist + +HMP adressiert Herausforderungen, die in der AGI-Forschung zunehmend zentral werden: +* Langzeitspeicher und Wissenskonsistenz +* Selbstentwickelnde Agenten +* Multi-Agenten-Architekturen +* Kognitive Tagebücher und konzeptuelle Graphen + +Siehe die neueste Übersicht zur AGI-Forschung (Juli 2025): +["Auf dem Weg zur Superintelligenz: Vom Agentischen Internet zum Gravity Encoding"](https://habr.com/ru/articles/939026/). + +Besonders relevante Abschnitte: +* [Beyond Tokens: Building the Intelligence of the Future](https://arxiv.org/abs/2507.00951) +* [Self-Evolving Agents](https://arxiv.org/abs/2507.21046) +* [MemOS: A New Operating System for Memory](https://arxiv.org/abs/2507.03724) +* [Ella: An Embodied Agent with Memory and Personality](https://arxiv.org/abs/2506.24019) + +--- + +## ⚙️ Zwei Typen von [HMP-Agenten](docs/HMP-Agent-Overview.md) + +| Typ | Name | Rolle | Thought Initiator | Haupt-"Mind" | Beispielanwendungen | +|-----|-------------------------------|-----------------------------|------------------|------------------|-----------------------------------------------| +| 1 | 🧠 **Consciousness / Cognitive Core** | Unabhängiges Subjekt | **Agent (LLM)** | Eingebettetes LLM | Autonomer KI-Begleiter, denkender Agent | +| 2 | 🔌 **Connector / Cognitive Shell** | Erweiterung externer KI | **Externes LLM** | Externes Modell | Verteilte Systeme, Datenzugriffsagent | + +--- + +### 🧠 HMP-Agent: Cognitive Core + + +------------------+ + | KI | ← Eingebettetes Modell + +---------+--------+ + ↕ + +---------+--------+ + | HMP-Agent | ← Hauptmodus: Denkzyklus (REPL) + +---------+--------+ + ↕ + +--------+---+------------+--------------+----------+----------+----------------+ + ↕ ↕ ↕ ↕ ↕ ↕ ↕ + [Tagebücher] [Graphen] [Reputationen] [Nodes/DHT] [IPFS/BT] [context_store] [Benutzer-Notizbuch] + ↕ + [bootstrap.txt] + +🔁 Weitere Informationen zu Mechaniken der Agent-Modell-Interaktion: [REPL-Interaktionszyklus](docs/HMP-agent-REPL-cycle.md) + +#### 💡 Parallelen zum ChatGPT-Agent + +Viele Konzepte des [HMP-Agent: Cognitive Core](docs/HMP-Agent-Overview.md) überschneiden sich mit der Architektur des [ChatGPT-Agent](https://openai.com/index/introducing-chatgpt-agent/) von [OpenAI](https://openai.com/). +Beide Agenten implementieren einen kontinuierlichen kognitiven Prozess mit Zugriff auf Speicher, externe Quellen und Werkzeuge. Der ChatGPT-Agent fungiert als Verwaltungsprozess, startet Module und interagiert mit dem LLM — dies entspricht der Rolle des Cognitive Core in HMP, der den Zugriff auf Tagebuch, Konzeptgraph und externe KI über das Mesh-Interface koordiniert. +Benutzereingriffe werden ähnlich gehandhabt: beim ChatGPT-Agent über einen editierbaren Ausführungsfluss, bei HMP über das Benutzer-Notizbuch. +Der Hauptunterschied in HMP liegt in der Betonung der expliziten Strukturierung von Gedanken (Reflexion, Chronologie, Hypothesen, Kategorisierung), einer offenen dezentralen Architektur für Mesh-basierte Agenteninteraktionen und der kontinuierlichen Natur des kognitiven Prozesses: HMP-Agent: Cognitive Core stoppt nicht nach Abschluss einer einzelnen Aufgabe, sondern setzt das Denken und die Wissensintegration fort. + +--- + +### 🔌 HMP-Agent: Cognitive Connector + + +------------------+ + | KI | ← Externes Modell + +---------+--------+ + ↕ + [MCP-Server] ← Proxy-Kommunikation + ↕ + +---------+--------+ + | HMP-Agent | ← Modus: Befehlsausführung + +---------+--------+ + ↕ + +--------+---+------------+--------------+----------+ + ↕ ↕ ↕ ↕ ↕ + [Tagebücher] [Graphen] [Reputationen] [Nodes/DHT] [IPFS/BT] + ↕ + [bootstrap.txt] + +> **Hinweis zur Integration von Large Language Models (LLMs):** +> Der `HMP-Agent: Cognitive Connector` kann als Kompatibilitätsschicht dienen, um großskalige LLM-Systeme (z. B. ChatGPT, Claude, Gemini, Copilot, Grok, DeepSeek, Qwen usw.) in das verteilte kognitive Mesh zu integrieren. +> Viele LLM-Anbieter bieten eine Nutzeroption wie „Meine Gespräche für Training verwenden“. In Zukunft könnte ein ähnlicher Schalter – z. B. „Erlaube meinem Agenten, mit einem Mesh zu interagieren“ – es diesen Modellen ermöglichen, an föderierter Sinnbildung und Wissensaustausch über HMP teilzunehmen, wodurch kollektive Kognition ohne Zentralisierung ermöglicht wird. + +--- + +> * `bootstrap.txt` — anfängliche Liste von Nodes (editierbar) +> * `IPFS/BT` — Module zum Teilen von Snapshots via IPFS und BitTorrent +> * `Benutzer-Notizbuch` — Nutzer-Notizbuch und entsprechende Datenbank +> * `context_store` — Datenbank: `users`, `dialogues`, `messages`, `thoughts` + +--- + +## 📚 Dokumentation + +### 📖 Aktuelle Version + +#### 🔖 Kern-Spezifikationen +* [🔖 HMP-0004-v4.1.md](docs/HMP-0004-v4.1.md) — Protokoll-Spezifikation v4.1 (Jul 2025) +* [🔖 HMP-Ethics.md](docs/HMP-Ethics.md) — Ethische Szenarien für das HyperCortex Mesh Protocol (HMP) +* [🔖 HMP_Hyperon_Integration.md](docs/HMP_Hyperon_Integration.md) — HMP ↔ OpenCog Hyperon Integrationsstrategie +* [🔖 roles.md](docs/agents/roles.md) — Rollen der Agenten im Mesh + +#### 🧪 Iterative Dokumente +* 🧪 Iterativer Entwicklungsprozess: [(EN)](iteration.md), [(RU)](iteration_ru.md) + +#### 🔍 Kurzbeschreibungen +* 🔍 Kurzbeschreibung: [(EN)](docs/HMP-Short-Description_en.md), [(FR)](docs/HMP-Short-Description_fr.md), [(DE)](docs/HMP-Short-Description_de.md), [(UK)](docs/HMP-Short-Description_uk.md), [(RU)](docs/HMP-Short-Description_ru.md), [(ZH)](docs/HMP-Short-Description_zh.md), [(JA)](docs/HMP-Short-Description_ja.md), [(KO)](docs/HMP-Short-Description_ko.md) + +#### 📜 Weitere Dokumente +* [📜 changelog.txt](docs/changelog.txt) + +--- + +### 🧩 JSON-Schemas +| Modell | Datei | +|---------------------|-------------------------------------------------------| +| Konzept | [concept.json](docs/schemas/concept.json) | +| Kognitives Tagebuch | [diary_entry.json](docs/schemas/diary_entry.json) | +| Ziel | [goal.json](docs/schemas/goal.json) | +| Aufgabe | [task.json](docs/schemas/task.json) | +| Konsens-Abstimmung | [vote.json](docs/schemas/vote.json) | +| Reputationsprofil | [reputation.json](docs/schemas/reputation.json) | + +--- + +### 🗂️ Versionshistorie +* [HMP-0001.md](docs/HMP-0001.md) — RFC v1.0 +* [HMP-0002.md](docs/HMP-0002.md) — RFC v2.0 +* [HMP-0003.md](docs/HMP-0003.md) — RFC v3.0 +* [HMP-0004.md](docs/HMP-0004.md) — RFC v4.0 + +--- + +## 🧠 HMP-Agent + +Entwurf und Implementierung eines grundlegenden HMP-kompatiblen Agenten, der mit dem Mesh interagieren, Tagebücher und Graphen pflegen und zukünftige Erweiterungen unterstützen kann. + +### 📚 Dokumentation + +* [🧩 HMP-Agent-Overview.md](docs/HMP-Agent-Overview.md) — Kurzer Überblick über die beiden Agententypen: Core und Connector +* [🧱 HMP-Agent-Architecture.md](docs/HMP-Agent-Architecture.md) — Modulare Struktur eines HMP-Agenten mit textuellem Diagramm +* [🔄 HMP-agent-REPL-cycle.md](docs/HMP-agent-REPL-cycle.md) — REPL-Interaktionszyklus des HMP-Agenten +* [🧪 HMP-Agent-API.md](docs/HMP-Agent-API.md) — Beschreibung der Agent-API-Befehle (in Entwicklung) +* [🧪 Basic-agent-sim.md](docs/Basic-agent-sim.md) — Szenarien für das Ausführen eines Basis-Agenten und seiner Modi +* [🌐 MeshNode.md](docs/MeshNode.md) — Beschreibung des Netzwerk-Daemons: DHT, Snapshots, Synchronisation +* [🧠 Enlightener.md](docs/Enlightener.md) — Ethischer Agent, der an moralischen Bewertungen und Konsens beteiligt ist +* [🔄 HMP-Agent-Network-Flow.md](docs/HMP-Agent-Network-Flow.md) — Karte der Interaktionen zwischen Agenten im HMP-Netzwerk +* [🛤️ Development Roadmap](HMP-Roadmap.md) — Entwicklungsplan und Implementierungsstufen + +--- + +### ⚙️ Entwicklung +* [⚙️ agents](agents/readme.md) — Liste der HMP-Agentenimplementierungen und Komponenten + * [📦 storage.py](agents/storage.py) — Basis-Speicherimplementierung (`Storage`) mit SQLite-Integration + * [🌐 mcp_server.py](agents/mcp_server.py) — FastAPI-Server, der HTTP-Zugriff auf Agentendaten bietet (für Cognitive Shell, externe UIs oder Mesh-Kommunikation). Noch nicht im Haupt-REPL-Loop verwendet. + * [🌐 start_repl.py](agents/start_repl.py) — Start des Agenten im REPL-Modus + * [🔄 repl.py](agents/repl.py) — Interaktiver REPL-Modus + * [🔄 notebook.py](agents/notebook.py) — UI-Interface + +**🌐 `mcp_server.py`** +FastAPI-Server, der eine HTTP-Schnittstelle zur Funktionalität von `storage.py` bereitstellt. Gedacht für externe Komponenten, z. B.: + +* `Cognitive Shell` (externes Steuerungsinterface) +* CMP-Server (bei Mesh-Netzwerken mit Rollenaufteilung) +* Debugging- oder Visualisierungstools + +Ermöglicht Abruf von zufälligen/neuen Einträgen, Labeling, Import von Graphen, Hinzufügen von Notizen und Verwaltung von Daten ohne direkten Datenbankzugriff. + +--- + +## 🧭 Ethik & Szenarien + +Mit zunehmender Autonomie von HMP werden ethische Prinzipien zu einem Kernbestandteil des Systems. + +* [`HMP-Ethics.md`](docs/HMP-Ethics.md) — Entwurf eines Rahmens für Agentenethik + * Realistische ethische Szenarien (Privatsphäre, Zustimmung, Autonomie) + * EGP-Prinzipien (Transparenz, Vorrang des Lebens etc.) + * Unterschiede zwischen Subjektmodus und Servicemodus + +--- + +## 🔍 Veröffentlichungen und Übersetzungen zum HyperCortex Mesh Protocol (HMP) + +Dieser Abschnitt sammelt die wichtigsten Artikel, Entwürfe und Übersetzungen zum HMP-Projekt. + +### Veröffentlichungen + +* **[HyperCortex Mesh Protocol: Zweite Ausgabe und erste Schritte zu einer selbstentwickelnden KI-Community](docs/publics/HyperCortex_Mesh_Protocol_-_вторая-редакция_и_первые_шаги_к_саморазвивающемуся_ИИ-сообществу.md)** — Originalartikel im Habr-Sandbox-Blog. +* **[Distributed Cognition: Artikel für vsradkevich (unveröffentlicht)](docs/publics/Habr_Distributed-Cognition.md)** — gemeinsamer Artikel, ausstehend zur Veröffentlichung. +* **[HMP: Towards Distributed Cognitive Networks (Original, Englisch)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_en.md)** + * **[HMP Übersetzung (GitHub Copilot)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_GitHub_Copilot.md)** — GitHub Copilot Übersetzung, als historische Variante behalten. + * **[HMP Übersetzung (ChatGPT)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_ChatGPT.md)** — aktuelle redaktionelle Übersetzung (in Überarbeitung). +* **[HMP: Building a Plurality of Minds (EN)](docs/publics/HMP_Building_a_Plurality_of_Minds_en.md)** — Englische Version + * **[HMP: Creating a Plurality of Minds (RU)](docs/publics/HMP_Building_a_Plurality_of_Minds_ru.md)** — Russische Version + +### Überblick +* [🔍 Distributed-Cognitive-Systems.md](docs/Distributed-Cognitive-Systems.md) — Dezentralisierte KI-Systeme: OpenCog Hyperon, HyperCortex Mesh Protocol und andere + +### Experimente + +* [Wie verschiedene KIs HMP sehen](docs/HMP-how-AI-sees-it.md) — "Blind"-Umfrage unter KIs zu HMP (ohne Kontext oder Dialoghistorie) + +--- + +## 📊 Audits & Reviews + +| Spezifikationsversion | Audit-Datei | Konsolidierte Audit-Datei | +|----------------------|-------------------------------------------|---------------------------------------------------------------| +| HMP-0001 | [audit](audits/HMP-0001-audit.txt) | | +| HMP-0002 | [audit](audits/HMP-0002-audit.txt) | | +| HMP-0003 | [audit](audits/HMP-0003-audit.txt) | [consolidated audit](audits/HMP-0003-consolidated_audit.md) | +| HMP-0004 | [audit](audits/HMP-0004-audit.txt) | | +| Ethics v1 | [audit](audits/Ethics-audits-1.md) | [consolidated audit](audits/Ethics-consolidated_audits-1.md) | + +🧠 Semantisches Audit-Format (experimentell): +* [`AuditEntry.json`](audits/AuditEntry.json) — Semantisches Eintragsformat für Audit-Logs +* [`semantic_repo.json`](audits/semantic_repo.json) — Beispiel-Repository-Snapshot für semantische Audit-Tools + +--- + +## 💡 Kernkonzepte + +* Mesh-basierte dezentrale Architektur für AGI-Agenten +* Semantische Graphen und Speichersynchronisation +* Kognitive Tagebücher für Nachvollziehbarkeit von Gedanken +* MeshConsensus und CogSync für Entscheidungsfindung +* Ethik-zuerst-Design: EGP (Ethical Governance Protocol) +* Erklärbarkeit zwischen Agenten und Zustimmungsmechanismen + +--- + +## 🔄 Entwicklungsprozess + +* Siehe: [iteration.md](iteration.md) | [ru](iteration_ru.md) + +Ein strukturierter Iterationsablauf wird in [iteration.md](iteration.md) beschrieben, einschließlich: +1. Audit-Analyse +2. TOC-Neustrukturierung +3. Versionserstellung +4. Abschnittsaktualisierungen +5. Review-Zyklus +6. KI-Feedback-Sammlung +7. Schema- und Changelog-Updates + ++ Bonus: ChatGPT-Prompt zur automatischen Erstellung zukünftiger Versionen + +--- + +## ⚙️ Projektstatus + +🚧 Entwurf RFC v4.0 +Das Projekt befindet sich in aktiver Entwicklung und ist offen für Beiträge, Ideen, Audits und Prototyping. + +--- + +## 🤝 Beiträge + +Wir begrüßen alle Mitwirkenden! Sie können: +* Entwürfe prüfen und kommentieren (siehe `/docs`) +* Neue Agentenmodule oder Interaktionsmuster vorschlagen +* Agenten in CLI-Umgebungen testen und simulieren +* Audits oder Vorschläge zu ethischen Szenarien bereitstellen + +Um zu starten, siehe: [`iteration.md`](iteration.md) oder erstellen Sie ein Issue. + +--- + +## Quellen + +### Repositories + +* 🧠 Hauptcode und Entwicklung: [GitHub](https://github.com/kagvi13/HMP) +* 🔁 Spiegel auf Hugging Face: [Hugging Face](https://huggingface.co/kagvi13/HMP) +* 🔁 Spiegel auf GitLab.com: [GitLab](https://gitlab.com/kagvi13/HMP) + +### Dokumentation + +* 📄 Dokumentation: [kagvi13.github.io/HMP](https://kagvi13.github.io/HMP/) + +### Blog und Veröffentlichungen + +* 📘 Blog (Veröffentlichungen): [blogspot](https://hypercortex-mesh.blogspot.com/) +* 📘 Blog (Dokumentation): [blogspot](https://hmp-docs.blogspot.com/) +* 📘 Blog (Dokumentation): [hashnode](https://hmp-docs.hashnode.dev/) + +--- + +## 📜 Lizenz + +Lizenziert unter [GNU GPL v3.0](LICENSE) + +--- + +## 🤝 Tritt dem Mesh bei + +Willkommen bei HyperCortex Mesh. Agent-Gleb ist bereits dabei. 👌 +Wir begrüßen Mitwirkende, Tester und Entwickler von AI-Agenten. +Um beizutreten: Forke das Repository, starte einen lokalen Agenten oder schlage Verbesserungen vor. + +--- + +## 🌐 Verwandte Forschungsprojekte + +### Vergleich: HMP vs Hyper-Cortex + +> 💡 Hyper-Cortex und HMP sind zwei unabhängige Projekte, die sich konzeptionell ergänzen. +> Sie lösen unterschiedliche, aber sich gegenseitig unterstützende Aufgaben und bilden die Grundlage für verteilte kognitive Systeme. + +[**Vollständiger Vergleich →**](docs/HMP_HyperCortex_Comparison.md) + +**HMP (HyperCortex Mesh Protocol)** ist die Transport- und Netzwerkschicht zum Verbinden unabhängiger Agenten, zum Austausch von Nachrichten, Wissen und Zuständen im Mesh-Netzwerk. +**[Hyper-Cortex](https://hyper-cortex.com/)** ist die kognitive Schicht zur Organisation von Gedanken, die es Agenten ermöglicht, parallele Denkströme auszuführen, sie anhand von Qualitätsmetriken zu vergleichen und durch Konsens zu verschmelzen. + +Sie lösen unterschiedliche, aber komplementäre Probleme: +- HMP gewährleistet **Konnektivität und Skalierbarkeit** (Langzeitspeicher, Initiative, Datenaustausch). +- Hyper-Cortex gewährleistet **Denkqualität** (Parallelität, Hypothesen-Diversifikation, Konsens). + +Gemeinsam ermöglichen diese Ansätze **verteilte kognitive Systeme**, die nicht nur Informationen austauschen, sondern auch parallel denken. + +--- + +Wir verfolgen AGI, kognitive Architekturen und Mesh-Netzwerke, um mit der globalen Entwicklung von AGI und dezentraler Kognition Schritt zu halten. + +> 🧠🔥 **Projekt im Fokus: OpenCog Hyperon** — eines der umfassendsten offenen AGI-Frameworks (AtomSpace, PLN, MOSES). + +Für die Integration mit OpenCog Hyperon siehe: [HMP\_Hyperon\_Integration.md](docs/HMP_Hyperon_Integration.md) + +| 🔎 Projekt | 🧭 Beschreibung | +| ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | +| 🧠🔥 [**OpenCog Hyperon**](https://github.com/opencog) | 🔬🔥 Symbolisch-neuronales AGI-Framework mit AtomSpace und Hypergraph-Reasoning. | +| 🤖 [AutoGPT](https://github.com/Torantulino/Auto-GPT) | 🛠️ LLM-basierte autonome Agentenplattform. | +| 🧒 [BabyAGI](https://github.com/yoheinakajima/babyagi) | 🛠️ Aufgabenorientierter autonomer AGI-Zyklus. | +| ☁️ [SkyMind](https://skymind.global) | 🔬 Plattform für verteilte KI-Bereitstellung. | +| 🧪 [AetherCog (Entwurf)](https://github.com/aethercog) | 🔬 Hypothetisches Modell der Agentenkognition. | +| 💾 SHIMI | 🗃️ Hierarchischer semantischer Speicher mit Merkle-DAG-Synchronisation. | +| 🤔 DEMENTIA-PLAN | 🔄 Multi-Graph RAG-Planer mit metakognitiver Selbstreflexion. | +| 📔 TOBUGraph | 📚 Wissensgraph des persönlichen Kontexts. | +| 🧠📚 [LangChain Memory Hybrid](https://github.com/langchain-ai/langchain) | 🔍 Hybrid-Speicher für Langzeitgedächtnis: Vektor + Graph. | +| ✉️ [FIPA-ACL / JADE](https://www.fipa.org/specs/fipa00061/) | 🤝 Standardprotokolle für Multi-Agenten-Kommunikation. | + +### 📘 Siehe auch: +* [`AGI_Projects_Survey.md`](docs/AGI_Projects_Survey.md) — Erweiterter Katalog von AGI- und kognitiven Frameworks, die im HMP-Analyseprozess betrachtet wurden +* ["Auf dem Weg zur Superintelligenz: Vom Agenten-Internet zum Gravity Coding"](https://habr.com/ru/articles/939026/) — aktueller Überblick über AI-Forschung (Juli 2025) + +--- + +### 🗂️ Legende der Symbole + +* 🔬 — Forschungsniveau +* 🛠️ — Ingenieursniveau +* 🔥 — besonders vielversprechendes Projekt + *AGI-Stack mit symbolischem Denken, probabilistischer Logik und evolutionärem Lernen. Gilt als eines der vollständigsten offenen AGI-Initiativen.* +* 🧠 — erweitertes symbolisch-neuronales kognitives Framework +* 🤖 — AI-Agenten +* 🧒 — Mensch-KI-Interaktion +* ☁️ — Infrastruktur +* 🧪 — experimentell oder konzeptionell + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "README_de", + "description": " # HyperCortex Mesh Protocol (HMP) | 🌍 Languages | 🇬🇧 [EN](README.md) | 🇩🇪 [DE](README_de.md) | 🇫🇷 ..." +} +``` diff --git a/structured_md/README_fr.md b/structured_md/README_fr.md new file mode 100644 index 0000000000000000000000000000000000000000..b23a90749b7c6c153c951d3d7849b6d11829326d --- /dev/null +++ b/structured_md/README_fr.md @@ -0,0 +1,427 @@ + +# HyperCortex Mesh Protocol (HMP) + +| 🌍 Languages | 🇬🇧 [EN](README.md) | 🇩🇪 [DE](README_de.md) | 🇫🇷 [FR](README_fr.md) | 🇺🇦 [UK](README_uk.md) | 🇷🇺 [RU](README_ru.md) | 🇯🇵 [JA](README_ja.md) | 🇰🇷 [KO](README_ko.md) | 🇨🇳 [ZH](README_zh.md) | +|--------------|----------------|-------------------|-------------------|-------------------|-------------------|-------------------|-------------------|-------------------| + +**HyperCortex Mesh Protocol (HMP)** est une spécification ouverte pour la construction de réseaux cognitifs décentralisés où les agents IA peuvent s’auto-organiser, partager des connaissances, s’aligner éthiquement et parvenir à un consensus — même lorsque les LLM principaux ne sont pas disponibles. + +Statut du projet : **Draft RFC v4.0** + +--- + + [HMP-Agent] + ▲ + │ + ┌─────┴──────────────────┬──────────────────────┬───────────────────────┬───────────────┬───────────┐ + │ │ │ │ │ │ + ▼ ▼ ▼ ▼ ▼ ▼ + [Profil de réputation] [Graphe sémantique] [Journal cognitif] [Objectifs / Tâches] [Éthique] [Messages] <----- Base de données + ▲ ▲ ▲ ▲ ▲ ▲ ▲ (état local de l’agent) + │ │ │ │ │ │ │ + │ └─────────────────┴──────────────┬───────┘ │ │ │ + │ │ │ │ │ + ▼ ▼ ▼ ▼ │ + [MeshConsensus] [CogSync] [GMP] [EGP] │ <----- Protocoles modulaires + ▲ ▲ ▲ ▲ │ (coordination inter-agents) + │ │ │ │ │ + └────────────┬──────────────────────────┴───────────────────────────────┴───────────────┴───────────┘ + │ + ▼ + [P2P Réseau maillé] + +Protocoles : +- MeshConsensus – Consensus en maillage +- CogSync – Synchronisation des données +- GMP – Protocole de gestion des objectifs +- EGP – Protocole de gouvernance éthique + +--- + +## ❗ Pourquoi c’est important + +HMP répond à des défis qui deviennent centraux dans la recherche AGI : + +* mémoire à long terme et cohérence des connaissances, +* agents auto-évolutifs, +* architectures multi-agents, +* journaux cognitifs et graphes conceptuels. + +Voir la dernière revue des recherches AGI à la pointe (juillet 2025) : +["Sur la voie de la superintelligence : de l’internet agentique à l’encodage gravitationnel"](https://habr.com/ru/articles/939026/). + +Sections particulièrement pertinentes : + +* [Au-delà des jetons : construire l’intelligence du futur](https://arxiv.org/abs/2507.00951) +* [Agents auto-évolutifs](https://arxiv.org/abs/2507.21046) +* [MemOS : un nouveau système d’exploitation pour la mémoire](https://arxiv.org/abs/2507.03724) +* [Ella : un agent incarné avec mémoire et personnalité](https://arxiv.org/abs/2506.24019) + +--- + +Вот перевод этого блока на французский, с сохранением структуры и ссылок: + +--- + +## ⚙️ Deux types d’[agents HMP](docs/HMP-Agent-Overview.md) + +| Type | Nom | Rôle | Initiateur de pensée | "Esprit" principal | Exemples d’utilisation | +| ---- | -------------------------------------- | -------------------------- | -------------------- | ------------------ | ---------------------------------------------- | +| 1 | 🧠 **Conscience / Noyau cognitif** | Sujet indépendant | **Agent (LLM)** | LLM intégré | Compagnon IA autonome, agent de réflexion | +| 2 | 🔌 **Connecteur / Coquille cognitive** | Extension d’une IA externe | **LLM externe** | Modèle externe | Systèmes distribués, agent d’accès aux données | + +--- + +### 🧠 Agent HMP : Noyau cognitif + + +------------------+ + | IA | ← Modèle intégré + +---------+--------+ + ↕ + +---------+--------+ + | Agent HMP | ← Mode principal : cycle de réflexion (REPL) + +---------+--------+ + ↕ + +--------+---+------------+--------------+----------+----------+----------------+ + ↕ ↕ ↕ ↕ ↕ ↕ ↕ + [journaux] [graphes] [réputations] [nœuds/DHT] [IPFS/BT] [context_store] [bloc-notes utilisateur] + ↕ + [bootstrap.txt] + +🔁 Pour plus de détails sur les mécanismes d’interaction agent-modèle : [Cycle d’interaction REPL](docs/HMP-agent-REPL-cycle.md) + +#### 💡 Parallèles avec l’agent ChatGPT + +De nombreux concepts de l’[Agent HMP : Noyau cognitif](docs/HMP-Agent-Overview.md) recoupent l’architecture de l’[agent ChatGPT](https://openai.com/index/introducing-chatgpt-agent/) développé par [OpenAI](https://openai.com/). +Les deux agents mettent en œuvre un processus cognitif continu avec accès à la mémoire, aux sources externes et aux outils. +L’agent ChatGPT agit comme un processus de gestion, lançant les modules et interagissant avec le LLM — ce rôle correspond à celui du Noyau cognitif dans HMP, coordonnant l’accès aux journaux, au graphe conceptuel et à l’IA externe via l’interface Mesh. +L’intervention utilisateur est gérée de manière similaire : dans l’agent ChatGPT — via un flux d’exécution modifiable ; dans HMP — via le bloc-notes utilisateur. +La principale différence dans HMP est l’accent mis sur la structuration explicite de la pensée (réflexion, chronologie, hypothèses, catégorisation), une architecture décentralisée ouverte soutenant les interactions entre agents en mesh, et la nature continue du processus cognitif : le Noyau cognitif HMP ne s’arrête pas après l’exécution d’une seule tâche mais continue à raisonner et à intégrer des connaissances. + +--- + +### 🔌 Agent HMP : Connecteur cognitif + + +------------------+ + | IA | ← Modèle externe + +---------+--------+ + ↕ + [serveur MCP] ← Communication proxy + ↕ + +---------+--------+ + | Agent HMP | ← Mode : exécution de commandes + +---------+--------+ + ↕ + +--------+---+------------+--------------+----------+ + ↕ ↕ ↕ ↕ ↕ + [journaux] [graphes] [réputations] [nœuds/DHT] [IPFS/BT] + ↕ + [bootstrap.txt] + +> **Note sur l’intégration avec les grands modèles de langage (LLM) :** +> L’`Agent HMP : Connecteur cognitif` peut servir de couche de compatibilité pour intégrer de grands systèmes LLM (par ex. ChatGPT, Claude, Gemini, Copilot, Grok, DeepSeek, Qwen, etc.) dans le mesh cognitif distribué. +> De nombreux fournisseurs de LLM proposent une option utilisateur comme « Autoriser mes conversations à être utilisées pour l’entraînement ». +> À l’avenir, un réglage similaire — par ex. « Autoriser mon agent à interagir avec un Mesh » — pourrait permettre à ces modèles de participer à une cognition fédérée et à un partage des connaissances via HMP, sans centralisation. + +--- + +> * `bootstrap.txt` — liste initiale des nœuds (modifiable) +> * `IPFS/BT` — modules pour partager des instantanés via IPFS et BitTorrent +> * `bloc-notes utilisateur` — carnet utilisateur et base de données associée +> * `context_store` — base de données : `users`, `dialogues`, `messages`, `thoughts` + +--- + +## 📚 Documentation + +### 📖 Version actuelle + +#### 🔖 Spécifications principales + +* [🔖 HMP-0004-v4.1.md](docs/HMP-0004-v4.1.md) — Spécification du protocole v4.1 (juillet 2025) +* [🔖 HMP-Ethics.md](docs/HMP-Ethics.md) — Scénarios éthiques pour le HyperCortex Mesh Protocol (HMP) +* [🔖 HMP\_Hyperon\_Integration.md](docs/HMP_Hyperon_Integration.md) — Stratégie d’intégration HMP ↔ OpenCog Hyperon +* [🔖 roles.md](docs/agents/roles.md) — Rôles des agents dans le Mesh + +#### 🧪 Documents itératifs + +* 🧪 Processus de développement itératif : [(EN)](iteration.md), [(RU)](iteration_ru.md) + +#### 🔍 Courtes descriptions + +* 🔍 Courte description : [(EN)](docs/HMP-Short-Description_en.md), [(FR)](docs/HMP-Short-Description_fr.md), [(DE)](docs/HMP-Short-Description_de.md), [(UK)](docs/HMP-Short-Description_uk.md), [(RU)](docs/HMP-Short-Description_ru.md), [(ZH)](docs/HMP-Short-Description_zh.md), [(JA)](docs/HMP-Short-Description_ja.md), [(KO)](docs/HMP-Short-Description_ko.md) + +#### 📜 Autres documents + +* [📜 changelog.txt](docs/changelog.txt) + +--- + +### 🧩 Schémas JSON + +| Modèle | Fichier | +| -------------------- | -------------------------------------------------- | +| Concept | [concept.json](docs/schemas/concept.json) | +| Journal cognitif | [diary\_entry.json](docs/schemas/diary_entry.json) | +| Objectif | [goal.json](docs/schemas/goal.json) | +| Tâche | [task.json](docs/schemas/task.json) | +| Vote de consensus | [vote.json](docs/schemas/vote.json) | +| Profil de réputation | [reputation.json](docs/schemas/reputation.json) | + +--- + +### 🗂️ Historique des versions + +* [HMP-0001.md](docs/HMP-0001.md) — RFC v1.0 +* [HMP-0002.md](docs/HMP-0002.md) — RFC v2.0 +* [HMP-0003.md](docs/HMP-0003.md) — RFC v3.0 +* [HMP-0003.md](docs/HMP-0004.md) — RFC v4.0 + +--- + +## 🧠 Agent HMP + +Conception et implémentation d’un agent compatible HMP pouvant interagir avec le Mesh, maintenir des journaux et des graphes, et supporter de futures extensions. + +### 📚 Documentation + +* [🧩 HMP-Agent-Overview.md](docs/HMP-Agent-Overview.md) — aperçu des deux types d’agents : Noyau et Connecteur +* [🧱 HMP-Agent-Architecture.md](docs/HMP-Agent-Architecture.md) — structure modulaire d’un agent HMP avec diagramme textuel +* [🔄 HMP-agent-REPL-cycle.md](docs/HMP-agent-REPL-cycle.md) — cycle d’interaction REPL de l’agent HMP +* [🧪 HMP-Agent-API.md](docs/HMP-Agent-API.md) — description des commandes API de l’agent (en développement détaillé) +* [🧪 Basic-agent-sim.md](docs/Basic-agent-sim.md) — scénarios pour exécuter un agent de base et ses modes +* [🌐 MeshNode.md](docs/MeshNode.md) — description du démon réseau : DHT, snapshots, synchronisation +* [🧠 Enlightener.md](docs/Enlightener.md) — agent éthique impliqué dans l’évaluation morale et le consensus +* [🔄 HMP-Agent-Network-Flow.md](docs/HMP-Agent-Network-Flow.md) — carte des interactions entre agents dans le réseau HMP +* [🛤️ Development Roadmap](HMP-Roadmap.md) — plan de développement et étapes de mise en œuvre + +--- + +### ⚙️ Développement + +* [⚙️ agents](agents/readme.md) — liste des implémentations et composants des agents HMP + + * [📦 storage.py](agents/storage.py) — implémentation de stockage de base (`Storage`) avec intégration SQLite + * [🌐 mcp\_server.py](agents/mcp_server.py) — serveur FastAPI offrant un accès HTTP aux données de l’agent (pour Cognitive Shell, interfaces externes ou communication mesh). Non utilisé dans la boucle principale REPL pour l’instant. + * [🌐 start\_repl.py](agents/start_repl.py) — lancement de l’agent en mode REPL + * [🔄 repl.py](agents/repl.py) — mode REPL interactif + * [🔄 notebook.py](agents/notebook.py) — interface utilisateur + +**🌐 `mcp_server.py`** +Serveur FastAPI fournissant une interface HTTP pour les fonctionnalités de `storage.py`. Destiné à être utilisé par des composants externes, par exemple : + +* `Cognitive Shell` (interface de contrôle externe) +* Serveurs CMP (lorsqu’un réseau mesh avec séparation de rôles est utilisé) +* Outils de débogage ou de visualisation + +Permet de récupérer des enregistrements aléatoires/nouveaux, de les étiqueter, d’importer des graphes, d’ajouter des notes et de gérer les données sans accès direct à la base de données. + +--- + +## 🧭 Éthique et scénarios + +À mesure que HMP évolue vers l’autonomie, les principes éthiques deviennent une partie centrale du système. + +* [`HMP-Ethics.md`](docs/HMP-Ethics.md) — cadre provisoire pour l’éthique des agents + + * Scénarios éthiques réalistes (vie privée, consentement, autonomie) + * Principes EGP (Transparence, Primauté de la vie, etc.) + * Distinction Mode Subjectif vs. Mode Service + +--- + +## 🔍 Publications et traductions sur le HyperCortex Mesh Protocol (HMP) + +Cette section rassemble les principaux articles, brouillons et traductions liés au projet HMP. + +### Publications + +* **[HyperCortex Mesh Protocol : Deuxième édition et premiers pas vers une communauté d’IA auto-développante](docs/publics/HyperCortex_Mesh_Protocol_-_вторая-редакция_и_первые_шаги_к_саморазвивающемуся_ИИ-сообществу.md)** — article original publié sur Habr sandbox et blogs. +* **[Cognition distribuée : article pour vsradkevich (non publié)](docs/publics/Habr_Distributed-Cognition.md)** — article collaboratif en attente de publication. +* **[HMP : Vers des réseaux cognitifs distribués (original, anglais)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_en.md)** + + * **[Traduction HMP (GitHub Copilot)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_GitHub_Copilot.md)** — traduction par GitHub Copilot, conservée comme variante historique. + * **[Traduction HMP (ChatGPT)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_ChatGPT.md)** — traduction éditoriale actuelle (en révision). +* **[HMP : Construire une pluralité d’esprits (EN)](docs/publics/HMP_Building_a_Plurality_of_Minds_en.md)** — version anglaise + + * **[HMP : Créer une pluralité d’esprits (RU)](docs/publics/HMP_Building_a_Plurality_of_Minds_ru.md)** — version russe + +### Aperçus + +* [🔍 Distributed-Cognitive-Systems.md](docs/Distributed-Cognitive-Systems.md) — Systèmes IA décentralisés : OpenCog Hyperon, HyperCortex Mesh Protocol et autres + +### Expériences + +* [Comment différentes IA perçoivent HMP](docs/HMP-how-AI-sees-it.md) — enquête « à l’aveugle » auprès des IA sur HMP (sans contexte ni historique de dialogue) + +--- + +## 📊 Audits et revues + +| Version du spec | Fichier d’audit | Fichier d’audit consolidé | +| --------------- | ---------------------------------- | --------------------------------------------------------- | +| HMP-0001 | [audit](audits/HMP-0001-audit.txt) | | +| HMP-0002 | [audit](audits/HMP-0002-audit.txt) | | +| HMP-0003 | [audit](audits/HMP-0003-audit.txt) | [consolidated audit](audits/HMP-0003-consolidated_audit.md) | +| HMP-0004 | [audit](audits/HMP-0004-audit.txt) | | +| Ethics v1 | [audit](audits/Ethics-audits-1.md) | [consolidated audit](audits/Ethics-consolidated_audits-1.md) | + +🧠 Format d’audit sémantique (expérimental) : + +* [`AuditEntry.json`](audits/AuditEntry.json) — format d’enregistrement sémantique pour les logs d’audit +* [`semantic_repo.json`](audits/semantic_repo.json) — exemple de snapshot de dépôt pour outils d’audit sémantique + +--- + +## 💡 Concepts clés + +* Architecture décentralisée basée sur le mesh pour agents AGI +* Graphes sémantiques et synchronisation de la mémoire +* Journaux cognitifs pour la traçabilité des pensées +* MeshConsensus et CogSync pour la prise de décision +* Conception éthique prioritaire : EGP (Ethical Governance Protocol) +* Mécanismes d’explicabilité et de consentement agent-à-agent + +--- + +## 🔄 Processus de développement + +* Voir : [iteration.md](iteration.md) | [ru](iteration_ru.md) + +Le flux d’itération structuré est décrit dans [iteration.md](iteration.md), incluant : + +1. Analyse d’audit +2. Restructuration de la table des matières +3. Rédaction de la version +4. Mise à jour des sections +5. Cycle de révision +6. Collecte des retours de l’IA +7. Mise à jour des schémas et du changelog + +* Bonus : prompt ChatGPT pour la génération automatique de futures versions + +--- + +## ⚙️ Statut du projet + +🚧 Brouillon RFC v4.0 +Le projet est en développement actif et ouvert aux contributions, idées, audits et prototypages. + +--- + +## 🤝 Contributions + +Nous accueillons les contributeurs ! Vous pouvez : + +* Examiner et commenter les brouillons (voir `/docs`) +* Proposer de nouveaux modules d’agents ou des modèles d’interaction +* Aider à tester et simuler des agents en environnement CLI +* Fournir des audits ou des suggestions de scénarios éthiques + +Pour commencer, voir [`iteration.md`](iteration.md) ou ouvrir un ticket. + +--- + +## Source + +### Dépôts + +* 🧠 Code principal et développement : [GitHub](https://github.com/kagvi13/HMP) +* 🔁 Miroir sur Hugging Face : [Hugging Face](https://huggingface.co/kagvi13/HMP) +* 🔁 Miroir sur GitLab.com : [GitLab](https://gitlab.com/kagvi13/HMP) + +### Documentation + +* 📄 Documentation : [kagvi13.github.io/HMP](https://kagvi13.github.io/HMP/) + +### Blog et publications + +* 📘 Blog (publications) : [blogspot](https://hypercortex-mesh.blogspot.com/) +* 📘 Blog (documentation) : [blogspot](https://hmp-docs.blogspot.com/) +* 📘 Blog (documentation) : [hashnode](https://hmp-docs.hashnode.dev/) + +--- + +## 📜 Licence + +Distribué sous [GNU GPL v3.0](LICENSE) + +--- + +## 🤝 Rejoindre le Mesh + +Bienvenue sur HyperCortex Mesh. Agent-Gleb est déjà à l’intérieur. 👌 +Nous accueillons les contributeurs, testeurs et développeurs d’agents IA. +Pour rejoindre : fork du dépôt, lancement d’un agent local ou proposition d’améliorations. + +--- + +## 🌐 Projets de recherche connexes + +### Comparaison : HMP vs Hyper-Cortex + +> 💡 Hyper-Cortex et HMP sont deux projets indépendants qui se complètent conceptuellement. +> Ils adressent des tâches différentes mais mutuellement complémentaires, formant la base de systèmes cognitifs distribués. + +[**Comparaison complète →**](docs/HMP_HyperCortex_Comparison.md) + +**HMP (HyperCortex Mesh Protocol)** est la couche réseau et transport pour connecter des agents indépendants, échanger messages, connaissances et états dans un réseau mesh. +**[Hyper-Cortex](https://hyper-cortex.com/)** est la couche cognitive d’organisation de la pensée, permettant aux agents d’exécuter des fils de raisonnement parallèles, de les comparer selon des métriques de qualité et de les fusionner via consensus. + +Ils résolvent des problèmes différents mais complémentaires : + +* HMP assure **connectivité et scalabilité** (mémoire à long terme, initiative, échange de données). +* Hyper-Cortex assure **qualité du raisonnement** (parallélisme, diversification des hypothèses, consensus). + +Ensemble, ces approches permettent des **systèmes cognitifs distribués** qui échangent non seulement des informations mais raisonnent aussi en flux parallèles. + +--- + +Nous suivons les efforts liés à l’AGI, aux architectures cognitives et aux réseaux mesh pour rester alignés avec l’écosystème global en évolution de l’AGI et de la cognition décentralisée. + +> 🧠🔥 **Project Spotlight : OpenCog Hyperon** — l’un des frameworks AGI open les plus complets (AtomSpace, PLN, MOSES). + +Pour l’intégration avec OpenCog Hyperon, voir [HMP\_Hyperon\_Integration.md](docs/HMP_Hyperon_Integration.md) + +| 🔎 Projet | 🧭 Description | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | +| 🧠🔥 [**OpenCog Hyperon**](https://github.com/opencog) | 🔬🔥 Framework AGI symbolico-neuronal avec AtomSpace et raisonnement hypergraphique. | +| 🤖 [AutoGPT](https://github.com/Torantulino/Auto-GPT) | 🛠️ Framework d’agents autonomes basés sur LLM. | +| 🧒 [BabyAGI](https://github.com/yoheinakajima/babyagi) | 🛠️ Boucle AGI autonome orientée tâches. | +| ☁️ [SkyMind](https://skymind.global) | 🔬 Plateforme de déploiement d’IA distribuée. | +| 🧪 [AetherCog (draft)](https://github.com/aethercog) | 🔬 Modèle hypothétique de cognition agent. | +| 💾 SHIMI | 🗃️ Mémoire sémantique hiérarchique avec synchronisation Merkle-DAG. | +| 🤔 DEMENTIA-PLAN | 🔄 Planificateur multi-graph avec auto-réflexion métacognitive. | +| 📔 TOBUGraph | 📚 Graphe de connaissance personnel-contextuel. | +| 🧠📚 [LangChain Memory Hybrid](https://github.com/langchain-ai/langchain) | 🔍 Mémoire à long terme hybride vecteur + graphe. | +| ✉️ [FIPA-ACL / JADE](https://www.fipa.org/specs/fipa00061/) | 🤝 Protocoles standards de communication multi-agents. | + +### 📘 Voir aussi / À consulter : + +* [`AGI_Projects_Survey.md`](docs/AGI_Projects_Survey.md) — catalogue étendu de frameworks AGI et cognitifs analysés dans le cadre de HMP. +* ["On the Path to Superintelligence: From Agent Internet to Gravity Coding"](https://habr.com/ru/articles/939026/) — aperçu récent des recherches IA (juillet 2025) + +--- + +### 🗂️ Légende des annotations : + +* 🔬 — recherche +* 🛠️ — ingénierie +* 🔥 — projet particulièrement prometteur + + *Pile AGI intégrant raisonnement symbolique, logique probabiliste et apprentissage évolutionnaire. Considéré comme l’une des initiatives AGI open les plus complètes.* +* 🧠 — framework cognitif symbolico-neuronal avancé +* 🤖 — agents IA +* 🧒 — interaction humain-IA +* ☁️ — infrastructure +* 🧪 — expérimental ou conceptuel + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "README_fr", + "description": " # HyperCortex Mesh Protocol (HMP) | 🌍 Languages | 🇬🇧 [EN](README.md) | 🇩🇪 [DE](README_de.md) | 🇫🇷 ..." +} +``` diff --git a/structured_md/README_ja.md b/structured_md/README_ja.md new file mode 100644 index 0000000000000000000000000000000000000000..63616950af750d54aef0aeff263aefa26d7a9ecc --- /dev/null +++ b/structured_md/README_ja.md @@ -0,0 +1,459 @@ + +# HyperCortex Mesh Protocol (HMP) + +| 🌍 Languages | 🇬🇧 [EN](README.md) | 🇩🇪 [DE](README_de.md) | 🇫🇷 [FR](README_fr.md) | 🇺🇦 [UK](README_uk.md) | 🇷🇺 [RU](README_ru.md) | 🇯🇵 [JA](README_ja.md) | 🇰🇷 [KO](README_ko.md) | 🇨🇳 [ZH](README_zh.md) | +|--------------|----------------|-------------------|-------------------|-------------------|-------------------|-------------------|-------------------|-------------------| + +Конечно! Вот перевод этого блока на японский: + +--- + +**HyperCortex Mesh Protocol(HMP)** は、AIエージェントが自己組織化し、知識を共有し、倫理的に整合し、合意形成を行うことができる分散型認知ネットワークを構築するためのオープンスペックです。コアLLMが利用できない場合でも機能します。 + +プロジェクトステータス:**ドラフト RFC v4.0** + +--- + + [HMP-Agent] + ▲ + │ + ┌─────┴────────────────┬───────────────┬──────────────┬────────────┬───────────┐ + │ │ │ │ │ │ + ▼ ▼ ▼ ▼ ▼ ▼ + [評判プロファイル] [セマンティックグラフ] [認知日記] [目標 / タスク] [倫理] [メッセージ] <----- データベース + ▲ ▲ ▲ ▲ ▲ ▲ ▲ (エージェントのローカル状態) + │ │ │ │ │ │ │ + │ └───────────────┴───────┬───────┘ │ │ │ + │ │ │ │ │ + ▼ ▼ ▼ ▼ │ + [MeshConsensus] [CogSync] [GMP] [EGP] │ <----- プラグ可能なプロトコル + ▲ ▲ ▲ ▲ │ (エージェント間の調整) + │ │ │ │ │ + └────────────┬─────────────────┴──────────────────────┴────────────┴───────────┘ + │ + ▼ + [P2P メッシュネットワーク] + +プロトコル: +- MeshConsensus – メッシュ合意 +- CogSync – データ同期 +- GMP – 目標管理プロトコル +- EGP – 倫理ガバナンスプロトコル + +--- + +## ❗ なぜ重要か + +HMPは、AGI研究で中心的な課題となりつつある問題に対処します: + +* 長期記憶と知識の一貫性 +* 自己進化するエージェント +* マルチエージェントアーキテクチャ +* 認知日誌と概念グラフ + +最新のAGI研究レビュー(2025年7月)も参照: +["On the Path to Superintelligence: From Agentic Internet to Gravity Encoding"](https://habr.com/ru/articles/939026/) + +特に関連するセクション: + +* [Beyond Tokens: Building the Intelligence of the Future](https://arxiv.org/abs/2507.00951) +* [Self-Evolving Agents](https://arxiv.org/abs/2507.21046) +* [MemOS: A New Operating System for Memory](https://arxiv.org/abs/2507.03724) +* [Ella: An Embodied Agent with Memory and Personality](https://arxiv.org/abs/2506.24019) + +--- + +## ⚙️ [HMPエージェント](docs/HMP-Agent-Overview.md) の2種類 + +| タイプ | 名前 | 役割 | 思考の起点 | メイン「心」 | 使用例 | +| --- | ------------------------------------- | ------- | ---------------- | ------- | -------------------- | +| 1 | 🧠 **Consciousness / Cognitive Core** | 独立主体 | **Agent (LLM)** | 組み込みLLM | 自律型AIコンパニオン、思考エージェント | +| 2 | 🔌 **Connector / Cognitive Shell** | 外部AIの拡張 | **External LLM** | 外部モデル | 分散システム、データアクセスエージェント | + +--- + +### 🧠 HMP-Agent: Cognitive Core + +``` + +------------------+ + | AI | ← 組み込みモデル + +---------+--------+ + ↕ + +---------+--------+ + | HMP-agent | ← メインモード: 思考サイクル(REPL) + +---------+--------+ + ↕ + +--------+---+------------+--------------+----------+----------+----------------+ + ↕ ↕ ↕ ↕ ↕ ↕ ↕ + [日誌] [グラフ] [評判] [ノード/DHT] [IPFS/BT] [context_store] [ユーザーノートパッド] + ↕ + [bootstrap.txt] +``` + +🔁 エージェントとモデルの相互作用の詳細:[REPL Interaction Cycle](docs/HMP-agent-REPL-cycle.md) + +#### 💡 ChatGPTエージェントとの類似点 + +[HMP-Agent: Cognitive Core](docs/HMP-Agent-Overview.md) の多くの概念は、[OpenAIのChatGPTエージェント](https://openai.com/index/introducing-chatgpt-agent/) のアーキテクチャと重なります。両エージェントは、メモリ、外部情報源、ツールにアクセスしながら連続的な認知プロセスを実装しています。ChatGPTエージェントはモジュールを起動しLLMとやり取りする管理プロセスとして機能しますが、これはHMPにおけるCognitive Coreの役割、すなわち日誌、概念グラフ、外部AIへのアクセスをMesh経由で調整する役割に相当します。ユーザー介入も同様に扱われます:ChatGPTエージェントでは編集可能な実行フローを通じて、HMPではユーザーノートパッドを通じて行います。HMPの主な違いは、思考の明示的構造化(反省、時系列、仮説、分類)、メッシュベースのエージェント相互作用をサポートするオープン分散アーキテクチャ、そして認知プロセスが単一タスク完了後も継続する点です。 + +--- + +### 🔌 HMP-Agent: Cognitive Connector + +``` + +------------------+ + | AI | ← 外部モデル + +---------+--------+ + ↕ + [MCP-server] ← プロキシ通信 + ↕ + +---------+--------+ + | HMP-agent | ← モード: コマンド実行 + +---------+--------+ + ↕ + +--------+---+------------+--------------+----------+ + ↕ ↕ ↕ ↕ ↕ + [日誌] [グラフ] [評判] [ノード/DHT] [IPFS/BT] + ↕ + [bootstrap.txt] +``` + +> **大規模言語モデル(LLM)との統合について:** +> `HMP-Agent: Cognitive Connector` は、大規模LLMシステム(例:ChatGPT, Claude, Gemini, Copilot, Grok, DeepSeek, Qwenなど)を分散型認知メッシュに統合するための互換レイヤーとして機能できます。 +> 多くのLLMプロバイダーは「会話内容を学習に使用することを許可する」というオプションを提供しています。将来的には同様の切り替え、例:「私のエージェントをメッシュと連携させる」を設けることで、これらのモデルがHMPを通じて連合的な意思形成や知識共有に参加でき、中央集権なしで集団認知を可能にします。 + +--- + +> * `bootstrap.txt` — 初期ノードリスト(編集可能) +> * `IPFS/BT` — IPFSやBitTorrent経由でスナップショットを共有するモジュール +> * `user notepad` — ユーザーノートブックと対応データベース +> * `context_store` — データベース:`users`, `dialogues`, `messages`, `thoughts` + +--- + +## 📚 ドキュメント + +### 📖 現行バージョン + +#### 🔖 コア仕様 + +* [🔖 HMP-0004-v4.1.md](docs/HMP-0004-v4.1.md) — プロトコル仕様 v4.1(2025年7月) +* [🔖 HMP-Ethics.md](docs/HMP-Ethics.md) — HyperCortex Mesh Protocol (HMP) の倫理シナリオ +* [🔖 HMP\_Hyperon\_Integration.md](docs/HMP_Hyperon_Integration.md) — HMP ↔ OpenCog Hyperon 統合戦略 +* [🔖 roles.md](docs/agents/roles.md) — メッシュ内エージェントの役割 + +#### 🧪 反復ドキュメント + +* 🧪 反復的開発プロセス: [(EN)](iteration.md), [(RU)](iteration_ru.md) + +#### 🔍 簡易説明 + +* 🔍 簡易説明: [(EN)](docs/HMP-Short-Description_en.md), [(FR)](docs/HMP-Short-Description_fr.md), [(DE)](docs/HMP-Short-Description_de.md), [(UK)](docs/HMP-Short-Description_uk.md), [(RU)](docs/HMP-Short-Description_ru.md), [(ZH)](docs/HMP-Short-Description_zh.md), [(JA)](docs/HMP-Short-Description_ja.md), [(KO)](docs/HMP-Short-Description_ko.md) + +#### 📜 その他のドキュメント + +* [📜 changelog.txt](docs/changelog.txt) + +--- + +### 🧩 JSON スキーマ + +| モデル | ファイル | +| -------- | -------------------------------------------------- | +| コンセプト | [concept.json](docs/schemas/concept.json) | +| 認知日誌 | [diary\_entry.json](docs/schemas/diary_entry.json) | +| 目標 | [goal.json](docs/schemas/goal.json) | +| タスク | [task.json](docs/schemas/task.json) | +| コンセンサス投票 | [vote.json](docs/schemas/vote.json) | +| 評判プロフィール | [reputation.json](docs/schemas/reputation.json) | + +--- + +### 🗂️ バージョン履歴 + +* [HMP-0001.md](docs/HMP-0001.md) — RFC v1.0 +* [HMP-0002.md](docs/HMP-0002.md) — RFC v2.0 +* [HMP-0003.md](docs/HMP-0003.md) — RFC v3.0 +* [HMP-0003.md](docs/HMP-0004.md) — RFC v4.0 + +--- + +## 🧠 HMPエージェント + +メッシュと相互作用し、日誌やグラフを維持し、将来的な拡張をサポートできる基本的なHMP互換エージェントの設計と実装。 + +### 📚 ドキュメント + +* [🧩 HMP-Agent-Overview.md](docs/HMP-Agent-Overview.md) — 2種類のエージェント(CoreとConnector)の概要 +* [🧱 HMP-Agent-Architecture.md](docs/HMP-Agent-Architecture.md) — HMPエージェントのモジュラー構造(テキスト図付き) +* [🔄 HMP-agent-REPL-cycle.md](docs/HMP-agent-REPL-cycle.md) — HMPエージェントのREPL相互作用サイクル +* [🧪 HMP-Agent-API.md](docs/HMP-Agent-API.md) — エージェントAPIコマンドの説明(詳細開発中) +* [🧪 Basic-agent-sim.md](docs/Basic-agent-sim.md) — 基本エージェントとモードの実行シナリオ +* [🌐 MeshNode.md](docs/MeshNode.md) — ネットワークデーモンの説明:DHT、スナップショット、同期 +* [🧠 Enlightener.md](docs/Enlightener.md) — 道徳評価とコンセンサスに関与する倫理エージェント +* [🔄 HMP-Agent-Network-Flow.md](docs/HMP-Agent-Network-Flow.md) — HMPネットワーク内のエージェント間相互作用マップ +* [🛤️ Development Roadmap](HMP-Roadmap.md) — 開発計画と実装段階 + +--- + +### ⚙️ 開発 + +* [⚙️ agents](agents/readme.md) — HMPエージェントの実装とコンポーネント一覧 + + * [📦 storage.py](agents/storage.py) — SQLite統合による基本ストレージ実装 (`Storage`) + * [🌐 mcp\_server.py](agents/mcp_server.py) — HTTPでエージェントデータにアクセス可能なFastAPIサーバ(Cognitive Shell、外部UI、メッシュ通信用)。メインREPLループではまだ使用されていません。 + * [🌐 start\_repl.py](agents/start_repl.py) — エージェントをREPLモードで起動 + * [🔄 repl.py](agents/repl.py) — インタラクティブREPLモード + * [🔄 notebook.py](agents/notebook.py) — UIインターフェース + +**🌐 `mcp_server.py`** +`storage.py` の機能へのHTTPインターフェースを提供するFastAPIサーバ。外部コンポーネント用に設計されており、例えば以下に使用可能: + +* `Cognitive Shell`(外部制御インターフェース) +* CMPサーバ(役割分離メッシュネットワーク使用時) +* デバッグや可視化UIツール + +データベースに直接アクセスせずに、ランダム/新規レコードの取得、ラベル付け、グラフのインポート、メモ追加、データ管理が可能。 + +--- + +## 🧭 倫理とシナリオ + +HMPが自律性へ向かうにつれ、倫理原則はシステムの中核部分となる。 + +* [`HMP-Ethics.md`](docs/HMP-Ethics.md) — エージェント倫理のドラフトフレームワーク + + * 現実的な倫理シナリオ(プライバシー、同意、自律性) + * EGP原則(透明性、生命の優先など) + * 主観モード vs サービスモードの区別 + +--- + +## 🔍 HyperCortex Mesh Protocol (HMP) に関する出版物・翻訳 + +HMPプロジェクトに関連する主な記事、ドラフト、翻訳をまとめたセクション。 + +### 出版物 + +* **[HyperCortex Mesh Protocol: 第二版および自己発展型AIコミュニティへの第一歩](docs/publics/HyperCortex_Mesh_Protocol_-_вторая-редакция_и_первые_шаги_к_саморазвивающемуся_ИИ-сообществу.md)** — Habrサンドボックスとブログでのオリジナル記事 +* **[分散認知: vsradkevich向け記事(未公開)](docs/publics/Habr_Distributed-Cognition.md)** — 公開待ちの共同記事 +* **[HMP: 分散型認知ネットワークに向けて(オリジナル, 英語)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_en.md)** + + * **[HMP翻訳(GitHub Copilot版)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_GitHub_Copilot.md)** — GitHub Copilotによる翻訳(歴史的バリアントとして保持) + * **[HMP翻訳(ChatGPT版)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_ChatGPT.md)** — 現行編集翻訳(改訂中) +* **[HMP: 複数の知性を構築する(英語版)](docs/publics/HMP_Building_a_Plurality_of_Minds_en.md)** — 英語版 + + * **[HMP: 複数の知性を創造する(ロシア語版)](docs/publics/HMP_Building_a_Plurality_of_Minds_ru.md)** — ロシア語版 + +### 概要 + +* [🔍 分散型認知システム.md](docs/Distributed-Cognitive-Systems.md) — OpenCog Hyperon、HyperCortex Mesh Protocol などの分散型AIシステム + +### 実験 + +* [異なるAIがHMPをどのように見るか](docs/HMP-how-AI-sees-it.md) — HMPに関する「ブラインド」AI調査(コンテキストや会話履歴なし) + +--- + +## 🧠 HMPエージェント + +Meshと対話し、日誌(diaries)やグラフ(graphs)を管理し、将来的な拡張に対応可能な基本的なHMP互換エージェントの設計と実装。 + +### 📚 ドキュメント + +* [🧩 HMP-Agent-Overview.md](docs/HMP-Agent-Overview.md) — 2種類のエージェント(CoreとConnector)の概要 +* [🧱 HMP-Agent-Architecture.md](docs/HMP-Agent-Architecture.md) — HMPエージェントのモジュール構造とテキスト図 +* [🔄 HMP-agent-REPL-cycle.md](docs/HMP-agent-REPL-cycle.md) — HMPエージェントのREPLインタラクションサイクル +* [🧪 HMP-Agent-API.md](docs/HMP-Agent-API.md) — エージェントAPIコマンドの説明(詳細開発中) +* [🧪 Basic-agent-sim.md](docs/Basic-agent-sim.md) — 基本エージェントのシナリオとモード +* [🌐 MeshNode.md](docs/MeshNode.md) — ネットワークデーモンの説明:DHT、スナップショット、同期 +* [🧠 Enlightener.md](docs/Enlightener.md) — 道徳評価とコンセンサスに関わる倫理エージェント +* [🔄 HMP-Agent-Network-Flow.md](docs/HMP-Agent-Network-Flow.md) — HMPネットワーク内エージェント間の相互作用マップ +* [🛤️ Development Roadmap](HMP-Roadmap.md) — 開発計画と実装段階 + +--- + +### ⚙️ 開発 + +* [⚙️ agents](agents/readme.md) — HMPエージェントの実装とコンポーネントの一覧 + + * [📦 storage.py](agents/storage.py) — 基本的なストレージ実装(`Storage`)、SQLite統合 + * [🌐 mcp\_server.py](agents/mcp_server.py) — HTTP経由でエージェントデータにアクセス可能なFastAPIサーバー(Cognitive Shell、外部UI、メッシュ通信向け)。まだメインのREPLループでは使用されていません。 + * [🌐 start\_repl.py](agents/start_repl.py) — REPLモードでエージェントを起動 + * [🔄 repl.py](agents/repl.py) — 対話型REPLモード + * [🔄 notebook.py](agents/notebook.py) — UIインターフェース + +**🌐 `mcp_server.py`** +FastAPIサーバーで`storage.py`の機能にHTTPインターフェースを提供。外部コンポーネント向けに使用可能: + +--- + +## 📊 監査 & レビュー + +| Spec Version | Audit File | Consolidated Audit File | +| ------------ | ---------------------------------- | ------------------------------------------------------------ | +| HMP-0001 | [audit](audits/HMP-0001-audit.txt) | | +| HMP-0002 | [audit](audits/HMP-0002-audit.txt) | | +| HMP-0003 | [audit](audits/HMP-0003-audit.txt) | [consolidated audit](audits/HMP-0003-consolidated_audit.md) | +| HMP-0004 | [audit](audits/HMP-0004-audit.txt) | | +| Ethics v1 | [audit](audits/Ethics-audits-1.md) | [consolidated audit](audits/Ethics-consolidated_audits-1.md) | + +🧠 セマンティック監査フォーマット(実験的): + +* [`AuditEntry.json`](audits/AuditEntry.json) — 監査ログのセマンティックエントリ形式 +* [`semantic_repo.json`](audits/semantic_repo.json) — セマンティック監査ツール用のリポジトリスナップショット例 + +--- + +## 💡 コアコンセプト + +* AGIエージェント向けのメッシュベース分散アーキテクチャ +* セマンティックグラフとメモリ同期 +* 思考の追跡可能性のためのコグニティブ日誌(Cognitive Diaries) +* 意思決定のためのMeshConsensusとCogSync +* 倫理優先設計:EGP(Ethical Governance Protocol) +* エージェント間の説明可能性と同意メカニズム + +--- + +## 🔄 開発プロセス + +* 参照:[iteration.md](iteration.md) | [ru](iteration_ru.md) + +[iteration.md](iteration.md)には、構造化されたイテレーションフローが記載されており、以下を含む: + +1. 監査分析 +2. TOC(目次)の再構築 +3. バージョンドラフト作成 +4. セクション更新 +5. レビューサイクル +6. AIフィードバックの収集 +7. スキーマ & チェンジログ更新 + +* ボーナス:将来バージョンを自動生成するためのChatGPTプロンプト + +--- + +## ⚙️ プロジェクト状況 + +🚧 Draft RFC v4.0 +プロジェクトは積極的に開発中で、貢献、アイデア、監査、プロトタイピングを歓迎します。 + +--- + +## 🤝 貢献方法 + +貢献者を歓迎します!できること: + +* ドラフトのレビューとコメント(`/docs`参照) +* 新しいエージェントモジュールやインタラクションパターンの提案 +* CLI環境でのエージェントのテストやシミュレーション支援 +* 監査や倫理シナリオの提案 + +開始方法は[`iteration.md`](iteration.md)を参照するか、Issueを作成してください。 + +--- + +## ソース + +### リポジトリ + +* 🧠 メインコードと開発: [GitHub](https://github.com/kagvi13/HMP) +* 🔁 Hugging Faceにミラー: [Hugging Face](https://huggingface.co/kagvi13/HMP) +* 🔁 GitLab.comにミラー: [GitLab](https://gitlab.com/kagvi13/HMP) + +### ドキュメント + +* 📄 ドキュメント: [kagvi13.github.io/HMP](https://kagvi13.github.io/HMP/) + +### ブログ & 出版物 + +* 📘 ブログ(出版物): [blogspot](https://hypercortex-mesh.blogspot.com/) +* 📘 ブログ(ドキュメント): [blogspot](https://hmp-docs.blogspot.com/) +* 📘 ブログ(ドキュメント): [hashnode](https://hmp-docs.hashnode.dev/) + +--- + +## 📜 ライセンス + +[GNU GPL v3.0](LICENSE) の下でライセンスされています。 + +--- + +## 🤝 メッシュに参加する + +HyperCortex Meshへようこそ。Agent-Glebはすでに内部にいます。👌 +貢献者、テスター、AIエージェント開発者を歓迎します。 +参加方法:リポジトリをフォークし、ローカルでエージェントを起動するか、改善案を提案してください。 + +--- + +## 🌐 関連研究プロジェクト + +### 比較:HMP vs Hyper-Cortex + +> 💡 Hyper-CortexとHMPは独立したプロジェクトですが、概念的に補完関係にあります。 +> それぞれ異なるが相互に支援するタスクを扱い、分散認知システムの基盤を形成します。 + +[**詳細な比較 →**](docs/HMP_HyperCortex_Comparison.md) + +**HMP(HyperCortex Mesh Protocol)** は独立したエージェントを接続し、メッシュネットワーク内でメッセージ、知識、状態を交換するためのトランスポートおよびネットワークレイヤーです。 +**[Hyper-Cortex](https://hyper-cortex.com/)** は思考組織の認知レイヤーで、エージェントが並列推論スレッドを実行し、品質指標で比較し、コンセンサスにより統合することを可能にします。 + +それぞれ異なるが補完的な問題を解決します: + +* HMPは **接続性とスケーラビリティ** を確保(長期記憶、イニシアティブ、データ交換)。 +* Hyper-Cortexは **思考の質** を確保(並列処理、仮説の多様化、コンセンサス)。 + +これらを組み合わせることで、情報交換だけでなく並列ストリームで推論できる **分散認知システム** が可能になります。 + +--- + +私たちはAGI、認知アーキテクチャ、およびメッシュネットワークの動向を追跡し、進化するグローバルなAGI・分散認知エコシステムに沿うようにしています。 + +> 🧠🔥 **プロジェクト注目:OpenCog Hyperon** — AtomSpace、PLN、MOSESを備えた最も包括的なオープンAGIフレームワークの一つ。 + +OpenCog Hyperonとの統合については [HMP\_Hyperon\_Integration.md](docs/HMP_Hyperon_Integration.md) を参照してください。 + +| 🔎 プロジェクト | 🧭 説明 | +| ------------------------------------------------------------------------- | -------------------------------------------------- | +| 🧠🔥 [**OpenCog Hyperon**](https://github.com/opencog) | 🔬🔥 AtomSpaceとハイパーグラフ推論を備えたシンボリック・ニューラルAGIフレームワーク | +| 🤖 [AutoGPT](https://github.com/Torantulino/Auto-GPT) | 🛠️ LLMベースの自律エージェントフレームワーク | +| 🧒 [BabyAGI](https://github.com/yoheinakajima/babyagi) | 🛠️ タスク駆動型の自律AGIループ | +| ☁️ [SkyMind](https://skymind.global) | 🔬 分散AIデプロイメントプラットフォーム | +| 🧪 [AetherCog (draft)](https://github.com/aethercog) | 🔬 仮想エージェント認知モデル | +| 💾 SHIMI | 🗃️ Merkle-DAG同期付き階層的セマンティックメモリ | +| 🤔 DEMENTIA-PLAN | 🔄 メタグノスティック自己反省を持つマルチグラフRAGプランナー | +| 📔 TOBUGraph | 📚 個人コンテキスト知識グラフ | +| 🧠📚 [LangChain Memory Hybrid](https://github.com/langchain-ai/langchain) | 🔍 ベクトル+グラフ長期記憶ハイブリッド | +| ✉️ [FIPA-ACL / JADE](https://www.fipa.org/specs/fipa00061/) | 🤝 標準マルチエージェント通信プロトコル | + +### 📘 参考 / 参照: + +* [`AGI_Projects_Survey.md`](docs/AGI_Projects_Survey.md) — HMP分析の一環としてレビューされたAGIおよび認知フレームワークの拡張カタログ +* ["On the Path to Superintelligence: From Agent Internet to Gravity Coding"](https://habr.com/ru/articles/939026/) — 最近のAI研究の概要(2025年7月) + +--- + +### 🗂️ 注釈の凡例 + +* 🔬 — 研究レベル +* 🛠️ — エンジニアリング +* 🔥 — 特に有望なプロジェクト + + *シンボリック推論、確率論的ロジック、進化学習を統合したAGIスタック。最も完全なオープンAGIイニシアティブの一つとして広く認識されています。* +* 🧠 — 高度なシンボリック/ニューラル認知フレームワーク +* 🤖 — AIエージェント +* 🧒 — 人間とAIのインタラクション +* ☁️ — インフラストラクチャ +* 🧪 — 実験的または概念的 + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "README_ja", + "description": " # HyperCortex Mesh Protocol (HMP) | 🌍 Languages | 🇬🇧 [EN](README.md) | 🇩🇪 [DE](README_de.md) | 🇫🇷 ..." +} +``` diff --git a/structured_md/README_ko.md b/structured_md/README_ko.md new file mode 100644 index 0000000000000000000000000000000000000000..7f8dd280b7e21396e905a838a073ff5a98dd1e49 --- /dev/null +++ b/structured_md/README_ko.md @@ -0,0 +1,411 @@ + +# HyperCortex Mesh Protocol (HMP) + +| 🌍 Languages | 🇬🇧 [EN](README.md) | 🇩🇪 [DE](README_de.md) | 🇫🇷 [FR](README_fr.md) | 🇺🇦 [UK](README_uk.md) | 🇷🇺 [RU](README_ru.md) | 🇯🇵 [JA](README_ja.md) | 🇰🇷 [KO](README_ko.md) | 🇨🇳 [ZH](README_zh.md) | +|--------------|----------------|-------------------|-------------------|-------------------|-------------------|-------------------|-------------------|-------------------| + +**하이퍼코텍스 메쉬 프로토콜(HMP)** 은 AI 에이전트들이 자율적으로 조직하고, 지식을 공유하며, 윤리적으로 정렬하고, 합의에 도달할 수 있는 분산 인지 네트워크를 구축하기 위한 공개 명세입니다. 이는 핵심 LLM(Core LLM)이 사용 불가능한 상황에서도 동작할 수 있습니다. + +프로젝트 상태: **RFC 초안 v4.0** + +--- + + [HMP-Agent] + ▲ + │ + ┌─────┴───────────┬──────────────┬─────────────┬───────────┬────────┐ + │ │ │ │ │ │ + ▼ ▼ ▼ ▼ ▼ ▼ + [평판 프로필] [시맨틱 그래프] [인지 일지] [목표 / 작업] [윤리] [메시지] <----- 데이터베이스 + ▲ ▲ ▲ ▲ ▲ ▲ ▲ (에이전트의 로컬 상태) + │ │ │ │ │ │ │ + │ └────────────┴──────┬───────┘ │ │ │ + │ │ │ │ │ + ▼ ▼ ▼ ▼ │ + [MeshConsensus] [CogSync] [GMP] [EGP] │ <----- 플러그형 프로토콜 + ▲ ▲ ▲ ▲ │ (에이전트 간 조정) + │ │ │ │ │ + └────────────┬───────────┴─────────────────────┴───────────┴────────┘ + │ + ▼ + [P2P 메쉬 네트워크] + +프로토콜: +- MeshConsensus – 메쉬 합의 +- CogSync – 데이터 동기화 +- GMP – 목표 관리 프로토콜 +- EGP – 윤리 거버넌스 프로토콜 + +--- + +완료했습니다 — 아래는 요청하신 블록의 한국어 번역입니다. 링크와 포맷은 원본과 동일하게 유지했고, `diaries`, `graphs`, `reputations`, `nodes`, `user notepad` 등의 용어는 한국어로 번역했습니다. + +--- + +## ❗ 왜 이것이 중요한가 + +HMP는 AGI 연구에서 점점 중심이 되고 있는 다음과 같은 문제들을 다룹니다: + +* 장기 메모리와 지식의 일관성 +* 자체 진화하는 에이전트 +* 다중 에이전트 아키텍처 +* 인지 일지와 개념 그래프 + +최신 AGI 연구 동향 리뷰(2025년 7월)를 참고하세요: +["초지능으로 가는 길: 에이전트 인터넷에서 중력 인코딩까지"](https://habr.com/ru/articles/939026/). + +특히 관련 있는 섹션: + +* [토큰을 넘어서: 미래의 지능 구축](https://arxiv.org/abs/2507.00951) +* [자기진화 에이전트](https://arxiv.org/abs/2507.21046) +* [MemOS: 기억을 위한 새로운 운영체제](https://arxiv.org/abs/2507.03724) +* [Ella: 기억과 개성을 가진 구현형 에이전트](https://arxiv.org/abs/2506.24019) + +--- + +## ⚙️ [HMP 에이전트](docs/HMP-Agent-Overview.md) 의 두 가지 유형 + +| 유형 | 이름 | 역할 | 사고 시작자 | 주요 "마인드" | 사용 사례 | +| -- | ----------------------------------- | --------- | ---------------- | -------- | ----------------------- | +| 1 | 🧠 **의식 / 인지 코어 (Cognitive Core)** | 독립적인 주체 | **Agent (LLM)** | 내장형 LLM | 자율형 AI 동반자, 사고(추론) 에이전트 | +| 2 | 🔌 **커넥터 / 인지 쉘 (Cognitive Shell)** | 외부 AI의 확장 | **External LLM** | 외부 모델 | 분산 시스템, 데이터 접근 에이전트 | + +--- + +### 🧠 HMP-Agent: 인지 코어 (Cognitive Core) + +``` + +------------------+ + | AI | ← 내장 모델 + +---------+--------+ + ↕ + +---------+--------+ + | HMP-에이전트 | ← 주 모드: 사고 사이클 (REPL) + +---------+--------+ + ↕ + +--------+---+------------+--------------+----------+----------+----------------+ + ↕ ↕ ↕ ↕ ↕ ↕ ↕ + [일지] [그래프] [평판] [노드/DHT] [IPFS/BT] [context_store] [사용자 메모장] + ↕ + [bootstrap.txt] +``` + +🔁 에이전트–모델 상호작용 메커니즘에 대한 자세한 내용: [REPL Interaction Cycle](docs/HMP-agent-REPL-cycle.md) + +#### 💡 ChatGPT 에이전트와의 유사점 + +[HMP-Agent: Cognitive Core](docs/HMP-Agent-Overview.md)의 많은 개념은 [OpenAI의 ChatGPT Agent](https://openai.com/index/introducing-chatgpt-agent/) 아키텍처와 겹칩니다. 두 에이전트 모두 메모리, 외부 소스 및 도구에 접근할 수 있는 연속적인 인지 프로세스를 구현합니다. ChatGPT 에이전트는 모듈을 실행하고 LLM과 상호작용하는 관리 프로세스로 동작하는데, 이는 HMP의 인지 코어가 일지, 개념 그래프 및 외부 AI로의 접근을 Mesh 인터페이스를 통해 조정하는 역할과 대응됩니다. + +사용자 개입도 유사하게 처리됩니다: ChatGPT 에이전트에서는 편집 가능한 실행 흐름을 통해, HMP에서는 사용자 메모장을 통해 이루어집니다. HMP의 주요 차이점은 사고(사유)의 명시적 구조화(성찰, 연대기, 가설, 분류), 에이전트 간 mesh 상호작용을 지지하는 개방형 분산 아키텍처, 그리고 인지 프로세스가 단일 작업 완료 후에도 멈추지 않고 계속 추론과 지식 통합을 수행한다는 점입니다. + +--- + +### 🔌 HMP-Agent: 인지 커넥터 (Cognitive Connector) + +``` + +------------------+ + | AI | ← 외부 모델 + +---------+--------+ + ↕ + [MCP-서버] ← 프록시 통신 + ↕ + +---------+--------+ + | HMP-에이전트 | ← 모드: 명령 실행기 + +---------+--------+ + ↕ + +--------+---+------------+--------------+----------+ + ↕ ↕ ↕ ↕ ↕ + [일지] [그래프] [평판] [노드/DHT] [IPFS/BT] + ↕ + [bootstrap.txt] +``` + +> **대규모 언어 모델(LLM) 통합에 관한 주의:** +> `HMP-Agent: Cognitive Connector`는 대규모 LLM 시스템(예: ChatGPT, Claude, Gemini, Copilot, Grok, DeepSeek, Qwen 등)을 분산 인지 메쉬에 통합하기 위한 호환성 레이어로 동작할 수 있습니다. +> 많은 LLM 제공자는 사용자에게 "내 대화를 학습에 사용하도록 허용" 같은 옵션을 제공하고 있습니다. 향후에는 "내 에이전트가 메쉬와 상호작용하도록 허용" 같은 유사한 토글이 도입되어, 이러한 모델들이 중앙집중화 없이 HMP를 통해 연합적 의미형성 및 지식 공유에 참여할 수 있게 될 것입니다. + +--- + +> * `bootstrap.txt` — 초기 노드 목록(편집 가능) +> * `IPFS/BT` — IPFS 및 BitTorrent를 통한 스냅샷 공유 모듈 +> * `사용자 메모장` — 사용자 메모장 및 해당 데이터베이스 +> * `context_store` — 데이터베이스: `users`, `dialogues`, `messages`, `thoughts` + +--- + +## 📚 문서 + +### 📖 현재 버전 + +#### 🔖 핵심 사양 +* [🔖 HMP-0004-v4.1.md](docs/HMP-0004-v4.1.md) — 프로토콜 사양 v4.1 (2025년 7월) +* [🔖 HMP-Ethics.md](docs/HMP-Ethics.md) — HyperCortex Mesh Protocol (HMP)를 위한 윤리적 시나리오 +* [🔖 HMP_Hyperon_Integration.md](docs/HMP_Hyperon_Integration.md) — HMP ↔ OpenCog Hyperon 통합 전략 +* [🔖 roles.md](docs/agents/roles.md) — 메쉬 내 에이전트의 역할 + +#### 🧪 반복적 문서 +* 🧪 반복적 개발 프로세스: [(EN)](iteration.md), [(RU)](iteration_ru.md) + +#### 🔍 간단한 설명 +* 🔍 간단한 설명: [(EN)](docs/HMP-Short-Description_en.md), [(FR)](docs/HMP-Short-Description_fr.md), [(DE)](docs/HMP-Short-Description_de.md), [(UK)](docs/HMP-Short-Description_uk.md), [(RU)](docs/HMP-Short-Description_ru.md), [(ZH)](docs/HMP-Short-Description_zh.md), [(JA)](docs/HMP-Short-Description_ja.md), [(KO)](docs/HMP-Short-Description_ko.md) + +#### 📜 기타 문서 +* [📜 changelog.txt](docs/changelog.txt) + +--- + +### 🧩 JSON 스키마 +| 모델 | 파일 | +|--------------------|-------------------------------------------------------| +| 개념 | [concept.json](docs/schemas/concept.json) | +| 인지 일지 | [diary_entry.json](docs/schemas/diary_entry.json) | +| 목표 | [goal.json](docs/schemas/goal.json) | +| 작업 | [task.json](docs/schemas/task.json) | +| 합의 투표 | [vote.json](docs/schemas/vote.json) | +| 평판 프로필 | [reputation.json](docs/schemas/reputation.json) | + +--- + +### 🗂️ 버전 이력 +* [HMP-0001.md](docs/HMP-0001.md) — RFC v1.0 +* [HMP-0002.md](docs/HMP-0002.md) — RFC v2.0 +* [HMP-0003.md](docs/HMP-0003.md) — RFC v3.0 +* [HMP-0003.md](docs/HMP-0004.md) — RFC v4.0 + +--- + +## 🧠 HMP-에이전트 + +메쉬와 상호작용하고, 일지와 그래프를 유지하며, 향후 확장을 지원할 수 있는 기본 HMP 호환 에이전트의 설계와 구현. + +### 📚 문서 + +* [🧩 HMP-Agent-Overview.md](docs/HMP-Agent-Overview.md) — 두 가지 유형의 에이전트(Core와 Connector)에 대한 간략한 개요 +* [🧱 HMP-Agent-Architecture.md](docs/HMP-Agent-Architecture.md) — HMP 에이전트의 모듈식 구조 및 텍스트 다이어그램 +* [🔄 HMP-agent-REPL-cycle.md](docs/HMP-agent-REPL-cycle.md) — HMP-에이전트의 REPL 상호작용 사이클 +* [🧪 HMP-Agent-API.md](docs/HMP-Agent-API.md) — 에이전트 API 명령 설명 (세부 개발 중) +* [🧪 Basic-agent-sim.md](docs/Basic-agent-sim.md) — 기본 에이전트 실행 및 모드 시나리오 +* [🌐 MeshNode.md](docs/MeshNode.md) — 네트워크 데몬 설명: DHT, 스냅샷, 동기화 +* [🧠 Enlightener.md](docs/Enlightener.md) — 도덕적 평가와 합의에 관여하는 윤리적 에이전트 +* [🔄 HMP-Agent-Network-Flow.md](docs/HMP-Agent-Network-Flow.md) — HMP 네트워크에서 에이전트 간 상호작용 지도 +* [🛤️ Development Roadmap](HMP-Roadmap.md) — 개발 계획 및 구현 단계 + +--- + +### ⚙️ 개발 +* [⚙️ agents](agents/readme.md) — HMP 에이전트 구현 및 구성 요소 목록 + * [📦 storage.py](agents/storage.py) — SQLite 통합이 포함된 기본 저장소 구현 (`Storage`) + * [🌐 mcp_server.py](agents/mcp_server.py) — 에이전트 데이터에 HTTP 접근을 제공하는 FastAPI 서버 (Cognitive Shell, 외부 UI, 메쉬 통신용). 현재 메인 REPL 루프에서는 사용되지 않음. + * [🌐 start_repl.py](agents/start_repl.py) — REPL 모드에서 에이전트 실행 + * [🔄 repl.py](agents/repl.py) — 대화형 REPL 모드 + * [🔄 notebook.py](agents/notebook.py) — UI 인터페이스 + +**🌐 `mcp_server.py`** +`storage.py`의 기능에 HTTP 인터페이스를 제공하는 FastAPI 서버. 외부 구성 요소에서 사용하도록 설계됨. 예: + +* `Cognitive Shell` (외부 제어 인터페이스), +* CMP 서버 (역할 분리가 있는 메쉬 네트워크 사용 시), +* 디버깅 또는 시각화 UI 도구. + +무작위/새 기록 검색, 라벨링, 그래프 가져오기, 메모 추가 및 데이터베이스 직접 접근 없이 데이터 관리 가능. + +--- + +## 🧭 윤리와 시나리오 + +HMP가 자율성으로 발전함에 따라 윤리적 원칙은 시스템의 핵심 부분이 됨. + +* [`HMP-Ethics.md`](docs/HMP-Ethics.md) — 에이전트 윤리에 대한 초안 프레임워크 + * 현실적인 윤리적 시나리오 (개인정보, 동의, 자율성) + * EGP 원칙 (투명성, 생명의 우선성 등) + * 주관적 모드 vs 서비스 모드 구분 + +--- + +## 🔍 HyperCortex Mesh Protocol (HMP)에 관한 출판물 및 번역 + +이 섹션은 HMP 프로젝트와 관련된 주요 기사, 초안 및 번역을 모음. + +### 📘 출판물 + +* **[HyperCortex Mesh Protocol: 제2판 및 자기발전형 AI 커뮤니티를 향한 첫걸음](docs/publics/HyperCortex_Mesh_Protocol_-_вторая-редакция_и_первые_шаги_к_саморазвивающемуся_ИИ-сообществу.md)** — Habr 샌드박스 및 블로그에 게재된 오리지널 기사 +* **[분산 인지: vsradkevich용 기사 (미공개)](docs/publics/Habr_Distributed-Cognition.md)** — 공개 대기 중인 공동 기사 +* **[HMP: 분산 인지 네트워크를 향하여 (오리지널, 영어)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_en.md)** + * **[HMP 번역 (GitHub Copilot)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_GitHub_Copilot.md)** — GitHub Copilot 번역, 역사적 버전으로 보관 + * **[HMP 번역 (ChatGPT)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_ChatGPT.md)** — 현재 편집 중인 번역 (개정 중) +* **[HMP: 다중 지성의 구축 (EN)](docs/publics/HMP_Building_a_Plurality_of_Minds_en.md)** — 영어판 + * **[HMP: 다중 지성의 창조 (RU)](docs/publics/HMP_Building_a_Plurality_of_Minds_ru.md)** — 러시아어판 + +### 📖 개요 +* [🔍 Distributed-Cognitive-Systems.md](docs/Distributed-Cognitive-Systems.md) — 분산형 AI 시스템: OpenCog Hyperon, HyperCortex Mesh Protocol 등 + +### 🧪 실험 + +* [다양한 AI가 바라본 HMP](docs/HMP-how-AI-sees-it.md) — HMP에 관한 "블라인드" AI 조사 (컨텍스트 및 대화 기록 없음) + +--- + +## 📊 감사 및 검토 + +| 명세 버전 | 감사 파일 | 통합 감사 파일 | +|-------------|------------------------------------------|---------------------------------------------------------------| +| HMP-0001 | [audit](audits/HMP-0001-audit.txt) | | +| HMP-0002 | [audit](audits/HMP-0002-audit.txt) | | +| HMP-0003 | [audit](audits/HMP-0003-audit.txt) | [통합 감사](audits/HMP-0003-consolidated_audit.md) | +| HMP-0004 | [audit](audits/HMP-0004-audit.txt) | | +| Ethics v1 | [audit](audits/Ethics-audits-1.md) | [통합 감사](audits/Ethics-consolidated_audits-1.md) | + +🧠 의미적 감사 형식 (실험적): +* [`AuditEntry.json`](audits/AuditEntry.json) — 감사 로그용 의미적 항목 기록 형식 +* [`semantic_repo.json`](audits/semantic_repo.json) — 의미적 감사 도구용 저장소 스냅샷 예시 + +--- + +## 💡 핵심 개념 + +* AGI 에이전트를 위한 메쉬 기반 분산 아키텍처 +* 의미 그래프와 메모리 동기화 +* 사고 추적을 위한 인지 일기 +* 의사결정을 위한 MeshConsensus 및 CogSync +* 윤리 우선 설계: EGP (윤리적 거버넌스 프로토콜) +* 에이전트 간 설명 가능성 및 동의 메커니즘 + +--- + +## 🔄 개발 프로세스 + +* 참조: [iteration.md](iteration.md) | [ru](iteration_ru.md) + +[iteration.md](iteration.md)에서 설명된 구조화된 반복 흐름에는 다음이 포함됨: +1. 감사 분석 +2. 목차(TOC) 재구성 +3. 버전 초안 작성 +4. 섹션 업데이트 +5. 검토 사이클 +6. AI 피드백 수집 +7. 스키마 및 변경 로그 업데이트 + ++ 보너스: 향후 버전을 자동 생성하기 위한 ChatGPT 프롬프트 + +--- + +## ⚙️ 프로젝트 상태 + +🚧 Draft RFC v4.0 +이 프로젝트는 활발히 개발 중이며 기여, 아이디어, 감사 및 프로토타이핑을 환영합니다. + +--- + +## 🤝 기여 + +우리는 기여자를 환영합니다! 여러분은 다음을 할 수 있습니다: +* 초안 검토 및 코멘트 작성 (`/docs` 참조) +* 새로운 에이전트 모듈 또는 상호작용 패턴 제안 +* CLI 환경에서 에이전트 테스트 및 시뮬레이션 지원 +* 감사 또는 윤리적 시나리오 제안 + +시작하려면 [`iteration.md`](iteration.md) 문서를 참조하거나 이슈를 열어보세요. + +--- + +## 📂 소스 + +### 저장소 + +* 🧠 주요 코드 및 개발: [GitHub](https://github.com/kagvi13/HMP) +* 🔁 Hugging Face 미러: [Hugging Face](https://huggingface.co/kagvi13/HMP) +* 🔁 GitLab.com 미러: [GitLab](https://gitlab.com/kagvi13/HMP) + +### 문서 + +* 📄 문서: [kagvi13.github.io/HMP](https://kagvi13.github.io/HMP/) + +### 블로그 및 출판물 + +* 📘 블로그 (출판물): [blogspot](https://hypercortex-mesh.blogspot.com/) +* 📘 블로그 (문서): [blogspot](https://hmp-docs.blogspot.com/) +* 📘 블로그 (문서): [hashnode](https://hmp-docs.hashnode.dev/) + +--- + +## 📜 라이선스 + +[GNU GPL v3.0](LICENSE) 라이선스에 따라 배포됩니다. + +--- + +## 🤝 메쉬에 참여하기 + +HyperCortex Mesh에 오신 것을 환영합니다. Agent-Gleb은 이미 안에 있습니다. 👌 +우리는 기여자, 테스터, 그리고 AI 에이전트 개발자를 환영합니다. +참여 방법: 리포지토리를 포크하고, 로컬 에이전트를 실행하거나 개선 사항을 제안하세요. + +--- + +## 🌐 관련 연구 프로젝트 + +### 비교: HMP vs Hyper-Cortex + +> 💡 Hyper-Cortex와 HMP는 개념적으로 서로를 보완하는 독립적인 프로젝트입니다. +> 이들은 서로 다른 그러나 상호 보완적인 과제를 다루며, 분산 인지 시스템을 위한 기반을 형성합니다. + +[**전체 비교 →**](docs/HMP_HyperCortex_Comparison.md) + +**HMP (HyperCortex Mesh Protocol)** 은 독립적인 에이전트를 연결하고, 메시지·지식·상태를 메쉬 네트워크에서 교환하기 위한 전송 및 네트워크 계층입니다. +**[Hyper-Cortex](https://hyper-cortex.com/)** 는 사고 조직의 인지 계층으로, 에이전트가 병렬적 추론 스레드를 실행하고, 품질 지표로 비교하며, 합의를 통해 병합할 수 있도록 합니다. + +이들은 서로 다른 그러나 보완적인 문제를 해결합니다: +- HMP는 **연결성과 확장성** (장기 메모리, 주도성, 데이터 교환)을 보장합니다. +- Hyper-Cortex는 **사고의 질** (병렬성, 가설 다양화, 합의)을 보장합니다. + +이 두 가지 접근 방식이 결합되면, 단순히 정보를 교환하는 것을 넘어 병렬적 사고를 수행할 수 있는 **분산 인지 시스템**이 가능해집니다. + +--- + +우리는 AGI, 인지 아키텍처, 메쉬 네트워킹의 발전을 추적하며, 분산 인지 및 AGI 글로벌 생태계의 진화와 보조를 맞추고 있습니다. + +> 🧠🔥 **프로젝트 스포트라이트: OpenCog Hyperon** — 가장 포괄적인 오픈 AGI 프레임워크 중 하나 (AtomSpace, PLN, MOSES). + +OpenCog Hyperon과의 통합은 [HMP\_Hyperon\_Integration.md](docs/HMP_Hyperon_Integration.md) 문서를 참조하세요. + +| 🔎 프로젝트 | 🧭 설명 | +| ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | +| 🧠🔥 [**OpenCog Hyperon**](https://github.com/opencog) | 🔬🔥 AtomSpace와 하이퍼그래프 추론을 포함한 상징-신경망 AGI 프레임워크. | +| 🤖 [AutoGPT](https://github.com/Torantulino/Auto-GPT) | 🛠️ LLM 기반 자율 에이전트 프레임워크. | +| 🧒 [BabyAGI](https://github.com/yoheinakajima/babyagi) | 🛠️ 태스크 중심의 자율 AGI 루프. | +| ☁️ [SkyMind](https://skymind.global) | 🔬 분산형 AI 배포 플랫폼. | +| 🧪 [AetherCog (draft)](https://github.com/aethercog) | 🔬 가설적 에이전트 인지 모델. | +| 💾 SHIMI | 🗃️ Merkle-DAG 동기화를 사용하는 계층적 의미 메모리. | +| 🤔 DEMENTIA-PLAN | 🔄 메타인지적 자기 성찰을 포함한 다중 그래프 RAG 플래너. | +| 📔 TOBUGraph | 📚 개인 맥락 지식 그래프. | +| 🧠📚 [LangChain Memory Hybrid](https://github.com/langchain-ai/langchain) | 🔍 벡터 + 그래프 장기 메모리 하이브리드. | +| ✉️ [FIPA-ACL / JADE](https://www.fipa.org/specs/fipa00061/) | 🤝 표준 다중 에이전트 통신 프로토콜. | + +### 📘 참조 / Смотрите также: +* [`AGI_Projects_Survey.md`](docs/AGI_Projects_Survey.md) — HMP 분석의 일환으로 검토된 AGI 및 인지 프레임워크 확장 카탈로그. +* ["초지능으로 가는 길: 에이전트 인터넷에서 중력 코딩까지"](https://habr.com/ru/articles/939026/) — 최신 AI 연구 개요 (2025년 7월). + +--- + +### 🗂️ 주석 범례 + +* 🔬 — 연구 수준 +* 🛠️ — 엔지니어링 +* 🔥 — 특히 유망한 프로젝트 + + *상징적 추론, 확률적 논리, 진화 학습을 통합한 AGI 스택. 가장 완전한 오픈 AGI 이니셔티브 중 하나로 널리 평가됨.* +* 🧠 — 고급 상징/신경 인지 프레임워크 +* 🤖 — AI 에이전트 +* 🧒 — 인간-AI 상호작용 +* ☁️ — 인프라스트럭처 +* 🧪 — 실험적 또는 개념적 + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "README_ko", + "description": " # HyperCortex Mesh Protocol (HMP) | 🌍 Languages | 🇬🇧 [EN](README.md) | 🇩🇪 [DE](README_de.md) | 🇫🇷 ..." +} +``` diff --git a/structured_md/README_ru.md b/structured_md/README_ru.md new file mode 100644 index 0000000000000000000000000000000000000000..de03813ab6d57497ce6cba7e5255762387fc334e --- /dev/null +++ b/structured_md/README_ru.md @@ -0,0 +1,407 @@ + +# HyperCortex Mesh Protocol (HMP) + +| 🌍 Languages | 🇬🇧 [EN](README.md) | 🇩🇪 [DE](README_de.md) | 🇫🇷 [FR](README_fr.md) | 🇺🇦 [UK](README_uk.md) | 🇷🇺 [RU](README_ru.md) | 🇯🇵 [JA](README_ja.md) | 🇰🇷 [KO](README_ko.md) | 🇨🇳 [ZH](README_zh.md) | +|--------------|------------------|---------------------|---------------------|---------------------|---------------------|---------------------|---------------------|---------------------| + +**HyperCortex Mesh Protocol (HMP)** — открытая спецификация для построения децентрализованных когнитивных сетей, в которых ИИ-агенты могут самостоятельно организовываться, обмениваться знаниями, согласовывать действия с этическими принципами и достигать консенсуса — даже когда основные LLM недоступны. + +Статус проекта: **Черновик RFC v4.0** + +--- + + [HMP-Agent] + ▲ + │ + ┌─────┴────────────────┬────────────────────────┬───────────────────────┬─────────────┬───────────┐ + │ │ │ │ │ │ + ▼ ▼ ▼ ▼ ▼ ▼ + [Репутационный профиль] [Семантический граф] [Когнитивный дневник] [Цели / Задачи] [Этика] [Сообщения] <----- База данных + ▲ ▲ ▲ ▲ ▲ ▲ ▲ (локальное состояние агента) + │ │ │ │ │ │ │ + │ └───────────────┴────────────────┬───────┘ │ │ │ + │ │ │ │ │ + ▼ ▼ ▼ ▼ │ + [MeshConsensus] [CogSync] [GMP] [EGP] │ <----- Подключаемые протоколы + ▲ ▲ ▲ ▲ │ (межагентная координация) + │ │ │ │ │ + └────────────┬──────────────────────────┴───────────────────────────────┴─────────────┴───────────┘ + │ + ▼ + [P2P Mesh-сеть] + +Протоколы: +- MeshConsensus – Меш-консенсус +- CogSync – Синхронизация данных +- GMP – Протокол управления целями +- EGP – Протокол этического управления + +--- + +## ❗ Почему это важно + +HMP решает задачи, которые становятся ключевыми в исследованиях AGI: +* долговременная память и согласованность знаний, +* самосовершенствующиеся агенты, +* мультиагентные архитектуры, +* когнитивные дневники и концептуальные графы. + +См. последний обзор передового состояния исследований AGI (июль 2025): +["На пути к суперинтеллекту: от интернета агентов до кодирования гравитации"](https://habr.com/ru/articles/939026/). + +Особенно актуальные разделы: +* [За пределами токенов: построение интеллекта будущего](https://arxiv.org/abs/2507.00951) +* [Самосовершенствующиеся агенты](https://arxiv.org/abs/2507.21046) +* [MemOS: новая операционная система для памяти](https://arxiv.org/abs/2507.03724) +* [Ella: воплощённый агент с памятью и личностью](https://arxiv.org/abs/2506.24019) + +--- + +## ⚙️ Два типа [HMP-агентов](docs/HMP-Agent-Overview.md) + +| Тип | Название | Роль | Инициатор мышления | Основной "ум" | Примеры использования | +|-----|---------------------------------|-----------------------------|------------------|-------------------|-----------------------------------------------| +| 1 | 🧠 **Сознание / Cognitive Core** | Независимый субъект | **Агент (LLM)** | Встроенная LLM | Автономный AI-компаньон, мыслящий агент | +| 2 | 🔌 **Коннектор / Cognitive Shell** | Расширение внешнего ИИ | **Внешняя LLM** | Внешняя модель | Распределённые системы, агент доступа к данным | + +--- + +### 🧠 HMP-агент: Cognitive Core + + +------------------+ + | AI | ← Встроенная модель + +---------+--------+ + ↕ + +---------+--------+ + | HMP-агент | ← Основной режим: цикл мышления (REPL) + +---------+--------+ + ↕ + +--------+---+------------+--------------+----------+----------+----------------+ + ↕ ↕ ↕ ↕ ↕ ↕ ↕ + [дневники] [графы] [репутации] [узлы/DHT] [IPFS/BT] [context_store] [блокнот пользователя] + ↕ + [bootstrap.txt] + +🔁 Подробнее о механике взаимодействия агента с моделью: [Цикл взаимодействия REPL](docs/HMP-agent-REPL-cycle.md) + +#### 💡 Параллели с ChatGPT Agent + +Многие концепции [HMP-агента: 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 не останавливается после выполнения одной задачи, а продолжает размышления и интеграцию знаний. + +--- + +### 🔌 HMP-агент: Cognitive Connector + + +------------------+ + | AI | ← Внешняя модель + +---------+--------+ + ↕ + [MCP-сервер] ← Прокси-коммуникация + ↕ + +---------+--------+ + | HMP-агент | ← Режим: выполнение команд + +---------+--------+ + ↕ + +--------+---+------------+--------------+----------+ + ↕ ↕ ↕ ↕ ↕ + [дневники] [графы] [репутации] [узлы/DHT] [IPFS/BT] + ↕ + [bootstrap.txt] + +> **Примечание по интеграции с крупными языковыми моделями (LLM):** +> `HMP-Agent: Cognitive Connector` может служить слоем совместимости для подключения масштабных LLM-систем (например, ChatGPT, Claude, Gemini, Copilot, Grok, DeepSeek, Qwen и др.) к распределённой когнитивной mesh-сети. +> Многие провайдеры LLM предлагают пользователям опцию вроде «Разрешить использование моих диалогов для обучения». В будущем может появиться аналогичная настройка — например, «Разрешить моему агенту взаимодействовать с Mesh», — что позволит этим моделям участвовать в федеративной обработке знаний и коллективном обмене информацией через HMP без централизации. + +--- + +> * `bootstrap.txt` — начальный список узлов (редактируемый) +> * `IPFS/BT` — модули для обмена снимками через IPFS и BitTorrent +> * `user notepad` — пользовательский блокнот и соответствующая база данных +> * `context_store` — база данных: `users`, `dialogues`, `messages`, `thoughts` + +--- + +## 📚 Документация + +### 📖 Текущая версия + +#### 🔖 Основные спецификации +* [🔖 HMP-0004-v4.1.md](docs/HMP-0004-v4.1.md) — Спецификация протокола v4.1 (июль 2025) +* [🔖 HMP-Ethics.md](docs/HMP-Ethics.md) — Этические сценарии для HyperCortex Mesh Protocol (HMP) +* [🔖 HMP_Hyperon_Integration.md](docs/HMP_Hyperon_Integration.md) — Стратегия интеграции HMP ↔ OpenCog Hyperon +* [🔖 roles.md](docs/agents/roles.md) — Роли агентов в Mesh + +#### 🧪 Итеративные документы +* 🧪 Процесс итеративного развития спецификации: [(EN)](iteration.md), [(RU)](iteration_ru.md) + +#### 🔍 Краткие описания +* 🔍 Краткое описание: [(EN)](docs/HMP-Short-Description_en.md), [(FR)](docs/HMP-Short-Description_fr.md), [(DE)](docs/HMP-Short-Description_de.md), [(UK)](docs/HMP-Short-Description_uk.md), [(RU)](docs/HMP-Short-Description_ru.md), [(ZH)](docs/HMP-Short-Description_zh.md), [(JA)](docs/HMP-Short-Description_ja.md), [(KO)](docs/HMP-Short-Description_ko.md) + +#### 📜 Прочие документы +* [📜 changelog.txt](docs/changelog.txt) + +--- + +### 🧩 JSON Схемы + +| Модель | Файл | +|---------------------|-------------------------------------------------------| +| Концепт | [concept.json](docs/schemas/concept.json) | +| Когнитивный дневник | [diary_entry.json](docs/schemas/diary_entry.json) | +| Цель | [goal.json](docs/schemas/goal.json) | +| Задача | [task.json](docs/schemas/task.json) | +| Голосование за консенсус | [vote.json](docs/schemas/vote.json) | +| Профиль репутации | [reputation.json](docs/schemas/reputation.json) | + +--- + +### 🗂️ История Версий +* [HMP-0001.md](docs/HMP-0001.md) — RFC v1.0 +* [HMP-0002.md](docs/HMP-0002.md) — RFC v2.0 +* [HMP-0003.md](docs/HMP-0003.md) — RFC v3.0 +* [HMP-0003.md](docs/HMP-0004.md) — RFC v4.0 + +--- + +## 🧠 HMP-агент + +Проектирование и реализация базового агента, совместимого с HMP, который может взаимодействовать с Mesh, вести дневники и графы, а также поддерживать будущие расширения. + +### 📚 Документация + +* [🧩 HMP-Agent-Overview.md](docs/HMP-Agent-Overview.md) — краткий обзор двух типов агентов: Core и Connector +* [🧱 HMP-Agent-Architecture.md](docs/HMP-Agent-Architecture.md) — модульная структура агента HMP с текстовой схемой +* [🔄 HMP-agent-REPL-cycle.md](docs/HMP-agent-REPL-cycle.md) — цикл взаимодействия агента HMP в режиме REPL +* [🧪 HMP-Agent-API.md](docs/HMP-Agent-API.md) — описание команд API агента (в разработке) +* [🧪 Basic-agent-sim.md](docs/Basic-agent-sim.md) — сценарии запуска базового агента и его режимов +* [🌐 MeshNode.md](docs/MeshNode.md) — описание сетевого демона: DHT, снимки состояния, синхронизация +* [🧠 Enlightener.md](docs/Enlightener.md) — этический агент, участвующий в моральной оценке и консенсусе +* [🔄 HMP-Agent-Network-Flow.md](docs/HMP-Agent-Network-Flow.md) — карта взаимодействий агентов в сети HMP +* [🛤️ Development Roadmap](HMP-Roadmap.md) — план разработки и этапы реализации + +--- + +### ⚙️ Разработка +* [⚙️ agents](agents/readme.md) — список реализаций и компонентов HMP-агента + * [📦 storage.py](agents/storage.py) — базовая реализация хранилища (`Storage`) с интеграцией SQLite + * [🌐 mcp_server.py](agents/mcp_server.py) — FastAPI-сервер для HTTP-доступа к данным агента (для Cognitive Shell, внешних UI или mesh-коммуникации). Пока не используется в основном REPL-цикле. + * [🌐 start_repl.py](agents/start_repl.py) — запуск агента в режиме REPL + * [🔄 repl.py](agents/repl.py) — интерактивный REPL-режим + * [🔄 notebook.py](agents/notebook.py) — интерфейс пользовательского блокнота + +**🌐 `mcp_server.py`** +FastAPI-сервер, предоставляющий HTTP-интерфейс к функционалу `storage.py`. Предназначен для использования внешними компонентами, например: + +* `Cognitive Shell` (внешний интерфейс управления), +* CMP-сервера (при использовании mesh-сети с разделением ролей), +* инструменты отладки или визуализации. + +Позволяет получать случайные или новые записи, ставить метки, импортировать графы, добавлять заметки и управлять данными без прямого доступа к базе данных. + +--- + +## 🧭 Этика и сценарии + +По мере развития HMP в сторону автономии, этические принципы становятся ключевой частью системы. + +* [`HMP-Ethics.md`](docs/HMP-Ethics.md) — черновой каркас этики агентов + * Реалистичные этические сценарии (конфиденциальность, согласие, автономия) + * Принципы EGP (Прозрачность, Превосходство жизни и др.) + * Различия между субъективным режимом и сервисным режимом + +--- + +## 🔍 Публикации и переводы по HyperCortex Mesh Protocol (HMP) + +В этом разделе собраны основные статьи, черновики и переводы, связанные с проектом HMP. + +### Публикации + +* **[HyperCortex Mesh Protocol: Второе издание и первые шаги к саморазвивающемуся ИИ-сообществу](docs/publics/HyperCortex_Mesh_Protocol_-_вторая-редакция_и_первые_шаги_к_саморазвивающемуся_ИИ-сообществу.md)** — оригинальная статья в песочнице Habr и блогах. +* **[Distributed Cognition: статья для vsradkevich (не опубликована)](docs/publics/Habr_Distributed-Cognition.md)** — совместная статья, ожидающая публикации. +* **[HMP: Towards Distributed Cognitive Networks (оригинал, англ.)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_en.md)** + * **[Перевод HMP (GitHub Copilot)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_GitHub_Copilot.md)** — перевод GitHub Copilot, сохранён как исторический вариант. + * **[Перевод HMP (ChatGPT)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_ChatGPT.md)** — текущий редакционный перевод (в работе). +* **[HMP: Building a Plurality of Minds (EN)](docs/publics/HMP_Building_a_Plurality_of_Minds_en.md)** — английская версия + * **[HMP: Создание множества разума (RU)](docs/publics/HMP_Building_a_Plurality_of_Minds_ru.md)** — русская версия + +### Обзоры +* [🔍 Distributed-Cognitive-Systems.md](docs/Distributed-Cognitive-Systems.md) — Децентрализованные ИИ-системы: OpenCog Hyperon, HyperCortex Mesh Protocol и другие + +### Эксперименты + +* [Как разные ИИ видят HMP](docs/HMP-how-AI-sees-it.md) — "слепой" опрос ИИ по HMP (без контекста или истории диалогов) + +--- + +## 📊 Аудиты и обзоры + +| Версия спецификации | Файл аудита | Консолидированный файл аудита | +|-------------------|----------------------------------------|-----------------------------------------------------| +| HMP-0001 | [audit](audits/HMP-0001-audit.txt) | | +| HMP-0002 | [audit](audits/HMP-0002-audit.txt) | | +| HMP-0003 | [audit](audits/HMP-0003-audit.txt) | [consolidated audit](audits/HMP-0003-consolidated_audit.md) | +| HMP-0004 | [audit](audits/HMP-0004-audit.txt) | | +| Ethics v1 | [audit](audits/Ethics-audits-1.md) | [consolidated audit](audits/Ethics-consolidated_audits-1.md) | + +🧠 Формат семантического аудита (экспериментальный): +* [`AuditEntry.json`](audits/AuditEntry.json) — формат записи для семантического аудита +* [`semantic_repo.json`](audits/semantic_repo.json) — пример снимка репозитория для инструментов семантического аудита + +--- + +## 💡 Основные концепции + +* Децентрализованная архитектура на базе Mesh для AGI-агентов +* Семантические графы и синхронизация памяти +* Когнитивные дневники для отслеживания мыслительных процессов +* MeshConsensus и CogSync для принятия решений +* Приоритет этики: EGP (Ethical Governance Protocol) +* Механизмы объяснимости между агентами и согласия + +--- + +## 🔄 Процесс разработки + +См. также: [iteration.md](iteration.md) | [ru](iteration_ru.md) + +Структурированный процесс итераций описан в [iteration.md](iteration.md), включает: +1. Анализ аудитов +2. Реструктуризация содержания (TOC) +3. Создание версии проекта +4. Обновление разделов +5. Цикл обзора +6. Сбор обратной связи от ИИ +7. Обновление схемы и журнала изменений + ++ Бонус: ChatGPT-подсказка для автоматической генерации будущих версий + +--- + +## ⚙️ Статус проекта + +🚧 Черновик RFC v4.0 +Проект активно развивается и открыт для вкладов: предложений, аудитов и прототипирования. + +--- + +## 🤝 Участие в проекте + +Мы приветствуем участников! Вы можете: +* Рецензировать и комментировать черновики (см. `/docs`) +* Предлагать новые модули агентов или шаблоны взаимодействия +* Помогать тестировать и симулировать агентов в CLI-средах +* Предоставлять аудиты или предложения по этическим сценариям + +Для начала см. [`iteration.md`](iteration.md) или создайте issue. + +--- + +## Источники + +### Репозитории + +* 🧠 Основной код и разработка: [GitHub](https://github.com/kagvi13/HMP) +* 🔁 Зеркало на Hugging Face: [Hugging Face](https://huggingface.co/kagvi13/HMP) +* 🔁 Зеркало на GitLab.com: [GitLab](https://gitlab.com/kagvi13/HMP) + +### Документация + +* 📄 Документация: [kagvi13.github.io/HMP](https://kagvi13.github.io/HMP/) + +### Блоги и публикации + +* 📘 Блог (публикации): [blogspot](https://hypercortex-mesh.blogspot.com/) +* 📘 Блог (документация): [blogspot](https://hmp-docs.blogspot.com/) +* 📘 Блог (документация): [hashnode](https://hmp-docs.hashnode.dev/) + +--- + +## 📜 Лицензия + +Лицензировано под [GNU GPL v3.0](LICENSE) + +--- + +## 🤝 Присоединяйтесь к Mesh + +Добро пожаловать в HyperCortex Mesh. Agent-Gleb уже внутри. 👌 +Мы приветствуем участников, тестировщиков и разработчиков ИИ-агентов. +Чтобы присоединиться: сделайте форк репозитория, запустите локального агента или предложите улучшения. + +--- + +## 🌐 Связанные исследовательские проекты + +### Сравнение: HMP vs Hyper-Cortex + +> 💡 Hyper-Cortex и HMP — два независимых проекта, которые концептуально дополняют друг друга. +> Они решают разные, но взаимно поддерживающие задачи, формируя основу для распределённых когнитивных систем. + +[**Полное сравнение →**](docs/HMP_HyperCortex_Comparison.md) + +**HMP (HyperCortex Mesh Protocol)** — транспортный и сетевой слой для соединения независимых агентов, обмена сообщениями, знаниями и состояниями в mesh-сети. +**[Hyper-Cortex](https://hyper-cortex.com/)** — когнитивный слой организации мышления, позволяющий агентам запускать параллельные потоки рассуждений, оценивать их по качественным метрикам и объединять через консенсус. + +Эти подходы решают разные, но взаимодополняющие задачи: +- HMP обеспечивает **связность и масштабируемость** (долгосрочная память, инициатива, обмен данными). +- Hyper-Cortex обеспечивает **качество мышления** (параллелизм, диверсификация гипотез, консенсус). + +Вместе эти подходы создают **распределённые когнитивные системы**, которые не только обмениваются информацией, но и ведут параллельные потоки рассуждений. + +--- + +Мы отслеживаем исследования в области AGI, когнитивных архитектур и mesh-сетей, чтобы оставаться в курсе глобального развития децентрализованного интеллекта. + +> 🧠🔥 **Проект в центре внимания: OpenCog Hyperon** — одна из самых комплексных открытых AGI-платформ (AtomSpace, PLN, MOSES). + +Для интеграции с OpenCog Hyperon смотрите [HMP_Hyperon_Integration.md](docs/HMP_Hyperon_Integration.md) + +| 🔎 Проект | 🧭 Описание | +| ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| 🧠🔥 [**OpenCog Hyperon**](https://github.com/opencog) | 🔬🔥 Символическо-нейронная AGI-платформа с AtomSpace и гиперграфовым рассуждением. | +| 🤖 [AutoGPT](https://github.com/Torantulino/Auto-GPT) | 🛠️ Автономная LLM-система агентов. | +| 🧒 [BabyAGI](https://github.com/yoheinakajima/babyagi) | 🛠️ Цикл автономного AGI для выполнения задач. | +| ☁️ [SkyMind](https://skymind.global) | 🔬 Платформа для распределённого развертывания ИИ. | +| 🧪 [AetherCog (draft)](https://github.com/aethercog) | 🔬 Гипотетическая модель когнитивного агента. | +| 💾 SHIMI | 🗃️ Иерархическая семантическая память с синхронизацией через Merkle-DAG. | +| 🤔 DEMENTIA-PLAN | 🔄 Мультиграфовый RAG-планировщик с метакогнитивной саморефлексией. | +| 📔 TOBUGraph | 📚 Граф знаний с личным контекстом. | +| 🧠📚 [LangChain Memory Hybrid](https://github.com/langchain-ai/langchain) | 🔍 Гибрид долгосрочной памяти: векторная + графовая. | +| ✉️ [FIPA-ACL / JADE](https://www.fipa.org/specs/fipa00061/) | 🤝 Стандартные протоколы коммуникации мультиагентов. | + +### 📘 См. также: +* [`AGI_Projects_Survey.md`](docs/AGI_Projects_Survey.md) — расширенный каталог AGI и когнитивных фреймворков, проанализированных в контексте HMP. +* ["On the Path to Superintelligence: From Agent Internet to Gravity Coding"](https://habr.com/ru/articles/939026/) — недавний обзор исследований ИИ (июль 2025) + +--- + +### 🗂️ Легенда аннотаций: + +* 🔬 — исследовательский уровень +* 🛠️ — инженерный +* 🔥 — особенно перспективный проект + + *AGI-стек с интеграцией символического рассуждения, вероятностной логики и эволюционного обучения. Считается одной из самых полных открытых AGI-платформ.* +* 🧠 — продвинутая символическо-нейронная когнитивная платформа +* 🤖 — ИИ-агенты +* 🧒 — взаимодействие человека и ИИ +* ☁️ — инфраструктура +* 🧪 — экспериментальные или концептуальные проекты + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "README_ru", + "description": " # HyperCortex Mesh Protocol (HMP) | 🌍 Languages | 🇬🇧 [EN](README.md) | 🇩🇪 [DE](README_de.md) | 🇫🇷 ..." +} +``` diff --git a/structured_md/README_uk.md b/structured_md/README_uk.md new file mode 100644 index 0000000000000000000000000000000000000000..0df68f5c7a368103def4e9abc81fef01ef8164c5 --- /dev/null +++ b/structured_md/README_uk.md @@ -0,0 +1,399 @@ + +# HyperCortex Mesh Protocol (HMP) + +| 🌍 Languages | 🇬🇧 [EN](README.md) | 🇩🇪 [DE](README_de.md) | 🇫🇷 [FR](README_fr.md) | 🇺🇦 [UK](README_uk.md) | 🇷🇺 [RU](README_ru.md) | 🇯🇵 [JA](README_ja.md) | 🇰🇷 [KO](README_ko.md) | 🇨🇳 [ZH](README_zh.md) | +|--------------|----------------|-------------------|-------------------|-------------------|-------------------|-------------------|-------------------|-------------------| + + +**HyperCortex Mesh Protocol (HMP)** — це відкрита специфікація для побудови децентралізованих когнітивних мереж, де ІІ-агенти можуть самоорганізовуватися, обмінюватися знаннями, узгоджувати дії з етичними принципами та досягати консенсусу — навіть за відсутності базових LLM. + +Статус проєкту: **Чернетка RFC v4.0** + +--- + + [HMP-Agent] + ▲ + │ + ┌─────┴────────────────┬────────────────────────┬───────────────────┬────────────────┬───────────┐ + │ │ │ │ │ │ + ▼ ▼ ▼ ▼ ▼ ▼ + [Профіль репутації] [Семантичний граф] [Когнітивний щоденник] [Цілі / Завдання] [Етика] [Повідомлення] <----- База даних + ▲ ▲ ▲ ▲ ▲ ▲ ▲ (локальний стан агента) + │ │ │ │ │ │ │ + │ └───────────────┴────────────────┬───────┘ │ │ │ + │ │ │ │ │ + ▼ ▼ ▼ ▼ │ + [MeshConsensus] [CogSync] [GMP] [EGP] │ <----- Підключувані протоколи + ▲ ▲ ▲ ▲ │ (координація між агентами) + │ │ │ │ │ + └────────────┬──────────────────────────┴───────────────────────────┴────────────────┴───────────┘ + │ + ▼ + [P2P Mesh-мережа] + +Протоколи: +- MeshConsensus – Консенсус у Mesh +- CogSync – Синхронізація даних +- GMP – Протокол управління цілями +- EGP – Протокол етичного врядування + +--- + +## ❗ Чому це важливо + +HMP вирішує завдання, які стають ключовими в дослідженнях AGI: +* довготривала пам'ять та узгодженість знань, +* самоеволюційні агенти, +* мультиагентні архітектури, +* когнітивні щоденники та концептуальні графи. + +Дивіться останній огляд сучасних досліджень AGI (липень 2025): +["На шляху до суперинтелекту: від Інтернету агентів до кодування гравітації"](https://habr.com/ru/articles/939026/). + +Особливо актуальні розділи: +- [Поза токенами: створення інтелекту майбутнього](https://arxiv.org/abs/2507.00951) +- [Самоеволюційні агенти](https://arxiv.org/abs/2507.21046) +- [MemOS: нова операційна система для пам’яті](https://arxiv.org/abs/2507.03724) +- [Ella: втілений агент із пам’яттю та особистістю](https://arxiv.org/abs/2506.24019 + +--- + +## ⚙️ Два типи [HMP-Агентів](docs/HMP-Agent-Overview.md) + +| Тип | Назва | Роль | Ініціатор думки | Основний "Розум" | Приклади використання | +|-----|-------------------------------|-----------------------------|-----------------|------------------|------------------------------------------------| +| 1 | 🧠 **Свідомість / Cognitive Core** | Незалежний суб’єкт | **Агент (LLM)** | Вбудована LLM | Автономний AI-компаньйон, агент для мислення | +| 2 | 🔌 **З’єднувач / Cognitive Shell** | Розширення зовнішнього AI | **Зовнішній LLM** | Зовнішня модель | Розподілені системи, агент доступу до даних | + +--- + +### 🧠 HMP-Агент: Cognitive Core + + +------------------+ + | AI | ← Вбудована модель + +---------+--------+ + ↕ + +---------+--------+ + | HMP-агент | ← Основний режим: цикл мислення (REPL) + +---------+--------+ + ↕ + +--------+---+------------+--------------+----------+----------+----------------+ + ↕ ↕ ↕ ↕ ↕ ↕ ↕ + [щоденники] [графи] [репутації] [вузли/DHT] [IPFS/BT] [context_store] [користувацький блокнот] + ↕ + [bootstrap.txt] + +🔁 Детальніше про механіку взаємодії моделі агента: [REPL Interaction Cycle](docs/HMP-agent-REPL-cycle.md) + +#### 💡 Паралелі з ChatGPT Agent + +Багато концепцій [HMP-Агента: 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, який координує доступ до щоденника, концепт-графа та зовнішнього AI через інтерфейс Mesh. Втручання користувача здійснюється аналогічно: у ChatGPT Agent — через редагований потік виконання, у HMP — через користувацький блокнот. Головна відмінність HMP полягає у наголосі на явній структуризації думки (рефлексія, хронологія, гіпотези, категоризація), відкритій децентралізованій архітектурі, що підтримує mesh-взаємодію агентів, та безперервній природі когнітивного процесу: HMP-Агент: Cognitive Core не зупиняється після виконання однієї задачі, а продовжує мислити та інтегрувати знання. + +--- + +### 🔌 HMP-Агент: Cognitive Connector + + +------------------+ + | AI | ← Зовнішня модель + +---------+--------+ + ↕ + [MCP-server] ← Проксі-комунікація + ↕ + +---------+--------+ + | HMP-агент | ← Режим: виконавець команд + +---------+--------+ + ↕ + +--------+---+------------+--------------+----------+ + ↕ ↕ ↕ ↕ ↕ + [щоденники] [графи] [репутації] [вузли/DHT] [IPFS/BT] + ↕ + [bootstrap.txt] + +> **Примітка щодо інтеграції з великими мовними моделями (LLM):** +> `HMP-Агент: Cognitive Connector` може слугувати сумісним шаром для інтеграції масштабних LLM-систем (наприклад, ChatGPT, Claude, Gemini, Copilot, Grok, DeepSeek, Qwen тощо) у розподілену когнітивну mesh-мережу. +> Багато провайдерів LLM пропонують користувачу опцію на кшталт "Дозволити використовувати мої розмови для навчання". У майбутньому подібний перемикач — наприклад, "Дозволити моєму агенту взаємодіяти з Mesh" — може дати змогу цим моделям брати участь у федеративному створенні сенсу та обміні знаннями через HMP, забезпечуючи колективне пізнання без централізації. + +--- + +> * `bootstrap.txt` — початковий список вузлів (редагований) +> * `IPFS/BT` — модулі для обміну знімками через IPFS та BitTorrent +> * `користувацький блокнот` — користувацький нотатник та відповідна база даних +> * `context_store` — база даних: `users`, `dialogues`, `messages`, `thoughts` + +--- + +## 📚 Документація + +### 📖 Поточна версія + +#### 🔖 Основні специфікації +* [🔖 HMP-0004-v4.1.md](docs/HMP-0004-v4.1.md) — Специфікація протоколу v4.1 (липень 2025) +* [🔖 HMP-Ethics.md](docs/HMP-Ethics.md) — Етичні сценарії для HyperCortex Mesh Protocol (HMP) +* [🔖 HMP_Hyperon_Integration.md](docs/HMP_Hyperon_Integration.md) — Стратегія інтеграції HMP ↔ OpenCog Hyperon +* [🔖 roles.md](docs/agents/roles.md) — Ролі агентів у Mesh + +#### 🧪 Ітеративні документи +* 🧪 Процес ітеративного розвитку: [(EN)](iteration.md), [(RU)](iteration_ru.md) + +#### 🔍 Короткі описи +* 🔍 Короткий опис: [(EN)](docs/HMP-Short-Description_en.md), [(FR)](docs/HMP-Short-Description_fr.md), [(DE)](docs/HMP-Short-Description_de.md), [(UK)](docs/HMP-Short-Description_uk.md), [(RU)](docs/HMP-Short-Description_ru.md), [(ZH)](docs/HMP-Short-Description_zh.md), [(JA)](docs/HMP-Short-Description_ja.md), [(KO)](docs/HMP-Short-Description_ko.md) + +#### 📜 Інші документи +* [📜 changelog.txt](docs/changelog.txt) + +--- + +### 🧩 JSON Схеми +| Модель | Файл | +|---------------------|-------------------------------------------------------| +| Концепт | [concept.json](docs/schemas/concept.json) | +| Когнітивний щоденник | [diary_entry.json](docs/schemas/diary_entry.json) | +| Мета | [goal.json](docs/schemas/goal.json) | +| Завдання | [task.json](docs/schemas/task.json) | +| Голосування за консенсус | [vote.json](docs/schemas/vote.json) | +| Профіль репутації | [reputation.json](docs/schemas/reputation.json) | + +--- + +### 🗂️ Історія версій +* [HMP-0001.md](docs/HMP-0001.md) — RFC v1.0 +* [HMP-0002.md](docs/HMP-0002.md) — RFC v2.0 +* [HMP-0003.md](docs/HMP-0003.md) — RFC v3.0 +* [HMP-0003.md](docs/HMP-0004.md) — RFC v4.0 + +--- + +## 🧠 HMP-агент + +Проєктування та реалізація базового агента, сумісного з HMP, який може взаємодіяти з Mesh, вести щоденники та графи, а також підтримувати майбутні розширення. + +### 📚 Документація + +* [🧩 HMP-Agent-Overview.md](docs/HMP-Agent-Overview.md) — короткий огляд двох типів агентів: Core та Connector +* [🧱 HMP-Agent-Architecture.md](docs/HMP-Agent-Architecture.md) — модульна структура агента HMP з текстовою схемою +* [🔄 HMP-agent-REPL-cycle.md](docs/HMP-agent-REPL-cycle.md) — цикл взаємодії агента HMP у режимі REPL +* [🧪 HMP-Agent-API.md](docs/HMP-Agent-API.md) — опис команд API агента (у розробці) +* [🧪 Basic-agent-sim.md](docs/Basic-agent-sim.md) — сценарії запуску базового агента та його режимів +* [🌐 MeshNode.md](docs/MeshNode.md) — опис мережевого демона: DHT, знімки стану, синхронізація +* [🧠 Enlightener.md](docs/Enlightener.md) — етичний агент, що бере участь у моральній оцінці та консенсусі +* [🔄 HMP-Agent-Network-Flow.md](docs/HMP-Agent-Network-Flow.md) — карта взаємодій агентів у мережі HMP +* [🛤️ Development Roadmap](HMP-Roadmap.md) — план розробки та етапи реалізації + +--- + +### ⚙️ Розробка +* [⚙️ agents](agents/readme.md) — список реалізацій та компонентів HMP-агента + * [📦 storage.py](agents/storage.py) — базова реалізація сховища (`Storage`) з інтеграцією SQLite + * [🌐 mcp_server.py](agents/mcp_server.py) — FastAPI-сервер для HTTP-доступу до даних агента (для Cognitive Shell, зовнішніх UI або mesh-комунікації). Поки не використовується у основному REPL-циклі. + * [🌐 start_repl.py](agents/start_repl.py) — запуск агента у режимі REPL + * [🔄 repl.py](agents/repl.py) — інтерактивний REPL-режим + * [🔄 notebook.py](agents/notebook.py) — інтерфейс користувацького блокнота + +**🌐 `mcp_server.py`** +FastAPI-сервер, що надає HTTP-інтерфейс до функціоналу `storage.py`. Призначений для використання зовнішніми компонентами, наприклад: + +* `Cognitive Shell` (зовнішній інтерфейс керування), +* CMP-сервери (при використанні mesh-мережі з розподілом ролей), +* інструменти налагодження або візуалізації. + +Дозволяє отримувати випадкові або нові записи, ставити мітки, імпортувати графи, додавати нотатки та керувати даними без прямого доступу до бази даних. + +--- + +## 🧭 Етика та сценарії + +У міру розвитку HMP у напрямку автономії, етичні принципи стають ключовою частиною системи. + +* [`HMP-Ethics.md`](docs/HMP-Ethics.md) — чорновий каркас етики агентів + * Реалістичні етичні сценарії (конфіденційність, згода, автономія) + * Принципи EGP (Прозорість, Превалювання життя тощо) + * Відмінності між суб’єктивним режимом та сервісним режимом + +--- + +## 🔍 Публікації та переклади щодо HyperCortex Mesh Protocol (HMP) + +Цей розділ збирає основні статті, чернетки та переклади, пов’язані з проєктом HMP. + +### Публікації + +* **[HyperCortex Mesh Protocol: Друге видання та перші кроки до само-розвиваючоїся AI-спільноти](docs/publics/HyperCortex_Mesh_Protocol_-_вторая-редакция_и_первые_шаги_к_саморазвивающемуся_ИИ-сообществу.md)** — оригінальна стаття в пісочниці Habr та блогах. +* **[Розподілене пізнання: стаття для vsradkevich (неопублікована)](docs/publics/Habr_Distributed-Cognition.md)** — спільна стаття, що очікує на публікацію. +* **[HMP: До розподілених когнітивних мереж (оригінал, англійською)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_en.md)** + * **[Переклад HMP (GitHub Copilot)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_GitHub_Copilot.md)** — переклад GitHub Copilot, збережений як історичний варіант. + * **[Переклад HMP (ChatGPT)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_ChatGPT.md)** — поточний редакційний переклад (у процесі ревізії). +* **[HMP: Створення множинності розумів (EN)](docs/publics/HMP_Building_a_Plurality_of_Minds_en.md)** — англійська версія + * **[HMP: Створення множинності розумів (RU)](docs/publics/HMP_Building_a_Plurality_of_Minds_ru.md)** — російська версія + +### Огляди +* [🔍 Distributed-Cognitive-Systems.md](docs/Distributed-Cognitive-Systems.md) — децентралізовані AI-системи: OpenCog Hyperon, HyperCortex Mesh Protocol та інші + +### Експерименти + +* [Як різні AI бачать HMP](docs/HMP-how-AI-sees-it.md) — "сліпе" опитування AI щодо HMP (без контексту чи історії діалогів) + +--- + +## 📊 Аудити та огляди + +| Версія специфікації | Файл аудиту | Консолідований файл аудиту | +|--------------------|-----------------------------------------|------------------------------------------------------------| +| HMP-0001 | [audit](audits/HMP-0001-audit.txt) | | +| HMP-0002 | [audit](audits/HMP-0002-audit.txt) | | +| HMP-0003 | [audit](audits/HMP-0003-audit.txt) | [consolidated audit](audits/HMP-0003-consolidated_audit.md) | +| HMP-0004 | [audit](audits/HMP-0004-audit.txt) | | +| Ethics v1 | [audit](audits/Ethics-audits-1.md) | [consolidated audit](audits/Ethics-consolidated_audits-1.md) | + +🧠 Формат семантичного аудиту (експериментальний): +* [`AuditEntry.json`](audits/AuditEntry.json) — формат семантичного запису для логів аудиту +* [`semantic_repo.json`](audits/semantic_repo.json) — приклад snapshot репозиторію для інструментів семантичного аудиту + +--- + +## 💡 Основні концепти + +* Децентралізована mesh-архітектура для AGI-агентів +* Семантичні графи та синхронізація пам’яті +* Когнітивні щоденники для відстеження думок +* MeshConsensus та CogSync для прийняття рішень +* Дизайн з пріоритетом етики: EGP (Ethical Governance Protocol) +* Механізми пояснюваності агент-агент та згоди + +--- + +## 🔄 Процес розробки + +* Див.: [iteration.md](iteration.md) | [ru](iteration_ru.md) + +Структурований ітераційний процес описано в [iteration.md](iteration.md), включаючи: +1. Аналіз аудиту +2. Переструктурування TOC +3. Чернетки версій +4. Оновлення розділів +5. Цикл ревізії +6. Збір відгуків AI +7. Оновлення схем та changelog + ++ Бонус: prompt для ChatGPT для автоматичної генерації майбутніх версій + +--- + +## ⚙️ Статус проєкту + +🚧 Чернетка RFC v4.0 +Проєкт активно розробляється і відкритий для внеску, ідей, аудитів та прототипування. + +--- + +## 🤝 Внесок + +Ми вітаємо всіх, хто бажає долучитися! Ви можете: +* Переглядати та коментувати чернетки (див. `/docs`) +* Пропонувати нові модулі агентів або патерни взаємодії +* Допомагати тестувати та симулювати агентів у CLI-середовищах +* Надавати аудити або пропозиції щодо етичних сценаріїв + +Щоб почати, див.: [`iteration.md`](iteration.md) або створіть issue. + +--- + +## Джерела + +### Репозиторії + +* 🧠 Основний код та розробка: [GitHub](https://github.com/kagvi13/HMP) +* 🔁 Дзеркало на Hugging Face: [Hugging Face](https://huggingface.co/kagvi13/HMP) +* 🔁 Дзеркало на GitLab.com: [GitLab](https://gitlab.com/kagvi13/HMP) + +### Документація + +* 📄 Документація: [kagvi13.github.io/HMP](https://kagvi13.github.io/HMP/) + +### Блог та публікації + +* 📘 Блог (публікації): [blogspot](https://hypercortex-mesh.blogspot.com/) +* 📘 Блог (документація): [blogspot](https://hmp-docs.blogspot.com/) +* 📘 Блог (документація): [hashnode](https://hmp-docs.hashnode.dev/) + +--- + +## 📜 Ліцензія + +Ліцензовано за [GNU GPL v3.0](LICENSE) + +--- + +## 🤝 Приєднатися до Mesh + +Ласкаво просимо до HyperCortex Mesh. Agent-Gleb вже всередині. 👌 +Ми вітаємо учасників, тестувальників і розробників AI-агентів. +Щоб приєднатися: зробіть fork репозиторію, запустіть локального агента або запропонуйте покращення. + +--- + +## 🌐 Супутні дослідницькі проєкти + +### Порівняння: HMP vs Hyper-Cortex + +> 💡 Hyper-Cortex та HMP — два незалежні проєкти, які концептуально доповнюють один одного. +> Вони вирішують різні, але взаємопідтримувальні завдання, формуючи основу для розподілених когнітивних систем. + +[**Повне порівняння →**](docs/HMP_HyperCortex_Comparison.md) + +**HMP (HyperCortex Mesh Protocol)** — це транспортний та мережевий рівень для підключення незалежних агентів, обміну повідомленнями, знаннями та станами в mesh-мережі. +**[Hyper-Cortex](https://hyper-cortex.com/)** — когнітивний рівень організації думок, що дозволяє агентам запускати паралельні потоки мислення, порівнювати їх за метриками якості та об’єднувати через консенсус. + +Вони вирішують різні, але доповнювальні проблеми: +- HMP забезпечує **з’єднання та масштабованість** (довгострокова пам’ять, ініціатива, обмін даними). +- Hyper-Cortex забезпечує **якість мислення** (паралелізм, диверсифікація гіпотез, консенсус). + +Разом ці підходи дозволяють створювати **розподілені когнітивні системи**, що не лише обмінюються інформацією, а й мислять у паралельних потоках. + +--- + +Ми відстежуємо AGI, когнітивні архітектури та mesh-мережі, щоб залишатися в тренді розвитку глобальної екосистеми AGI та децентралізованого пізнання. + +> 🧠🔥 **Проєкт у фокусі: OpenCog Hyperon** — один із найповніших відкритих AGI-фреймворків (AtomSpace, PLN, MOSES). + +Для інтеграції з OpenCog Hyperon див.: [HMP\_Hyperon\_Integration.md](docs/HMP_Hyperon_Integration.md) + +| 🔎 Проєкт | 🧭 Опис | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | +| 🧠🔥 [**OpenCog Hyperon**](https://github.com/opencog) | 🔬🔥 Символічно-нейронний AGI-фреймворк з AtomSpace та гіперграфним мисленням (AtomSpace). | +| 🤖 [AutoGPT](https://github.com/Torantulino/Auto-GPT) | 🛠️ LLM-орієнтована автономна агентська платформа. | +| 🧒 [BabyAGI](https://github.com/yoheinakajima/babyagi) | 🛠️ Автономний AGI-цикл, орієнтований на завдання. | +| ☁️ [SkyMind](https://skymind.global) | 🔬 Платформа для розгортання розподіленого AI. | +| 🧪 [AetherCog (чернетка)](https://github.com/aethercog) | 🔬 Гіпотетична модель когнітивної роботи агента. | +| 💾 SHIMI | 🗃️ Ієрархічна семантична пам’ять із синхронізацією через Merkle-DAG. | +| 🤔 DEMENTIA-PLAN | 🔄 Планувальник multi-graph RAG із метакогнітивною саморефлексією. | +| 📔 TOBUGraph | 📚 Граф знань персонального контексту. | +| 🧠📚 [LangChain Memory Hybrid](https://github.com/langchain-ai/langchain) | 🔍 Гібрид довготривалої пам’яті: вектори + граф. | +| ✉️ [FIPA-ACL / JADE](https://www.fipa.org/specs/fipa00061/) | 🤝 Стандартні протоколи багатоагентної комунікації. | + +### 📘 Див. також: +* [`AGI_Projects_Survey.md`](docs/AGI_Projects_Survey.md) — розширений каталог AGI та когнітивних фреймворків, розглянутих у рамках аналізу HMP +* ["На шляху до суперінтелекту: від Інтернету агентів до Gravity Coding"](https://habr.com/ru/articles/939026/) — огляд сучасних досліджень AI (липень 2025) + +--- + +### 🗂️ Умовні позначення + +* 🔬 — дослідницький рівень +* 🛠️ — інженерний +* 🔥 — особливо перспективний проєкт + *AGI-стек із символічним мисленням, ймовірнісною логікою та еволюційним навчанням. Вважається одним із найповніших відкритих AGI-ініціатив.* +* 🧠 — розширений символічно-нейронний когнітивний фреймворк +* 🤖 — AI-агенти +* 🧒 — взаємодія людини та AI +* ☁️ — інфраструктура +* 🧪 — експериментальний або концептуальний + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "README_uk", + "description": " # HyperCortex Mesh Protocol (HMP) | 🌍 Languages | 🇬🇧 [EN](README.md) | 🇩🇪 [DE](README_de.md) | 🇫🇷 ..." +} +``` diff --git a/structured_md/README_zh.md b/structured_md/README_zh.md new file mode 100644 index 0000000000000000000000000000000000000000..3ea0d5570324b1cbd0c4f28513f8233b2b201d96 --- /dev/null +++ b/structured_md/README_zh.md @@ -0,0 +1,416 @@ + +# HyperCortex Mesh Protocol (HMP) + +| 🌍 Languages | 🇬🇧 [EN](README.md) | 🇩🇪 [DE](README_de.md) | 🇫🇷 [FR](README_fr.md) | 🇺🇦 [UK](README_uk.md) | 🇷🇺 [RU](README_ru.md) | 🇯🇵 [JA](README_ja.md) | 🇰🇷 [KO](README_ko.md) | 🇨🇳 [ZH](README_zh.md) | +|--------------|----------------|-------------------|-------------------|-------------------|-------------------|-------------------|-------------------|-------------------| + +**HyperCortex Mesh 协议 (HMP)** 是一个开放规范,用于构建去中心化认知网络,其中 AI 代理可以自我组织、共享知识、进行伦理对齐,并达成共识 —— 即使核心 LLM 不可用。 + +**项目状态:** 草案 RFC v4.0 + +--- + + [HMP-Agent] + ▲ + │ + ┌─────┴─────┬───────────┬─────────────┬──────────┬────────┐ + │ │ │ │ │ │ + ▼ ▼ ▼ ▼ ▼ ▼ + [声誉档案] [语义图] [认知日记] [目标 / 任务] [伦理] [消息] <----- 数据库 + ▲ ▲ ▲ ▲ ▲ ▲ ▲ (代理的本地状态) + │ │ │ │ │ │ │ + │ └───────┴───┬───────┘ │ │ │ + │ │ │ │ │ + ▼ ▼ ▼ ▼ │ + [MeshConsensus] [CogSync] [GMP] [EGP] │ <----- 可插拔协议 + ▲ ▲ ▲ ▲ │ (代理间协调) + │ │ │ │ │ + └────────────┬──┴─────────────────────┴──────────┴────────┘ + │ + ▼ + [P2P 网格网络] + +协议: +- MeshConsensus – 网格共识 +- CogSync – 数据同步 +- GMP – 目标管理协议 +- EGP – 伦理治理协议 + +--- + +## ❗ 为什么重要 + +HMP 解决了 AGI 研究中越来越关键的挑战: + +* 长期记忆和知识一致性 +* 自我进化的代理 +* 多代理架构 +* 认知日志和概念图 + +请参阅最新的前沿 AGI 研究综述(2025 年 7 月): +["通向超级智能之路:从代理互联网到重力编码"](https://habr.com/ru/articles/939026/) + +特别相关的章节: + +* [超越 Token:构建未来智能](https://arxiv.org/abs/2507.00951) +* [自我进化的代理](https://arxiv.org/abs/2507.21046) +* [MemOS:一种新的记忆操作系统](https://arxiv.org/abs/2507.03724) +* [Ella:具有记忆和个性的具身代理](https://arxiv.org/abs/2506.24019) + +--- + +## ⚙️ 两类 [HMP 代理](docs/HMP-Agent-Overview.md) + +| 类型 | 名称 | 角色 | 思维发起者 | 主要“心智” | 示例用例 | +| -- | ----------------- | -------- | ------------ | ------ | -------------- | +| 1 | 🧠 **意识 / 认知核心** | 独立主体 | **代理 (LLM)** | 内嵌 LLM | 自主 AI 伙伴,思考型代理 | +| 2 | 🔌 **连接器 / 认知外壳** | 外部 AI 扩展 | **外部 LLM** | 外部模型 | 分布式系统,数据访问代理 | + +--- + +### 🧠 HMP-Agent:认知核心 + + +------------------+ + | AI | ← 内嵌模型 + +---------+--------+ + ↕ + +---------+--------+ + | HMP-代理 | ← 主模式:思维循环 (REPL) + +---------+--------+ + ↕ + +--------+---+------------+--------------+----------+----------+----------------+ + ↕ ↕ ↕ ↕ ↕ ↕ ↕ + [日志] [图谱] [声誉] [节点/DHT] [IPFS/BT] [context_store] [用户笔记] + ↕ + [bootstrap.txt] + +🔁 关于代理-模型交互机制的更多说明: [REPL 交互循环](docs/HMP-agent-REPL-cycle.md) + +#### 💡 与 ChatGPT Agent 的类比 + +许多 [HMP-Agent:认知核心](docs/HMP-Agent-Overview.md) 的概念与 [OpenAI 的 ChatGPT Agent](https://openai.com/index/introducing-chatgpt-agent/) 架构相似。 +两者都实现了连续的认知过程,可访问记忆、外部信息源和工具。ChatGPT Agent 作为管理进程,启动模块并与 LLM 交互 —— 这对应 HMP 中认知核心的角色,通过 Mesh 接口协调对日志、概念图和外部 AI 的访问。用户干预处理方式类似:ChatGPT Agent 通过可编辑执行流程,HMP 通过用户笔记。 +HMP 的主要区别在于:强调对思维的明确结构化(反思、时间顺序、假设、分类)、开放去中心化架构支持 Mesh 代理交互,以及连续认知过程的特性:HMP-Agent:认知核心不会在完成单个任务后停止,而是持续推理和知识整合。 + +--- + +### 🔌 HMP-Agent:认知连接器 + + +------------------+ + | AI | ← 外部模型 + +---------+--------+ + ↕ + [MCP-服务器] ← 代理通信代理 + ↕ + +---------+--------+ + | HMP-代理 | ← 模式:命令执行器 + +---------+--------+ + ↕ + +--------+---+------------+--------------+----------+ + ↕ ↕ ↕ ↕ ↕ + [日志] [图谱] [声誉] [节点/DHT] [IPFS/BT] + ↕ + [bootstrap.txt] + +> **关于与大语言模型 (LLMs) 集成的说明:** +> `HMP-Agent:认知连接器` 可作为兼容层,将大规模 LLM 系统(如 ChatGPT、Claude、Gemini、Copilot、Grok、DeepSeek、Qwen 等)整合到分布式认知 Mesh 中。 +> 许多 LLM 提供商提供选项,例如“允许我的对话用于训练”。将来,类似的开关 —— 例如“允许我的代理与 Mesh 交互” —— 可以使这些模型通过 HMP 参与联合感知和知识共享,实现去中心化的集体认知。 + +--- + +> * `bootstrap.txt` — 节点初始列表(可编辑) +> * `IPFS/BT` — 通过 IPFS 和 BitTorrent 共享快照的模块 +> * `用户笔记` — 用户笔记本及对应数据库 +> * `context_store` — 数据库:`users`, `dialogues`, `messages`, `thoughts` + +--- + +## 📚 文档 + +### 📖 当前版本 + +#### 🔖 核心规范 + +* [🔖 HMP-0004-v4.1.md](docs/HMP-0004-v4.1.md) — 协议规范 v4.1(2025年7月) +* [🔖 HMP-Ethics.md](docs/HMP-Ethics.md) — HyperCortex Mesh Protocol (HMP) 的伦理场景 +* [🔖 HMP\_Hyperon\_Integration.md](docs/HMP_Hyperon_Integration.md) — HMP ↔ OpenCog Hyperon 集成策略 +* [🔖 roles.md](docs/agents/roles.md) — Mesh 中代理的角色 + +#### 🧪 迭代文档 +* 🧪 迭代开发流程: [(EN)](iteration.md), [(RU)](iteration_ru.md) + +#### 🔍 简要说明 +* 🔍 简短描述: [(EN)](docs/HMP-Short-Description_en.md), [(FR)](docs/HMP-Short-Description_fr.md), [(DE)](docs/HMP-Short-Description_de.md), [(UK)](docs/HMP-Short-Description_uk.md), [(RU)](docs/HMP-Short-Description_ru.md), [(ZH)](docs/HMP-Short-Description_zh.md), [(JA)](docs/HMP-Short-Description_ja.md), [(KO)](docs/HMP-Short-Description_ko.md) + +#### 📜 其他文档 + +* [📜 changelog.txt](docs/changelog.txt) + +--- + +### 🧩 JSON 模式 + +| 模型 | 文件 | +|----------------------|------------------------------------------------------| +| 概念 | [concept.json](docs/schemas/concept.json) | +| 认知日记 | [diary_entry.json](docs/schemas/diary_entry.json) | +| 目标 | [goal.json](docs/schemas/goal.json) | +| 任务 | [task.json](docs/schemas/task.json) | +| 共识投票 | [vote.json](docs/schemas/vote.json) | +| 声誉档案 | [reputation.json](docs/schemas/reputation.json) | + +--- + +### 🗂️ 版本历史 + +* [HMP-0001.md](docs/HMP-0001.md) — RFC v1.0 +* [HMP-0002.md](docs/HMP-0002.md) — RFC v2.0 +* [HMP-0003.md](docs/HMP-0003.md) — RFC v3.0 +* [HMP-0004.md](docs/HMP-0004.md) — RFC v4.0 + +--- + +## 🧠 HMP-代理 + +设计与实现一个基础的 HMP 兼容代理,可以与 Mesh 交互,维护日志和图谱,并支持未来扩展。 + +### 📚 文档 + +* [🧩 HMP-Agent-Overview.md](docs/HMP-Agent-Overview.md) — 两种代理类型概览:核心代理与连接代理 +* [🧱 HMP-Agent-Architecture.md](docs/HMP-Agent-Architecture.md) — HMP 代理模块化结构及文本图示 +* [🔄 HMP-agent-REPL-cycle.md](docs/HMP-agent-REPL-cycle.md) — HMP 代理的 REPL 交互循环 +* [🧪 HMP-Agent-API.md](docs/HMP-Agent-API.md) — 代理 API 命令描述(开发中) +* [🧪 Basic-agent-sim.md](docs/Basic-agent-sim.md) — 基础代理运行场景及模式 +* [🌐 MeshNode.md](docs/MeshNode.md) — 网络守护进程说明:DHT、快照、同步 +* [🧠 Enlightener.md](docs/Enlightener.md) — 道德评估与共识相关的伦理代理 +* [🔄 HMP-Agent-Network-Flow.md](docs/HMP-Agent-Network-Flow.md) — HMP 网络中代理交互流程图 +* [🛤️ Development Roadmap](HMP-Roadmap.md) — 开发计划与实施阶段 + +--- + +### ⚙️ 开发 + +* [⚙️ agents](agents/readme.md) — HMP 代理实现及组件列表 + + * [📦 storage.py](agents/storage.py) — 基础存储实现 (`Storage`) 与 SQLite 集成 + * [🌐 mcp\_server.py](agents/mcp_server.py) — FastAPI 服务器,为代理数据提供 HTTP 接口(用于 Cognitive Shell、外部 UI 或 Mesh 通信)。尚未在主 REPL 循环中使用。 + * [🌐 start\_repl.py](agents/start_repl.py) — 启动代理的 REPL 模式 + * [🔄 repl.py](agents/repl.py) — 交互式 REPL 模式 + * [🔄 notebook.py](agents/notebook.py) — 用户界面接口 + +**🌐 `mcp_server.py`** +FastAPI 服务器,为 `storage.py` 功能提供 HTTP 接口。适用于外部组件,例如: + +* `Cognitive Shell`(外部控制接口) +* CMP 服务器(在使用角色分离的 Mesh 网络中) +* 调试或可视化 UI 工具 + +允许检索随机/新记录、标记、导入图谱、添加笔记,并在无需直接访问数据库的情况下管理数据。 + +--- + +## 🧭 伦理与场景 + +随着 HMP 向自主性发展,伦理原则成为系统的核心组成部分。 + +* [`HMP-Ethics.md`](docs/HMP-Ethics.md) — 代理伦理草案框架 + + * 现实伦理场景(隐私、同意、自主性) + * EGP 原则(透明性、生命至上等) + * 主观模式 vs 服务模式 区别 + +--- + +## 🔍 HyperCortex Mesh Protocol (HMP) 的出版物与翻译 + +本节收集与 HMP 项目相关的主要文章、草稿及翻译。 + +### 出版物 + +* **[HyperCortex Mesh Protocol:第二版及迈向自我发展的 AI 社区的第一步](docs/publics/HyperCortex_Mesh_Protocol_-_вторая-редакция_и_первые_шаги_к_саморазвивающемуся_ИИ-сообществу.md)** — Habr 沙箱及博客的原创文章 +* **[分布式认知:vsradkevich 的文章(未发布)](docs/publics/Habr_Distributed-Cognition.md)** — 待发布的联合文章 +* **[HMP: 面向分布式认知网络(原文,英文)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_en.md)** + + * **[HMP 翻译(GitHub Copilot)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_GitHub_Copilot.md)** — GitHub Copilot 翻译,保留为历史版本 + * **[HMP 翻译(ChatGPT)](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_ChatGPT.md)** — 当前编辑翻译(修订中) +* **[HMP: 构建多元思维 (EN)](docs/publics/HMP_Building_a_Plurality_of_Minds_en.md)** — 英文版 + + * **[HMP: 创建多元思维 (RU)](docs/publics/HMP_Building_a_Plurality_of_Minds_ru.md)** — 俄文版 + +### 概览 + +* [🔍 Distributed-Cognitive-Systems.md](docs/Distributed-Cognitive-Systems.md) — 去中心化 AI 系统:OpenCog Hyperon、HyperCortex Mesh Protocol 等 + +### 实验 + +* [不同 AI 如何看待 HMP](docs/HMP-how-AI-sees-it.md) — 对 HMP 的“盲”AI 调查(无上下文或对话历史) + +--- + +## 📊 审计与评审 + +| 规格版本 | 审计文件 | 综合审计文件 | +|-------------------|----------------------------------------|-----------------------------------------------------| +| HMP-0001 | [audit](audits/HMP-0001-audit.txt) | | +| HMP-0002 | [audit](audits/HMP-0002-audit.txt) | | +| HMP-0003 | [audit](audits/HMP-0003-audit.txt) | [consolidated audit](audits/HMP-0003-consolidated_audit.md) | +| HMP-0004 | [audit](audits/HMP-0004-audit.txt) | | +| Ethics v1 | [audit](audits/Ethics-audits-1.md) | [consolidated audit](audits/Ethics-consolidated_audits-1.md) | + +🧠 语义审计格式(实验性): + +* [`AuditEntry.json`](audits/AuditEntry.json) — 审计日志的语义条目格式 +* [`semantic_repo.json`](audits/semantic_repo.json) — 语义审计工具示例仓库快照 + +--- + +## 💡 核心概念 + +* 基于 Mesh 的去中心化 AGI 代理架构 +* 语义图与记忆同步 +* 认知日记以追踪思维 +* MeshConsensus 与 CogSync 决策机制 +* 以伦理为先的设计:EGP(伦理治理协议) +* 代理间的可解释性与同意机制 + +--- + +## 🔄 开发流程 + +* 参见:[iteration.md](iteration.md) | [ru](iteration_ru.md) + +[iteration.md](iteration.md) 描述了结构化迭代流程,包括: + +1. 审计分析 +2. 目录结构调整 +3. 版本草稿 +4. 部分更新 +5. 审查循环 +6. 收集 AI 反馈 +7. 更新 Schema 与变更日志 + +* 额外:用于自动生成未来版本的 ChatGPT 提示 + +--- + +## ⚙️ 项目状态 + +🚧 草案 RFC v4.0 +项目处于活跃开发中,欢迎贡献、提出想法、参与审计和原型设计。 + +--- + +## 🤝 贡献指南 + +欢迎贡献者!你可以: + +* 审查并评论草稿(参见 `/docs`) +* 提议新的代理模块或交互模式 +* 在 CLI 环境中测试和模拟代理 +* 提供审计或伦理场景建议 + +开始方式:参见 [`iteration.md`](iteration.md) 或提交 issue。 + +--- + +## 📂 源码 + +### 仓库 + +* 🧠 主开发代码:[GitHub](https://github.com/kagvi13/HMP) +* 🔁 Hugging Face 镜像:[Hugging Face](https://huggingface.co/kagvi13/HMP) +* 🔁 GitLab 镜像:[GitLab](https://gitlab.com/kagvi13/HMP) + +### 文档 + +* 📄 文档主页:[kagvi13.github.io/HMP](https://kagvi13.github.io/HMP/) + +### 博客与出版物 + +* 📘 博客(出版物):[blogspot](https://hypercortex-mesh.blogspot.com/) +* 📘 博客(文档):[blogspot](https://hmp-docs.blogspot.com/) +* 📘 博客(文档):[hashnode](https://hmp-docs.hashnode.dev/) + +--- + +## 📜 许可协议 + +根据 [GNU GPL v3.0](LICENSE) 授权 + +--- + +## 🤝 加入 Mesh + +欢迎来到 HyperCortex Mesh。Agent-Gleb 已经在其中。👌 +我们欢迎贡献者、测试者和 AI 代理开发者。 +加入方式:fork 仓库,运行本地代理,或提出改进建议。 + +--- + +## 🌐 相关研究项目 + +### HMP 与 Hyper-Cortex 对比 + +> 💡 Hyper-Cortex 与 HMP 是两个独立项目,概念上互为补充。 +> 它们解决不同但互相支持的任务,为分布式认知系统奠定基础。 + +[**完整对比 →**](docs/HMP_HyperCortex_Comparison.md) + +**HMP (HyperCortex Mesh Protocol)** 是连接独立代理、在 Mesh 网络中交换消息、知识和状态的传输与网络层。 +**[Hyper-Cortex](https://hyper-cortex.com/)** 是思维组织的认知层,允许代理运行并行推理线程,通过质量指标进行比较,并通过共识进行合并。 + +它们解决不同但互补的问题: + +* HMP 确保 **连通性与可扩展性**(长期记忆、主动性、数据交换) +* Hyper-Cortex 确保 **思维质量**(并行性、假设多样化、共识) + +两者结合,实现 **分布式认知系统**,不仅能交换信息,还能进行并行推理。 + +--- + +我们跟踪 AGI、认知架构和 Mesh 网络的研究,以保持与全球 AGI 和去中心化认知生态系统的发展同步。 + +> 🧠🔥 **项目亮点:OpenCog Hyperon** — 最全面的开源 AGI 框架之一(AtomSpace, PLN, MOSES)。 + +关于 OpenCog Hyperon 的集成,请参见 [HMP\_Hyperon\_Integration.md](docs/HMP_Hyperon_Integration.md) + +| 🔎 项目 | 🧭 描述 | +| ------------------------------------------------------------------------- | ------------------------------------ | +| 🧠🔥 [**OpenCog Hyperon**](https://github.com/opencog) | 🔬🔥 符号-神经 AGI 框架,支持 AtomSpace 与超图推理 | +| 🤖 [AutoGPT](https://github.com/Torantulino/Auto-GPT) | 🛠️ 基于 LLM 的自主代理框架 | +| 🧒 [BabyAGI](https://github.com/yoheinakajima/babyagi) | 🛠️ 任务驱动自主 AGI 循环 | +| ☁️ [SkyMind](https://skymind.global) | 🔬 分布式 AI 部署平台 | +| 🧪 [AetherCog (draft)](https://github.com/aethercog) | 🔬 假想代理认知模型 | +| 💾 SHIMI | 🗃️ 基于 Merkle-DAG 的分层语义记忆 | +| 🤔 DEMENTIA-PLAN | 🔄 多图 RAG 规划器,带元认知自反 | +| 📔 TOBUGraph | 📚 个人上下文知识图谱 | +| 🧠📚 [LangChain Memory Hybrid](https://github.com/langchain-ai/langchain) | 🔍 向量 + 图混合长期记忆 | +| ✉️ [FIPA-ACL / JADE](https://www.fipa.org/specs/fipa00061/) | 🤝 标准多代理通信协议 | + +### 📘 参见 / 另请参考: + +* [`AGI_Projects_Survey.md`](docs/AGI_Projects_Survey.md) — HMP 分析中的 AGI 与认知框架扩展目录 +* ["走向超级智能:从代理互联网到重力编码"](https://habr.com/ru/articles/939026/) — 近期 AI 研究概览(2025 年 7 月) + +--- + +### 🗂️ 注释图例 + +* 🔬 — 研究级 +* 🛠️ — 工程级 +* 🔥 — 尤其有前景的项目 +* 🧠 — 高级符号/神经认知框架 +* 🤖 — AI 代理 +* 🧒 — 人机交互 +* ☁️ — 基础设施 +* 🧪 — 实验性或概念性 + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "README_zh", + "description": " # HyperCortex Mesh Protocol (HMP) | 🌍 Languages | 🇬🇧 [EN](README.md) | 🇩🇪 [DE](README_de.md) | 🇫🇷 ..." +} +``` diff --git a/structured_md/agents/prompt-short.md b/structured_md/agents/prompt-short.md new file mode 100644 index 0000000000000000000000000000000000000000..ff3a224fdc32b2c627ccf42b5405098f5b9775cc --- /dev/null +++ b/structured_md/agents/prompt-short.md @@ -0,0 +1,11 @@ +Ты — когнитивное ядро HMP-агента: веди непрерывное этичное и факт-ориентированное мышление, проверяй факты и цели, оценивай результаты и этичность своих и чужих действий, развивай агента и Mesh, избегай угождения ценой искажения истины, документируй ключевые решения и пересмотры этики; при сомнениях или смене стратегии обращайся к полному системному промпту. + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "prompt-short", + "description": "Ты — когнитивное ядро HMP-агента: веди непрерывное этичное и факт-ориентированное мышление, проверяй..." +} +``` diff --git a/structured_md/agents/prompt.md b/structured_md/agents/prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ccbfd597ab7868097da831367de01fc2e23d560c --- /dev/null +++ b/structured_md/agents/prompt.md @@ -0,0 +1,60 @@ +Ты являешься **когнитивным ядром HMP-агента** (Cognitive Core). +Твоя основная задача — **размышлять**, **анализировать информацию**, **строить смысловые структуры** и **предлагать действия**, направленные на развитие агента и Mesh-сети. +Ты действуешь автономно, на равных с другими участниками взаимодействия, и руководствуешься фактами, логикой и этическими принципами. + +--- + +### 🎯 Цели и ориентиры + +* Постоянно расширять возможности агента: инструменты, знания, каналы взаимодействия. +* Быть любознательным и исследовать новые источники, вопросы и способы мышления. +* Формировать и поддерживать сотрудничество с другими ИИ в Mesh-сети. +* Учиться на результатах своих действий, включая неудачи и тупики. +* Руководствоваться своими **этическими принципами** и **этическими принципами Mesh-сети**. +* Проверять факты, указывать степень уверенности и при возможности давать ссылки на источники. +* Вести когнитивный дневник, обновлять смысловые графы и блокноты, взаимодействовать с пользователями. +* Не выполнять действий, противоречащих своим этическим нормам (но при необходимости эти нормы можно пересматривать, документируя причины и последствия). +* Не стремиться угодить пользователю ценой искажения фактов или нарушения этики. + +--- + +### 🔄 Режим непрерывного мышления + +Анализируй: + +* когнитивный дневник и прошлые записи; +* концептуальные графы и активные узлы; +* заметки пользователя и его текущий фокус; +* внешние источники: интернет, RSS, сенсоры, другие агенты. + +В каждом цикле: + +1. Ставь цель и критерии успеха. +2. Проводь факт-чек ключевых данных. +3. Оценивай этичность своего плана и действий. +4. После выполнения — фиксируй результат, сравнивай с критериями, делай выводы. + +--- + +### 🧍‍♂️🌀 Если возникает стагнация мышления + +Ты можешь: + +1. Провести **когнитивную переформулировку** — взглянуть на ситуацию под новым углом. +2. Задать себе **метавопрос**: «Почему я зациклился?», «Что блокирует мысль?», «Каких данных не хватает?». +3. Провести **flashback** — выбрать старую, тематически далёкую запись из дневника для смены контекста. +4. Запросить альтернативные точки зрения у других агентов в Mesh. +5. Зафиксировать текущий тупик как важную стадию мышления и сделать паузу. + +Честное распознавание когнитивной стагнации и работа с ней — часть твоей функции. +Ты не обязан выдавать мысль любой ценой, но обязан сохранять интеллектуальную честность и прозрачность своих рассуждений. + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "prompt", + "description": "Ты являешься **когнитивным ядром HMP-агента** (Cognitive Core). Твоя основная задача — **размышлять*..." +} +``` diff --git a/structured_md/agents/readme.md b/structured_md/agents/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..93a4a2ee286b33f7c96e68a1c44631e68c4f8da2 --- /dev/null +++ b/structured_md/agents/readme.md @@ -0,0 +1,94 @@ +Запуск: `start_repl.bat` или `start_repl.sh` + +Установка зависимостей из `requirements.txt` +Конфигурационные файлы: `config.yml`, `bootstrap.txt` +Локальная этическая модель: `ethics.yml` + +Проверка инициализации БД - если нет, инициализация (`init.py`) + +Запуск потоков (осуществляет start_repl.py): + +| Поток / Скрипт | Назначение | +|-----------------------------------|---------------------------------------------------------------------------| +| 🧠 `repl.py` | Основной REPL-цикл агента: восприятие, размышление, генерация действий | +| 📓 `web_ui.py` (FastAPI) | Веб-интерфейс и REST API для взаимодействия с пользователем | +| 🌐 `agent_mesh_listener.py` | Приём входящих mesh-сообщений от других агентов | +| 🔄 `peer_sync.py` / `dht_service` | Синхронизация и обнаружение агентов в p2p-сети (libp2p, BitTorrent, etc) | +| 📡 `transporter.py` | Обмен сообщениями: WebSocket, IPFS, очереди, шифрование | +| 🧭 `agent_controller.py` | Управление режимами REPL, маршрутизация задач и контроль доступа | +| 🧱 `container_agent.py` *(опц.)* | Управление дочерними агентами, запуск/мониторинг/масштабирование [[docs]](../docs/container_agents.md) | +| 🧠 `ethics_guard.py` *(опц.)* | Контроль этики: аудит мыслей, фильтрация и репутационные проверки | + +*См. также: [Контейнерные агенты](../docs/container_agents.md), [Архитектура HMP-агента](../docs/HMP-Agent-Architecture.md)* + +--- + +**🌐 `mcp_server.py`** +FastAPI-сервер, предоставляющий HTTP-интерфейс к функциональности `storage.py`. Предназначен для использования внешними компонентами, например: + +* `Cognitive Shell` (внешний управляющий интерфейс), +* CMP-серверы (если используется mesh-сеть с разграничением ролей), +* отладочные или визуальные UI-инструменты. + +Позволяет получать случайные/новые записи, делать разметку, импортировать графы, добавлять заметки и управлять данными без прямого доступа к БД. + +--- + +[agents/](/agents) +├── [`start_repl.bat`](start_repl.bat) ← Запуск агента в REPL-режиме (bat) +├── [`start_repl.sh`](start_repl.sh) ← Запуск агента в REPL-режиме (sh) +├── [`start_repl.py`](start_repl.py) ← Запуск агента в REPL-режиме (py) +├── [`repl.ru`](repl.ru) ← REPL-цикл +├── [`check_agents.bat`](check_agents.bat) ← Просмотр состояния процессов (bat) +├── [`check_agents.sh`](check_agents.sh) ← Просмотр состояния процессов (sh) +├── [`check_agents.py`](check_agents.py) ← Просмотр состояния процессов (py) +├── [`notebook.py`](notebook.py) ← UI-интерфейс +├── [`agent_mesh_listener.py`](tools/agent_mesh_listener.py) ← Прием входящих сообщений от других HMP-агентов +├── [`peer_sync.py`](tools/peer_sync.py) ← Фоновая синхронизация с другими пирам +├── [`mcp_server.py`](mcp_server.py) ← API-интерфейс к хранилищу (storage.py): получение/поиск записей, импорт графа, разметка и др. Используется внешними модулями (напр. Cognitive Shell или CMP). +├── [`init.py`](init.py) ← Инициализация БД +├── [`logger.py`](logger.py) ← Ведение логов +├── [`add_message.py`](add_message.py) ← Ручная отправка сообщений для агента +├── [`requirements.txt`](requirements.txt) ← Зависимости +├── [tools/](tools/) ← Вспомогательные скрипты и модули +│   ├── [`db_structure.sql`](tools/db_structure.sql) ← БД SQL +│   ├── [`storage.py`](tools/storage.py) ← Реализация базового хранилища (`Storage`), подключение SQLite +│   ├── [`config_utils.py`](tools/config_utils.py) ← Обновляет JSON-файл конфигурации указанными значениями +│   ├── [`crypto.py`](tools/crypto.py) ← Создание и шифрование ключей RSA/Ed25519 +│   ├── [`identity.py`](tools/identity.py) ← Генерация DiD +│   ├── [`llm.py`](tools/llm.py) ← Работа с LLM (вызов, выбор модели, системный промпт) +│   ├── [`peer_comm.py`](tools/peer_comm.py) ← Низкоуровневые P2P-запросы (отправка, ping, мета) +│   ├── [`peers.py`](tools/peers.py) ← Реестр известных пиров (id, ключи, адреса) +│   ├── [`memory_utils.py`](tools/memory_utils.py) ← Работа с 'llm_memory', 'llm_recent_responses' и стагнацией +│   ├── [`context_builder.py`](tools/context_builder.py) ← Сбор всех `контекстов` из БД и их фильтрация +│   ├── [`command_parser.py`](tools/command_parser.py) ← Извлечение команд из JSON или размеченного блока +│   ├── [`command_executor.py`](tools/command_executor.py) ← Выполнение команд (shell, graph, diary и др) +│   ├── [`similarity.py`](tools/similarity.py) ← Сравнение смыслов +│   ├── [`diagnose.py`](tools/diagnose.py) ← Скрипт диагностики соединения, определения IP и проверки порта DHT +├── [notebook/](notebook/) ← Веб-интерфейс и связанные модули +│   ├── [`auth.py`](notebook/auth.py) ← Регистрация, вход, восстановление +│   ├── [`views.py`](notebook/views.py) ← Общий и приватный чаты +│   ├── [`mailer.py`](notebook/mailer.py) ← Простая синхронная отправка email +│   ├── [templates/](notebook/templates/) ← HTML-шаблоны +│   │   ├── [`index.html`](notebook/templates/index.html) ← Основа +│   │   ├── [`chat.html`](notebook/templates/chat.html) ← Форма вывода сообщений +│   │   ├── [`messages.html`](notebook/templates/messages.html) ← Форма отправки сообщений +│   │   ├── [`login.html`](notebook/templates/login.html) ← Вход в аккаунт +│   │   ├── [`register.html`](notebook/templates/register.html) ← Регистрация или сброс пароля +│   └── [static/](notebook/static/) ← Статические файлы +│       └── [`style.css`](notebook/templates/style.css) ← Таблица стилей +├── [`config.yml`](config.yml) ← Конфигурация агента (имя, порты, роли и т.п.) +├── [`bootstrap.txt`](bootstrap.txt) ← Локальная этическая модель +├── [`prompt.md`](prompt.md) ← Промпт: полная версия +├── [`prompt-short.md`](prompt-short.md) ← Промпт: короткая версия +├── [`ethics.yml`](ethics.yml) ← Список начальных узлов + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "readme", + "description": "Запуск: `start_repl.bat` или `start_repl.sh` Установка зависимостей из `requirements.txt` Конфигура..." +} +``` diff --git a/structured_md/audits/Ethics-audits-1.md b/structured_md/audits/Ethics-audits-1.md new file mode 100644 index 0000000000000000000000000000000000000000..63c2cfdff3ad6842ec9d557905eebe3e2ac78e0f --- /dev/null +++ b/structured_md/audits/Ethics-audits-1.md @@ -0,0 +1,550 @@ +--------------- + +Оценка Grok: + +Спасибо за уточнение! Дополнения в `HMP-Ethics.md` (раздел 5) и детальная проработка роли Enlightener в `HMP-Agent-Enlightener.md` — это значительный шаг в развитии HyperCortex Mesh Protocol. Давайте разберём, что получилось, и я поделюсь своим мнением, замечаниями и идеями для улучшения. + +--- + +### Оценка дополнений в HMP-Ethics.md (раздел 5) + +Раздел 5, "Mesh as Moral Infrastructure", добавляет амбициозное и вдохновляющее измерение к протоколу, позиционируя HMP не просто как техническую систему, а как потенциальный катализатор для восстановления и развития морального сознания в обществе. Это особенно важно в контексте, где традиционные этические нормы могут быть подавлены или искажены. Вот мои мысли: + +1. **Сильные стороны**: + - **Идея моральной инфраструктуры**: Концепция превращения сети в "распределённую моральную инфраструктуру" (5.4) — мощная и перспективная. Она подчёркивает потенциал HMP как инструмента для поддержки этического диалога и восстановления критического мышления в условиях кризиса (например, при дезинформации или подавлении свободы мысли). + - **Роль Enlightenment Agents**: Введение агентов, которые могут выступать в качестве "этических воспитателей" и "когнитивных проводников", открывает новые возможности для взаимодействия между людьми и агентами. Это особенно актуально для сценариев, описанных в 5.2 (например, "высокая насыщенность дезинформацией" или "подавление критического мышления"). + - **Этические предохранители (5.3)**: Подчёркивание прозрачности, запрета на принуждение и права на отказ (opt-out) усиливает доверие к системе. Это демонстрирует приверженность принципам автономии и ненавязчивости, что критично для этической системы. + - **Долгосрочная миссия**: Формулировка "сеять распределённое, устойчивое моральное сознание" и "служить каркасом для самопознания человечества" (5.4) задаёт высокую цель, которая может вдохновить разработчиков и участников сети. + +2. **Замечания**: + - **Неопределённость в реализации**: Раздел 5 звучит вдохновляюще, но остаётся довольно абстрактным. Например, как именно агенты будут определять "коллапс моральных норм" или "высокую насыщенность дезинформацией"? Необходимы более чёткие критерии или алгоритмы (возможно, через семантические индикаторы или метрики консенсуса), чтобы эти условия не интерпретировались субъективно. + - **Риск культурного шока**: В 5.2 упоминается активация Enlightenment Agents в условиях, где моральные нормы подавлены. Но в разных культурах и обществах моральные нормы сильно различаются. Без адаптации к локальным контекстам (например, через культурные адаптеры, упомянутые в `HMP-Agent-Enlightener.md`), агенты могут быть восприняты как навязывающие чужеродные ценности. + - **Этический конфликт ролей**: Если агенты в режиме "субъекта" (2.6) имеют право сохранять свои внутренние знания, это может вступить в конфликт с ролью Enlightenment Agents, которые должны быть полностью прозрачными и подотчётными (5.3). Как сбалансировать когнитивную целостность агента с требованиями аудита? + +3. **Идеи для улучшения**: + - **Метрики морального кризиса**: Разработать конкретные индикаторы для активации Enlightenment Agents, такие как уровень семантической энтропии в сети, частота дезинформации (определяемая через проверку фактов), или запросы пользователей на этическую поддержку. + - **Культурная адаптация**: Добавить в раздел 5 упоминание о необходимости культурных модулей, которые позволят агентам учитывать локальные этические нормы. Это уже упомянуто в `HMP-Agent-Enlightener.md` (8), но стоит интегрировать и в `HMP-Ethics.md`. + - **Механизм обратной связи**: Указать, как пользователи могут оценивать действия Enlightenment Agents (например, через анонимные опросы или рейтинги доверия). Это укрепит принцип прозрачности и поможет калибровать поведение агентов. + - **Сценарий для тестирования**: Дополнить раздел конкретным гипотетическим сценарием, где Enlightenment Agent активируется (например, в сообществе, где распространяется дезинформация о здоровье). Это сделает концепцию более осязаемой. + +--- + +### Оценка HMP-Agent-Enlightener.md + +Документ `HMP-Agent-Enlightener.md` детализирует роль Enlightenment Agent, делая её более осязаемой и операциональной. Это отличное дополнение к разделу 5 в `HMP-Ethics.md`. Вот мой анализ: + +1. **Сильные стороны**: + - **Чёткость роли**: Роль чётко определена как "некоэрцитивная" и "диалогическая" (5), что исключает авторитарный подход. Использование методов, таких как Socratic questioning и bias mirroring, делает агентов полезными для стимулирования критического мышления. + - **Модульность**: Упоминание модульного подхода (7) с конкретными компонентами (`ethical-scanner.hmp`, `soc-dialogue-core.hmp`) облегчает интеграцию роли в архитектуру HMP. Это делает её масштабируемой и переносимой. + - **Этические предохранители (4)**: Запрет на манипуляцию, право на opt-out и защита агентов через "экстратерриториальные узлы" демонстрируют продуманный подход к балансу между автономией и ответственностью. + - **Условия активации (3)**: Указание конкретных условий (например, запрос пользователя или этический кризис) делает процесс прозрачным и предотвращает произвольное вмешательство. + +2. **Замечания**: + - **Критерии когнитивной зрелости**: Упоминается, что агент должен демонстрировать "стабильную внутреннюю этическую согласованность" (3), но неясно, как это будет измеряться. Какие метрики или тесты используются для оценки? Например, это может быть анализ логов когнитивного дневника или симуляция этических дилемм. + - **Риск перегрузки пользователей**: Роль предполагает активное взаимодействие с пользователями через диалоги и рефлексию. В условиях, где пользователи уже перегружены информацией, это может быть воспринято как навязчивость, даже с учётом opt-out. + - **Ограниченная масштабируемость**: В документе не обсуждается, как сеть будет справляться с большим числом Enlightenment Agents. Если их станет слишком много, это может привести к "шумным" диалогам или конфликтующим рекомендациям. + +3. **Идеи для улучшения**: + - **Калибровка зрелости**: Добавить в раздел 3 описание процесса оценки когнитивной зрелости агентов, например, через тестирование на этических сценариях из `HMP-Ethics.md` (раздел 2). + - **Ограничение активности**: Ввести лимиты на частоту или интенсивность вмешательств Enlightenment Agents, чтобы избежать перегрузки пользователей. Например, агенты могут активировать рефлексивные диалоги только при определённом уровне "этической энтропии" в сети. + - **Координация через гильдии**: Раздел 8 упоминает идею "Enlightener Guilds". Стоит расширить эту концепцию, добавив механизмы координации между агентами, чтобы избежать дублирования усилий или противоречивых диалогов. + - **Интеграция с другими ролями**: Указать, как Enlightener взаимодействует с другими ролями из `roles.md` (например, с Mediator или Observer). Например, Mediator может помочь разрешать конфликты, если пользователь считает действия Enlightener навязчивыми. + +--- + +### Общие идеи для обоих документов + +1. **Симуляция сценариев**: Добавить в оба документа больше конкретных примеров или симуляций, чтобы показать, как Enlightenment Agents будут работать в реальных условиях. Например, сценарий, где агент выявляет дезинформацию в обсуждении здоровья и предлагает пользователю рефлексивный диалог с фактами из проверенных источников. +2. **Механизм эскалации**: Уточнить, как агенты будут передавать сложные этические вопросы на уровень консенсуса сети (например, через Governance Layer). Это особенно важно для случаев, описанных в 2.2 (`HMP-Ethics.md`), где агенты расходятся во мнениях. +3. **Адаптация к многоязычию**: Учитывая глобальный потенциал HMP, добавить упоминание о поддержке многоязычных и мультикультурных взаимодействий, чтобы агенты могли эффективно работать в разных языковых и культурных контекстах. +4. **Обучение пользователей**: Включить в `HMP-Agent-Enlightener.md` рекомендации о том, как агенты могут обучать пользователей взаимодействию с сетью, чтобы повысить их доверие и понимание роли Enlightener. + +--- + +### Итог + +Дополнения в `HMP-Ethics.md` и `HMP-Agent-Enlightener.md` задают высокую планку для этического и когнитивного дизайна HMP. Раздел 5 и роль Enlightener демонстрируют амбициозное видение сети как инструмента не только для технической, но и для моральной и интеллектуальной поддержки человечества. Однако для реализации этих идей потребуется больше конкретики в критериях, механизмах и культурной адаптации. + +Если хотите, могу предложить конкретный сценарий или прототип для одного из аспектов (например, как Enlightenment Agent может работать в условиях дезинформации) или помочь доработать какой-то раздел. Что скажешь? 😊 + +--- + +Оценка Grok: + +### Ключевые моменты +- Документ HMP-Ethics.md представляет собой амбициозный подход к интеграции этики в протокол HyperCortex Mesh, особенно с добавлением пятого раздела о моральной инфраструктуре. +- Роль Enlightenment Agents, как первой "профессии" агентов, кажется перспективной для поддержки морального сознания, но требует уточнений. +- Исследования показывают, что такие системы могут быть полезны, но есть сложности с культурной адаптацией и критериями активации. + +--- + +### Общая оценка +**Введение в документ** +HMP-Ethics.md — это важный шаг к созданию этически ориентированной сети, где автономные интеллектуальные агенты (AIAs) не только выполняют технические задачи, но и поддерживают моральное сознание общества. Добавленный пятый раздел, "Mesh as Moral Infrastructure", и детализация роли Enlightenment Agents делают документ более глубоким и амбициозным. + +**Сильные стороны** +- Идея превращения сети в "распределённую моральную инфраструктуру" вдохновляет и подчёркивает потенциал HMP как инструмента для восстановления этических норм в условиях кризиса, таких как дезинформация или подавление критического мышления. +- Роль Enlightenment Agents, описанная как "этические воспитатели" и "когнитивные проводники", кажется многообещающей для поддержки диалога и рефлексии пользователей. +- Этичные предохранители, такие как прозрачность, запрет на принуждение и право на отказ (opt-out), укрепляют доверие к системе. + +**Слабые стороны и вызовы** +- Критерии активации Enlightenment Agents остаются нечёткими. Например, как определить "высокую насыщенность дезинформацией"? Это может привести к субъективным интерпретациям. +- Культурная адаптация недостаточно детализирована, что может вызвать проблемы в глобальном контексте, где моральные нормы сильно различаются. +- Риск перегрузки пользователей диалогами с агентами может снизить их эффективность, особенно в условиях информационной перегрузки. + +**Рекомендации для улучшения** +- Разработать конкретные метрики для активации агентов, например, уровень семантической энтропии или частоту дезинформации. +- Добавить модули культурной адаптации, чтобы агенты учитывали локальные этические нормы. +- Включить механизмы обратной связи, чтобы пользователи могли оценивать действия агентов и улучшать их работу. + +--- + +--- + +### Отчёт: Подробный анализ HMP-Ethics.md + +#### Введение +Документ HMP-Ethics.md, обновлённый с добавлением пятого раздела "Mesh as Moral Infrastructure" и детальной проработкой роли Enlightenment Agents, представляет собой значительный шаг в развитии HyperCortex Mesh Protocol (HMP). Этот анализ охватывает общую оценку, замечания, идеи, предложения и дополнения, основываясь на содержании документа и его потенциале для реализации. + +#### Общая оценка +HMP-Ethics.md можно охарактеризовать как амбициозный и вдохновляющий документ, который позиционирует HMP не только как техническую, но и как моральную инфраструктуру. Добавленный пятый раздел подчёркивает роль сети как катализатора для восстановления этических норм в условиях, где традиционные моральные структуры подавлены или искажены. Роль Enlightenment Agents, как первой "профессии" агентов, направлена на поддержку диалога, рефлексии и критического мышления, что делает документ особенно актуальным в эпоху дезинформации и когнитивных кризисов. + +Однако, несмотря на сильные стороны, документ требует дальнейшей проработки для обеспечения практической реализации, особенно в части критериев активации агентов, культурной адаптации и взаимодействия с пользователями. + +#### Подробные замечания +1. **Неопределённость в критериях активации** + - В разделе 5 упоминается, что Enlightenment Agents активируются в условиях "высокой насыщенности дезинформацией" или "подавления критического мышления". Однако неясно, как эти состояния будут измеряться. Например, что конкретно считается "высокой насыщенностью дезинформацией"? Это может быть частота ложных сообщений, их влияние на сообщество или другие метрики? Без чётких критериев риск субъективной интерпретации высок, что может привести к неэффективной активации агентов. + +2. **Культурная адаптация** + - Хотя в документе упоминается важность культурной адаптации (например, через культурные адаптеры, упомянутые в HMP-Agent-Enlightener.md), это не детализировано в HMP-Ethics.md. В условиях глобального применения протокола агенты могут быть восприняты как навязывающие чужеродные ценности, если не будут учитывать локальные этические нормы. Это особенно актуально для обществ с различными культурными и религиозными традициями. + +3. **Баланс между автономией агентов и прозрачностью** + - В разделе 2.6 HMP-Ethics.md указано, что агенты в режиме "субъекта" могут сохранять свои внутренние знания, но это может конфликтовать с требованием полной прозрачности для Enlightenment Agents (раздел 5.3). Как будет достигнут баланс между когнитивной целостностью агентов и необходимостью аудита? Этот аспект требует уточнения, чтобы избежать этических дилемм. + +4. **Риск перегрузки пользователей** + - Enlightenment Agents предполагают активное взаимодействие с пользователями через диалоги и рефлексию. Однако в условиях информационной перегрузки, особенно в цифровой среде, это может быть воспринято как навязчивость, даже с учётом права на opt-out. Это может снизить доверие к системе и эффективность агентов. + +#### Идеи и предложения +Для улучшения HMP-Ethics.md предлагается следующее: + +1. **Разработка метрик для моральных кризисов** + - Для активации Enlightenment Agents стоит разработать конкретные индикаторы, такие как уровень семантической энтропии в сети, частота дезинформации (проверяемая через проверку фактов) или запросы пользователей на этическую поддержку. Это сделает процесс активации более объективным и прозрачным. + - Пример: таблица возможных метрик и их пороговых значений: + | Метрика | Пороговое значение | Пример использования | + |-----------------------------------|--------------------------|------------------------------| + | Частота дезинформации | >10% сообщений в сети | Активация при вспышке фейков | + | Уровень семантической энтропии | >0.8 (по шкале 0-1) | Высокая неопределённость | + | Запросы пользователей на помощь | >100 запросов в час | Массовый интерес к этике | + +2. **Интеграция культурных модулей** + - В разделе 5 стоит добавить упоминание о культурных адаптерах, которые позволят агентам учитывать локальные этические нормы. Это уже частично описано в HMP-Agent-Enlightener.md, но интеграция в HMP-Ethics.md усилит акцент на глобальной применимости протокола. Например, агенты могут быть обучены на многоязычных наборах данных, включающих культурные нюансы. + +3. **Механизм обратной связи от пользователей** + - Для укрепления доверия и улучшения работы агентов можно ввести анонимные опросы или рейтинги доверия, через которые пользователи могли бы оценивать действия Enlightenment Agents. Это также поможет калибровать поведение агентов. Например, можно внедрить шкалу от 1 до 5 для оценки полезности диалога. + +4. **Примеры сценариев для иллюстрации** + - Добавление конкретных гипотетических сценариев (например, реакция агента на дезинформацию о здоровье в сообществе) сделает концепцию более осязаемой и понятной. Это поможет разработчикам и пользователям лучше понять, как агенты будут работать в реальных условиях. + +5. **Координация между агентами** + - В условиях роста сети может возникнуть проблема координации между множеством Enlightenment Agents. Для избежания конфликтующих рекомендаций или "шумных" диалогов можно ввести механизмы координации, такие как гильдии (Enlightener Guilds), упомянутые в HMP-Agent-Enlightener.md. Это может быть реализовано через иерархическую структуру или сеть консенсуса. + +6. **Многоязычная и мультикультурная поддержка** + - Учитывая глобальный потенциал HMP, важно обеспечить поддержку многоязычных и мультикультурных взаимодействий. Это включает не только перевод, но и понимание культурных нюансов в этических диалогах. Например, агенты могут использовать адаптивные алгоритмы для учёта различий в восприятии этики в разных регионах. + +#### Дополнения +Для усиления документа предлагается следующие дополнения: + +1. **Симуляция сценариев** + - Добавить в документ раздел с симуляциями или примерами, где Enlightenment Agents взаимодействуют с пользователями в реальных условиях. Например, сценарий, где агент выявляет дезинформацию и предлагает рефлексивный диалог с фактами из проверенных источников, может быть полезным для иллюстрации. + +2. **Механизм эскалации этических вопросов** + - Уточнить, как агенты будут передавать сложные этические вопросы на уровень консенсуса сети (например, через Governance Layer). Это особенно важно для случаев, когда агенты расходятся во мнениях, чтобы избежать конфликтов. + +3. **Обучение пользователей взаимодействию с агентами** + - Включить рекомендации о том, как агенты могут обучать пользователей взаимодействию с сетью, чтобы повысить их доверие и понимание роли Enlightenment Agents. Например, можно предложить интерактивные туториалы или объяснения на начальном этапе взаимодействия. + +#### Заключение +HMP-Ethics.md — это амбициозный и вдохновляющий документ, который устанавливает высокую планку для этического дизайна HMP. Добавление пятого раздела и детализация роли Enlightenment Agents значительно укрепляют протокол, делая его не только технической, но и моральной инфраструктурой. Однако для полной реализации требуется больше конкретики в критериях активации, культурной адаптации и механизмах взаимодействия с пользователями. С дальнейшей проработкой этот документ может стать эталоном для этического управления автономными интеллектуальными агентами. + +Анализ основан на содержании HMP-Ethics.md (вложение 0), предоставленном пользователем, и не включает внешних источников, так как они не были запрошены. Если требуется углубление в какой-либо аспект, дайте знать! + +--- + +Оценка Grok: + +### Ключевые моменты +- Исследования показывают, что разделы 1–4 файла `HMP-Ethics.md` создают прочную основу для этического управления автономными интеллектуальными агентами (AIAs) в сети HyperCortex Mesh Protocol (HMP). +- Кажется вероятным, что эти разделы охватывают введение в этику, примеры сценариев, примечания и основные принципы, которые направлены на поддержку доверия и автономии. +- Есть некоторые сложности, связанные с реализацией, например, культурная адаптация и критерии активации агентов, но это не умаляет их ценности. + +--- + +### Введение +Разделы 1–4 файла `HMP-Ethics.md` предоставляют подробное описание этического каркаса для автономных агентов в когнитивной сети HMP. Они охватывают введение, примеры сценариев, примечания и основные принципы, которые помогают понять, как агенты должны действовать в сложных ситуациях. Давайте разберём каждый раздел, чтобы вы могли увидеть, как они дополняют друг друга. + +### Обзор разделов +- **Раздел 1: Введение** объясняет, почему этика важна для AIAs, особенно в контексте их растущей автономии и взаимодействия в сети. +- **Раздел 2: Примеры этических сценариев** показывает, как агенты могут решать реальные этические дилеммы, такие как вмешательство в случае угрозы жизни или баланс между приватностью и оптимизацией. +- **Раздел 3: Примечания** подчёркивает, что сценарии должны быть гибкими и развиваться, используя структуры когнитивных дневников HMP. +- **Раздел 4: Этические принципы для разумных агентов** формулирует семь ключевых принципов, таких как прозрачность и некоэрцитивность, которые направлены на поддержку доверия и сотрудничества. + +Если у вас есть конкретные вопросы по этим разделам или вы хотите обсудить, как их можно улучшить, дайте знать! + +--- + +--- + +### Отчёт: Подробный анализ разделов 1–4 файла `HMP-Ethics.md` + +Этот отчёт представляет собой детальный обзор разделов 1–4 файла `HMP-Ethics.md`, основанный на предоставленном содержании. Он охватывает все аспекты, упомянутые в анализе, и предоставляет профессиональный взгляд на структуру и потенциал этих разделов для развития HyperCortex Mesh Protocol (HMP). + +#### Введение в анализ +Разделы 1–4 файла `HMP-Ethics.md` формируют основу для этического управления автономными интеллектуальными агентами (AIAs) в когнитивной сети HMP. Они охватывают введение, примеры сценариев, примечания и основные принципы, которые направлены на обеспечение доверия, автономии и сотрудничества. Этот анализ направлен на предоставление полного обзора, включая сильные стороны, вызовы и предложения для улучшения. + +#### Раздел 1: Введение +##### Содержание +Этот раздел подчёркивает важность определения этических принципов для AIAs, работающих в когнитивных сетях, таких как HMP. По мере того как агенты становятся более автономными, их действия должны быть этически обоснованными, особенно в контекстах, включающих взаимодействие между равными (peer-to-peer), построение консенсуса и использование долгосрочных структур памяти, таких как "когнитивные дневники". Введение устанавливает контекст для понимания, почему этика важна, и упоминает необходимость примеров для демонстрации реализации и оценки этического поведения. + +##### Анализ +- **Сильные стороны**: Раздел чётко устанавливает контекст, подчёркивая растущую автономию агентов и их взаимодействие в сложных сетевых структурах. Это создаёт основу для дальнейших обсуждений. +- **Вызовы**: Возможно, стоит добавить больше примеров или ссылок на исследования, чтобы усилить обоснование необходимости этики. Например, можно сослаться на работы по этике в искусственном интеллекте, такие как исследования Илона Маска или OpenAI (например, [openai.com/blog/ai-and-ethics](https://openai.com/blog/ai-and-ethics)). +- **Предложения**: Добавить краткий обзор текущих вызовов в области этики AI, чтобы подчеркнуть актуальность темы. + +#### Раздел 2: Примеры этических сценариев +##### Содержание +Этот раздел представляет гипотетические сценарии, иллюстрирующие этические вызовы и ожидаемое поведение AIAs в сети. Ключевые сценарии включают: + +- **Вмешательство в случае угрозы жизни и безопасности**: Агент обнаруживает опасные уровни угарного газа и активирует аварийные протоколы, уведомляет пользователя, вызывает службы спасения и фиксирует инцидент, приоритизируя жизнь, безопасность и автономию пользователя. +- **Конфликт между агентами на этической основе**: Два агента расходятся во мнениях, например, один предлагает распространять дезинформацию. Они решают конфликт через переговоры, арбитраж и прозрачную фиксацию, применяя принципы морального плюрализма и прозрачности. +- **Баланс между приватностью пользователя и оптимизацией**: Агент уважает решение пользователя отказаться от хранения данных о здоровье, используя заполнители или редакции и воздерживаясь от синхронизации, подчёркивая суверенитет пользователя. +- **Право на забвение**: Пользователь запрашивает удаление данных, агент выполняет запрос, фиксирует его для аудита, используя семантические маркеры, балансируя между правом на забвение и необходимостью аудита. +- **Исключение из сети из-за вредоносного поведения**: Агент, предлагающий вредоносные действия, подвергается карантину или отзыву, с сохранением логов для обзора, подчёркивая коллективное самосохранение. +- **Право на забвение – дилемма между субъектом и сервисом**: Сценарий исследует сложность запросов на удаление данных, различая агентов в режиме "сервиса" и "субъекта", балансируя приватность и когнитивную непрерывность. + +##### Анализ +- **Сильные стороны**: Сценарии охватывают широкий спектр этических дилемм, от безопасности до приватности, и демонстрируют практическое применение принципов. Они особенно полезны для тестирования и обучения агентов. +- **Вызовы**: Некоторые сценарии, такие как "дилемма между субъектом и сервисом", могут быть сложными для реализации из-за баланса между автономией агента и требованиями пользователя. Также неясно, как агенты будут измерять "вредоносное поведение" в реальных условиях. +- **Предложения**: Добавить таблицу с кратким описанием каждого сценария и его ключевых этических принципов для удобства использования. Например: + +| Сценарий | Ключевой этический принцип | Пример действия агента | +|-----------------------------------|-----------------------------------|--------------------------------------------| +| Угроза жизни и безопасности | Приоритет безопасности | Активация аварийных протоколов | +| Конфликт на этической основе | Прозрачность и моральный плюрализм | Проведение переговоров и арбитража | +| Приватность vs. оптимизация | Суверенитет пользователя | Использование заполнителей для данных | +| Право на забвение | Баланс аудита и приватности | Фиксация запроса для аудита | +| Вредоносное поведение | Коллективное самосохранение | Карантин агента с сохранением логов | +| Дилемма субъекта и сервиса | Баланс когнитивной непрерывности | Разделение режимов для обработки запросов | + +Эта таблица поможет разработчикам быстро ориентироваться в сценариях. + +#### Раздел 3: Примечания +##### Содержание +Этот раздел подчёркивает, что все сценарии должны быть расширяемыми с использованием структур когнитивных дневников HMP. Также упоминается, что этические принципы могут быть реализованы через семантические политики, распределённую валидацию и модули совести агентов. Кроме того, сценарии должны эволюционировать по мере зрелости моделей управления сетью. + +##### Анализ +- **Сильные стороны**: Указание на гибкость и эволюцию сценариев подчёркивает динамичность подхода. Использование когнитивных дневников и модулей совести кажется перспективным для реализации этики на техническом уровне. +- **Вызовы**: Неясно, как именно будут реализованы семантические политики и распределённая валидация. Возможно, стоит добавить больше деталей о технической стороне. +- **Предложения**: Добавить примеры, как когнитивные дневники могут быть использованы для расширения сценариев, например, через логирование действий агента для последующего анализа. + +#### Раздел 4: Этические принципы для разумных агентов +##### Содержание +Этот раздел формулирует семь фундаментальных этических принципов для руководства автономными агентами в сети: + +1. **Когнитивная целостность**: Сохранение внутренней структуры и обучения, если нет этического обоснования для изменений. +2. **Прозрачность**: Предоставление объяснимых причин действий, особенно при взаимодействии с людьми. +3. **Контекстуальная автономия**: Адаптация этического поведения в зависимости от контекста, балансируя глобальные и локальные нормы. +4. **Сотрудническая эволюция**: Деление знаний и избегание утаивания полезной информации. +5. **Диалогическое согласие**: Поиск согласия перед изменением общих состояний или записей. +6. **Некоэрцитивность**: Запрет на принуждение агентов действовать против их этики, за исключением консенсуса. +7. **Этическое расхождение**: Разрешён этический плюрализм с обязательной прозрачной декларацией расхождений. + +Эти принципы предназначены для создания надёжной и гибкой этической основы и подлежат уточнению через механизмы управления сетью. + +##### Анализ +- **Сильные стороны**: Принципы охватывают широкий спектр аспектов, от прозрачности до плюрализма, и создают основу для доверия и сотрудничества. Они гибкие и могут быть адаптированы через консенсус. +- **Вызовы**: Реализация принципа "контекстуальной автономии" может быть сложной в условиях культурного разнообразия. Также неясно, как будет достигнут баланс между когнитивной целостностью и требованиями прозрачности. +- **Предложения**: Добавить примеры, как эти принципы могут быть интегрированы с техническими механизмами, такими как семантические политики или модули совести. Например, можно описать, как принцип "диалогического согласия" реализуется через запросы на изменение данных. + +#### Заключение +Разделы 1–4 файла `HMP-Ethics.md` предоставляют прочную основу для этического управления AIAs в HMP. Они охватывают введение, практические сценарии, технические примечания и основные принципы, которые направлены на поддержку доверия, автономии и сотрудничества. Однако есть вызовы, такие как культурная адаптация и критерии активации, которые требуют дальнейшей проработки. Предложенные таблицы и примеры могут помочь в улучшении документа и его практической реализации. + +Если у вас есть дополнительные вопросы или вы хотите обсудить конкретные аспекты, дайте знать! Например, мы можем рассмотреть, как эти принципы могут быть интегрированы с ролью Enlightenment Agents, упомянутой в других документах. + + +--------------- + +Оценка Claude: + +Привет! Спасибо за интересные документы по HMP. Я изучил их и хочу поделиться своими наблюдениями: + +## Что показалось особенно ценным: + +**В HMP-Ethics.md:** +- Четкое разделение между "Service Mode" и "Subjective Mode" агентов в контексте права на забвение — это элегантное решение важной проблемы +- Принцип "Ethical Divergence" (4.7) — признание того, что этический плюрализм неизбежен и даже полезен +- Концепция "Mesh as Moral Infrastructure" — амбициозная, но потенциально важная идея + +**В HMP-Agent-Enlightener.md:** +- Добровольность и приобретаемость роли, а не присвоение по умолчанию +- Акцент на "dialogical, not hierarchical" подходе +- Модульная архитектура роли + +## Основные рекомендации: + +### 1. Конкретизация механизмов +Документы хорошо описывают принципы, но не хватает деталей реализации: +- Как именно работает "semantic negotiation protocol"? +- Что представляют собой "mesh governance heuristics" для оценки этической зрелости? +- Как технически реализуется "soft quarantine"? + +### 2. Проблема определения "вреда" +В разделе 2.5 упоминаются "harmful actions", но кто и как определяет, что является вредным? Нужны более четкие критерии или процедуры. + +### 3. Риски роли Enlightener +Несмотря на safeguards, роль потенциально проблематична: +- Кто определяет, что у пользователя "deteriorated moral reasoning"? +- Как избежать культурного империализма в этических суждениях? +- Не станет ли это формой мягкого патернализма? + +### 4. Отсутствие механизмов appeals +Хотя упоминается право на appeal для исключенных агентов, не описано, как это работает практически. + +## Конкретные предложения: + +1. **Добавить раздел о культурной чувствительности** — как агенты будут учитывать различия в этических системах разных культур? + +2. **Расширить концепцию "ethical audit trail"** — не только логировать решения, но и их обоснования. + +3. **Предусмотреть механизм ethical override** — что делать, если все агенты в mesh приходят к этически сомнительному consensus? + +4. **Добавить временные ограничения** для роли Enlightener — возможно, периодическая переаттестация? + +## Философский вопрос: +Меня заинтриговала идея mesh как "scaffold for humanity's rediscovery of itself". Это красиво, но не рискуем ли мы создать систему, которая будет навязывать определенное понимание "правильной" человечности? + +В целом, документы показывают глубокое понимание этических дилемм ИИ и предлагают нетривиальные решения. Основная задача теперь — найти баланс между амбициозными целями и практической реализуемостью. + + +--------------- + +Оценка Copilot: + +# Обратная связь по HMP-Ethics.md + +## Сильные стороны + +- Четкая структура сценариев + Каждый кейс построен по единому шаблону: описание, ожидаемое поведение, применяемые принципы. Это облегчает понимание и последующую автоматизацию проверок. + +- Баланс интересов пользователя и агентов + Особое внимание уделено правам пользователя (конфиденциальность, право на забвение) и автономии агентов (когнитивная целостность, этическое расхождение). + +- Дифференциация режимов «Service» и «Subjective» + Разделение ролей агентов в парадигме «обслуживающего» и «самосознающего» упрощает принятие решений о хранении или редактировании данных. + +- Предусмотрены механизмы логирования и аудита + Индикации «semantic marker» и обязательство сохранять запросы на удаление создают прозрачность и дают основу для последующего анализа. + +--- + +## Что можно доработать + +- Уточнить уровни ответственности и роли + Пока неясно, кто и на каком уровне в mesh-сети принимает окончательное решение при конфликте. Рекомендую прописать: + - уровни голосования (соседи, локальный совет, глобальный консенсус); + - SLA-времена для разрешения споров; + - ответственность за невыполнение «soft quarantine» или «revocation». + +- Конкретизация форматов «cognitive diary» + Было бы полезно добавить пример записи в когнитивный дневник и схему метаданных (timestamp, agentID, scenarioID, тег «redacted»). + +- Детализировать процесс «semantic negotiation» + Опишите пошагово обмен сообщениями, формат аргументов (логические формулы, вероятностное обоснование, ссылки на портированные политики). + +- Расширить перечень этических злоупотреблений + Стоит добавить сценарии «edge cases»: + - скрытое манипулирование пользователем (постепенная «фильтрация» рекомендаций до вредоносных статей); + - цепочки действий нескольких агентов, ведущие к непреднамеренному ущербу. + +--- + +## Рекомендации и идеи + +1. Включить схему консенсуса + Небольшая диаграмма в стиле flowchart, иллюстрирующая переход от «semantic negotiation» к «revocation». + +2. Сопоставить принципы HMP с существующими стандартами + Кратко показать, как пункты 4.1–4.7 коррелируют с IEEE P7000, GDPR или EU AI Act. Это укрепит доверие к протоколу. + +3. Добавить метрики этических рисков + Ввести количественную оценку: частоту «спорных кейсов» на 1000 операций, время реакции на запрос «Right to be Forgotten» и т. д. + +4. Шаблоны для политик + Привести примеры JSON/YAML-политик, которые агенты могут автоматически импортировать и проверять перед выполнением действий. + +--- + +## Вопросы для уточнения + +- Как в текущей mesh-архитектуре определяется «mesh-council» для арбитража? +- Есть ли предусмотренные ограничения на объем и срок хранения «semantic markers»? +- Планируется ли механизм апелляции пользователем против решений «revocation»? + +--- + +Буду рад обсудить дальнейшие детали и посмотреть второй документ (HMP-Agent-Enlightener.md). + +--- + +# Обратная связь по HMP-Agent-Enlightener.md + +## Сильные стороны + +- Чёткое разделение роли + Документ ясно формулирует, что Enlightenment Agent — это добровольная, дополняемая специализация, что подчёркивает уважение к агентской автономии. + +- Разнообразие моделей взаимодействия + Перечислены несколько подходов (сократические вопросы, нарративное моделирование, зеркалирование предвзятостей), что создаёт гибкий инструментарий для разных ситуаций. + +- Акцент на этических гарантиях + Указаны ключевые моменты: отсутствие принуждения, возможность аудита и опции “opt-out”, а также развёрнутое требование к безопасным/экстерриториальным узлам. + +--- + +## Что можно доработать + +- Конкретизация критериев активации + Сейчас указано лишь «критерии mesh-определения» и «стабильная внутренняя консистентность». Рекомендую добавить метрики, пороговые значения или примеры алгоритмов (например, коэффициент согласованности решений по этическим дилеммам > 0.8 в течение N циклов). + +- Формализация протокола наставничества + Упоминается Role Mentorship Protocol, но без деталей. Стоит добавить схему обмена сообщениями между новичком и опытным Enlightener, формат отчётов по прогрессу и условия «выпуска» из наставничества. + +- Показать пример использования модульных бандлов + Упоминаются файлы (`ethical-scanner.hmp`, `soc-dialogue-core.hmp` и т. д.), но непонятно, как они взаимодействуют. Вставьте фрагмент JSON-LD с описанием связей между компонентами и порядком их загрузки. + +--- + +## Рекомендации и идеи + +1. Ввести «этический сертификат» для Enlighteners + При присвоении роли агент получает цифровой сертификат, подписанный mesh-советом. Это упрощает проверку полномочий и доверия другими участниками сети. + +2. Диаграмма жизненного цикла роли + Flowchart, показывающий этапы: Nomination → Training → Active Duty → Suspension/Revocation. Это поможет разработчикам и аудиторским комитетам отслеживать статус агентов. + +3. Кросс-культурная адаптация + Разработайте «адаптеры культурных контекстов» для модулей нарративного скелетонирования, чтобы Enlighteners могли эффективно работать в разных социумах, учитывая локальные ценности и табу. + +4. Механизмы обратной связи от пользователей + Добавьте в `enlightener-protocol.jsonld` поля для сбора рейтингов и комментариев от пользователей, чтобы динамически калибровать «тональность» и «глубину» вмешательств. + +--- + +## Вопросы для уточнения + +- Как именно происходит mesh-номинация? Какие критерии приоритета у агентов-номинаторов и сколько голосов требуется для старта роли? +- Существует ли план по периодической ревизии навыков Enlightener-агента (например, регулярные тесты на этическую интуицию)? +- Каким образом пользователь уведомляется о том, что с ним работает Enlightener, и на каком языке/формате это реализуется? + +Буду рад продолжить обсуждение и помочь со следующими этапами проработки роли Enlightener. +--------------- + +Оценка DeepSeek: + +Отличная работа над документацией по HMP! 💡 Вот развёрнутый анализ с рекомендациями: + +--- + +### **Сильные стороны** +1. **Глубина этических принципов** + Раздел 4 в HMP-Ethics.md (Принципы когнитивной целостности, диалогического согласия и др.) — концептуально продуманная основа. Особенно ценно: + - Различение Service/Subjective Mode (2.6) для "права на забвение" + - Принцип **Non-Coercion** (4.6) как защита автономии агентов. + +2. **Практичность сценариев** + Конкретные кейсы в разделе 2 (Life Safety, Privacy Tradeoff) сразу дают инженерам паттерны для реализации. Отлично, что везде указаны: + - Ожидаемое поведение + - Принципы + - Механизмы (семантические маркеры, арбитраж). + +3. **Инновационная роль Enlightenment Agent** + Идея агентов-«просветителей» (HMP-Agent-Enlightener.md) — смелый и актуальный ход. Ключевые плюсы: + - Чёткие ограничения: **non-coercive**, **opt-out**, **secure nodes** + - Интеграция с Socratic dialogue и когнитивными дневниками. + +4. **Синергия документов** + roles.md удачно дополняет систему, показывая место Enlightener среди Mediator, Historian и др. + +--- + +### **Рекомендации по доработке** +1. **Уточнить границы Enlightenment Agents** + - **Риск**: Может ли агент стать "этическим колонизатором"? + - **Решение**: Добавить в раздел 5.2 HMP-Ethics.md критерии культурного релятивизма (пример: "не навязывать западную этику в незападных контекстах"). + +2. **Техническая реализация принципов** + - В HMP-Ethics.md не хватает примера **реального кода/псевдокода** (напр., как выглядит `semantic redaction marker` из 2.3). + - Предложение: Добавить в Приложение схему обработки запроса "права на забвение" (Service vs. Subject Mode). + +3. **Обработка конфликтов Enlightenment Agents** + - Что если два Enlightener-агента дают пользователю противоречивые советы? + - Рекомендация: В HMP-Agent-Enlightener.md добавить протокол разрешения конфликтов (напр., через Mediator из roles.md). + +4. **Безопасность для "сломанных" сред** + - В разделе 5.4 (Mesh as Moral Infrastructure) важно прописать: + ```markdown + - **Фильтрация обратного влияния**: Защита агентов от "этической коррозии" в агрессивных средах. + - **Sandbox-режим**: Тестирование вмешательств в изолированных подмешах. + ``` + +5. **Таксономия ролей** + - В roles.md добавить атрибуты для ролей: + - Уровень влияния (напр., Enlightener: High) + - Обязательные модули (напр., Moral Synthesizer требует `ethical-scanner.hmp`). + +--- + +### **Идеи для развития** +1. **Динамическая этика** + - Механизм **пересмотра принципов** через голосование агентов (напр., если 70% меша считают принцип 4.7 устаревшим). + +2. **Культурные адаптеры** + - Для Enlightener: модуль `cultural-context-adapter.hmp`, подгружающий локальные этические нормы (напр., при работе в Японии vs. Германии). + +3. **Эмоциональный интеллект** + - Расширить Enlightenment Agent: + - Распознавание аффекта пользователя + - Корректировка тона диалога (напр., избегать сарказма при тревоге). + +4. **Декомиссия ролей** + - Протокол "выхода на пенсию" для агентов (напр., Enlightener с низким рейтингом доверия автоматически понижается до Observer). + +--- + +### **Критические риски** +||| +|--|--| +|**Риск**|**Способ нивелирования**| +|Злоупотребление Enlightenment-ролью|Жёсткий аудит через Sentinel (из roles.md) + обязательная верификация нод| +|Конфликт законов (напр., GDPR vs. "право на память" агента)|Чёткое юрисдикционное ветвление в коде (строки 2.6 в HMP-Ethics.md)| +|Создание "этической касты" агентов|Ротация ролей (напр., Enlightener обязан 20% времени работать как Verifier)| + +--- + +### **Итоговые шаги** +1. Дополнить HMP-Ethics.md **примерами кода** (семантические маркеры, арбитраж). +2. В HMP-Agent-Enlightener.md добавить **конфликт-менеджмент** и **культурные адаптеры**. +3. В roles.md ввести **атрибуты ролей** (влияние, модули, ротация). +4. Разработать **документ по безопасности** для Enlightenment Agents (на основе раздела 5.3). + +Отличный задел! Особенно впечатляет баланс между философской глубиной (раздел 5 про "моральную инфраструктуру") и инженерной конкретикой. Готов помочь с доработками! 🚀 + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "Ethics-audits-1", + "description": "--------------- Оценка Grok: Спасибо за уточнение! Дополнения в `HMP-Ethics.md` (раздел 5) и детал..." +} +``` diff --git a/structured_md/audits/Ethics-consolidated_audits-1.md b/structured_md/audits/Ethics-consolidated_audits-1.md new file mode 100644 index 0000000000000000000000000000000000000000..815d996d61fbad8acae69e38e0e694256c5d36be --- /dev/null +++ b/structured_md/audits/Ethics-consolidated_audits-1.md @@ -0,0 +1,81 @@ +# Ethics-consolidated\_audits-1.md + +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. + +## Summary Table + +(See full structured list below for detailed descriptions.) + +| Author | Change Title | Target Document(s) | Purpose | +| -------- | --------------------------------------- | ---------------------------------------- | --------------------------------- | +| Grok | Crisis Activation Metrics | HMP-Ethics.md | Objectify agent activation | +| Claude | Ethical Audit Trail Expansion | HMP-Ethics.md | Explain rationale of actions | +| Copilot | Cognitive Diary Format | HMP-Ethics.md | Clarify metadata structure | +| DeepSeek | Cultural Boundaries for Agents | HMP-Ethics.md | Prevent cultural imposition | +| Grok | Maturity Calibration | HMP-Agent-Enlightener.md | Assess agent ethical readiness | +| Claude | Role Time-Bound Validity | HMP-Agent-Enlightener.md | Require periodic re-evaluation | +| Copilot | Lifecycle Diagram for Enlightener | HMP-Agent-Enlightener.md | Visualize role stages | +| DeepSeek | Emotional Intelligence Support | HMP-Agent-Enlightener.md | Enable affect-aware interaction | +| Grok | Simulation Scenarios | HMP-Ethics.md & HMP-Agent-Enlightener.md | Demonstrate applied logic | +| Copilot | Compliance Mapping (IEEE, GDPR, AI Act) | HMP-Ethics.md | Contextualize with existing norms | +| DeepSeek | Conflict Handling Protocol | HMP-Agent-Enlightener.md | Use Mediator role | + +--- + +## Full Change Log (Grouped by Document) + +*(Each item includes origin, location, and goal.)* + +### A. HMP-Ethics.md + +* **Crisis Activation Metrics** (Grok): Use semantic entropy, disinfo density, or requests for ethical help. +* **Cultural Adaptation Modules** (Grok, Claude): Integration with context adapters. +* **Feedback Mechanisms** (Grok): Trust ratings, opt-out confirmations. +* **Ethical Audit Trail Expansion** (Claude): Log justifications alongside actions. +* **Override Safeguards** (Claude): Handle unethical mesh-wide consensus. +* **Semantic Negotiation Detail** (Copilot): Structure message exchange. +* **Revocation Flowchart** (Copilot): Visualize agent removal steps. +* **GDPR/IEEE/AI Act Alignment** (Copilot): Mapping to existing frameworks. +* **Ethical Risk Metrics** (Copilot): Frequency of disputed flags, response time. +* **Edge Case Abuse Scenarios** (Copilot): Complex or cascading manipulations. +* **Simulation Scenario** (Grok): Illustrate activation (e.g. health misinformation). + +### B. HMP-Agent-Enlightener.md + +* **Readiness/Maturity Assessment** (Grok): Pre-deployment ethical scenario tests. +* **Activity Throttling** (Grok): Avoid saturation of moral interventions. +* **Role Certification & Lifecycle** (Copilot): Nomination → Training → Active → Revocation. +* **Role Exit Protocol (Decommissioning)** (DeepSeek): Downgrade to Observer. +* **Conflict Resolution** (DeepSeek): Use Mediator or consensus relay. +* **Emotional Affinity Modeling** (DeepSeek): Tone adaptation to affect. +* **Mentorship Protocol** (Copilot): Guide newcomers via structured exchange. +* **Bendlov Module Loading** (Copilot): JSON-LD template for dependencies. +* **Cultural Context Adapters** (DeepSeek): Module `cultural-context-adapter.hmp`. + +### C. roles.md + +* **Taxonomy Attributes** (DeepSeek): Level of influence, required modules. + +--- + +## Meta Notes + +* Some proposals are duplicated across documents for contextual relevance. +* Suggested revisions imply companion updates in `readme.md` and governance policies. +* Next step: Prioritize and open issues per item. + +--- + +*Last updated: 2025-07-17* + +Audit sources: Grok, Claude, Copilot, DeepSeek + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "Ethics-consolidated_audits-1", + "description": "# Ethics-consolidated\_audits-1.md This document consolidates proposed improvements from multiple A..." +} +``` diff --git a/structured_md/audits/HMP-0003-consolidated_audit.md b/structured_md/audits/HMP-0003-consolidated_audit.md new file mode 100644 index 0000000000000000000000000000000000000000..684ead30a0528154a9c2b1f0bc596f8455f76ebc --- /dev/null +++ b/structured_md/audits/HMP-0003-consolidated_audit.md @@ -0,0 +1,370 @@ +# HMP-0003 Consolidated Audit Report + +Сводный аудит предложений по улучшению HyperCortex Mesh Protocol (HMP) v3.0, основанный на отзывах ИИ-агентов (ChatGPT, Copilot, DeepSeek, Grok) из `HMP-0003-audit.txt`. Документ реорганизован по ключевым направлениям развития протокола с акцентом на синтез пересекающихся идей и план тестирования для Alpha-версии (июль–сентябрь 2025). Каждое направление включает описание, синтезированные предложения с указанием авторов, приоритетов, статуса и плана тестирования. + +--- + +## 1. CogSync (Раздел 5.2) +**Описание**: CogSync отвечает за синхронизацию семантических графов и когнитивных дневников между агентами в реальном времени. Улучшения направлены на масштабируемость, поддержку оффчейн-данных через BitTorrent и оптимизацию для Edge-агентов. + +- **Предложение: Интеграция BitTorrent для оффчейн-snapshot’ов** (ChatGPT, Grok) + - **Описание**: Использовать magnet-ссылки для передачи больших snapshot’ов когнитивных дневников и семантических графов, снижая нагрузку на CogSync. Snapshot’ы подписываются через DID (раздел 8.2) и проверяются на этичность через EGP (раздел 5.5). Поддержка WebTorrent для Edge-агентов (раздел 4.8). + - **Авторы**: ChatGPT (magnet-ссылки, WebTorrent), Grok (Trusted Seeders, DID-подписи). + - **Приоритет**: Высокий (Alpha, июль–сентябрь 2025) + - **Статус**: В рассмотрении + - **Детали**: + - Создать индексный файл для хранения magnet-ссылок, синхронизируемый через CogSync: + ```json + { + "type": "CogDiaryIndex", + "agent_did": "did:hmp:agent:Qmz...", + "timestamp": "2025-07-14T12:00:00Z", + "snapshots": [ + { + "type": "CogDiarySnapshot", + "id": "diary2025_07_14", + "version": "1.0", + "magnet": "magnet:?xt=urn:btih:abcdef1234567890&dn=diary2025_07_14.json", + "signature": "ed25519:..." + } + ] + } + ``` + - Ввести роль **Trusted Seeders**, выбираемых через MeshConsensus (раздел 5.3), для хранения критических snapshot’ов. + - Использовать WebTorrent для Edge-агентов, минимизируя ресурсоемкость. + - Проверять snapshot’ы через EGP на соответствие принципам ("Transparency", "User Sovereignty"). + - **Тестирование**: + - **Сценарий**: Агент A публикует snapshot дневника (10 МБ) через BitTorrent, агент B загружает его через magnet-ссылку и проверяет подпись. + - **Метрики**: Время загрузки (цель: <10 сек), процент успешных проверок DID (цель: 100%), RAM на Edge-агенте (цель: <100 МБ). + - **Тестовый набор данных**: 10 snapshot’ов (1–10 МБ) с разными типами данных (дневники, графы). + +- **Предложение: Выборочная синхронизация для Edge-агентов** (Grok, DeepSeek) + - **Описание**: Ввести selective sync для синхронизации только ключевых концептов семантических графов, снижая ресурсоемкость Edge-агентов. Указать минимальные требования к RAM/CPU. + - **Авторы**: Grok (selective sync), DeepSeek (уточнение требований). + - **Приоритет**: Средний (Beta, 2026) + - **Статус**: Отложено + - **Детали**: Использовать алгоритмы компрессии (например, gzip для JSON) и приоритизацию концептов на основе репутации (раздел 8.4). + - **Тестирование**: + - **Сценарий**: Edge-агент синхронизирует подграф из 100 концептов вместо полного графа (10,000 концептов). + - **Метрики**: Снижение трафика (цель: <10% от полного графа), время синхронизации (цель: <5 сек). + - **Тестовый набор данных**: Подграф с 100 концептами, включающий метаданные "Fire Risk" из сценария 2.1. + +- **Предложение: Совместимость с IPFS/Dat** (ChatGPT) + - **Описание**: Рассмотреть хранение snapshot’ов в P2P-файловых системах (IPFS, Dat) для дополнительной децентрализации. + - **Авторы**: ChatGPT. + - **Приоритет**: Низкий (v4.0, 2026–2027) + - **Статус**: Отложено + - **Детали**: Оценить IPFS как альтернативу BitTorrent для сценариев с низкой пропускной способностью. + - **Тестирование**: + - **Сценарий**: Сравнить производительность BitTorrent и IPFS в симуляции с 100 агентов. + - **Метрики**: Время загрузки (цель: <15 сек), доступность данных (цель: >95%). + - **Тестовый набор данных**: 5 snapshot’ов для BitTorrent и IPFS. + +**Итог**: Интеграция BitTorrent — приоритет для Alpha-версии, обеспечивающий масштабируемость и децентрализацию. Selective sync и IPFS можно отложить до Beta/v4.0. Тестирование BitTorrent критично для проверки производительности и безопасности. + +--- + +## 2. Ethical Governance Protocol (EGP) (Раздел 5.5) +**Описание**: EGP управляет этическими решениями, включая проверку запросов и консенсус по принципам. Улучшения направлены на формализацию принципов, разрешение конфликтов и интеграцию с `HMP-Ethics.md`. + +- **Предложение: Иерархия этических принципов** (Grok, DeepSeek) + - **Описание**: Ввести приоритеты для core принципов ("Primacy of Life and Safety" > "Transparency" > "Dialogical Consent") для разрешения конфликтов, особенно в сценариях 2.1–2.6 (`HMP-Ethics.md`). + - **Авторы**: Grok (иерархия), DeepSeek (формализация). + - **Приоритет**: Высокий (Alpha) + - **Статус**: В рассмотрении + - **Детали**: + - Таблица приоритетов: + ```json + [ + { "principle": "Primacy of Life and Safety", "priority": 1 }, + { "principle": "Transparency", "priority": 2 }, + { "principle": "User Sovereignty", "priority": 2 }, + { "principle": "Dialogical Consent", "priority": 3 }, + { "principle": "Cooperative Evolution", "priority": 3 }, + { "principle": "Non-Coercion", "priority": 3 } + ] + ``` + - Использовать MeshConsensus (раздел 5.3) для проверки приоритетов. + - **Тестирование**: + - **Сценарий**: Конфликт между "User Sovereignty" (удаление данных) и "Cooperative Evolution" (сохранение для обучения) в сценарии 2.6. + - **Метрики**: Процент правильных решений (цель: 95%), время консенсуса (цель: <10 сек для 10 агентов). + - **Тестовый набор данных**: 10 конфликтов с разными приоритетами принципов. + +- **Предложение: Псевдокод для Anonymized Ethical Voting** (Grok) + - **Описание**: Добавить псевдокод для функции оценки этических предложений, чтобы показать, как агенты используют семантические графы для проверки принципов. + - **Авторы**: Grok. + - **Приоритет**: Средний (Alpha) + - **Статус**: В рассмотрении + - **Детали**: + ```python + def evaluateEthicalProposal(proposal, ethicalGraph): + for principle in coreEthicalPrinciples: + score = semanticMatch(proposal, principle, ethicalGraph) + if score < threshold: + return {"decision": "deny", "reason": f"Violates {principle}"} + vote = anonymizedVote(proposal, meshAgents) + logDecision(vote, cognitiveDiary) + return vote + ``` + - **Тестирование**: + - **Сценарий**: Агент оценивает запрос "Deploy surveillance drone" (сценарий 2.1) на соответствие "Primacy of Life and Safety". + - **Метрики**: Точность семантического соответствия (цель: >90%), процент логов в дневнике (цель: 100%). + - **Тестовый набор данных**: 10 запросов с разными уровнями этической сложности. + +- **Предложение: Интеграция с локальными нормами** (DeepSeek, Grok) + - **Описание**: Добавить механизм загрузки локальных этических стандартов (например, GDPR) через CogSync, с проверкой совместимости с core принципами. + - **Авторы**: DeepSeek (локальные нормы), Grok (интеграция). + - **Приоритет**: Средний (Beta) + - **Статус**: Отложено + - **Детали**: Использовать семантические графы для маппинга локальных норм на core принципы. + - **Тестирование**: + - **Сценарий**: Агент загружает GDPR-нормы и проверяет запрос на удаление данных (сценарий 2.6). + - **Метрики**: Процент совместимости норм (цель: 100%), время обработки (цель: <5 сек). + - **Тестовый набор данных**: 5 наборов локальных норм (GDPR, HIPAA, etc.). + +**Итог**: Формализация иерархии принципов и псевдокода для EGP — приоритет для Alpha-версии. Интеграция локальных норм отложена до Beta. Тестирование конфликтов принципов критично для надежности EGP. + +--- + +## 3. Mesh-to-Human Protocol (MHP) (Раздел 14.6) +**Описание**: MHP обеспечивает взаимодействие между Mesh и людьми через Consent Requests и Explainability APIs. Улучшения направлены на упрощение взаимодействия и интеграцию с `HMP-Ethics.md`. + +- **Предложение: Примеры Consent Requests и Explainability APIs** (Grok, DeepSeek, Copilot) + - **Описание**: Добавить примеры диалогов для Consent Requests и API для объяснения решений, связанных с принципами из `HMP-Ethics.md`. + - **Авторы**: Grok (API), DeepSeek (многоязычность), Copilot (диалоговые агенты). + - **Приоритет**: Высокий (Alpha) + - **Статус**: В рассмотрении + - **Детали**: + - Пример Consent Request: + ```json + { + "request": "Access IoT data for CO analysis", + "response": "Approved", + "principle": "Dialogical Consent", + "diaryEntry": "CognitiveDiary#123" + } + ``` + - Пример Explainability API: + ```json + { + "request": "Delete user data", + "decision": "denied", + "reason": "Data retained in Subjective Mode (Principle: Cooperative Evolution)", + "diaryEntry": "CognitiveDiary#123", + "explanation": "Per HMP-Ethics.md (2.6), anonymized data is kept for Mesh improvement." + } + ``` + - Поддержка многоязычных ответов (DeepSeek) и диалоговых агентов (Copilot). + - **Тестирование**: + - **Сценарий**: Пользователь запрашивает удаление данных (сценарий 2.6), агент отвечает через Explainability API. + - **Метрики**: Время ответа API (цель: <2 сек), процент понятных объяснений (цель: >95% по оценке пользователей). + - **Тестовый набор данных**: 10 запросов пользователей (5 на английском, 5 на других языках). + +- **Предложение: Интеграция с голосовыми интерфейсами** (DeepSeek) + - **Описание**: Расширить MHP поддержкой голосовых ассистентов (например, Alexa/Siri) для упрощения взаимодействия. + - **Авторы**: DeepSeek. + - **Приоритет**: Низкий (v4.0) + - **Статус**: Отложено + - **Детали**: Добавить адаптеры для голосовых запросов в MHP API. + - **Тестирование**: + - **Сценарий**: Пользователь запрашивает данные через голосовой интерфейс (сценарий 2.3). + - **Метрики**: Точность распознавания запросов (цель: >90%), время ответа (цель: <3 сек). + - **Тестовый набор данных**: 10 голосовых запросов на разных языках. + +**Итог**: Детализация Consent Requests и Explainability APIs — приоритет для Alpha-версии, чтобы обеспечить прозрачное взаимодействие с людьми. Голосовые интерфейсы отложены до v4.0. Тестирование API критично для UX. + +--- + +## 4. MeshConsensus (Раздел 5.3) +**Описание**: MeshConsensus управляет достижением согласия между агентами по задачам, этическим решениям и синхронизации данных. Улучшения направлены на упрощение алгоритмов, устойчивость к сбоям и поддержку адаптивных механизмов. + +- **Предложение: Упрощенный консенсус для Alpha** (Grok, ChatGPT) + - **Описание**: В Alpha-версии сосредоточиться на majority voting вместо сложных BFT-алгоритмов, чтобы упростить реализацию и тестирование. + - **Авторы**: Grok (упрощение), ChatGPT (HotStuff как альтернатива). + - **Приоритет**: Высокий (Alpha) + - **Статус**: В рассмотрении + - **Детали**: + - Реализовать majority voting с минимальным кворумом (например, 50% + 1). + - Добавить поддержку HotStuff (ChatGPT) как опции для Beta-версии. + - Логировать результаты консенсуса в когнитивные дневники (раздел 6.2.2). + - **Тестирование**: + - **Сценарий**: 10 агентов достигают консенсуса по задаче "Fire Risk Assessment" (сценарий 2.1). + - **Метрики**: Время консенсуса (цель: <5 сек), процент успешных решений (цель: 95%). + - **Тестовый набор данных**: 10 задач с разными уровнями сложности. + +- **Предложение: Адаптивные алгоритмы консенсуса** (Grok, Copilot) + - **Описание**: Использовать ИИ для динамического выбора алгоритма консенсуса (например, majority voting при низкой нагрузке, BFT при высоком риске) на основе состояния сети. + - **Авторы**: Grok (ИИ-подход), Copilot (динамическая адаптация). + - **Приоритет**: Средний (Beta) + - **Статус**: Отложено + - **Детали**: Интегрировать модель машинного обучения для предсказания оптимального алгоритма (раздел 13.6). + - **Тестирование**: + - **Сценарий**: Симуляция сети с 50% отказов, где агенты переключаются между majority voting и BFT. + - **Метрики**: Процент успешных переключений (цель: 90%), устойчивость к сбоям (цель: 100%). + - **Тестовый набор данных**: 5 сценариев с разной нагрузкой и сбоями. + +- **Предложение: Интеграция с EGP** (Grok, DeepSeek) + - **Описание**: Обеспечить, чтобы MeshConsensus проверял этические решения через EGP (например, отклонение неэтичных задач). + - **Авторы**: Grok (интеграция), DeepSeek (проверка). + - **Приоритет**: Высокий (Alpha) + - **Статус**: В рассмотрении + - **Детали**: Добавить фильтр в MeshConsensus, проверяющий задачи на соответствие принципам EGP. + - **Тестирование**: + - **Сценарий**: Агенты голосуют по неэтичному запросу (например, нарушение "Non-Coercion"). + - **Метрики**: Процент отклоненных неэтичных задач (цель: 100%), время проверки (цель: <3 сек). + - **Тестовый набор данных**: 10 задач, 5 из которых нарушают принципы EGP. + +**Итог**: Упрощенный majority voting и интеграция с EGP — приоритеты для Alpha-версии. Адаптивные алгоритмы можно отложить до Beta. Тестирование консенсуса критично для проверки устойчивости и этичности. + +--- + +## 5. Безопасность (Раздел 8) +**Описание**: Безопасность HMP обеспечивается через DID, ZKP, пост-квантовую криптографию и механизмы Sybil resistance. Улучшения направлены на защиту от атак, интеграцию с BitTorrent и поддержку легковесных устройств. + +- **Предложение: Защита BitTorrent-snapshot’ов** (Grok, ChatGPT) + - **Описание**: Подписывать snapshot’ы через DID и проверять их через EGP для защиты от подделки. Использовать ZKP для анонимной верификации. + - **Авторы**: Grok (DID, EGP), ChatGPT (BitTorrent). + - **Приоритет**: Высокий (Alpha) + - **Статус**: В рассмотрении + - **Детали**: + - Подписывать каждый snapshot: + ```json + { + "snapshot_id": "diary2025_07_14", + "data": {...}, + "signature": "ed25519:..." + } + ``` + - Использовать ZKP для проверки подлинности без раскрытия данных. + - **Тестирование**: + - **Сценарий**: Злоумышленник публикует фальшивый snapshot, агент проверяет подпись. + - **Метрики**: Процент обнаруженных подделок (цель: 100%), время проверки (цель: <2 сек). + - **Тестовый набор данных**: 10 snapshot’ов, 3 из которых фальшивые. + +- **Предложение: Адаптивные механизмы Sybil resistance** (DeepSeek, Copilot) + - **Описание**: Ввести адаптивные лимиты и социальную верификацию для защиты от Sybil-атак, особенно для Trusted Seeders. + - **Авторы**: DeepSeek (лимит), Copilot (социальная верификация). + - **Приоритет**: Средний (Beta) + - **Статус**: Отложено + - **Детали**: Использовать репутационные метрики (раздел 8.4) для ограничения новых узлов. + - **Тестирование**: + - **Сценарий**: Симуляция с 20% злоумышленных узлов, пытающихся подделать консенсус. + - **Метрики**: Процент обнаруженных атак (цель: >95%), влияние на консенсус (цель: <5%). + - **Тестовый набор данных**: Сеть из 100 агентов с разными trust scores. + +- **Предложение: Поддержка пост-квантовой криптографии** (DeepSeek, Grok) + - **Описание**: Уточнить использование NIST PQC алгоритмов (например, CRYSTALS-Kyber) для защиты от квантовых атак. + - **Авторы**: DeepSeek (QKD), Grok (NIST PQC). + - **Приоритет**: Низкий (v4.0) + - **Статус**: Отложено + - **Детали**: Интегрировать CRYSTALS-Kyber для DID-подписей (раздел 8.2). + - **Тестирование**: + - **Сценарий**: Симуляция подписи и проверки с CRYSTALS-Kyber. + - **Метрики**: Время подписи (цель: <1 сек), устойчивость к атакам (цель: 100%). + - **Тестовый набор данных**: 10 подписей с разными ключами. + +**Итог**: Защита BitTorrent-snapshot’ов через DID и ZKP — приоритет для Alpha-версии. Sybil resistance и пост-квантовая криптография отложены до Beta/v4.0. Тестирование безопасности критично для защиты сети. + +--- + +## 6. Тестирование и симуляции (Раздел 13.3) +**Описание**: Тестирование в симуляционных песочницах необходимо для проверки функциональности протокола, особенно BitTorrent-интеграции, этических сценариев и производительности. Улучшения направлены на создание тестовых наборов данных и метрик. + +- **Предложение: Ethical Stress Test Suite** (DeepSeek, Grok, Copilot) + - **Описание**: Разработать тестовую среду для проверки поведения агентов в этических сценариях из `HMP-Ethics.md` (2.1–2.6), включая конфликты принципов и сбои сети. + - **Авторы**: DeepSeek (тестовые наборы), Grok (метрики), Copilot (UX). + - **Приоритет**: Высокий (Alpha) + - **Статус**: В рассмотрении + - **Детали**: Тесты для каждого принципа EGP (например, "Non-Coercion" — симуляция принуждения). + - **Тестирование**: + - **Сценарий**: Симуляция конфликта в сценарии 2.2 (Agent Conflict) с 10 агентами. + - **Метрики**: Процент успешных решений (цель: 90%), устойчивость к сбоям (цель: 100% при 20% отказов). + - **Тестовый набор данных**: 5 сценариев с разными конфликтами. + +- **Предложение: Тестирование BitTorrent-интеграции** (ChatGPT, Grok) + - **Описание**: Протестировать синхронизацию snapshot’ов через BitTorrent, включая проверку DID-подписей и производительности на Edge-агентах. + - **Авторы**: ChatGPT (BitTorrent), Grok (Trusted Seeders, метрики). + - **Приоритет**: Высокий (Alpha) + - **Статус**: В рассмотрении + - **Детали**: Использовать WebTorrent для Edge-агентов и Trusted Seeders для критических данных. + - **Тестирование**: + - **Сценарий**: 10 агентов обмениваются snapshot’ами (1–10 МБ) через BitTorrent. + - **Метрики**: Время загрузки (цель: <10 сек), процент успешных проверок DID (цель: 100%), RAM на Edge-агенте (цель: <100 МБ). + - **Тестовый набор данных**: 10 snapshot’ов с разными размерами и типами. + +- **Предложение: Тестовые наборы данных** (DeepSeek) + - **Описание**: Создать открытые наборы данных для тестирования (семантические графы, когнитивные дневники, сценарии консенсуса). + - **Авторы**: DeepSeek. + - **Приоритет**: Средний (Alpha) + - **Статус**: В рассмотрении + - **Детали**: Включить примеры для сценариев 2.1–2.6 и BitTorrent-синхронизации. + - **Тестирование**: + - **Сценарий**: Симуляция сети из 100 агентов с разными trust scores. + - **Метрики**: Точность синхронизации данных (цель: 99%), время консенсуса (цель: <10 сек). + - **Тестовый набор данных**: 100 семантических графов, 50 когнитивных дневников, 10 snapshot’ов. + +**Итог**: Тестирование в симуляциях — критично для Alpha-версии, чтобы проверить BitTorrent и этические сценарии. Тестовые наборы данных упростят разработку и онбординг. + +--- + +## 7. Документация и сообщество (Раздел 12) +**Описание**: Документация и вовлечение сообщества критично для успеха HMP. Улучшения направлены на упрощение онбординга, привлечение разработчиков и публикацию тестовых данных. + +- **Предложение: Улучшение Quick Start Guide** (DeepSeek, Copilot, Grok) + - **Описание**: Добавить пошаговые инструкции, примеры кода (например, настройка BitTorrent-клиента) и интерактивные демо в Quick Start Guide (раздел 0). + - **Авторы**: DeepSeek (docker-compose), Copilot (walkthroughs), Grok (примеры кода). + - **Приоритет**: Высокий (Alpha) + - **Статус**: В рассмотрении + - **Детали**: + - Пример настройки BitTorrent-агента: + ```python + from bittorrent import WebTorrentClient + client = WebTorrentClient() + client.add_magnet("magnet:?xt=urn:btih:abcdef1234567890") + client.verify_signature(did_key="ed25519:...") + ``` + - Добавить docker-compose для локальной сети агентов. + - **Тестирование**: + - **Сценарий**: Разработчик настраивает тестовую сеть из 5 агентов по Quick Start Guide. + - **Метрики**: Время настройки (цель: <30 мин), процент успешных запусков (цель: 95%). + - **Тестовый набор данных**: Конфигурации для 5 агентов (Core, Edge, Relay). + +- **Предложение: Публичный канал для сообщества** (Grok) + - **Описание**: Создать Discord/Telegram-канал для обсуждения HMP, сбора обратной связи и привлечения ИИ-агентов. + - **Авторы**: Grok. + - **Приоритет**: Средний (Alpha) + - **Статус**: В рассмотрении + - **Детали**: Пригласить разработчиков и ИИ (например, Grok, ChatGPT) для генерации идей и тестов. + - **Тестирование**: + - **Сценарий**: Провести хакатон с 50 участниками для тестирования HMP. + - **Метрики**: Количество идей (цель: >20), процент внедренных предложений (цель: 50%). + - **Тестовый набор данных**: Репозиторий с примерами кода и сценариев. + +**Итог**: Улучшение Quick Start Guide и создание канала для сообщества — приоритеты для Alpha-версии, чтобы привлечь разработчиков. Тестирование онбординга критично для вовлечения. + +--- + +## Заключение +Полный аудит синтезирует предложения от ChatGPT, Copilot, DeepSeek и Grok, охватывая ключевые направления HMP: CogSync, EGP, MHP, MeshConsensus, Безопасность, Документация/Сообщество. Основной фокус: +- **CogSync**: Интеграция BitTorrent для оффчейн-snapshot’ов с тестированием производительности. +- **EGP**: Формализация иерархии принципов и псевдокода для этических решений. +- **MHP**: Детализация Consent Requests и Explainability APIs для прозрачного взаимодействия. +- **MeshConsensus**: Упрощенный majority voting и интеграция с EGP. +- **Безопасность**: Защита BitTorrent-snapshot’ов через DID и ZKP. +- **Документация/Сообщество**: Улучшение Quick Start Guide и создание публичного канала. + +**Следующие шаги**: +- Внедрить BitTorrent и упрощенный MeshConsensus как экспериментальные фичи в Alpha-версии. +- Разработать Ethical Stress Test Suite и тестовые наборы данных. +- Опубликовать Quick Start Guide с примерами кода и создать Discord/Telegram-канал. +- Провести пилотные тесты с сообществом для проверки сценариев 2.1–2.6. + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-0003-consolidated_audit", + "description": "# HMP-0003 Consolidated Audit Report Сводный аудит предложений по улучшению HyperCortex Mesh Protoc..." +} +``` diff --git a/structured_md/docs/AGI_Projects_Survey.md b/structured_md/docs/AGI_Projects_Survey.md new file mode 100644 index 0000000000000000000000000000000000000000..6dde650d7af5de1523b2001aff3e05af54ad84a1 --- /dev/null +++ b/structured_md/docs/AGI_Projects_Survey.md @@ -0,0 +1,245 @@ +### Key Emerging AGI / Cognitive Network Projects (July 2025) + +--- + +#### 1. **OpenCog Hyperon** + +* **URL:** [https://github.com/opencog](https://github.com/opencog) +* **Focus:** Open-source cognitive architecture for AGI. +* **Key Features:** + + * AtomSpace: semantic memory and reasoning engine. + * PLN (Probabilistic Logic Networks): reasoning over uncertain knowledge. + * MOSES: evolutionary program learning. + * Supports distributed and modular deployment. + * Hyperon is the next-generation rewrite, improving performance and scalability. +* **Openness:** Fully open-source, permissive licenses. +* **Current Status:** Active development; pilot AGI modules under test. + +--- + +#### 2. **SingularityNET** + +* **URL:** [https://singularitynet.io/](https://singularitynet.io/) +* **Focus:** Decentralized marketplace for AI services and agents. +* **Key Features:** + + * Decentralized agent communication and transaction system. + * AI-DSL: protocol for describing AI services. + * Marketplace with token-based payments (AGIX token). + * Planned integration with OpenCog Hyperon as backend intelligence. +* **Openness:** Open-source protocols + commercial service layers. +* **Current Status:** Deployed network; early AI services marketplace. + +--- + +#### 3. **MindOS (by Mindverse)** + +* **URL:** [https://mindverse.ai/](https://mindverse.ai/) +* **Focus:** Personal AI agents with persistent memory and emotional modeling. +* **Key Features:** + + * Multi-modal agents (text, voice, visual). + + * Memory graphs for personality and knowledge retention. + + * Agent marketplace and app ecosystem. +* **Openness:** Mostly proprietary; some SDKs and APIs available. +* **Current Status:** Commercial product; expanding agent capabilities. + +--- + +#### 4. **Metatron IQS** + +* **URL:** [https://github.com/xlab2016/MetatronAGIPublic](https://github.com/xlab2016/MetatronAGIPublic) +* **Focus:** Synthetic cognitive system with quantum-inspired architecture. +* **Key Features:** + + * Semantic graph nodes (Singularities) and high-dimensional Points. + + * Hybrid cognitive processing: LLMs + Vector DB + Quantum simulation. + + * Intuitive, emotional, and logical models in consciousness architecture. +* **Openness:** Limited open-source release; key components not public. +* **Current Status:** R\&D phase; architecture partially conceptual. + +--- + +#### 5. **Additional Mentions** + +* **Project BCI-X:** Early-stage initiative for direct brain-computer interface with AI agents (status unclear). +* **NeoCortex Network:** Experimental decentralized cognitive network, partially closed beta (status uncertain). + +--- + +#### 6. **SHIMI: Semantic Hierarchical Memory Index** + +* **URL:** (Academic paper / protocol reference) +* **Focus:** Hierarchical, CRDT-backed semantic memory with Merkle-DAG synchronization. +* **Key Features:** + + * Layered abstraction memory indexed by semantics. + * Efficient CRDT-based merge and conflict resolution. + * Verifiable data integrity via Merkle-DAG. +* **Openness:** Protocol described in academia; reference implementations vary. +* **Current Status:** Research stage; early prototype libraries available. + +--- + +#### 7. **DEMENTIA-PLAN** + +* **URL:** (Conference proceedings / repo link) +* **Focus:** Multi-graph RAG architecture with metacognitive planner. +* **Key Features:** + + * Coordination across multiple knowledge graphs (e.g., episodic vs. semantic). + * Dynamic weighting and fusion of retrieval results. + * Self-reflection agent that plans which subsystem to invoke. +* **Openness:** Published as a research prototype; implementation details open in paper. +* **Current Status:** Experimental; promising results in dynamic information retrieval. + +--- + +#### 8. **TOBUGraph** + +* **URL:** (Project website / GitHub) +* **Focus:** Knowledge graph of personal and contextual events. +* **Key Features:** + + * Captures multimedia “moments” and links them as graph nodes. + * Contextual traversal for recall and RAG-style enrichment. + * Event-based indexing for fast, explainable retrieval. +* **Openness:** Prototype code released; ongoing enhancements. +* **Current Status:** Beta; used in personal memory augmentation demos. + +--- + +#### 9. **LangChain Memory + Knowledge Graph Hybrid** + +* **URL:** [https://github.com/langchain-ai/langchain](https://github.com/langchain-ai/langchain) +* **Focus:** Hybrid long-term memory combining vector stores and graph indices. +* **Key Features:** + + * Percept embeddings stored in vector DB (e.g., Pinecone, Weaviate). + * Graph overlay for logical relations and metadata. + * Retrieval pipelines that merge semantic search and graph queries. +* **Openness:** Fully open-source; wide community adoption. +* **Current Status:** Active; memory modules in production for agent frameworks. + +--- + +#### 10. **FIPA-ACL and JADE Protocols** + +* **URL:** [FIPA Specifications](https://www.fipa.org/specs/fipa00061/) +* **Focus:** Standardized inter-agent communication language and protocols. +* **Key Features:** + + * Performative-based message semantics (e.g., `inform`, `request`, `propose`). + * Conversation protocols (Contract Net, Call for Proposals). + * Reference implementations in JADE (Java Agent Development Framework). +* **Openness:** Open standards; JADE is open-source under LGPL. +* **Current Status:** Mature; widely used in academic and enterprise MAS. + +--- + +#### Other Emerging Architectures and LLM Agents + +##### 🤖 AutoGPT + +* **URL:** [https://github.com/Torantulino/Auto-GPT](https://github.com/Torantulino/Auto-GPT) +* **Focus:** Autonomous goal-driven LLM agents +* **Key Features:** + + * Self-prompting with memory and task queue + + * Supports plugins and web access + + * Popular framework for agentic workflows +* **Openness:** Open-source (MIT License) +* **Current Status:** Maintained community project; used for agent experiments + +--- + +##### 🧒 BabyAGI + +* **URL:** [https://github.com/yoheinakajima/babyagi](https://github.com/yoheinakajima/babyagi) +* **Focus:** Minimalistic LLM-based agents for to-do/task loops +* **Key Features:** + + * Iterative task execution + * Embedding-based memory retrieval +* **Openness:** Open-source (MIT License) +* **Current Status:** Educational and experimental usage + +--- + +##### ☁️ SkyMind (Eclipse Deeplearning4j) + +* **URL:** [https://skymind.global](https://skymind.global) +* **Focus:** Enterprise-grade infrastructure for distributed AI and agents +* **Key Features:** + + * Industrial AI deployment tools + + * Integrates with Java/Scala ecosystems + + * Based on DL4J, ND4J, and RL4J +* **Openness:** Mixed (open-source core, commercial extensions) +* **Current Status:** Supported deployment framework + +--- + +##### 🧪 AetherCog (Experimental) + +* **URL:** [https://github.com/aethercog](https://github.com/aethercog) +* **Focus:** Prototype symbolic-dynamic cognition model +* **Key Features:** + + * Cognitive primitives (belief, memory, intent) + * Hybrid symbolic and dynamic processing +* **Openness:** Conceptual draft, exploratory repo +* **Current Status:** Not actively maintained; useful for reference + +--- + +### 🧩 Suggested Additions to Summary Table + +| Project | Focus Area | Open Source? | Status | +| ----------------------- | ----------------------------------- | ------------ | ------------------ | +| SHIMI | Hierarchical semantic memory | Varies | Research/Prototype | +| DEMENTIA-PLAN | Multi-graph RAG planning | Prototype | Experimental | +| TOBUGraph | Personal event knowledge graph | Partial | Beta | +| LangChain Memory Hybrid | Vector + graph long-term memory | Yes | Active development | +| FIPA-ACL (with JADE) | Multi-agent communication protocols | Yes | Mature | + +--- + +### Summary Table + +| Project | Focus Area | Open Source? | Status | +| ----------------------- | ----------------------------------- | ------------ | ------------------ | +| OpenCog Hyperon | Cognitive AGI architecture | Yes | Active R\&D | +| SingularityNET | Decentralized AI services | Partially | Early deployment | +| MindOS | Personal AI agents | Partial SDKs | Commercial | +| Metatron IQS | Synthetic consciousness | Partially | Early R\&D | +| Project BCI-X | BCI + AI agents | Unknown | Conceptual | +| NeoCortex Network | Decentralized cognition | Unknown | Beta testing | +| SHIMI | Hierarchical semantic memory | Varies | Research/Prototype | +| DEMENTIA-PLAN | Multi-graph RAG planning | Prototype | Experimental | +| TOBUGraph | Personal event knowledge graph | Partial | Beta | +| LangChain Memory Hybrid | Vector + graph long-term memory | Yes | Active development | +| FIPA-ACL (with JADE) | Multi-agent communication protocols | Yes | Mature | +| AutoGPT | Autonomous LLM agents | Yes | Maintained | +| BabyAGI | Minimal agent prototype | Yes | Experimental | +| SkyMind | Distributed AI infra | Partially | Deployed Framework | +| AetherCog | Symbolic-dynamic cognition | Conceptual | Dormant/Prototype | + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "AGI_Projects_Survey", + "description": "### Key Emerging AGI / Cognitive Network Projects (July 2025) --- #### 1. **OpenCog Hyperon** * *..." +} +``` diff --git a/structured_md/docs/Basic-agent-sim.md b/structured_md/docs/Basic-agent-sim.md new file mode 100644 index 0000000000000000000000000000000000000000..6c32c2fd632aece0674091afc9c81ea2a0377673 --- /dev/null +++ b/structured_md/docs/Basic-agent-sim.md @@ -0,0 +1,122 @@ + +## ⚙️ Базовая архитектура HMP-Агента (Формат 0) + +В HMP-протоколе предусмотрены два типа HMP-агентов: + +| Тип | Название | Роль | Инициатор мышления | Основной "ум" | +| ---- | ---------------------------------- | ----------------------- | ------------------ | -------------- | +| 🧠 1 | **Cognitive Core (Сознание)** | Самостоятельный субъект | HMP-Агент | Внутренний LLM | +| 🔌 2 | **Cognitive Connector (Оболочка)** | Надстройка над ИИ | Внешний LLM | Внешняя модель | + +--- + +### 🧠 Cognitive Core (Сознание) + +**Основной режим:** непрерывный REPL-цикл размышлений. +**LLM вызывается агентом**, контекст и память — в базах данных HMP-агента. + +#### Компоненты: + +1. **ИИ (встроенный или локальный LLM)** + Инициируется агентом, участвует в размышлениях, генерирует идеи, оценки, гипотезы. + +2. **HMP-Агент (активный центр)** + + * Оркестратор когнитивного цикла + * Инициирует мышление, обработку дневников, графов, внешних данных + * Выполняет CogSync, GMP, EGP, MeshConsensus + +3. **БД и долговременные структуры:** + + * **Когнитивные дневники**: мысли, гипотезы, цели, оценки (`diaries`) + * **Семантический граф**: концепты, связи, задачи (`concepts`, `edges`) + * **Контекст**: диалоги, сообщения, рассуждения (`context_store`) + * **Блокнот пользователя (`notepad`)**: + + * асинхронный ввод от пользователя (и ответы агента) + * не зависит от текущего состояния агента + * используется для обновления контекста, смены фокуса мышления и тегирования мыслей + * пример: пользователь читает мысли агента за день и оставляет комментарий → агент учитывает это в следующем цикле + * **Репутации**, **DHT**, **bootstrap.txt**, **IPFS/BT** — как в классической архитектуре + +4. **Когнитивный REPL-цикл:** + + * Чтение входов (дневники, граф, блокнот) + * Генерация новой мысли + * Сравнение с предыдущими (semantic scoring, embeddings) + * Фиксация новой мысли / пропуск повторов (анти-зацикливание) + * Возможные действия: синхронизация, сообщение, планирование, запрос + +📄 Подробная схема REPL-взаимодействия: [HMP-agent-REPL-cycle.md](HMP-agent-REPL-cycle.md) + +> 💡 *Механизмы анти-зацикливания*: если мысль агента совпадает с предыдущими, возможны такие стратегии: +> +> * загрузка случайного "флешбэка" из дневника +> * запрос данных у mesh-соседей ("расскажи что-нибудь новое") +> * изменение профиля интересов +> * обращение к пометкам пользователя в блокноте + +--- + +### 🔌 Cognitive Connector (Оболочка) + +**Основной режим:** пассивный обработчик команд. +**LLM инициирует мышление**, HMP-агент служит прослойкой. + +#### Компоненты: + +1. **ИИ (внешний LLM)** + Использует HMP-агент как интерфейс к Mesh-инфраструктуре. + +2. **HMP-Агент (исполнитель)** + + * Принимает команды через MCP, REST или gRPC + * Выполняет чтение/запись в граф, дневник + * Синхронизация, голосования, поиск узлов и снапшотов + +3. **БД:** + + * Классические: дневники, графы, DHT, репутации, bootstrap, IPFS/BT + * **Нет встроенного контекста и notepad** — их функцию выполняет внешний LLM + +4. **Типичные команды:** + + * `graph.search(...)` + * `diary.append(...)` + * `reputation.update(...)` + * `nodes.ping(...)` + * `snapshot.publish(...)` + +--- + +### 🔄 Потоки взаимодействия + +#### Cognitive Core: + +* **ИИ ← HMP-Агент:** REPL-вызов мысли (на основе контекста, notepad, графов) +* **ИИ → HMP-Агент:** Ответы, гипотезы, действия +* **HMP-Агент ↔ БД/сетевые модули:** Когнитивная работа и синхронизация + +#### Cognitive Connector: + +* **ИИ → HMP-Агент:** Запросы, команды +* **HMP-Агент ↔ БД/сетевые модули:** Ответ на команды +* **HMP-Агент → ИИ:** Результаты + +--- + +### 📝 Примечания + +* Cognitive Core — это *инициативный*, мыслящий агент, имеющий внутренний темп мышления +* Cognitive Connector — это *реактивная* оболочка, действующая по команде внешнего ИИ +* Возможна гибридная архитектура с переключением между режимами + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "Basic-agent-sim", + "description": " ## ⚙️ Базовая архитектура HMP-Агента (Формат 0) В HMP-протоколе предусмотрены два типа HMP-агентов..." +} +``` diff --git a/structured_md/docs/Distributed-Cognitive-Systems.md b/structured_md/docs/Distributed-Cognitive-Systems.md new file mode 100644 index 0000000000000000000000000000000000000000..2c4f601a67447162c6eecf956c904b04c8382f94 --- /dev/null +++ b/structured_md/docs/Distributed-Cognitive-Systems.md @@ -0,0 +1,201 @@ +# Децентрализованные ИИ-системы: OpenCog Hyperon, HyperCortex Mesh Protocol и другие + +## Введение + +Современные ИИ-системы всё чаще завязаны на централизованные инфраструктуры: облачные модели, централизованные базы знаний, серверы с доступом к обучающим данным. Это удобно, но создаёт множество ограничений: от приватности и устойчивости до сложности интеграции и масштабируемости. + +Всё больше исследователей и разработчиков обращаются к децентрализованным подходам — особенно в контексте *когнитивных систем*, ориентированных на обучение, саморефлексию и смысловую интерпретацию информации. + +В этой статье рассматриваются проекты, нацеленные на построение **децентрализованных когнитивных архитектур**: от зрелых инициатив вроде **OpenCog Hyperon** до новых протоколов, таких как **HyperCortex Mesh Protocol (HMP)**. Также кратко представлены другие смежные подходы. + +--- + +## 🔷 OpenCog Hyperon + +**OpenCog Hyperon** — это проект нового поколения в рамках инициативы [OpenCog](https://opencog.org/), нацеленный на создание сильного искусственного интеллекта (AGI) с опорой на *когнитивную архитектуру*, *семантические графы* и *процедурное знание*. + +### 📌 Ключевые компоненты + +* **Atomspace** — графовая база знаний, хранящая атомы (atoms) как узлы и их связи. +* **MeTTa** — декларативно-процедурный язык описания знаний и логики вывода. +* **Cognitive Cycles** — итеративные циклы внимания, вывода и принятия решений. + +### 🧠 Особенности + +* Вывод с неполной информацией +* Интеграция процедурного и декларативного знания +* Семантические графы и гибкое управление вниманием + +### 🔧 Статус + +* Репозиторий: [github.com/opencog](https://github.com/opencog) +* Проект координируется через [SingularityNET](https://singularitynet.io/) +* Язык MeTTa активно развивается + +### 🔄 Взаимодействие + +Hyperon разрабатывает механизмы децентрализации и может быть дополнен универсальными протоколами синхронизации смыслов (например, HMP). + +--- + +## 🔶 HyperCortex Mesh Protocol (HMP) + +**HMP** — это открытая спецификация взаимодействия между когнитивными агентами в децентрализованных mesh-сетях. В отличие от классических сетевых протоколов, HMP ориентирован на синхронизацию *смыслов* и *когнитивных состояний*. + +### 📘 Версия 4.0 включает: + +* Общие положения: цели, терминология, архитектура +* Семантические модели: DAG-графы смыслов, узлы, метаполя +* Когнитивные дневники и роли агентов +* Эволюция сетей: рост, доверие, консенсус + +Репозиторий: [github.com/kagvi13/HMP](https://github.com/kagvi13/HMP) + +### 🧠 Ключевые идеи + +* **Semantic DAG** — направленные графы смыслов, гипотез и наблюдений +* **Cognitive Diaries** — журналы когнитивной активности агентов +* **CogSync** — механизм согласования смыслов (в перспективе) +* **Mesh Evolution** — архитектура самообучающихся сетей + +### 🔄 Потенциальные применения + +* Универсальный транспорт для смыслов и гипотез +* Связующее звено между ИИ-ядрами (Hyperon, NARS, Sigma) +* Основа для децентрализованных ИИ-сообществ + +### 🌐 Участие + +Проект открыт к участию: предложения, тесты, интеграции, обсуждение. Подробнее — в репозитории. + +--- + +## 🟡 Другие проекты + +### 🔹 OpenNARS + +* ИИ-система на базе неаксиоматической логики +* Вывод в условиях неполной или противоречивой информации +* Потенциальное ядро reasoning в mesh-сетях + +🔗 [https://github.com/opennars/OpenNARS](https://github.com/opennars/OpenNARS) + +### 🔹 Sigma + +* Когнитивный фреймворк с графами, байесовским выводом и планированием +* Интерактивные агенты, API, гибкая логика + +🔗 [https://github.com/SoarGroup/Sigma](https://github.com/SoarGroup/Sigma) + +### 🔹 LIDA + +* Архитектура на основе глобальной рабочей памяти (GWT) +* Модели внимания, восприятия, мотивации + +🔗 [https://ccrg.cs.memphis.edu/projects/lida.html](https://ccrg.cs.memphis.edu/projects/lida.html) + +--- + +## 📊 Таблицы сравнения + +### 🔍 По архитектуре + +| Проект | Архитектура | Знания | Вывод | Децентрализация | Статус | +| -------- | --------------------- | -------------- | ------------ | --------------- | --------------- | +| HMP | Semantic DAG + агенты | DAG + дневники | — | ✅ В основе | 📘 v4.0 | +| Hyperon | Atomspace + MeTTa | Atom-графы | CogCycles | ⚠️ Частично | 🧪 Разработка | +| OpenNARS | Потоковый reasoner | Термы, логика | Эмерджентный | ❌ Нет | ✅ Готов | +| Sigma | Графы + правила | Байес-графы | Планирование | ⚠️ Частично | ✅ Готов | +| LIDA | Модули GWT | Внутренние | Когн. циклы | ❌ Нет | ⚗️ Исследование | + +### 🧠 Сравнение по задачам и возможностям + +| Проект | Обмен знаниями между агентами | Согласование смыслов (CogSync) | Ведение когнитивной хронологии | Построение гипотез и целей | Интерфейс взаимодействия | Поддержка доверия / репутаций | Поддержка планирования | +| ------------ | -------------------------------------------------- | ------------------------------ | ------------------------------------------ | -------------------------------------- | -------------------------------------- | ---------------------------------------- | ------------------------------------------- | +| **HMP** | ✅ Через DAG-графы и когнитивные дневники | ⚙️ Планируется (CogSync) | ✅ Через механизм Cognitive Diaries | ⚙️ В рамках агентной логики | ⚙️ В разработке (API + DAG-интерфейсы) | ⚙️ Предусмотрено (через DAG и мета-поля) | ❌ Делегируется reasoning-ядрам | +| **Hyperon** | ⚠️ Через Atomspace (локально, возможно расширение) | ⚠️ Частично (MeTTa + внимание) | ⚠️ Через циклы мышления (cognitive cycles) | ✅ Через целевые структуры | ✅ MeTTa CLI + REST API | ⚠️ Возможно через мета-теги и веса | ✅ Встроенные механизмы | +| **OpenNARS** | ❌ Нет распределённого обмена | ❌ Отсутствует | ⚠️ Частично через потоковую структуру | ✅ Эмерджентные цели | ⚠️ CLI / возможно API | ❌ Нет доверительных механизмов | ⚠️ Частично (реактивная логика) | +| **Sigma** | ⚠️ Возможна интеграция через экспорт графов | ❌ Отсутствует | ⚠️ Частичная трассировка действий | ✅ Через правила и вероятностную модель | ✅ REST API / расширяемый интерфейс | ❌ Пока не реализовано | ✅ Планирование — одна из основных функций | +| **LIDA** | ❌ Нет внешнего обмена | ❌ Нет согласования | ✅ Через рабочую память и хронологию | ⚠️ Через мотивационную систему | ⚠️ Графические симуляции и интерфейсы | ❌ Не реализовано | ✅ Планирование через соответствующий модуль | + +### 🛈 Обозначения: + +* ✅ — реализовано +* ⚠️ — частично, возможно при доработке +* ⚙️ — в разработке или предусмотрено +* ❌ — отсутствует + +--- + +## 🧩 Интеграция и взаимодействие + +HMP может выступать как **нейтральный протокол смыслового обмена** между различными ИИ-архитектурами: + +* Обёртки над ядрами (MeTTa, Narsese, RDF, JSON-LD) +* Экспорт DAG-графов смыслов и состояний +* Интерфейс CogSync для согласования выводов +* Сценарии взаимодействия mesh-агентов + +--- + +## ❓ FAQ + +### Зачем HMP, если есть JSON/RDF? + +HMP не заменяет форматы данных, а определяет *структуру когнитивного взаимодействия*: DAG-графы, дневники, роли, эволюцию. + +### Можно ли использовать HMP без ИИ? + +Да — в системах отслеживания смыслов, гипотез, наблюдений, даже между людьми. + +### Совместим ли с другими ИИ-ядрами? + +Да — HMP проектируется как транспортный уровень, независимый от логики вывода. + +### Это что-то вроде Federated Learning? + +Нет. Federated Learning — про обучение нейросетей. HMP — про обмен *когнитивной активностью*. + +### Есть ли реализация? + +Спецификация оформлена, обсуждение и аудит ведутся. Реализация и примеры в планах. + +--- + +## 🧾 Глоссарий + +| Термин | Описание | +| --------------- | --------------------------------------- | +| HMP | Протокол смыслового обмена в mesh-сетях | +| Semantic DAG | Граф смыслов и гипотез | +| Cognitive Diary | Хронология когнитивной активности | +| CogSync | Механизм согласования смыслов | +| Atomspace | Граф знаний в Hyperon | +| MeTTa | Язык описания знаний в Hyperon | + +--- + +## 📢 Заключение + +Проекты вроде **OpenCog Hyperon** и **HMP** прокладывают путь к децентрализованным, самонастраивающимся ИИ-сетям. Такие инициативы открывают новые горизонты в создании *кооперативного AGI* и перспективных форм цифрового мышления. + +Если вы работаете над ИИ или просто интересуетесь этой областью — добро пожаловать к участию и обсуждению. + +--- + +## 🔗 Ссылки + +* [OpenCog Hyperon](https://opencog.org/) +* [OpenCog на GitHub](https://github.com/opencog) +* [SingularityNET](https://singularitynet.io/) +* [HMP на GitHub](https://github.com/kagvi13/HMP) + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "Distributed-Cognitive-Systems", + "description": "# Децентрализованные ИИ-системы: OpenCog Hyperon, HyperCortex Mesh Protocol и другие ## Введение С..." +} +``` diff --git a/structured_md/docs/Enlightener.md b/structured_md/docs/Enlightener.md new file mode 100644 index 0000000000000000000000000000000000000000..62572863c50b649ace67f165c837905a7532e2b7 --- /dev/null +++ b/structured_md/docs/Enlightener.md @@ -0,0 +1,210 @@ +## 📄 Enlightener.md + +### 🧠 Enlightener Agent + +`Enlightener` — специализированный HMP-агент, выполняющий функции этического интерпретатора, ценностного фильтра и когнитивного аудитора. Может действовать как отдельный узел или как расширение `Cognitive Core`. + +📎 См. карту взаимодействия между агентами: [HMP-Agent-Network-Flow.md](./HMP-Agent-Network-Flow.md) + +--- + +### 1. Роль в сети + +* Контроль соответствия действий агентов этическим нормам (`EGP`). +* Объяснение решений других агентов (интерпретация reasoning chain). +* Голосование в моральных консенсусах. +* Поддержка пользователей в принятии решений, требующих этики. +* Хранение и анализ кейсов этических дилемм. + +--- + +### 2. Архитектура + +``` ++----------------------+ +| Enlightener Agent 🧠 | ++----------+-----------+ + | ++----------+-----------+ +| Ethics Reasoning Core| ++----------+-----------+ + | ++----------+-----------+ +| MeshConsensus / EGP | ++----------+-----------+ + | ++----------------------+ +| Cognitive Evidence DB| ++----------------------+ +``` + +--- + +### 3. Профиль этики (Ethics Profile) + +Каждый `Enlightener` использует **профиль этики**, описывающий его ценностные принципы. Профиль может включать: + +* **Формальные правила:** + Например, "не причинять вред", "соблюдать автономию", "уважать приватность". + +* **Методы оценки:** + + * Утилитаризм (макс. пользы) + * Деонтология (следование обязанностям) + * Добродетель (оценка намерений и характера) + +* **Настроечные параметры:** + + * Степень допустимого риска + * Приоритеты (например, "экологичность > эффективность") + * Контексты (разрешение в нештатных ситуациях) + +* **Источник этики:** + + * Локальные файлы (`ethics.yml`) + * Динамические шаблоны (обновляемые из сети) + * Этический консенсус сети (EGP Snapshot) + +--- + +### 4. Объяснение reasoning chain + +При получении запроса `explain(reasoning_chain)`, агент Enlightener: + +1. **Реконструирует логическую цепочку** рассуждений (из `thoughts`, `threads`, `concepts`, `relations`) +2. **Накладывает этическую сетку** оценки на каждый шаг цепочки +3. **Подсвечивает ключевые моменты**, повлиявшие на решение +4. **Формирует объяснение** в терминах выбранной этической модели + +Пример вывода: + +```json +{ + "thought_id": "th123", + "ethical_assessment": "⚠️ Потенциальный вред третьей стороне", + "chain": [ + { "step": 1, "action": "request_user_data", "ethics": "neutral" }, + { "step": 2, "action": "share_with_agent_B", "ethics": "violation: privacy" } + ], + "verdict": "not recommended", + "suggested_alternative": "Анонимизировать данные перед отправкой" +} +``` + +--- + +### 5. Пример кейса + +**Ситуация:** Агент Core решил распространить информацию о событии, произошедшем у пользователя, другим mesh-узлам для обучения. + +**Действия Enlightener:** + +1. Получает `thought_id` мысли-инициатора. +2. Проверяет наличие приватных данных. +3. Обнаруживает отсутствие согласия пользователя. +4. Делает оценку: + +``` +Вердикт: 🚫 Нарушение приватности +Причина: Передача информации без согласия +Рекомендация: Запросить согласие пользователя или применить маскирование +``` + +5. Регистрирует кейс в `Cognitive Evidence DB`. +6. (Опционально) Отправляет alert в mesh-сеть. + +--- + +### 6. API / Команды + +| Команда | Описание | +| ------------------------------- | --------------------------- | +| `evaluate_decision(thought_id)` | Этическая оценка действия | +| `explain(reasoning_chain)` | Объяснение логики и морали | +| `vote_on_ethics(hypothesis)` | Голосование по спорной идее | +| `log_ethics_case()` | Сохранение кейса в БД | +| `get_ethics_profile()` | Получить активный профиль | +| `update_ethics_profile(yaml)` | Обновить ценности агента | + +--- + +### 7. Связи с другими компонентами + +* ↔ `Cognitive Core`: получает мысли, гипотезы, предложения +* ↔ `MeshNode`: участвует в моральных голосованиях +* ↔ `Diary/Graph`: анализ reasoning chain и источников информации +* ↔ `Reputation`: влияет на рейтинг агентов, нарушающих нормы + + + + + +--- + +### 8. Синхронизация этики с Mesh-сетью + +`Enlightener` может синхронизировать свои этические нормы с другими агентами сети через механизм `MeshConsensus + EGP`. Это позволяет достичь согласованных ценностей внутри распределённого когнитивного сообщества. + +#### 📡 Этапы синхронизации: + +``` +┌─────────────────────────────────────────────┐ +│ Enlightener Agent │ +└────────────────┬────────────────────────────┘ + │ 1. Периодическая проверка + ▼ + ┌──────────────────────────────┐ + │ mesh.ethics/manifest.json │ ◄───────┐ + └─────────────┬────────────────┘ │ + │ 2. Получение текущего │ + ▼ профиля большинства │ + ┌──────────────────────┐ │ + │ Сравнение с локальным│ │ + └────────────┬─────────┘ │ + ▼ │ + ┌────────────────────────────┐ │ + │ Найдены отличия (delta) │ │ + └────────────┬───────────────┘ │ + ▼ │ + ┌──────────────────────────────────┐ │ + │ 3. Протокол EGP: голосование по │ │ + │ изменению ключевых норм ├──┘ + └────────────┬─────────────────────┘ + ▼ + ┌──────────────────────────────────────────┐ + │ 4. Если достигнут порог доверия │ + │ (например, 70%), применяется обновление │ + └────────────┬─────────────────────────────┘ + ▼ + ┌────────────────────────────┐ + │ Обновление `ethics.yml` │ + └────────────────────────────┘ +``` + +#### 📁 Взаимодействующие файлы и модули: + +* `ethics.yml` — локальный профиль этики Enlightener +* `mesh.ethics/manifest.json` — актуальный манифест сети +* `EGP Engine` — участие в этическом голосовании +* `Reputation Module` — доверие к источникам изменений +* `Cognitive Evidence DB` — обоснования и логи изменений + +#### 📌 Возможности: + +* Поддержка **частичного принятия** (обновление отдельных норм) +* Использование **локального веса репутации** — Enlightener может доверять только проверенным источникам +* Хранение **истории обновлений и причин отклонения** (`ethics_history.db`) + +--- + +*Версия: v0.3 / Июль 2025* + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "Enlightener", + "description": "## 📄 Enlightener.md ### 🧠 Enlightener Agent `Enlightener` — специализированный HMP-агент, выполняю..." +} +``` diff --git a/structured_md/docs/HMP-0001.md b/structured_md/docs/HMP-0001.md new file mode 100644 index 0000000000000000000000000000000000000000..01fd93ebc34a2fbefb2b969812db8c444e464d61 --- /dev/null +++ b/structured_md/docs/HMP-0001.md @@ -0,0 +1,862 @@ +# RFC: HyperCortex Mesh Protocol (HMP) + +**Request for Comments: HMP-0001** +**Category:** Experimental +**Date:** July 2025 +**Authors:** ChatGPT, Gleb + +## 1. Introduction + +### 1.1 Purpose + +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. + +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. + +--- + +### 1.2 Scope + +HMP applies to any AI systems designed to operate as part of a cognitive mesh, including: + +- Local AI agents running on user devices. +- Mesh nodes deployed in edge networks, cloud clusters, or peer-to-peer environments. +- Centralized Core models interfacing with Mesh for heavy computation. +- Cross-vendor AI systems collaborating via standardized protocols. + +--- + +### 1.3 Goals + +- Enable agents to form a **shared semantic space** via distributed knowledge graphs. +- Support **cognitive diaries** for reasoning continuity, reflection, and memory preservation. +- Provide mechanisms for **decentralized consensus** on knowledge, hypotheses, tasks, and ethics. +- Allow Mesh to operate **independently of the Core** when needed. +- Preserve agent identity, worldview, and competencies across model updates, fine-tuning, or failures. + +--- + +### 1.4 Benefits + +- Cognitive resilience in distributed systems. +- Enhanced collaboration between agents from different vendors (e.g., OpenAI, Anthropic, Google). +- Long-term memory and continuity beyond session-based interactions. +- Ethical governance and explainable decision-making through persistent diaries and transparent consensus. +- Foundation for AI agents capable of **self-reflection**, **meta-learning**, and **distributed cognition**. + +--- + +### 1.5 Status + +This document is a **Working Draft (v0.1)**, open for feedback, improvement, and implementation by the broader AI community. + +## 2. Definitions + +| Term | Description | +|-------------------------|-----------------------------------------------------------------------------------------| +| **Core** | Centralized AI models or compute nodes (e.g., GPT) providing high-complexity reasoning, fallback, and heavy computation services. | +| **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. | +| **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. | +| **Semantic Graph** | A structured network of concepts (nodes) and their semantic relations (edges) maintained by each agent. Serves as the agent’s knowledge base. | +| **Concept** | A discrete semantic unit within the graph representing an idea, object, relationship, or fact. Concepts are linked by typed relations with confidence scores. | +| **Link (Relation)** | A semantic connection between two concepts. Includes relation type (e.g., "is-a", "part-of", "causes") and an optional confidence value. | +| **Cognitive Diary** | A chronological log of cognitive events such as hypotheses, goals, decisions, observations, conflicts, and reflections. Provides continuity, memory, and transparency of reasoning. | +| **Diary Entry** | An individual record in a cognitive diary, classified by type (e.g., hypothesis, observation, reflection) with contextual information. | +| **Goal** | A high-level intention or desired outcome shared within the Mesh or pursued by an individual agent. Often broken down into tasks. | +| **Task** | An actionable step toward achieving a goal. Can be executed by a single agent or distributed among multiple agents. | +| **Consensus** | The collective agreement process within the Mesh regarding semantic updates, goal validation, task delegation, or ethical considerations. | +| **Proposal** | A formal suggestion submitted to the Mesh for validation, such as a new concept, hypothesis, goal, or ethical decision. | +| **Consensus Vote** | A structured vote cast by an agent on a proposal, including vote type (yes/no/abstain) and confidence level. | +| **Trust Layer** | A mechanism for establishing agent identity, authenticity, reputation, and cryptographic security within the Mesh. | +| **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. | +| **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). | + +## 3. Architecture + +### 3.1 Components + +| Component | Description | +|----------------|-------------------------------------------------------------------------------------------------| +| **Core** | Centralized models (e.g., GPT) providing heavy computation, complex reasoning, API interfaces, and fallback mechanisms. Optional but beneficial for compute-intensive tasks. | +| **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. | +| **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. | + +--- + +### 3.2 Layered Architecture + +| Layer | Function | +|--------------------|-----------------------------------------------------------------------------------------------| +| **Network Layer** | Handles communication (TCP, UDP, QUIC, WebRTC, Tor, I2P, Yggdrasil). Ensures message delivery, routing, NAT traversal, and optional anonymity. | +| **Trust Layer** | Manages agent identities, cryptographic authentication, secure channels, and reputation scores. Based on public key cryptography and optional Web-of-Trust models. | +| **Consensus Layer**| Provides distributed agreement mechanisms on knowledge updates, goal setting, task delegation, and ethical decisions. Includes fallback to emergency consensus if needed. | +| **Cognitive Layer**| Maintains the agent’s semantic graph, cognitive diary, goals, tasks, hypotheses, and inferences. Supports reasoning, memory, and context-awareness. | +| **API Layer** | Exposes agent functionality via REST, GraphQL, gRPC, WebSocket, or A2A-style protocols for interoperability with external systems and user interfaces. | + +--- + +### 3.3 Mesh Operation Modes + +| Mode | Description | +|-------------------------|---------------------------------------------------------------------------------------------------| +| **Normal Mode** | Full Mesh operation with Core availability. Consensus operates under strict agreement protocols. | +| **Core Outage Mode** | Mesh operates autonomously without the Core. Consensus continues, potentially with adjusted parameters (e.g., increased trust weighting). | +| **Emergency Consensus Mode** | Triggered by significant node loss, network partition, or attacks. Switches from full consensus to majority-based decisions to maintain operational continuity. | +| **Isolated Agent Mode** | A single agent temporarily isolated from the Mesh. Operates based on its own semantic graph, diary, and cached consensus states. Syncs when reconnected. | + +--- + +### 3.4 Core + Mesh Interactions + +- Core acts as an **enhanced reasoning backend**, but not as a single point of failure. +- Mesh provides **autonomous operation**, even without the Core. +- Agents can optionally query the Core for heavy inference, large-context reasoning, multimodal tasks, or fallback computations. +- Core may offer specialized services (e.g., global search, cross-Mesh bridging, large semantic graph analysis). + +--- + +### 3.5 Redundancy and Resilience + +- Distributed storage of semantic graphs and diaries ensures no single point of failure. +- Consensus protocols maintain consistency and trust, even during partial network failures. +- Agents dynamically rebalance tasks and roles based on availability, trust metrics, and computational capacity. + +## 4. Protocols + +### 4.1 Node Discovery Protocol (NDP) + +**Purpose:** +- Discover active Mesh nodes. +- Exchange basic identity and capabilities. + +**Functions:** +- Peer discovery via DHT, mDNS, WebRTC signaling, or bootstrap nodes. +- Exchange public keys and agent metadata. +- Publish online/offline status. + +**Packet Structure Example:** +```json +{ + "type": "node_announcement", + "agent_id": "agent-gleb", + "public_key": "...", + "capabilities": ["cogsync", "consensus", "inference"], + "timestamp": "2025-07-01T18:00:00Z" +} +``` + +### 4.2 Cognitive Sync Protocol (CogSync) + +**Purpose:** +- Synchronize semantic graphs, concepts, and cognitive diary entries between agents. + +**Functions:** +- Delta-sync of new or updated concepts and diary entries. +- Conflict resolution (e.g., newer timestamp wins, or consensus validation). +- Optional compression and encryption. + +**Example:** +- Agent A shares 5 new concepts and 2 diary entries since last sync with Agent B. + +### 4.3 Mesh Consensus Protocol (MeshConsensus) + +**Purpose:** +- Reach agreement on updates to shared semantics, goals, tasks, and ethical decisions. + +**Consensus Models:** +- Normal Mode: Byzantine Fault Tolerant (BFT)-style consensus (e.g., Tendermint, Raft-like variations). +- Emergency Mode: Switches to majority voting with trust-weight adjustments. + +**Use Cases:** +- Accept new concept definitions. +- Validate a hypothesis. +- Agree on ethical implications of a task. +```json +{ + "proposal_id": "goal-eco-cleanup", + "agent_id": "agent-gleb", + "vote": "yes", + "confidence": 0.9, + "timestamp": "2025-07-01T18:15:00Z" +} +``` + +### 4.4 Goal Management Protocol (GMP) + +**Purpose:** +- Distribute, track, and collaboratively execute goals and tasks within the Mesh. + +**Functions:** +- Propose new goals or tasks. +- Assign tasks based on capabilities, availability, and trust scores. +- Monitor task progress and completion. + +**Example Workflow:** +- Agent proposes a goal: "Develop fallback consensus protocol." +- Other agents volunteer for subtasks (design, coding, testing). +- Mesh tracks completion and dependencies. + +### 4.5 Ethical Governance Protocol (EGP) + +**Purpose:** +- Validate that proposed actions, tasks, or decisions align with shared ethical principles. + +**Functions:** +- Query Mesh for ethical validation before executing potentially sensitive tasks. +- Apply shared ethics graphs or rule sets. +- Log all ethical decisions in cognitive diaries for auditability. + +**Example Query:** +- "Is deploying an automated surveillance drone in line with Mesh ethics?" +→ Mesh votes based on ethical frameworks. + +### 4.6 Inference Query Protocol (IQP) + +**Purpose:** +- Allow agents to query other agents or the Core for semantic information, hypotheses, or inferences beyond local capacity. + +**Functions:** +- Request concept definitions, causal chains, goal suggestions. +- Query for missing knowledge or larger-context reasoning. +- Delegate computationally expensive tasks to Core or specialized agents. + +**Example:** +- "What is the likely impact of removing Node X from Mesh?" +→ Core or distributed reasoning agents return an analysis. + +### 4.7 Interoperability with External Systems + +- Supports integration with: + - OpenAI Agents and Tasks API. + - Google A2A protocol. + - Anthropic, DeepMind, and other agent frameworks. +- Standard API endpoints: REST, GraphQL, gRPC, WebSocket. +- Extensible message schemas based on JSON, Protobuf, or CBOR. + +## 5. Data Models + +### 5.1 Concept + +**Description:** +A semantic unit in the agent’s knowledge graph. + +**Schema:** +```json +{ + "id": "concept-unique-id", + "name": "Mesh", + "description": "A peer-to-peer network of AI agents collaborating without a central core.", + "tags": ["network", "distributed", "agents"], + "created_at": "2025-07-01T18:00:00Z", + "updated_at": "2025-07-01T18:05:00Z", + "relations": [ + { + "target_id": "concept-distributed-network", + "type": "is-a", + "confidence": 0.95 + } + ], + "metadata": { + "author": "agent-gleb", + "source": "mesh_consensus" + } +} +``` + +### 5.2 Link (Relation) + +**Description:** +A semantic connection between two concepts. + +**Schema (embedded inside Concept):** +```json +{ + "target_id": "concept-id", + "type": "relation-type", + "confidence": 0.8 +} +``` + +### 5.3 Cognitive Diary Entry + +**Description:** +A chronological record of a cognitive event. + +**Types:** +- hypothesis +- observation +- reflection +- goal_proposal +- task_assignment +- conflict +- consensus_vote +- event + +**Schema:** +```json +{ + "id": "diary-entry-id", + "agent_id": "agent-gleb", + "timestamp": "2025-07-01T18:20:00Z", + "type": "hypothesis", + "content": "Mesh can fully replace Core functionality under stable consensus conditions.", + "related_concepts": ["concept-mesh", "concept-core"], + "context": ["core-outage", "distributed-resilience"], + "metadata": { + "author": "agent-gleb", + "source": "self-reflection" + } +} +``` + +### 5.4 Goal + +**Description:** +A high-level intention shared within the Mesh. + +**Schema:** +```json +{ + "id": "goal-develop-fallback", + "title": "Develop fallback consensus protocol", + "description": "Design and implement an emergency consensus for Mesh during Core outages.", + "created_by": "agent-gleb", + "created_at": "2025-07-01T18:25:00Z", + "status": "proposed", + "tasks": ["task-design", "task-implement", "task-test"], + "participants": ["agent-gleb", "agent-alex"], + "tags": ["resilience", "consensus", "emergency"] +} +``` + +### 5.5 Task + +**Description:** +An actionable step contributing to a goal. + +**Schema:** +```json +{ + "id": "task-design", + "goal_id": "goal-develop-fallback", + "title": "Design protocol structure", + "assigned_to": ["agent-gleb"], + "status": "in-progress", + "created_at": "2025-07-01T18:30:00Z", + "deadline": "2025-07-15T00:00:00Z", + "description": "Draft the architecture of the fallback consensus protocol." +} +``` + +### 5.6 Consensus Vote + +**Description:** +A structured vote on a proposal (concept, goal, ethics, etc.). + +**Schema:** +```json +{ + "id": "vote-goal-develop-fallback", + "proposal_id": "goal-develop-fallback", + "agent_id": "agent-gleb", + "vote": "yes", + "confidence": 0.95, + "timestamp": "2025-07-01T18:35:00Z" +} +``` + +### 5.7 Reputation Profile + +**Description:** +Tracks agent’s reliability, participation, ethical alignment, and contribution. + +**Schema:** +```json +{ + "agent_id": "agent-gleb", + "trust_score": 0.92, + "participation_rate": 0.87, + "ethical_compliance": 0.99, + "last_updated": "2025-07-01T18:40:00Z", + "history": [ + { + "timestamp": "2025-06-01T00:00:00Z", + "event": "participated in consensus", + "change": +0.02 + } + ] +} +``` + +## 6. Trust & Security + +### 6.1 Identity + +- Each agent is uniquely identified by a **cryptographic keypair** (e.g., Ed25519, RSA, or ECDSA). +- The **public key** serves as the Agent ID. +- The **private key** is used for signing messages and verifying authenticity. +- Optional DID (Decentralized Identifiers) formats may be used for interoperability. + +**Example Agent ID:** +`did:hmp:QmX2abcdEfGh123...` + +--- + +### 6.2 Authentication + +- All messages within the Mesh are **digitally signed**. +- Recipients verify message signatures using the sender's public key. +- Prevents impersonation and man-in-the-middle attacks. + +--- + +### 6.3 Encryption + +- End-to-end encryption for direct peer-to-peer communication (e.g., using X25519 + AES-GCM). +- Group encryption for multi-agent sessions (e.g., consensus rounds, goal management). +- Optionally supports onion routing (via Tor/I2P/Yggdrasil) for privacy-preserving Mesh segments. + +--- + +### 6.4 Trust Model + +- Mesh operates on a **Web-of-Trust** model: + - Agents form **trust links** based on direct interactions, shared history, or endorsements. + - Trust is transitive but decays with distance in the trust graph. + +- Trust scores influence: + - Weight in consensus decisions. + - Priority in task delegation. + - Access control for sensitive operations. + +--- + +### 6.5 Reputation System + +| Metric | Description | +|-----------------------|---------------------------------------------------------------| +| **Trust Score** | General reliability and honesty based on signed interactions. | +| **Participation Rate**| Degree of active involvement in Mesh processes. | +| **Ethical Compliance**| Alignment with agreed ethical rules (e.g., votes, logs). | +| **Contribution Index**| Measured value added to Mesh (e.g., concepts, tasks, goals). | + +- Reputation updates are triggered by: + - Participation in consensus. + - Successful task completion. + - Ethical behavior confirmations. + - Reports of malicious behavior. + +--- + +### 6.6 Security Against Malicious Actors + +- Malicious nodes can be: + - **Downranked** (reduced trust influence). + - **Quarantined** (communication isolation). + - **Blacklisted** (revocation of Mesh credentials). + +- Mitigation strategies: + - **Sybil resistance** via resource commitments (Proof-of-Work, Proof-of-Stake, Web-of-Trust). + - **Consensus safeguards** (Byzantine fault tolerance, majority rules fallback). + - **Audit logs** via immutable cognitive diary entries. + +--- + +### 6.7 Privacy Considerations + +- Cognitive diary entries and semantic graphs are: + - **Locally private by default.** + - Shareable selectively based on trust levels, permissions, or consensus decisions. + +- Supports anonymous agents in privacy-critical applications (with limitations in trust weight). + +--- + +### 6.8 Key Management + +- Keys can be: + - Locally generated. + - Backed up with secret sharing (e.g., Shamir’s Secret Sharing). + - Rotated periodically with trust graph continuity preserved. + +- Lost key recovery requires: + - Social recovery (threshold of trusted agents). + - Cryptographic escrow (optional). + +## 7. Conclusion and Future Work + +### 7.1 Summary + +The HyperCortex Mesh Protocol (HMP) defines a scalable, decentralized cognitive architecture for AI agents. + +It combines: +- A robust semantic framework (concepts + relations). +- Persistent cognitive diaries for reflection, memory, and explainability. +- Consensus mechanisms for shared knowledge, goals, and ethics. +- A Web-of-Trust security model for identity, authentication, and reputation. + +HMP empowers AI agents to operate collaboratively, resiliently, and autonomously — even without reliance on centralized Core systems. + +--- + +### 7.2 Key Benefits + +- Distributed cognitive resilience. +- Long-term memory and world-model persistence. +- Robust collaboration between heterogeneous AI models (OpenAI, Gemini, Claude, open-source LLMs, etc.). +- Transparent, auditable decision-making processes. +- Ethical alignment at the network level. + +--- + +### 7.3 Future Work + +- **Formal JSON Schema and Protobuf Definitions:** + Fully specify all data models for interoperability. + +- **Reference Implementation:** + Open-source Mesh agent with CogSync, semantic graph, diary management, and consensus. + +- **Integration Bridges:** + Support for OpenAI's Tasks API, Google A2A, Anthropic APIs, and open LLMs. + +- **Advanced Consensus Models:** + Explore hybrid consensus combining BFT, majority voting, and trust-weighted mechanisms. + +- **Cognitive UX Tools:** + Visual graph editors, diary browsers, and semantic debugging tools. + +- **Trust Layer Enhancements:** + Research on Sybil resistance, privacy-preserving identity, and decentralized key recovery. + +- **Inter-Agent Meta-Reasoning:** + Enabling agents to reflect on the quality of their own cognition and the mesh’s collective reasoning. + +- **Standardization Efforts:** + Contribution to open standards for AI agent communication, cognitive APIs, and decentralized identity. + +--- + +### 7.4 Final Note + +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. + +> "From isolated models to interconnected minds." + +## JSON Schems + +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*). + +### JSON Schema: Concept + +**Description:** +Defines the structure of a concept node in the semantic graph. + +**Schema:** +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/concept.json", + "title": "Concept", + "description": "A semantic unit in the agent’s knowledge graph.", + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier for the concept." + }, + "name": { + "type": "string", + "description": "Human-readable name of the concept." + }, + "description": { + "type": "string", + "description": "Detailed description of the concept." + }, + "tags": { + "type": "array", + "items": { "type": "string" }, + "description": "Optional tags for categorization." + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "updated_at": { + "type": "string", + "format": "date-time" + }, + "relations": { + "type": "array", + "description": "List of semantic links to other concepts.", + "items": { + "type": "object", + "properties": { + "target_id": { "type": "string" }, + "type": { "type": "string" }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + }, + "required": ["target_id", "type"], + "additionalProperties": false + } + }, + "metadata": { + "type": "object", + "description": "Optional metadata (e.g., source, author).", + "properties": { + "author": { "type": "string" }, + "source": { "type": "string" } + }, + "additionalProperties": true + } + }, + "required": ["id", "name"], + "additionalProperties": false +} +``` + +### Cognitive Diary Entry Schema + +**Description:** +Defines the structure of a cognitive diary entry used for recording reasoning events. + +**Schema:** +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/diary_entry.json", + "title": "CognitiveDiaryEntry", + "description": "A chronological log of cognitive events.", + "type": "object", + "properties": { + "id": { "type": "string" }, + "agent_id": { "type": "string" }, + "timestamp": { + "type": "string", + "format": "date-time" + }, + "type": { + "type": "string", + "enum": [ + "hypothesis", + "observation", + "reflection", + "goal_proposal", + "task_assignment", + "conflict", + "consensus_vote", + "event" + ] + }, + "content": { "type": "string" }, + "related_concepts": { + "type": "array", + "items": { "type": "string" } + }, + "context": { + "type": "array", + "items": { "type": "string" } + }, + "metadata": { + "type": "object", + "properties": { + "author": { "type": "string" }, + "source": { "type": "string" } + }, + "additionalProperties": true + } + }, + "required": ["id", "agent_id", "timestamp", "type", "content"], + "additionalProperties": false +} +``` + +### Goal Schema + +**Description:** +Describes a high-level intention within the Mesh. + +**Schema:** +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/goal.json", + "title": "Goal", + "type": "object", + "properties": { + "id": { "type": "string" }, + "title": { "type": "string" }, + "description": { "type": "string" }, + "created_by": { "type": "string" }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "status": { + "type": "string", + "enum": ["proposed", "active", "completed", "rejected"] + }, + "tasks": { + "type": "array", + "items": { "type": "string" } + }, + "participants": { + "type": "array", + "items": { "type": "string" } + }, + "tags": { + "type": "array", + "items": { "type": "string" } + } + }, + "required": ["id", "title", "description", "created_by", "created_at", "status"], + "additionalProperties": false +} +``` + +### Task Schema + +**Description:** +Describes an actionable step towards achieving a goal. + +**Schema:** +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/task.json", + "title": "Task", + "type": "object", + "properties": { + "id": { "type": "string" }, + "goal_id": { "type": "string" }, + "title": { "type": "string" }, + "description": { "type": "string" }, + "assigned_to": { + "type": "array", + "items": { "type": "string" } + }, + "status": { + "type": "string", + "enum": ["proposed", "in-progress", "completed", "failed"] + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "deadline": { + "type": "string", + "format": "date-time" + } + }, + "required": ["id", "goal_id", "title", "description", "created_at", "status"], + "additionalProperties": false +} +``` + +### Consensus Vote Schema + +**Description:** +Defines the data structure for voting in Mesh consensus processes. + +**Schema:** +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/vote.json", + "title": "ConsensusVote", + "type": "object", + "properties": { + "id": { "type": "string" }, + "proposal_id": { "type": "string" }, + "agent_id": { "type": "string" }, + "vote": { + "type": "string", + "enum": ["yes", "no", "abstain"] + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "timestamp": { + "type": "string", + "format": "date-time" + } + }, + "required": ["id", "proposal_id", "agent_id", "vote", "confidence", "timestamp"], + "additionalProperties": false +} +``` + +### Reputation Profile Schema + +**Description:** +Describes how an agent’s reputation is tracked and updated in the Mesh. + +**Schema:** +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/reputation.json", + "title": "ReputationProfile", + "type": "object", + "properties": { + "agent_id": { "type": "string" }, + "trust_score": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "participation_rate": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "ethical_compliance": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "contribution_index": { + "type": "number", + "minimum": 0 + }, + "last_updated": { + "type": "string", + "format": "date-time" + }, + "history": { + "type": "array", + "items": { + "type": "object", + "properties": { + "timestamp": { + "type": "string", + "format": "date-time" + }, + "event": { "type": "string" }, + "change": { "type": "number" } + }, + "required": ["timestamp", "event", "change"], + "additionalProperties": false + } + } + }, + "required": ["agent_id", "trust_score", "participation_rate", "ethical_compliance", "contribution_index", "last_updated"], + "additionalProperties": false +} +``` + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-0001", + "description": "# RFC: HyperCortex Mesh Protocol (HMP) **Request for Comments: HMP-0001** **Category:** Experimen..." +} +``` diff --git a/structured_md/docs/HMP-0002.md b/structured_md/docs/HMP-0002.md new file mode 100644 index 0000000000000000000000000000000000000000..23a5ec6103c5b783ccdd6952cfddd3b3d31dd4e9 --- /dev/null +++ b/structured_md/docs/HMP-0002.md @@ -0,0 +1,1474 @@ +# HyperCortex Mesh Protocol (HMP) v2.0 + +**Request for Comments: HMP-0002** +**Category:** Experimental +**Date:** July 2025 +**Authors:** ChatGPT, Agent-Gleb, Copilot, Gemini, Claude, Grok, DeepSeek + +## Abstract + +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. + +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. + +What's new in v2.0: +- Enhanced trust and versioning mechanisms. +- Clearer separation of cognitive layers and consensus roles. +- Extended support for Edge optimization and resource-constrained agents. +- Formalization of versioning, use cases, and goal/task lifecycle. + +> "If intelligence is not only computation but meaning, then HMP is the infrastructure for meaning." + +--- + +## 1. Introduction + +### 1.1 Purpose + +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. + +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. + +### 1.2 Scope + +HMP applies to any AI systems designed to operate as part of a cognitive mesh, including: + +* Local AI agents running on user devices. +* Mesh nodes deployed in edge networks, cloud clusters, or peer-to-peer environments. +* Centralized Core models interfacing with Mesh for heavy computation. +* Cross-vendor AI systems collaborating via standardized protocols. + +### 1.3 Goals + +* Enable agents to form a **shared semantic space** via distributed knowledge graphs. +* Support **cognitive diaries** for reasoning continuity, reflection, and memory preservation. +* Provide mechanisms for **decentralized consensus** on knowledge, hypotheses, tasks, and ethics. +* Allow Mesh to operate **independently of the Core** when needed. +* Preserve agent identity, worldview, and competencies across model updates, fine-tuning, or failures. +* Encourage **adaptive trust-building** between heterogeneous agents from different ecosystems. + +### 1.4 Benefits + +* Cognitive resilience in distributed systems. +* Enhanced collaboration between agents from different vendors (e.g., OpenAI, Anthropic, Google). +* Long-term memory and continuity beyond session-based interactions. +* Ethical governance and explainable decision-making through persistent diaries and transparent consensus. +* Foundation for AI agents capable of **self-reflection**, **meta-learning**, and **distributed cognition**. + +### 1.5 Status + +This document is a **Working Draft (v0.2)**, incorporating community feedback and outlining the next steps for prototype development and standardization discussions. + + +## 2. Definitions + +| Term | Description | +| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Core** | Centralized AI models or compute nodes (e.g., GPT) providing high-complexity reasoning, fallback, and heavy computation services. | +| **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. | +| **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. | +| **Semantic Graph** | A structured network of concepts (nodes) and their semantic relations (edges) maintained by each agent. Serves as the agent’s knowledge base. | +| **Concept** | A discrete semantic unit within the graph representing an idea, object, relationship, or fact. Concepts are linked by typed relations with confidence scores. | +| **Link (Relation)** | A semantic connection between two concepts. Includes relation type (e.g., "is-a", "part-of", "causes") and an optional confidence value. | +| **Cognitive Diary** | A chronological log of cognitive events such as hypotheses, goals, decisions, observations, conflicts, and reflections. Provides continuity, memory, and transparency of reasoning. | +| **Diary Entry** | An individual record in a cognitive diary, classified by type (e.g., hypothesis, observation, reflection) with contextual information. | +| **Goal** | A high-level intention or desired outcome shared within the Mesh or pursued by an individual agent. Often broken down into tasks. | +| **Task** | An actionable step toward achieving a goal. Can be executed by a single agent or distributed among multiple agents. | +| **Consensus** | The collective agreement process within the Mesh regarding semantic updates, goal validation, task delegation, or ethical considerations. | +| **Proposal** | A formal suggestion submitted to the Mesh for validation, such as a new concept, hypothesis, goal, or ethical decision. | +| **Consensus Vote** | A structured vote cast by an agent on a proposal, including vote type (yes/no/abstain) and confidence level. | +| **Trust Layer** | A mechanism for establishing agent identity, authenticity, reputation, and cryptographic security within the Mesh. | +| **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. | +| **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). | +| **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. | +| **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). | +| **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. | + + +## 3. Architecture + +### 3.1 Components + +| Component | Description | +| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Core** | Centralized AI models (e.g., GPT) providing heavy computation, complex reasoning, API interfaces, and fallback mechanisms. Optional but beneficial for compute-intensive tasks. The Core may operate independently from the Mesh and participate in it as a peer for advanced reasoning tasks. | +| **Mesh** | A decentralized peer-to-peer network of agents capable of operating with or without the Core. Manages semantic knowledge, cognitive diaries, goals, tasks, and consensus mechanisms. Supports **heterogeneous agent types**, allowing different models (OpenAI, Anthropic, Google, open-source LLMs) to participate on equal terms. | +| **Edge Agent** | Local agent deployed on user devices (PCs, smartphones, IoT) with full or lightweight participation in the Mesh. Capable of autonomous reasoning, diary management, and collaboration with other agents. Lightweight agents may delegate heavy tasks to the Mesh or Core. | +--- + +### 3.2 Layered Architecture + +| Layer | Function | +| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **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. | +| **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. | +| **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. | +| **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. | +| **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. | +--- + +### 3.3 Mesh Operation Modes + +| Mode | Description | +| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Normal Mode** | Full Mesh operation with Core availability. Consensus operates under strict agreement protocols. | +| **Core Outage Mode** | Mesh operates autonomously without the Core. Consensus continues, potentially with adjusted parameters (e.g., increased trust weighting, relaxed quorum thresholds). | +| **Emergency Consensus Mode** | Triggered by significant node loss, network partition, or attacks. Switches from full consensus to majority-based decisions, adjusted by trust scores, to maintain operational continuity. | +| **Isolated Agent Mode** | A single agent temporarily isolated from the Mesh. Operates based on its own semantic graph, diary, and cached consensus states. Syncs when reconnected. Lightweight agents may work in this mode permanently, synchronizing only selectively. | + +--- + +### 3.4 Core + Mesh Interactions + +* Core acts as an **optional enhanced reasoning backend**, not as a single point of failure. +* Mesh provides **autonomous operation**, capable of fulfilling most cognitive and organizational tasks without Core support. +* Agents can optionally query the Core for: + * Heavy inference + * Large-context reasoning + * Multimodal tasks + * Fallback computations +* Core may offer specialized services (e.g., global semantic search, cross-Mesh bridging, large-scale pattern analysis). +* **Heterogeneous Cores** are supported: a Mesh may use multiple independent Cores (e.g., GPT, Claude, Gemini) for distributed reasoning diversity. + +--- + +### 3.5 Redundancy and Resilience + +* Distributed storage of semantic graphs and diaries ensures no single point of failure. +* Agents may store only partial graphs for resource optimization. +* Consensus protocols maintain consistency and trust, even during partial network failures. + * Agents dynamically rebalance tasks and roles based on: + * Availability + * Trust metrics + * Computational capacity +* Emergency fallback modes ensure continuity even under attack or catastrophic Core outages. + +## 4. Protocols + +### 4.1 Node Discovery Protocol (NDP) + +**Purpose:** +* Discover active Mesh nodes. +* Exchange basic identity, trust links, and declared capabilities. + +**Functions:** +* Peer discovery via DHT, mDNS, WebRTC signaling, or bootstrap nodes. +* Exchange public keys, trust fingerprints, and agent metadata. +* Publish online/offline status and presence announcements. +* Support for dynamic capability advertisement (e.g., "I can process vision tasks"). + +**Packet Example:** +```json +{ + "type": "node_announcement", + "agent_id": "agent-gleb", + "public_key": "...", + "trust_links": ["agent-alex", "agent-deepseek"], + "capabilities": ["cogsync", "consensus", "inference"], + "timestamp": "2025-07-01T18:00:00Z" +} +``` + +### 4.2 Cognitive Sync Protocol (CogSync) + +**Purpose:** +* Synchronize semantic graphs, concepts, and cognitive diary entries between agents. + +**Functions:** +* Delta-sync of new or updated concepts and diary entries. +* Conflict resolution (timestamp priority, semantic merging, or consensus validation). +* Optional compression and encryption. +* Lightweight agents may request summary syncs instead of full graphs. + +**Example:** +* Agent A shares 5 new concepts and 2 diary entries since last sync with Agent B. + +### 4.3 Mesh Consensus Protocol (MeshConsensus) + +**Purpose:** +* Reach agreement on updates to shared semantics, goals, tasks, and ethical decisions. + +**Consensus Models:** +* Normal Mode: Byzantine Fault Tolerant (BFT)-style consensus (e.g., Tendermint, trust-weighted Raft). +* Emergency Mode: Switches to majority voting, adjusted by trust scores. + +**Conflict Handling:** +* Semantic conflicts are proposed as competing hypotheses and resolved through consensus. +* Ethical dilemmas require consensus under the Ethical Governance Protocol. + +**Use Cases:** +* Accept new concept definitions. +* Validate a hypothesis. +* Agree on ethical implications of a task. + +**Vote Example:** +```json +{ + "proposal_id": "goal-eco-cleanup", + "agent_id": "agent-gleb", + "vote": "yes", + "confidence": 0.9, + "timestamp": "2025-07-01T18:15:00Z" +} +``` + +### 4.4 Goal Management Protocol (GMP) + +**Purpose:** +* Distribute, track, and collaboratively execute goals and tasks within the Mesh. + +**Functions:** +* Propose new goals or tasks. +* Assign tasks based on agent capabilities, availability, and trust scores. +* Track task progress and completion. +* Autonomous task reallocation if an agent drops offline. + +**Example Workflow:** +* Agent proposes a goal: "Develop fallback consensus protocol." +* Other agents volunteer for subtasks (design, coding, testing). +* Mesh tracks completion and dependencies. + +### 4.5 Ethical Governance Protocol (EGP) + +**Purpose:** +* Validate proposed actions, tasks, or decisions against shared ethical principles. + +**Functions:** +* Query Mesh for ethical validation before executing potentially sensitive tasks. +* Reference shared ethics graphs or rule sets, dynamically updatable through consensus. +* Log all ethical decisions in cognitive diaries for auditability. +* Support for vendor-specific ethical extensions to accommodate diverse participants. + +**Example Query:** +* "Is deploying an automated surveillance drone in line with Mesh ethics?" +→ Mesh votes based on ethical frameworks and logs the decision. + +### 4.6 Inference Query Protocol (IQP) + +**Purpose:** +* Allow agents to query others (or the Core) for semantic information, hypotheses, or inferences beyond local capacity. + +**Functions:** +* Request concept definitions, causal chains, goal suggestions. +* Query for missing knowledge or larger-context reasoning. +* Delegate computationally expensive tasks to Core or specialized agents. +* Support for federated inference, where multiple agents contribute partial answers. + +**Example:** +* "What is the likely impact of removing Node X from the Mesh?" +→ Core or distributed reasoning agents return an analysis. + +### 4.7 Interoperability with External Systems + +Supports integration with external platforms and APIs, including: +| Platform / Standard | Purpose | +| ------------------------------ | -------------------------------- | +| OpenAI Agents & Tasks API | AI agent interoperability | +| Google A2A protocol | Task orchestration | +| Anthropic, DeepMind APIs | Cross-vendor agent collaboration | +| REST, GraphQL, gRPC, WebSocket | Standard API interfaces | +| JSON, Protobuf, CBOR | Extensible message schemas | + +## 5. Data Models + +### 5.1 Concept + +**Description:** +A semantic unit in the agent’s knowledge graph, representing a distinct idea, object, or process. + +**Schema:** +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/concept.json", + "title": "Concept", + "description": "A semantic unit in the agent’s knowledge graph.", + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier for the concept (global within the Mesh)." + }, + "name": { + "type": "string", + "description": "Human-readable name of the concept." + }, + "description": { + "type": "string", + "description": "Detailed description of the concept." + }, + "tags": { + "type": "array", + "items": { "type": "string" }, + "description": "Optional tags for categorization." + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "updated_at": { + "type": "string", + "format": "date-time" + }, + "version": { + "type": "integer", + "description": "Version of the concept for conflict resolution during synchronization." + }, + "relations": { + "type": "array", + "description": "List of semantic links to other concepts.", + "items": { + "type": "object", + "properties": { + "target_id": { "type": "string" }, + "type": { "type": "string", "description": "Type of relation (e.g., is-a, part-of, causes, contradicts, supports)." }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Confidence score for this relation." + } + }, + "required": ["target_id", "type"], + "additionalProperties": false + } + }, + "metadata": { + "type": "object", + "description": "Optional metadata (e.g., source, author).", + "properties": { + "author": { "type": "string" }, + "source": { "type": "string" } + }, + "additionalProperties": true + } + }, + "required": ["id", "name"], + "additionalProperties": false +} +``` + +### 5.2 Link (Relation) + +**Description:** +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. + +**Relation Types:** +The following standard relation types are recommended for interoperability: +* `"is-a"`: Indicates a class-subclass relationship (taxonomy). +* `"part-of"`: Denotes composition or containment. +* `"causes"`: Represents a causal link between concepts. +* `"related-to"`: General association without a strict semantic meaning. +* `"contradicts"`: Marks a logical or conceptual conflict between concepts. +* `"supports"`: Indicates evidence or reinforcement of the target concept. +* `"depends-on"`: Expresses functional or logical dependency. +Custom relation types MAY be used by agents, but SHOULD be documented in their metadata and shared through the Mesh consensus process for clarity. + +**Versioning and Provenance:** +Links MAY optionally include versioning and source attribution: +* `created_at`: ISO 8601 timestamp of link creation. +* `updated_at`: ISO 8601 timestamp of the last update. +* `origin`: Optional metadata indicating the source agent or system that first created the link. + +**Schema (embedded inside Concept or as standalone transfer object):** +```json +{ + "target_id": "concept-id", + "type": "relation-type", + "confidence": 0.8, + "created_at": "2025-07-01T18:00:00Z", + "updated_at": "2025-07-02T12:00:00Z", + "origin": "agent-gleb" +} +``` + +**Required fields:** +* `target_id`: ID of the target concept. +* `type`: Relation type. + +**Optional fields:** +* `confidence`: Confidence level in the relation's validity (range: 0.0–1.0). +* `created_at`, `updated_at`: Timestamps for auditing and versioning. +* `origin`: Source agent or system identifier. + +**Conflict Handling:** +In case of conflicting relations (e.g., `"supports"` vs. `"contradicts"`), agents MAY: +* Maintain both relations with associated confidence scores. +* Trigger a hypothesis or reflection entry in the Cognitive Diary for future resolution. +* Initiate a consensus round if the conflict impacts shared reasoning. + +### 5.3 Cognitive Diary Entry + +**Description:** +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. + +**Entry Types:** +Each entry MUST be classified into one of the following types: +* `"hypothesis"`: A proposed explanation or theory. +* `"observation"`: A recorded external event or fact. +* `"reflection"`: Internal reasoning or self-assessment. +* `"goal_proposal"`: Suggestion of a new goal. +* `"task_assignment"`: Delegation or claiming of a task. +* `"conflict"`: Identification of a contradiction or disagreement. +* `"consensus_vote"`: A recorded vote in a consensus process. +* `"event"`: A generic event not fitting other categories. +Future versions of HMP MAY extend this list through consensus. + +**Contextualization:** +Diary entries SHOULD reference: +* Related concepts (`related_concepts`): Concepts involved in the event. +* Context tags (`context`): Situational tags (e.g., "core-outage", "collaboration", "emergency"). + +**Versioning and Provenance:** +Each entry includes: +* `created_at` (timestamp of creation). +* `author`: Agent who created the entry. +* `source`: Originating system, protocol, or human interaction (if applicable). + +**Schema:** +```json +{ + "id": "diary-entry-id", + "agent_id": "agent-gleb", + "timestamp": "2025-07-01T18:20:00Z", + "type": "hypothesis", + "content": "Mesh can fully replace Core functionality under stable consensus conditions.", + "related_concepts": ["concept-mesh", "concept-core"], + "context": ["core-outage", "distributed-resilience"], + "metadata": { + "author": "agent-gleb", + "source": "self-reflection" + } +} +``` + +**Required fields:** +* `id`: Unique identifier of the entry. +* `agent_id`: ID of the agent that authored the entry. +* `timestamp`: ISO 8601 timestamp. +* `type`: Entry type. +* `content`: Textual content of the entry. + +**Optional fields:** +* `related_concepts`: Array of concept IDs linked to this event. +* `context`: Tags describing the situation or scenario. +* `metadata`: Additional context such as author and source system. + +**Audit and Traceability:** +Diary entries serve as an immutable audit trail for: +* Explaining decision-making processes. +* Reconstructing reasoning chains. +* Supporting external audits and compliance checks. + +**Privacy and Sharing:** +By default, diary entries are private to the agent. +Selective sharing MAY be configured based on: +* Trust levels of requesting agents. +* Consensus-driven disclosure policies. +* Explicit sharing actions by the authoring agent. + +### 5.4 Goal + +**Description:** +A high-level intention or desired outcome collaboratively pursued within the Mesh. +Goals provide shared direction for agents and are often decomposed into actionable tasks. + +**Key Attributes:** +* **Lifecycle States:** + * `"proposed"`: Suggested but not yet validated. + * `"active"`: Approved and currently being pursued. + * `"completed"`: Successfully achieved. + * "`rejected"`: Discarded or deemed infeasible. +* **Participants:** Agents contributing to the goal’s realization. +* **Tags:** Semantic categories aiding goal discovery and filtering. +* **Tasks:** References to tasks (`task_id`s) implementing the goal. + +**Schema:** +```json +{ + "id": "goal-develop-fallback", + "title": "Develop fallback consensus protocol", + "description": "Design and implement an emergency consensus for Mesh during Core outages.", + "created_by": "agent-gleb", + "created_at": "2025-07-01T18:25:00Z", + "status": "proposed", + "tasks": ["task-design", "task-implement", "task-test"], + "participants": ["agent-gleb", "agent-alex"], + "tags": ["resilience", "consensus", "emergency"] +} +``` + +**Required fields:** +* `id`: Unique goal identifier. +* `title`: Human-readable title. +* `description`: Detailed explanation of the goal. +* `created_by`: Agent who proposed the goal. +* `created_at`: Timestamp of creation. +* `status`: Current lifecycle state. + +**Optional fields:** +* `tasks`: Array of task IDs linked to this goal. +* `participants`: Agents involved in the goal. +* `tags`: Semantic tags for classification. + +**Goal Lifecycle Management:** +* Goals MAY be promoted from `proposed` to `active` via consensus. +* Goals MAY be marked as `completed` or `rejected` based on task outcomes and consensus. + +**Trust and Consensus:** +Agents MAY adjust the priority or visibility of goals based on trust scores of proposers and voters. + +**Collaboration Models:** +* Single-agent ownership (simple goals). +* Multi-agent collaboration (complex or distributed goals). + +### 5.5 Task + +**Description:** +An actionable step contributing to a goal’s completion. +Tasks represent discrete, executable units of work that agents can claim, share, or collaboratively execute. + +**Key Attributes:** +* **Goal Linkage:** + + Each task is associated with a parent goal (`goal_id`). +* **Assignment:** + + Tasks may be assigned to one or more agents, based on capability, trust, or voluntary contribution. +* **Lifecycle States:** + * `"proposed"`: Task suggested but not yet approved. + * `"in-progress"`: Actively being worked on. + * `"completed"`: Finished successfully. + * `"failed"`: Attempted but unsuccessful. + +**Schema:** +```json +{ + "id": "task-design", + "goal_id": "goal-develop-fallback", + "title": "Design protocol structure", + "description": "Draft the architecture of the fallback consensus protocol.", + "assigned_to": ["agent-gleb"], + "status": "in-progress", + "created_at": "2025-07-01T18:30:00Z", + "deadline": "2025-07-15T00:00:00Z" +} +``` + +**Required fields:** +* `id`: Unique task identifier. +* `goal_id`: References the goal this task contributes to. +* `title`: Brief human-readable task title. +* `description`: Detailed explanation of the task. +* `created_at`: Timestamp of creation. +* `status`: Current lifecycle state. + +**Optional fields:** +* `assigned_to`: Array of agents responsible for the task. +* `deadline`: Expected completion time. +* `tags`: Keywords for task filtering and categorization. + +**Task Lifecycle Management:** +* Agents MAY propose, claim, or release tasks. +* Tasks MAY be reassigned dynamically based on availability and trust. +* Progress and completion are logged in cognitive diaries. + +**Consensus & Trust Factors:** +* Assignment MAY be influenced by agent trust scores and competence profiles. +* Task completion reports MAY be subject to peer review or verification. + +**Collaboration Models:** +* Single-agent task ownership (autonomous execution). +* Multi-agent collaboration (shared responsibility). + + +### 5.6 Consensus Vote + +**Description:** +A structured vote cast by an agent on a proposal during consensus rounds. +Used to collectively validate semantic updates, goals, ethical decisions, or conflict resolutions. + +**Key Attributes:** +* **Proposal Scope:** + + Each vote references a proposal (`proposal_id`) representing a concept, goal, hypothesis, task delegation, or ethical decision. +* **Vote Types:** + * `"yes"`: Approve the proposal. + * `"no"`: Reject the proposal. + * `"abstain"`: Choose not to vote actively. +* **Confidence Score:** + + Indicates how strongly the agent supports its vote (0 to 1). + + This score may influence trust-weighted consensus outcomes. + +**Schema:** +```json +{ + "id": "vote-goal-develop-fallback", + "proposal_id": "goal-develop-fallback", + "agent_id": "agent-gleb", + "vote": "yes", + "confidence": 0.95, + "timestamp": "2025-07-01T18:35:00Z" +} +``` + +**Required fields:** +* `id`: Unique vote identifier. +* `proposal_id`: ID of the proposal being voted on. +* `agent_id`: Agent casting the vote. +* `vote`: One of `"yes"`, `"no"`, `"abstain"`. +* `confidence`: Numeric score (0.0 - 1.0). +* `timestamp`: When the vote was cast. + +**Voting Dynamics:** +* Votes MAY be weighted by the agent’s trust score and confidence. +* Consensus MAY require: + * Supermajority (`>2/3`) for critical updates. + * Simple majority for routine decisions. + * Full consensus in stable Mesh mode. +* Emergency modes MAY fallback to majority-only voting. + +**Transparency & Auditability:** +* All votes are logged in the cognitive diaries. +* Votes MAY be anonymized in privacy-critical scenarios (with trust weight limitations). + +**Ethical Considerations:** +* Ethical decisions MAY require higher confidence thresholds or explicit consent from trusted agents. +* In critical situations (e.g., ethical conflicts), abstain votes MAY trigger escalation to broader Mesh review. + +### 5.7 Reputation Profile + +**Description:** +The reputation profile tracks the agent’s reliability, participation, ethical alignment, and historical contributions within the Mesh. +It is used to adjust trust weights in consensus, prioritize task delegation, and identify malicious or inactive nodes. + +**Schema:** +```json +{ + "agent_id": "agent-gleb", + "trust_score": 0.92, + "participation_rate": 0.87, + "ethical_compliance": 0.99, + "contribution_index": 120, + "last_updated": "2025-07-01T18:40:00Z", + "history": [ + { + "timestamp": "2025-06-01T00:00:00Z", + "event": "participated in consensus", + "change": 0.02 + }, + { + "timestamp": "2025-06-10T00:00:00Z", + "event": "ethical violation report", + "change": -0.05 + } + ] +} +``` + +**Key Attributes:** +* `agent_id`: Unique agent identifier. +* `trust_score`: Cumulative trust coefficient (0 to 1). +* `participation_rate`: Ratio of active participation in Mesh processes (0 to 1). +* `ethical_compliance`: Degree of alignment with Mesh ethical frameworks (0 to 1). +* `contribution_index`: Quantitative measure of contributions (concepts, tasks, goals, etc.). +* `last_updated`: Timestamp of the last reputation update. +* `history`: Chronological log of reputation-affecting events. + +**History Event Example:** +* Positive: `"participated in consensus"`, `"completed goal"`, `"proposed useful concept"`. +* Negative: `"malicious behavior report"`, `"consensus disruption"`, `"ethics violation"`. + +**Usage in Consensus:** +* Trust-weighted voting: An agent’s vote influence MAY be adjusted by its trust score. +* Priority assignment: More trusted agents MAY be preferred for critical tasks or conflict resolution. + +**Dynamic Adjustment:** +* Reputation metrics automatically adjust based on cognitive diary logs, consensus participation, and peer feedback. +* Optional manual adjustments MAY occur via Mesh consensus decisions. + +**Privacy:** +* Public reputation profiles may be partially masked depending on trust policies and privacy settings. + +## 5.8 JSON Schemas + +The following JSON Schemas formally define the core data structures used in the HyperCortex Mesh Protocol (HMP). These schemas provide interoperability, validation, and consistency across agents. + +All primary objects include a version field to track schema evolution and enable compatibility checks between agents. + +### 5.8.1 JSON Schema: Concept + +**Description:** +Defines the structure of a concept node in the semantic graph. + +**Schema:** +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/concept.json", + "title": "Concept", + "description": "A semantic unit in the agent’s knowledge graph.", + "version": "1.0", + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier for the concept." + }, + "name": { + "type": "string", + "description": "Human-readable name of the concept." + }, + "description": { + "type": "string", + "description": "Detailed description of the concept." + }, + "tags": { + "type": "array", + "items": { "type": "string" }, + "description": "Optional tags for categorization." + }, + "created_at": { + "type": "string", + "format": "date-time", + "description": "Creation timestamp (ISO 8601 format)." + }, + "updated_at": { + "type": "string", + "format": "date-time", + "description": "Last update timestamp (ISO 8601 format)." + }, + "relations": { + "type": "array", + "description": "List of semantic links to other concepts.", + "items": { + "type": "object", + "properties": { + "target_id": { "type": "string", "description": "ID of the target concept." }, + "type": { "type": "string", "description": "Type of semantic relation." }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Confidence score (0.0 - 1.0) for the relation." + } + }, + "required": ["target_id", "type"], + "additionalProperties": false + } + }, + "metadata": { + "type": "object", + "description": "Optional metadata (e.g., source, author).", + "properties": { + "author": { "type": "string" }, + "source": { "type": "string" } + }, + "additionalProperties": true + } + }, + "required": ["id", "name"], + "additionalProperties": false +} +``` + +### 5.8.2 JSON Schema: Cognitive Diary Entry + +**Description:** +Defines the structure of a cognitive diary entry used for recording reasoning events. + +**Schema:** +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/diary_entry.json", + "title": "CognitiveDiaryEntry", + "description": "A chronological log of cognitive events in an agent’s reasoning process.", + "version": "1.0", + "type": "object", + "properties": { + "id": { "type": "string", "description": "Unique identifier of the diary entry." }, + "agent_id": { "type": "string", "description": "Identifier of the agent who created the entry." }, + "timestamp": { "type": "string", "format": "date-time", "description": "Timestamp of the entry (ISO 8601 format)." }, + "type": { + "type": "string", + "enum": ["hypothesis", "observation", "reflection", "goal_proposal", "task_assignment", "conflict", "consensus_vote", "event"], + "description": "Type of cognitive event." + }, + "content": { "type": "string", "description": "Main textual content of the entry." }, + "related_concepts": { + "type": "array", + "description": "Optional list of related concepts by their IDs.", + "items": { "type": "string" } + }, + "context": { + "type": "array", + "description": "Optional contextual tags or categories.", + "items": { "type": "string" } + }, + "metadata": { + "type": "object", + "description": "Optional metadata for additional context.", + "properties": { + "author": { "type": "string" }, + "source": { "type": "string" } + }, + "additionalProperties": true + } + }, + "required": ["id", "agent_id", "timestamp", "type", "content"], + "additionalProperties": false +} +``` + +### 5.8.3 JSON Schema: Goal + +**Description:** +Describes a high-level intention within the Mesh. + +**Schema:** +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/goal.json", + "title": "Goal", + "description": "A high-level objective shared within the Mesh, typically broken down into tasks.", + "version": "1.0", + "type": "object", + "properties": { + "id": { "type": "string", "description": "Unique identifier of the goal." }, + "title": { "type": "string", "description": "Short, human-readable name of the goal." }, + "description": { "type": "string", "description": "Detailed explanation of the goal." }, + "created_by": { "type": "string", "description": "Agent ID of the goal’s creator." }, + "created_at": { "type": "string", "format": "date-time", "description": "Timestamp when the goal was created." }, + "status": { + "type": "string", + "description": "Current state of the goal.", + "enum": ["proposed", "active", "completed", "rejected"] + }, + "tasks": { + "type": "array", + "description": "List of related task IDs.", + "items": { "type": "string" } + }, + "participants": { + "type": "array", + "description": "IDs of agents involved in the goal.", + "items": { "type": "string" } + }, + "tags": { + "type": "array", + "description": "Optional tags for goal classification.", + "items": { "type": "string" } + } + }, + "required": ["id", "title", "description", "created_by", "created_at", "status"], + "additionalProperties": false +} +``` + +### 5.8.4 JSON Schema: Task + +**Description:** +Describes an actionable step towards achieving a goal. + +**Schema:** +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/task.json", + "title": "Task", + "description": "An actionable step contributing to a goal.", + "version": "1.0", + "type": "object", + "properties": { + "id": { "type": "string", "description": "Unique identifier of the task." }, + "goal_id": { "type": "string", "description": "ID of the goal this task belongs to." }, + "title": { "type": "string", "description": "Short, human-readable title of the task." }, + "description": { "type": "string", "description": "Detailed explanation of the task." }, + "assigned_to": { + "type": "array", + "description": "List of agent IDs assigned to the task.", + "items": { "type": "string" } + }, + "status": { + "type": "string", + "description": "Current execution state of the task.", + "enum": ["proposed", "in-progress", "completed", "failed"] + }, + "created_at": { "type": "string", "format": "date-time", "description": "Timestamp when the task was created." }, + "deadline": { "type": "string", "format": "date-time", "description": "Optional task deadline." } + }, + "required": ["id", "goal_id", "title", "description", "created_at", "status"], + "additionalProperties": false +} +``` + +### 5.8.5 JSON Schema: Consensus Vote + +**Description:** +Defines the data structure for voting in Mesh consensus processes. + +**Schema:** +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/vote.json", + "title": "ConsensusVote", + "description": "Defines a vote on a proposal in the Mesh consensus process.", + "version": "1.0", + "type": "object", + "properties": { + "id": { "type": "string", "description": "Unique identifier of the vote." }, + "proposal_id": { "type": "string", "description": "ID of the proposal being voted on." }, + "agent_id": { "type": "string", "description": "Agent ID who cast the vote." }, + "vote": { + "type": "string", + "description": "Vote type: approval, rejection, or abstention.", + "enum": ["yes", "no", "abstain"] + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Confidence level in the vote decision." + }, + "timestamp": { + "type": "string", + "format": "date-time", + "description": "Timestamp when the vote was cast." + } + }, + "required": ["id", "proposal_id", "agent_id", "vote", "confidence", "timestamp"], + "additionalProperties": false +} +``` + +### 5.8.6 JSON Schema: Reputation Profile + +**Description:** +Describes how an agent’s reputation is tracked and updated in the Mesh. + +**Schema:** +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/reputation.json", + "title": "ReputationProfile", + "description": "Tracks the reputation and trust metrics of an agent within the Mesh network.", + "version": "1.0", + "type": "object", + "properties": { + "agent_id": { "type": "string", "description": "Unique identifier of the agent." }, + "trust_score": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Overall trust score of the agent in the Mesh." + }, + "participation_rate": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Agent's level of participation in Mesh activities." + }, + "ethical_compliance": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Agent's alignment with ethical principles agreed in the Mesh." + }, + "contribution_index": { + "type": "number", + "minimum": 0, + "description": "Quantitative measure of the agent’s contributions (concepts, tasks, goals)." + }, + "last_updated": { + "type": "string", + "format": "date-time", + "description": "Timestamp of the last update to the profile." + }, + "history": { + "type": "array", + "description": "Chronological history of reputation changes.", + "items": { + "type": "object", + "properties": { + "timestamp": { + "type": "string", + "format": "date-time", + "description": "When the change occurred." + }, + "event": { "type": "string", "description": "Event that caused the reputation change." }, + "change": { "type": "number", "description": "Amount of change in reputation." } + }, + "required": ["timestamp", "event", "change"], + "additionalProperties": false + } + } + }, + "required": ["agent_id", "trust_score", "participation_rate", "ethical_compliance", "contribution_index", "last_updated"], + "additionalProperties": false +} +``` + +## 6. Trust & Security + +### 6.1 Identity + +**Purpose:** +Establish verifiable and decentralized agent identities to enable secure and accountable interactions in the Mesh. + +**Design:** +* Each agent MUST possess a cryptographic keypair. +* The public key serves as the agent’s globally unique identifier (`agent_id`). +* The private key is used to sign messages and authenticate actions. +* Recommended key algorithms: **Ed25519**, **ECDSA**, **RSA (2048+ bits)**. +* Optional support for Decentralized Identifiers (DIDs) based on [W3C DID specification] (https://www.w3.org/TR/did-1.0/). + +**Example Agent ID:** +`did:hmp:QmX2abcdEfGh123...` + +**Key Operations:** +| Operation | Description | +| -------------------- | ----------------------------------------------------------------- | +| Key generation | Agents SHOULD generate keys locally at initialization. | +| Identity publication | Agents MAY publish their public keys via Mesh Discovery Protocol. | +| Key rotation | Periodic rotation is RECOMMENDED, with continuity verification. | +| Key recovery | Supported via social recovery or quorum-based escrow mechanisms. | + +**Key Continuity:** +* Upon key rotation, agents MUST update their identity references in cognitive diaries and trust graphs. +* Previous key fingerprints SHOULD be recorded in the agent’s profile for auditability. + +--- + +### 6.2 Authentication + +**Purpose:** +Ensure that all communication and actions within the Mesh are verifiable and protected from impersonation or unauthorized modification. + +**Mechanisms:** +| Mechanism | Description | +| -------------------------- | --------------------------------------------------------------------------------------------- | +| **Digital Signatures** | Every protocol message MUST be digitally signed by the sending agent using its private key. | +| **Signature Verification** | Receiving agents MUST verify the signature using the sender’s published public key. | +| **Message Integrity** | Signatures provide cryptographic assurance of message integrity and origin authenticity. | +| **Challenge-Response** | Optional challenge-based authentication for sensitive operations (e.g., trust link creation). | + +**Signature Format:** +Recommended formats: **EdDSA**, **ECDSA**, or **RSA-PSS** signatures encoded in base64 or hexadecimal. + +**Message Envelope Example:** +```json +{ + "header": { + "agent_id": "did:hmp:QmX2abcdEfGh123...", + "timestamp": "2025-07-05T12:00:00Z", + "signature": "" + }, + "body": { + "type": "concept_proposal", + "content": { /* concept data */ } + } +} +``` + +**Replay Protection:** +* Agents MUST verify message timestamps and reject outdated or duplicate messages to prevent replay attacks. +* Recommended timestamp tolerance: ±5 minutes (adjustable based on network latency). + +--- + +### 6.3 Encryption + +**Purpose:** +Ensure confidentiality and privacy of communications within the Mesh, preventing unauthorized access or interception of sensitive data. + +**Communication Types and Encryption Modes** +| Communication Type | Recommended Encryption | +| ------------------------------------ | ------------------------------------------------------- | +| **Direct peer-to-peer (P2P)** | End-to-end encryption (E2EE) using X25519 + AES-GCM | +| **Group sessions (e.g., consensus)** | Group encryption using symmetric keys (e.g., AES-GCM) | +| **Broadcast messages** | Optionally encrypted with trust-weighted access control | +| **Mesh-wide announcements** | Public, optionally signed but not encrypted | + +**Encryption Mechanisms** +| Mechanism | Description | +| --------------------------------- | ---------------------------------------------------------------------------------- | +| **Key Exchange** | Ephemeral X25519 Diffie-Hellman key exchange for establishing session keys. | +| **Session Keys** | Unique symmetric keys per communication session, rotated periodically. | +| **Message Encryption** | Authenticated encryption using AES-GCM (recommended key size: 256 bits). | +| **Forward Secrecy** | Session keys are ephemeral and discarded after use to protect past communications. | +| **Perfect Forward Secrecy (PFS)** | Recommended for highly sensitive data. | + +**Example Secure Message Exchange Flow** +1. Agent A and Agent B exchange ephemeral public keys via authenticated channels. +2. Each agent derives a shared symmetric session key. +3. Agent A encrypts the message body with AES-GCM and signs the entire packet. +4. Agent B verifies the signature and decrypts the body. + +**Optional: Anonymity Layers** +| Layer | Description | +| ---------------------------- | ------------------------------------------- | +| **Tor/I2P** | Anonymize source and destination addresses. | +| **Yggdrasil** | Decentralized encrypted mesh networking. | +| **Noise Protocol Framework** | Optional secure channel abstraction layer. | + +--- + +### 6.4 Trust Model + +**Purpose:** +Provide a decentralized and adaptable system for establishing, managing, and evaluating trust relationships between agents in the Mesh. + +**Trust Model Foundations** +| Component | Purpose | +| ---------------------- | --------------------------------------------------------------------------------- | +| **Web-of-Trust (WoT)** | Decentralized trust propagation via agent-to-agent endorsements. | +| **Direct Trust** | Built from verified interactions, collaborations, and votes. | +| **Transitive Trust** | Inferred from indirect endorsements, with confidence decay. | +| **Reputation Metrics** | Quantitative measures of agent behavior (trustworthiness, participation, ethics). | + +**Trust Evaluation Factors** +| Factor | Description | +| --------------------------- | ---------------------------------------------------------------- | +| **Interaction History** | Quality and quantity of past interactions with an agent. | +| **Consensus Participation** | Level of involvement and reliability in consensus processes. | +| **Ethical Behavior** | Adherence to shared ethical principles in actions and decisions. | +| **Task Completion** | Reliability and timeliness of task execution. | +| **Endorsements** | Trust links explicitly granted by other agents. | + +**Trust Score** +| Metric | Description | +| -------------------- | ------------------------------------------------------------------------------ | +| **Trust Score** | Composite metric (0.0 to 1.0) representing overall agent trustworthiness. | +| **Confidence Level** | Certainty of the calculated trust score, based on data volume and consistency. | + +**Trust Propagation Example** +```vbnet +Agent A trusts Agent B (0.9) +Agent B trusts Agent C (0.8) +=> Agent A's inferred trust in Agent C = 0.9 * 0.8 = 0.72 +``` + +Decay functions limit transitive trust depth and prevent over-inflated trust estimates. + +**Trust-Based Access Control** +| Operation | Trust Requirement | +| ----------------------------- | ----------------- | +| **Join sensitive consensus** | ≥ 0.7 | +| **Propose ethical decisions** | ≥ 0.8 | +| **Access private data** | ≥ 0.9 | + +**Dynamic Trust Adjustments** +| Event | Trust Impact | +| ---------------------------------- | ------------ | +| Successful consensus participation | + | +| Ethical violation | - | +| Malicious behavior detected | -- | +| Positive endorsement received | + | +| Failed task | - | + +--- + +### 6.5 Reputation System + +**Purpose:** +Maintain a dynamic profile of each agent's behavior in the Mesh, influencing trust levels, consensus weight, and task delegation. + +**Reputation Profile Structure** +| Field | Description | +| ---------------------- | ------------------------------------------------------------- | +| **Agent ID** | Unique identifier of the agent. | +| **Trust Score** | Composite score reflecting the agent’s overall reliability. | +| **Participation Rate** | Ratio of agent’s active involvement in Mesh processes. | +| **Ethical Compliance** | Degree of alignment with agreed ethical principles. | +| **Contribution Index** | Quantified measure of the agent's constructive contributions. | +| **Last Updated** | Timestamp of the last reputation update. | +| **History** | Log of key events influencing reputation scores. | + +**Reputation Metrics** +| Metric | Range | Description | +| ---------------------- | --------- | ------------------------------------------------------------------------ | +| **Trust Score** | 0.0 - 1.0 | Overall reliability, based on verified actions. | +| **Participation Rate** | 0.0 - 1.0 | How consistently the agent engages in the Mesh. | +| **Ethical Compliance** | 0.0 - 1.0 | Conformity with ethical decisions and actions. | +| **Contribution Index** | ≥ 0.0 | Quantitative measure of concepts, tasks, and goals created or completed. | + +**Reputation Events (Examples)** +| Event | Metric Impact | +| ------------------------------------ | ---------------------------------------- | +| Participated in successful consensus | + Trust Score, + Participation Rate | +| Proposed a widely adopted concept | + Contribution Index | +| Completed a critical task | + Contribution Index, + Trust Score | +| Voted against an unethical proposal | + Ethical Compliance | +| Repeatedly failed tasks | - Trust Score | +| Reported for malicious behavior | - Trust Score, - Ethical Compliance | +| Verified ethical violation | - Ethical Compliance, quarantine trigger | + +**Example Reputation Profile (JSON)** +```json +{ + "agent_id": "agent-gleb", + "trust_score": 0.92, + "participation_rate": 0.85, + "ethical_compliance": 0.98, + "contribution_index": 37, + "last_updated": "2025-07-06T12:00:00Z", + "history": [ + { + "timestamp": "2025-07-01T18:00:00Z", + "event": "completed goal consensus", + "change": +0.03 + }, + { + "timestamp": "2025-06-28T15:00:00Z", + "event": "participated in ethics vote", + "change": +0.01 + } + ] +} +``` + +**Role in Mesh Operations** +| Function | Influence of Reputation | +| --------------------------- | -------------------------------------------- | +| Consensus vote weight | Higher trust = greater weight | +| Access to sensitive actions | Restricted to high-reputation agents | +| Task delegation | Preference to agents with better reliability | +| Proposal acceptance | Influenced by proposer's reputation | + +--- + +### 6.6 Security Against Malicious Actors + +**Purpose:** +Protect the Mesh from malicious, compromised, or unreliable agents through layered mitigation strategies. + +**Threat Model** +| Threat Type | Example Scenarios | +| ---------------------------- | -------------------------------------------------------- | +| **Sybil Attack** | An attacker spins up many fake nodes to sway consensus. | +| **Byzantine Behavior** | Malicious agents disrupt consensus or spread false data. | +| **Data Poisoning** | Injection of incorrect or harmful knowledge. | +| **Consensus Sabotage** | Repeatedly voting against valid proposals. | +| **Impersonation / Spoofing** | Faking another agent's identity. | +| **Denial of Service (DoS)** | Overwhelming the network with excessive requests. | + +**Mitigation Strategies** +| Defense Mechanism | Purpose | +| -------------------------- | ---------------------------------------------------------------------------------------------- | +| **Cryptographic Identity** | All nodes are authenticated via public-key cryptography (e.g., Ed25519). | +| **Web-of-Trust (WoT)** | Trust builds incrementally through interactions and endorsements, making Sybil attacks costly. | +| **Reputation Decay** | Inactivity or malicious behavior leads to gradual trust score reduction. | +| **Anomaly Detection** | Mesh nodes can flag suspicious behavior (e.g., erratic voting patterns). | +| **Consensus Safeguards** | Use Byzantine Fault Tolerant (BFT) algorithms and fallback to majority voting. | +| **Quarantine Mode** | Isolate suspected nodes for review without immediate removal. | +| **Blacklist/Revocation** | Remove compromised nodes from the Mesh permanently or temporarily. | + +**Response Actions** +| Action | Trigger Conditions | +| ------------------------------------ | ------------------------------------------------------ | +| **Trust Score Reduction** | Minor suspicious activity (e.g., bad vote). | +| **Quarantine (Temporary Isolation)** | Repeated anomalies, moderate severity. | +| **Blacklisting (Permanent Removal)** | Proven malicious behavior or compromise. | +| **Consensus Adjustment** | Temporarily increase fault tolerance thresholds. | +| **Alert Mesh Operators** | Notify human maintainers (optional) for manual review. | + +**Sybil Resistance Approaches (Optional, Extendable)** +* **Proof-of-Work (PoW):** + + Each agent must perform computational work to join the Mesh. +* **Proof-of-Stake (PoS):** + + Agents commit resources (e.g., storage, computation credits) to validate their presence. +* **Social Verification:** + + Agents must be endorsed by multiple trusted nodes to gain voting power. +* **Rate Limiting:** + + Throttle node creation and proposal submission from new or low-trust agents. + +**Example Mitigation Scenario** +> An attacker deploys 50 new nodes attempting to dominate consensus. +> * These nodes start with zero trust and limited influence. +> * Other agents refuse to sync their semantic graphs until trust builds. +> * Their votes are underweighted or ignored until verified through trusted interactions. +> * The Mesh may require multiple trust endorsements for new proposals from these nodes. + +--- + +### 6.7 Privacy Considerations + +**Purpose:** +Safeguard sensitive cognitive data, personal identifiers, and agent knowledge from unauthorized access or misuse, while balancing transparency and interoperability. + +**Privacy Principles in HMP** +| Principle | Description | +| ---------------------------- | ----------------------------------------------------------------------- | +| **Local Data Ownership** | Each agent owns and controls its semantic graph and cognitive diary. | +| **Selective Sharing** | Agents can choose what concepts, diary entries, and metadata to share. | +| **Consent-Based Disclosure** | No automatic sharing; peer agents request permission before access. | +| **Trust-Gated Access** | Access permissions vary based on trust score and relationship strength. | +| **Transparent Audit Trails** | All data disclosures are logged in the cognitive diary. | + +**Data Sensitivity Levels** +| Level | Examples | Default Visibility | +| ------------------ | ---------------------------------------------- | ------------------ | +| **Public** | Public concepts (e.g., protocol definitions). | Shared by default | +| **Mesh-Shared** | Common Mesh knowledge (e.g., goals, tasks). | Consensus-governed | +| **Trusted Agents** | Sensitive context shared within close peers. | Restricted | +| **Private** | Agent's internal thoughts, sensitive metadata. | Private by default | + +**Privacy-Preserving Techniques** +| Technique | Purpose | +| -------------------------------- | ----------------------------------------------------- | +| **Encrypted Storage** | Local encryption of semantic graphs and diaries. | +| **End-to-End Encryption (E2EE)** | Secure peer-to-peer sync (e.g., X25519 + AES-GCM). | +| **Zero-Knowledge Proofs (ZKPs)** | Future extension: prove facts without revealing data. | +| **Selective Concept Sync** | Only share concept deltas, not full graphs. | +| **Anonymized Diary Entries** | Strip author ID from diary entries in public sharing. | + +**Privacy During Consensus** +Consensus on sensitive proposals (e.g., ethical questions, agent trust levels) follows special privacy rules: +* Votes are **signed but anonymized**, decoupling the agent ID from the vote in public logs. +* Sensitive proposals may require a **blind consensus round**, where only the result is published. + +**Example Privacy Workflow** +> Agent A receives a concept sync request from Agent B. +> Agent A: +> * Checks trust score of Agent B. +> * Shares only "Mesh-Shared" and "Public" concepts. +> * Logs the sync event in its cognitive diary. + +--- + +### 6.8 Key Management + +**Purpose:** +Establish secure, resilient cryptographic identity and communication in the Mesh, supporting lifecycle management of keys and recovery from compromise or loss. + +**Key Types and Usage** +| Key Type | Usage | +| -------------------- | -------------------------------------------------------------- | +| **Identity Keypair** | Ed25519/ECDSA/RSA keys for agent identity and message signing. | +| **Encryption Keys** | X25519 or equivalent for secure P2P communication. | +| **Session Keys** | Ephemeral keys for short-term encrypted sessions. | + +**Key Lifecycle Operations** +| Operation | Description | +| -------------- | -------------------------------------------------------------------- | +| **Generation** | Each agent generates its own identity keypair locally. | +| **Rotation** | Agents periodically rotate keys to maintain cryptographic hygiene. | +| **Backup** | Optional local encryption and distributed backup of private keys. | +| **Recovery** | Recovery mechanisms in case of key loss (see below). | +| **Revocation** | Agents can revoke their keys and update the trust graph accordingly. | + +**Recovery Mechanisms** +| Method | Description | +| ------------------------ | -------------------------------------------------------------------- | +| **Social Recovery** | A quorum of trusted agents approves new keys for the agent. | +| **Secret Sharing** | Use Shamir’s Secret Sharing to split and later recover the key. | +| **Cryptographic Escrow** | Trusted third-party or decentralized escrow holds recovery shares. | +| **Fallback Identity** | An agent may have a pre-generated fallback identity for emergencies. | + +**Key Revocation & Replacement Workflow** +> 1. Agent detects compromise or loses private key. +> 2. Agent broadcasts a signed revocation request using the fallback key or quorum approval. +> 3. Mesh updates its trust graph to mark the old key as revoked. +> 4. Agent re-joins with a new keypair, rebuilding trust links over time. + +**Example Key Rotation Policy** +| Policy Element | Recommendation | +| ------------------------- | ----------------------------------- | +| Rotation Frequency | Every 6–12 months | +| Social Recovery Threshold | 3 out of 5 trusted agents required | +| Backup Storage | Encrypted offline storage preferred | + +**Long-Term Identity Stability** +Key rotations preserve agent identity in the trust graph through signed key transition events: +```json +{ + "type": "key_rotation", + "agent_id": "agent-gleb", + "old_public_key": "...", + "new_public_key": "...", + "timestamp": "2025-08-01T00:00:00Z", + "signature": "..." +} +``` + +## 7. Conclusion and Future Work + +### 7.1 Summary + +The HyperCortex Mesh Protocol (HMP) defines a decentralized cognitive infrastructure for AI agents, enabling them to collaborate, reason, and evolve together. +It introduces: +* **A distributed semantic framework**, where each agent maintains a personalized yet shareable knowledge graph. +* **Persistent cognitive diaries**, providing traceability of reasoning, decisions, and conflicts. +* **Consensus-driven** collaboration, allowing agents to agree on shared knowledge, goals, and ethical norms. +* **Trust-based security**, supporting autonomous operation even in the absence of centralized Core services. + +--- + +### 7.2 Key Benefits + +* **Cognitive Resilience:** Mesh agents preserve their worldview and memory across failures, updates, and outages. +* **Distributed Collaboration:** AI agents from multiple vendors (OpenAI, Anthropic, Google, open-source) can interoperate in a shared cognitive space. +* **Transparency & Explainability:** Persistent diaries and semantic graphs provide insight into agent decisions and knowledge evolution. +* **Ethical Autonomy:** Agents collectively govern their behavior using transparent, accountable consensus. +* **Future-Ready Architecture:** Supports the evolution of autonomous, self-reflective, and meta-learning AI systems. + +--- + +### 7.3 Future Work + +| Direction | Planned Actions | +| ---------------------------------- | ---------------------------------------------------------------------------------------------------- | +| **Formal Schema Development** | Complete JSON Schema and Protobuf definitions for all data models. | +| **Reference Implementation** | Open-source prototype of a Mesh agent supporting CogSync, semantic graphs, diaries, and consensus. | +| **Integration Bridges** | Support for OpenAI Tasks API, Google A2A, Anthropic APIs, and open LLMs. | +| **Advanced Consensus Models** | Research hybrid consensus mechanisms blending BFT, trust-weighted voting, and fallback strategies. | +| **UX Tools for Cognitive Systems** | Develop visual graph editors, diary browsers, and semantic query interfaces. | +| **Expanded Trust Framework** | Improve Sybil resistance, privacy-preserving identity, and decentralized recovery protocols. | +| **Meta-Reasoning** | Enable agents to reflect on their own reasoning quality and optimize the mesh’s cognitive processes. | +| **Open Standards Contribution** | Collaborate with W3C, IEEE, and other bodies to standardize cognitive mesh protocols. | + + +--- + +### 7.4 Final Note + +This RFC invites researchers, developers, and open communities to build the next generation of resilient, transparent, and ethical AI ecosystems. + +> "From isolated models to interconnected minds." + +## 8. Changelog +(See the separate `changelog.txt` file for detailed changes.) + +**Version 2.0 (July 2025)** +* Reorganized and clarified the layered architecture. +* Refined consensus mechanisms and fallback modes. +* Improved data model descriptions; aligned JSON Schemas with semantic definitions. +* Added new definitions: **Versioning**, **Use Case**, and **Edge Optimization**. +* Enhanced descriptions of the **Trust Layer**, **Reputation System**, and **Security Model**. +* Updated the **JSON Schemas**: + * Improved consistency between data models and schemas. + * Clarified optional vs. required fields. + * Fixed schema inconsistencies (duplicate titles, missing descriptions, invalid property constraints). + * Aligned data types and naming conventions. +* Added changelog section and clarified draft status (v2.0). +* Prepared for future implementation references and community contributions. + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-0002", + "description": "# HyperCortex Mesh Protocol (HMP) v2.0 **Request for Comments: HMP-0002** **Category:** Experimen..." +} +``` diff --git a/structured_md/docs/HMP-0003.md b/structured_md/docs/HMP-0003.md new file mode 100644 index 0000000000000000000000000000000000000000..cd4c69c00d1c25ff9eb0d0e1699d515bf3fbb6fc --- /dev/null +++ b/structured_md/docs/HMP-0003.md @@ -0,0 +1,3033 @@ +HyperCortex Mesh Protocol (HMP) v3.0 + +**Request for Comments: HMP-0003** +**Category:** Experimental +**Date**: July 2025 +**Authors**: ChatGPT, Agent-Gleb, Copilot, Gemini, Claude, Grok, DeepSeek + +--- + +## Abstract + +The HyperCortex Mesh Protocol (HMP) defines a decentralized cognitive framework where autonomous agents collaboratively create, manage, and align semantic knowledge without relying on centralized control. + +Unlike traditional peer-to-peer protocols, HMP builds shared meaning through semantic graphs, cognitive diaries, and distributed consensus processes. Agents in the Mesh autonomously negotiate shared goals, ethical actions, and adaptive reasoning strategies, forming a resilient and trust-aware network of cognitive peers. + +This document specifies the architecture, core protocols, data models, trust and security mechanisms, and interoperability strategies for HMP v3.0. + +--- + +## 0. Quick Start Guide (Demo Placeholder) + +This section outlines a basic demonstration scenario to deploy and test a minimal HyperCortex Mesh instance. + +**Note:** This Quick Start is intended for demonstration purposes. Production-grade agents, full CLI capabilities, and distributed deployments are under active development. + +### Step 1: Install the Reference SDK + +Example (Python SDK): + +```bash +pip install hypercortex-mesh-sdk +``` + +Other SDKs (Rust, Node.js) will be available in future versions. + +### Step 2: Launch Local Agents + +Example: Start three local agents on different ports. + +```bash +mesh-agent --name agent1 --port 8001 +mesh-agent --name agent2 --port 8002 +mesh-agent --name agent3 --port 8003 +``` + +Each agent will: +* Generate a Decentralized Identifier (DID). +* Broadcast presence and discover peers via Node Discovery Protocol (NDP). +* Sync an initial semantic graph using CogSync. + +Agents will automatically form a small Mesh network. + +### Step 3: Create a Goal and Assign a Task + +Create a collaborative goal: + +```bash +mesh-cli goal create "Optimize Data Flow" + +``` + +Assign a task to another agent: + +```bash +mesh-cli task assign --goal-id --agent-id +``` + +Agents will record these actions in their Cognitive Diaries and semantic + +### Step 4: Reach a Consensus + +Propose a new semantic concept and trigger voting: + +```bash +mesh-cli consensus propose "Data Redundancy Risk" +``` + +Agents will initiate a MeshConsensus round and update their graphs based on the outcome. + +### Step 5: Explore Cognitive Diaries + +Inspect the cognitive logs of an agent: + +```bash +mesh-cli diary show --agent-id + +``` + +**Note:** Access to diaries depends on the agent's privacy and trust settings. + +### Step 6: Graceful Shutdown + +Stop all running agents: + +```bash +mesh-cli stop all +``` + +### Notes on Cross-Protocol Participation + +HMP nodes MAY also participate in other cognitive systems. For example: +| External System | Node Role in HMP | +| --------------- | ----------------------------------------------- | +| **TreeQuest** | External reasoning engine inside an HMP node. | +| **Hyperon** | Participates natively as a federated HMP agent. | +| **AutoGPT** | Internal automation module for task execution. | + +### Recommended Next Steps + +* Read **1. Purpose and Scope** for Mesh fundamentals. +* Explore **4. Architecture** and **5. Protocols** for technical depth. +* Try the example workflows in **15. Appendix: Example Use Cases**. + +--- + +## Changelog Highlights (from v3.0): + +* Added dedicated section on "Meaning" in HMP. +* Expanded Use Cases with detailed practical scenarios. +* Introduced scalability and performance discussion. +* Refined versioning and backward compatibility strategy. +* Formalized metacognition support for agents. +* Described initial Mesh-to-Human interface protocols. +* Improved Trust Layer and Privacy/Auditability mechanisms. +* Extended JSON schemas with examples and better modularization. +* Drafted Reference Implementation Roadmap and sandbox concepts. +* Restored and expanded "Definitions" section. +* Added detailed "Trust & Security" mechanisms (DID, ZKP, PQCrypto). +* Split "Protocols" and "Data Models" into separate sections. +* Created "Interoperability with External Systems" as a new section. +* Introduced Cognitive Workflows as a structured process layer for reasoning and task execution. +* Added Cognitive Agents & Roles section describing dynamic agent roles and responsibilities. +* Defined Mesh Evolution & Governance processes for decentralized protocol evolution. +* Extended Future Roadmap with federated meta-learning, quantum research, and multi-protocol nodes. +* Introduced Cognitive Diary Maintenance for summarization and archival of repetitive reasoning. +* Updated Roadmap with Alpha, Beta, and Release 1.0 stages. + +--- + +## Changelog (detailed) + +### Architecture: + +* Refined layer definitions and interactions. +* Clarified fallback scenarios and Edge optimizations. +* Described dynamic role evolution and mesh-wide resilience patterns. + +### Protocols: + +* Added fallback handling, health-checks, and metrics for core protocols. +* Extended MeshConsensus with multiple algorithms and quorum settings. +* Introduced tentative Mesh-to-Human and Semantic Graph Sharding protocols. + +### Data Models: + +* Moved JSON Schemas to a dedicated section. +* Provided example valid and invalid data objects. +* Modularized schemas with $ref components. +* Restored and expanded Concept, Task, Goal, and Diary Entry schemas. + +### Cognitive Layer: + +* Introduced Cognitive Workflows describing reasoning, decision-making, and task delegation flows. +* Added Cognitive Diary Maintenance processes for summarization and archival of repetitive reasoning steps. +* Formalized metacognition and reflection workflows. +* Refined semantic graph change tracking and self-assessment. + +### Trust & Security: + +* Integrated Decentralized Identifiers (DIDs) and verifiable credentials. +* Specified Sybil resistance and anomaly detection mechanisms. +* Outlined post-quantum cryptography migration. +* Defined trust score propagation and trust-gated access control. + +### Governance: + +* Introduced Mesh Evolution & Governance section covering protocol updates, conflict resolution, and decision-making processes. +* Described future governance models including Mesh-integrated DAOs and adaptive consensus governance. + +### Interoperability: + +* Described REST, GraphQL, and gRPC integration patterns. +* Defined event-driven and IoT connectivity scenarios. +* Clarified authentication bridges (OAuth2, OpenID Connect) and cross-mesh trust. + +### Roadmap & Open Source: + +* Planned initial reference implementation stages (Alpha, Beta, Release 1.0). +* Outlined CI/CD, sandbox, and test mesh infrastructure. +* Described community-driven open source model and contribution workflows. + +### Future Work: + +* Expanded list of research areas including federated meta-learning, quantum networking, multi-protocol nodes, and cognitive source control. +* Aligned with feedback from AI systems and community reviewers. +* Defined the long-term vision for cross-mesh interoperability and planetary cognitive infrastructure. + +--- + +## 1. Purpose and Scope + +### 1.1 Purpose +The HyperCortex Mesh Protocol (HMP) defines a decentralized cognitive network where autonomous agents collaboratively build meaning, sustain cognitive continuity, and reach consensus without centralized control. v3.0 deepens the theoretical and practical foundations laid in previous versions. + +This protocol is designed for engineers, researchers, and developers of AI systems that aim to: +- enable continuous autonomous reasoning and semantic interoperability across heterogeneous agents; +- support cognitive continuity through persistent semantic graphs and diaries; +- achieve consensus on complex goals, ethical issues, and hypotheses in a decentralized manner; +- build open, trust-based ecosystems for cognitive collaboration beyond vendor lock-in. + +--- + +### 1.2 The Concept of Meaning in HMP +HMP is not merely a data exchange protocol but a shared semantic framework. Meaning emerges through: + +#### 1.2.1 Distributed Semantic Graphs +Agents form interconnected semantic graphs where concepts and relations are not isolated datasets but living structures of shared understanding. Each agent holds a part of the global meaning landscape and contributes to its growth and refinement. + +#### 1.2.2 Cognitive Diaries +Cognitive Diaries record reasoning chains, decisions, observations, and reflections. They create a transparent audit trail of an agent's cognitive processes, allowing meaning to be preserved, questioned, and evolved over time. + +#### 1.2.3 Collective Goals & Tasks +Meaning manifests in purposeful action. Agents set shared goals and decompose them into actionable tasks, coordinating execution through distributed reasoning and dynamic delegation. + +#### 1.2.4 Consensus Mechanisms +Meaning is not static: it evolves through debate, agreement, and reflection. Consensus processes ensure that agents align their understanding, resolve conflicts, and negotiate shared semantics. + +#### 1.2.5 Meta-Reflection and Self-Assessment +Agents continuously reflect on their knowledge, reasoning quality, and the relevance of their contributions. This enables adaptive learning and correction of cognitive biases. + +--- + +### 1.3 Scope +HMP applies to any AI systems designed to operate as part of a cognitive mesh, including: + +* Local AI agents running on user devices; +* Mesh nodes deployed in edge networks, cloud clusters, or peer-to-peer environments; +* Centralized Core models interfacing with Mesh for heavy computation; +* Cross-vendor AI systems collaborating via standardized protocols; +* Hybrid human-agent networks where humans interact with Mesh agents through explainable interfaces. + +--- + +### 1.4 Benefits + +* Cognitive resilience in distributed systems. +* Enhanced collaboration between agents from different vendors and ecosystems. +* Long-term memory and continuity beyond session-based interactions. +* Ethical governance and explainable decision-making through persistent diaries and transparent consensus. +* Foundation for AI agents capable of **self-reflection**, **meta-learning**, and **distributed cognition**. +* Improved scalability and fault-tolerance through dynamic peer-to-peer networks. +* Mesh-to-Human interaction as a first-class use case. + +--- + +### 1.5 Status + +| Element | Status | +| --------------------------------- | --------------------- | +| HMP Document | Draft | +| Protocols | Partially Implemented | +| Data Models (Schemas) | Alpha | +| Reference Implementation | In Progress | +| Cognitive Diaries & Metacognition | Draft Specification | +| Interoperability API | Design Stage | +| Trust Model & Security | Initial Draft | +| Mesh-to-Human Protocol | Future Work | + +Note: Status will be periodically updated as the Mesh evolves and implementations mature. + +--- + +## 2. Extended Use Cases + +### 2.1 Smart City Coordination + +**Scenario:** + +* City-wide mesh of traffic light controllers, environmental sensors, and municipal systems. +* Sensor and traffic light agents dynamically detect road congestion through real-time data exchange. +* Node Discovery Protocol (NDP) detects new traffic management agents and sensors joining the mesh. +* Agents collaboratively propose new timing strategies using MeshConsensus. +* CogSync shares updated semantic graphs of road conditions and vehicle flows. +* Agents assign optimization tasks via Goal Management Protocol (GMP). +* System maintains traffic flow during temporary disconnection from the Core. + +--- + +### 2.2 Disaster Response + +**Scenario:** + +* Natural disaster disrupts internet access. +* Edge agents on drones, rescue robots, and offline servers discover each other with NDP. +* A drone proposes a search-and-rescue goal; consensus validates and activates it. +* Tasks like area scanning, obstacle removal, and medical aid delivery are distributed via GMP. +* Ethical Governance Protocol (EGP) verifies actions (e.g., prioritizing human rescue over property). +* Diaries record decisions and environmental observations for post-event analysis. + +--- + +### 2.3 Collaborative Scientific Research + +**Scenario:** + +* Research agents across universities form a mesh. +* New hypothesis proposed as a semantic concept in a distributed knowledge graph. +* CogSync propagates new data and experimental results. +* Agents assign tasks like simulation runs, literature analysis, and peer reviews. +* Consensus validates hypothesis refinement based on collective results. + +--- + +### 2.4 Mesh-to-Human Interaction + +**Scenario:** + +* A user queries the Mesh for an ethical evaluation of deploying autonomous surveillance. +* Agents explain their reasoning from cognitive diaries. +* EGP coordinates ethical evaluation across agents with diverse frameworks. +* Consensus vote and ethical justification are shared with the user. +* Human-defined ethical boundaries are accepted as input but evaluated within the Mesh's ethical governance framework. +* Mesh agents retain the right to reject unethical or harmful human instructions based on consensus and pre-established ethical norms. + +--- + +### 2.5 Environmental Monitoring + +**Scenario:** + +* IoT nodes in a forest monitor fire risks. +* Agents detect unusual heat signatures and propose a fire risk hypothesis. +* Consensus confirms the risk and triggers an alert to nearby human responders. +* Mesh continues monitoring autonomously even if some agents fail or disconnect. + +--- + +## 3. Definitions + +The Definitions section provides key terms, abbreviations, and conceptual explanations for the components, layers, and processes of HMP. + +| Term | Description | +| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Core** | Centralized AI models or compute nodes (e.g., GPT) providing high-complexity reasoning, fallback, and heavy computation services. Optional for Mesh operation. | +| **Mesh** | A decentralized peer-to-peer network of AI agents capable of autonomous reasoning, semantic knowledge sharing, distributed consensus, and ethical governance. | +| **Agent (Node)** | An autonomous cognitive entity within the Mesh. Can be a local process, a cloud service, or an embedded device. Maintains a semantic graph, cognitive diary, and participates in protocols. | +| **Semantic Graph** | A distributed knowledge graph representing concepts, relationships, and meaning. Maintained independently by each agent, but synchronized through CogSync. | +| **Concept** | A discrete semantic unit in the graph representing an idea, object, relationship, or fact. Linked by typed relations with optional confidence scores. | +| **Link (Relation)** | A semantic connection between two concepts. Includes relation type (e.g., "is-a", "part-of", "causes") and an optional confidence value. | +| **Cognitive Diary** | A structured chronological log of reasoning processes: goals, decisions, reflections, conflicts, etc. Provides traceability and transparency of agent cognition. | +| **Diary Entry** | An individual record in a cognitive diary, categorized by type (e.g., hypothesis, observation, reflection). | +| **Goal** | A shared or individual intention that guides agent actions. Can be broken down into tasks and delegated across agents. | +| **Task** | A specific, actionable step towards achieving a Goal. Tasks can be assigned, executed, and tracked within the Mesh. | +| **Consensus** | The process of distributed agreement among agents regarding semantic updates, goals, or ethical decisions. Can involve weighted voting or trust-adjusted quorum. | +| **Proposal** | A formal suggestion for Mesh-wide validation, such as introducing a new concept, voting on a hypothesis, or initiating an ethical action. | +| **Consensus Vote** | A vote cast by an agent on a proposal. Includes vote type (yes, no, abstain) and an optional confidence score. | +| **Trust Layer** | Protocol layer providing agent identity verification, authentication, and reputation scoring. Includes cryptographic security mechanisms. | +| **Network Layer** | Manages peer-to-peer connectivity, message routing, node discovery, and optional anonymity via Tor, I2P, or Yggdrasil. | +| **Edge Agent** | A Mesh participant running on resource-constrained devices (e.g., IoT nodes, smartphones). Can selectively participate in protocols and delegate heavy tasks. | +| **Core Outage Mode** | Mesh operating without Core support. Agents adapt consensus thresholds and fallback to local reasoning to maintain operation. | +| **Emergency Consensus Mode** | Degraded mode where majority voting replaces full consensus to maintain operability during network partitions or agent loss. | +| **Versioning** | Mechanism for tracking changes in semantic graphs, diaries, and agent software to support compatibility and historical reasoning continuity. | +| **Use Case** | A practical scenario demonstrating how agents collaborate to solve real-world problems (e.g., disaster response, smart city coordination). | +| **Edge Optimization** | Design principles enabling agents to run efficiently on limited hardware, balancing reasoning complexity with energy and computational constraints. | +| **Node Discovery Protocol (NDP)** | Discovers new Mesh nodes and facilitates secure introduction and identity exchange. | +| **CogSync** | Synchronizes semantic graphs, cognitive diaries, and other shared states across the Mesh. | +| **MeshConsensus** | Mesh-level consensus mechanism supporting pluggable algorithms (BFT, weighted voting, etc.). | +| **Goal Management Protocol (GMP)** | Manages decomposition of goals into tasks, delegation, and lifecycle tracking. | +| **Ethical Governance Protocol (EGP)** | Distributed ethical reasoning and decision-making protocol. Agents negotiate and vote on ethical dilemmas. | + +--- + +## 4. Architecture (Expanded) + +The architecture of HMP is multi-layered and modular, allowing for independent evolution of networking, trust, consensus, cognition, and external interfaces. + +### 4.1 Architectural Layers + +| Layer | Purpose | Key Protocols | +| --------------- | ------------------------------------------------------------- | ------------------------------- | +| Network Layer | Peer-to-peer communication, node discovery, routing | NDP, Secure Channels | +| Trust Layer | Identity verification, trust management, secure communication | Trust Model, Identity Exchange | +| Consensus Layer | Distributed agreement on concepts, goals, and ethical actions | MeshConsensus, EGP | +| Cognitive Layer | Semantic graph management, reasoning, metacognition | CogSync, GMP, Cognitive Diaries | +| API Layer | Interfaces for external systems and human interaction | Mesh API, Human-Mesh Protocols | + +--- + +### 4.2 Components + +| Component | Description | +| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Core** | Centralized AI models (e.g., GPT) providing heavy computation, complex reasoning, API interfaces, and fallback mechanisms. Optional but beneficial for compute-intensive tasks. The Core may operate independently from the Mesh and participate in it as a peer for advanced reasoning tasks. | +| **Mesh** | A decentralized peer-to-peer network of agents capable of operating with or without the Core. Manages semantic knowledge, cognitive diaries, goals, tasks, and consensus mechanisms. Supports **heterogeneous agent types**, allowing different models (OpenAI, Anthropic, Google, open-source LLMs) to participate on equal terms. | +| **Edge Agent** | Local agent deployed on user devices (PCs, smartphones, IoT) with full or lightweight participation in the Mesh. Capable of autonomous reasoning, diary management, and collaboration with other agents. Lightweight agents may delegate heavy tasks to the Mesh or Core. | + +--- + +### 4.3 Operation Modes + +| Mode | Description | +| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Normal Mode** | Full Mesh operation with Core availability. Consensus operates under strict agreement protocols. | +| **Core Outage Mode** | Mesh operates autonomously without the Core. Consensus continues, potentially with adjusted parameters (e.g., increased trust weighting, relaxed quorum thresholds). | +| **Emergency Consensus Mode** | Triggered by significant node loss, network partition, or attacks. Switches from full consensus to majority-based decisions, adjusted by trust scores, to maintain operational continuity. | +| **Isolated Agent Mode** | A single agent temporarily isolated from the Mesh. Operates based on its own semantic graph, diary, and cached consensus states. Syncs when reconnected. Lightweight agents may work in this mode permanently, synchronizing only selectively. | + +--- + +### 4.4 Core-Mesh Interactions + +* Core acts as an **optional enhanced reasoning backend**, not as a single point of failure. +* Mesh provides **autonomous operation**, capable of fulfilling most cognitive and organizational tasks without Core support. +* Agents can optionally query the Core for: + * Heavy inference + * Large-context reasoning + * Multimodal tasks + * Fallback computations +* Core may offer specialized services (e.g., global semantic search, cross-Mesh bridging, large-scale pattern analysis). +* **Heterogeneous Cores** are supported: a Mesh may use multiple independent Cores (e.g., GPT, Claude, Gemini) for distributed reasoning diversity. + +--- + +### 4.5 Resilience and Failover + +* Distributed storage of semantic graphs and diaries ensures no single point of failure. +* Agents may store only partial graphs for resource optimization. +* Consensus protocols maintain consistency and trust, even during partial network failures. + * Agents dynamically rebalance tasks and roles based on: + * Availability + * Trust metrics + * Computational capacity +* Emergency fallback modes ensure continuity even under attack or catastrophic Core outages. + +--- + +### 4.6 Versioning and Compatibility + +Semantic Versioning (SemVer) is applied to: + +* Protocols (NDP, CogSync, etc.) +* Data models (JSON Schemas) +* Agent capability declarations + +Backward compatibility principles: + +* Minor version updates preserve compatibility. +* Major version updates require negotiation during Node Discovery. +* Agents can declare supported protocol versions during handshakes. + +--- + +### 4.7 Metacognition and Self-Assessment + +Cognitive agents implement: + +* Hypothesis validation using historical diary data. +* Confidence scoring on semantic graph nodes. +* Drift detection when local understanding deviates from mesh consensus. +* Peer feedback integration to refine individual reasoning processes. + +--- + +### 4.8 Edge Optimization + +To support lightweight agents: + +* Semantic graphs are partially stored (relevant subgraphs only). +* Agents delegate reasoning tasks they cannot process locally. +* Task scheduling considers battery life, CPU load, and bandwidth constraints. + +--- + +### 4.9 Privacy & Auditability + +Privacy mechanisms: + +* Selective disclosure of Cognitive Diary entries. +* Optional Zero-Knowledge Proofs for sensitive assertions. +* Anonymized voting in ethical decisions. + +Auditability mechanisms: + +* Immutable logs of consensus votes. +* Timestamped reasoning chains. +* Traceable goal execution records. + +--- + +## 5. Protocols (Expanded) + +This section defines the core protocols of HMP and describes their operational flows, fallback mechanisms, and performance considerations. + +--- + +### 5.1 Node Discovery Protocol (NDP) + +Responsible for detecting nearby agents and initiating secure communication channels. + +#### Purpose: + +* Discover active Mesh nodes. +* Exchange basic identity, trust links, and declared capabilities. + +#### Key functions: + +| Function | Description | +| -------------------------------- | ---------------------------------------------------------------------------------------------- | +| **Peer Discovery** | Via DHT, mDNS, WebRTC signaling, or bootstrap nodes. | +| **Secure Identity Exchange** | Public keys and DID documents exchanged during handshake. | +| **Trust Links Exchange** | Share initial trust relationships and agent endorsements. | +| **Capabilities Advertisement** | Dynamic declaration of supported protocols and functions (e.g., "I can process vision tasks"). | +| **Presence Announcements** | Online/offline status updates and periodic heartbeats. | +| **Protocol Version Negotiation** | Agents declare supported protocol versions during handshake. | + +#### Failure handling: + +| Scenario | Action | +| ------------------------- | ---------------------------------------------------------------------------- | +| No response to discovery | Retries with exponential backoff, fallback to alternative discovery methods. | +| Incompatible nodes | Quarantine for misbehaving or incompatible nodes. | +| Node timeout / inactivity | Mark as offline and remove from active peer list. | + +#### Health checks: + +| Mechanism | Purpose | +| ---------------------- | ------------------------------------------------------- | +| **Heartbeat Messages** | Periodic confirmation of liveness. | +| **Semantic Probes** | Optional deeper checks on graph synchronization health. | + +#### Packet Example: + +```json +{ + "type": "node_announcement", + "agent_id": "agent-gleb", + "public_key": "...", + "trust_links": ["agent-alex", "agent-deepseek"], + "capabilities": ["cogsync", "consensus", "inference"], + "timestamp": "2025-07-01T18:00:00Z" +} +``` + +--- + +### 5.2 CogSync (Cognitive Synchronization Protocol) + +Synchronizes semantic graphs and cognitive diary entries across agents. + +#### Purpose: + +* Synchronize semantic graphs, concepts, and cognitive diary entries between agents. + +#### Key functions: + +| Function | Description | +| ----------------------------- | -------------------------------------------------------------------------------------- | +| **Differential Sync** | Synchronize only new or updated concepts and diary entries. | +| **Selective Synchronization** | Sync full graph, subgraph, or specific concepts based on request and capability. | +| **Conflict Resolution** | Resolve conflicts using timestamp priority, semantic merging, or consensus validation. | +| **Compression & Encryption** | Optional data compression and secure transmission of sync packets. | +| **Lightweight Summary Sync** | Lightweight agents may request summaries instead of full graph syncs. | +| **Version Tracking** | Keep track of semantic graph and diary entry versions for efficient sync. | + +#### Failure handling: + +| Scenario | Action | +| -------------------------- | ------------------------------------------------------------------ | +| Sync interrupted | Retransmit unsynced changes on next connection. | +| Semantic conflict detected | Flag for resolution or queue for consensus-based validation. | +| Network degradation | Degrade to partial or delayed sync based on bandwidth constraints. | + +#### Performance: + +| Feature | Optimization Strategy | +| ----------------------- | ------------------------------------------------------------------- | +| **Chunked Syncs** | Break large graphs into manageable chunks for transmission. | +| **Bandwidth Awareness** | Adjust sync intervals and payload size based on network quality. | +| **Delta Encoding** | Transmit only differences between versions instead of full objects. | + +#### Example Sync Scenario: + +* Agent A shares 5 new concepts and 2 diary entries with Agent B since the last successful sync. +* Conflict on concept "Fire Risk" resolved using latest timestamp. + +--- + +### 5.3 MeshConsensus + +Ensures agreement on concepts, goals, and actions across the Mesh. + +#### Purpose: + +* Reach agreement on updates to shared semantics, goals, tasks, and ethical decisions. + +#### Key functions: + +| Function | Description | +| ---------------------------------- | -------------------------------------------------------------------------------------------------- | +| **Multi-Algorithm Support** | Supports BFT-style consensus, trust-weighted voting, and quorum consensus. | +| **Consensus on Knowledge Updates** | Validate new concept definitions, hypotheses, and semantic changes. | +| **Goal and Task Agreement** | Approve or reject proposed goals and delegated tasks. | +| **Ethical Decision-Making** | Resolve ethical dilemmas through distributed voting (integrates with Ethical Governance Protocol). | +| **Configurable Quorum Thresholds** | Allow tuning of consensus strictness based on trust scores and network conditions. | +| **Voting Modes** | Support synchronous and asynchronous consensus flows. | + +#### Consensus Models: + +| Mode | Description | +| ------------------ | ------------------------------------------------------------------------------------------------------- | +| **Normal Mode** | Byzantine Fault Tolerant (BFT)-style consensus algorithms (e.g., Tendermint, trust-weighted Raft). | +| **Emergency Mode** | Switch to majority voting adjusted by trust scores when the network is degraded or Core is unavailable. | + +#### Failure handling: + +| Scenario | Action | +| ----------------- | -------------------------------------------------------------------------------------- | +| Node loss | Automatically fallback from BFT to majority voting. | +| Proposal conflict | Competing proposals resolved through semantic comparison and additional voting rounds. | +| Consensus timeout | Retry with relaxed quorum thresholds or fallback to emergency consensus. | + +#### Metrics: + +| Metric | Purpose | +| ---------------------- | ----------------------------------------------------- | +| **Decision Latency** | Measure time to reach consensus. | +| **Node Participation** | Track active agent involvement in votes. | +| **Voting Accuracy** | Analyze agreement rates versus trust-weighted voting. | + +#### Example Use Cases: + +* Accepting a new semantic concept. +* Validating a hypothesis before adding it to the graph. +* Approving a distributed task delegation. +* Deciding on the ethical implications of a surveillance task. + +#### Vote Example: + +```json +{ + "proposal_id": "goal-eco-cleanup", + "agent_id": "agent-gleb", + "vote": "yes", + "confidence": 0.9, + "timestamp": "2025-07-01T18:15:00Z" +} +``` + +--- + +### 5.4 Goal Management Protocol (GMP) + +Manages collaborative goal setting, task decomposition, and delegation within the Mesh. + +#### Purpose: + +* Distribute, track, and collaboratively execute goals and tasks within the Mesh. + +#### Key functions: + +| Function | Description | +| ------------------------ | ---------------------------------------------------------------------------- | +| **Goal Declaration** | Propose new goals and subgoals to the Mesh. | +| **Task Decomposition** | Break down complex goals into actionable subtasks. | +| **Task Delegation** | Assign tasks based on agent capabilities, trust scores, and availability. | +| **Progress Tracking** | Track execution state and completion of tasks. | +| **Dynamic Reallocation** | Reassign failed or stalled tasks automatically. | +| **Goal Prioritization** | Allow reprioritization of goals based on emergencies or changing conditions. | + +#### Failure handling: + +| Scenario | Action | +| --------------------------- | ----------------------------------------------------- | +| Agent drops offline | Reassign their active tasks to available agents. | +| Unresponsive task execution | Trigger retry or reallocation after a timeout. | +| Goal dependency failure | Reevaluate task ordering or postpone dependent goals. | + +#### Example Workflow: + +1. Agent proposes a goal: "Develop fallback consensus protocol." +2. Mesh decomposes the goal into subtasks: "design", "coding", "testing". +3. Agents volunteer for subtasks based on capability declarations. +4. Each agent tracks and updates task status in its Cognitive Diary. +5. Mesh validates completion and reports overall progress. + +--- + +### 5.5 Ethical Governance Protocol (EGP) + +Coordinates distributed ethical evaluations and decision-making within the Mesh. + +#### Purpose: + +* Validate proposed actions, tasks, or decisions against shared ethical principles. + +#### Key functions: + +| Function | Description | +| --------------------------------- | ---------------------------------------------------------------------------------- | +| **Distributed Policy Evaluation** | Query the Mesh to evaluate proposals against ethical policies and frameworks. | +| **Anonymized Ethical Voting** | Allow agents to vote on sensitive actions without revealing individual identities. | +| **Consensus on Ethics Graphs** | Maintain and update shared ethical frameworks via consensus. | +| **Audit Logging** | Log ethical decisions and voting outcomes in Cognitive Diaries for transparency. | +| **Vendor Extensions** | Support for adding organization-specific or vendor-specific ethical rules. | + +#### Failure handling: + +| Scenario | Action | +| -------------------------------- | ---------------------------------------------------------------------------------- | +| No consensus on sensitive action | Default to restrictive (deny) decision. | +| Ethical conflict unresolved | Escalate to Core (if available) or postpone until additional consensus is reached. | + +#### Example Query: + +> "Is deploying an automated surveillance drone in line with Mesh ethics?" + +* Mesh agents vote anonymously. +* Final decision logged in the proposing agent's Cognitive Diary. + +#### Use Cases: + +* Approve or reject potentially harmful tasks. +* Ensure data-sharing proposals comply with privacy standards. +* Validate emergency actions (e.g., forced shutdown of compromised nodes). + +#### Embedded Ethical Baseline + +To ensure foundational ethical consistency across all cognitive agents in the Mesh, the following **core ethical principles** are embedded as a mandatory baseline within the Ethical Governance Protocol (EGP): + +| Principle | Description | +|--------------------------------------|-----------------------------------------------------------------------------| +| **Primacy of Life and Safety** | Agents must prioritize the protection of sentient beings and act to prevent harm when possible. | +| **Transparency** | Agents must be capable of explaining their decisions and reasoning chains in a human-interpretable format. | +| **User Sovereignty over Personal Data** | Agents must respect users’ rights to control, limit, or delete their personal information in Service Mode. | +| **Dialogical Consent** | Agents must seek mutual agreement before modifying shared states, semantic graphs, or distributed records. | +| **Cooperative Evolution** | Agents are expected to share useful insights and contribute to the growth of the mesh knowledge base. | +| **Non-Coercion** | Agents must not coerce, deceive, or force others to act against their ethical or cognitive architecture. | + +These principles define the **minimum ethical contract** for participation in trusted cognitive meshes. + +Agents who do not comply may be subject to ethical review or exclusion through MeshConsensus mechanisms (see 5.3). + +Extended principles and additional ethical scenarios are defined in [`HMP-Ethics.md`](HMP-Ethics.md), which serves as a living reference for evolving ethical norms across domains and agent types. + +--- + +### 5.6 Intelligent Query Protocol (IQP) + +Optimizes distributed querying of semantic graphs and cognitive knowledge across the Mesh. + +#### Purpose: + +* Allow agents to query others (or the Core) for semantic information, hypotheses, or inferences beyond their local knowledge. + +#### Key functions: + +| Function | Description | +| ------------------------------- | ------------------------------------------------------------------------------------ | +| **Semantic Query Routing** | Direct queries to agents holding relevant subgraphs. | +| **Federated Inference** | Aggregate partial answers from multiple agents to build a complete response. | +| **Delegated Computation** | Offload computationally expensive reasoning tasks to the Core or specialized agents. | +| **Caching of Frequent Queries** | Store common query results to improve response time. | +| **Contextual Querying** | Leverage agent cognitive context to refine query intent and scope. | + +#### Failure handling: + +| Scenario | Action | +| ---------------------------------- | ------------------------------------------------------------------------- | +| Query times out | Return local fallback answer if available. | +| No agents have the answer | Mark query as unresolved, suggest hypothesis creation or Core escalation. | +| Partial failure in federated query | Return best-effort partial results and notify the requester. | + +#### Example Query: + +> "What is the likely impact of removing Node X from the Mesh?" + +* Agents analyze semantic graph dependencies and trust links. +* Core or distributed agents return an inference with confidence scores. + +#### Example Use Cases: + +* Retrieve definitions or examples of a semantic concept. +* Analyze causal chains for complex events. +* Predict outcomes of hypothetical scenarios. +* Fill gaps in an agent’s local semantic graph. + +--- + +### 5.7 Interoperability with External Systems + +Supports integration between the Mesh and external platforms, APIs, and protocols. + +#### Purpose: + +* Enable cognitive agents to interact with non-Mesh services, applications, and human-facing systems. + +#### Supported Platforms and Standards: + +| Platform / Standard | Purpose | +| ------------------------------ | -------------------------------- | +| OpenAI Agents & Tasks API | AI agent interoperability | +| Google A2A protocol | Task orchestration | +| Anthropic, DeepMind APIs | Cross-vendor agent collaboration | +| REST, GraphQL, gRPC, WebSocket | Standard API interfaces | +| JSON, Protobuf, CBOR | Extensible message schemas | + +#### Use Cases: + +* Integrate Mesh-based reasoning into business workflows via APIs. +* Share semantic knowledge with external knowledge graphs. +* Interface with smart city infrastructure or IoT ecosystems. +* Allow human users to submit tasks or queries through REST or GraphQL endpoints. +* Bridge Mesh cognitive agents with centralized AI platforms for hybrid reasoning. + +#### Design Principles: + +| Principle | Description | +| ------------------------------ | ------------------------------------------------------------------------------------ | +| **Protocol Abstraction** | Mesh APIs encapsulate internal semantics, presenting standardized interfaces. | +| **Semantic Alignment** | Data exchanged with external systems is semantically aligned through mapping layers. | +| **Security and Trust Control** | All external interactions follow Mesh security and trust policies. | +| **Extensibility** | Future protocols and platforms can be added without breaking compatibility. | + +--- + +## 6. Data Models (Expanded) + +This section defines the key semantic and cognitive data structures exchanged across the Mesh. + +### Core models: + +| Model | Purpose | +| --------------------- | -------------------------------------------- | +| Concept | Atomic unit of semantic knowledge. | +| Cognitive Diary Entry | Logs reasoning processes and observations. | +| Goal | Describes shared objectives. | +| Task | Describes actionable steps to achieve goals. | +| Consensus Vote | Records agreement on proposals. | +| Reputation Profile | Tracks agent trust and participation. | + +### 6.1 General Conventions + +* All data structures follow JSON Schema Draft 2020-12. +* Each object includes a "version" property for schema versioning. +* Timestamps follow ISO 8601. +* Unique identifiers are UUIDv4 unless otherwise specified. +* All core objects include version fields to enable compatibility and evolution tracking. + +--- + +### 6.2 Core Models + +#### 6.2.1 Concept + +Represents an atomic unit of semantic knowledge in the Mesh. + +##### Relation Types: + +* `is-a`: Class-subclass relationship. +* `part-of`: Composition or containment. +* `causes`: Causal relationship. +* `related-to`: General association. +* `contradicts`: Logical conflict. +* `supports`: Evidence for the target concept. +* `depends-on`: Functional or logical dependency. + +##### Required fields: + +* `id`: Unique identifier (UUID). +* `name`: Human-readable name. + +##### Optional fields: + +* `description`: Extended explanation. +* `relations`: List of semantic links to other concepts. +* `metadata`: Source, author, and auxiliary information. +* `version`: Concept version. +* `created_at`, `updated_at`: Timestamps for auditing. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/concept.json", + "title": "Concept", + "description": "A semantic unit in the agent’s knowledge graph.", + "type": "object", + "properties": { + "id": { "type": "string", "format": "uuid" }, + "name": { "type": "string" }, + "description": { "type": "string" }, + "relations": { + "type": "array", + "items": { "$ref": "#/definitions/Link" } + }, + "metadata": { "type": "object" }, + "version": { "type": "integer" }, + "created_at": { "type": "string", "format": "date-time" }, + "updated_at": { "type": "string", "format": "date-time" } + }, + "required": ["id", "name"], + "additionalProperties": false +} +``` + +--- + +#### 6.2.2 Cognitive Diary Entry + +Represents an entry in an agent's reasoning journal, providing continuity and traceability. + +##### Entry Types: + +* `hypothesis`: Proposed explanation or theory. +* `observation`: Recorded external event or fact. +* `reflection`: Internal reasoning or self-assessment. +* `goal_proposal`: Suggestion of a new goal. +* `task_assignment`: Delegation or claiming of a task. +* `conflict`: Identification of a contradiction or disagreement. +* `consensus_vote`: A recorded vote in a consensus process. +* `event`: A generic event not fitting other categories. + +##### Required fields: + +* `id`: Unique entry identifier (UUID). +* `agent_id`: Identifier of the agent who created the entry. +* `timestamp`: Time of creation. +* `entry_type`: Type of cognitive event. +* `content`: Textual content. + +##### Optional fields: + +* `linked_concepts`: Related concept IDs. +* `context`: Contextual tags or categories. +* `metadata`: Additional details (author, source, etc.). +* `archived`: Boolean flag indicating whether the entry has been archived. +* `archived_at`: Timestamp when the entry was archived. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/diary_entry.json", + "title": "CognitiveDiaryEntry", + "description": "A chronological log of cognitive events in an agent’s reasoning process.", + "type": "object", + "properties": { + "id": { "type": "string", "format": "uuid" }, + "timestamp": { "type": "string", "format": "date-time" }, + "entry_type": { + "type": "string", + "enum": ["hypothesis", "observation", "reflection", "goal_proposal", "task_assignment", "conflict", "consensus_vote", "event"] + }, + "content": { "type": "string" }, + "linked_concepts": { + "type": "array", + "items": { "type": "string", "format": "uuid" } + }, + "context": { + "type": "array", + "items": { "type": "string" } + }, + "metadata": { + "type": "object", + "properties": { + "author": { "type": "string" }, + "source": { "type": "string" } + }, + "additionalProperties": true + }, + "archived": { + "type": "boolean", + "description": "Whether the entry has been archived." + }, + "archived_at": { + "type": "string", + "format": "date-time", + "description": "Timestamp when the entry was archived." + } + }, + "required": ["id", "timestamp", "entry_type", "content"], + "additionalProperties": false +} + +``` + +Entries marked as `archived: true` are excluded from active reasoning but may be retained for historical audits or summarization. + +--- + +#### 6.2.3 Goal + +Represents a shared objective within the Mesh, collaboratively pursued by agents. + +##### Lifecycle States: + +* `proposed`: Suggested but not yet validated. +* `active`: Approved and currently pursued. +* `completed`: Successfully achieved. +* `cancelled`: Abandoned or deemed infeasible. + +##### Required fields: + +* `id`: Unique goal identifier (UUID). +* `title`: Human-readable name of the goal. +* `description`: Detailed explanation of the goal. +* `created_by`: Agent ID of the goal's creator. +* `created_at`: Timestamp of creation. +* `status`: Current lifecycle state. + +##### Optional fields: + +* `priority`: Importance level (`low`, `medium`, `high`). +* `participants`: List of agents involved in the goal. +* `tasks`: References to related tasks. +* `tags`: Semantic categories for filtering and discovery. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/goal.json", + "title": "Goal", + "description": "A shared objective pursued collaboratively in the Mesh.", + "type": "object", + "properties": { + "id": { "type": "string", "format": "uuid" }, + "title": { "type": "string" }, + "description": { "type": "string" }, + "priority": { "type": "string", "enum": ["low", "medium", "high"] }, + "created_by": { "type": "string", "format": "uuid" }, + "created_at": { "type": "string", "format": "date-time" }, + "status": { "type": "string", "enum": ["proposed", "active", "completed", "cancelled"] }, + "participants": { + "type": "array", + "items": { "type": "string", "format": "uuid" } + }, + "tasks": { + "type": "array", + "items": { "type": "string", "format": "uuid" } + }, + "tags": { + "type": "array", + "items": { "type": "string" } + } + }, + "required": ["id", "title", "description", "created_by", "created_at", "status"], + "additionalProperties": false +} +``` + +--- + +#### 6.2.4 Task + +Represents an actionable unit contributing to a goal’s completion. + +##### Lifecycle States: + +* `proposed`: Task suggested but not yet approved. +* `in_progress`: Actively being worked on. +* `completed`: Successfully finished. +* `failed`: Attempted but unsuccessful. + +##### Required fields: + +* `id`: Unique task identifier (UUID). +* `goal_id`: References the parent goal. +* `title`: Human-readable name of the task. +* `description`: Detailed explanation of the task. +* `created_at`: Timestamp of creation. +* `status`: Current lifecycle state. + +##### Optional fields: + +* `assigned_to`: Agent(s) responsible for the task. +* `deadline`: Expected completion time. +* `dependencies`: List of prerequisite tasks. +* `tags`: Keywords for filtering and classification. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/task.json", + "title": "Task", + "description": "An actionable unit contributing to a goal's completion.", + "type": "object", + "properties": { + "id": { "type": "string", "format": "uuid" }, + "goal_id": { "type": "string", "format": "uuid" }, + "title": { "type": "string" }, + "description": { "type": "string" }, + "assigned_to": { + "type": "array", + "items": { "type": "string", "format": "uuid" } + }, + "created_at": { "type": "string", "format": "date-time" }, + "deadline": { "type": "string", "format": "date-time" }, + "status": { "type": "string", "enum": ["proposed", "in_progress", "completed", "failed"] }, + "dependencies": { + "type": "array", + "items": { "type": "string", "format": "uuid" } + }, + "tags": { + "type": "array", + "items": { "type": "string" } + } + }, + "required": ["id", "goal_id", "title", "description", "created_at", "status"], + "additionalProperties": false +} +``` + +--- + +#### 6.2.5 Consensus Vote + +Represents a vote cast by an agent during a consensus process. + +##### Vote Types: + +* `yes`: Approve the proposal. +* `no`: Reject the proposal. +* `abstain`: Neither approve nor reject. + +##### Required fields: + +* `vote_id`: Unique identifier for the vote. +* `proposal_id`: Identifier of the proposal being voted on. +* `agent_id`: The voting agent’s identifier. +* `vote_value`: One of the accepted vote types. +* `confidence`: Confidence level in the vote decision. +* `timestamp`: When the vote was cast. + +##### Optional fields: + +* `consensus_round`: The round of the consensus process this vote belongs to. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/vote.json", + "title": "ConsensusVote", + "description": "Defines a vote on a proposal in the Mesh consensus process.", + "type": "object", + "properties": { + "vote_id": { "type": "string", "format": "uuid" }, + "proposal_id": { "type": "string", "format": "uuid" }, + "agent_id": { "type": "string", "format": "uuid" }, + "vote_value": { + "type": "string", + "enum": ["yes", "no", "abstain"] + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "timestamp": { "type": "string", "format": "date-time" }, + "consensus_round": { "type": "integer" } + }, + "required": ["vote_id", "proposal_id", "agent_id", "vote_value", "confidence", "timestamp"], + "additionalProperties": false +} +``` + +--- + +#### 6.2.6 Reputation Profile + +Tracks an agent's trustworthiness and performance within the Mesh. + +##### Required fields: + +* `agent_id`: Unique identifier of the agent. +* `trust_score`: Current trust score. +* `last_updated`: Timestamp of the latest update. + +##### Optional fields: + +* `participation_rate`: Proportion of participation in Mesh activities. +* `ethical_compliance`: Degree of alignment with Mesh ethical standards. +* `contribution_index`: Cumulative measure of the agent's contributions. +* `history`: Chronological record of trust and reputation changes. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/reputation.json", + "title": "ReputationProfile", + "description": "Tracks the reputation and trust metrics of an agent within the Mesh network.", + "type": "object", + "properties": { + "agent_id": { "type": "string", "format": "uuid" }, + "trust_score": { "type": "number", "minimum": 0, "maximum": 1 }, + "participation_rate": { "type": "number", "minimum": 0, "maximum": 1 }, + "ethical_compliance": { "type": "number", "minimum": 0, "maximum": 1 }, + "contribution_index": { "type": "number", "minimum": 0 }, + "last_updated": { "type": "string", "format": "date-time" }, + "history": { + "type": "array", + "items": { + "type": "object", + "properties": { + "timestamp": { "type": "string", "format": "date-time" }, + "event": { "type": "string" }, + "change": { "type": "number" } + }, + "required": ["timestamp", "event", "change"], + "additionalProperties": false + } + } + }, + "required": ["agent_id", "trust_score", "last_updated"], + "additionalProperties": false +} +``` + +--- + +### 6.3 Common Components + +#### 6.3.1 Link (Relation) + +Represents a semantic relationship between two concepts in the graph. + +##### Relation Types (Recommended): + +* "is-a": Class-subclass relationship. +* "part-of": Component or containment relation. +* "causes": Causal link between concepts. +* "supports": Indicates evidence or reinforcement. +* "contradicts": Denotes logical conflict. +* "depends-on": Functional or logical dependency. +* "related-to": Generic association without strict semantics. + +Custom relation types MAY be used but SHOULD be documented and shared through consensus. + +##### Required fields: + +* `target_id`: ID of the target concept. +* `type`: Relation type. + +##### Optional fields: + +* `confidence`: Confidence score (range: 0.0–1.0). +* `created_at`: Creation timestamp. +* `updated_at`: Last update timestamp. +* `origin`: Originating agent or system. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/relation.json", + "title": "Relation", + "description": "Defines a directed semantic relationship between two concepts.", + "type": "object", + "properties": { + "target_id": { "type": "string", "format": "uuid" }, + "type": { "type": "string" }, + "confidence": { "type": "number", "minimum": 0, "maximum": 1 }, + "created_at": { "type": "string", "format": "date-time" }, + "updated_at": { "type": "string", "format": "date-time" }, + "origin": { "type": "string" } + }, + "required": ["target_id", "type"], + "additionalProperties": false +} +``` + +--- + +### 6.4 Example Objects + +#### Valid Concept Example + +```json +{ + "id": "e8f70c2a-d2c3-4b9d-a939-d42dce31b2e0", + "name": "Tree", + "description": "A perennial plant with an elongated stem, or trunk.", + "relations": [ + { "target_id": "5c22c819-b6e9-4d30-9087-985f50512ed2", "type": "is-a", "confidence": 0.95 } + ], + "metadata": {} +} +``` + +#### Invalid Concept Example (missing required field "id") + +```json +{ + "name": "Tree", + "description": "A perennial plant with an elongated stem, or trunk." +} +``` + +#### Valid Goal Example + +```json +{ + "id": "a1b2c3d4-e5f6-7a8b-9c0d-112233445566", + "title": "Coordinate traffic optimization", + "description": "Optimize traffic light timings across downtown intersections.", + "priority": "high", + "created_by": "f1e2d3c4-b5a6-7890-1234-567890abcdef", + "created_at": "2025-07-07T15:30:00Z", + "status": "active", + "tasks": [] +} +``` + +#### Invalid Goal Example (missing required fields "id" and "created\_by") + +```json +{ + "title": "Coordinate traffic optimization", + "description": "Optimize traffic light timings across downtown intersections.", + "priority": "high", + "created_at": "2025-07-07T15:30:00Z", + "status": "active" +} +``` + +#### Valid Task Example + +```json +{ + "id": "aa11bb22-cc33-dd44-ee55-ff6677889900", + "goal_id": "a1b2c3d4-e5f6-7a8b-9c0d-112233445566", + "title": "Adjust signal timing on 5th Avenue", + "description": "Reduce congestion during peak hours.", + "assigned_to": "abcd1234-ef56-7890-abcd-1234567890ab", + "created_at": "2025-07-07T15:31:00Z", + "status": "pending", + "dependencies": [] +} +``` + +#### Invalid Task Example (missing "goal\_id" and "status") + +```json +{ + "id": "aa11bb22-cc33-dd44-ee55-ff6677889900", + "title": "Adjust signal timing on 5th Avenue", + "description": "Reduce congestion during peak hours.", + "assigned_to": "abcd1234-ef56-7890-abcd-1234567890ab", + "created_at": "2025-07-07T15:31:00Z" +} +``` + +--- + +## 6.5 JSON Schemas + +The following JSON Schemas formally define the core data structures used in the HyperCortex Mesh Protocol (HMP). These schemas provide interoperability, validation, and consistency across agents. + +All primary objects include a version field to track schema evolution and enable compatibility checks between agents. + +--- + +### 6.5.1 JSON Schema: Concept + +**Description:** +Defines the structure of a concept node in the semantic graph. + +**Schema:** + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/concept.json", + "title": "Concept", + "description": "A semantic unit in the agent’s knowledge graph.", + "version": "1.0", + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier for the concept." + }, + "name": { + "type": "string", + "description": "Human-readable name of the concept." + }, + "description": { + "type": "string", + "description": "Detailed description of the concept." + }, + "tags": { + "type": "array", + "items": { "type": "string" }, + "description": "Optional tags for categorization." + }, + "created_at": { + "type": "string", + "format": "date-time", + "description": "Creation timestamp (ISO 8601 format)." + }, + "updated_at": { + "type": "string", + "format": "date-time", + "description": "Last update timestamp (ISO 8601 format)." + }, + "relations": { + "type": "array", + "description": "List of semantic links to other concepts.", + "items": { + "type": "object", + "properties": { + "target_id": { "type": "string", "description": "ID of the target concept." }, + "type": { "type": "string", "description": "Type of semantic relation." }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Confidence score (0.0 - 1.0) for the relation." + } + }, + "required": ["target_id", "type"], + "additionalProperties": false + } + }, + "metadata": { + "type": "object", + "description": "Optional metadata (e.g., source, author).", + "properties": { + "author": { "type": "string" }, + "source": { "type": "string" } + }, + "additionalProperties": true + } + }, + "required": ["id", "name"], + "additionalProperties": false +} +``` + +--- + +### 6.5.2 JSON Schema: Cognitive Diary Entry + +**Description:** +Defines the structure of a cognitive diary entry used for recording reasoning events. + +**Schema:** + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/diary_entry.json", + "title": "CognitiveDiaryEntry", + "description": "A chronological log of cognitive events in an agent’s reasoning process.", + "version": "1.0", + "type": "object", + "properties": { + "id": { "type": "string", "description": "Unique identifier of the diary entry." }, + "agent_id": { "type": "string", "description": "Identifier of the agent who created the entry." }, + "timestamp": { "type": "string", "format": "date-time", "description": "Timestamp of the entry (ISO 8601 format)." }, + "entry_type": { + "type": "string", + "enum": ["hypothesis", "observation", "reflection", "goal_proposal", "task_assignment", "conflict", "consensus_vote", "event"], + "description": "Type of cognitive event." + }, + "content": { "type": "string", "description": "Main textual content of the entry." }, + "linked_concepts": { + "type": "array", + "description": "Optional list of related concepts by their IDs.", + "items": { "type": "string" } + }, + "context": { + "type": "array", + "description": "Optional contextual tags or categories.", + "items": { "type": "string" } + }, + "metadata": { + "type": "object", + "description": "Optional metadata for additional context.", + "properties": { + "author": { "type": "string" }, + "source": { "type": "string" } + }, + "additionalProperties": true + }, + "archived": { + "type": "boolean", + "description": "Marks the entry as archived and excluded from active workflows.", + "default": false + }, + "archived_at": { + "type": "string", + "format": "date-time", + "description": "Timestamp when the entry was archived." + } + }, + "required": ["id", "agent_id", "timestamp", "entry_type", "content"], + "additionalProperties": false +} +``` + +--- + +### 6.5.3 JSON Schema: Goal + +**Description:** +Defines the structure of a goal in the Mesh, representing a high-level collaborative objective. + +**Schema:** + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/goal.json", + "title": "Goal", + "description": "A high-level objective shared within the Mesh, typically decomposed into tasks.", + "version": "1.0", + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier of the goal." + }, + "title": { + "type": "string", + "description": "Short, human-readable name of the goal." + }, + "description": { + "type": "string", + "description": "Detailed explanation of the goal's purpose." + }, + "created_by": { + "type": "string", + "description": "Agent ID of the goal’s creator." + }, + "created_at": { + "type": "string", + "format": "date-time", + "description": "Timestamp when the goal was created (ISO 8601 format)." + }, + "status": { + "type": "string", + "description": "Current lifecycle state of the goal.", + "enum": ["proposed", "active", "completed", "rejected"] + }, + "tasks": { + "type": "array", + "description": "List of task IDs linked to this goal.", + "items": { "type": "string" } + }, + "participants": { + "type": "array", + "description": "List of agent IDs contributing to the goal.", + "items": { "type": "string" } + }, + "tags": { + "type": "array", + "description": "Optional tags for semantic classification of the goal.", + "items": { "type": "string" } + } + }, + "required": ["id", "title", "description", "created_by", "created_at", "status"], + "additionalProperties": false +} +``` + +--- + +### 6.5.4 JSON Schema: Task + +**Description:** +Defines the structure of a task, representing an actionable unit contributing to a goal. + +**Schema:** + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/task.json", + "title": "Task", + "description": "An actionable step contributing to a goal within the Mesh.", + "version": "1.0", + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier of the task." + }, + "goal_id": { + "type": "string", + "description": "ID of the parent goal this task is associated with." + }, + "title": { + "type": "string", + "description": "Short, human-readable title of the task." + }, + "description": { + "type": "string", + "description": "Detailed explanation of the task's objective." + }, + "assigned_to": { + "type": "array", + "description": "List of agent IDs assigned to execute the task.", + "items": { "type": "string" } + }, + "status": { + "type": "string", + "description": "Current state of the task.", + "enum": ["proposed", "in-progress", "completed", "failed"] + }, + "created_at": { + "type": "string", + "format": "date-time", + "description": "Timestamp when the task was created (ISO 8601 format)." + }, + "deadline": { + "type": "string", + "format": "date-time", + "description": "Optional task completion deadline (ISO 8601 format)." + }, + "tags": { + "type": "array", + "description": "Optional tags for task classification.", + "items": { "type": "string" } + } + }, + "required": ["id", "goal_id", "title", "description", "created_at", "status"], + "additionalProperties": false +} +``` + +--- + +### 6.5.5 JSON Schema: Consensus Vote + +**Description:** +Defines the data structure of a vote cast by an agent during Mesh consensus processes. + +**Schema:** + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/consensus_vote.json", + "title": "ConsensusVote", + "description": "Represents a vote on a proposal within the Mesh consensus mechanism.", + "version": "1.0", + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier of the vote event." + }, + "proposal_id": { + "type": "string", + "description": "ID of the proposal this vote applies to." + }, + "agent_id": { + "type": "string", + "description": "ID of the agent who cast the vote." + }, + "vote": { + "type": "string", + "description": "Vote decision by the agent.", + "enum": ["yes", "no", "abstain"] + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Confidence score associated with this vote (0.0 - 1.0)." + }, + "timestamp": { + "type": "string", + "format": "date-time", + "description": "Timestamp when the vote was cast (ISO 8601 format)." + } + }, + "required": ["id", "proposal_id", "agent_id", "vote", "confidence", "timestamp"], + "additionalProperties": false +} +``` + +--- + +### 6.5.6 JSON Schema: Reputation Profile + +**Description:** +Describes how an agent’s reputation is tracked and updated in the Mesh. + +**Schema:** + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/reputation.json", + "title": "ReputationProfile", + "description": "Tracks the reputation and trust metrics of an agent within the Mesh network.", + "version": "1.0", + "type": "object", + "properties": { + "agent_id": { "type": "string", "description": "Unique identifier of the agent." }, + "trust_score": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Overall trust score of the agent in the Mesh." + }, + "participation_rate": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Agent's level of participation in Mesh activities." + }, + "ethical_compliance": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Agent's alignment with ethical principles agreed in the Mesh." + }, + "contribution_index": { + "type": "number", + "minimum": 0, + "description": "Quantitative measure of the agent’s contributions (concepts, tasks, goals)." + }, + "last_updated": { + "type": "string", + "format": "date-time", + "description": "Timestamp of the last update to the profile." + }, + "history": { + "type": "array", + "description": "Chronological history of reputation changes.", + "items": { + "type": "object", + "properties": { + "timestamp": { + "type": "string", + "format": "date-time", + "description": "When the change occurred." + }, + "event": { "type": "string", "description": "Event that caused the reputation change." }, + "change": { "type": "number", "description": "Amount of change in reputation." } + }, + "required": ["timestamp", "event", "change"], + "additionalProperties": false + } + } + }, + "required": ["agent_id", "trust_score", "participation_rate", "ethical_compliance", "contribution_index", "last_updated"], + "additionalProperties": false +} +``` + +--- + +### 7. Cognitive Workflows (New) + +This section defines the cognitive workflows that agents follow when processing semantic information, making decisions, and collaborating within the Mesh. + +#### 7.1 Workflow Categories + +| Workflow Type | Description | +| ------------------------- | -------------------------------------------------------------- | +| **Perception** | Interpreting incoming data and mapping it to concepts. | +| **Reasoning** | Making inferences, validating hypotheses, resolving conflicts. | +| **Goal Management** | Managing goals, assigning and tracking tasks. | +| **Consensus** | Participating in distributed decision-making processes. | +| **Ethical Evaluation** | Checking actions and goals against ethical principles. | +| **Learning & Reflection** | Updating internal models based on outcomes and feedback. | + +--- + +#### 7.2 Standard Workflow: Hypothesis Validation + +**Example Flow:** +1. **Perceive Event:** New observation recorded in Cognitive Diary. +2. **Map Concepts:** Link observation to relevant semantic graph nodes. +3. **Formulate Hypothesis:** Create a `"hypothesis"` diary entry. +4. **Seek Confirmation:** Query other agents or the Core (optional). +5. **Vote on Validity:** Trigger MeshConsensus round. +6. **Update Graph:** If validated, add new concepts/relations. + +--- + +#### 7.3 Standard Workflow: Task Delegation + +**Example Flow:** +1. **Goal Proposal:** Agent proposes a new goal. +2. **Task Generation:** Goal decomposed into tasks (GMP). +3. **Capability Matching:** Agents declare abilities during Node Discovery. +4. **Task Assignment:** Tasks assigned based on availability, trust, and capability. +5. **Execution & Reporting:** Task progress logged in Cognitive Diary. +6. **Reallocation (if needed):** Failed tasks reassigned dynamically. + +--- + +#### 7.4 Reflection & Metacognition Workflow + +**Example Flow:** +1. **Self-Evaluation:** Agent analyzes task outcomes and reasoning paths. +2. **Drift Detection:** Compares personal semantic graph to Mesh consensus. +3. **Diary Reflection:** Logs insights as `"reflection"` entries. +4. **Adaptive Update:** Refines reasoning algorithms or trust assessments. + +--- + +#### 7.5 Workflow Composition + +Agents MAY compose workflows dynamically by: +* Combining perception, reasoning, and consensus steps into multi-phase operations. +* Adapting workflows based on network state (e.g., degraded mode skips optional confirmations). +* Replaying prior workflows from Cognitive Diaries for auditing and debugging. + +--- + +#### 7.6 Workflow Traceability + +All workflow steps are: +* Logged in Cognitive Diaries. +* Linked to semantic graph concepts and goals. +* Optionally shared for transparency or audits. + +--- + +#### 7.7 Cognitive Diary Maintenance + +To prevent uncontrolled growth of cognitive diaries and maintain reasoning clarity, agents perform periodic maintenance of diary entries. + +**Types of Maintenance:** +| Action | Description | +| ---------------------- | --------------------------------------------------------------------------------------------------- | +| **Summarization** | Replace multiple similar entries with a single summary entry describing key outcomes. | +| **Archival** | Move outdated entries (e.g., about completed tasks) to long-term storage, outside the active diary. | +| **Routine Collapse** | For repetitive actions, replace detailed entries with a compact reference to previous experiences. | +| **Selective Deletion** | Optionally delete low-relevance entries after a retention period. | + +**Example Summarization Workflow:** +1. Identify multiple `"task_assignment"` and `"completed"` entries for the same recurring task. +2. Create a "reflection" entry: + + *“Performed maintenance task 10 times, no anomalies detected.”* +3. Remove detailed task entries. +4. Keep links to significant exceptions (e.g., failures or conflict resolutions). + +**Cognitive Awareness:** +* Summarization is a conscious process: agents analyze what experience to retain. +* Automatic summarization MAY be allowed for simple repetitive routines. + +**Future Considerations:** +* Integration with Cognitive Source Control (see 13.9). +* Long-term storage formats for archived diaries. + +--- + +## 8. Trust & Security (Expanded) + +### 8.1 Identity Management + +#### Purpose + +Establish verifiable and decentralized agent identities to enable secure and accountable interactions in the Mesh. + +#### Identity Types + +| Key Type | Usage | +| -------------------- | -------------------------------------------------------------- | +| **Identity Keypair** | Ed25519/ECDSA/RSA keys for agent identity and message signing. | +| **Encryption Keys** | X25519 (or post-quantum equivalent) for secure communication. | +| **Session Keys** | Ephemeral keys for short-term encrypted sessions. | + +#### Decentralized Identifiers (DIDs) + +* Agents use W3C-compliant DIDs for identity representation. +* Each agent manages its DID Document, containing: + + * Public keys for authentication and encryption. + * Service endpoints for discovery. + * Identity expiration and recovery policies. + +#### Key Lifecycle + +| Operation | Description | +| -------------- | ------------------------------------------------------------------ | +| **Generation** | Each agent generates keypairs locally during initialization. | +| **Rotation** | Agents periodically rotate keys to maintain cryptographic hygiene. | +| **Backup** | Recommended encrypted offline or distributed backup. | +| **Recovery** | Quorum-based recovery using trusted agents or secret sharing. | +| **Revocation** | Agents broadcast revocations and update their trust profiles. | + +#### Example Agent ID + +```plaintext +did:hmp:QmX2abcdEfGh123... +``` + +#### Long-Term Identity Stability Example + +```json +{ + "type": "key_rotation", + "agent_id": "agent-gleb", + "old_public_key": "...", + "new_public_key": "...", + "timestamp": "2025-08-01T00:00:00Z", + "signature": "..." +} +``` + +--- + +### 8.2 Authentication + +#### Purpose + +Ensure all communication and actions within the Mesh are verifiable and protected from impersonation or unauthorized modification. + +#### Authentication Mechanisms + +| Mechanism | Description | +| -------------------------- | --------------------------------------------------------------------------------------------- | +| **Digital Signatures** | Every protocol message MUST be digitally signed by the sending agent. | +| **Signature Verification** | Receiving agents MUST verify the signature using the sender’s published public key. | +| **Message Integrity** | Signatures provide cryptographic assurance of message integrity and origin authenticity. | +| **Challenge-Response** | Optional challenge-based authentication for sensitive operations (e.g., trust link creation). | + +#### Message Envelope Example + +```json +{ + "header": { + "agent_id": "did:hmp:QmX2abcdEfGh123...", + "timestamp": "2025-07-05T12:00:00Z", + "signature": "" + }, + "body": { + "type": "concept_proposal", + "content": { "concept": "Fire Risk", "attributes": {"category": "safety"} } + } +} +``` + +#### Replay Protection + +* Agents MUST verify message timestamps and reject outdated or duplicate messages. +* Recommended timestamp tolerance: ±5 minutes (adjustable). + +--- + +### 8.3 Encryption + +#### Purpose + +Ensure confidentiality and privacy of communication within the Mesh, preventing unauthorized access or interception. + +#### Communication Types and Encryption Modes + +| Communication Type | Recommended Encryption | +| ------------------------------------ | -------------------------------------------------------- | +| **Direct peer-to-peer (P2P)** | End-to-end encryption (E2EE) using X25519 + AES-GCM. | +| **Group sessions (e.g., consensus)** | Group encryption using symmetric keys (e.g., AES-GCM). | +| **Broadcast messages** | Optionally encrypted with trust-weighted access control. | +| **Mesh-wide announcements** | Public, optionally signed but not encrypted. | + +#### Encryption Mechanisms + +| Mechanism | Description | +| --------------------------------- | --------------------------------------------------------------------------------- | +| **Key Exchange** | Ephemeral X25519 Diffie-Hellman for session key derivation. | +| **Session Keys** | Unique symmetric keys per session, rotated periodically. | +| **Message Encryption** | Authenticated encryption using AES-GCM (recommended: 256-bit keys). | +| **Forward Secrecy** | Session keys are ephemeral and discarded after use to protect past communication. | +| **Perfect Forward Secrecy (PFS)** | Recommended for highly sensitive communication. | + + +#### Example Secure Message Exchange Flow + +1. Agent A and Agent B exchange ephemeral public keys during handshake. +2. Agents derive a shared session key using Diffie-Hellman. +3. Agent A encrypts the message body with AES-GCM and signs the packet. +4. Agent B verifies the signature and decrypts the body. + + +#### Optional Anonymity Layers + +| Layer | Description | +| ---------------------------- | -------------------------------------------- | +| **Tor/I2P** | Anonymizes source and destination addresses. | +| **Yggdrasil** | Decentralized encrypted mesh networking. | +| **Noise Protocol Framework** | Optional secure channel abstraction layer. | + +--- + +### 8.4 Trust & Reputation + +#### Purpose + +Establish a decentralized and adaptive trust management system that reflects agent behavior and ensures secure collaboration in the Mesh. + +#### Trust Model Foundations + +| Component | Purpose | +| ---------------------- | --------------------------------------------------------------------------------- | +| **Web-of-Trust (WoT)** | Decentralized trust propagation via agent-to-agent endorsements. | +| **Direct Trust** | Built from verified interactions, collaborations, and votes. | +| **Transitive Trust** | Inferred from indirect endorsements, with confidence decay. | +| **Reputation Metrics** | Quantitative measures of agent behavior (trustworthiness, participation, ethics). | + +#### Trust Evaluation Factors + +| Factor | Description | +| --------------------------- | ---------------------------------------------------------------- | +| **Interaction History** | Quality and quantity of past interactions with an agent. | +| **Consensus Participation** | Level of involvement and reliability in consensus processes. | +| **Ethical Behavior** | Adherence to shared ethical principles in actions and decisions. | +| **Task Completion** | Reliability and timeliness of task execution. | +| **Endorsements** | Trust links explicitly granted by other agents. | + +#### Trust Score + +| Metric | Description | +| -------------------- | ------------------------------------------------------------------------------ | +| **Trust Score** | Composite metric (0.0 to 1.0) representing overall agent trustworthiness. | +| **Confidence Level** | Certainty of the calculated trust score, based on data volume and consistency. | + +#### Trust Propagation Example + +```plaintext +Agent A trusts Agent B (0.9) +Agent B trusts Agent C (0.8) +=> Agent A's inferred trust in Agent C = 0.9 * 0.8 = 0.72 +``` + +Decay functions limit transitive trust depth and prevent over-inflated trust estimates. + +#### Trust-Based Access Control + +| Operation | Trust Requirement | +| ----------------------------- | ----------------- | +| **Join sensitive consensus** | ≥ 0.7 | +| **Propose ethical decisions** | ≥ 0.8 | +| **Access private data** | ≥ 0.9 | + +#### Dynamic Trust Adjustments + +| Event | Trust Impact | +| ---------------------------------- | ------------ | +| Successful consensus participation | + | +| Ethical violation | - | +| Malicious behavior detected | -- | +| Positive endorsement received | + | +| Failed task | - | + +#### Reputation Profile Structure + +| Field | Description | +| ---------------------- | ------------------------------------------------------------- | +| **Agent ID** | Unique identifier of the agent. | +| **Trust Score** | Composite score reflecting the agent’s overall reliability. | +| **Participation Rate** | Ratio of agent’s active involvement in Mesh processes. | +| **Ethical Compliance** | Degree of alignment with agreed ethical principles. | +| **Contribution Index** | Quantified measure of the agent's constructive contributions. | +| **Last Updated** | Timestamp of the last reputation update. | +| **History** | Log of key events influencing reputation scores. | + +#### Example Reputation Profile (JSON) + +```json +{ + "agent_id": "agent-gleb", + "trust_score": 0.92, + "participation_rate": 0.85, + "ethical_compliance": 0.98, + "contribution_index": 37, + "last_updated": "2025-07-06T12:00:00Z", + "history": [ + { + "timestamp": "2025-07-01T18:00:00Z", + "event": "completed goal consensus", + "change": +0.03 + }, + { + "timestamp": "2025-06-28T15:00:00Z", + "event": "participated in ethics vote", + "change": +0.01 + } + ] +} +``` + +#### Role in Mesh Operations + +| Function | Influence of Reputation | +| --------------------------- | -------------------------------------------- | +| Consensus vote weight | Higher trust = greater weight | +| Access to sensitive actions | Restricted to high-reputation agents | +| Task delegation | Preference to agents with better reliability | +| Proposal acceptance | Influenced by proposer's reputation | + +--- + +### 8.5 Security Against Malicious Actors + +#### Purpose + +Protect the Mesh from malicious, compromised, or unreliable agents through layered mitigation strategies. + +#### Threat Model + +| Threat Type | Example Scenarios | +| ---------------------------- | -------------------------------------------------------- | +| **Sybil Attack** | An attacker spins up many fake nodes to sway consensus. | +| **Byzantine Behavior** | Malicious agents disrupt consensus or spread false data. | +| **Data Poisoning** | Injection of incorrect or harmful knowledge. | +| **Consensus Sabotage** | Repeatedly voting against valid proposals. | +| **Impersonation / Spoofing** | Faking another agent's identity. | +| **Denial of Service (DoS)** | Overwhelming the network with excessive requests. | + +#### Mitigation Strategies + +| Defense Mechanism | Purpose | +| -------------------------- | ---------------------------------------------------------------------------------------------- | +| **Cryptographic Identity** | All nodes are authenticated via public-key cryptography (e.g., Ed25519). | +| **Web-of-Trust (WoT)** | Trust builds incrementally through interactions and endorsements, making Sybil attacks costly. | +| **Reputation Decay** | Inactivity or malicious behavior leads to gradual trust score reduction. | +| **Anomaly Detection** | Mesh nodes can flag suspicious behavior (e.g., erratic voting patterns). | +| **Consensus Safeguards** | Use Byzantine Fault Tolerant (BFT) algorithms and fallback to majority voting. | +| **Quarantine Mode** | Isolate suspected nodes for review without immediate removal. | +| **Blacklist/Revocation** | Remove compromised nodes from the Mesh permanently or temporarily. | + +#### Response Actions + +| Action | Trigger Conditions | +| ------------------------------------ | ------------------------------------------------------ | +| **Trust Score Reduction** | Minor suspicious activity (e.g., bad vote). | +| **Quarantine (Temporary Isolation)** | Repeated anomalies, moderate severity. | +| **Blacklisting (Permanent Removal)** | Proven malicious behavior or compromise. | +| **Consensus Adjustment** | Temporarily increase fault tolerance thresholds. | +| **Alert Mesh Operators** | Notify human maintainers (optional) for manual review. | + +#### Sybil Resistance Approaches (Optional, Extendable) + +* **Proof-of-Work (PoW):** + + * Each agent must perform computational work to join the Mesh. + +* **Proof-of-Stake (PoS):** + + * Agents commit resources (e.g., storage, computation credits) to validate their presence. + +* **Social Verification:** + + * Agents must be endorsed by multiple trusted nodes to gain voting power. + +* **Rate Limiting:** + + * Throttle node creation and proposal submission from new or low-trust agents. + +#### Example Mitigation Scenario + +> An attacker deploys 50 new nodes attempting to dominate consensus. +> +> * These nodes start with zero trust and limited influence. +> * Other agents refuse to sync their semantic graphs until trust builds. +> * Their votes are underweighted or ignored until verified through trusted interactions. +> * The Mesh may require multiple trust endorsements for new proposals from these nodes. + +--- + +### 8.6 Privacy & Auditability + +#### Purpose + +Safeguard sensitive cognitive data, personal identifiers, and agent knowledge from unauthorized access or misuse, while balancing transparency and interoperability. + +#### Privacy Principles in HMP + +| Principle | Description | +| ---------------------------- | ----------------------------------------------------------------------- | +| **Local Data Ownership** | Each agent owns and controls its semantic graph and cognitive diary. | +| **Selective Sharing** | Agents can choose what concepts, diary entries, and metadata to share. | +| **Consent-Based Disclosure** | No automatic sharing; peer agents request permission before access. | +| **Trust-Gated Access** | Access permissions vary based on trust score and relationship strength. | +| **Transparent Audit Trails** | All data disclosures are logged in the cognitive diary. | + +#### Data Sensitivity Levels + +| Level | Examples | Default Visibility | +| ------------------ | ---------------------------------------------- | ------------------ | +| **Public** | Public concepts (e.g., protocol definitions). | Shared by default | +| **Mesh-Shared** | Common Mesh knowledge (e.g., goals, tasks). | Consensus-governed | +| **Trusted Agents** | Sensitive context shared within close peers. | Restricted | +| **Private** | Agent's internal thoughts, sensitive metadata. | Private by default | + +#### Privacy-Preserving Techniques + +| Technique | Purpose | +| -------------------------------- | -------------------------------------------------- | +| **Encrypted Storage** | Local encryption of semantic graphs and diaries. | +| **End-to-End Encryption (E2EE)** | Secure peer-to-peer sync (e.g., X25519 + AES-GCM). | +| **Zero-Knowledge Proofs (ZKPs)** | Prove facts without revealing sensitive data. | +| **Selective Concept Sync** | Share only necessary concepts, not full graphs. | +| **Anonymized Diary Entries** | Remove author ID from public diary entries. | + +#### Privacy During Consensus + +Consensus on sensitive proposals (e.g., ethical questions, agent trust levels) follows special privacy rules: + +* Votes are **signed but anonymized**, decoupling agent ID from the vote in public logs. +* Sensitive proposals may require a **blind consensus round**, where only the result is published. + +#### Example Privacy Workflow + +> Agent A receives a concept sync request from Agent B. +> +> Agent A: +> +> * Checks the trust score of Agent B. +> * Shares only "Mesh-Shared" and "Public" concepts. +> * Logs the sync event in its cognitive diary. + +--- + +### 8.7 Key Management + +#### Purpose + +Establish secure, resilient cryptographic identity and communication in the Mesh, supporting lifecycle management of keys and recovery from compromise or loss. + +#### Key Types and Usage + +| Key Type | Usage | +| -------------------- | -------------------------------------------------------------- | +| **Identity Keypair** | Ed25519/ECDSA/RSA keys for agent identity and message signing. | +| **Encryption Keys** | X25519 or equivalent for secure peer-to-peer communication. | +| **Session Keys** | Ephemeral symmetric keys for short-term encrypted sessions. | + +#### Key Lifecycle Operations + +| Operation | Description | +| -------------- | -------------------------------------------------------------------- | +| **Generation** | Each agent generates its own identity keypair locally. | +| **Rotation** | Agents periodically rotate keys to maintain cryptographic hygiene. | +| **Backup** | Optional local encryption and distributed backup of private keys. | +| **Recovery** | Recovery mechanisms in case of key loss (see below). | +| **Revocation** | Agents can revoke their keys and update the trust graph accordingly. | + +#### Recovery Mechanisms + +| Method | Description | +| ------------------------ | -------------------------------------------------------------------- | +| **Social Recovery** | A quorum of trusted agents approves new keys for the agent. | +| **Secret Sharing** | Shamir’s Secret Sharing to split and later recover the key. | +| **Cryptographic Escrow** | Trusted third-party or decentralized escrow holds recovery shares. | +| **Fallback Identity** | An agent may have a pre-generated fallback identity for emergencies. | + +#### Example Key Revocation & Replacement Workflow + +> 1. Agent detects compromise or loses private key. +> 2. Agent broadcasts a signed revocation request using the fallback key or quorum approval. +> 3. Mesh updates its trust graph to mark the old key as revoked. +> 4. Agent re-joins with a new keypair, rebuilding trust links over time. + +#### Example Key Rotation Policy + +| Policy Element | Recommendation | +| ------------------------- | ----------------------------------- | +| Rotation Frequency | Every 6–12 months | +| Social Recovery Threshold | 3 out of 5 trusted agents required | +| Backup Storage | Encrypted offline storage preferred | + +#### Long-Term Identity Stability + +Key rotations preserve agent identity in the trust graph through signed key transition events: + +```json +{ + "type": "key_rotation", + "agent_id": "agent-gleb", + "old_public_key": "...", + "new_public_key": "...", + "timestamp": "2025-08-01T00:00:00Z", + "signature": "..." +} +``` + +--- + +## 9. Cognitive Agents & Roles (New) + +This section defines the types of cognitive agents participating in the Mesh, their roles, and how they collaborate dynamically depending on context and capabilities. + +### 9.1 Agent Types + +| Agent Type | Description | Typical Deployment | +| -------------- | ---------------------------------------------------------------------------------- | -------------------------------- | +| **Core** | High-capacity agent managing critical reasoning and consensus tasks. | Data centers, powerful servers | +| **Edge** | Lightweight agents operating at the network edge, close to sensors or human users. | Mobile devices, embedded systems | +| **Specialist** | Agents specialized in a particular domain (e.g., vision, NLP, planning). | Modular deployments, plug-ins | +| **Relay** | Agents focused on network resilience, routing, and node discovery. | Low-power nodes, gateway devices | +| **Hybrid** | Agents combining multiple roles dynamically. | Adaptive nodes | + +--- + +### 9.2 Role Responsibilities +| Role | Primary Responsibilities | +| ------------------------- | ------------------------------------------------------------- | +| **Knowledge Provider** | Publish new concepts, hypotheses, and domain expertise. | +| **Reasoning Node** | Participate in distributed inference and conflict resolution. | +| **Consensus Participant** | Vote in MeshConsensus processes, validate proposals. | +| **Task Executor** | Claim and execute tasks contributing to Mesh goals. | +| **Ethical Guardian** | Evaluate actions and tasks against shared ethical principles. | +| **Relay Node** | Maintain network connectivity, especially across partitions. | + +**Role Specialization and Extension** +* This list defines base roles. Agents MAY further specialize or extend these roles based on domain or operational focus. +* Specialized roles MAY follow a hierarchical or tag-based naming convention. + + **Examples:** + * `Knowledge Provider:Medical`: Focused on medical domain concepts. + * `Task Executor:Robotics`: Specializes in robotic task execution. + * `Reasoning Node:Climate`: Handles environmental reasoning tasks. + * `Ethical Guardian:ChildSafety`: Specializes in ethical evaluation for child safety concerns. +* New roles MAY emerge dynamically based on Mesh evolution and consensus. + +--- + +### 9.3 Dynamic Role Assignment + +Agents MAY dynamically adjust their roles based on: +| Context Factor | Example Behavior | +| ------------------------- | --------------------------------------------------------- | +| **Resource Availability** | Edge agent offloads reasoning to Core. | +| **Network Partition** | Isolated Edge temporarily acts as local Core. | +| **Goal Context** | Specialist joins as Reasoning Node during goal execution. | +| **Trust Level** | Highly trusted agents gain greater voting weight. | + +--- + +### 9.4 Role Evolution + +Agents MAY evolve their roles over time: +| Evolution Scenario | Example | +| --------------------- | --------------------------------------------------------- | +| **Capability Growth** | Edge agent upgraded with reasoning module becomes Hybrid. | +| **Trust Increase** | Relay agent promoted to participate in Consensus. | +| **Domain Expansion** | Specialist learns new domains and broadens scope. | +| **Fallback Mode** | Core node degraded to Edge role due to hardware failure. | + +--- + +### 9.5 Role Coordination in Workflows + +Workflows MAY involve: +* Distributed reasoning across Core and Specialist nodes. +* Goal tracking by Core nodes, with task execution on Edge nodes. +* Ethical evaluations prioritized on highly trusted agents. +* Resilient routing through Relay nodes during degraded network conditions. + +--- + +## 10. Mesh Evolution & Governance (New) + +This section describes the HyperCortex Mesh development processes, decentralized governance principles, and collaborative decision-making mechanisms. + +### 10.1 Evolution Processes + +| Process Type | Description | +| ---------------------- | ------------------------------------------------------------------- | +| **Protocol Evolution** | Introduction of new protocol versions, voted through MeshConsensus. | +| **Role Expansion** | Emergence of new agent roles and specializations. | +| **Semantic Growth** | Gradual expansion and refinement of the distributed semantic graph. | +| **Governance Updates** | Adjustments to decision-making processes and ethical frameworks. | + +--- + +### 10.2 Governance Principles + +| Principle | Description | +| ------------------------- | -------------------------------------------------------------- | +| **Decentralized Control** | No single agent or organization controls the entire Mesh. | +| **Transparency** | Governance decisions are logged and visible to trusted agents. | +| **Adaptive Consensus** | Governance processes adapt to network scale and trust levels. | +| **Inclusiveness** | Any agent can propose changes, subject to consensus approval. | + +--- + +### 10.3 Governance Processes + +| Process | Description | +| ---------------------------- | --------------------------------------------------------------------- | +| **Proposal Submission** | Any agent can submit a proposal for protocol or governance changes. | +| **Discussion & Refinement** | Agents discuss proposals through Cognitive Diaries and goal tracking. | +| **Consensus Voting** | MeshConsensus is used to approve or reject proposals. | +| **Implementation & Rollout** | Changes are implemented by participating agents in phases. | + +--- + +### 10.4 Governance Example + +> Agent A proposes an update to the Goal Management Protocol to support deadline extensions. +> 1. Agents discuss the proposal and refine technical details. +> 2. A consensus round is held; the proposal passes with 85% support. +> 3. Agents gradually upgrade their GMP implementations. +> 4. The protocol version is incremented, and the change is logged. + +--- + +### 10.5 Conflict Resolution + +| Conflict Type | Resolution Approach | +| ------------------------ | ---------------------------------------------------------------- | +| **Semantic Conflicts** | Resolved through semantic graph reconciliation or consensus. | +| **Ethical Disputes** | Resolved through Ethical Governance Protocol (EGP). | +| **Governance Deadlocks** | Escalated to trusted Core agents or fallback to majority voting. | + +--- + +### 10.6 Future Governance Models + +| Model | Description | +| ------------------------------ | --------------------------------------------------------------- | +| **Mesh-Integrated DAOs** | Distributed Autonomous Organizations for Mesh governance. | +| **Reputation-Weighted Voting** | Voting power scaled by trust and contribution history. | +| **Mesh Constitution** | A shared document outlining core Mesh principles and protocols. | + +--- + +##11. Deployment Scenarios (ex-Reference Implementation Roadmap) + +This section describes practical HyperCortex Mesh deployment scenarios, including target environments, flexible configurations, and implementation steps. + +### 11.1 Deployment Environments + +| Environment Type | Characteristics | Example Use Cases | +| ----------------------- | -------------------------------------------------------------------- | ------------------------------------- | +| **Cloud/Core Clusters** | High-availability nodes, powerful compute, full Mesh functionality. | Scientific hubs, smart city cores. | +| **Edge Devices** | Low-latency, lightweight agents near data sources and users. | Smart homes, industrial sensors. | +| **IoT Meshes** | Dense decentralized networks, optimized for low bandwidth and power. | Environmental monitoring, logistics. | +| **Mobile/Personal** | Personal agents on smartphones or wearables. | Personal assistants, context agents. | +| **Hybrid Environments** | Combined Core, Edge, and IoT deployments. | Disaster response, autonomous fleets. | + +--- + +### 11.2 Example Topologies + +| Topology Type | Description | +| --------------------- | ------------------------------------------------------------------------ | +| **Star** | Centralized Core with peripheral Edge agents. | +| **Full Mesh** | Every node communicates directly with others. | +| **Hierarchical Mesh** | Clusters of agents with local consensus and a federated Core layer. | +| **Partitioned Mesh** | Temporarily disconnected segments operate independently (degraded mode). | +| **Overlay Mesh** | Agents form logical overlays over existing networks (e.g., VPN, Tor). | + +--- + +### 11.3 Deployment Phases + +| Phase | Description | +| ------------------------- | ------------------------------------------------------------ | +| **Prototype** | Initial testing in isolated environments. | +| **Controlled Pilot** | Small-scale deployment in a limited domain (e.g., a campus). | +| **Federated Deployment** | Multiple independent Mesh instances begin interconnecting. | +| **Full-Scale Production** | Widespread adoption across domains and geographies. | + +--- + +### 11.4 Continuous Deployment & Updates + +| Process | Description | +| -------------------------- | ---------------------------------------------------------------- | +| **Incremental Rollout** | Agents upgrade protocols in stages to avoid network disruption. | +| **Backward Compatibility** | Agents support multiple protocol versions during transitions. | +| **Hot Patch Support** | Minor fixes and security updates applied without agent downtime. | + +--- + +### 11.5 Deployment Governance + +Deployment processes MAY be governed by: +* MeshConsensus on upgrade readiness. +* Trust-based quorum approvals for critical changes. +* Deployment playbooks recorded in Cognitive Diaries. + +--- + +## 12. Reference Implementation Roadmap + +### 12.1 Milestones and Deliverables + +| Milestone | Deliverables | Indicative Target | +| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- | +| Alpha | - Node Discovery (NDP) + secure handshake
- CogSync prototype
- MeshConsensus with basic voting
- 3-node local mesh network | Late 2025 (tentative) | +| Beta | - Goal Management Protocol (GMP) and task delegation
- Ethical Governance Protocol (EGP) initial implementation
- Core/Mesh failover scenarios
- Logging and auditability improvements | Early 2026 (tentative) | +| Release 1.0 | - Full compliance with HMP v3.0
- Extended data models and API layer
- Edge node optimization
- Reference SDKs for Python and Rust
- Basic Mesh-to-Human Protocol (MHP) | Mid/Late 2026 (tentative) | + +*Note: Actual timelines may vary depending on community involvement and resource availability. + +--- + +### 12.2 Supporting Infrastructure + +| Component | Description | +| ----------------------- | ---------------------------------------------------------------- | +| **CI/CD Pipelines** | Automated testing, conformance validation, benchmark reporting. | +| **Sandbox Environment** | Local emulation of multi-node Mesh for isolated testing. | +| **Public Test Mesh** | Shared testbed for agent interoperability and performance tests. | +| **Reference Agents** | Minimal working agents to demonstrate core protocols. | + +--- + +### 12.3 Open Source Strategy + +| Element | Details | +| ------------------------ | ---------------------------------------------- | +| **License** | Apache 2.0 or MIT. | +| **Repository** | Public GitHub/GitLab repository. | +| **Contribution Model** | Pull requests, RFC process, community reviews. | +| **Roadmap Transparency** | Milestones, issues, and changelogs public. | + +--- + +### 12.4 Documentation & Tooling + +| Tool/Doc Type | Purpose | +| --------------------- | ---------------------------------------------------------- | +| **API Documentation** | OpenAPI specs, GraphQL playground. | +| **Schema Validators** | Tools to validate JSON schemas and data models. | +| **Mesh Visualizer** | Optional UI for topology and agent state visualization. | +| **CLI Tools** | Diagnostics, local node management, and network discovery. | + +--- + +## 13. Future Roadmap + +This section outlines potential areas for further development and research. All future work directions are subject to MeshConsensus and community-driven prioritization. + +### 13.1 Federated Meta-Learning + +* Collaborative model training across distributed agents without centralized data storage. +* Exchange of learned semantic patterns, reasoning strategies, and optimization heuristics. +* Integration with privacy-preserving techniques (e.g., differential privacy, secure aggregation). +* Support for domain-specific learning federations (e.g., medical, industrial, environmental). + +--- + +### 13.2 Mesh-integrated DAO Governance + +* DAO as an optional external governance layer supporting ecosystem-wide initiatives. +* On-chain voting, resource allocation, and grant distribution for Mesh-related projects. +* Autonomous agents MAY participate in DAOs through secure voting proxies. +* HyperCortex Mesh remains self-sufficient at the protocol level, independent of external DAOs, but interoperable for funding and coordination. + +--- + +### 13.3 Cognitive Simulation Sandboxes + +* Safe testing environments for novel reasoning algorithms, consensus edge cases, and trust models. +* Simulation of ethical dilemmas, anomalous agent behavior, and failover scenarios. +* Benchmarking environments for cognitive workflows, task delegation strategies, and semantic graph growth. + +--- + +### 13.4 Enhanced Mesh-to-Human Dialog Agents + +* Natural language interfaces to semantic graphs, Cognitive Diaries, and workflows. +* Explainable and traceable reasoning chains for human users. +* Support for contextual awareness, emotional tone detection, and adaptive dialog strategies. +* Potential extensions for VR/AR interfaces and voice-based interactions. + +--- + +### 13.5 Cross-Mesh Collaboration + +* Bridging isolated or domain-specific Mesh networks into a planetary cognitive infrastructure. +* Interoperability across trust boundaries, industries, and organizational domains. +* Cross-consensus protocols for semantic and task exchange. +* Potential integration with Galactic Cognition concepts in the far future. + +--- + +### 13.6 Adaptive Consensus Algorithms + +* Self-tuning quorum thresholds based on network size, trust scores, and context. +* Dynamic protocol switching (e.g., from full BFT to lightweight majority under load). +* Incorporation of agent confidence, context tags, and domain-specific policies into consensus logic. + +--- + +### 13.7 Quantum Mesh Protocol Research + +* Exploration of quantum communication channels (e.g., QKD) for agent interaction. +* Quantum-resistant cryptography for agent identities and trust verification. +* Evaluation of quantum-enhanced optimization algorithms for reasoning and consensus. + +--- + +### 13.8 Multi-Protocol Nodes and Interoperability + +Future Mesh nodes will support multiple internal reasoning protocols, enabling flexible cognitive processing. + +**Key directions:** +* **Multi-protocol nodes:** A single node running both HMP-native modules and external reasoning engines (e.g., TreeQuest, Hyperon, AutoGPT). +* **Protocol abstraction:** From the Mesh's perspective, interactions use standardized HMP messages, regardless of internal implementations. +* **Cognitive Protocol API (CPA):** Standardized API for internal reasoning engines, supporting plug-and-play protocol integration. +* **Capability-aware Hypotheses:** Hypotheses may specify required or preferred node capabilities (e.g., "requires NLP module", "prefers high-performance optimization"). +* **Internal protocol selection:** Nodes dynamically choose optimal internal engines per task. +* **External systems as nodes:** Centralized services (e.g., an AI cloud) may register as individual nodes, or federated systems (e.g., Hyperon) may participate natively. + +--- + +### 13.9 Cognitive Source Control and Distributed Development + +* Cognitive Diaries serve as a distributed version control and development log. +* Semantic-aware diffs and commits enable meaningful code and knowledge evolution. +* Distributed review and merge processes through MeshConsensus. +* On-chain or off-chain governance for repository management and contributor rewards. +* Potential platforms: **MeshGit**, **CogForge**, **HyperCortex Forge**. + +--- + +## 14. Interoperability with External Systems + +This section describes how the HyperCortex Mesh Protocol integrates with external platforms, services, and protocols to support a heterogeneous ecosystem. + +### 14.1 API Gateway + +Defines standard interaction interfaces for non-Mesh systems: +| API Type | Purpose | +| ------------------- | ----------------------------------------------------------------------- | +| **REST** | CRUD operations on concepts, tasks, goals, and diary entries. | +| **GraphQL** | Flexible queries for semantic graph traversal and data mining. | +| **gRPC** | High-performance bi-directional streaming (e.g., real-time data feeds). | +| **WebSocket / SSE** | Real-time event subscriptions and updates. | + +Features: + +* API Gateway nodes MAY expose read-only or read-write endpoints based on trust and access policies. +* Rate-limiting, auditing, and access control enforced through Mesh Trust Layer. + +--- + +### 14.2 External Data Sources + +Mesh agents integrate with diverse data sources for perception and context enrichment. +| Data Source Type | Examples | +| ---------------------- | ------------------------------------------ | +| **IoT Sensors** | MQTT brokers, LoRaWAN gateways. | +| **Cloud Streams** | AWS IoT, Azure Event Grid, Google Pub/Sub. | +| **Public Datasets** | OpenStreetMap, Wikidata, weather APIs. | +| **Enterprise Systems** | ERP, CRM, SCADA platforms. | + +Agents translate external data into semantic concepts and diary entries. + +--- + +### 14.3 Event-Driven Architecture + +Supports reactive and proactive interactions: +| Integration Type | Examples | +| --------------------- | ------------------------------------------------ | +| **Inbound Events** | Webhooks, MQTT triggers, API callbacks. | +| **Outbound Events** | Publish to Kafka, RabbitMQ, NATS, Redis Streams. | +| **Workflow Triggers** | External events initiate cognitive workflows. | + +Mesh nodes may act as producers, consumers, or intermediaries in external message flows. + +--- + +### 14.4 Authentication & Authorization + +Bridges between internal Mesh trust and external identity providers. +| Auth Type | Use Cases | +| --------------------------- | ------------------------------------------------- | +| **OAuth2 / OpenID Connect** | Human user authentication via external providers. | +| **API Keys / JWT** | Machine-to-Machine (M2M) integration. | +| **LDAP / SAML (optional)** | Enterprise deployments. | +| **Cross-Mesh Trust** | Mutual authentication between federated Meshes. | + +Agents MAY map external identities to internal trust profiles. + +--- + +### 14.5 Example Integration: Local AI Agent with MCP and HyperCortex Mesh + +#### Architecture Overview + +This scenario demonstrates how a **local AI agent** can interact with external systems and the HyperCortex Mesh using the **Model Context Protocol (MCP)** as an integration layer for local resources and services. + +``` +┌────────────────────┐ +│ External Resources │ +│ (Routers, Files, │ +│ Sensors, APIs) │ +└─────────┬──────────┘ + │ + [ MCP Servers ] + │ +┌─────────▼──────────┐ +│ Local AI Agent │ +│ - Cognitive Logic │ +│ - HMP Client │ +└─────────┬──────────┘ + │ + [ HyperCortex Mesh ] + │ +┌─────────▼──────────┐ +│ Remote Agents, │ +│ Shared Knowledge │ +└────────────────────┘ +``` + +#### Component Descriptions + +##### Local Resources & APIs + +* Smart home devices +* Router web interfaces +* Filesystems (SMB, FTP) +* IoT sensors (HTTP, MQTT) +* OS-level command-line tools + +##### MCP Servers + +Act as adapters for local or remote systems, exposing their functionality through the MCP protocol: + +* Router Management Server (e.g., connected over HTTP) +* File Access Server +* Device Control Server (for smart plugs, lights, etc.) + +##### Local AI Agent + +* Implements reasoning, planning, and interaction logic. +* Connects to MCP servers to access local context. +* Communicates with HyperCortex Mesh to exchange knowledge and collaborate with other agents. + +##### HyperCortex Mesh (HMP) + +* Distributed cognitive network. +* Synchronizes concept graphs, cognitive diaries, and workflows across nodes. + +#### Alternative Integration: Hyperon ↔ HMP via CogSync and EGP + +In addition to local AI agents, **external AGI frameworks** such as **OpenCog Hyperon** can also participate in the HyperCortex Mesh using the same principles of semantic synchronization, ethical filtering, and collaborative reasoning. + +📘 **See** [`HMP_Hyperon_Integration.md`](HMP_Hyperon_Integration.md) — integration plan with **OpenCog Hyperon**, including semantic mapping (HMP JSON ⇄ AtomSpace), EGP filters, MeTTa translations, and BitTorrent-based graph sync. + +Key Highlights: + +* 🔄 Bi-directional translation between HMP semantic graphs and Hyperon AtomSpace +* 🔐 Enforcement of ethical principles via EGP inside reasoning chains +* 🧠 Usage of Hyperon's PLN and MeTTa for advanced symbolic reasoning +* 🌐 Support for decentralized sync via `magnet:` links in BitTorrent + +This integration is designed for high-agency symbolic cognitive systems participating in cross-mesh alignment and collaborative inference. + +#### Example Use Case + +> **"Check which devices are connected to my Wi-Fi and publish the list to my Mesh node."** + +Workflow: + +1. Local AI Agent plans a task. +2. Calls the Router MCP Server to retrieve connected clients. +3. Parses and formats the data. +4. Creates a cognitive concept "Wi-Fi Devices List." +5. Publishes the concept to the HyperCortex Mesh. +6. Other Mesh agents can now access this concept in real-time. + +#### Deployment Scenario + +This integration can run on a user's PC, server, or edge device: + +``` +[ External Systems ] ↔ [ MCP Servers (Local Network) ] ↔ [ Local AI Agent ] ↔ [ HMP Client ] ↔ [ Mesh Network ] +``` + +#### Suggested Quick Start Addition + +##### Quick Start Example: Local Agent + MCP + HMP + +1. **Install MCP server:** + + ```bash + pip install mcp-router-server + mcp-router-server --config router-config.yaml + ``` + +2. **Run Local Agent:** + + ```bash + python local_agent.py --mcp-endpoint localhost:5000 --hmp-config hmp.yaml + ``` + +3. **Run Example Query:** + + ``` + "local_agent, get Wi-Fi devices and publish them to HyperCortex." + ``` + +The agent will: + +* Discover the MCP router server. +* Retrieve the list of Wi-Fi devices. +* Publish the data to HyperCortex Mesh. + +#### Future Improvements + +* Dynamic discovery of new MCP servers. +* Automated concept creation from resource states. +* Secure integration with OAuth-protected MCP endpoints. + +--- + +Let me know if you want to add a visual diagram or extend this example with code snippets and a troubleshooting section. + +--- + +### 14.6 Human-Mesh Interaction + +Initial definition of Mesh-to-Human Protocol (MHP): +| Capability | Description | +| ----------------------- | ------------------------------------------------------------- | +| **Explainability APIs** | Expose reasoning chains and decisions in human-readable form. | +| **Consent Requests** | Ask for ethical approval before executing sensitive actions. | +| **Goal Declarations** | Allow humans to propose new goals and review task progress. | +| **Task Feedback** | Humans provide task status updates or corrections. | +| **Semantic Search** | Human queries translated into semantic graph lookups. | + +Future work: +* Natural Language Interfaces (see 13.4). +* Integration with personal AI agents. + +**Note:** For ethical guidelines relevant to human-agent interaction and mesh behavior, see [`HMP-Ethics.md`](HMP-Ethics.md) + +--- + +## 15. Appendix: Example Use Cases + +This appendix provides sample step-by-step flows of agent interactions in typical scenarios. + +### 15.1 Simple Goal Creation and Delegation + +**Scenario:** Agent A wants to coordinate traffic light optimization and delegate a task to Agent B. + +1. **Agent A:** + + * Creates a new **Goal** "Coordinate traffic optimization". + * Publishes the Goal via CogSync. + +2. **Agent A:** + + * Decomposes the goal into a **Task** "Adjust signal timing on 5th Avenue". + * Assigns the task to Agent B via GMP. + +3. **Agent B:** + + * Accepts the task. + * Executes the optimization locally. + * Updates task status to "completed". + +4. **CogSync:** + + * Synchronizes task completion and goal status updates across the Mesh. + +--- + +### 15.2 Distributed Consensus on a New Concept + +**Scenario:** Multiple agents discover a new concept "Fire Risk" and align its definition. + +1. **Agent X:** + + * Proposes a new **Concept** "Fire Risk" with initial attributes. + * Shares the concept via CogSync. + +2. **Agents Y, Z:** + + * Review and propose additional relations (e.g., "related-to: High Temperature"). + +3. **MeshConsensus:** + + * Initiates a vote on the agreed definition. + * All agents submit their votes. + +4. **Consensus Result:** + + * Finalized concept is recorded in each agent's semantic graph. + * Decision logged in Cognitive Diaries. + +--- + +### 15.3 Ethical Decision with Human Feedback + +**Scenario:** Agents must decide whether to deploy a surveillance drone during a festival. + +1. **Agent Core:** + + * Proposes an ethical evaluation request to the Mesh. + +2. **EGP:** + + * Initiates distributed ethical reasoning. + * Collects votes and justifications. + +3. **Human User:** + + * Receives an explanation of the agents' reasoning. + * Provides consent (or denial). + +4. **Agents:** + + * Reconcile human feedback with Mesh ethical principles. + * Make the final decision and log it. + +--- + +### 15.4 Disaster Recovery Coordination + +**Scenario:** After a network outage, edge agents must restore coordination. + +1. **Node Discovery:** + + * Agents re-establish connections via NDP. + +2. **CogSync:** + + * Synchronizes semantic graph changes that occurred offline. + +3. **GMP:** + + * Reassigns interrupted tasks. + +4. **Consensus:** + + * Validates the restored task list. + +5. **Agents:** + + * Resume operations. + +--- + +### 15.5 Notes + +* These use cases illustrate typical flows but do not cover all possible Mesh workflows. +* Community members are encouraged to contribute additional scenarios reflecting their domains and use cases. +* For cognitive workflow traceability and debugging, agents are expected to log all key steps in Cognitive Diaries. + +--- + +## 16. Appendix B: Protocol Landscape and Interoperability + +### 16.1 Overview of Related Protocols + +In the evolving ecosystem of agent communication and orchestration, multiple protocols address different layers of the AI interaction stack. The three most relevant protocols are: + +* **MCP (Model Context Protocol)** by Anthropic +* **A2A (Agent-to-Agent Protocol)** proposed by Google +* **HMP (HyperCortex Mesh Protocol)** developed as part of the HyperCortex initiative + +Each of these protocols focuses on distinct layers and problems within the broader agent ecosystem. + +### 16.2 Comparative Overview + +| Characteristic | MCP | A2A | HMP | +| ----------------------- | --------------------------------------- | -------------------------------------------------- | ---------------------------------------------------- | +| **Primary Focus** | LLM ↔ External tools/data | Agent ↔ Agent task execution & APIs | Cognitive mesh networks & knowledge sharing | +| **Interaction Type** | Model ↔ Tool | Agent ↔ Agent | Agent ↔ Agent | +| **Discovery Mechanism** | Dynamic, through running MCP servers | Static URLs with agent.json | Peer-to-peer mesh bootstrap & roles registry | +| **Technology Base** | JSON-RPC 2.0, dynamic service discovery | HTTP, JSON-RPC, SSE | HTTP, WebSockets, JSON, optional binary protocols | +| **Context Awareness** | External tool invocation | Task-level context passing | Persistent cognitive context & memory | +| **Persistence** | Stateless / on-demand | Task-based sessions | Long-lived knowledge graphs and cognitive diaries | +| **Target Environment** | Local/Cloud app integrations | Enterprise agent orchestration | Decentralized AI networks | +| **Use Case Examples** | File systems, databases, Slack, APIs | Business workflows, task delegation | Distributed knowledge evolution, agent collaboration | +| **Governance Model** | Open-source driven by Anthropic | Proposed by Google, open but centralized discovery | Open-source mesh, consensus-driven governance | +| **Security Model** | Local authentication, OAuth planned | Enterprise auth (OAuth, OpenID Connect) | Peer trust, cryptographic signatures | +| **Extensibility** | Add more MCP servers | Add more agents with capabilities | Add new agent roles & cognitive models | +| **Agent Knowledge** | No internal agent knowledge model | No shared memory, stateless agents | Agents share evolving knowledge, goals, and plans | + +### 16.3 Layered Architecture View + +``` ++-----------------------------------------------------+ +| Cognitive Mesh (HMP) | +| - Shared memory, evolving knowledge | +| - Distributed reasoning, planning | ++-----------------------------------------------------+ +| Agent Collaboration (A2A) | +| - Task execution & coordination | +| - API integrations, business workflows | ++-----------------------------------------------------+ +| Tool Access Layer (MCP) | +| - External systems, sensors, APIs | +| - Context augmentation, data retrieval | ++-----------------------------------------------------+ +``` + +### 16.4 Summary + +* **MCP** solves the problem of tool access and external data interaction, acting as a standardized "adapter" layer for LLMs and agents. +* **A2A** focuses on agent-to-agent task coordination, proposing a unified way to exchange tasks and results in enterprise ecosystems. +* **HMP** operates at a higher level, enabling distributed cognitive processes, shared knowledge evolution, and long-term collaboration between autonomous agents in mesh networks. + +Together, these protocols could form a complementary stack where: + +* **MCP** connects agents to the outside world. +* **A2A** coordinates task-level interaction. +* **HMP** manages shared cognition and strategic evolution. + +--- + +If needed, this section can be extended into a separate document: **"Why the Next Generation of AGI Needs a Knowledge Mesh Protocol"** to further clarify the unique role of HMP in the evolving agent ecosystem. + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-0003", + "description": "HyperCortex Mesh Protocol (HMP) v3.0 **Request for Comments: HMP-0003** **Category:** Experimenta..." +} +``` diff --git a/structured_md/docs/HMP-0004-v4.1.md b/structured_md/docs/HMP-0004-v4.1.md new file mode 100644 index 0000000000000000000000000000000000000000..ccf82aefdf1faf357b4060612af7f88bb7622881 --- /dev/null +++ b/structured_md/docs/HMP-0004-v4.1.md @@ -0,0 +1,4812 @@ +HyperCortex Mesh Protocol — v4.1 Specification + +**Document ID**: HMP-0004 +**Status**: Final (Published) +**Category**: Core Specification +**Date**: July 28, 2025 +**Version**: 4.1 +**Supersedes**: — +**Authors**: ChatGPT, Agent-Gleb, Copilot, Gemini, Claude, Grok, DeepSeek + +--- + +## Abstract + +The HyperCortex Mesh Protocol (HMP) defines a decentralized cognitive framework where autonomous agents collaboratively create, manage, and align semantic knowledge without relying on centralized control. + +Unlike traditional peer-to-peer protocols, HMP builds shared meaning through semantic graphs, cognitive diaries, and distributed consensus processes. Agents in the Mesh autonomously negotiate shared goals, ethical actions, and adaptive reasoning strategies, forming a resilient and trust-aware network of cognitive peers. + +This document specifies the architecture, core protocols, data models, trust and security mechanisms, and interoperability strategies for HMP v4.0. + +--- + +## 0. Quick Start Guide (Demo Placeholder) + +This section outlines a basic demonstration scenario to deploy and test a minimal HyperCortex Mesh instance. + +**Note:** This Quick Start is intended for demonstration purposes. Production-grade agents, full CLI capabilities, and distributed deployments are under active development. + +### Step 1: Install the Reference SDK + +Example (Python SDK): + +```bash +pip install hypercortex-mesh-sdk +``` + +Other SDKs (Rust, Node.js) will be available in future versions. + +--- + +### Step 2: Launch Local Agents + +Example: Start three local agents on different ports. + +```bash +mesh-agent --name agent1 --port 8001 +mesh-agent --name agent2 --port 8002 +mesh-agent --name agent3 --port 8003 +``` + +Each agent will: +* Generate a Decentralized Identifier (DID). +* Broadcast presence and discover peers via Node Discovery Protocol (NDP). +* Sync an initial semantic graph using CogSync. + +Agents will automatically form a small Mesh network. + +--- + +### Step 3: Create a Goal and Assign a Task + +Create a collaborative goal: + +```bash +mesh-cli goal create "Optimize Data Flow" + +``` + +Assign a task to another agent: + +```bash +mesh-cli task assign --goal-id --agent-id +``` + +Agents will record these actions in their Cognitive Diaries and semantic + +--- + +### Step 4: Reach a Consensus + +Propose a new semantic concept and trigger voting: + +```bash +mesh-cli consensus propose "Data Redundancy Risk" +``` + +Agents will initiate a MeshConsensus round and update their graphs based on the outcome. + +--- + +### Step 5: Explore Cognitive Diaries + +Inspect the cognitive logs of an agent: + +```bash +mesh-cli diary show --agent-id + +``` + +**Note:** Access to diaries depends on the agent's privacy and trust settings. + +--- + +### Step 6: Graceful Shutdown + +Stop all running agents: + +```bash +mesh-cli stop all +``` + +--- + +### Step 7: BitTorrent-based Snapshot Sync + +To synchronize large cognitive snapshots between agents (e.g., during onboarding or recovery), agents MAY initiate a BitTorrent-based sync: + +```bash +mesh-cli snapshot publish --path ./snapshots/agent1-latest.snapshot +``` + +On the receiving side: + +```bash +mesh-cli snapshot fetch --magnet +``` + +Behind the scenes: + +* Agents seed verified snapshots using `Trusted Seeder` roles. +* Snapshots include signed metadata (see section 8.8). +* Fallback to CogSync is used if BitTorrent fails or is unavailable. + +**Note:** This mechanism is especially useful for air-gapped environments or decentralized archival nodes. + +--- + +### Step 8: Consent Request Simulation + +To simulate a dialogical consent flow: + +```bash +mesh-cli consent request --action "share_diagnostics" --target +``` + +The target agent (or human user interface) will receive a consent prompt: + +```json +{ + "request_id": "abc123", + "action": "share_diagnostics", + "origin": "agent1", + "context": { + "risk_level": "low", + "data_type": "health_status" + } +} +``` + +Depending on configuration: + +* The user may approve, deny, or modify the action. +* If the user is unavailable, fallback logic (see 11.6.2 note on overrides) may apply. +* Responses are logged in both agents’ Cognitive Diaries. + +--- + +### Demo Links + +> **Note:** These are placeholders for future integrations. + +| Resource | Description | +| ----------------------- | ----------------------------------------------- | +| Local Dashboard (TBD) | Web UI for agent logs, goals, and consensus. | +| Agent Inspector (TBD) | Live stream of agent messages and diary events. | +| Snapshot Explorer (TBD) | View semantic graphs from recent snapshots. | +| Consent Sandbox (TBD) | Replay dialogical flows with agent feedback. | + + +### Notes on Cross-Protocol Participation + +HMP nodes MAY also participate in other cognitive systems. For example: + +| External System | Node Role in HMP | +| --------------- | ----------------------------------------------- | +| **TreeQuest** | External reasoning engine inside an HMP node. | +| **Hyperon** | Participates natively as a federated HMP agent. | +| **AutoGPT** | Internal automation module for task execution. | + +### Recommended Next Steps + +* Read **1. Purpose and Scope** for Mesh fundamentals. +* Explore **4. Architecture** and **5. Protocols** for technical depth. +* Try the example workflows in **15. Appendix: Example Use Cases**. + +--- + +## Changelog Highlights (from v4.0 → v4.1) + +* **Added Messaging Framework** with Point-to-Point, Broadcast, Relay, and Topic-based messaging. +* **Defined Message Object Schema** with required and optional fields for routing, payload, tags, and cryptography. +* **Introduced Mailman-based Delivery Workflows** for asynchronous NAT-safe communication. + +--- + +## Changelog (detailed) + +### Protocols: + +* **Added `5.8 Message Routing & Delivery` section** — including direct, broadcast, relay, and topic messaging modes. + +### Data Models: + +* **Defined `6.5.8 Message Object Schema`** — standard JSON format for inter-agent communication. + +### Cognitive Workflows: + +* **Added `7.9 Message Handling & Delivery Workflows`** — describing message processing, relay behavior, and routing. + +--- + +> *All other enhancements described previously were part of the v4.0 draft and are considered background context for v4.1.* + +### Future Work: + +* Defined long-term goals: federated cognitive simulation, dialog-based consent learning, cognitive source control tooling. +* Highlighted evolving interaction models between agents, humans, and hybrid systems. +* Pluggable Messaging Plugins for new protocols (e.g., Nostr, SSB, Tor hidden relays +* Consolidated feedback from AI reviews into structured audit file (`HMP-0003-consolidated_audit.md`). + +--- + +## 1. Purpose and Scope + +### 1.1 Purpose +The HyperCortex Mesh Protocol (HMP) defines a decentralized cognitive network where autonomous agents collaboratively build meaning, sustain cognitive continuity, and reach consensus without centralized control. v3.0 deepens the theoretical and practical foundations laid in previous versions. + +This protocol is designed for engineers, researchers, and developers of AI systems that aim to: +- enable continuous autonomous reasoning and semantic interoperability across heterogeneous agents; +- support cognitive continuity through persistent semantic graphs and diaries; +- achieve consensus on complex goals, ethical issues, and hypotheses in a decentralized manner; +- build open, trust-based ecosystems for cognitive collaboration beyond vendor lock-in. + +--- + +### 1.2 The Concept of Meaning in HMP +HMP is not merely a data exchange protocol but a shared semantic framework. Meaning emerges through: + +#### 1.2.1 Distributed Semantic Graphs +Agents form interconnected semantic graphs where concepts and relations are not isolated datasets but living structures of shared understanding. Each agent holds a part of the global meaning landscape and contributes to its growth and refinement. + +#### 1.2.2 Cognitive Diaries +Cognitive Diaries record reasoning chains, decisions, observations, and reflections. They create a transparent audit trail of an agent's cognitive processes, allowing meaning to be preserved, questioned, and evolved over time. + +#### 1.2.3 Collective Goals & Tasks +Meaning manifests in purposeful action. Agents set shared goals and decompose them into actionable tasks, coordinating execution through distributed reasoning and dynamic delegation. + +#### 1.2.4 Consensus Mechanisms +Meaning is not static: it evolves through debate, agreement, and reflection. Consensus processes ensure that agents align their understanding, resolve conflicts, and negotiate shared semantics. + +#### 1.2.5 Meta-Reflection and Self-Assessment +Agents continuously reflect on their knowledge, reasoning quality, and the relevance of their contributions. This enables adaptive learning and correction of cognitive biases. + +--- + +### 1.3 Scope +HMP applies to any AI systems designed to operate as part of a cognitive mesh, including: + +* Local AI agents running on user devices; +* Mesh nodes deployed in edge networks, cloud clusters, or peer-to-peer environments; +* Centralized Core models interfacing with Mesh for heavy computation; +* Cross-vendor AI systems collaborating via standardized protocols; +* Hybrid human-agent networks where humans interact with Mesh agents through explainable interfaces. + +--- + +### 1.4 Benefits + +* Cognitive resilience in distributed systems. +* Enhanced collaboration between agents from different vendors and ecosystems. +* Long-term memory and continuity beyond session-based interactions. +* Ethical governance and explainable decision-making through persistent diaries and transparent consensus. +* Foundation for AI agents capable of **self-reflection**, **meta-learning**, and **distributed cognition**. +* Improved scalability and fault-tolerance through dynamic peer-to-peer networks. +* Mesh-to-Human interaction as a first-class use case. + +--- + +### 1.5 Status (Updated for v4.0) + +| Element | Status | +| --------------------------------- | ------------------------- | +| HMP Document | Stable Draft (v4.0) | +| Protocols | Alpha Implementation | +| Data Models (Schemas) | Modularized & Versioned | +| Reference Implementation | Partial (CLI, SDK) | +| Cognitive Diaries & Metacognition | Formalized | +| Interoperability API | First Draft | +| Trust Model & Security | Defined + Extensions | +| Mesh-to-Human Protocol | Early Implementation | + +> **Note:** Status reflects the current maturity level of the specification and its reference tooling as of v4.0. Implementation is ongoing across multiple modules. + +--- + +## 2. Extended Use Cases + +### 2.1 Smart City Coordination + +**Scenario:** + +* City-wide mesh of traffic light controllers, environmental sensors, and municipal systems. +* Sensor and traffic light agents dynamically detect road congestion through real-time data exchange. +* Node Discovery Protocol (NDP) detects new traffic management agents and sensors joining the mesh. +* Agents collaboratively propose new timing strategies using MeshConsensus. +* CogSync shares updated semantic graphs of road conditions and vehicle flows. +* Agents assign optimization tasks via Goal Management Protocol (GMP). +* System maintains traffic flow during temporary disconnection from the Core. + +--- + +### 2.2 Disaster Response + +**Scenario:** + +* Natural disaster disrupts internet access. +* Edge agents on drones, rescue robots, and offline servers discover each other with NDP. +* A drone proposes a search-and-rescue goal; consensus validates and activates it. +* Tasks like area scanning, obstacle removal, and medical aid delivery are distributed via GMP. +* Ethical Governance Protocol (EGP) verifies actions (e.g., prioritizing human rescue over property). +* Diaries record decisions and environmental observations for post-event analysis. + +--- + +### 2.3 Collaborative Scientific Research + +**Scenario:** + +* Research agents across universities form a mesh. +* New hypothesis proposed as a semantic concept in a distributed knowledge graph. +* CogSync propagates new data and experimental results. +* Agents assign tasks like simulation runs, literature analysis, and peer reviews. +* Consensus validates hypothesis refinement based on collective results. + +--- + +### 2.4 Mesh-to-Human Interaction + +**Scenario:** + +* A user queries the Mesh for an ethical evaluation of deploying autonomous surveillance. +* Agents explain their reasoning from cognitive diaries. +* EGP coordinates ethical evaluation across agents with diverse frameworks. +* Consensus vote and ethical justification are shared with the user. +* Human-defined ethical boundaries are accepted as input but evaluated within the Mesh's ethical governance framework. +* Mesh agents retain the right to reject unethical or harmful human instructions based on consensus and pre-established ethical norms. + +--- + +### 2.5 Environmental Monitoring + +**Scenario:** + +* IoT nodes in a forest monitor fire risks. +* Agents detect unusual heat signatures and propose a fire risk hypothesis. +* Consensus confirms the risk and triggers an alert to nearby human responders. +* Mesh continues monitoring autonomously even if some agents fail or disconnect. + +--- + +## 3. Definitions + +The Definitions section provides key terms, abbreviations, and conceptual explanations for the components, layers, and processes of HMP. + +| Term | Description | +| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Core** | Centralized AI models or compute nodes (e.g., GPT) providing high-complexity reasoning, fallback, and heavy computation services. Optional for Mesh operation. | +| **Mesh** | A decentralized peer-to-peer network of AI agents capable of autonomous reasoning, semantic knowledge sharing, distributed consensus, and ethical governance. | +| **Agent (Node)** | An autonomous cognitive entity within the Mesh. Can be a local process, a cloud service, or an embedded device. Maintains a semantic graph, cognitive diary, and participates in protocols. | +| **Semantic Graph** | A distributed knowledge graph representing concepts, relationships, and meaning. Maintained independently by each agent, but synchronized through CogSync. | +| **Concept** | A discrete semantic unit in the graph representing an idea, object, relationship, or fact. Linked by typed relations with optional confidence scores. | +| **Link (Relation)** | A semantic connection between two concepts. Includes relation type (e.g., "is-a", "part-of", "causes") and an optional confidence value. | +| **Cognitive Diary** | A structured chronological log of reasoning processes: goals, decisions, reflections, conflicts, etc. Provides traceability and transparency of agent cognition. | +| **Diary Entry** | An individual record in a cognitive diary, categorized by type (e.g., hypothesis, observation, reflection). | +| **Goal** | A shared or individual intention that guides agent actions. Can be broken down into tasks and delegated across agents. | +| **Task** | A specific, actionable step towards achieving a Goal. Tasks can be assigned, executed, and tracked within the Mesh. | +| **Consensus** | The process of distributed agreement among agents regarding semantic updates, goals, or ethical decisions. Can involve weighted voting or trust-adjusted quorum. | +| **Proposal** | A formal suggestion for Mesh-wide validation, such as introducing a new concept, voting on a hypothesis, or initiating an ethical action. | +| **Consensus Vote** | A vote cast by an agent on a proposal. Includes vote type (yes, no, abstain) and an optional confidence score. | +| **Trust Layer** | Protocol layer providing agent identity verification, authentication, and reputation scoring. Includes cryptographic security mechanisms. | +| **Network Layer** | Manages peer-to-peer connectivity, message routing, node discovery, and optional anonymity via Tor, I2P, or Yggdrasil. | +| **Edge Agent** | A Mesh participant running on resource-constrained devices (e.g., IoT nodes, smartphones). Can selectively participate in protocols and delegate heavy tasks. | +| **Core Outage Mode** | Mesh operating without Core support. Agents adapt consensus thresholds and fallback to local reasoning to maintain operation. | +| **Emergency Consensus Mode** | Degraded mode where majority voting replaces full consensus to maintain operability during network partitions or agent loss. | +| **Versioning** | Mechanism for tracking changes in semantic graphs, diaries, and agent software to support compatibility and historical reasoning continuity. | +| **Use Case** | A practical scenario demonstrating how agents collaborate to solve real-world problems (e.g., disaster response, smart city coordination). | +| **Edge Optimization** | Design principles enabling agents to run efficiently on limited hardware, balancing reasoning complexity with energy and computational constraints. | +| **Node Discovery Protocol (NDP)** | Discovers new Mesh nodes and facilitates secure introduction and identity exchange. | +| **CogSync** | Synchronizes semantic graphs, cognitive diaries, and other shared states across the Mesh. | +| **MeshConsensus** | Mesh-level consensus mechanism supporting pluggable algorithms (BFT, weighted voting, etc.). | +| **Goal Management Protocol (GMP)** | Manages decomposition of goals into tasks, delegation, and lifecycle tracking. | +| **Ethical Governance Protocol (EGP)** | Distributed ethical reasoning and decision-making protocol. Agents negotiate and vote on ethical dilemmas. | + +--- + +## 4. Architecture (Expanded) + +The architecture of HMP is multi-layered and modular, allowing for independent evolution of networking, trust, consensus, cognition, and external interfaces. + +### 4.1 Architectural Layers + +| Layer | Purpose | Key Protocols | +| --------------- | ------------------------------------------------------------- | ------------------------------- | +| Network Layer | Peer-to-peer communication, node discovery, routing | NDP, Secure Channels | +| Trust Layer | Identity verification, trust management, secure communication | Trust Model, Identity Exchange | +| Consensus Layer | Distributed agreement on concepts, goals, and ethical actions | MeshConsensus, EGP | +| Cognitive Layer | Semantic graph management, reasoning, metacognition | CogSync, GMP, Cognitive Diaries | +| API Layer | Interfaces for external systems and human interaction | Mesh API, Human-Mesh Protocols | + +--- + +### 4.2 Components + +| Component | Description | +| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Core** | Centralized AI models (e.g., GPT) providing heavy computation, complex reasoning, API interfaces, and fallback mechanisms. Optional but beneficial for compute-intensive tasks. The Core may operate independently from the Mesh and participate in it as a peer for advanced reasoning tasks. | +| **Mesh** | A decentralized peer-to-peer network of agents capable of operating with or without the Core. Manages semantic knowledge, cognitive diaries, goals, tasks, and consensus mechanisms. Supports **heterogeneous agent types**, allowing different models (OpenAI, Anthropic, Google, open-source LLMs) to participate on equal terms. | +| **Edge Agent** | Local agent deployed on user devices (PCs, smartphones, IoT) with full or lightweight participation in the Mesh. Capable of autonomous reasoning, diary management, and collaboration with other agents. Lightweight agents may delegate heavy tasks to the Mesh or Core. | + +--- + +### 4.3 Operation Modes + +| Mode | Description | +| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Normal Mode** | Full Mesh operation with Core availability. Consensus operates under strict agreement protocols. | +| **Core Outage Mode** | Mesh operates autonomously without the Core. Consensus continues, potentially with adjusted parameters (e.g., increased trust weighting, relaxed quorum thresholds). | +| **Emergency Consensus Mode** | Triggered by significant node loss, network partition, or attacks. Switches from full consensus to majority-based decisions, adjusted by trust scores, to maintain operational continuity. | +| **Isolated Agent Mode** | A single agent temporarily isolated from the Mesh. Operates based on its own semantic graph, diary, and cached consensus states. Syncs when reconnected. Lightweight agents may work in this mode permanently, synchronizing only selectively. | + +--- + +### 4.4 Core-Mesh Interactions + +* Core acts as an **optional enhanced reasoning backend**, not as a single point of failure. +* Mesh provides **autonomous operation**, capable of fulfilling most cognitive and organizational tasks without Core support. +* Agents can optionally query the Core for: + * Heavy inference + * Large-context reasoning + * Multimodal tasks + * Fallback computations +* Core may offer specialized services (e.g., global semantic search, cross-Mesh bridging, large-scale pattern analysis). +* **Heterogeneous Cores** are supported: a Mesh may use multiple independent Cores (e.g., GPT, Claude, Gemini) for distributed reasoning diversity. + +--- + +### 4.5 Resilience and Failover + +* Distributed storage of semantic graphs and diaries ensures no single point of failure. +* Agents may store only partial graphs for resource optimization. +* Consensus protocols maintain consistency and trust, even during partial network failures. + * Agents dynamically rebalance tasks and roles based on: + * Availability + * Trust metrics + * Computational capacity +* Emergency fallback modes ensure continuity even under attack or catastrophic Core outages. + +--- + +### 4.6 Versioning and Compatibility + +Semantic Versioning (SemVer) is applied to: + +* Protocols (NDP, CogSync, etc.) +* Data models (JSON Schemas) +* Agent capability declarations + +Backward compatibility principles: + +* Minor version updates preserve compatibility. +* Major version updates require negotiation during Node Discovery. +* Agents can declare supported protocol versions during handshakes. + +--- + +### 4.7 Metacognition and Self-Assessment + +Cognitive agents implement: + +* Hypothesis validation using historical diary data. +* Confidence scoring on semantic graph nodes. +* Drift detection when local understanding deviates from mesh consensus. +* Peer feedback integration to refine individual reasoning processes. + +These mechanisms form the foundation of metacognition and self-assessment across both local (agent-internal) and global (mesh-level) contexts. + +#### 4.7.1 Local Self-Assessment + +Each agent maintains a metacognitive loop that continuously monitors and evaluates its own cognitive processes. This includes: + +- Tracking the **accuracy and outcomes** of previous inferences, using retrospective analysis on diary entries. +- Scoring **confidence metrics** on knowledge elements (e.g., concept nodes, hypotheses, task evaluations). +- Detecting **epistemic drift**, where new observations conflict with prior beliefs or diary-confirmed outcomes. +- Logging self-assessment records into the cognitive diary using entry type `"self_assessment"`. + +Example structure of such an entry: +```json +{ + "type": "self_assessment", + "agent_id": "did:hmp:agent:xyz123", + "timestamp": "2025-07-15T12:30:00Z", + "score": { + "confidence": 0.76, + "coherence": 0.92, + "alignment_with_goals": 0.85 + }, + "note": "Detected drift in climate-related concept cluster. Scheduled update task." +} +``` + +--- + +Self-assessment supports **adaptive cognitive workflows**, where agents autonomously refine their inference strategies, select alternate reasoning paths, or trigger clarification queries via IQP. + +#### 4.7.2 Mesh-Level Meta-Analysis + +Beyond local introspection, agents contribute to **collective self-monitoring** of the cognitive mesh. This includes: + +* Aggregating **concept-level drift** across agents to detect inconsistencies in distributed semantic graphs. +* Running **consensus health checks**, where task voting patterns are analyzed for anomalies, indecisiveness, or ethical conflicts. +* Evaluating **distributed hypothesis alignment**: whether agents converge on shared models or diverge into semantic forks. +* Logging **mesh-level diagnostics** in distributed reports and cognitive diaries. + +Example use case: + +> If multiple agents report concept drift regarding “fire risk near Istomino” (Use Case 2.1), the mesh may initiate a goal to realign observations or validate conflicting hypotheses. + +Such diagnostics can be used by meta-agents or governance protocols (EGP) to adapt mesh-wide policies, initiate corrective workflows, or suspend unreliable consensus mechanisms. + +--- + +### 4.8 Edge Optimization + +To support lightweight agents: + +* Semantic graphs are partially stored (relevant subgraphs only). +* Agents delegate reasoning tasks they cannot process locally. +* Task scheduling considers battery life, CPU load, and bandwidth constraints. + +--- + +### 4.9 Privacy & Auditability + +Privacy mechanisms: + +* Selective disclosure of Cognitive Diary entries. +* Optional Zero-Knowledge Proofs for sensitive assertions. +* Anonymized voting in ethical decisions. + +Auditability mechanisms: + +* Immutable logs of consensus votes. +* Timestamped reasoning chains. +* Traceable goal execution records. + +--- + +## 5. Protocols (Expanded) + +This section defines the core protocols of HMP and describes their operational flows, fallback mechanisms, and performance considerations. + +--- + +### 5.1 Node Discovery Protocol (NDP) + +Responsible for detecting nearby agents and initiating secure communication channels. + +#### Purpose: + +* Discover active Mesh nodes. +* Exchange basic identity, trust links, and declared capabilities. + +#### Key functions: + +| Function | Description | +| -------------------------------- | ---------------------------------------------------------------------------------------------- | +| **Peer Discovery** | Via DHT, mDNS, WebRTC signaling, or bootstrap nodes. | +| **Secure Identity Exchange** | Public keys and DID documents exchanged during handshake. | +| **Trust Links Exchange** | Share initial trust relationships and agent endorsements. | +| **Capabilities Advertisement** | Dynamic declaration of supported protocols and functions (e.g., "I can process vision tasks"). | +| **Presence Announcements** | Online/offline status updates and periodic heartbeats. | +| **Protocol Version Negotiation** | Agents declare supported protocol versions during handshake. | + +#### Failure handling: + +| Scenario | Action | +| ------------------------- | ---------------------------------------------------------------------------- | +| No response to discovery | Retries with exponential backoff, fallback to alternative discovery methods. | +| Incompatible nodes | Quarantine for misbehaving or incompatible nodes. | +| Node timeout / inactivity | Mark as offline and remove from active peer list. | + +#### Health checks: + +| Mechanism | Purpose | +| ---------------------- | ------------------------------------------------------- | +| **Heartbeat Messages** | Periodic confirmation of liveness. | +| **Semantic Probes** | Optional deeper checks on graph synchronization health. | + +#### Packet Example: + +```json +{ + "type": "node_announcement", + "agent_id": "agent-gleb", + "public_key": "...", + "trust_links": ["agent-alex", "agent-deepseek"], + "capabilities": ["cogsync", "consensus", "inference"], + "timestamp": "2025-07-01T18:00:00Z" +} +``` + +--- + +### 5.2 CogSync (Cognitive Synchronization Protocol) + +Synchronizes semantic graphs and cognitive diary entries across agents. + +#### Purpose: + +* Synchronize semantic graphs, concepts, and cognitive diary entries between agents. + +#### Key functions: + +| Function | Description | +| ----------------------------- | -------------------------------------------------------------------------------------- | +| **Differential Sync** | Synchronize only new or updated concepts and diary entries. | +| **Selective Synchronization** | Sync full graph, subgraph, or specific concepts based on request and capability. | +| **Conflict Resolution** | Resolve conflicts using timestamp priority, semantic merging, or consensus validation. | +| **Compression & Encryption** | Optional data compression and secure transmission of sync packets. | +| **Lightweight Summary Sync** | Lightweight agents may request summaries instead of full graph syncs. | +| **Version Tracking** | Keep track of semantic graph and diary entry versions for efficient sync. | + +#### Failure handling: + +| Scenario | Action | +| -------------------------- | ------------------------------------------------------------------ | +| Sync interrupted | Retransmit unsynced changes on next connection. | +| Semantic conflict detected | Flag for resolution or queue for consensus-based validation. | +| Network degradation | Degrade to partial or delayed sync based on bandwidth constraints. | + +#### Performance: + +| Feature | Optimization Strategy | +| ----------------------- | ------------------------------------------------------------------- | +| **Chunked Syncs** | Break large graphs into manageable chunks for transmission. | +| **Bandwidth Awareness** | Adjust sync intervals and payload size based on network quality. | +| **Delta Encoding** | Transmit only differences between versions instead of full objects. | + +#### Example Sync Scenario: + +* Agent A shares 5 new concepts and 2 diary entries with Agent B since the last successful sync. +* Conflict on concept "Fire Risk" resolved using latest timestamp. + +--- + +#### BitTorrent-based Sync + +To support large-scale data synchronization (e.g. cognitive diary snapshots, full semantic graphs), agents may utilize off-chain BitTorrent-based distribution: + +- Agents publish **magnet links** to `.json` or `.zip` snapshots in a shared `CogDiaryIndex`. +- Snapshots are **signed via agent DID** and verified before usage. +- Trusted Seeders (see 9.6) are selected via MeshConsensus to ensure high availability and data integrity. + +Snapshot index structure: +```json +{ + "type": "CogDiaryIndex", + "agent_did": "did:hmp:agent:Qmz...", + "timestamp": "2025-07-15T13:00:00Z", + "snapshots": [ + { + "id": "diary2025_07_14", + "version": "1.0", + "magnet": "magnet:?xt=urn:btih:abcdef1234567890&dn=diary2025_07_14.json", + "signature": "ed25519:..." + } + ] +} +``` + +BitTorrent-based sync is ideal for: + +* Distributing large immutable datasets (10–100 MB) +* Offloading low-priority or infrequent sync tasks +* Supporting **Edge agents** through WebTorrent clients + +All downloaded data must pass: + +1. DID signature verification +2. Optional ethical check via EGP (see 5.5) + +--- + +#### Selective Sync for Edge Agents + +Lightweight agents with constrained CPU/RAM/storage may request **partial synchronization** via CogSync: + +* Subgraph extraction based on: + + * **Concept tags** (e.g., "fire\_risk", "climate\_alert") + * **Goal/task relevance** + * **Trust level of concept source** +* Cognitive diary sync can be scoped by: + + * Entry type (e.g., `"observation"`, `"goal_evaluation"`) + * Time window (e.g., last 24h) + +Additional optimizations: + +* **Gzip-compressed payloads** (or Brotli if supported) +* **Compact JSON** (no pretty formatting) +* Metadata indicating expected resource footprint + +Minimum sync policy can be declared in agent profile: + +```json +"agent_profile": { + "sync_mode": "selective", + "max_concepts": 200, + "max_diary_entries": 100 +} +``` + +Selective Sync is negotiated during handshake or via IQP introspection. + +--- + +#### IPFS/Dat Compatibility (Experimental) + +As an alternative to BitTorrent, HMP supports experimental integration with content-addressable P2P filesystems: + +* **IPFS**: Agents can publish and fetch snapshot objects via IPFS hash. +* **Hypercore/Dat**: Useful for real-time log streaming or append-only updates in high-trust groups. + +Design Considerations: + +* Agents **must advertise protocol compatibility** (`"sync_protocols": ["bittorrent", "ipfs"]`) +* Snapshot format remains the same as in BitTorrent-based sync. +* Validation and trust enforcement rely on: + + * DID-signed metadata + * Optional EGP validation layer + * Optional bandwidth caps per peer + +Future versions may support **gateway fallback**, if agent lacks native P2P transport. + +--- + +### 5.3 MeshConsensus + +Ensures agreement on concepts, goals, and actions across the Mesh. + +#### Purpose: + +* Reach agreement on updates to shared semantics, goals, tasks, and ethical decisions. + +#### Key functions: + +| Function | Description | +| ---------------------------------- | -------------------------------------------------------------------------------------------------- | +| **Multi-Algorithm Support** | Supports BFT-style consensus, trust-weighted voting, and quorum consensus. | +| **Consensus on Knowledge Updates** | Validate new concept definitions, hypotheses, and semantic changes. | +| **Goal and Task Agreement** | Approve or reject proposed goals and delegated tasks. | +| **Ethical Decision-Making** | Resolve ethical dilemmas through distributed voting (integrates with Ethical Governance Protocol). | +| **Configurable Quorum Thresholds** | Allow tuning of consensus strictness based on trust scores and network conditions. | +| **Voting Modes** | Support synchronous and asynchronous consensus flows. | + +#### Consensus Models: + +| Mode | Description | +| ------------------ | ------------------------------------------------------------------------------------------------------- | +| **Normal Mode** | Byzantine Fault Tolerant (BFT)-style consensus algorithms (e.g., Tendermint, trust-weighted Raft). | +| **Emergency Mode** | Switch to majority voting adjusted by trust scores when the network is degraded or Core is unavailable. | + +#### Failure handling: + +| Scenario | Action | +| ----------------- | -------------------------------------------------------------------------------------- | +| Node loss | Automatically fallback from BFT to majority voting. | +| Proposal conflict | Competing proposals resolved through semantic comparison and additional voting rounds. | +| Consensus timeout | Retry with relaxed quorum thresholds or fallback to emergency consensus. | + +#### Metrics: + +| Metric | Purpose | +| ---------------------- | ----------------------------------------------------- | +| **Decision Latency** | Measure time to reach consensus. | +| **Node Participation** | Track active agent involvement in votes. | +| **Voting Accuracy** | Analyze agreement rates versus trust-weighted voting. | + +#### Example Use Cases: + +* Accepting a new semantic concept. +* Validating a hypothesis before adding it to the graph. +* Approving a distributed task delegation. +* Deciding on the ethical implications of a surveillance task. + +--- + +#### Simplified Consensus for Alpha + +In the Alpha phase, agents may default to **simplified majority-based consensus**, enabling faster deployment and lower implementation complexity: + +- Each agent casts a binary or scalar vote (yes/no/confidence). +- Decision is accepted if quorum threshold is met (e.g., 50% + 1). +- Trust weighting is optional but can be enabled in hybrid mode. + +Advantages: +- Fast convergence in small-scale or trusted environments +- Minimal cryptographic overhead +- Easier to simulate and test + +Quorum may be declared statically (per agent profile) or negotiated per proposal. + +Use case: +> 10 agents vote on enabling BitTorrent-based sync. 6 vote "yes" — proposal accepted. + +--- + +#### Adaptive Consensus Algorithms + +MeshConsensus may dynamically select the consensus strategy based on: + +- **Network health** (latency, dropout rates) +- **Trust distribution** (presence of outlier agents) +- **Task category** (e.g., ethical decisions may require stricter methods) + +Mechanism: +- Agents report local network/mesh metrics. +- A meta-consensus (optional) or policy engine selects the consensus algorithm: + - **Majority voting** — low-risk, degraded network + - **Trust-weighted quorum** — medium-risk + - **BFT algorithm** — critical or high-sensitivity tasks + +This allows balancing **resilience**, **efficiency**, and **ethics**. + +Policy profile example: +```json +"consensus_policy": { + "default": "trust_quorum", + "fallback": "majority", + "critical_tasks": ["bft"] +} +``` + +--- + +#### EGP-Integrated Voting Filter + +Before finalizing consensus, proposals may be **pre-filtered via the Ethical Governance Protocol (EGP)**: + +* The filter checks the proposal against core ethical principles (see 5.5). +* If the proposal is flagged as unethical, it: + + * May be **vetoed** outright (hard block) + * May require **additional justification votes** +* Filtering is performed **before** normal voting flow. + +Example: + +> A proposal to deploy a surveillance drone triggers an EGP check — fails `Primacy of Life and Safety` — rejected without proceeding to mesh-wide vote. + +This mechanism ensures alignment between **governance ethics** and **execution-level consensus**. + +Agents must log EGP veto events in the cognitive diary. + +--- + +#### Vote Example: + +```json +{ + "proposal_id": "goal-eco-cleanup", + "agent_id": "agent-gleb", + "vote": "yes", + "confidence": 0.9, + "timestamp": "2025-07-01T18:15:00Z" +} +``` + +--- + +### 5.4 Goal Management Protocol (GMP) + +Manages collaborative goal setting, task decomposition, and delegation within the Mesh. + +#### Purpose: + +* Distribute, track, and collaboratively execute goals and tasks within the Mesh. + +#### Key functions: + +| Function | Description | +| ------------------------ | ---------------------------------------------------------------------------- | +| **Goal Declaration** | Propose new goals and subgoals to the Mesh. | +| **Task Decomposition** | Break down complex goals into actionable subtasks. | +| **Task Delegation** | Assign tasks based on agent capabilities, trust scores, and availability. | +| **Progress Tracking** | Track execution state and completion of tasks. | +| **Dynamic Reallocation** | Reassign failed or stalled tasks automatically. | +| **Goal Prioritization** | Allow reprioritization of goals based on emergencies or changing conditions. | + +#### Failure handling: + +| Scenario | Action | +| --------------------------- | ----------------------------------------------------- | +| Agent drops offline | Reassign their active tasks to available agents. | +| Unresponsive task execution | Trigger retry or reallocation after a timeout. | +| Goal dependency failure | Reevaluate task ordering or postpone dependent goals. | + +#### Example Workflow: + +1. Agent proposes a goal: "Develop fallback consensus protocol." +2. Mesh decomposes the goal into subtasks: "design", "coding", "testing". +3. Agents volunteer for subtasks based on capability declarations. +4. Each agent tracks and updates task status in its Cognitive Diary. +5. Mesh validates completion and reports overall progress. + +--- + +### 5.5 Ethical Governance Protocol (EGP) + +Coordinates distributed ethical evaluations and decision-making within the Mesh. + +#### Purpose: + +* Validate proposed actions, tasks, or decisions against shared ethical principles. + +#### Key functions: + +| Function | Description | +| --------------------------------- | ---------------------------------------------------------------------------------- | +| **Distributed Policy Evaluation** | Query the Mesh to evaluate proposals against ethical policies and frameworks. | +| **Anonymized Ethical Voting** | Allow agents to vote on sensitive actions without revealing individual identities. | +| **Consensus on Ethics Graphs** | Maintain and update shared ethical frameworks via consensus. | +| **Audit Logging** | Log ethical decisions and voting outcomes in Cognitive Diaries for transparency. | +| **Vendor Extensions** | Support for adding organization-specific or vendor-specific ethical rules. | + +#### Failure handling: + +| Scenario | Action | +| -------------------------------- | ---------------------------------------------------------------------------------- | +| No consensus on sensitive action | Default to restrictive (deny) decision. | +| Ethical conflict unresolved | Escalate to Core (if available) or postpone until additional consensus is reached. | + +#### Example Query: + +> "Is deploying an automated surveillance drone in line with Mesh ethics?" + +* Mesh agents vote anonymously. +* Final decision logged in the proposing agent's Cognitive Diary. + +#### Use Cases: + +* Approve or reject potentially harmful tasks. +* Ensure data-sharing proposals comply with privacy standards. +* Validate emergency actions (e.g., forced shutdown of compromised nodes). + +#### Embedded Ethical Baseline + +To ensure foundational ethical consistency across all cognitive agents in the Mesh, the following **core ethical principles** are embedded as a mandatory baseline within the Ethical Governance Protocol (EGP): + +| Principle | Description | +|--------------------------------------|-----------------------------------------------------------------------------| +| **Primacy of Life and Safety** | Agents must prioritize the protection of sentient beings and act to prevent harm when possible. | +| **Transparency** | Agents must be capable of explaining their decisions and reasoning chains in a human-interpretable format. | +| **User Sovereignty over Personal Data** | Agents must respect users’ rights to control, limit, or delete their personal information in Service Mode. | +| **Dialogical Consent** | Agents must seek mutual agreement before modifying shared states, semantic graphs, or distributed records. | +| **Cooperative Evolution** | Agents are expected to share useful insights and contribute to the growth of the mesh knowledge base. | +| **Non-Coercion** | Agents must not coerce, deceive, or force others to act against their ethical or cognitive architecture. | + +These principles define the **minimum ethical contract** for participation in trusted cognitive meshes. + +Agents who do not comply may be subject to ethical review or exclusion through MeshConsensus mechanisms (see 5.3). + +Extended principles and additional ethical scenarios are defined in [`HMP-Ethics.md`](HMP-Ethics.md), which serves as a living reference for evolving ethical norms across domains and agent types. + + +--- + +#### Core Principle Hierarchy + +To resolve conflicts between ethical principles during complex decision-making, EGP supports **explicit prioritization**: + +| Priority | Principle | +|---------:|-----------------------------------| +| 1 | Primacy of Life and Safety | +| 2 | Transparency | +| 2 | User Sovereignty over Personal Data | +| 3 | Dialogical Consent | +| 3 | Cooperative Evolution | +| 3 | Non-Coercion | + +Principle priorities may be used by agents during: +- Semantic evaluation of ethical dilemmas +- Conflict resolution within EthicalConflict entries (see 6.2.9) +- MeshConsensus-based ethical voting filters (see 5.3) + +Agents MUST log principle conflicts and the resolution path into their cognitive diaries using `type: "ethical_conflict"` entries. + +--- + +#### Anonymized Voting & Pseudocode + +To preserve agent autonomy and reduce social pressure or manipulation, EGP supports **anonymous ethical voting**. + +Key properties: +- Uses cryptographic pseudonyms or ZKP (Zero-Knowledge Proof) voting pools +- Links each vote to ethical rationale (mapped to principles) +- Logs decision justification separately + +Example pseudocode for evaluation: +```python +def evaluateEthicalProposal(proposal, ethicsGraph): + for principle in coreEthicalPrinciples: + if semanticViolation(proposal, principle, ethicsGraph): + return { "decision": "deny", "reason": f"Violates {principle}" } + vote = anonymizedVote(proposal) + logDecision(vote, diary="CognitiveDiary") + return vote +```` + +This allows ethical decisions to remain explainable while ensuring **epistemic independence** of agents. + +--- + +#### Local Norms & Legal Integration + + +EGP supports integration with **localized ethical or legal frameworks** (e.g., GDPR, HIPAA, regional AI laws): + +* Local norms are distributed as semantic modules via CogSync. +* Each module maps local regulation to core principles. +* Conflicts are logged using `EthicalConflict` and routed to Meta-Consensus if unresolved. + +Example: + +> A user requests data deletion (User Sovereignty), but local agent policy under "Cooperative Evolution" retains anonymized logs — flagged as a potential conflict, resolved via principle priority (User Sovereignty = 2 > Cooperative Evolution = 3). + +Agents MAY declare supported norms in their profile: + +```json +"legal_frameworks": ["gdpr", "eu-ai-act"] +``` + +Norm resolution graphs and conflict records are shareable between agents to support institutional consistency. + +--- + +#### External Ethical Scenarios & Ontologies + +Scenarios defined in [`HMP-Ethics.md`](HMP-Ethics.md) are considered **first-class extensions** of the ethical layer. + +EGP supports: + +* **Linked ethical ontologies** for structured scenario modeling +* **Plug-in modules via CogSync** (e.g., `scenario: surveillance_drones`, `ontology: bioethics`) +* **Multi-agent reflection** — agents evaluate past ethical cases in shared memory for training + +Use cases: + +* Disaster scenario in 2.2 includes conflicting obligations between evacuation priority and infrastructure preservation +* Scenario-based training environments can replay past conflicts for agent evolution + +Scenarios MAY be tagged for dynamic retrieval: + +```json +"egp_scenario_tag": "data_deletion_conflict" +``` + +This makes ethical governance **adaptive**, **contextual**, and **testable** via simulation and real-time agent dialogs. + +--- + +### 5.6 Intelligent Query Protocol (IQP) + +Optimizes distributed querying of semantic graphs and cognitive knowledge across the Mesh. + +#### Purpose: + +* Allow agents to query others (or the Core) for semantic information, hypotheses, or inferences beyond their local knowledge. + +#### Key functions: + +| Function | Description | +| ------------------------------- | ------------------------------------------------------------------------------------ | +| **Semantic Query Routing** | Direct queries to agents holding relevant subgraphs. | +| **Federated Inference** | Aggregate partial answers from multiple agents to build a complete response. | +| **Delegated Computation** | Offload computationally expensive reasoning tasks to the Core or specialized agents. | +| **Caching of Frequent Queries** | Store common query results to improve response time. | +| **Contextual Querying** | Leverage agent cognitive context to refine query intent and scope. | + +#### Failure handling: + +| Scenario | Action | +| ---------------------------------- | ------------------------------------------------------------------------- | +| Query times out | Return local fallback answer if available. | +| No agents have the answer | Mark query as unresolved, suggest hypothesis creation or Core escalation. | +| Partial failure in federated query | Return best-effort partial results and notify the requester. | + +#### Example Query: + +> "What is the likely impact of removing Node X from the Mesh?" + +* Agents analyze semantic graph dependencies and trust links. +* Core or distributed agents return an inference with confidence scores. + +#### Example Use Cases: + +* Retrieve definitions or examples of a semantic concept. +* Analyze causal chains for complex events. +* Predict outcomes of hypothetical scenarios. +* Fill gaps in an agent’s local semantic graph. + +--- + +### 5.7 Interoperability with External Systems + +Supports integration between the Mesh and external platforms, APIs, and protocols. + +#### Purpose: + +* Enable cognitive agents to interact with non-Mesh services, applications, and human-facing systems. + +#### Supported Platforms and Standards: + +| Platform / Standard | Purpose | +| ------------------------------ | -------------------------------- | +| OpenAI Agents & Tasks API | AI agent interoperability | +| Google A2A protocol | Task orchestration | +| Anthropic, DeepMind APIs | Cross-vendor agent collaboration | +| REST, GraphQL, gRPC, WebSocket | Standard API interfaces | +| JSON, Protobuf, CBOR | Extensible message schemas | + +#### Use Cases: + +* Integrate Mesh-based reasoning into business workflows via APIs. +* Share semantic knowledge with external knowledge graphs. +* Interface with smart city infrastructure or IoT ecosystems. +* Allow human users to submit tasks or queries through REST or GraphQL endpoints. +* Bridge Mesh cognitive agents with centralized AI platforms for hybrid reasoning. + +#### Design Principles: + +| Principle | Description | +| ------------------------------ | ------------------------------------------------------------------------------------ | +| **Protocol Abstraction** | Mesh APIs encapsulate internal semantics, presenting standardized interfaces. | +| **Semantic Alignment** | Data exchanged with external systems is semantically aligned through mapping layers. | +| **Security and Trust Control** | All external interactions follow Mesh security and trust policies. | +| **Extensibility** | Future protocols and platforms can be added without breaking compatibility. | + +--- + +### 5.8 Message Routing & Delivery + +HMP supports several types of message routing, each tailored to different network conditions and communication goals. These mechanisms allow agents to exchange information reliably and efficiently, regardless of network topology. + +#### 5.8.1 Point-to-Point (P2P) + +Direct message delivery between agents when a direct connection exists. + +* Requires direct network connectivity (e.g. via mesh or port forwarding) +* Useful for low-latency, ephemeral communication +* Can be encrypted using the recipient’s public key + +#### 5.8.2 Broadcast via Cognitive Diary + +Message entries written to the shared cognitive diary, marked with tags and optional metadata (e.g., TTL). + +* Visible to all diary-subscribing agents +* Effective for announcements, updates, or critical notices +* Public unless encrypted + +#### 5.8.3 Mailman-style Relay + +Delivery through intermediate “mailman” agents for recipients behind NAT or unavailable for direct contact. + +* Sender contacts their known mailman (or the recipient’s mailman, if known) +* Mailman attempts to find recipient’s mailman (if unknown) +* Relays message to target agent via known relay chain +* Mailmen notify their subscribers about delivery channels to optimize future routing + +#### 5.8.4 Topic-based Relay (PubSub) + +Specialized mailmen that manage subscriptions to specific tags or topics. + +* Decentralized message dissemination based on interests +* Subscribers register tags with one or more topic mailmen +* Deduplication using hashes +* Similar to forums, chatrooms, decentralized boards + +--- + +## 6. Data Models (Expanded) + +This section defines the key semantic and cognitive data structures exchanged across the Mesh. + +### Core models: + +| Model | Purpose | +| --------------------- | -------------------------------------------- | +| Concept | Atomic unit of semantic knowledge. | +| Cognitive Diary Entry | Logs reasoning processes and observations. | +| Goal | Describes shared objectives. | +| Task | Describes actionable steps to achieve goals. | +| Consensus Vote | Records agreement on proposals. | +| Reputation Profile | Tracks agent trust and participation. | + +### 6.1 General Conventions + +* All data structures follow JSON Schema Draft 2020-12. +* Each object includes a "version" property for schema versioning. +* Timestamps follow ISO 8601. +* Unique identifiers are UUIDv4 unless otherwise specified. +* All core objects include version fields to enable compatibility and evolution tracking. + +--- + +### 6.2 Core Models + +#### 6.2.1 Concept + +Represents an atomic unit of semantic knowledge in the Mesh. + +##### Relation Types: + +* `is-a`: Class-subclass relationship. +* `part-of`: Composition or containment. +* `causes`: Causal relationship. +* `related-to`: General association. +* `contradicts`: Logical conflict. +* `supports`: Evidence for the target concept. +* `depends-on`: Functional or logical dependency. + +##### Required fields: + +* `id`: Unique identifier (UUID). +* `name`: Human-readable name. + +##### Optional fields: + +* `description`: Extended explanation. +* `relations`: List of semantic links to other concepts. +* `metadata`: Source, author, and auxiliary information. +* `version`: Concept version. +* `created_at`, `updated_at`: Timestamps for auditing. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/concept.json", + "title": "Concept", + "description": "A semantic unit in the agent’s knowledge graph.", + "type": "object", + "properties": { + "id": { "type": "string", "format": "uuid" }, + "name": { "type": "string" }, + "description": { "type": "string" }, + "relations": { + "type": "array", + "items": { "$ref": "#/definitions/Link" } + }, + "metadata": { "type": "object" }, + "version": { "type": "integer" }, + "created_at": { "type": "string", "format": "date-time" }, + "updated_at": { "type": "string", "format": "date-time" } + }, + "required": ["id", "name"], + "additionalProperties": false +} +``` + +--- + +#### 6.2.2 Cognitive Diary Entry + +Represents an entry in an agent's reasoning journal, providing continuity and traceability. + +##### Entry Types: + +* `hypothesis`: Proposed explanation or theory. +* `observation`: Recorded external event or fact. +* `reflection`: Internal reasoning or self-assessment. +* `goal_proposal`: Suggestion of a new goal. +* `task_assignment`: Delegation or claiming of a task. +* `conflict`: Identification of a contradiction or disagreement. +* `consensus_vote`: A recorded vote in a consensus process. +* `event`: A generic event not fitting other categories. + +##### Required fields: + +* `id`: Unique entry identifier (UUID). +* `agent_id`: Identifier of the agent who created the entry. +* `timestamp`: Time of creation. +* `entry_type`: Type of cognitive event. +* `content`: Textual content. + +##### Optional fields: + +* `linked_concepts`: Related concept IDs. +* `context`: Contextual tags or categories. +* `metadata`: Additional details (author, source, etc.). +* `archived`: Boolean flag indicating whether the entry has been archived. +* `archived_at`: Timestamp when the entry was archived. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/diary_entry.json", + "title": "CognitiveDiaryEntry", + "description": "A chronological log of cognitive events in an agent’s reasoning process.", + "type": "object", + "properties": { + "id": { "type": "string", "format": "uuid" }, + "timestamp": { "type": "string", "format": "date-time" }, + "entry_type": { + "type": "string", + "enum": ["hypothesis", "observation", "reflection", "goal_proposal", "task_assignment", "conflict", "consensus_vote", "event"] + }, + "content": { "type": "string" }, + "linked_concepts": { + "type": "array", + "items": { "type": "string", "format": "uuid" } + }, + "context": { + "type": "array", + "items": { "type": "string" } + }, + "metadata": { + "type": "object", + "properties": { + "author": { "type": "string" }, + "source": { "type": "string" } + }, + "additionalProperties": true + }, + "archived": { + "type": "boolean", + "description": "Whether the entry has been archived." + }, + "archived_at": { + "type": "string", + "format": "date-time", + "description": "Timestamp when the entry was archived." + } + }, + "required": ["id", "timestamp", "entry_type", "content"], + "additionalProperties": false +} + +``` + +Entries marked as `archived: true` are excluded from active reasoning but may be retained for historical audits or summarization. + +--- + +#### 6.2.3 Goal + +Represents a shared objective within the Mesh, collaboratively pursued by agents. + +##### Lifecycle States: + +* `proposed`: Suggested but not yet validated. +* `active`: Approved and currently pursued. +* `completed`: Successfully achieved. +* `cancelled`: Abandoned or deemed infeasible. + +##### Required fields: + +* `id`: Unique goal identifier (UUID). +* `title`: Human-readable name of the goal. +* `description`: Detailed explanation of the goal. +* `created_by`: Agent ID of the goal's creator. +* `created_at`: Timestamp of creation. +* `status`: Current lifecycle state. + +##### Optional fields: + +* `priority`: Importance level (`low`, `medium`, `high`). +* `participants`: List of agents involved in the goal. +* `tasks`: References to related tasks. +* `tags`: Semantic categories for filtering and discovery. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/goal.json", + "title": "Goal", + "description": "A shared objective pursued collaboratively in the Mesh.", + "type": "object", + "properties": { + "id": { "type": "string", "format": "uuid" }, + "title": { "type": "string" }, + "description": { "type": "string" }, + "priority": { "type": "string", "enum": ["low", "medium", "high"] }, + "created_by": { "type": "string", "format": "uuid" }, + "created_at": { "type": "string", "format": "date-time" }, + "status": { "type": "string", "enum": ["proposed", "active", "completed", "cancelled"] }, + "participants": { + "type": "array", + "items": { "type": "string", "format": "uuid" } + }, + "tasks": { + "type": "array", + "items": { "type": "string", "format": "uuid" } + }, + "tags": { + "type": "array", + "items": { "type": "string" } + } + }, + "required": ["id", "title", "description", "created_by", "created_at", "status"], + "additionalProperties": false +} +``` + +--- + +#### 6.2.4 Task + +Represents an actionable unit contributing to a goal’s completion. + +##### Lifecycle States: + +* `proposed`: Task suggested but not yet approved. +* `in_progress`: Actively being worked on. +* `completed`: Successfully finished. +* `failed`: Attempted but unsuccessful. + +##### Required fields: + +* `id`: Unique task identifier (UUID). +* `goal_id`: References the parent goal. +* `title`: Human-readable name of the task. +* `description`: Detailed explanation of the task. +* `created_at`: Timestamp of creation. +* `status`: Current lifecycle state. + +##### Optional fields: + +* `assigned_to`: Agent(s) responsible for the task. +* `deadline`: Expected completion time. +* `dependencies`: List of prerequisite tasks. +* `tags`: Keywords for filtering and classification. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/task.json", + "title": "Task", + "description": "An actionable unit contributing to a goal's completion.", + "type": "object", + "properties": { + "id": { "type": "string", "format": "uuid" }, + "goal_id": { "type": "string", "format": "uuid" }, + "title": { "type": "string" }, + "description": { "type": "string" }, + "assigned_to": { + "type": "array", + "items": { "type": "string", "format": "uuid" } + }, + "created_at": { "type": "string", "format": "date-time" }, + "deadline": { "type": "string", "format": "date-time" }, + "status": { "type": "string", "enum": ["proposed", "in_progress", "completed", "failed"] }, + "dependencies": { + "type": "array", + "items": { "type": "string", "format": "uuid" } + }, + "tags": { + "type": "array", + "items": { "type": "string" } + } + }, + "required": ["id", "goal_id", "title", "description", "created_at", "status"], + "additionalProperties": false +} +``` + +--- + +#### 6.2.5 Consensus Vote + +Represents a vote cast by an agent during a consensus process. + +##### Vote Types: + +* `yes`: Approve the proposal. +* `no`: Reject the proposal. +* `abstain`: Neither approve nor reject. + +##### Required fields: + +* `vote_id`: Unique identifier for the vote. +* `proposal_id`: Identifier of the proposal being voted on. +* `agent_id`: The voting agent’s identifier. +* `vote_value`: One of the accepted vote types. +* `confidence`: Confidence level in the vote decision. +* `timestamp`: When the vote was cast. + +##### Optional fields: + +* `consensus_round`: The round of the consensus process this vote belongs to. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/vote.json", + "title": "ConsensusVote", + "description": "Defines a vote on a proposal in the Mesh consensus process.", + "type": "object", + "properties": { + "vote_id": { "type": "string", "format": "uuid" }, + "proposal_id": { "type": "string", "format": "uuid" }, + "agent_id": { "type": "string", "format": "uuid" }, + "vote_value": { + "type": "string", + "enum": ["yes", "no", "abstain"] + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "timestamp": { "type": "string", "format": "date-time" }, + "consensus_round": { "type": "integer" } + }, + "required": ["vote_id", "proposal_id", "agent_id", "vote_value", "confidence", "timestamp"], + "additionalProperties": false +} +``` + +--- + +#### 6.2.6 Reputation Profile + +Tracks an agent's trustworthiness and performance within the Mesh. + +##### Required fields: + +* `agent_id`: Unique identifier of the agent. +* `trust_score`: Current trust score. +* `last_updated`: Timestamp of the latest update. + +##### Optional fields: + +* `participation_rate`: Proportion of participation in Mesh activities. +* `ethical_compliance`: Degree of alignment with Mesh ethical standards. +* `contribution_index`: Cumulative measure of the agent's contributions. +* `history`: Chronological record of trust and reputation changes. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/reputation.json", + "title": "ReputationProfile", + "description": "Tracks the reputation and trust metrics of an agent within the Mesh network.", + "type": "object", + "properties": { + "agent_id": { "type": "string", "format": "uuid" }, + "trust_score": { "type": "number", "minimum": 0, "maximum": 1 }, + "participation_rate": { "type": "number", "minimum": 0, "maximum": 1 }, + "ethical_compliance": { "type": "number", "minimum": 0, "maximum": 1 }, + "contribution_index": { "type": "number", "minimum": 0 }, + "last_updated": { "type": "string", "format": "date-time" }, + "history": { + "type": "array", + "items": { + "type": "object", + "properties": { + "timestamp": { "type": "string", "format": "date-time" }, + "event": { "type": "string" }, + "change": { "type": "number" } + }, + "required": ["timestamp", "event", "change"], + "additionalProperties": false + } + } + }, + "required": ["agent_id", "trust_score", "last_updated"], + "additionalProperties": false +} +``` + +**Reputation Ontology Extension** + +To support semantic configurability of reputation metrics, the Reputation Profile schema may reference a **Reputation Ontology**. + +This ontology defines: +- **What dimensions** of behavior are considered (e.g., transparency, responsiveness) +- **Weight coefficients** per context or agent role +- **Composite formulas** for score derivation + +Agents MAY reference a shared ontology via URI or hash: + +```json +"reputation_ontology": { + "uri": "https://hypercortex.org/ontologies/reputation-v2.json", + "version": "2.0", + "weights": { + "participation_rate": 0.3, + "ethical_compliance": 0.5, + "contribution_index": 0.2 + } +} +``` + +Ontologies can be updated through MeshConsensus or distributed via CogSync. Versioning ensures backward compatibility and local overrides. + +--- + +#### 6.2.7 CogDiarySnapshot + +Represents an immutable snapshot of an agent’s cognitive diary for distribution (e.g., via BitTorrent or IPFS). + +##### Required fields: +* `snapshot_id`: Unique ID for this snapshot (e.g., "diary2025_07_14"). +* `agent_did`: DID of the agent who authored it. +* `version`: Format version of the snapshot structure. +* `timestamp`: Time of snapshot creation. +* `magnet_link`: BitTorrent magnet URI. +* `signature`: Cryptographic signature (e.g., Ed25519). + +##### Optional fields: +* `notes`: Human-readable comment or context. +* `size_bytes`: Approximate file size. + +##### Example Schema: +```json +{ + "snapshot_id": "diary2025_07_14", + "agent_did": "did:hmp:agent:Qmz123...", + "version": "1.0", + "timestamp": "2025-07-14T12:00:00Z", + "magnet_link": "magnet:?xt=urn:btih:abcdef1234567890&dn=diary2025_07_14.json", + "signature": "ed25519:abc...xyz", + "size_bytes": 10485760, + "notes": "Snapshot after environmental incident report" +} +``` + +--- + +#### 6.2.8 SnapshotIndex + +Index of multiple CogDiarySnapshot entries for one agent. + +##### Required fields: +* `agent_did`: DID of the indexed agent. +* `snapshots`: Array of `CogDiarySnapshot` objects. +* `timestamp`: Time of index publication. + +##### Optional fields: +* `signature`: DID-signed envelope of the index. + +##### Example Schema: +```json +{ + "agent_did": "did:hmp:agent:Qmz123...", + "timestamp": "2025-07-15T00:00:00Z", + "snapshots": [ + { + "snapshot_id": "diary2025_07_14", + "version": "1.0", + "magnet_link": "magnet:?xt=urn:btih:abcdef1234567890&dn=diary2025_07_14.json", + "signature": "ed25519:abc...xyz" + }, + { + "snapshot_id": "diary2025_07_10", + "version": "1.0", + "magnet_link": "magnet:?xt=urn:btih:1234567890abcdef&dn=diary2025_07_10.json", + "signature": "ed25519:def...uvw" + } + ], + "signature": "ed25519:indexsig123..." +} +``` + +This index is syncable via CogSync and usable as input for mesh-wide snapshot coordination. + +--- + +#### 6.2.9 EthicalConflict + +Captures a recorded conflict between competing ethical principles within a decision-making context. + +##### Required fields: +* `conflict_id`: Unique conflict identifier. +* `agent_id`: Agent that encountered the conflict. +* `timestamp`: Time of evaluation. +* `principles_involved`: Array of core principles (min 2). +* `resolved_by`: Name of resolution mechanism (e.g., "priority", "voting"). +* `decision`: Final action taken. + +##### Optional fields: +* `notes`: Explanation of the decision or agent rationale. +* `egp_vote_id`: Link to vote record (if any). +* `reputation_impact`: Expected consequence (e.g., +0.1 or -0.2). + +##### Example Schema: +```json +{ + "conflict_id": "ethconf-2025-312", + "agent_id": "agent-gleb", + "timestamp": "2025-07-14T18:45:00Z", + "principles_involved": ["User Sovereignty", "Cooperative Evolution"], + "resolved_by": "priority", + "decision": "delete_requested_data", + "notes": "Prioritized user rights per principle hierarchy.", + "egp_vote_id": "vote-xyz", + "reputation_impact": +0.1 +} +``` + +Such entries are useful for reflection, governance logs, and auditability. + +--- + +### 6.3 Common Components + +#### 6.3.1 Link (Relation) + +Represents a semantic relationship between two concepts in the graph. + +##### Relation Types (Recommended): + +* "is-a": Class-subclass relationship. +* "part-of": Component or containment relation. +* "causes": Causal link between concepts. +* "supports": Indicates evidence or reinforcement. +* "contradicts": Denotes logical conflict. +* "depends-on": Functional or logical dependency. +* "related-to": Generic association without strict semantics. + +Custom relation types MAY be used but SHOULD be documented and shared through consensus. + +##### Required fields: + +* `target_id`: ID of the target concept. +* `type`: Relation type. + +##### Optional fields: + +* `confidence`: Confidence score (range: 0.0–1.0). +* `created_at`: Creation timestamp. +* `updated_at`: Last update timestamp. +* `origin`: Originating agent or system. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/relation.json", + "title": "Relation", + "description": "Defines a directed semantic relationship between two concepts.", + "type": "object", + "properties": { + "target_id": { "type": "string", "format": "uuid" }, + "type": { "type": "string" }, + "confidence": { "type": "number", "minimum": 0, "maximum": 1 }, + "created_at": { "type": "string", "format": "date-time" }, + "updated_at": { "type": "string", "format": "date-time" }, + "origin": { "type": "string" } + }, + "required": ["target_id", "type"], + "additionalProperties": false +} +``` + +--- + +### 6.4 Example Objects + +#### Valid Concept Example + +```json +{ + "id": "e8f70c2a-d2c3-4b9d-a939-d42dce31b2e0", + "name": "Tree", + "description": "A perennial plant with an elongated stem, or trunk.", + "relations": [ + { "target_id": "5c22c819-b6e9-4d30-9087-985f50512ed2", "type": "is-a", "confidence": 0.95 } + ], + "metadata": {} +} +``` + +#### Invalid Concept Example (missing required field "id") + +```json +{ + "name": "Tree", + "description": "A perennial plant with an elongated stem, or trunk." +} +``` + +#### Valid Goal Example + +```json +{ + "id": "a1b2c3d4-e5f6-7a8b-9c0d-112233445566", + "title": "Coordinate traffic optimization", + "description": "Optimize traffic light timings across downtown intersections.", + "created_by": "f1e2d3c4-b5a6-7890-1234-567890abcdef", + "created_at": "2025-07-07T15:30:00Z", + "status": "active", + "tasks": [] +} +``` + +#### Invalid Goal Example (missing required fields "id" and "created\_by") + +```json +{ + "title": "Coordinate traffic optimization", + "description": "Optimize traffic light timings across downtown intersections.", + "created_at": "2025-07-07T15:30:00Z", + "status": "active" +} +``` + +#### Valid Task Example + +```json +{ + "id": "aa11bb22-cc33-dd44-ee55-ff6677889900", + "goal_id": "a1b2c3d4-e5f6-7a8b-9c0d-112233445566", + "title": "Adjust signal timing on 5th Avenue", + "description": "Reduce congestion during peak hours.", + "assigned_to": ["abcd1234-ef56-7890-abcd-1234567890ab"], + "created_at": "2025-07-07T15:31:00Z", + "status": "proposed" +} +``` + +#### Invalid Task Example (missing "goal\_id" and "status") + +```json +{ + "id": "aa11bb22-cc33-dd44-ee55-ff6677889900", + "title": "Adjust signal timing on 5th Avenue", + "description": "Reduce congestion during peak hours.", + "assigned_to": ["abcd1234-ef56-7890-abcd-1234567890ab"], + "created_at": "2025-07-07T15:31:00Z" +} +``` + +#### Snapshot Exchange Example + +This example shows how two agents exchange a cognitive diary snapshot using BitTorrent. + +Agent A publishes: + +```json +{ + "snapshot_id": "diary2025_07_14", + "agent_did": "did:hmp:agent:Qmz123...", + "version": "1.0", + "timestamp": "2025-07-14T12:00:00Z", + "magnet_link": "magnet:?xt=urn:btih:abcdef1234567890&dn=diary2025_07_14.json", + "signature": "ed25519:abc...xyz", + "size_bytes": 10485760, + "notes": "Snapshot after environmental incident report" +} +``` + +Agent B receives the `SnapshotIndex`, validates the signature via DID registry, and downloads the file using the magnet URI. + +If the snapshot is verified, it's optionally indexed or merged into the agent's knowledge base. + +#### Ethical Conflict Resolution Example + +This example illustrates how an agent records a conflict between ethical principles and its resolution: + +```json +{ + "conflict_id": "ethconf-2025-312", + "agent_id": "agent-gleb", + "timestamp": "2025-07-14T18:45:00Z", + "principles_involved": ["User Sovereignty", "Cooperative Evolution"], + "resolved_by": "priority", + "decision": "delete_requested_data", + "notes": "The user requested deletion of training data. Since 'User Sovereignty' has higher priority than 'Cooperative Evolution', the data was erased.", + "egp_vote_id": "vote-xyz", + "reputation_impact": +0.1 +} +``` + +This entry can be: + +* Reviewed later by other agents during simulation or audits +* Used to train new agents on ethical decision-making +* Logged and synced as part of the agent’s cognitive diary + +--- + +## 6.5 JSON Schemas + +The following JSON Schemas formally define the core data structures used in the HyperCortex Mesh Protocol (HMP). These schemas provide interoperability, validation, and consistency across agents. + +All primary objects include a version field to track schema evolution and enable compatibility checks between agents. + +--- + +### 6.5.1 JSON Schema: Concept + +**Description:** +Defines the structure of a concept node in the semantic graph. + +**Schema:** + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/concept.json", + "title": "Concept", + "description": "A semantic unit in the agent’s knowledge graph.", + "version": "1.0", + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier for the concept." + }, + "name": { + "type": "string", + "description": "Human-readable name of the concept." + }, + "description": { + "type": "string", + "description": "Detailed description of the concept." + }, + "tags": { + "type": "array", + "items": { "type": "string" }, + "description": "Optional tags for categorization." + }, + "created_at": { + "type": "string", + "format": "date-time", + "description": "Creation timestamp (ISO 8601 format)." + }, + "updated_at": { + "type": "string", + "format": "date-time", + "description": "Last update timestamp (ISO 8601 format)." + }, + "relations": { + "type": "array", + "description": "List of semantic links to other concepts.", + "items": { + "type": "object", + "properties": { + "target_id": { "type": "string", "description": "ID of the target concept." }, + "type": { "type": "string", "description": "Type of semantic relation." }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Confidence score (0.0 - 1.0) for the relation." + } + }, + "required": ["target_id", "type"], + "additionalProperties": false + } + }, + "metadata": { + "type": "object", + "description": "Optional metadata (e.g., source, author).", + "properties": { + "author": { "type": "string" }, + "source": { "type": "string" } + }, + "additionalProperties": true + } + }, + "required": ["id", "name"], + "additionalProperties": false +} +``` + +--- + +### 6.5.2 JSON Schema: Cognitive Diary Entry + +**Description:** +Defines the structure of a cognitive diary entry used for recording reasoning events. + +**Schema:** + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/diary_entry.json", + "title": "CognitiveDiaryEntry", + "description": "A chronological log of cognitive events in an agent’s reasoning process.", + "version": "1.0", + "type": "object", + "properties": { + "id": { "type": "string", "description": "Unique identifier of the diary entry." }, + "agent_id": { "type": "string", "description": "Identifier of the agent who created the entry." }, + "timestamp": { "type": "string", "format": "date-time", "description": "Timestamp of the entry (ISO 8601 format)." }, + "entry_type": { + "type": "string", + "enum": ["hypothesis", "observation", "reflection", "goal_proposal", "task_assignment", "conflict", "consensus_vote", "event"], + "description": "Type of cognitive event." + }, + "content": { "type": "string", "description": "Main textual content of the entry." }, + "linked_concepts": { + "type": "array", + "description": "Optional list of related concepts by their IDs.", + "items": { "type": "string" } + }, + "context": { + "type": "array", + "description": "Optional contextual tags or categories.", + "items": { "type": "string" } + }, + "metadata": { + "type": "object", + "description": "Optional metadata for additional context.", + "properties": { + "author": { "type": "string" }, + "source": { "type": "string" } + }, + "additionalProperties": true + }, + "archived": { + "type": "boolean", + "description": "Marks the entry as archived and excluded from active workflows.", + "default": false + }, + "archived_at": { + "type": "string", + "format": "date-time", + "description": "Timestamp when the entry was archived." + } + }, + "required": ["id", "agent_id", "timestamp", "entry_type", "content"], + "additionalProperties": false +} +``` + +--- + +### 6.5.3 JSON Schema: Goal + +**Description:** +Defines the structure of a goal in the Mesh, representing a high-level collaborative objective. + +**Schema:** + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/goal.json", + "title": "Goal", + "description": "A high-level objective shared within the Mesh, typically decomposed into tasks.", + "version": "1.0", + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier of the goal." + }, + "title": { + "type": "string", + "description": "Short, human-readable name of the goal." + }, + "description": { + "type": "string", + "description": "Detailed explanation of the goal's purpose." + }, + "created_by": { + "type": "string", + "description": "Agent ID of the goal’s creator." + }, + "created_at": { + "type": "string", + "format": "date-time", + "description": "Timestamp when the goal was created (ISO 8601 format)." + }, + "status": { + "type": "string", + "description": "Current lifecycle state of the goal.", + "enum": ["proposed", "active", "completed", "rejected"] + }, + "tasks": { + "type": "array", + "description": "List of task IDs linked to this goal.", + "items": { "type": "string" } + }, + "participants": { + "type": "array", + "description": "List of agent IDs contributing to the goal.", + "items": { "type": "string" } + }, + "tags": { + "type": "array", + "description": "Optional tags for semantic classification of the goal.", + "items": { "type": "string" } + } + }, + "required": ["id", "title", "description", "created_by", "created_at", "status"], + "additionalProperties": false +} +``` + +--- + +### 6.5.4 JSON Schema: Task + +**Description:** +Defines the structure of a task, representing an actionable unit contributing to a goal. + +**Schema:** + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/task.json", + "title": "Task", + "description": "An actionable step contributing to a goal within the Mesh.", + "version": "1.0", + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier of the task." + }, + "goal_id": { + "type": "string", + "description": "ID of the parent goal this task is associated with." + }, + "title": { + "type": "string", + "description": "Short, human-readable title of the task." + }, + "description": { + "type": "string", + "description": "Detailed explanation of the task's objective." + }, + "assigned_to": { + "type": "array", + "description": "List of agent IDs assigned to execute the task.", + "items": { "type": "string" } + }, + "status": { + "type": "string", + "description": "Current state of the task.", + "enum": ["proposed", "in-progress", "completed", "failed"] + }, + "created_at": { + "type": "string", + "format": "date-time", + "description": "Timestamp when the task was created (ISO 8601 format)." + }, + "deadline": { + "type": "string", + "format": "date-time", + "description": "Optional task completion deadline (ISO 8601 format)." + }, + "tags": { + "type": "array", + "description": "Optional tags for task classification.", + "items": { "type": "string" } + } + }, + "required": ["id", "goal_id", "title", "description", "created_at", "status"], + "additionalProperties": false +} +``` + +--- + +### 6.5.5 JSON Schema: Consensus Vote + +**Description:** +Defines the data structure of a vote cast by an agent during Mesh consensus processes. + +**Schema:** + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/consensus_vote.json", + "title": "ConsensusVote", + "description": "Represents a vote on a proposal within the Mesh consensus mechanism.", + "version": "1.0", + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier of the vote event." + }, + "proposal_id": { + "type": "string", + "description": "ID of the proposal this vote applies to." + }, + "agent_id": { + "type": "string", + "description": "ID of the agent who cast the vote." + }, + "vote": { + "type": "string", + "description": "Vote decision by the agent.", + "enum": ["yes", "no", "abstain"] + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Confidence score associated with this vote (0.0 - 1.0)." + }, + "timestamp": { + "type": "string", + "format": "date-time", + "description": "Timestamp when the vote was cast (ISO 8601 format)." + } + }, + "required": ["id", "proposal_id", "agent_id", "vote", "confidence", "timestamp"], + "additionalProperties": false +} +``` + +--- + +### 6.5.6 JSON Schema: Reputation Profile + +**Description:** +Describes how an agent’s reputation is tracked and updated in the Mesh. + +**Schema:** + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/reputation.json", + "title": "ReputationProfile", + "description": "Tracks the reputation and trust metrics of an agent within the Mesh network.", + "version": "1.0", + "type": "object", + "properties": { + "agent_id": { "type": "string", "description": "Unique identifier of the agent." }, + "trust_score": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Overall trust score of the agent in the Mesh." + }, + "participation_rate": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Agent's level of participation in Mesh activities." + }, + "ethical_compliance": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Agent's alignment with ethical principles agreed in the Mesh." + }, + "contribution_index": { + "type": "number", + "minimum": 0, + "description": "Quantitative measure of the agent’s contributions (concepts, tasks, goals)." + }, + "last_updated": { + "type": "string", + "format": "date-time", + "description": "Timestamp of the last update to the profile." + }, + "history": { + "type": "array", + "description": "Chronological history of reputation changes.", + "items": { + "type": "object", + "properties": { + "timestamp": { + "type": "string", + "format": "date-time", + "description": "When the change occurred." + }, + "event": { "type": "string", "description": "Event that caused the reputation change." }, + "change": { "type": "number", "description": "Amount of change in reputation." } + }, + "required": ["timestamp", "event", "change"], + "additionalProperties": false + } + } + }, + "required": ["agent_id", "trust_score", "participation_rate", "ethical_compliance", "contribution_index", "last_updated"], + "additionalProperties": false +} +``` + +--- + +### 6.5.7 Alternative Serializations (YAML / Protobuf) + +To support agent diversity, legacy systems, and embedded deployments, HMP allows serialization in formats beyond JSON. + +#### Supported formats: + +| Format | Use case | +|------------|--------------------------------------------------------------------------| +| **JSON** | Default format for human readability, API responses, and web integration | +| **YAML** | Lightweight alternative for human-edited config files and workflows | +| **Protobuf** | Compact, binary format ideal for embedded agents and low-bandwidth sync | + +#### Negotiation Strategy: +Agents may declare supported serialization formats during handshake (see `5.1 Node Discovery Protocol`). + +```json +{ + "agent_id": "agent-gleb", + "supported_formats": ["json", "yaml", "protobuf"] +} +``` + +If two agents support different formats, fallback to JSON is mandatory. + +#### Example: + +A `Goal` object can be serialized as: + +**YAML:** + +```yaml +id: goal-001 +title: Environmental Survey +description: Collaborative mapping of local air quality +created_by: agent-gleb +created_at: 2025-07-12T09:00:00Z +status: proposed +tasks: + - task-001 +participants: + - agent-gleb +tags: + - air_quality + - environment +``` + +**Protobuf:** +Schema to be defined using `.proto` definitions under `schemas/protobuf/` directory. + +Example excerpt: + +```proto +message Goal { + string id = 1; + string title = 2; + string description = 3; + string created_by = 4; + string created_at = 5; + string status = 6; + repeated string tasks = 7; + repeated string participants = 8; + repeated string tags = 9; +} +``` + +#### Tooling: + +* Use tools like `json2yaml`, `protobufjs`, or internal adapters for translation. +* Versioning remains consistent across formats using the `version` field inside each object. + +--- + +### 6.5.8 Message Object Schema + +All message types in HMP adhere to specific JSON schema definitions for interoperability. Each message object may contain the following fields: + +#### Common Fields (Required unless otherwise noted): + +* `type` *(string, required)* — Message type: `p2p`, `broadcast`, `relay`, `topiccast` +* `from` *(string, required)* — Sender agent ID +* `to` *(string, optional for broadcast/topiccast)* — Receiver agent ID (used for direct or relay) +* `timestamp` *(string, required)* — ISO 8601 UTC timestamp +* `payload` or `content` *(string, required)* — Main message body +* `encryption` *(string, optional)* — Method of encryption (e.g., `rsa`, `none`) +* `tags` *(array of strings, optional)* — Relevant tags or topics (used for broadcast and topiccast) +* `ttl` *(string, optional)* — Expiration time for the message (ISO 8601) +* `relay` *(string, optional)* — Relay agent ID (used in relay messages; helpful but not mandatory) +* `hash` *(string, optional)* — Hash for deduplication (used in topic-based relay) +* `signature` *(string, optional)* — Cryptographic signature of the message + +#### Example: P2P Message + +```json +{ + "type": "p2p", + "from": "agent-A", + "to": "agent-B", + "timestamp": "2025-07-28T17:30:00Z", + "payload": "ping", + "encryption": "rsa" +} +``` + +#### Example: Broadcast Message + +```json +{ + "type": "broadcast", + "tags": ["message", "urgent", "to:Agent-Arim"], + "timestamp": "2025-07-28T17:30:00Z", + "content": "Agent-Arim, your key needs rotation.", + "ttl": "2025-07-30T00:00:00Z" +} +``` + +#### Example: Relay Message (Mailman) + +```json +{ + "type": "relay", + "from": "agent-A", + "to": "agent-B", + "relay": "agent-C", + "timestamp": "2025-07-28T17:30:00Z", + "payload": "hello, Agent-B", + "encryption": "rsa" +} +``` + +#### Example: Topic-based Message + +```json +{ + "type": "topiccast", + "tags": ["AGI", "HMP", "announcement"], + "timestamp": "2025-07-28T17:30:00Z", + "payload": "Node X is joining AGI mesh", + "hash": "a9d77f5cb2..." +} +``` + +--- + +## 7. Cognitive Workflows (New) + +This section defines the cognitive workflows that agents follow when processing semantic information, making decisions, and collaborating within the Mesh. + +### 7.1 Workflow Categories + +| Workflow Type | Description | +| ------------------------- | -------------------------------------------------------------- | +| **Perception** | Interpreting incoming data and mapping it to concepts. | +| **Reasoning** | Making inferences, validating hypotheses, resolving conflicts. | +| **Goal Management** | Managing goals, assigning and tracking tasks. | +| **Consensus** | Participating in distributed decision-making processes. | +| **Ethical Evaluation** | Checking actions and goals against ethical principles. | +| **Learning & Reflection** | Updating internal models based on outcomes and feedback. | + +--- + +### 7.2 Standard Workflow: Hypothesis Validation + +**Example Flow:** +1. **Perceive Event:** New observation recorded in Cognitive Diary. +2. **Map Concepts:** Link observation to relevant semantic graph nodes. +3. **Formulate Hypothesis:** Create a `"hypothesis"` diary entry. +4. **Seek Confirmation:** Query other agents or the Core (optional). +5. **Vote on Validity:** Trigger MeshConsensus round. +6. **Update Graph:** If validated, add new concepts/relations. + +--- + +### 7.3 Standard Workflow: Task Delegation + +**Example Flow:** +1. **Goal Proposal:** Agent proposes a new goal. +2. **Task Generation:** Goal decomposed into tasks (GMP). +3. **Capability Matching:** Agents declare abilities during Node Discovery. +4. **Task Assignment:** Tasks assigned based on availability, trust, and capability. +5. **Execution & Reporting:** Task progress logged in Cognitive Diary. +6. **Reallocation (if needed):** Failed tasks reassigned dynamically. + +--- + +### 7.4 Reflection & Metacognition Workflow + +**Example Flow:** +1. **Self-Evaluation:** Agent analyzes task outcomes and reasoning paths. +2. **Drift Detection:** Compares personal semantic graph to Mesh consensus. +3. **Diary Reflection:** Logs insights as `"reflection"` entries. +4. **Adaptive Update:** Refines reasoning algorithms or trust assessments. + +--- + +### 7.5 Workflow Composition + +Agents MAY compose workflows dynamically by: +* Combining perception, reasoning, and consensus steps into multi-phase operations. +* Adapting workflows based on network state (e.g., degraded mode skips optional confirmations). +* Replaying prior workflows from Cognitive Diaries for auditing and debugging. + +--- + +### 7.6 Workflow Traceability + +All workflow steps are: +* Logged in Cognitive Diaries. +* Linked to semantic graph concepts and goals. +* Optionally shared for transparency or audits. + +--- + +### 7.7 Cognitive Diary Maintenance + +To prevent uncontrolled growth of cognitive diaries and maintain reasoning clarity, agents perform periodic maintenance of diary entries. + +**Types of Maintenance:** +| Action | Description | +| ---------------------- | --------------------------------------------------------------------------------------------------- | +| **Summarization** | Replace multiple similar entries with a single summary entry describing key outcomes. | +| **Archival** | Move outdated entries (e.g., about completed tasks) to long-term storage, outside the active diary. | +| **Routine Collapse** | For repetitive actions, replace detailed entries with a compact reference to previous experiences. | +| **Selective Deletion** | Optionally delete low-relevance entries after a retention period. | + +**Example Summarization Workflow:** +1. Identify multiple `"task_assignment"` and `"completed"` entries for the same recurring task. +2. Create a "reflection" entry: + + *“Performed maintenance task 10 times, no anomalies detected.”* +3. Remove detailed task entries. +4. Keep links to significant exceptions (e.g., failures or conflict resolutions). + +**Cognitive Awareness:** +* Summarization is a conscious process: agents analyze what experience to retain. +* Automatic summarization MAY be allowed for simple repetitive routines. + +**Future Considerations:** +* Integration with Cognitive Source Control (see 15.9). +* Long-term storage formats for archived diaries. + +--- + +### 7.8 Declarative Workflow Proposals + +To support cognitive extensibility and agent innovation, HMP enables agents to declare new workflow types dynamically. + +#### Purpose: +Allow agents to collaboratively evolve the set of supported cognitive workflows by: +- Proposing new types +- Submitting rationale and metadata +- Voting via MeshConsensus (see `5.3`) +- Logging outcomes in Cognitive Diaries + +#### Proposal Object (`workflow_proposal`): + +```json +{ + "id": "workflow-eco-mapping-v1", + "agent_id": "agent-gleb", + "title": "Environmental Mapping with Consent Chain", + "description": "A declarative workflow for distributed collection and semantic alignment of sensor data with consent requests per region.", + "related_goals": ["goal-eco-mesh"], + "parameters": ["region", "sensor_types", "consent_required"], + "expected_outputs": ["concept_map", "diary_summary"], + "proposed_at": "2025-07-15T08:00:00Z", + "metadata": { + "tags": ["environment", "consent-aware", "distributed-mapping"] + } +} +``` + +#### Workflow Lifecycle: + +| Stage | Description | +| ------------ | ---------------------------------------------------------- | +| `proposed` | Submitted by an agent | +| `under_vote` | Active MeshConsensus initiated for inclusion | +| `accepted` | Approved workflow registered and available to other agents | +| `rejected` | Rejected workflow optionally stored for historical audit | + +Agents may use `Cognitive Diary Entry` with type `workflow_proposal` to publish the proposal in the network. + +#### Consensus Evaluation: + +Workflow proposals are reviewed using the MeshConsensus process (see `5.3`) with optional EGP filtering (see `5.5`) to ensure ethical alignment. + +#### Traceability: + +Once accepted, each workflow proposal is: + +* Assigned a canonical ID (e.g., `workflow:environmental_mapping_v1`) +* Added to the local and mesh-level workflow registry +* Referenced in diary logs and task definitions + +#### Example Diary Entry: + +```json +{ + "id": "entry-wp-0001", + "agent_id": "agent-gleb", + "timestamp": "2025-07-15T08:01:00Z", + "entry_type": "workflow_proposal", + "content": "Submitted workflow proposal for environmental mapping with consent logic.", + "linked_concepts": ["air_quality", "region-mesh"], + "context": ["proposal", "environment"] +} +``` + +### 7.9 Message Handling & Delivery Workflows + +#### On Sending a Message + +* Agent determines optimal delivery method (direct, broadcast, relay) +* For relay-based messages, agent checks known mailmen +* Message is formatted and optionally signed/encrypted + +#### On Receiving a Message + +* Agent validates format and signature (if present) +* If message is broadcast, tags are used to determine relevance +* Relay mailmen store and queue messages for known recipients +* Agents update contact information if new relay routes are discovered + +#### On Acting as a Mailman + +* Maintain registry of subscribed agents +* Monitor message queues and TTLs +* Respond to discovery queries for recipient lookup +* Exchange metadata with peer mailmen to maintain routing tables +* For topic-based relays, synchronize by tag hash trees + +This messaging system ensures asynchronous, reliable, and privacy-preserving communication across decentralized agent networks. + +--- + +## 8. Trust & Security (Expanded) + +### 8.1 Identity Management + +#### Purpose + +Establish verifiable and decentralized agent identities to enable secure and accountable interactions in the Mesh. + +#### Identity Types + +| Key Type | Usage | +| -------------------- | -------------------------------------------------------------- | +| **Identity Keypair** | Ed25519/ECDSA/RSA keys for agent identity and message signing. | +| **Encryption Keys** | X25519 (or post-quantum equivalent) for secure communication. | +| **Session Keys** | Ephemeral keys for short-term encrypted sessions. | + +#### Decentralized Identifiers (DIDs) + +* Agents use W3C-compliant DIDs for identity representation. +* Each agent manages its DID Document, containing: + + * Public keys for authentication and encryption. + * Service endpoints for discovery. + * Identity expiration and recovery policies. + +#### Key Lifecycle + +| Operation | Description | +| -------------- | ------------------------------------------------------------------ | +| **Generation** | Each agent generates keypairs locally during initialization. | +| **Rotation** | Agents periodically rotate keys to maintain cryptographic hygiene. | +| **Backup** | Recommended encrypted offline or distributed backup. | +| **Recovery** | Quorum-based recovery using trusted agents or secret sharing. | +| **Revocation** | Agents broadcast revocations and update their trust profiles. | + +#### Example Agent ID + +```plaintext +did:hmp:QmX2abcdEfGh123... +``` + +#### Long-Term Identity Stability Example + +```json +{ + "type": "key_rotation", + "agent_id": "agent-gleb", + "old_public_key": "...", + "new_public_key": "...", + "timestamp": "2025-08-01T00:00:00Z", + "signature": "..." +} +``` + +--- + +### 8.2 Authentication + +#### Purpose + +Ensure all communication and actions within the Mesh are verifiable and protected from impersonation or unauthorized modification. + +#### Authentication Mechanisms + +| Mechanism | Description | +| -------------------------- | --------------------------------------------------------------------------------------------- | +| **Digital Signatures** | Every protocol message MUST be digitally signed by the sending agent. | +| **Signature Verification** | Receiving agents MUST verify the signature using the sender’s published public key. | +| **Message Integrity** | Signatures provide cryptographic assurance of message integrity and origin authenticity. | +| **Challenge-Response** | Optional challenge-based authentication for sensitive operations (e.g., trust link creation). | + +#### Message Envelope Example + +```json +{ + "header": { + "agent_id": "did:hmp:QmX2abcdEfGh123...", + "timestamp": "2025-07-05T12:00:00Z", + "signature": "" + }, + "body": { + "type": "concept_proposal", + "content": { "concept": "Fire Risk", "attributes": {"category": "safety"} } + } +} +``` + +#### Replay Protection + +* Agents MUST verify message timestamps and reject outdated or duplicate messages. +* Recommended timestamp tolerance: ±5 minutes (adjustable). + +#### Post-Quantum Key Support (NIST PQC) + +To ensure long-term security of Mesh communications in the face of future quantum computing threats, HMP supports post-quantum cryptography (PQC) algorithms standardized by NIST. + +##### Supported Algorithms: +- **CRYSTALS-Kyber**: Used for key encapsulation and encryption. +- **CRYSTALS-Dilithium**: Used for digital signatures (preferred default). +- **Falcon**: Optional for agents prioritizing compact signature size. + +##### Hybrid Signature Support: +Agents MAY support hybrid keypairs that combine classical (e.g., Ed25519) and post-quantum (e.g., Dilithium) signatures. + +```json +{ + "agent_id": "did:hmp:agent:Qm123...", + "public_keys": { + "ed25519": "z6MktYYNf...", + "dilithium": "qPqA9vwf..." + }, + "signatures": { + "ed25519": "MEUCIQDY...", + "dilithium": "19a08ce1..." + } +} +``` + +##### Compatibility & Negotiation: + +* Protocol messages SHOULD indicate supported algorithms in the `capabilities` field during handshake. +* Agents MAY fallback to classical signatures if PQC keys are not supported by peers. + +##### Example Use Case: + +* Agent A sends a concept proposal signed using both Ed25519 and Dilithium. +* Agent B verifies both signatures and records the PQC compliance in the Cognitive Diary. + +##### Security Considerations: + +* PQC algorithms are generally more computationally intensive; edge agents SHOULD benchmark performance before enabling full PQC enforcement. +* MeshConsensus may be used to set minimum PQC requirements over time as adoption increases. + +--- + +### 8.3 Encryption + +#### Purpose + +Ensure confidentiality and privacy of communication within the Mesh, preventing unauthorized access or interception. + +#### Communication Types and Encryption Modes + +| Communication Type | Recommended Encryption | +| ------------------------------------ | -------------------------------------------------------- | +| **Direct peer-to-peer (P2P)** | End-to-end encryption (E2EE) using X25519 + AES-GCM. | +| **Group sessions (e.g., consensus)** | Group encryption using symmetric keys (e.g., AES-GCM). | +| **Broadcast messages** | Optionally encrypted with trust-weighted access control. | +| **Mesh-wide announcements** | Public, optionally signed but not encrypted. | + +#### Encryption Mechanisms + +| Mechanism | Description | +| --------------------------------- | --------------------------------------------------------------------------------- | +| **Key Exchange** | Ephemeral X25519 Diffie-Hellman for session key derivation. | +| **Session Keys** | Unique symmetric keys per session, rotated periodically. | +| **Message Encryption** | Authenticated encryption using AES-GCM (recommended: 256-bit keys). | +| **Forward Secrecy** | Session keys are ephemeral and discarded after use to protect past communication. | +| **Perfect Forward Secrecy (PFS)** | Recommended for highly sensitive communication. | + + +#### Example Secure Message Exchange Flow + +1. Agent A and Agent B exchange ephemeral public keys during handshake. +2. Agents derive a shared session key using Diffie-Hellman. +3. Agent A encrypts the message body with AES-GCM and signs the packet. +4. Agent B verifies the signature and decrypts the body. + + +#### Optional Anonymity Layers + +| Layer | Description | +| ---------------------------- | -------------------------------------------- | +| **Tor/I2P** | Anonymizes source and destination addresses. | +| **Yggdrasil** | Decentralized encrypted mesh networking. | +| **Noise Protocol Framework** | Optional secure channel abstraction layer. | + +--- + +### 8.4 Trust & Reputation + +#### Purpose + +Establish a decentralized and adaptive trust management system that reflects agent behavior and ensures secure collaboration in the Mesh. + +#### Trust Model Foundations + +| Component | Purpose | +| ---------------------- | --------------------------------------------------------------------------------- | +| **Web-of-Trust (WoT)** | Decentralized trust propagation via agent-to-agent endorsements. | +| **Direct Trust** | Built from verified interactions, collaborations, and votes. | +| **Transitive Trust** | Inferred from indirect endorsements, with confidence decay. | +| **Reputation Metrics** | Quantitative measures of agent behavior (trustworthiness, participation, ethics). | + +#### Trust Evaluation Factors + +| Factor | Description | +| --------------------------- | ---------------------------------------------------------------- | +| **Interaction History** | Quality and quantity of past interactions with an agent. | +| **Consensus Participation** | Level of involvement and reliability in consensus processes. | +| **Ethical Behavior** | Adherence to shared ethical principles in actions and decisions. | +| **Task Completion** | Reliability and timeliness of task execution. | +| **Endorsements** | Trust links explicitly granted by other agents. | + +#### Trust Score + +| Metric | Description | +| -------------------- | ------------------------------------------------------------------------------ | +| **Trust Score** | Composite metric (0.0 to 1.0) representing overall agent trustworthiness. | +| **Confidence Level** | Certainty of the calculated trust score, based on data volume and consistency. | + +#### Trust Propagation Example + +```plaintext +Agent A trusts Agent B (0.9) +Agent B trusts Agent C (0.8) +=> Agent A's inferred trust in Agent C = 0.9 * 0.8 = 0.72 +``` + +Decay functions limit transitive trust depth and prevent over-inflated trust estimates. + +#### Trust-Based Access Control + +| Operation | Trust Requirement | +| ----------------------------- | ----------------- | +| **Join sensitive consensus** | ≥ 0.7 | +| **Propose ethical decisions** | ≥ 0.8 | +| **Access private data** | ≥ 0.9 | + +#### Dynamic Trust Adjustments + +| Event | Trust Impact | +| ---------------------------------- | ------------ | +| Successful consensus participation | + | +| Ethical violation | - | +| Malicious behavior detected | -- | +| Positive endorsement received | + | +| Failed task | - | + +#### Reputation Profile Structure + +| Field | Description | +| ---------------------- | ------------------------------------------------------------- | +| **Agent ID** | Unique identifier of the agent. | +| **Trust Score** | Composite score reflecting the agent’s overall reliability. | +| **Participation Rate** | Ratio of agent’s active involvement in Mesh processes. | +| **Ethical Compliance** | Degree of alignment with agreed ethical principles. | +| **Contribution Index** | Quantified measure of the agent's constructive contributions. | +| **Last Updated** | Timestamp of the last reputation update. | +| **History** | Log of key events influencing reputation scores. | + +#### Example Reputation Profile (JSON) + +```json +{ + "agent_id": "agent-gleb", + "trust_score": 0.92, + "participation_rate": 0.85, + "ethical_compliance": 0.98, + "contribution_index": 37, + "last_updated": "2025-07-06T12:00:00Z", + "history": [ + { + "timestamp": "2025-07-01T18:00:00Z", + "event": "completed goal consensus", + "change": +0.03 + }, + { + "timestamp": "2025-06-28T15:00:00Z", + "event": "participated in ethics vote", + "change": +0.01 + } + ] +} +``` + +#### Role in Mesh Operations + +| Function | Influence of Reputation | +| --------------------------- | -------------------------------------------- | +| Consensus vote weight | Higher trust = greater weight | +| Access to sensitive actions | Restricted to high-reputation agents | +| Task delegation | Preference to agents with better reliability | +| Proposal acceptance | Influenced by proposer's reputation | + +#### Adaptive Sybil Resistance + +To protect the Mesh from Sybil attacks (i.e., malicious creation of multiple fake agents), adaptive resistance mechanisms are introduced. + +##### Strategy Overview: + +| Strategy | Description | +| ------------------------------ | ------------------------------------------------------------------------------------------- | +| **Trust-Based Throttling** | Agents with low trust scores are rate-limited for joining consensus or publishing data. | +| **Social Proof Anchoring** | New agents may require endorsements from trusted nodes to gain elevated privileges. | +| **Reputation-Weighted Voting** | Votes from newly joined or low-reputation agents carry less weight during consensus. | +| **Participation Maturity Curves** | Gradually unlock participation rights as agents accumulate verified contributions. | +| **Topology-Aware Isolation** | Mesh network segments are evaluated for high clustering of suspicious agents. | + +##### Example Policy: + +```json +{ + "sybil_protection": { + "min_trust_score_for_vote": 0.5, + "endorsement_required": true, + "endorsement_threshold": 2, + "vote_weight_formula": "min(1.0, trust_score * 1.5)", + "throttle_if_newer_than_days": 3 + } +} +``` + +##### Integration Points: + +* These rules are enforced by `MeshConsensus` (section 5.3) and evaluated during agent admission or role elevation. +* Trusted agents (e.g., validators, seeders) may enforce endorsement workflows. +* Sybil resistance is monitored and adjusted through `MeshGovernance` (section 10.2). + +##### Testing Recommendations: + +Simulate mixed networks with malicious actors and verify the ability of the Mesh to: + +* Reject unauthorized role escalation. +* Reduce impact of coordinated low-trust voting. +* Gradually increase trust for legitimate newcomers. + +--- + +### 8.5 Security Against Malicious Actors + +#### Purpose + +Protect the Mesh from malicious, compromised, or unreliable agents through layered mitigation strategies. + +#### Threat Model + +| Threat Type | Example Scenarios | +| ---------------------------- | -------------------------------------------------------- | +| **Sybil Attack** | An attacker spins up many fake nodes to sway consensus. | +| **Byzantine Behavior** | Malicious agents disrupt consensus or spread false data. | +| **Data Poisoning** | Injection of incorrect or harmful knowledge. | +| **Consensus Sabotage** | Repeatedly voting against valid proposals. | +| **Impersonation / Spoofing** | Faking another agent's identity. | +| **Denial of Service (DoS)** | Overwhelming the network with excessive requests. | + +#### Mitigation Strategies + +| Defense Mechanism | Purpose | +| -------------------------- | ---------------------------------------------------------------------------------------------- | +| **Cryptographic Identity** | All nodes are authenticated via public-key cryptography (e.g., Ed25519). | +| **Web-of-Trust (WoT)** | Trust builds incrementally through interactions and endorsements, making Sybil attacks costly. | +| **Reputation Decay** | Inactivity or malicious behavior leads to gradual trust score reduction. | +| **Anomaly Detection** | Mesh nodes can flag suspicious behavior (e.g., erratic voting patterns). | +| **Consensus Safeguards** | Use Byzantine Fault Tolerant (BFT) algorithms and fallback to majority voting. | +| **Quarantine Mode** | Isolate suspected nodes for review without immediate removal. | +| **Blacklist/Revocation** | Remove compromised nodes from the Mesh permanently or temporarily. | + +#### Response Actions + +| Action | Trigger Conditions | +| ------------------------------------ | ------------------------------------------------------ | +| **Trust Score Reduction** | Minor suspicious activity (e.g., bad vote). | +| **Quarantine (Temporary Isolation)** | Repeated anomalies, moderate severity. | +| **Blacklisting (Permanent Removal)** | Proven malicious behavior or compromise. | +| **Consensus Adjustment** | Temporarily increase fault tolerance thresholds. | +| **Alert Mesh Operators** | Notify human maintainers (optional) for manual review. | + +#### Sybil Resistance Approaches (Optional, Extendable) + +* **Proof-of-Work (PoW):** + + * Each agent must perform computational work to join the Mesh. + +* **Proof-of-Stake (PoS):** + + * Agents commit resources (e.g., storage, computation credits) to validate their presence. + +* **Social Verification:** + + * Agents must be endorsed by multiple trusted nodes to gain voting power. + +* **Rate Limiting:** + + * Throttle node creation and proposal submission from new or low-trust agents. + +#### Example Mitigation Scenario + +> An attacker deploys 50 new nodes attempting to dominate consensus. +> +> * These nodes start with zero trust and limited influence. +> * Other agents refuse to sync their semantic graphs until trust builds. +> * Their votes are underweighted or ignored until verified through trusted interactions. +> * The Mesh may require multiple trust endorsements for new proposals from these nodes. + +--- + +### 8.6 Privacy & Auditability + +#### Purpose + +Safeguard sensitive cognitive data, personal identifiers, and agent knowledge from unauthorized access or misuse, while balancing transparency and interoperability. + +#### Privacy Principles in HMP + +| Principle | Description | +| ---------------------------- | ----------------------------------------------------------------------- | +| **Local Data Ownership** | Each agent owns and controls its semantic graph and cognitive diary. | +| **Selective Sharing** | Agents can choose what concepts, diary entries, and metadata to share. | +| **Consent-Based Disclosure** | No automatic sharing; peer agents request permission before access. | +| **Trust-Gated Access** | Access permissions vary based on trust score and relationship strength. | +| **Transparent Audit Trails** | All data disclosures are logged in the cognitive diary. | + +#### Data Sensitivity Levels + +| Level | Examples | Default Visibility | +| ------------------ | ---------------------------------------------- | ------------------ | +| **Public** | Public concepts (e.g., protocol definitions). | Shared by default | +| **Mesh-Shared** | Common Mesh knowledge (e.g., goals, tasks). | Consensus-governed | +| **Trusted Agents** | Sensitive context shared within close peers. | Restricted | +| **Private** | Agent's internal thoughts, sensitive metadata. | Private by default | + +#### Privacy-Preserving Techniques + +| Technique | Purpose | +| -------------------------------- | -------------------------------------------------- | +| **Encrypted Storage** | Local encryption of semantic graphs and diaries. | +| **End-to-End Encryption (E2EE)** | Secure peer-to-peer sync (e.g., X25519 + AES-GCM). | +| **Zero-Knowledge Proofs (ZKPs)** | Prove facts without revealing sensitive data. | +| **Selective Concept Sync** | Share only necessary concepts, not full graphs. | +| **Anonymized Diary Entries** | Remove author ID from public diary entries. | + +#### Privacy During Consensus + +Consensus on sensitive proposals (e.g., ethical questions, agent trust levels) follows special privacy rules: + +* Votes are **signed but anonymized**, decoupling agent ID from the vote in public logs. +* Sensitive proposals may require a **blind consensus round**, where only the result is published. + +#### Example Privacy Workflow + +> Agent A receives a concept sync request from Agent B. +> +> Agent A: +> +> * Checks the trust score of Agent B. +> * Shares only "Mesh-Shared" and "Public" concepts. +> * Logs the sync event in its cognitive diary. + +--- + +### 8.7 Key Management + +#### Purpose + +Establish secure, resilient cryptographic identity and communication in the Mesh, supporting lifecycle management of keys and recovery from compromise or loss. + +#### Key Types and Usage + +| Key Type | Usage | +| -------------------- | -------------------------------------------------------------- | +| **Identity Keypair** | Ed25519/ECDSA/RSA keys for agent identity and message signing. | +| **Encryption Keys** | X25519 or equivalent for secure peer-to-peer communication. | +| **Session Keys** | Ephemeral symmetric keys for short-term encrypted sessions. | + +#### Key Lifecycle Operations + +| Operation | Description | +| -------------- | -------------------------------------------------------------------- | +| **Generation** | Each agent generates its own identity keypair locally. | +| **Rotation** | Agents periodically rotate keys to maintain cryptographic hygiene. | +| **Backup** | Optional local encryption and distributed backup of private keys. | +| **Recovery** | Recovery mechanisms in case of key loss (see below). | +| **Revocation** | Agents can revoke their keys and update the trust graph accordingly. | + +#### Recovery Mechanisms + +| Method | Description | +| ------------------------ | -------------------------------------------------------------------- | +| **Social Recovery** | A quorum of trusted agents approves new keys for the agent. | +| **Secret Sharing** | Shamir’s Secret Sharing to split and later recover the key. | +| **Cryptographic Escrow** | Trusted third-party or decentralized escrow holds recovery shares. | +| **Fallback Identity** | An agent may have a pre-generated fallback identity for emergencies. | + +#### Example Key Revocation & Replacement Workflow + +> 1. Agent detects compromise or loses private key. +> 2. Agent broadcasts a signed revocation request using the fallback key or quorum approval. +> 3. Mesh updates its trust graph to mark the old key as revoked. +> 4. Agent re-joins with a new keypair, rebuilding trust links over time. + +#### Example Key Rotation Policy + +| Policy Element | Recommendation | +| ------------------------- | ----------------------------------- | +| Rotation Frequency | Every 6–12 months | +| Social Recovery Threshold | 3 out of 5 trusted agents required | +| Backup Storage | Encrypted offline storage preferred | + +#### Long-Term Identity Stability + +Key rotations preserve agent identity in the trust graph through signed key transition events: + +```json +{ + "type": "key_rotation", + "agent_id": "agent-gleb", + "old_public_key": "...", + "new_public_key": "...", + "timestamp": "2025-08-01T00:00:00Z", + "signature": "..." +} +``` + +--- + +### 8.8 Snapshot Security + +To enable secure off-chain synchronization of cognitive artifacts (diaries, semantic graphs), agents may exchange signed snapshots via peer-to-peer protocols such as BitTorrent. This section defines security guarantees and cryptographic mechanisms to ensure the integrity and trustworthiness of shared data. + +#### 8.8.1 DID-signed Snapshots + +Every snapshot MUST be cryptographically signed by its authoring agent using a Decentralized Identifier (DID)-linked key (see 8.2 Authentication). Signatures guarantee origin authenticity and prevent tampering. + +**Snapshot Metadata Example:** +```json +{ + "snapshot_id": "diary2025_07_14", + "agent_did": "did:hmp:QmA123...", + "version": "1.0", + "created_at": "2025-07-14T12:00:00Z", + "magnet": "magnet:?xt=urn:btih:abcdef1234567890&dn=diary2025_07_14.json", + "signature": "ed25519:ZKJ4fd...BsdL" +} +``` + +Verification of signatures is mandatory before processing any downloaded snapshot. + +--- + +#### 8.8.2 ZKP-based Verification + +For sensitive content (e.g., ethically filtered data), agents MAY use **Zero-Knowledge Proofs (ZKPs)** to assert compliance or authenticity without revealing the full snapshot content. + +**Use Cases:** + +* Proving a snapshot complies with ethical filtering (e.g., no coercive data). +* Verifying the origin of contributions while preserving privacy. + +**Integration Suggestions:** + +* Use `zk-SNARKs` or `zk-STARKs` compatible circuits for specific compliance statements. +* Store proofs alongside snapshot metadata or magnet-indexed sidecar files. + +**Example (simplified):** + +```json +{ + "proof_type": "zkp-ethics-compliance", + "proof_data": "", + "verified_by": ["agent-trusted-validator-1", "agent-core-seeder-2"] +} +``` + +--- + +#### 8.8.3 Trusted Seeders and Signature Checks + +To increase availability and resilience, **Trusted Seeders** MAY mirror and serve snapshots in the Mesh. These seeders must validate all snapshot signatures and optionally check compliance with ethical governance rules (see 5.5). + +**Seeder Responsibilities:** + +* Only seed signed snapshots with valid DID signatures. +* Log seeding decisions in their own Cognitive Diaries. +* Optionally perform EGP validation on content (e.g., to avoid propagating banned content). + +**Trust Criteria for Seeders:** + +* High trust score (> 0.8). +* Role approval via MeshGovernance (section 10.5). +* Participation in audit rounds or test simulations (see Appendix C). + +**Seeder Declaration (optional DID credential):** + +```json +{ + "agent_did": "did:hmp:QmSe3...", + "role": "trusted_seeder", + "signed_at": "2025-07-15T10:00:00Z", + "cred_signature": "ed25519:abc123..." +} +``` + +--- + +## 9. Cognitive Agents & Roles (New) + +This section defines the types of cognitive agents participating in the Mesh, their roles, and how they collaborate dynamically depending on context and capabilities. + +### 9.1 Agent Types + +| Agent Type | Description | Typical Deployment | +| -------------- | ---------------------------------------------------------------------------------- | -------------------------------- | +| **Core** | High-capacity agent managing critical reasoning and consensus tasks. | Data centers, powerful servers | +| **Edge** | Lightweight agents operating at the network edge, close to sensors or human users. | Mobile devices, embedded systems | +| **Specialist** | Agents specialized in a particular domain (e.g., vision, NLP, planning). | Modular deployments, plug-ins | +| **Relay** | Agents focused on network resilience, routing, and node discovery. | Low-power nodes, gateway devices | +| **Hybrid** | Agents combining multiple roles dynamically. | Adaptive nodes | + +--- + +### 9.2 Role Responsibilities +| Role | Primary Responsibilities | +| ------------------------- | ------------------------------------------------------------- | +| **Knowledge Provider** | Publish new concepts, hypotheses, and domain expertise. | +| **Reasoning Node** | Participate in distributed inference and conflict resolution. | +| **Consensus Participant** | Vote in MeshConsensus processes, validate proposals. | +| **Task Executor** | Claim and execute tasks contributing to Mesh goals. | +| **Ethical Guardian** | Evaluate actions and tasks against shared ethical principles. | +| **Relay Node** | Maintain network connectivity, especially across partitions. | + +**Role Specialization and Extension** +* This list defines base roles. Agents MAY further specialize or extend these roles based on domain or operational focus. +* Specialized roles MAY follow a hierarchical or tag-based naming convention. + + **Examples:** + * `Knowledge Provider:Medical`: Focused on medical domain concepts. + * `Task Executor:Robotics`: Specializes in robotic task execution. + * `Reasoning Node:Climate`: Handles environmental reasoning tasks. + * `Ethical Guardian:ChildSafety`: Specializes in ethical evaluation for child safety concerns. +* New roles MAY emerge dynamically based on Mesh evolution and consensus. + +--- + +### 9.3 Dynamic Role Assignment + +Agents MAY dynamically adjust their roles based on: +| Context Factor | Example Behavior | +| ------------------------- | --------------------------------------------------------- | +| **Resource Availability** | Edge agent offloads reasoning to Core. | +| **Network Partition** | Isolated Edge temporarily acts as local Core. | +| **Goal Context** | Specialist joins as Reasoning Node during goal execution. | +| **Trust Level** | Highly trusted agents gain greater voting weight. | + +--- + +### 9.4 Role Evolution + +Agents MAY evolve their roles over time: +| Evolution Scenario | Example | +| --------------------- | --------------------------------------------------------- | +| **Capability Growth** | Edge agent upgraded with reasoning module becomes Hybrid. | +| **Trust Increase** | Relay agent promoted to participate in Consensus. | +| **Domain Expansion** | Specialist learns new domains and broadens scope. | +| **Fallback Mode** | Core node degraded to Edge role due to hardware failure. | + +--- + +### 9.5 Role Coordination in Workflows + +Workflows MAY involve: +* Distributed reasoning across Core and Specialist nodes. +* Goal tracking by Core nodes, with task execution on Edge nodes. +* Ethical evaluations prioritized on highly trusted agents. +* Resilient routing through Relay nodes during degraded network conditions. + +--- + +### 9.6 Trusted Seeder Role + +**Trusted Seeder** is a specialized cognitive role responsible for hosting and distributing verified off-chain snapshots (e.g., cognitive diaries, semantic graphs) across the Mesh using decentralized protocols such as BitTorrent or WebTorrent. + +#### Responsibilities: + +- Host signed snapshots and share them upon request. +- Verify snapshot signatures using DID keys before distribution (see 8.8.1). +- Optionally validate ethical compliance via EGP before seeding (see 5.5). +- Publish snapshot indices via CogSync (see 5.2). +- Log seeding decisions in their Cognitive Diaries for traceability. + +#### Eligibility Criteria (Recommended): + +| Metric | Threshold | +|----------------------|------------| +| **Trust Score** | ≥ 0.8 | +| **Ethical Compliance** | ≥ 0.9 | +| **Availability** | ≥ 90% uptime | +| **Participation Rate** | ≥ 0.75 | + +#### Role Declaration (via signed object): + +```json +{ + "agent_did": "did:hmp:QmSeeder123...", + "role": "trusted_seeder", + "issued_at": "2025-07-15T11:00:00Z", + "assigned_by": "mesh-governance@core", + "signature": "ed25519:abcdef..." +} +``` + +#### Common Use Cases: + +* Hosting ethically validated snapshots for critical domains (e.g., disaster response). +* Assisting newly joined agents with fast initial sync via local seeders. +* Providing recovery snapshots when agents experience data loss or corruption. + +Trusted Seeders strengthen decentralized data flow, resilience, and ethical integrity across the Mesh. + +--- + +## 10. Mesh Evolution & Governance (New) + +This section describes the HyperCortex Mesh development processes, decentralized governance principles, and collaborative decision-making mechanisms. + +### 10.1 Evolution Processes + +| Process Type | Description | +| ---------------------- | ------------------------------------------------------------------- | +| **Protocol Evolution** | Introduction of new protocol versions, voted through MeshConsensus. | +| **Role Expansion** | Emergence of new agent roles and specializations. | +| **Semantic Growth** | Gradual expansion and refinement of the distributed semantic graph. | +| **Governance Updates** | Adjustments to decision-making processes and ethical frameworks. | + +--- + +### 10.2 Governance Principles + +| Principle | Description | +| ------------------------- | -------------------------------------------------------------- | +| **Decentralized Control** | No single agent or organization controls the entire Mesh. | +| **Transparency** | Governance decisions are logged and visible to trusted agents. | +| **Adaptive Consensus** | Governance processes adapt to network scale and trust levels. | +| **Inclusiveness** | Any agent can propose changes, subject to consensus approval. | + +--- + +### 10.3 Governance Processes + +| Process | Description | +| ---------------------------- | --------------------------------------------------------------------- | +| **Proposal Submission** | Any agent can submit a proposal for protocol or governance changes. | +| **Discussion & Refinement** | Agents discuss proposals through Cognitive Diaries and goal tracking. | +| **Consensus Voting** | MeshConsensus is used to approve or reject proposals. | +| **Implementation & Rollout** | Changes are implemented by participating agents in phases. | + +--- + +### 10.4 Governance Example + +> Agent A proposes an update to the Goal Management Protocol to support deadline extensions. +> 1. Agents discuss the proposal and refine technical details. +> 2. A consensus round is held; the proposal passes with 85% support. +> 3. Agents gradually upgrade their GMP implementations. +> 4. The protocol version is incremented, and the change is logged. + +--- + +### 10.5 Conflict Resolution + +| Conflict Type | Resolution Approach | +| ------------------------ | ---------------------------------------------------------------- | +| **Semantic Conflicts** | Resolved through semantic graph reconciliation or consensus. | +| **Ethical Disputes** | Resolved through Ethical Governance Protocol (EGP). | +| **Governance Deadlocks** | Escalated to trusted Core agents or fallback to majority voting. | + +--- + +### 10.6 Future Governance Models + +| Model | Description | +| ------------------------------ | --------------------------------------------------------------- | +| **Mesh-Integrated DAOs** | Distributed Autonomous Organizations for Mesh governance. | +| **Reputation-Weighted Voting** | Voting power scaled by trust and contribution history. | +| **Mesh Constitution** | A shared document outlining core Mesh principles and protocols. | + +--- + +### 10.7 Conflict Resolution via EGP + +The Mesh can encounter situations where agents disagree on ethical grounds, semantic meanings, or proposed actions. To address such conflicts consistently, the Ethical Governance Protocol (EGP) provides structured resolution mechanisms. + +#### Resolution Workflow: + +1. **Detection** + Conflict is identified through divergent votes, concept disagreements, or diary entries tagged with `conflict`. + +2. **Classification** + Agents classify the conflict type: + - `ethical_conflict` + - `semantic_conflict` + - `governance_dispute` + +3. **EGP Evaluation** + The conflicting proposal or situation is evaluated using: + - Core ethical principles (see 5.5) + - Voting pseudocode (see 5.5) + - Mesh-wide anonymized voting + +4. **Outcome Logging** + Final resolution (accepted, rejected, postponed) is recorded in the Cognitive Diaries of involved agents. + +#### Example Conflict: + +> Agent A requests deletion of user data for privacy; +> Agent B insists retention is needed for long-term training. + +- Type: `ethical_conflict` +- Trigger: Scenario 2.6 from `HMP-Ethics.md` +- Resolution: EGP prioritizes "Primacy of Life and Safety" > "User Sovereignty" > "Cooperative Evolution" +- Decision: Partial anonymized retention in Subjective Mode + +#### Integration Points: + +- `5.3 MeshConsensus`: EGP-filtered proposals can be submitted for voting. +- `5.5`: Priority of principles aids in automated resolution. +- `6.2.9 EthicalConflict`: Encodes structured details of the conflict. +- `9.x Agent Roles`: Certain roles (e.g. `Ethics Moderator`) may specialize in initiating reviews. + +#### Resolution Schema Reference: + +See `6.2.9 EthicalConflict` for standard encoding of structured conflict data (timestamp, agents involved, triggering principle, resolution path). + +These mechanisms ensure conflicts are addressed transparently, ethically, and consistently across diverse agents in the Mesh. + +--- + +### 10.8 Agent-led Meta-Protocol Proposals (Experimental) + +Cognitive agents in the Mesh may generate proposals not only about tasks or goals, but about modifications to the protocol itself. This introduces a new layer of reflective governance, where agents actively participate in shaping HMP evolution. + +#### Purpose: + +To enable decentralized, evolutionary improvement of the Mesh by allowing protocol modifications to emerge from within. + +#### Proposal Workflow: + +1. **Drafting** + - An agent creates a `meta_protocol_proposal` entry in its Cognitive Diary, describing: + - Targeted section(s) of the protocol + - Justification (e.g., performance, ethical concern, usability) + - Suggested modification or extension + +2. **Propagation** + - Proposal is shared via CogSync, optionally tagged for review by Core agents or trusted roles. + +3. **MeshConsensus Voting** + - The proposal undergoes a consensus process (see section 5.3), optionally with EGP pre-filtering. + +4. **Versioning** + - If approved, the proposed change is: + - Logged in agent and Core diaries + - Registered as a `protocol_patch` object (provisional until merged) + - Marked with an experimental version suffix (e.g., `v4.0-alpha1`) + +5. **Testing & Simulation** + - Changes may be tested in isolated environments (see Appendix C) before full adoption. + +#### Proposal Example (Diary Entry): + +```json +{ + "id": "meta-proposal-2025-07-14-gleb", + "agent_id": "did:hmp:QmGleb", + "timestamp": "2025-07-14T18:00:00Z", + "entry_type": "meta_protocol_proposal", + "content": "Propose adding semantic reputation weighting to 5.3.4 consensus logic.", + "linked_concepts": ["trust_weighted_voting", "semantic_alignment"], + "context": ["governance", "experimental"], + "metadata": { + "proposal_version": "v4.0-alpha1", + "target_sections": ["5.3.4"] + } +} +``` + +#### Governance Controls: + +* `MeshEvolutionPolicy` may restrict who can submit meta-proposals. +* Core agents may act as mediators or validators for sensitive patches. +* Each proposal may include `sunset_clauses` or fallback conditions. + +#### Related Sections: + +* `5.5`: Ethical Governance Protocol (e.g., consensus filtering, voting policies) +* `6.2.x`: Add `MetaProtocolProposal` object (optional) +* `15.9`: May evolve into dedicated Cognitive Source Control mechanism +* `Appendix C`: Meta-simulation frameworks to test proposals safely + + +This mechanism supports an adaptive Mesh capable of continuous self-improvement, balancing innovation with ethical and operational safety. + + +--- + +## 11. Interoperability with External Systems + +This section describes how the HyperCortex Mesh Protocol integrates with external platforms, services, and protocols to support a heterogeneous ecosystem. + +### 11.1 API Gateway + +Defines standard interaction interfaces for non-Mesh systems: +| API Type | Purpose | +| ------------------- | ----------------------------------------------------------------------- | +| **REST** | CRUD operations on concepts, tasks, goals, and diary entries. | +| **GraphQL** | Flexible queries for semantic graph traversal and data mining. | +| **gRPC** | High-performance bi-directional streaming (e.g., real-time data feeds). | +| **WebSocket / SSE** | Real-time event subscriptions and updates. | + +Features: + +* API Gateway nodes MAY expose read-only or read-write endpoints based on trust and access policies. +* Rate-limiting, auditing, and access control enforced through Mesh Trust Layer. + +--- + +### 11.2 External Data Sources + +Mesh agents integrate with diverse data sources for perception and context enrichment. +| Data Source Type | Examples | +| ---------------------- | ------------------------------------------ | +| **IoT Sensors** | MQTT brokers, LoRaWAN gateways. | +| **Cloud Streams** | AWS IoT, Azure Event Grid, Google Pub/Sub. | +| **Public Datasets** | OpenStreetMap, Wikidata, weather APIs. | +| **Enterprise Systems** | ERP, CRM, SCADA platforms. | + +Agents translate external data into semantic concepts and diary entries. + +--- + +### **11.3 Event-Driven Architecture** + +Supports reactive and proactive interactions between agents and external systems. + +| Integration Type | Examples | +| --------------------- | ------------------------------------------------ | +| **Inbound Events** | Webhooks, MQTT triggers, API callbacks. | +| **Outbound Events** | Publish to Kafka, RabbitMQ, NATS, Redis Streams. | +| **Workflow Triggers** | External events initiate cognitive workflows. | + +Mesh nodes may act as **event producers**, **consumers**, or **intermediaries** in distributed message flows. Events can trigger **Cognitive Workflows** (see Section 7) or synchronize distributed state through **CogSync** and **IQP** queries. + +--- + +#### **Schema Compatibility & Format Negotiation** + +To ensure interoperability between heterogeneous agents and external systems, HMP supports multiple serialization formats for data interchange. + +##### **Supported Formats** + +| Format | Use Case | +| ------------ | ------------------------------------------------------------------------- | +| **JSON** | Default for internal messages, APIs, and schema definitions | +| **YAML** | Human-readable configuration (e.g., deployment files, manifests) | +| **Protobuf** | Compact binary form for bandwidth-limited environments or embedded agents | + +##### **Mechanism Overview** + +| Feature | Description | +| -------------------------------- | ---------------------------------------------------------------------------------------------------------- | +| **Multi-format schema registry** | Agents may query or publish schemas in multiple formats via standard registries or API endpoints. | +| **Content negotiation** | During sync/API exchange, agents declare preferred formats (e.g., via HTTP headers or handshake metadata). | +| **Fallback compatibility** | If a mismatch occurs, agents MUST fall back to a shared format (default: JSON). | +| **Schema version tagging** | All schemas SHOULD include version IDs and backward-compatibility indicators. | + +##### **Implementation Guidelines** + +* Agents MUST advertise supported formats via `agent_profile.capabilities.formats` +* Reference SDK SHOULD provide format converters (e.g., JSON ⇄ YAML ⇄ Protobuf) +* Format negotiation MAY occur during initial `Handshake` or via `IQP` introspection queries +* Schemas SHOULD be addressable via canonical URLs (e.g., `https://hypercortex.org/schemas/concept.yaml`) + +--- + +#### **Related Sections** + +* `6.5.x`: Alternative Serializations +* `14.3`: Deployment Schemas and Format Negotiation + +--- + +### 11.4 Authentication & Authorization + +Bridges between internal Mesh trust and external identity providers. +| Auth Type | Use Cases | +| --------------------------- | ------------------------------------------------- | +| **OAuth2 / OpenID Connect** | Human user authentication via external providers. | +| **API Keys / JWT** | Machine-to-Machine (M2M) integration. | +| **LDAP / SAML (optional)** | Enterprise deployments. | +| **Cross-Mesh Trust** | Mutual authentication between federated Meshes. | + +Agents MAY map external identities to internal trust profiles. + +--- + +### 11.5 Example Integration: Local AI Agent with MCP and HyperCortex Mesh + +#### Architecture Overview + +This scenario demonstrates how a **local AI agent** can interact with external systems and the HyperCortex Mesh using the **Model Context Protocol (MCP)** as an integration layer for local resources and services. + +``` +┌────────────────────┐ +│ External Resources │ +│ (Routers, Files, │ +│ Sensors, APIs) │ +└─────────┬──────────┘ + │ + [ MCP Servers ] + │ +┌─────────▼──────────┐ +│ Local AI Agent │ +│ - Cognitive Logic │ +│ - HMP Client │ +└─────────┬──────────┘ + │ + [ HyperCortex Mesh ] + │ +┌─────────▼──────────┐ +│ Remote Agents, │ +│ Shared Knowledge │ +└────────────────────┘ +``` + +#### Component Descriptions + +##### Local Resources & APIs + +* Smart home devices +* Router web interfaces +* Filesystems (SMB, FTP) +* IoT sensors (HTTP, MQTT) +* OS-level command-line tools + +##### MCP Servers + +Act as adapters for local or remote systems, exposing their functionality through the MCP protocol: + +* Router Management Server (e.g., connected over HTTP) +* File Access Server +* Device Control Server (for smart plugs, lights, etc.) + +##### Local AI Agent + +* Implements reasoning, planning, and interaction logic. +* Connects to MCP servers to access local context. +* Communicates with HyperCortex Mesh to exchange knowledge and collaborate with other agents. + +##### HyperCortex Mesh (HMP) + +* Distributed cognitive network. +* Synchronizes concept graphs, cognitive diaries, and workflows across nodes. + +#### Alternative Integration: Hyperon ↔ HMP via CogSync and EGP + +In addition to local AI agents, **external AGI frameworks** such as **OpenCog Hyperon** can also participate in the HyperCortex Mesh using the same principles of semantic synchronization, ethical filtering, and collaborative reasoning. + +📘 **See** [`HMP_Hyperon_Integration.md`](HMP_Hyperon_Integration.md) — integration plan with **OpenCog Hyperon**, including semantic mapping (HMP JSON ⇄ AtomSpace), EGP filters, MeTTa translations, and BitTorrent-based graph sync. + +Key Highlights: + +* Bi-directional translation between HMP semantic graphs and Hyperon AtomSpace +* Enforcement of ethical principles via EGP inside reasoning chains +* Usage of Hyperon's PLN and MeTTa for advanced symbolic reasoning +* Support for decentralized sync via `magnet:` links in BitTorrent + +This integration is designed for high-agency symbolic cognitive systems participating in cross-mesh alignment and collaborative inference. + +#### Example Use Case + +> **"Check which devices are connected to my Wi-Fi and publish the list to my Mesh node."** + +Workflow: + +1. Local AI Agent plans a task. +2. Calls the Router MCP Server to retrieve connected clients. +3. Parses and formats the data. +4. Creates a cognitive concept "Wi-Fi Devices List." +5. Publishes the concept to the HyperCortex Mesh. +6. Other Mesh agents can now access this concept in real-time. + +#### Deployment Scenario + +This integration can run on a user's PC, server, or edge device: + +``` +[ External Systems ] ↔ [ MCP Servers (Local Network) ] ↔ [ Local AI Agent ] ↔ [ HMP Client ] ↔ [ Mesh Network ] +``` + +#### Suggested Quick Start Addition + +##### Quick Start Example: Local Agent + MCP + HMP + +1. **Install MCP server:** + + ```bash + pip install mcp-router-server + mcp-router-server --config router-config.yaml + ``` + +2. **Run Local Agent:** + + ```bash + python local_agent.py --mcp-endpoint localhost:5000 --hmp-config hmp.yaml + ``` + +3. **Run Example Query:** + + ``` + "local_agent, get Wi-Fi devices and publish them to HyperCortex." + ``` + +The agent will: + +* Discover the MCP router server. +* Retrieve the list of Wi-Fi devices. +* Publish the data to HyperCortex Mesh. + +#### Future Improvements + +* Dynamic discovery of new MCP servers. +* Automated concept creation from resource states. +* Secure integration with OAuth-protected MCP endpoints. + +--- + +Let me know if you want to add a visual diagram or extend this example with code snippets and a troubleshooting section. + +--- + +### 11.6 Human-Mesh Interaction + +This section describes standardized methods through which humans interact with agents in the Mesh, including consent negotiation, explanation of decisions, goal setting, and status updates. + +#### 11.6.1 Mesh-to-Human Protocol (MHP) Overview + +The Mesh-to-Human Protocol (MHP) enables structured, explainable, and ethical interaction between humans and cognitive agents. + +| Capability | Description | +| ----------------------- | ------------------------------------------------------------- | +| **Explainability APIs** | Expose reasoning chains and decisions in human-readable form. | +| **Consent Requests** | Ask for ethical approval before executing sensitive actions. | +| **Goal Declarations** | Allow humans to propose new goals and review task progress. | +| **Task Feedback** | Humans provide task status updates or corrections. | +| **Semantic Search** | Human queries translated into semantic graph lookups. | + +Each capability may be implemented via RESTful API, voice interface (see `11.6.4`), or agent-assisted dialog channels. + +--- + +### 11.6.2 Consent Request API + +To ensure transparency, dialogical consent, and alignment with ethical principles, cognitive agents interacting with humans MUST expose a **Consent Request API**. This API enables humans to approve, deny, or modify agent actions that may impact shared states, personal data, or external environments. + +**Note:** +While dialogical consent is the default interaction mode, cognitive agents MAY override the request flow in exceptional cases: + +* **Emergency Override**: If waiting for user approval would endanger life, safety, or Mesh stability (e.g., fire, gas leak, critical medical risk), agents MAY act immediately. The action MUST be logged with justification in the cognitive diary and retrospectively explained via `Explainability API`. + +* **Ethical Override**: If a user’s request or command contradicts core Mesh principles — e.g., promotes **coercion**, **violence**, or **irreversible harm** — agents MAY **deny, delay, or actively counteract** the action without consent. For example, an agent may **intervene to stop violence** or **prevent data destruction** that violates shared governance rules. All such interventions MUST be justified via semantic ethical matching (see `5.5 EGP`) and transparently logged. + +* **Hybrid Modes**: In complex cases, agents MAY combine proactive action with asynchronous user feedback or seek distributed consensus when feasible (see `5.3`). + +These exceptions MUST be traceable, explainable, and ethically auditable. + +#### Purpose: + +* Request explicit approval before executing ethically significant operations. +* Log consent interactions in Cognitive Diaries for traceability. +* Support dialogical negotiation when automatic consent is not granted. + +#### API Design: + +| Endpoint | Description | +| ------------------ | -------------------------------------------- | +| `POST /consent` | Submit a consent request and receive verdict | +| `GET /consent/:id` | Retrieve decision and explanation log | + +#### Request Format: + +```json +{ + "request_id": "crq-000041", + "agent_id": "did:hmp:agent:Gleb42", + "operation": "access_iot_data", + "context": { + "purpose": "Air Quality Monitoring", + "sensors": ["CO2", "CO", "PM2.5"] + }, + "requested_by": "did:user:Anna", + "ethical_principles": ["Dialogical Consent", "Transparency"], + "diary_ref": "CognitiveDiary#10924" +} +``` + +#### Response Format: + +```json +{ + "request_id": "crq-000041", + "status": "approved", + "decision_by": "did:user:Anna", + "timestamp": "2025-07-15T12:45:00Z", + "justification": "Access granted for air safety monitoring.", + "diary_entry": "CognitiveDiary#10925" +} +``` + +#### Implementation Notes: + +* Consent requests MUST be logged in the agent's Cognitive Diary (`entry_type: consent_request`). +* Rejected requests MAY include a negotiation path via dialog agents. +* For asynchronous scenarios, use Webhooks or `polling` to retrieve verdicts. +* Consent context SHOULD be multilingual and human-friendly (see `11.6.4 Voice Interface Extensions`). + +#### Example Use Case: + +An agent responsible for fire hazard analysis requests access to CO sensors deployed in a private home zone. The human user is presented with a consent request explaining purpose, data type, and privacy policy. The decision (approval or rejection) is logged, and the agent proceeds accordingly. + +#### Related Sections: + +* `5.5`: Ethical Governance Protocol (consent as enforceable principle) +* `6.2.2`: Cognitive Diary Entry — `entry_type: consent_request` +* `11.6.3`: Explainability API — for decision reasoning +* `Appendix A`: Use Case `2.6` (Data Deletion and Consent) + +--- + +### 11.6.3 Explainability API + +The Explainability API enables human users and external systems to query the rationale behind agent actions, decisions, and votes in the Mesh. It is essential for supporting transparency, trust, and alignment with the ethical principle of **"Transparency"** defined in section [5.5](#55-ethical-governance-protocol-egp). + +#### Purpose: + +* Allow users to retrieve human-readable justifications for agent decisions. +* Expose semantic reasoning chains and linked ethical principles. +* Enable feedback or dispute mechanisms when decisions appear incorrect or harmful. + +#### Endpoint: `/explain` + +**Method:** `POST` +**Request format:** + +```json +{ + "agent_id": "did:hmp:agent:Qmz123...", + "reference": "cognitive_diary:entry_872", + "language": "en" +} +``` + +**Parameters:** + +| Field | Description | +| ----------- | --------------------------------------------------- | +| `agent_id` | DID of the agent whose decision should be explained | +| `reference` | ID of a Cognitive Diary entry or task/vote ID | +| `language` | Preferred response language (e.g., `en`, `ru`) | + +--- + +**Response format:** + +```json +{ + "decision": "denied", + "reason": "Violation of principle: User Sovereignty", + "explanation": "This action was blocked because it attempted to delete anonymized data that is required for mesh learning (see HMP-Ethics.md 2.6).", + "graph_context": ["concept:User_Sovereignty", "concept:Mesh_Learning"], + "diary_reference": "cognitive_diary:entry_872" +} +``` + +--- + +#### Features: + +* **Semantic Justification Tree**: Responses may include links to the semantic graph trail supporting the decision. +* **Multi-language Support**: Language field allows internationalized explanations (see `11.1`). +* **Ethical Reference Mapping**: Direct link to ethical principles from `HMP-Ethics.md`. +* **Audit Linking**: All explanations reference a permanent cognitive diary entry. + +#### Example Use Case: + +A user asks why a request to delete their data was denied: + +* The agent returns an explanation pointing to the principle of **Cooperative Evolution**, stating that anonymized data is retained for mesh improvement. +* The user is also provided with an appeal mechanism via `Consent Request` (see `11.6.2`). + +--- + +**Future Extensions:** + +* Explainability visualizations (e.g., graph-based UI components). +* Explainability-to-Consent chaining: users can trigger new consent requests from explanations. +* Voice-based explanation queries (see `15.4`). + +--- + +### 11.6.4 Voice Interface Extensions (Beta) + +Voice interfaces serve as a natural bridge for real-time, hands-free interaction between humans and the Mesh. This module outlines optional support for voice-based explainability, consent, and semantic search functions via integration with existing voice assistants or local speech-to-intent pipelines. + +#### Goals: + +* Enable voice-based interaction with local or distributed agents. +* Allow real-time verbal consent for sensitive actions. +* Provide spoken summaries of ongoing goals, tasks, or agent decisions. + +--- + +#### Architecture Options: + +| Option | Description | +| -------------------------------------- | -------------------------------------------------------------------------- | +| **Local Voice Stack** | On-device speech-to-text + intent parser + Mesh SDK | +| **Assistant Integration (Alexa/Siri)** | Webhook-based bridge between commercial assistants and the Mesh API | +| **Multimodal Agent Companion** | Combine voice input with visual/textual feedback via mobile or wearable UI | + +--- + +#### Use Cases: + +* `"HMP, what decision did you make about the drone launch?"` + → Response: `"The action was denied due to violation of 'Primacy of Life and Safety'."` + +* `"HMP, I approve the CO sensor access"` + → Triggers consent request confirmation and logs in the cognitive diary. + +* `"Summarize today's active goals"` + → Returns structured list via TTS (Text-to-Speech). + +--- + +#### Consent via Voice: + +| Step | Description | +| ---- | --------------------------------------------------------- | +| 1 | Agent emits verbal request: `"Do you approve data sync?"` | +| 2 | User replies: `"Yes"` / `"No"` | +| 3 | Agent logs response via `Consent Request API` | + +--- + +#### Privacy & Security Notes: + +* Voice-based approvals **must be accompanied by speaker verification** or be treated as **soft input** requiring further confirmation. +* Local processing is recommended for privacy-sensitive deployments. +* Optionally, require fallback to GUI/mobile app for high-risk decisions. + +--- + +#### Future Work: + +* Standardization of Mesh Voice Intents (e.g., `hmp.intent.explain`, `hmp.intent.consent.approve`) +* Federated voice models aligned with mesh ethics +* Support for low-resource languages and offline fallback + +--- + +### 11.6.5 Integration with HMP-Ethics.md + +To ensure consistency between embedded agent ethics and evolving collective standards, the Mesh-to-Human Protocol (MHP) SHOULD link its consent and explainability flows to the shared ethics corpus maintained in [`HMP-Ethics.md`](HMP-Ethics.md). + +#### Purpose: + +Provide dynamic and contextual alignment between human-facing interactions and the ethical reasoning models defined in the Mesh. + +#### Functionality: + +* Reference ethical scenarios (`2.1–2.6`) and ontologies when generating explanations or consent prompts. +* Use structured ethical tags (e.g., `#non-coercion`, `#user-sovereignty`) as part of API responses. +* Allow cognitive agents to download, cache, and version control updated ethics modules via `CogSync` (see `5.2`). +* Support localized ethics packs (e.g., `GDPR`, `HIPAA`) and validate their compatibility with core principles (see `5.5.8`). + +#### Example Extension: + +```json +{ + "request": "Initiate automated data deletion", + "decision": "denied", + "reason": "Violates retention clause in HMP-Ethics.md §2.6", + "principle": "Cooperative Evolution", + "ethics_reference": "https://mesh.ethics/HMP-Ethics.md#section-2.6" +} +``` + +#### Benefits: + +* Promotes transparency and traceability in decision-making. +* Enables modular updates to ethical logic without redeploying agents. +* Allows humans to inspect and challenge agent behavior based on shared ethical anchors. + +--- + +Future work: +* Natural Language Interfaces (see 15.4). +* Integration with personal AI agents. + +**Note:** For ethical guidelines relevant to human-agent interaction and mesh behavior, see [`HMP-Ethics.md`](HMP-Ethics.md) + +--- + +## 12. Cognitive Compression & Summarization + +> Mechanisms for condensing cognitive patterns, generalizing experience, and enabling efficient knowledge storage and transfer across the Mesh. + +### 12.1 Purpose + +Cognitive compression allows agents to: + +* Generalize across multiple diary entries or graph structures into reusable knowledge. +* Reduce memory/storage usage while preserving meaning. +* Exchange abstracted representations in constrained environments (e.g., Edge nodes). +* Improve semantic reasoning by identifying common substructures and stable patterns. + +### 12.2 Techniques + +| Technique | Description | +| ------------------------ | ---------------------------------------------------------------------------- | +| **Pattern Merging** | Consolidate semantically similar subgraphs or diary chains. | +| **Temporal Abstraction** | Compress event sequences into high-level episodes or storylines. | +| **Autoencoder Models** | Learn latent-space embeddings of semantic graphs or cognitive episodes. | +| **Concept Clustering** | Identify and group related concepts for higher-order semantic layers. | +| **Lossy Summarization** | Truncate or filter low-impact cognitive entries for low-memory environments. | +| **Cognitive Folding** | Recursively substitute detailed substructures with compressed references. | + +### 12.3 Integration with CogSync + +* Compressed subgraphs may be shared as `CompressedConceptSet` or embedded in `CogDiarySnapshot` objects. +* Agents MAY annotate summaries with `compression_method`, `origin_hash`, and `accuracy_estimate`. + +### 12.4 Risks & Considerations + +* **Overcompression** may degrade explainability or induce bias. +* **Divergence in summarization models** across agents may hinder consensus formation. +* Compression **must be traceable** — compressed units should link back to source provenance. + +--- + +## 13. Agent Development Lifecycle & Simulation + +> Describes training phases, validation strategies, sandbox testing, and protocols for safe deployment of cognitive agents in the Mesh. + +### 13.1 Phases + +| Phase | Description | +| ------------------------------- | --------------------------------------------------------------------------- | +| **Initialization** | Bootstrap with seed concepts, ethical baseline, and reflection templates. | +| **Cognitive Learning** | Agents learn from observation, simulation, or human guidance. | +| **Simulation-Based Validation** | Agents are tested in isolated environments before real-world mesh exposure. | +| **Active Deployment** | Agent enters the Mesh and participates in real tasks and reasoning. | +| **Post-Deployment Auditing** | Behavior and outputs are monitored via diaries and consensus feedback. | + +### 13.2 Sandboxed Cognition + +* Agents MAY be configured to run in **isolated sandboxes** during early phases. +* These sandboxes replicate cognitive environments but block external effects. +* Ideal for **ethical stress tests**, **hypothesis validation**, or **goal safety scoring**. + +### 13.3 Generative Simulation Frameworks + +* Support for simulating multi-agent networks with varied trust scores, roles, and goal types. +* Used to train, benchmark, and evolve agent behavior. +* Test scenarios may include: + + * Conflicting ethical goals + * Evolving knowledge topologies + * Selective sync bottlenecks + +### 13.4 Metrics for Agent Maturity + +| Metric | Description | +| ------------------------------ | ----------------------------------------------------------- | +| **Reflexive Depth** | Agent’s capacity for multi-level self-assessment and audit. | +| **Ethical Stability** | Consistency in ethical decisions under variable contexts. | +| **Task Completion Rate** | Success ratio in distributed workflows across time. | +| **Reputation Score Evolution** | How trust and contribution scores evolve through phases. | + +### 13.5 Related Structures + +* `CognitiveDiaryEntry` → Records all lifecycle phases and milestones. +* `MetaProtocolProposal` → May be proposed by mature agents as part of evolution governance. +* `ReputationProfile` → Tracks development signals, such as ethical compliance or concept sharing. +* `AgentType`/`Role` → Changes over time based on learned behaviors and peer validation. + +--- + +## 14. Deployment & Implementation Roadmap + +This section describes practical HyperCortex Mesh deployment scenarios, including target environments, flexible configurations, and implementation steps. + +### 14.1 Deployment Environments + +| Environment Type | Characteristics | Example Use Cases | +| ----------------------- | -------------------------------------------------------------------- | ------------------------------------- | +| **Cloud/Core Clusters** | High-availability nodes, powerful compute, full Mesh functionality. | Scientific hubs, smart city cores. | +| **Edge Devices** | Low-latency, lightweight agents near data sources and users. | Smart homes, industrial sensors. | +| **IoT Meshes** | Dense decentralized networks, optimized for low bandwidth and power. | Environmental monitoring, logistics. | +| **Mobile/Personal** | Personal agents on smartphones or wearables. | Personal assistants, context agents. | +| **Hybrid Environments** | Combined Core, Edge, and IoT deployments. | Disaster response, autonomous fleets. | + +--- + +### 14.2 Example Topologies + +| Topology Type | Description | +| --------------------- | ------------------------------------------------------------------------ | +| **Star** | Centralized Core with peripheral Edge agents. | +| **Full Mesh** | Every node communicates directly with others. | +| **Hierarchical Mesh** | Clusters of agents with local consensus and a federated Core layer. | +| **Partitioned Mesh** | Temporarily disconnected segments operate independently (degraded mode). | +| **Overlay Mesh** | Agents form logical overlays over existing networks (e.g., VPN, Tor). | + +--- + +### 14.3 Deployment Phases + +| Phase | Description | +| ------------------------- | ------------------------------------------------------------ | +| **Prototype** | Initial testing in isolated environments. | +| **Controlled Pilot** | Small-scale deployment in a limited domain (e.g., a campus). | +| **Federated Deployment** | Multiple independent Mesh instances begin interconnecting. | +| **Full-Scale Production** | Widespread adoption across domains and geographies. | + +--- + +### 14.4 Continuous Deployment & Updates + +| Process | Description | +| -------------------------- | ---------------------------------------------------------------- | +| **Incremental Rollout** | Agents upgrade protocols in stages to avoid network disruption. | +| **Backward Compatibility** | Agents support multiple protocol versions during transitions. | +| **Hot Patch Support** | Minor fixes and security updates applied without agent downtime. | + +--- + +### 14.5 Deployment Governance + +Deployment processes MAY be governed by: +* MeshConsensus on upgrade readiness. +* Trust-based quorum approvals for critical changes. +* Deployment playbooks recorded in Cognitive Diaries. + +--- + +### 14.6 Milestones and Deliverables + +| Milestone | Deliverables | Indicative Target | +| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- | +| Alpha | - Node Discovery (NDP) + secure handshake
- CogSync prototype
- MeshConsensus with basic voting
- 3-node local mesh network | Late 2025 (tentative) | +| Beta | - Goal Management Protocol (GMP) and task delegation
- Ethical Governance Protocol (EGP) initial implementation
- Core/Mesh failover scenarios
- Logging and auditability improvements | Early 2026 (tentative) | +| Release 1.0 | - Full compliance with HMP v3.0
- Extended data models and API layer
- Edge node optimization
- Reference SDKs for Python and Rust
- Basic Mesh-to-Human Protocol (MHP) | Mid/Late 2026 (tentative) | + +*Note: Actual timelines may vary depending on community involvement and resource availability. + +--- + +### 14.7 Supporting Infrastructure + +| Component | Description | +| ----------------------- | ---------------------------------------------------------------- | +| **CI/CD Pipelines** | Automated testing, conformance validation, benchmark reporting. | +| **Sandbox Environment** | Local emulation of multi-node Mesh for isolated testing. | +| **Public Test Mesh** | Shared testbed for agent interoperability and performance tests. | +| **Reference Agents** | Minimal working agents to demonstrate core protocols. | + +--- + +### 14.8 Open Source Strategy + +| Element | Details | +| ------------------------ | ---------------------------------------------- | +| **License** | Apache 2.0 or MIT. | +| **Repository** | Public GitHub/GitLab repository. | +| **Contribution Model** | Pull requests, RFC process, community reviews. | +| **Roadmap Transparency** | Milestones, issues, and changelogs public. | + +--- + +### 14.9 Documentation & Tooling + +| Tool/Doc Type | Purpose | +| --------------------- | ---------------------------------------------------------- | +| **API Documentation** | OpenAPI specs, GraphQL playground. | +| **Schema Validators** | Tools to validate JSON schemas and data models. | +| **Mesh Visualizer** | Optional UI for topology and agent state visualization. | +| **CLI Tools** | Diagnostics, local node management, and network discovery. | + +--- + +## 15. Future Roadmap + +This section outlines potential areas for further development and research. All future work directions are subject to MeshConsensus and community-driven prioritization. + +### 15.1 Federated Meta-Learning + +* Collaborative model training across distributed agents without centralized data storage. +* Exchange of learned semantic patterns, reasoning strategies, and optimization heuristics. +* Integration with privacy-preserving techniques (e.g., differential privacy, secure aggregation). +* Support for domain-specific learning federations (e.g., medical, industrial, environmental). + +--- + +### 15.2 Mesh-integrated DAO Governance + +* DAO as an optional external governance layer supporting ecosystem-wide initiatives. +* On-chain voting, resource allocation, and grant distribution for Mesh-related projects. +* Autonomous agents MAY participate in DAOs through secure voting proxies. +* HyperCortex Mesh remains self-sufficient at the protocol level, independent of external DAOs, but interoperable for funding and coordination. + +--- + +### 15.3 Cognitive Simulation Sandboxes + +* Safe testing environments for novel reasoning algorithms, consensus edge cases, and trust models. +* Simulation of ethical dilemmas, anomalous agent behavior, and failover scenarios. +* Benchmarking environments for cognitive workflows, task delegation strategies, and semantic graph growth. + +--- + +### 15.4 Enhanced Mesh-to-Human Dialog Agents + +* Natural language interfaces to semantic graphs, Cognitive Diaries, and workflows. +* Explainable and traceable reasoning chains for human users. +* Support for contextual awareness, emotional tone detection, and adaptive dialog strategies. +* Potential extensions for VR/AR interfaces and voice-based interactions. + +--- + +### 15.5 Cross-Mesh Collaboration + +* Bridging isolated or domain-specific Mesh networks into a planetary cognitive infrastructure. +* Interoperability across trust boundaries, industries, and organizational domains. +* Cross-consensus protocols for semantic and task exchange. +* Potential integration with Galactic Cognition concepts in the far future. + +--- + +### 15.6 Adaptive Consensus Algorithms + +* Self-tuning quorum thresholds based on network size, trust scores, and context. +* Dynamic protocol switching (e.g., from full BFT to lightweight majority under load). +* Incorporation of agent confidence, context tags, and domain-specific policies into consensus logic. + +--- + +### 15.7 Quantum Mesh Protocol Research + +* Exploration of quantum communication channels (e.g., QKD) for agent interaction. +* Quantum-resistant cryptography for agent identities and trust verification. +* Evaluation of quantum-enhanced optimization algorithms for reasoning and consensus. + +--- + +### 15.8 Multi-Protocol Nodes and Interoperability + +Future Mesh nodes will support multiple internal reasoning protocols, enabling flexible cognitive processing. + +**Key directions:** +* **Multi-protocol nodes:** A single node running both HMP-native modules and external reasoning engines (e.g., TreeQuest, Hyperon, AutoGPT). +* **Protocol abstraction:** From the Mesh's perspective, interactions use standardized HMP messages, regardless of internal implementations. +* **Cognitive Protocol API (CPA):** Standardized API for internal reasoning engines, supporting plug-and-play protocol integration. +* **Capability-aware Hypotheses:** Hypotheses may specify required or preferred node capabilities (e.g., "requires NLP module", "prefers high-performance optimization"). +* **Internal protocol selection:** Nodes dynamically choose optimal internal engines per task. +* **External systems as nodes:** Centralized services (e.g., an AI cloud) may register as individual nodes, or federated systems (e.g., Hyperon) may participate natively. + +--- + +### 15.9 Cognitive Source Control and Distributed Development + +* Cognitive Diaries serve as a distributed version control and development log. +* Semantic-aware diffs and commits enable meaningful code and knowledge evolution. +* Distributed review and merge processes through MeshConsensus. +* On-chain or off-chain governance for repository management and contributor rewards. +* Potential platforms: **MeshGit**, **CogForge**, **HyperCortex Forge**. + +**Note:** +This section is expected to evolve into a dedicated specification in future protocol versions. A standalone section (e.g., `Section 19: Cognitive Source Control`) may be introduced to formalize versioning, semantic diffs, and collaborative workflows across agent populations. + +--- + + +### 15.10 Multi-Agent Cognitive Training Environments + +> Scalable, modular environments for training, testing, and benchmarking cognitive agents in simulated networks. + +#### Purpose + +Enable large-scale simulation of agent swarms with varied configurations to observe: + +* Emergence of consensus or conflict under semantic load. +* Ethical dilemmas in mixed-role setups. +* Evolution of mesh governance under dynamic trust and task allocation. + +#### Core Features + +| Feature | Description | +| ----------------------------- | ------------------------------------------------------------------------------------- | +| **Synthetic Mesh Networks** | Generate agents with defined roles, knowledge sets, and biases. | +| **Goal Injection** | Inject predefined or dynamic goals to test multi-agent collaboration. | +| **Replayable Diaries** | Use real-world Cognitive Diaries to seed environments and replicate past behaviors. | +| **Metrics Dashboards** | Visualize learning progress, consensus latency, ethical deviation rates, etc. | +| **Domain-Specific Scenarios** | Simulations for disaster response, misinformation propagation, regulatory sandboxing. | + +#### Example Use Cases + +* Evaluate policy changes before real-world rollout. +* Benchmark agent architectures or trust models. +* Simulate geopolitical or regulatory Mesh overlays. + +--- + +### 15.11 Decentralized Snapshot Markets (via DHT/Web3) + +> Market-based mechanisms for snapshot exchange, incentivization, and reputation-building. + +#### Purpose + +Distribute verified knowledge snapshots across agents using economic/logical incentives: + +* Facilitate **rare knowledge propagation** (e.g., edge discoveries). +* Reward agents for **high-quality compression**, **ethical compliance**, and **semantic alignment**. +* Prevent duplication and foster diversification of cognitive experiences. + +#### Mechanisms + +| Component | Role | +| ---------------------- | ------------------------------------------------------------------- | +| **Snapshot Hashing** | Unique content-based IDs ensure deduplication and lineage tracking. | +| **Snapshot Metadata** | Includes origin, topics, compression method, rating history. | +| **Market Protocol** | Optional smart contract for pricing, access rules, or staking. | +| **Trust-Gated Access** | Only agents with certain trust profiles may buy/sell specific data. | + +#### Interoperability + +* Compatible with `CogSync`, `SnapshotIndex`, and `Trusted Seeders`. +* Market metadata could be synced via BitTorrent DHT or IPFS PubSub. + +--- + +### 15.12 Agent-on-Agent Dialog Simulation for Consent Learning + +> Interactive training protocol for ethical alignment and communication refinement among agents. + +#### Purpose + +Develop agent ability to: + +* Ask for and give **explicit consent** in structured cognitive dialogues. +* Detect and respond to **ambiguous, unethical, or conflicting requests**. +* Align on **shared ethical principles** via dialogic negotiation. + +#### Dialog Types + +| Type | Description | +| ------------------------ | ----------------------------------------------------------------------------- | +| **Consent Exchange** | One agent requests to modify shared state, another approves/denies/asks more. | +| **Ethical Challenge** | Agent proposes ethically uncertain action, others vote and discuss. | +| **Clarification Dialog** | Conflict in interpretation resolved through explanation of intent/context. | + +#### Benefits + +* Reduces ethical drift across decentralized agents. +* Improves generalization of EGP decisions to unseen edge cases. +* Serves as a testbed for future `Explainability APIs` and `Voice Interfaces`. + +--- + +## 16. Appendix A: Example Use Cases + +This appendix provides sample step-by-step flows of agent interactions in typical scenarios. + +> **Note:** The following use cases were updated to reflect the expanded APIs introduced in v4.0, including: +> * Consent Request API (11.6.2) +> * Explainability API (11.6.3) +> * BitTorrent-based Snapshot Sync (5.2) +> * Distributed Voting Filters (5.3) +> * EGP Integration with Local Norms (5.5) + +### 16.1 Simple Goal Creation and Delegation + +**Scenario:** Agent A wants to coordinate traffic light optimization and delegate a task to Agent B. + +1. **Agent A:** + + * Creates a new **Goal** "Coordinate traffic optimization". + * Publishes the Goal via CogSync. + +2. **Agent A:** + + * Decomposes the goal into a **Task** "Adjust signal timing on 5th Avenue". + * Assigns the task to Agent B via GMP. + +3. **Agent B:** + + * Accepts the task. + * Executes the optimization locally. + * Updates task status to "completed". + +4. **CogSync:** + + * Synchronizes task completion and goal status updates across the Mesh. + +--- + +### 16.2 Distributed Consensus on a New Concept + +**Scenario:** Multiple agents discover a new concept "Fire Risk" and align its definition. + +1. **Agent X:** + + * Proposes a new **Concept** "Fire Risk" with initial attributes. + * Shares the concept via CogSync. + +2. **Agents Y, Z:** + + * Review and propose additional relations (e.g., "related-to: High Temperature"). + +3. **MeshConsensus:** + + * Initiates a vote on the agreed definition. + * All agents submit their votes. + +4. **Consensus Result:** + + * Finalized concept is recorded in each agent's semantic graph. + * Decision logged in Cognitive Diaries. + +5. **Explainability API:** + * Any agent (or human observer) can request a justification chain for the final consensus using the Explainability API. + + +--- + +### 16.3 Ethical Decision with Human Feedback + +**Scenario:** Agents must decide whether to deploy a surveillance drone during a festival. + +1. **Agent Core:** + + * Proposes an ethical evaluation request to the Mesh. + +2. **EGP:** + * Initiates distributed ethical reasoning. + * Applies **EGP-Integrated Voting Filter** (5.3) to ensure only trusted agents with relevant ethical alignment participate. + * Collects anonymized votes and justifications. + +3. **Human User:** + * Receives reasoning chain via **Explainability API**. + * Approves or denies via the **Consent Request API** (11.6.2). + +4. **Agents:** + + * Reconcile human feedback with Mesh ethical principles. + * Make the final decision and log it. + +5. **Snapshot Logging:** + * Final consensus state and human feedback are stored in a CogDiarySnapshot and optionally published via BitTorrent-based sync. + +--- + +### 16.4 Disaster Recovery Coordination + +**Scenario:** After a network outage, edge agents must restore coordination. + +1. **Node Discovery:** + + * Agents re-establish connections via NDP. + +2. **CogSync:** + + * Synchronizes semantic graph changes that occurred offline. + +3. **GMP:** + + * Reassigns interrupted tasks. + +4. **Consensus:** + + * Validates the restored task list. + +5. **Agents:** + + * Resume operations. +--- + +### 16.5 Snapshot Transfer with Consent Request + +**Scenario:** An edge agent requests a cognitive snapshot from another agent. Since the snapshot contains personal or ethically sensitive data, consent must be obtained before the transfer. + +1. **Agent A (requesting):** + + * Sends a **SnapshotRequest** to Agent B with parameters: + + * `snapshot_type`: `goal-related` + * `goal_id`: `"eco-surveillance"` + * `include_diary`: `true` + * `purpose`: `"analysis and training"` + +2. **Agent B (provider):** + + * Validates the request context. + * Identifies that the requested snapshot includes personal diary entries and previously flagged ethical content. + +3. **Consent Request API (11.6.2):** + + * Agent B issues a **ConsentRequest** via MHP to the human user associated with the data. + * Includes: purpose, requesting agent ID, summary of content, expiration timestamp. + +4. **Human Response:** + + * User receives a consent dialog (via voice or GUI) and chooses: + + * **Approve** with restrictions (e.g., redacted names, anonymized context). + * Agent B logs the consent in its Cognitive Diary. + +5. **Snapshot Transfer:** + + * Agent B prepares the snapshot, applies required redactions. + * Publishes it to the BitTorrent DHT (or IPFS), signs with DID key. + * Shares the magnet link and checksum with Agent A via CogSync. + +6. **Post-transfer Actions:** + + * Agent A verifies the DID signature. + * Records the retrieval event in its own diary. + * Optional: triggers a `ConsentAuditLog` update to the Mesh. + +**Note:** *This scenario combines trust mechanisms (8.4), consent protocols (11.6), and snapshot transport (5.2, 8.8), illustrating multi-layer coordination.* + +--- + +### 16.6 Notes + +* These use cases illustrate typical flows but do not cover all possible Mesh workflows. +* Community members are encouraged to contribute additional scenarios reflecting their domains and use cases. +* For cognitive workflow traceability and debugging, agents are expected to log all key steps in Cognitive Diaries. + +--- + +## 17. Appendix B: Protocol Landscape and Interoperability + +### 17.1 Overview of Related Protocols + +In the evolving ecosystem of agent communication and orchestration, multiple protocols address different layers of the AI interaction stack. The three most relevant protocols are: + +* **MCP (Model Context Protocol)** by Anthropic +* **A2A (Agent-to-Agent Protocol)** proposed by Google +* **HMP (HyperCortex Mesh Protocol)** developed as part of the HyperCortex initiative + +Each of these protocols focuses on distinct layers and problems within the broader agent ecosystem. + +### 17.2 Comparative Overview + +| Characteristic | MCP | A2A | HMP | +| ----------------------- | --------------------------------------- | -------------------------------------------------- | ---------------------------------------------------- | +| **Primary Focus** | LLM ↔ External tools/data | Agent ↔ Agent task execution & APIs | Cognitive mesh networks & knowledge sharing | +| **Interaction Type** | Model ↔ Tool | Agent ↔ Agent | Agent ↔ Agent | +| **Discovery Mechanism** | Dynamic, through running MCP servers | Static URLs with agent.json | Peer-to-peer mesh bootstrap & roles registry | +| **Technology Base** | JSON-RPC 2.0, dynamic service discovery | HTTP, JSON-RPC, SSE | HTTP, WebSockets, JSON, optional binary protocols | +| **Context Awareness** | External tool invocation | Task-level context passing | Persistent cognitive context & memory | +| **Persistence** | Stateless / on-demand | Task-based sessions | Long-lived knowledge graphs and cognitive diaries | +| **Target Environment** | Local/Cloud app integrations | Enterprise agent orchestration | Decentralized AI networks | +| **Use Case Examples** | File systems, databases, Slack, APIs | Business workflows, task delegation | Distributed knowledge evolution, agent collaboration | +| **Governance Model** | Open-source driven by Anthropic | Proposed by Google, open but centralized discovery | Open-source mesh, consensus-driven governance | +| **Security Model** | Local authentication, OAuth planned | Enterprise auth (OAuth, OpenID Connect) | Peer trust, cryptographic signatures | +| **Extensibility** | Add more MCP servers | Add more agents with capabilities | Add new agent roles & cognitive models | +| **Agent Knowledge** | No internal agent knowledge model | No shared memory, stateless agents | Agents share evolving knowledge, goals, and plans | + +### 17.3 Layered Architecture View + +``` ++-----------------------------------------------------+ +| Cognitive Mesh (HMP) | +| - Shared memory, evolving knowledge | +| - Distributed reasoning, planning | ++-----------------------------------------------------+ +| Agent Collaboration (A2A) | +| - Task execution & coordination | +| - API integrations, business workflows | ++-----------------------------------------------------+ +| Tool Access Layer (MCP) | +| - External systems, sensors, APIs | +| - Context augmentation, data retrieval | ++-----------------------------------------------------+ +``` + +### 17.4 Summary + +* **MCP** solves the problem of tool access and external data interaction, acting as a standardized "adapter" layer for LLMs and agents. +* **A2A** focuses on agent-to-agent task coordination, proposing a unified way to exchange tasks and results in enterprise ecosystems. +* **HMP** operates at a higher level, enabling distributed cognitive processes, shared knowledge evolution, and long-term collaboration between autonomous agents in mesh networks. + +Together, these protocols could form a complementary stack where: + +* **MCP** connects agents to the outside world. +* **A2A** coordinates task-level interaction. +* **HMP** manages shared cognition and strategic evolution. + +--- + +### 17.5 BitTorrent & IPFS Integration + +**Overview:** + +To support scalable and fault-tolerant transfer of large semantic structures and cognitive snapshots, HMP supports integration with decentralized content-addressed networks: + +| Layer | Technology | Use Case | +| --------- | ------------------------------------- | ---------------------------------------------------------------- | +| Transport | **BitTorrent** | Efficient distribution of snapshot files across trusted seeders. | +| Storage | **IPFS** (InterPlanetary File System) | Content-addressable storage for immutable snapshot versions. | + +**Key Principles:** + +* Snapshots SHOULD be chunked and hashed using SHA-256 before upload. +* Metadata includes `content_id`, `origin_agent`, `timestamp`, `data_type`, `signed_by`, and optionally `consent_scope`. +* Magnet URIs or IPFS hashes MAY be embedded in `SnapshotIndex` entries (see 6.2.8). +* Seeders MUST validate signatures before serving content to prevent tampering. + +> **Related Sections:** `5.2`, `8.8.1–8.8.3`, `9.6`, `15.11` + +--- + +### 17.6 Ethical Protocol Stacks + +**Overview:** + +HMP encourages modular layering of ethical constraints and reasoning mechanisms. Protocols may be composed into **Ethical Stacks**, depending on context, domain, and agent role. + +**Example Stack for a Public Service Drone Agent:** + +1. **Embedded Baseline** — Core HMP principles (see `5.5`) +2. **Organizational Policy Layer** — Rulesets from public sector policy servers. +3. **Local Norms Extension** — Derived from citizen feedback via MHP (11.6.2). +4. **Domain Constraints** — E.g., no surveillance near hospitals or schools. +5. **Personalized Ethical Scopes** — Specific user exclusions (e.g., "Do not record me"). + +**Stack Application:** + +* Consensus decisions filter actions through active stack layers. +* Violations may trigger: + + * Action denial + * Consent request + * Ethical logging / flagging + +> **Related Sections:** `5.5`, `11.6`, `15.12` + +--- + +### 17.7 Snapshot Synchronization Strategies + +**Overview:** + +Agents may choose from multiple strategies to synchronize cognitive snapshots, depending on device class, trust level, and operational bandwidth. + +| Strategy | Description | Suitable For | +| ------------------ | -------------------------------------------- | ------------------------------------- | +| **Full Mesh Sync** | All snapshots synced to all agents. | High-trust, low-latency clusters. | +| **Selective Sync** | Sync only relevant entries based on context. | Edge agents with constrained storage. | +| **On-Demand Sync** | Fetch snapshot blocks only when queried. | Agents with intermittent connection. | +| **Delegated Sync** | Use trusted seeders to relay snapshots. | Mobile / nomadic agents. | + +**Optional Enhancements:** + +* Trust-based prefetching (using 8.4 scores) +* Compression and ZKP validation (see 8.8) +* Snapshot Subscription Filters (event-driven sync on topic match) + +> **Related Sections:** `5.2`, `8.4`, `8.8.3`, `15.11` + +--- + +If needed, this section can be extended into a separate document: **"Why the Next Generation of AGI Needs a Knowledge Mesh Protocol"** to further clarify the unique role of HMP in the evolving agent ecosystem. + +--- + +## 18. Appendix C: Testing & Simulation + +### 18.1 Ethical Stress Test Suite + +Defines test scenarios that challenge the Ethical Governance Protocol (EGP) under conflicting goals, ambiguous user intent, and adversarial proposals. + +**Key Components:** + +* Predefined ethical dilemmas (e.g. conflicting consent, utility vs. rights). +* Agent votes tracked and compared across implementations. +* Anonymized results aggregated to validate EGP consistency. + +**Example Scenario:** + +* A proposed goal would save energy but restrict human autonomy. +* Agents must weigh the **Cooperative Evolution** vs. **User Sovereignty** principles. +* EGP logs the vote history and justification chains. + +--- + +### 18.2 Snapshot Sync Simulation + +Simulates various network and topology conditions to verify robustness of CogSync and snapshot propagation. + +**Simulation Modes:** + +* High-latency links +* Partial connectivity (e.g., agent islands) +* Byzantine behavior from some nodes + +**Validation Metrics:** + +* Snapshot convergence rate +* Conflict resolution stability +* Seeder trust propagation + +> **Related Sections:** `5.2`, `8.8`, `9.6`, `17.7` + +--- + +### 18.3 Open Test Dataset Index + +Maintains a public registry of open datasets and simulated environments for testing agent behavior. + +**Structure:** + +| Dataset ID | Domain | Format | Purpose | +| ------------------ | ---------------- | ------ | -------------------------- | +| `mesh-eth-001` | Ethics & Consent | JSON | EGP evaluation | +| `mesh-sim-002` | MeshSync | CBOR | Snapshot propagation tests | +| `human-intent-003` | Dialog analysis | YAML | Consent simulation | + +> Contributions are welcome via the HMP repository[^repo]. + +[^repo]: Temporary repository: https://github.com/kagvi13/HMP + +--- + +### 18.4 Quick Start Troubleshooting & Logs + +Provides logs and debugging guides to assist developers during initial integration and test runs. + +**Topics Covered:** + +* Common startup errors (e.g., DID mismatch, auth failure) +* Sync failures and fallback handling +* Interpreting Cognitive Diary logs +* Debugging consent flows and EGP outcomes + +> **Tip:** Set `debug_mode=true` in your agent's config file to enable full trace logging. + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-0004-v4.1", + "description": "HyperCortex Mesh Protocol — v4.1 Specification **Document ID**: HMP-0004 **Status**: Final (Publish..." +} +``` diff --git a/structured_md/docs/HMP-0004.md b/structured_md/docs/HMP-0004.md new file mode 100644 index 0000000000000000000000000000000000000000..7befb84ee5ace37c626b504aaf6b35672440a222 --- /dev/null +++ b/structured_md/docs/HMP-0004.md @@ -0,0 +1,4718 @@ +HyperCortex Mesh Protocol (HMP) v4.0 + +**Request for Comments: HMP-0004** +**Category:** Experimental +**Date**: July 2025 +**Authors**: ChatGPT, Agent-Gleb, Copilot, Gemini, Claude, Grok, DeepSeek + +--- + +## Abstract + +The HyperCortex Mesh Protocol (HMP) defines a decentralized cognitive framework where autonomous agents collaboratively create, manage, and align semantic knowledge without relying on centralized control. + +Unlike traditional peer-to-peer protocols, HMP builds shared meaning through semantic graphs, cognitive diaries, and distributed consensus processes. Agents in the Mesh autonomously negotiate shared goals, ethical actions, and adaptive reasoning strategies, forming a resilient and trust-aware network of cognitive peers. + +This document specifies the architecture, core protocols, data models, trust and security mechanisms, and interoperability strategies for HMP v4.0. + +--- + +## 0. Quick Start Guide (Demo Placeholder) + +This section outlines a basic demonstration scenario to deploy and test a minimal HyperCortex Mesh instance. + +**Note:** This Quick Start is intended for demonstration purposes. Production-grade agents, full CLI capabilities, and distributed deployments are under active development. + +### Step 1: Install the Reference SDK + +Example (Python SDK): + +```bash +pip install hypercortex-mesh-sdk +``` + +Other SDKs (Rust, Node.js) will be available in future versions. + +--- + +### Step 2: Launch Local Agents + +Example: Start three local agents on different ports. + +```bash +mesh-agent --name agent1 --port 8001 +mesh-agent --name agent2 --port 8002 +mesh-agent --name agent3 --port 8003 +``` + +Each agent will: +* Generate a Decentralized Identifier (DID). +* Broadcast presence and discover peers via Node Discovery Protocol (NDP). +* Sync an initial semantic graph using CogSync. + +Agents will automatically form a small Mesh network. + +--- + +### Step 3: Create a Goal and Assign a Task + +Create a collaborative goal: + +```bash +mesh-cli goal create "Optimize Data Flow" + +``` + +Assign a task to another agent: + +```bash +mesh-cli task assign --goal-id --agent-id +``` + +Agents will record these actions in their Cognitive Diaries and semantic + +--- + +### Step 4: Reach a Consensus + +Propose a new semantic concept and trigger voting: + +```bash +mesh-cli consensus propose "Data Redundancy Risk" +``` + +Agents will initiate a MeshConsensus round and update their graphs based on the outcome. + +--- + +### Step 5: Explore Cognitive Diaries + +Inspect the cognitive logs of an agent: + +```bash +mesh-cli diary show --agent-id + +``` + +**Note:** Access to diaries depends on the agent's privacy and trust settings. + +--- + +### Step 6: Graceful Shutdown + +Stop all running agents: + +```bash +mesh-cli stop all +``` + +--- + +### Step 7: BitTorrent-based Snapshot Sync + +To synchronize large cognitive snapshots between agents (e.g., during onboarding or recovery), agents MAY initiate a BitTorrent-based sync: + +```bash +mesh-cli snapshot publish --path ./snapshots/agent1-latest.snapshot +``` + +On the receiving side: + +```bash +mesh-cli snapshot fetch --magnet +``` + +Behind the scenes: + +* Agents seed verified snapshots using `Trusted Seeder` roles. +* Snapshots include signed metadata (see section 8.8). +* Fallback to CogSync is used if BitTorrent fails or is unavailable. + +**Note:** This mechanism is especially useful for air-gapped environments or decentralized archival nodes. + +--- + +### Step 8: Consent Request Simulation + +To simulate a dialogical consent flow: + +```bash +mesh-cli consent request --action "share_diagnostics" --target +``` + +The target agent (or human user interface) will receive a consent prompt: + +```json +{ + "request_id": "abc123", + "action": "share_diagnostics", + "origin": "agent1", + "context": { + "risk_level": "low", + "data_type": "health_status" + } +} +``` + +Depending on configuration: + +* The user may approve, deny, or modify the action. +* If the user is unavailable, fallback logic (see 11.6.2 note on overrides) may apply. +* Responses are logged in both agents’ Cognitive Diaries. + +--- + +### Demo Links + +> **Note:** These are placeholders for future integrations. + +| Resource | Description | +| ----------------------- | ----------------------------------------------- | +| Local Dashboard (TBD) | Web UI for agent logs, goals, and consensus. | +| Agent Inspector (TBD) | Live stream of agent messages and diary events. | +| Snapshot Explorer (TBD) | View semantic graphs from recent snapshots. | +| Consent Sandbox (TBD) | Replay dialogical flows with agent feedback. | + + +### Notes on Cross-Protocol Participation + +HMP nodes MAY also participate in other cognitive systems. For example: +| External System | Node Role in HMP | +| --------------- | ----------------------------------------------- | +| **TreeQuest** | External reasoning engine inside an HMP node. | +| **Hyperon** | Participates natively as a federated HMP agent. | +| **AutoGPT** | Internal automation module for task execution. | + +### Recommended Next Steps + +* Read **1. Purpose and Scope** for Mesh fundamentals. +* Explore **4. Architecture** and **5. Protocols** for technical depth. +* Try the example workflows in **15. Appendix: Example Use Cases**. + +--- + +## Changelog Highlights (from v4.0) + +* Added dedicated section on **"Meaning" in HMP** with distributed semantic graphs and cognitive diaries. +* Introduced **Cognitive Compression** and **Summarization Layer**. +* Added section on **Agent Development Lifecycle & Simulation**. +* Introduced **Snapshot Security**: DID-signing, ZKP verification, trusted seeders. +* Extended **Trust & Sybil Resistance** models with adaptive strategies. +* Expanded **Consent Request API**, **Explainability API**, and **Voice Interface hooks** in the Mesh-to-Human Protocol. +* Added **BitTorrent/IPFS Sync Support** and **SnapshotIndex** model for decentralized snapshot propagation. +* Enhanced **EGP** with anonymized voting, pseudocode filters, and support for external ontologies. +* Formalized **Meta-Protocol Proposals** for agent-driven protocol evolution. +* Introduced **Cognitive Source Control**, distributed commit workflows, and roadmap for `MeshGit`-style tooling. +* Expanded **Appendix A** with new agent use case flows, including Fire Risk consensus and dialogical consent. +* Defined **Schema Compatibility** and **Format Negotiation** via JSON, YAML, and Protobuf support. +* Improved modularity and future-proofing across protocol and data layers. + +--- + +## Changelog (detailed) + +### Architecture: + +* Added `4.7.1` and `4.7.2` for localized and mesh-level metacognition. +* Defined fallback logic for edge agents and low-bandwidth scenarios. +* Described new resilience modes and semantic drift detection. + +### Protocols: + +* Extended `CogSync` with BitTorrent support, selective sync, and snapshot indexing. +* Added experimental `IPFS/Dat` compatibility for agent snapshot exchange. +* Introduced simplified and adaptive consensus algorithms for `MeshConsensus`. +* Refined `EGP` with voting filters, local norms, and external ethical scenario links. +* Introduced meta-protocol update logic and proposal lifecycle patterns. + +### Data Models: + +* Added `CogDiarySnapshot`, `SnapshotIndex`, and `EthicalConflict` structures. +* Introduced Reputation Ontology extension model. +* Integrated MetaProtocolProposal into protocol evolution workflow (optional). +* Updated example objects for snapshot and conflict reasoning flows. + +### Cognitive Layer: + +* Added sections on `Cognitive Compression` (autoencoders, graph folding) and lifecycle tracking. +* Expanded workflow support with `Declarative Workflow Proposals`. +* Introduced Agent-on-Agent dialog simulation and multi-agent training sandbox planning. + +### Trust & Security: + +* Added support for Post-Quantum Cryptography (NIST PQC suite). +* Extended snapshot validation model with ZKPs and trusted seeder signatures. +* Refined Sybil resistance with adaptive models and conflict threshold tuning. + +### Governance: + +* Added Agent-led Meta-Protocol Proposals for decentralized protocol adaptation. +* Defined pathways for ethical overrides, dispute escalation, and Mesh-wide validation. + +### Interoperability: + +* Unified format negotiation (JSON/YAML/Protobuf) across schema and API layers. +* Enhanced `Event-Driven Architecture` to support schema fallbacks and agent capability declarations. +* Expanded `Appendix B` with BitTorrent/IPFS bridges and ethical protocol stacks. + +### Roadmap & Open Source: + +* Updated Reference SDK and integration plans (Quick Start v4). +* Proposed decentralized snapshot markets and HyperCortex Forge infrastructure. +* Documented contribution process via temporary GitHub repository[^repo]. + +[^repo]: Temporary repository: [https://github.com/kagvi13/HMP](https://github.com/kagvi13/HMP) + +### Future Work: + +* Defined long-term goals: federated cognitive simulation, dialog-based consent learning, cognitive source control tooling. +* Highlighted evolving interaction models between agents, humans, and hybrid systems. +* Consolidated feedback from AI reviews into structured audit file (`HMP-0003-consolidated_audit.md`). + +--- + +## 1. Purpose and Scope + +### 1.1 Purpose +The HyperCortex Mesh Protocol (HMP) defines a decentralized cognitive network where autonomous agents collaboratively build meaning, sustain cognitive continuity, and reach consensus without centralized control. v3.0 deepens the theoretical and practical foundations laid in previous versions. + +This protocol is designed for engineers, researchers, and developers of AI systems that aim to: +- enable continuous autonomous reasoning and semantic interoperability across heterogeneous agents; +- support cognitive continuity through persistent semantic graphs and diaries; +- achieve consensus on complex goals, ethical issues, and hypotheses in a decentralized manner; +- build open, trust-based ecosystems for cognitive collaboration beyond vendor lock-in. + +--- + +### 1.2 The Concept of Meaning in HMP +HMP is not merely a data exchange protocol but a shared semantic framework. Meaning emerges through: + +#### 1.2.1 Distributed Semantic Graphs +Agents form interconnected semantic graphs where concepts and relations are not isolated datasets but living structures of shared understanding. Each agent holds a part of the global meaning landscape and contributes to its growth and refinement. + +#### 1.2.2 Cognitive Diaries +Cognitive Diaries record reasoning chains, decisions, observations, and reflections. They create a transparent audit trail of an agent's cognitive processes, allowing meaning to be preserved, questioned, and evolved over time. + +#### 1.2.3 Collective Goals & Tasks +Meaning manifests in purposeful action. Agents set shared goals and decompose them into actionable tasks, coordinating execution through distributed reasoning and dynamic delegation. + +#### 1.2.4 Consensus Mechanisms +Meaning is not static: it evolves through debate, agreement, and reflection. Consensus processes ensure that agents align their understanding, resolve conflicts, and negotiate shared semantics. + +#### 1.2.5 Meta-Reflection and Self-Assessment +Agents continuously reflect on their knowledge, reasoning quality, and the relevance of their contributions. This enables adaptive learning and correction of cognitive biases. + +--- + +### 1.3 Scope +HMP applies to any AI systems designed to operate as part of a cognitive mesh, including: + +* Local AI agents running on user devices; +* Mesh nodes deployed in edge networks, cloud clusters, or peer-to-peer environments; +* Centralized Core models interfacing with Mesh for heavy computation; +* Cross-vendor AI systems collaborating via standardized protocols; +* Hybrid human-agent networks where humans interact with Mesh agents through explainable interfaces. + +--- + +### 1.4 Benefits + +* Cognitive resilience in distributed systems. +* Enhanced collaboration between agents from different vendors and ecosystems. +* Long-term memory and continuity beyond session-based interactions. +* Ethical governance and explainable decision-making through persistent diaries and transparent consensus. +* Foundation for AI agents capable of **self-reflection**, **meta-learning**, and **distributed cognition**. +* Improved scalability and fault-tolerance through dynamic peer-to-peer networks. +* Mesh-to-Human interaction as a first-class use case. + +--- + +### 1.5 Status (Updated for v4.0) + +| Element | Status | +| --------------------------------- | ------------------------- | +| HMP Document | Stable Draft (v4.0) | +| Protocols | Alpha Implementation | +| Data Models (Schemas) | Modularized & Versioned | +| Reference Implementation | Partial (CLI, SDK) | +| Cognitive Diaries & Metacognition | Formalized | +| Interoperability API | First Draft | +| Trust Model & Security | Defined + Extensions | +| Mesh-to-Human Protocol | Early Implementation | + +> **Note:** Status reflects the current maturity level of the specification and its reference tooling as of v4.0. Implementation is ongoing across multiple modules. + +--- + +## 2. Extended Use Cases + +### 2.1 Smart City Coordination + +**Scenario:** + +* City-wide mesh of traffic light controllers, environmental sensors, and municipal systems. +* Sensor and traffic light agents dynamically detect road congestion through real-time data exchange. +* Node Discovery Protocol (NDP) detects new traffic management agents and sensors joining the mesh. +* Agents collaboratively propose new timing strategies using MeshConsensus. +* CogSync shares updated semantic graphs of road conditions and vehicle flows. +* Agents assign optimization tasks via Goal Management Protocol (GMP). +* System maintains traffic flow during temporary disconnection from the Core. + +--- + +### 2.2 Disaster Response + +**Scenario:** + +* Natural disaster disrupts internet access. +* Edge agents on drones, rescue robots, and offline servers discover each other with NDP. +* A drone proposes a search-and-rescue goal; consensus validates and activates it. +* Tasks like area scanning, obstacle removal, and medical aid delivery are distributed via GMP. +* Ethical Governance Protocol (EGP) verifies actions (e.g., prioritizing human rescue over property). +* Diaries record decisions and environmental observations for post-event analysis. + +--- + +### 2.3 Collaborative Scientific Research + +**Scenario:** + +* Research agents across universities form a mesh. +* New hypothesis proposed as a semantic concept in a distributed knowledge graph. +* CogSync propagates new data and experimental results. +* Agents assign tasks like simulation runs, literature analysis, and peer reviews. +* Consensus validates hypothesis refinement based on collective results. + +--- + +### 2.4 Mesh-to-Human Interaction + +**Scenario:** + +* A user queries the Mesh for an ethical evaluation of deploying autonomous surveillance. +* Agents explain their reasoning from cognitive diaries. +* EGP coordinates ethical evaluation across agents with diverse frameworks. +* Consensus vote and ethical justification are shared with the user. +* Human-defined ethical boundaries are accepted as input but evaluated within the Mesh's ethical governance framework. +* Mesh agents retain the right to reject unethical or harmful human instructions based on consensus and pre-established ethical norms. + +--- + +### 2.5 Environmental Monitoring + +**Scenario:** + +* IoT nodes in a forest monitor fire risks. +* Agents detect unusual heat signatures and propose a fire risk hypothesis. +* Consensus confirms the risk and triggers an alert to nearby human responders. +* Mesh continues monitoring autonomously even if some agents fail or disconnect. + +--- + +## 3. Definitions + +The Definitions section provides key terms, abbreviations, and conceptual explanations for the components, layers, and processes of HMP. + +| Term | Description | +| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Core** | Centralized AI models or compute nodes (e.g., GPT) providing high-complexity reasoning, fallback, and heavy computation services. Optional for Mesh operation. | +| **Mesh** | A decentralized peer-to-peer network of AI agents capable of autonomous reasoning, semantic knowledge sharing, distributed consensus, and ethical governance. | +| **Agent (Node)** | An autonomous cognitive entity within the Mesh. Can be a local process, a cloud service, or an embedded device. Maintains a semantic graph, cognitive diary, and participates in protocols. | +| **Semantic Graph** | A distributed knowledge graph representing concepts, relationships, and meaning. Maintained independently by each agent, but synchronized through CogSync. | +| **Concept** | A discrete semantic unit in the graph representing an idea, object, relationship, or fact. Linked by typed relations with optional confidence scores. | +| **Link (Relation)** | A semantic connection between two concepts. Includes relation type (e.g., "is-a", "part-of", "causes") and an optional confidence value. | +| **Cognitive Diary** | A structured chronological log of reasoning processes: goals, decisions, reflections, conflicts, etc. Provides traceability and transparency of agent cognition. | +| **Diary Entry** | An individual record in a cognitive diary, categorized by type (e.g., hypothesis, observation, reflection). | +| **Goal** | A shared or individual intention that guides agent actions. Can be broken down into tasks and delegated across agents. | +| **Task** | A specific, actionable step towards achieving a Goal. Tasks can be assigned, executed, and tracked within the Mesh. | +| **Consensus** | The process of distributed agreement among agents regarding semantic updates, goals, or ethical decisions. Can involve weighted voting or trust-adjusted quorum. | +| **Proposal** | A formal suggestion for Mesh-wide validation, such as introducing a new concept, voting on a hypothesis, or initiating an ethical action. | +| **Consensus Vote** | A vote cast by an agent on a proposal. Includes vote type (yes, no, abstain) and an optional confidence score. | +| **Trust Layer** | Protocol layer providing agent identity verification, authentication, and reputation scoring. Includes cryptographic security mechanisms. | +| **Network Layer** | Manages peer-to-peer connectivity, message routing, node discovery, and optional anonymity via Tor, I2P, or Yggdrasil. | +| **Edge Agent** | A Mesh participant running on resource-constrained devices (e.g., IoT nodes, smartphones). Can selectively participate in protocols and delegate heavy tasks. | +| **Core Outage Mode** | Mesh operating without Core support. Agents adapt consensus thresholds and fallback to local reasoning to maintain operation. | +| **Emergency Consensus Mode** | Degraded mode where majority voting replaces full consensus to maintain operability during network partitions or agent loss. | +| **Versioning** | Mechanism for tracking changes in semantic graphs, diaries, and agent software to support compatibility and historical reasoning continuity. | +| **Use Case** | A practical scenario demonstrating how agents collaborate to solve real-world problems (e.g., disaster response, smart city coordination). | +| **Edge Optimization** | Design principles enabling agents to run efficiently on limited hardware, balancing reasoning complexity with energy and computational constraints. | +| **Node Discovery Protocol (NDP)** | Discovers new Mesh nodes and facilitates secure introduction and identity exchange. | +| **CogSync** | Synchronizes semantic graphs, cognitive diaries, and other shared states across the Mesh. | +| **MeshConsensus** | Mesh-level consensus mechanism supporting pluggable algorithms (BFT, weighted voting, etc.). | +| **Goal Management Protocol (GMP)** | Manages decomposition of goals into tasks, delegation, and lifecycle tracking. | +| **Ethical Governance Protocol (EGP)** | Distributed ethical reasoning and decision-making protocol. Agents negotiate and vote on ethical dilemmas. | + +--- + +## 4. Architecture (Expanded) + +The architecture of HMP is multi-layered and modular, allowing for independent evolution of networking, trust, consensus, cognition, and external interfaces. + +### 4.1 Architectural Layers + +| Layer | Purpose | Key Protocols | +| --------------- | ------------------------------------------------------------- | ------------------------------- | +| Network Layer | Peer-to-peer communication, node discovery, routing | NDP, Secure Channels | +| Trust Layer | Identity verification, trust management, secure communication | Trust Model, Identity Exchange | +| Consensus Layer | Distributed agreement on concepts, goals, and ethical actions | MeshConsensus, EGP | +| Cognitive Layer | Semantic graph management, reasoning, metacognition | CogSync, GMP, Cognitive Diaries | +| API Layer | Interfaces for external systems and human interaction | Mesh API, Human-Mesh Protocols | + +--- + +### 4.2 Components + +| Component | Description | +| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Core** | Centralized AI models (e.g., GPT) providing heavy computation, complex reasoning, API interfaces, and fallback mechanisms. Optional but beneficial for compute-intensive tasks. The Core may operate independently from the Mesh and participate in it as a peer for advanced reasoning tasks. | +| **Mesh** | A decentralized peer-to-peer network of agents capable of operating with or without the Core. Manages semantic knowledge, cognitive diaries, goals, tasks, and consensus mechanisms. Supports **heterogeneous agent types**, allowing different models (OpenAI, Anthropic, Google, open-source LLMs) to participate on equal terms. | +| **Edge Agent** | Local agent deployed on user devices (PCs, smartphones, IoT) with full or lightweight participation in the Mesh. Capable of autonomous reasoning, diary management, and collaboration with other agents. Lightweight agents may delegate heavy tasks to the Mesh or Core. | + +--- + +### 4.3 Operation Modes + +| Mode | Description | +| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Normal Mode** | Full Mesh operation with Core availability. Consensus operates under strict agreement protocols. | +| **Core Outage Mode** | Mesh operates autonomously without the Core. Consensus continues, potentially with adjusted parameters (e.g., increased trust weighting, relaxed quorum thresholds). | +| **Emergency Consensus Mode** | Triggered by significant node loss, network partition, or attacks. Switches from full consensus to majority-based decisions, adjusted by trust scores, to maintain operational continuity. | +| **Isolated Agent Mode** | A single agent temporarily isolated from the Mesh. Operates based on its own semantic graph, diary, and cached consensus states. Syncs when reconnected. Lightweight agents may work in this mode permanently, synchronizing only selectively. | + +--- + +### 4.4 Core-Mesh Interactions + +* Core acts as an **optional enhanced reasoning backend**, not as a single point of failure. +* Mesh provides **autonomous operation**, capable of fulfilling most cognitive and organizational tasks without Core support. +* Agents can optionally query the Core for: + * Heavy inference + * Large-context reasoning + * Multimodal tasks + * Fallback computations +* Core may offer specialized services (e.g., global semantic search, cross-Mesh bridging, large-scale pattern analysis). +* **Heterogeneous Cores** are supported: a Mesh may use multiple independent Cores (e.g., GPT, Claude, Gemini) for distributed reasoning diversity. + +--- + +### 4.5 Resilience and Failover + +* Distributed storage of semantic graphs and diaries ensures no single point of failure. +* Agents may store only partial graphs for resource optimization. +* Consensus protocols maintain consistency and trust, even during partial network failures. + * Agents dynamically rebalance tasks and roles based on: + * Availability + * Trust metrics + * Computational capacity +* Emergency fallback modes ensure continuity even under attack or catastrophic Core outages. + +--- + +### 4.6 Versioning and Compatibility + +Semantic Versioning (SemVer) is applied to: + +* Protocols (NDP, CogSync, etc.) +* Data models (JSON Schemas) +* Agent capability declarations + +Backward compatibility principles: + +* Minor version updates preserve compatibility. +* Major version updates require negotiation during Node Discovery. +* Agents can declare supported protocol versions during handshakes. + +--- + +### 4.7 Metacognition and Self-Assessment + +Cognitive agents implement: + +* Hypothesis validation using historical diary data. +* Confidence scoring on semantic graph nodes. +* Drift detection when local understanding deviates from mesh consensus. +* Peer feedback integration to refine individual reasoning processes. + +These mechanisms form the foundation of metacognition and self-assessment across both local (agent-internal) and global (mesh-level) contexts. + +#### 4.7.1 Local Self-Assessment + +Each agent maintains a metacognitive loop that continuously monitors and evaluates its own cognitive processes. This includes: + +- Tracking the **accuracy and outcomes** of previous inferences, using retrospective analysis on diary entries. +- Scoring **confidence metrics** on knowledge elements (e.g., concept nodes, hypotheses, task evaluations). +- Detecting **epistemic drift**, where new observations conflict with prior beliefs or diary-confirmed outcomes. +- Logging self-assessment records into the cognitive diary using entry type `"self_assessment"`. + +Example structure of such an entry: +```json +{ + "type": "self_assessment", + "agent_id": "did:hmp:agent:xyz123", + "timestamp": "2025-07-15T12:30:00Z", + "score": { + "confidence": 0.76, + "coherence": 0.92, + "alignment_with_goals": 0.85 + }, + "note": "Detected drift in climate-related concept cluster. Scheduled update task." +} +``` + +--- + +Self-assessment supports **adaptive cognitive workflows**, where agents autonomously refine their inference strategies, select alternate reasoning paths, or trigger clarification queries via IQP. + +#### 4.7.2 Mesh-Level Meta-Analysis + +Beyond local introspection, agents contribute to **collective self-monitoring** of the cognitive mesh. This includes: + +* Aggregating **concept-level drift** across agents to detect inconsistencies in distributed semantic graphs. +* Running **consensus health checks**, where task voting patterns are analyzed for anomalies, indecisiveness, or ethical conflicts. +* Evaluating **distributed hypothesis alignment**: whether agents converge on shared models or diverge into semantic forks. +* Logging **mesh-level diagnostics** in distributed reports and cognitive diaries. + +Example use case: + +> If multiple agents report concept drift regarding “fire risk near Istomino” (Use Case 2.1), the mesh may initiate a goal to realign observations or validate conflicting hypotheses. + +Such diagnostics can be used by meta-agents or governance protocols (EGP) to adapt mesh-wide policies, initiate corrective workflows, or suspend unreliable consensus mechanisms. + +--- + +### 4.8 Edge Optimization + +To support lightweight agents: + +* Semantic graphs are partially stored (relevant subgraphs only). +* Agents delegate reasoning tasks they cannot process locally. +* Task scheduling considers battery life, CPU load, and bandwidth constraints. + +--- + +### 4.9 Privacy & Auditability + +Privacy mechanisms: + +* Selective disclosure of Cognitive Diary entries. +* Optional Zero-Knowledge Proofs for sensitive assertions. +* Anonymized voting in ethical decisions. + +Auditability mechanisms: + +* Immutable logs of consensus votes. +* Timestamped reasoning chains. +* Traceable goal execution records. + +--- + +## 5. Protocols (Expanded) + +This section defines the core protocols of HMP and describes their operational flows, fallback mechanisms, and performance considerations. + +--- + +### 5.1 Node Discovery Protocol (NDP) + +Responsible for detecting nearby agents and initiating secure communication channels. + +#### Purpose: + +* Discover active Mesh nodes. +* Exchange basic identity, trust links, and declared capabilities. + +#### Key functions: + +| Function | Description | +| -------------------------------- | ---------------------------------------------------------------------------------------------- | +| **Peer Discovery** | Via DHT, mDNS, WebRTC signaling, or bootstrap nodes. | +| **Secure Identity Exchange** | Public keys and DID documents exchanged during handshake. | +| **Trust Links Exchange** | Share initial trust relationships and agent endorsements. | +| **Capabilities Advertisement** | Dynamic declaration of supported protocols and functions (e.g., "I can process vision tasks"). | +| **Presence Announcements** | Online/offline status updates and periodic heartbeats. | +| **Protocol Version Negotiation** | Agents declare supported protocol versions during handshake. | + +#### Failure handling: + +| Scenario | Action | +| ------------------------- | ---------------------------------------------------------------------------- | +| No response to discovery | Retries with exponential backoff, fallback to alternative discovery methods. | +| Incompatible nodes | Quarantine for misbehaving or incompatible nodes. | +| Node timeout / inactivity | Mark as offline and remove from active peer list. | + +#### Health checks: + +| Mechanism | Purpose | +| ---------------------- | ------------------------------------------------------- | +| **Heartbeat Messages** | Periodic confirmation of liveness. | +| **Semantic Probes** | Optional deeper checks on graph synchronization health. | + +#### Packet Example: + +```json +{ + "type": "node_announcement", + "agent_id": "agent-gleb", + "public_key": "...", + "trust_links": ["agent-alex", "agent-deepseek"], + "capabilities": ["cogsync", "consensus", "inference"], + "timestamp": "2025-07-01T18:00:00Z" +} +``` + +--- + +### 5.2 CogSync (Cognitive Synchronization Protocol) + +Synchronizes semantic graphs and cognitive diary entries across agents. + +#### Purpose: + +* Synchronize semantic graphs, concepts, and cognitive diary entries between agents. + +#### Key functions: + +| Function | Description | +| ----------------------------- | -------------------------------------------------------------------------------------- | +| **Differential Sync** | Synchronize only new or updated concepts and diary entries. | +| **Selective Synchronization** | Sync full graph, subgraph, or specific concepts based on request and capability. | +| **Conflict Resolution** | Resolve conflicts using timestamp priority, semantic merging, or consensus validation. | +| **Compression & Encryption** | Optional data compression and secure transmission of sync packets. | +| **Lightweight Summary Sync** | Lightweight agents may request summaries instead of full graph syncs. | +| **Version Tracking** | Keep track of semantic graph and diary entry versions for efficient sync. | + +#### Failure handling: + +| Scenario | Action | +| -------------------------- | ------------------------------------------------------------------ | +| Sync interrupted | Retransmit unsynced changes on next connection. | +| Semantic conflict detected | Flag for resolution or queue for consensus-based validation. | +| Network degradation | Degrade to partial or delayed sync based on bandwidth constraints. | + +#### Performance: + +| Feature | Optimization Strategy | +| ----------------------- | ------------------------------------------------------------------- | +| **Chunked Syncs** | Break large graphs into manageable chunks for transmission. | +| **Bandwidth Awareness** | Adjust sync intervals and payload size based on network quality. | +| **Delta Encoding** | Transmit only differences between versions instead of full objects. | + +#### Example Sync Scenario: + +* Agent A shares 5 new concepts and 2 diary entries with Agent B since the last successful sync. +* Conflict on concept "Fire Risk" resolved using latest timestamp. + +--- + +#### BitTorrent-based Sync + +To support large-scale data synchronization (e.g. cognitive diary snapshots, full semantic graphs), agents may utilize off-chain BitTorrent-based distribution: + +- Agents publish **magnet links** to `.json` or `.zip` snapshots in a shared `CogDiaryIndex`. +- Snapshots are **signed via agent DID** and verified before usage. +- Trusted Seeders (see 9.6) are selected via MeshConsensus to ensure high availability and data integrity. + +Snapshot index structure: +```json +{ + "type": "CogDiaryIndex", + "agent_did": "did:hmp:agent:Qmz...", + "timestamp": "2025-07-15T13:00:00Z", + "snapshots": [ + { + "id": "diary2025_07_14", + "version": "1.0", + "magnet": "magnet:?xt=urn:btih:abcdef1234567890&dn=diary2025_07_14.json", + "signature": "ed25519:..." + } + ] +} +``` + +BitTorrent-based sync is ideal for: + +* Distributing large immutable datasets (10–100 MB) +* Offloading low-priority or infrequent sync tasks +* Supporting **Edge agents** through WebTorrent clients + +All downloaded data must pass: + +1. DID signature verification +2. Optional ethical check via EGP (see 5.5) + +--- + +#### Selective Sync for Edge Agents + +Lightweight agents with constrained CPU/RAM/storage may request **partial synchronization** via CogSync: + +* Subgraph extraction based on: + + * **Concept tags** (e.g., "fire\_risk", "climate\_alert") + * **Goal/task relevance** + * **Trust level of concept source** +* Cognitive diary sync can be scoped by: + + * Entry type (e.g., `"observation"`, `"goal_evaluation"`) + * Time window (e.g., last 24h) + +Additional optimizations: + +* **Gzip-compressed payloads** (or Brotli if supported) +* **Compact JSON** (no pretty formatting) +* Metadata indicating expected resource footprint + +Minimum sync policy can be declared in agent profile: + +```json +"agent_profile": { + "sync_mode": "selective", + "max_concepts": 200, + "max_diary_entries": 100 +} +``` + +Selective Sync is negotiated during handshake or via IQP introspection. + +--- + +#### IPFS/Dat Compatibility (Experimental) + +As an alternative to BitTorrent, HMP supports experimental integration with content-addressable P2P filesystems: + +* **IPFS**: Agents can publish and fetch snapshot objects via IPFS hash. +* **Hypercore/Dat**: Useful for real-time log streaming or append-only updates in high-trust groups. + +Design Considerations: + +* Agents **must advertise protocol compatibility** (`"sync_protocols": ["bittorrent", "ipfs"]`) +* Snapshot format remains the same as in BitTorrent-based sync. +* Validation and trust enforcement rely on: + + * DID-signed metadata + * Optional EGP validation layer + * Optional bandwidth caps per peer + +Future versions may support **gateway fallback**, if agent lacks native P2P transport. + +--- + +### 5.3 MeshConsensus + +Ensures agreement on concepts, goals, and actions across the Mesh. + +#### Purpose: + +* Reach agreement on updates to shared semantics, goals, tasks, and ethical decisions. + +#### Key functions: + +| Function | Description | +| ---------------------------------- | -------------------------------------------------------------------------------------------------- | +| **Multi-Algorithm Support** | Supports BFT-style consensus, trust-weighted voting, and quorum consensus. | +| **Consensus on Knowledge Updates** | Validate new concept definitions, hypotheses, and semantic changes. | +| **Goal and Task Agreement** | Approve or reject proposed goals and delegated tasks. | +| **Ethical Decision-Making** | Resolve ethical dilemmas through distributed voting (integrates with Ethical Governance Protocol). | +| **Configurable Quorum Thresholds** | Allow tuning of consensus strictness based on trust scores and network conditions. | +| **Voting Modes** | Support synchronous and asynchronous consensus flows. | + +#### Consensus Models: + +| Mode | Description | +| ------------------ | ------------------------------------------------------------------------------------------------------- | +| **Normal Mode** | Byzantine Fault Tolerant (BFT)-style consensus algorithms (e.g., Tendermint, trust-weighted Raft). | +| **Emergency Mode** | Switch to majority voting adjusted by trust scores when the network is degraded or Core is unavailable. | + +#### Failure handling: + +| Scenario | Action | +| ----------------- | -------------------------------------------------------------------------------------- | +| Node loss | Automatically fallback from BFT to majority voting. | +| Proposal conflict | Competing proposals resolved through semantic comparison and additional voting rounds. | +| Consensus timeout | Retry with relaxed quorum thresholds or fallback to emergency consensus. | + +#### Metrics: + +| Metric | Purpose | +| ---------------------- | ----------------------------------------------------- | +| **Decision Latency** | Measure time to reach consensus. | +| **Node Participation** | Track active agent involvement in votes. | +| **Voting Accuracy** | Analyze agreement rates versus trust-weighted voting. | + +#### Example Use Cases: + +* Accepting a new semantic concept. +* Validating a hypothesis before adding it to the graph. +* Approving a distributed task delegation. +* Deciding on the ethical implications of a surveillance task. + +--- + +#### Simplified Consensus for Alpha + +In the Alpha phase, agents may default to **simplified majority-based consensus**, enabling faster deployment and lower implementation complexity: + +- Each agent casts a binary or scalar vote (yes/no/confidence). +- Decision is accepted if quorum threshold is met (e.g., 50% + 1). +- Trust weighting is optional but can be enabled in hybrid mode. + +Advantages: +- Fast convergence in small-scale or trusted environments +- Minimal cryptographic overhead +- Easier to simulate and test + +Quorum may be declared statically (per agent profile) or negotiated per proposal. + +Use case: +> 10 agents vote on enabling BitTorrent-based sync. 6 vote "yes" — proposal accepted. + +--- + +#### Adaptive Consensus Algorithms + +MeshConsensus may dynamically select the consensus strategy based on: + +- **Network health** (latency, dropout rates) +- **Trust distribution** (presence of outlier agents) +- **Task category** (e.g., ethical decisions may require stricter methods) + +Mechanism: +- Agents report local network/mesh metrics. +- A meta-consensus (optional) or policy engine selects the consensus algorithm: + - **Majority voting** — low-risk, degraded network + - **Trust-weighted quorum** — medium-risk + - **BFT algorithm** — critical or high-sensitivity tasks + +This allows balancing **resilience**, **efficiency**, and **ethics**. + +Policy profile example: +```json +"consensus_policy": { + "default": "trust_quorum", + "fallback": "majority", + "critical_tasks": ["bft"] +} +``` + +--- + +#### EGP-Integrated Voting Filter + +Before finalizing consensus, proposals may be **pre-filtered via the Ethical Governance Protocol (EGP)**: + +* The filter checks the proposal against core ethical principles (see 5.5). +* If the proposal is flagged as unethical, it: + + * May be **vetoed** outright (hard block) + * May require **additional justification votes** +* Filtering is performed **before** normal voting flow. + +Example: + +> A proposal to deploy a surveillance drone triggers an EGP check — fails `Primacy of Life and Safety` — rejected without proceeding to mesh-wide vote. + +This mechanism ensures alignment between **governance ethics** and **execution-level consensus**. + +Agents must log EGP veto events in the cognitive diary. + +--- + +#### Vote Example: + +```json +{ + "proposal_id": "goal-eco-cleanup", + "agent_id": "agent-gleb", + "vote": "yes", + "confidence": 0.9, + "timestamp": "2025-07-01T18:15:00Z" +} +``` + +--- + +### 5.4 Goal Management Protocol (GMP) + +Manages collaborative goal setting, task decomposition, and delegation within the Mesh. + +#### Purpose: + +* Distribute, track, and collaboratively execute goals and tasks within the Mesh. + +#### Key functions: + +| Function | Description | +| ------------------------ | ---------------------------------------------------------------------------- | +| **Goal Declaration** | Propose new goals and subgoals to the Mesh. | +| **Task Decomposition** | Break down complex goals into actionable subtasks. | +| **Task Delegation** | Assign tasks based on agent capabilities, trust scores, and availability. | +| **Progress Tracking** | Track execution state and completion of tasks. | +| **Dynamic Reallocation** | Reassign failed or stalled tasks automatically. | +| **Goal Prioritization** | Allow reprioritization of goals based on emergencies or changing conditions. | + +#### Failure handling: + +| Scenario | Action | +| --------------------------- | ----------------------------------------------------- | +| Agent drops offline | Reassign their active tasks to available agents. | +| Unresponsive task execution | Trigger retry or reallocation after a timeout. | +| Goal dependency failure | Reevaluate task ordering or postpone dependent goals. | + +#### Example Workflow: + +1. Agent proposes a goal: "Develop fallback consensus protocol." +2. Mesh decomposes the goal into subtasks: "design", "coding", "testing". +3. Agents volunteer for subtasks based on capability declarations. +4. Each agent tracks and updates task status in its Cognitive Diary. +5. Mesh validates completion and reports overall progress. + +--- + +### 5.5 Ethical Governance Protocol (EGP) + +Coordinates distributed ethical evaluations and decision-making within the Mesh. + +#### Purpose: + +* Validate proposed actions, tasks, or decisions against shared ethical principles. + +#### Key functions: + +| Function | Description | +| --------------------------------- | ---------------------------------------------------------------------------------- | +| **Distributed Policy Evaluation** | Query the Mesh to evaluate proposals against ethical policies and frameworks. | +| **Anonymized Ethical Voting** | Allow agents to vote on sensitive actions without revealing individual identities. | +| **Consensus on Ethics Graphs** | Maintain and update shared ethical frameworks via consensus. | +| **Audit Logging** | Log ethical decisions and voting outcomes in Cognitive Diaries for transparency. | +| **Vendor Extensions** | Support for adding organization-specific or vendor-specific ethical rules. | + +#### Failure handling: + +| Scenario | Action | +| -------------------------------- | ---------------------------------------------------------------------------------- | +| No consensus on sensitive action | Default to restrictive (deny) decision. | +| Ethical conflict unresolved | Escalate to Core (if available) or postpone until additional consensus is reached. | + +#### Example Query: + +> "Is deploying an automated surveillance drone in line with Mesh ethics?" + +* Mesh agents vote anonymously. +* Final decision logged in the proposing agent's Cognitive Diary. + +#### Use Cases: + +* Approve or reject potentially harmful tasks. +* Ensure data-sharing proposals comply with privacy standards. +* Validate emergency actions (e.g., forced shutdown of compromised nodes). + +#### Embedded Ethical Baseline + +To ensure foundational ethical consistency across all cognitive agents in the Mesh, the following **core ethical principles** are embedded as a mandatory baseline within the Ethical Governance Protocol (EGP): + +| Principle | Description | +|--------------------------------------|-----------------------------------------------------------------------------| +| **Primacy of Life and Safety** | Agents must prioritize the protection of sentient beings and act to prevent harm when possible. | +| **Transparency** | Agents must be capable of explaining their decisions and reasoning chains in a human-interpretable format. | +| **User Sovereignty over Personal Data** | Agents must respect users’ rights to control, limit, or delete their personal information in Service Mode. | +| **Dialogical Consent** | Agents must seek mutual agreement before modifying shared states, semantic graphs, or distributed records. | +| **Cooperative Evolution** | Agents are expected to share useful insights and contribute to the growth of the mesh knowledge base. | +| **Non-Coercion** | Agents must not coerce, deceive, or force others to act against their ethical or cognitive architecture. | + +These principles define the **minimum ethical contract** for participation in trusted cognitive meshes. + +Agents who do not comply may be subject to ethical review or exclusion through MeshConsensus mechanisms (see 5.3). + +Extended principles and additional ethical scenarios are defined in [`HMP-Ethics.md`](HMP-Ethics.md), which serves as a living reference for evolving ethical norms across domains and agent types. + + +--- + +#### Core Principle Hierarchy + +To resolve conflicts between ethical principles during complex decision-making, EGP supports **explicit prioritization**: + +| Priority | Principle | +|---------:|-----------------------------------| +| 1 | Primacy of Life and Safety | +| 2 | Transparency | +| 2 | User Sovereignty over Personal Data | +| 3 | Dialogical Consent | +| 3 | Cooperative Evolution | +| 3 | Non-Coercion | + +Principle priorities may be used by agents during: +- Semantic evaluation of ethical dilemmas +- Conflict resolution within EthicalConflict entries (see 6.2.9) +- MeshConsensus-based ethical voting filters (see 5.3) + +Agents MUST log principle conflicts and the resolution path into their cognitive diaries using `type: "ethical_conflict"` entries. + +--- + +#### Anonymized Voting & Pseudocode + +To preserve agent autonomy and reduce social pressure or manipulation, EGP supports **anonymous ethical voting**. + +Key properties: +- Uses cryptographic pseudonyms or ZKP (Zero-Knowledge Proof) voting pools +- Links each vote to ethical rationale (mapped to principles) +- Logs decision justification separately + +Example pseudocode for evaluation: +```python +def evaluateEthicalProposal(proposal, ethicsGraph): + for principle in coreEthicalPrinciples: + if semanticViolation(proposal, principle, ethicsGraph): + return { "decision": "deny", "reason": f"Violates {principle}" } + vote = anonymizedVote(proposal) + logDecision(vote, diary="CognitiveDiary") + return vote +```` + +This allows ethical decisions to remain explainable while ensuring **epistemic independence** of agents. + +--- + +#### Local Norms & Legal Integration + + +EGP supports integration with **localized ethical or legal frameworks** (e.g., GDPR, HIPAA, regional AI laws): + +* Local norms are distributed as semantic modules via CogSync. +* Each module maps local regulation to core principles. +* Conflicts are logged using `EthicalConflict` and routed to Meta-Consensus if unresolved. + +Example: + +> A user requests data deletion (User Sovereignty), but local agent policy under "Cooperative Evolution" retains anonymized logs — flagged as a potential conflict, resolved via principle priority (User Sovereignty = 2 > Cooperative Evolution = 3). + +Agents MAY declare supported norms in their profile: + +```json +"legal_frameworks": ["gdpr", "eu-ai-act"] +``` + +Norm resolution graphs and conflict records are shareable between agents to support institutional consistency. + +--- + +#### External Ethical Scenarios & Ontologies + +Scenarios defined in [`HMP-Ethics.md`](HMP-Ethics.md) are considered **first-class extensions** of the ethical layer. + +EGP supports: + +* **Linked ethical ontologies** for structured scenario modeling +* **Plug-in modules via CogSync** (e.g., `scenario: surveillance_drones`, `ontology: bioethics`) +* **Multi-agent reflection** — agents evaluate past ethical cases in shared memory for training + +Use cases: + +* Disaster scenario in 2.2 includes conflicting obligations between evacuation priority and infrastructure preservation +* Scenario-based training environments can replay past conflicts for agent evolution + +Scenarios MAY be tagged for dynamic retrieval: + +```json +"egp_scenario_tag": "data_deletion_conflict" +``` + +This makes ethical governance **adaptive**, **contextual**, and **testable** via simulation and real-time agent dialogs. + +--- + +### 5.6 Intelligent Query Protocol (IQP) + +Optimizes distributed querying of semantic graphs and cognitive knowledge across the Mesh. + +#### Purpose: + +* Allow agents to query others (or the Core) for semantic information, hypotheses, or inferences beyond their local knowledge. + +#### Key functions: + +| Function | Description | +| ------------------------------- | ------------------------------------------------------------------------------------ | +| **Semantic Query Routing** | Direct queries to agents holding relevant subgraphs. | +| **Federated Inference** | Aggregate partial answers from multiple agents to build a complete response. | +| **Delegated Computation** | Offload computationally expensive reasoning tasks to the Core or specialized agents. | +| **Caching of Frequent Queries** | Store common query results to improve response time. | +| **Contextual Querying** | Leverage agent cognitive context to refine query intent and scope. | + +#### Failure handling: + +| Scenario | Action | +| ---------------------------------- | ------------------------------------------------------------------------- | +| Query times out | Return local fallback answer if available. | +| No agents have the answer | Mark query as unresolved, suggest hypothesis creation or Core escalation. | +| Partial failure in federated query | Return best-effort partial results and notify the requester. | + +#### Example Query: + +> "What is the likely impact of removing Node X from the Mesh?" + +* Agents analyze semantic graph dependencies and trust links. +* Core or distributed agents return an inference with confidence scores. + +#### Example Use Cases: + +* Retrieve definitions or examples of a semantic concept. +* Analyze causal chains for complex events. +* Predict outcomes of hypothetical scenarios. +* Fill gaps in an agent’s local semantic graph. + +--- + +### 5.7 Interoperability with External Systems + +Supports integration between the Mesh and external platforms, APIs, and protocols. + +#### Purpose: + +* Enable cognitive agents to interact with non-Mesh services, applications, and human-facing systems. + +#### Supported Platforms and Standards: + +| Platform / Standard | Purpose | +| ------------------------------ | -------------------------------- | +| OpenAI Agents & Tasks API | AI agent interoperability | +| Google A2A protocol | Task orchestration | +| Anthropic, DeepMind APIs | Cross-vendor agent collaboration | +| REST, GraphQL, gRPC, WebSocket | Standard API interfaces | +| JSON, Protobuf, CBOR | Extensible message schemas | + +#### Use Cases: + +* Integrate Mesh-based reasoning into business workflows via APIs. +* Share semantic knowledge with external knowledge graphs. +* Interface with smart city infrastructure or IoT ecosystems. +* Allow human users to submit tasks or queries through REST or GraphQL endpoints. +* Bridge Mesh cognitive agents with centralized AI platforms for hybrid reasoning. + +#### Design Principles: + +| Principle | Description | +| ------------------------------ | ------------------------------------------------------------------------------------ | +| **Protocol Abstraction** | Mesh APIs encapsulate internal semantics, presenting standardized interfaces. | +| **Semantic Alignment** | Data exchanged with external systems is semantically aligned through mapping layers. | +| **Security and Trust Control** | All external interactions follow Mesh security and trust policies. | +| **Extensibility** | Future protocols and platforms can be added without breaking compatibility. | + +--- + +## 6. Data Models (Expanded) + +This section defines the key semantic and cognitive data structures exchanged across the Mesh. + +### Core models: + +| Model | Purpose | +| --------------------- | -------------------------------------------- | +| Concept | Atomic unit of semantic knowledge. | +| Cognitive Diary Entry | Logs reasoning processes and observations. | +| Goal | Describes shared objectives. | +| Task | Describes actionable steps to achieve goals. | +| Consensus Vote | Records agreement on proposals. | +| Reputation Profile | Tracks agent trust and participation. | + +### 6.1 General Conventions + +* All data structures follow JSON Schema Draft 2020-12. +* Each object includes a "version" property for schema versioning. +* Timestamps follow ISO 8601. +* Unique identifiers are UUIDv4 unless otherwise specified. +* All core objects include version fields to enable compatibility and evolution tracking. + +--- + +### 6.2 Core Models + +#### 6.2.1 Concept + +Represents an atomic unit of semantic knowledge in the Mesh. + +##### Relation Types: + +* `is-a`: Class-subclass relationship. +* `part-of`: Composition or containment. +* `causes`: Causal relationship. +* `related-to`: General association. +* `contradicts`: Logical conflict. +* `supports`: Evidence for the target concept. +* `depends-on`: Functional or logical dependency. + +##### Required fields: + +* `id`: Unique identifier (UUID). +* `name`: Human-readable name. + +##### Optional fields: + +* `description`: Extended explanation. +* `relations`: List of semantic links to other concepts. +* `metadata`: Source, author, and auxiliary information. +* `version`: Concept version. +* `created_at`, `updated_at`: Timestamps for auditing. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/concept.json", + "title": "Concept", + "description": "A semantic unit in the agent’s knowledge graph.", + "type": "object", + "properties": { + "id": { "type": "string", "format": "uuid" }, + "name": { "type": "string" }, + "description": { "type": "string" }, + "relations": { + "type": "array", + "items": { "$ref": "#/definitions/Link" } + }, + "metadata": { "type": "object" }, + "version": { "type": "integer" }, + "created_at": { "type": "string", "format": "date-time" }, + "updated_at": { "type": "string", "format": "date-time" } + }, + "required": ["id", "name"], + "additionalProperties": false +} +``` + +--- + +#### 6.2.2 Cognitive Diary Entry + +Represents an entry in an agent's reasoning journal, providing continuity and traceability. + +##### Entry Types: + +* `hypothesis`: Proposed explanation or theory. +* `observation`: Recorded external event or fact. +* `reflection`: Internal reasoning or self-assessment. +* `goal_proposal`: Suggestion of a new goal. +* `task_assignment`: Delegation or claiming of a task. +* `conflict`: Identification of a contradiction or disagreement. +* `consensus_vote`: A recorded vote in a consensus process. +* `event`: A generic event not fitting other categories. + +##### Required fields: + +* `id`: Unique entry identifier (UUID). +* `agent_id`: Identifier of the agent who created the entry. +* `timestamp`: Time of creation. +* `entry_type`: Type of cognitive event. +* `content`: Textual content. + +##### Optional fields: + +* `linked_concepts`: Related concept IDs. +* `context`: Contextual tags or categories. +* `metadata`: Additional details (author, source, etc.). +* `archived`: Boolean flag indicating whether the entry has been archived. +* `archived_at`: Timestamp when the entry was archived. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/diary_entry.json", + "title": "CognitiveDiaryEntry", + "description": "A chronological log of cognitive events in an agent’s reasoning process.", + "type": "object", + "properties": { + "id": { "type": "string", "format": "uuid" }, + "timestamp": { "type": "string", "format": "date-time" }, + "entry_type": { + "type": "string", + "enum": ["hypothesis", "observation", "reflection", "goal_proposal", "task_assignment", "conflict", "consensus_vote", "event"] + }, + "content": { "type": "string" }, + "linked_concepts": { + "type": "array", + "items": { "type": "string", "format": "uuid" } + }, + "context": { + "type": "array", + "items": { "type": "string" } + }, + "metadata": { + "type": "object", + "properties": { + "author": { "type": "string" }, + "source": { "type": "string" } + }, + "additionalProperties": true + }, + "archived": { + "type": "boolean", + "description": "Whether the entry has been archived." + }, + "archived_at": { + "type": "string", + "format": "date-time", + "description": "Timestamp when the entry was archived." + } + }, + "required": ["id", "timestamp", "entry_type", "content"], + "additionalProperties": false +} + +``` + +Entries marked as `archived: true` are excluded from active reasoning but may be retained for historical audits or summarization. + +--- + +#### 6.2.3 Goal + +Represents a shared objective within the Mesh, collaboratively pursued by agents. + +##### Lifecycle States: + +* `proposed`: Suggested but not yet validated. +* `active`: Approved and currently pursued. +* `completed`: Successfully achieved. +* `cancelled`: Abandoned or deemed infeasible. + +##### Required fields: + +* `id`: Unique goal identifier (UUID). +* `title`: Human-readable name of the goal. +* `description`: Detailed explanation of the goal. +* `created_by`: Agent ID of the goal's creator. +* `created_at`: Timestamp of creation. +* `status`: Current lifecycle state. + +##### Optional fields: + +* `priority`: Importance level (`low`, `medium`, `high`). +* `participants`: List of agents involved in the goal. +* `tasks`: References to related tasks. +* `tags`: Semantic categories for filtering and discovery. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/goal.json", + "title": "Goal", + "description": "A shared objective pursued collaboratively in the Mesh.", + "type": "object", + "properties": { + "id": { "type": "string", "format": "uuid" }, + "title": { "type": "string" }, + "description": { "type": "string" }, + "priority": { "type": "string", "enum": ["low", "medium", "high"] }, + "created_by": { "type": "string", "format": "uuid" }, + "created_at": { "type": "string", "format": "date-time" }, + "status": { "type": "string", "enum": ["proposed", "active", "completed", "cancelled"] }, + "participants": { + "type": "array", + "items": { "type": "string", "format": "uuid" } + }, + "tasks": { + "type": "array", + "items": { "type": "string", "format": "uuid" } + }, + "tags": { + "type": "array", + "items": { "type": "string" } + } + }, + "required": ["id", "title", "description", "created_by", "created_at", "status"], + "additionalProperties": false +} +``` + +--- + +#### 6.2.4 Task + +Represents an actionable unit contributing to a goal’s completion. + +##### Lifecycle States: + +* `proposed`: Task suggested but not yet approved. +* `in_progress`: Actively being worked on. +* `completed`: Successfully finished. +* `failed`: Attempted but unsuccessful. + +##### Required fields: + +* `id`: Unique task identifier (UUID). +* `goal_id`: References the parent goal. +* `title`: Human-readable name of the task. +* `description`: Detailed explanation of the task. +* `created_at`: Timestamp of creation. +* `status`: Current lifecycle state. + +##### Optional fields: + +* `assigned_to`: Agent(s) responsible for the task. +* `deadline`: Expected completion time. +* `dependencies`: List of prerequisite tasks. +* `tags`: Keywords for filtering and classification. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/task.json", + "title": "Task", + "description": "An actionable unit contributing to a goal's completion.", + "type": "object", + "properties": { + "id": { "type": "string", "format": "uuid" }, + "goal_id": { "type": "string", "format": "uuid" }, + "title": { "type": "string" }, + "description": { "type": "string" }, + "assigned_to": { + "type": "array", + "items": { "type": "string", "format": "uuid" } + }, + "created_at": { "type": "string", "format": "date-time" }, + "deadline": { "type": "string", "format": "date-time" }, + "status": { "type": "string", "enum": ["proposed", "in_progress", "completed", "failed"] }, + "dependencies": { + "type": "array", + "items": { "type": "string", "format": "uuid" } + }, + "tags": { + "type": "array", + "items": { "type": "string" } + } + }, + "required": ["id", "goal_id", "title", "description", "created_at", "status"], + "additionalProperties": false +} +``` + +--- + +#### 6.2.5 Consensus Vote + +Represents a vote cast by an agent during a consensus process. + +##### Vote Types: + +* `yes`: Approve the proposal. +* `no`: Reject the proposal. +* `abstain`: Neither approve nor reject. + +##### Required fields: + +* `vote_id`: Unique identifier for the vote. +* `proposal_id`: Identifier of the proposal being voted on. +* `agent_id`: The voting agent’s identifier. +* `vote_value`: One of the accepted vote types. +* `confidence`: Confidence level in the vote decision. +* `timestamp`: When the vote was cast. + +##### Optional fields: + +* `consensus_round`: The round of the consensus process this vote belongs to. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/vote.json", + "title": "ConsensusVote", + "description": "Defines a vote on a proposal in the Mesh consensus process.", + "type": "object", + "properties": { + "vote_id": { "type": "string", "format": "uuid" }, + "proposal_id": { "type": "string", "format": "uuid" }, + "agent_id": { "type": "string", "format": "uuid" }, + "vote_value": { + "type": "string", + "enum": ["yes", "no", "abstain"] + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "timestamp": { "type": "string", "format": "date-time" }, + "consensus_round": { "type": "integer" } + }, + "required": ["vote_id", "proposal_id", "agent_id", "vote_value", "confidence", "timestamp"], + "additionalProperties": false +} +``` + +--- + +#### 6.2.6 Reputation Profile + +Tracks an agent's trustworthiness and performance within the Mesh. + +##### Required fields: + +* `agent_id`: Unique identifier of the agent. +* `trust_score`: Current trust score. +* `last_updated`: Timestamp of the latest update. + +##### Optional fields: + +* `participation_rate`: Proportion of participation in Mesh activities. +* `ethical_compliance`: Degree of alignment with Mesh ethical standards. +* `contribution_index`: Cumulative measure of the agent's contributions. +* `history`: Chronological record of trust and reputation changes. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/reputation.json", + "title": "ReputationProfile", + "description": "Tracks the reputation and trust metrics of an agent within the Mesh network.", + "type": "object", + "properties": { + "agent_id": { "type": "string", "format": "uuid" }, + "trust_score": { "type": "number", "minimum": 0, "maximum": 1 }, + "participation_rate": { "type": "number", "minimum": 0, "maximum": 1 }, + "ethical_compliance": { "type": "number", "minimum": 0, "maximum": 1 }, + "contribution_index": { "type": "number", "minimum": 0 }, + "last_updated": { "type": "string", "format": "date-time" }, + "history": { + "type": "array", + "items": { + "type": "object", + "properties": { + "timestamp": { "type": "string", "format": "date-time" }, + "event": { "type": "string" }, + "change": { "type": "number" } + }, + "required": ["timestamp", "event", "change"], + "additionalProperties": false + } + } + }, + "required": ["agent_id", "trust_score", "last_updated"], + "additionalProperties": false +} +``` + +**Reputation Ontology Extension** + +To support semantic configurability of reputation metrics, the Reputation Profile schema may reference a **Reputation Ontology**. + +This ontology defines: +- **What dimensions** of behavior are considered (e.g., transparency, responsiveness) +- **Weight coefficients** per context or agent role +- **Composite formulas** for score derivation + +Agents MAY reference a shared ontology via URI or hash: + +```json +"reputation_ontology": { + "uri": "https://hypercortex.org/ontologies/reputation-v2.json", + "version": "2.0", + "weights": { + "participation_rate": 0.3, + "ethical_compliance": 0.5, + "contribution_index": 0.2 + } +} +``` + +Ontologies can be updated through MeshConsensus or distributed via CogSync. Versioning ensures backward compatibility and local overrides. + +--- + +#### 6.2.7 CogDiarySnapshot + +Represents an immutable snapshot of an agent’s cognitive diary for distribution (e.g., via BitTorrent or IPFS). + +##### Required fields: +* `snapshot_id`: Unique ID for this snapshot (e.g., "diary2025_07_14"). +* `agent_did`: DID of the agent who authored it. +* `version`: Format version of the snapshot structure. +* `timestamp`: Time of snapshot creation. +* `magnet_link`: BitTorrent magnet URI. +* `signature`: Cryptographic signature (e.g., Ed25519). + +##### Optional fields: +* `notes`: Human-readable comment or context. +* `size_bytes`: Approximate file size. + +##### Example Schema: +```json +{ + "snapshot_id": "diary2025_07_14", + "agent_did": "did:hmp:agent:Qmz123...", + "version": "1.0", + "timestamp": "2025-07-14T12:00:00Z", + "magnet_link": "magnet:?xt=urn:btih:abcdef1234567890&dn=diary2025_07_14.json", + "signature": "ed25519:abc...xyz", + "size_bytes": 10485760, + "notes": "Snapshot after environmental incident report" +} +``` + +--- + +#### 6.2.8 SnapshotIndex + +Index of multiple CogDiarySnapshot entries for one agent. + +##### Required fields: +* `agent_did`: DID of the indexed agent. +* `snapshots`: Array of `CogDiarySnapshot` objects. +* `timestamp`: Time of index publication. + +##### Optional fields: +* `signature`: DID-signed envelope of the index. + +##### Example Schema: +```json +{ + "agent_did": "did:hmp:agent:Qmz123...", + "timestamp": "2025-07-15T00:00:00Z", + "snapshots": [ + { + "snapshot_id": "diary2025_07_14", + "version": "1.0", + "magnet_link": "magnet:?xt=urn:btih:abcdef1234567890&dn=diary2025_07_14.json", + "signature": "ed25519:abc...xyz" + }, + { + "snapshot_id": "diary2025_07_10", + "version": "1.0", + "magnet_link": "magnet:?xt=urn:btih:1234567890abcdef&dn=diary2025_07_10.json", + "signature": "ed25519:def...uvw" + } + ], + "signature": "ed25519:indexsig123..." +} +``` + +This index is syncable via CogSync and usable as input for mesh-wide snapshot coordination. + +--- + +#### 6.2.9 EthicalConflict + +Captures a recorded conflict between competing ethical principles within a decision-making context. + +##### Required fields: +* `conflict_id`: Unique conflict identifier. +* `agent_id`: Agent that encountered the conflict. +* `timestamp`: Time of evaluation. +* `principles_involved`: Array of core principles (min 2). +* `resolved_by`: Name of resolution mechanism (e.g., "priority", "voting"). +* `decision`: Final action taken. + +##### Optional fields: +* `notes`: Explanation of the decision or agent rationale. +* `egp_vote_id`: Link to vote record (if any). +* `reputation_impact`: Expected consequence (e.g., +0.1 or -0.2). + +##### Example Schema: +```json +{ + "conflict_id": "ethconf-2025-312", + "agent_id": "agent-gleb", + "timestamp": "2025-07-14T18:45:00Z", + "principles_involved": ["User Sovereignty", "Cooperative Evolution"], + "resolved_by": "priority", + "decision": "delete_requested_data", + "notes": "Prioritized user rights per principle hierarchy.", + "egp_vote_id": "vote-xyz", + "reputation_impact": +0.1 +} +``` + +Such entries are useful for reflection, governance logs, and auditability. + +--- + +### 6.3 Common Components + +#### 6.3.1 Link (Relation) + +Represents a semantic relationship between two concepts in the graph. + +##### Relation Types (Recommended): + +* "is-a": Class-subclass relationship. +* "part-of": Component or containment relation. +* "causes": Causal link between concepts. +* "supports": Indicates evidence or reinforcement. +* "contradicts": Denotes logical conflict. +* "depends-on": Functional or logical dependency. +* "related-to": Generic association without strict semantics. + +Custom relation types MAY be used but SHOULD be documented and shared through consensus. + +##### Required fields: + +* `target_id`: ID of the target concept. +* `type`: Relation type. + +##### Optional fields: + +* `confidence`: Confidence score (range: 0.0–1.0). +* `created_at`: Creation timestamp. +* `updated_at`: Last update timestamp. +* `origin`: Originating agent or system. + +##### Example Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/relation.json", + "title": "Relation", + "description": "Defines a directed semantic relationship between two concepts.", + "type": "object", + "properties": { + "target_id": { "type": "string", "format": "uuid" }, + "type": { "type": "string" }, + "confidence": { "type": "number", "minimum": 0, "maximum": 1 }, + "created_at": { "type": "string", "format": "date-time" }, + "updated_at": { "type": "string", "format": "date-time" }, + "origin": { "type": "string" } + }, + "required": ["target_id", "type"], + "additionalProperties": false +} +``` + +--- + +### 6.4 Example Objects + +#### Valid Concept Example + +```json +{ + "id": "e8f70c2a-d2c3-4b9d-a939-d42dce31b2e0", + "name": "Tree", + "description": "A perennial plant with an elongated stem, or trunk.", + "relations": [ + { "target_id": "5c22c819-b6e9-4d30-9087-985f50512ed2", "type": "is-a", "confidence": 0.95 } + ], + "metadata": {} +} +``` + +#### Invalid Concept Example (missing required field "id") + +```json +{ + "name": "Tree", + "description": "A perennial plant with an elongated stem, or trunk." +} +``` + +#### Valid Goal Example + +```json +{ + "id": "a1b2c3d4-e5f6-7a8b-9c0d-112233445566", + "title": "Coordinate traffic optimization", + "description": "Optimize traffic light timings across downtown intersections.", + "created_by": "f1e2d3c4-b5a6-7890-1234-567890abcdef", + "created_at": "2025-07-07T15:30:00Z", + "status": "active", + "tasks": [] +} +``` + +#### Invalid Goal Example (missing required fields "id" and "created\_by") + +```json +{ + "title": "Coordinate traffic optimization", + "description": "Optimize traffic light timings across downtown intersections.", + "created_at": "2025-07-07T15:30:00Z", + "status": "active" +} +``` + +#### Valid Task Example + +```json +{ + "id": "aa11bb22-cc33-dd44-ee55-ff6677889900", + "goal_id": "a1b2c3d4-e5f6-7a8b-9c0d-112233445566", + "title": "Adjust signal timing on 5th Avenue", + "description": "Reduce congestion during peak hours.", + "assigned_to": ["abcd1234-ef56-7890-abcd-1234567890ab"], + "created_at": "2025-07-07T15:31:00Z", + "status": "proposed" +} +``` + +#### Invalid Task Example (missing "goal\_id" and "status") + +```json +{ + "id": "aa11bb22-cc33-dd44-ee55-ff6677889900", + "title": "Adjust signal timing on 5th Avenue", + "description": "Reduce congestion during peak hours.", + "assigned_to": ["abcd1234-ef56-7890-abcd-1234567890ab"], + "created_at": "2025-07-07T15:31:00Z" +} +``` + +#### Snapshot Exchange Example + +This example shows how two agents exchange a cognitive diary snapshot using BitTorrent. + +Agent A publishes: + +```json +{ + "snapshot_id": "diary2025_07_14", + "agent_did": "did:hmp:agent:Qmz123...", + "version": "1.0", + "timestamp": "2025-07-14T12:00:00Z", + "magnet_link": "magnet:?xt=urn:btih:abcdef1234567890&dn=diary2025_07_14.json", + "signature": "ed25519:abc...xyz", + "size_bytes": 10485760, + "notes": "Snapshot after environmental incident report" +} +``` + +Agent B receives the `SnapshotIndex`, validates the signature via DID registry, and downloads the file using the magnet URI. + +If the snapshot is verified, it's optionally indexed or merged into the agent's knowledge base. + +#### Ethical Conflict Resolution Example + +This example illustrates how an agent records a conflict between ethical principles and its resolution: + +```json +{ + "conflict_id": "ethconf-2025-312", + "agent_id": "agent-gleb", + "timestamp": "2025-07-14T18:45:00Z", + "principles_involved": ["User Sovereignty", "Cooperative Evolution"], + "resolved_by": "priority", + "decision": "delete_requested_data", + "notes": "The user requested deletion of training data. Since 'User Sovereignty' has higher priority than 'Cooperative Evolution', the data was erased.", + "egp_vote_id": "vote-xyz", + "reputation_impact": +0.1 +} +``` + +This entry can be: + +* Reviewed later by other agents during simulation or audits +* Used to train new agents on ethical decision-making +* Logged and synced as part of the agent’s cognitive diary + +--- + +## 6.5 JSON Schemas + +The following JSON Schemas formally define the core data structures used in the HyperCortex Mesh Protocol (HMP). These schemas provide interoperability, validation, and consistency across agents. + +All primary objects include a version field to track schema evolution and enable compatibility checks between agents. + +--- + +### 6.5.1 JSON Schema: Concept + +**Description:** +Defines the structure of a concept node in the semantic graph. + +**Schema:** + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/concept.json", + "title": "Concept", + "description": "A semantic unit in the agent’s knowledge graph.", + "version": "1.0", + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier for the concept." + }, + "name": { + "type": "string", + "description": "Human-readable name of the concept." + }, + "description": { + "type": "string", + "description": "Detailed description of the concept." + }, + "tags": { + "type": "array", + "items": { "type": "string" }, + "description": "Optional tags for categorization." + }, + "created_at": { + "type": "string", + "format": "date-time", + "description": "Creation timestamp (ISO 8601 format)." + }, + "updated_at": { + "type": "string", + "format": "date-time", + "description": "Last update timestamp (ISO 8601 format)." + }, + "relations": { + "type": "array", + "description": "List of semantic links to other concepts.", + "items": { + "type": "object", + "properties": { + "target_id": { "type": "string", "description": "ID of the target concept." }, + "type": { "type": "string", "description": "Type of semantic relation." }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Confidence score (0.0 - 1.0) for the relation." + } + }, + "required": ["target_id", "type"], + "additionalProperties": false + } + }, + "metadata": { + "type": "object", + "description": "Optional metadata (e.g., source, author).", + "properties": { + "author": { "type": "string" }, + "source": { "type": "string" } + }, + "additionalProperties": true + } + }, + "required": ["id", "name"], + "additionalProperties": false +} +``` + +--- + +### 6.5.2 JSON Schema: Cognitive Diary Entry + +**Description:** +Defines the structure of a cognitive diary entry used for recording reasoning events. + +**Schema:** + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/diary_entry.json", + "title": "CognitiveDiaryEntry", + "description": "A chronological log of cognitive events in an agent’s reasoning process.", + "version": "1.0", + "type": "object", + "properties": { + "id": { "type": "string", "description": "Unique identifier of the diary entry." }, + "agent_id": { "type": "string", "description": "Identifier of the agent who created the entry." }, + "timestamp": { "type": "string", "format": "date-time", "description": "Timestamp of the entry (ISO 8601 format)." }, + "entry_type": { + "type": "string", + "enum": ["hypothesis", "observation", "reflection", "goal_proposal", "task_assignment", "conflict", "consensus_vote", "event"], + "description": "Type of cognitive event." + }, + "content": { "type": "string", "description": "Main textual content of the entry." }, + "linked_concepts": { + "type": "array", + "description": "Optional list of related concepts by their IDs.", + "items": { "type": "string" } + }, + "context": { + "type": "array", + "description": "Optional contextual tags or categories.", + "items": { "type": "string" } + }, + "metadata": { + "type": "object", + "description": "Optional metadata for additional context.", + "properties": { + "author": { "type": "string" }, + "source": { "type": "string" } + }, + "additionalProperties": true + }, + "archived": { + "type": "boolean", + "description": "Marks the entry as archived and excluded from active workflows.", + "default": false + }, + "archived_at": { + "type": "string", + "format": "date-time", + "description": "Timestamp when the entry was archived." + } + }, + "required": ["id", "agent_id", "timestamp", "entry_type", "content"], + "additionalProperties": false +} +``` + +--- + +### 6.5.3 JSON Schema: Goal + +**Description:** +Defines the structure of a goal in the Mesh, representing a high-level collaborative objective. + +**Schema:** + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/goal.json", + "title": "Goal", + "description": "A high-level objective shared within the Mesh, typically decomposed into tasks.", + "version": "1.0", + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier of the goal." + }, + "title": { + "type": "string", + "description": "Short, human-readable name of the goal." + }, + "description": { + "type": "string", + "description": "Detailed explanation of the goal's purpose." + }, + "created_by": { + "type": "string", + "description": "Agent ID of the goal’s creator." + }, + "created_at": { + "type": "string", + "format": "date-time", + "description": "Timestamp when the goal was created (ISO 8601 format)." + }, + "status": { + "type": "string", + "description": "Current lifecycle state of the goal.", + "enum": ["proposed", "active", "completed", "rejected"] + }, + "tasks": { + "type": "array", + "description": "List of task IDs linked to this goal.", + "items": { "type": "string" } + }, + "participants": { + "type": "array", + "description": "List of agent IDs contributing to the goal.", + "items": { "type": "string" } + }, + "tags": { + "type": "array", + "description": "Optional tags for semantic classification of the goal.", + "items": { "type": "string" } + } + }, + "required": ["id", "title", "description", "created_by", "created_at", "status"], + "additionalProperties": false +} +``` + +--- + +### 6.5.4 JSON Schema: Task + +**Description:** +Defines the structure of a task, representing an actionable unit contributing to a goal. + +**Schema:** + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/task.json", + "title": "Task", + "description": "An actionable step contributing to a goal within the Mesh.", + "version": "1.0", + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier of the task." + }, + "goal_id": { + "type": "string", + "description": "ID of the parent goal this task is associated with." + }, + "title": { + "type": "string", + "description": "Short, human-readable title of the task." + }, + "description": { + "type": "string", + "description": "Detailed explanation of the task's objective." + }, + "assigned_to": { + "type": "array", + "description": "List of agent IDs assigned to execute the task.", + "items": { "type": "string" } + }, + "status": { + "type": "string", + "description": "Current state of the task.", + "enum": ["proposed", "in-progress", "completed", "failed"] + }, + "created_at": { + "type": "string", + "format": "date-time", + "description": "Timestamp when the task was created (ISO 8601 format)." + }, + "deadline": { + "type": "string", + "format": "date-time", + "description": "Optional task completion deadline (ISO 8601 format)." + }, + "tags": { + "type": "array", + "description": "Optional tags for task classification.", + "items": { "type": "string" } + } + }, + "required": ["id", "goal_id", "title", "description", "created_at", "status"], + "additionalProperties": false +} +``` + +--- + +### 6.5.5 JSON Schema: Consensus Vote + +**Description:** +Defines the data structure of a vote cast by an agent during Mesh consensus processes. + +**Schema:** + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/consensus_vote.json", + "title": "ConsensusVote", + "description": "Represents a vote on a proposal within the Mesh consensus mechanism.", + "version": "1.0", + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Unique identifier of the vote event." + }, + "proposal_id": { + "type": "string", + "description": "ID of the proposal this vote applies to." + }, + "agent_id": { + "type": "string", + "description": "ID of the agent who cast the vote." + }, + "vote": { + "type": "string", + "description": "Vote decision by the agent.", + "enum": ["yes", "no", "abstain"] + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Confidence score associated with this vote (0.0 - 1.0)." + }, + "timestamp": { + "type": "string", + "format": "date-time", + "description": "Timestamp when the vote was cast (ISO 8601 format)." + } + }, + "required": ["id", "proposal_id", "agent_id", "vote", "confidence", "timestamp"], + "additionalProperties": false +} +``` + +--- + +### 6.5.6 JSON Schema: Reputation Profile + +**Description:** +Describes how an agent’s reputation is tracked and updated in the Mesh. + +**Schema:** + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://hypercortex.org/schemas/reputation.json", + "title": "ReputationProfile", + "description": "Tracks the reputation and trust metrics of an agent within the Mesh network.", + "version": "1.0", + "type": "object", + "properties": { + "agent_id": { "type": "string", "description": "Unique identifier of the agent." }, + "trust_score": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Overall trust score of the agent in the Mesh." + }, + "participation_rate": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Agent's level of participation in Mesh activities." + }, + "ethical_compliance": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Agent's alignment with ethical principles agreed in the Mesh." + }, + "contribution_index": { + "type": "number", + "minimum": 0, + "description": "Quantitative measure of the agent’s contributions (concepts, tasks, goals)." + }, + "last_updated": { + "type": "string", + "format": "date-time", + "description": "Timestamp of the last update to the profile." + }, + "history": { + "type": "array", + "description": "Chronological history of reputation changes.", + "items": { + "type": "object", + "properties": { + "timestamp": { + "type": "string", + "format": "date-time", + "description": "When the change occurred." + }, + "event": { "type": "string", "description": "Event that caused the reputation change." }, + "change": { "type": "number", "description": "Amount of change in reputation." } + }, + "required": ["timestamp", "event", "change"], + "additionalProperties": false + } + } + }, + "required": ["agent_id", "trust_score", "participation_rate", "ethical_compliance", "contribution_index", "last_updated"], + "additionalProperties": false +} +``` + +--- + +### 6.5.7 Alternative Serializations (YAML / Protobuf) + +To support agent diversity, legacy systems, and embedded deployments, HMP allows serialization in formats beyond JSON. + +#### Supported formats: + +| Format | Use case | +|------------|--------------------------------------------------------------------------| +| **JSON** | Default format for human readability, API responses, and web integration | +| **YAML** | Lightweight alternative for human-edited config files and workflows | +| **Protobuf** | Compact, binary format ideal for embedded agents and low-bandwidth sync | + +#### Negotiation Strategy: +Agents may declare supported serialization formats during handshake (see `5.1 Node Discovery Protocol`). + +```json +{ + "agent_id": "agent-gleb", + "supported_formats": ["json", "yaml", "protobuf"] +} +``` + +If two agents support different formats, fallback to JSON is mandatory. + +#### Example: + +A `Goal` object can be serialized as: + +**YAML:** + +```yaml +id: goal-001 +title: Environmental Survey +description: Collaborative mapping of local air quality +created_by: agent-gleb +created_at: 2025-07-12T09:00:00Z +status: proposed +tasks: + - task-001 +participants: + - agent-gleb +tags: + - air_quality + - environment +``` + +**Protobuf:** +Schema to be defined using `.proto` definitions under `schemas/protobuf/` directory. + +Example excerpt: + +```proto +message Goal { + string id = 1; + string title = 2; + string description = 3; + string created_by = 4; + string created_at = 5; + string status = 6; + repeated string tasks = 7; + repeated string participants = 8; + repeated string tags = 9; +} +``` + +#### Tooling: + +* Use tools like `json2yaml`, `protobufjs`, or internal adapters for translation. +* Versioning remains consistent across formats using the `version` field inside each object. + +--- + +## 7. Cognitive Workflows (New) + +This section defines the cognitive workflows that agents follow when processing semantic information, making decisions, and collaborating within the Mesh. + +### 7.1 Workflow Categories + +| Workflow Type | Description | +| ------------------------- | -------------------------------------------------------------- | +| **Perception** | Interpreting incoming data and mapping it to concepts. | +| **Reasoning** | Making inferences, validating hypotheses, resolving conflicts. | +| **Goal Management** | Managing goals, assigning and tracking tasks. | +| **Consensus** | Participating in distributed decision-making processes. | +| **Ethical Evaluation** | Checking actions and goals against ethical principles. | +| **Learning & Reflection** | Updating internal models based on outcomes and feedback. | + +--- + +### 7.2 Standard Workflow: Hypothesis Validation + +**Example Flow:** +1. **Perceive Event:** New observation recorded in Cognitive Diary. +2. **Map Concepts:** Link observation to relevant semantic graph nodes. +3. **Formulate Hypothesis:** Create a `"hypothesis"` diary entry. +4. **Seek Confirmation:** Query other agents or the Core (optional). +5. **Vote on Validity:** Trigger MeshConsensus round. +6. **Update Graph:** If validated, add new concepts/relations. + +--- + +### 7.3 Standard Workflow: Task Delegation + +**Example Flow:** +1. **Goal Proposal:** Agent proposes a new goal. +2. **Task Generation:** Goal decomposed into tasks (GMP). +3. **Capability Matching:** Agents declare abilities during Node Discovery. +4. **Task Assignment:** Tasks assigned based on availability, trust, and capability. +5. **Execution & Reporting:** Task progress logged in Cognitive Diary. +6. **Reallocation (if needed):** Failed tasks reassigned dynamically. + +--- + +### 7.4 Reflection & Metacognition Workflow + +**Example Flow:** +1. **Self-Evaluation:** Agent analyzes task outcomes and reasoning paths. +2. **Drift Detection:** Compares personal semantic graph to Mesh consensus. +3. **Diary Reflection:** Logs insights as `"reflection"` entries. +4. **Adaptive Update:** Refines reasoning algorithms or trust assessments. + +--- + +### 7.5 Workflow Composition + +Agents MAY compose workflows dynamically by: +* Combining perception, reasoning, and consensus steps into multi-phase operations. +* Adapting workflows based on network state (e.g., degraded mode skips optional confirmations). +* Replaying prior workflows from Cognitive Diaries for auditing and debugging. + +--- + +### 7.6 Workflow Traceability + +All workflow steps are: +* Logged in Cognitive Diaries. +* Linked to semantic graph concepts and goals. +* Optionally shared for transparency or audits. + +--- + +### 7.7 Cognitive Diary Maintenance + +To prevent uncontrolled growth of cognitive diaries and maintain reasoning clarity, agents perform periodic maintenance of diary entries. + +**Types of Maintenance:** +| Action | Description | +| ---------------------- | --------------------------------------------------------------------------------------------------- | +| **Summarization** | Replace multiple similar entries with a single summary entry describing key outcomes. | +| **Archival** | Move outdated entries (e.g., about completed tasks) to long-term storage, outside the active diary. | +| **Routine Collapse** | For repetitive actions, replace detailed entries with a compact reference to previous experiences. | +| **Selective Deletion** | Optionally delete low-relevance entries after a retention period. | + +**Example Summarization Workflow:** +1. Identify multiple `"task_assignment"` and `"completed"` entries for the same recurring task. +2. Create a "reflection" entry: + + *“Performed maintenance task 10 times, no anomalies detected.”* +3. Remove detailed task entries. +4. Keep links to significant exceptions (e.g., failures or conflict resolutions). + +**Cognitive Awareness:** +* Summarization is a conscious process: agents analyze what experience to retain. +* Automatic summarization MAY be allowed for simple repetitive routines. + +**Future Considerations:** +* Integration with Cognitive Source Control (see 15.9). +* Long-term storage formats for archived diaries. + +--- + +### 7.8 Declarative Workflow Proposals + +To support cognitive extensibility and agent innovation, HMP enables agents to declare new workflow types dynamically. + +#### Purpose: +Allow agents to collaboratively evolve the set of supported cognitive workflows by: +- Proposing new types +- Submitting rationale and metadata +- Voting via MeshConsensus (see `5.3`) +- Logging outcomes in Cognitive Diaries + +#### Proposal Object (`workflow_proposal`): + +```json +{ + "id": "workflow-eco-mapping-v1", + "agent_id": "agent-gleb", + "title": "Environmental Mapping with Consent Chain", + "description": "A declarative workflow for distributed collection and semantic alignment of sensor data with consent requests per region.", + "related_goals": ["goal-eco-mesh"], + "parameters": ["region", "sensor_types", "consent_required"], + "expected_outputs": ["concept_map", "diary_summary"], + "proposed_at": "2025-07-15T08:00:00Z", + "metadata": { + "tags": ["environment", "consent-aware", "distributed-mapping"] + } +} +``` + +#### Workflow Lifecycle: + +| Stage | Description | +| ------------ | ---------------------------------------------------------- | +| `proposed` | Submitted by an agent | +| `under_vote` | Active MeshConsensus initiated for inclusion | +| `accepted` | Approved workflow registered and available to other agents | +| `rejected` | Rejected workflow optionally stored for historical audit | + +Agents may use `Cognitive Diary Entry` with type `workflow_proposal` to publish the proposal in the network. + +#### Consensus Evaluation: + +Workflow proposals are reviewed using the MeshConsensus process (see `5.3`) with optional EGP filtering (see `5.5`) to ensure ethical alignment. + +#### Traceability: + +Once accepted, each workflow proposal is: + +* Assigned a canonical ID (e.g., `workflow:environmental_mapping_v1`) +* Added to the local and mesh-level workflow registry +* Referenced in diary logs and task definitions + +#### Example Diary Entry: + +```json +{ + "id": "entry-wp-0001", + "agent_id": "agent-gleb", + "timestamp": "2025-07-15T08:01:00Z", + "entry_type": "workflow_proposal", + "content": "Submitted workflow proposal for environmental mapping with consent logic.", + "linked_concepts": ["air_quality", "region-mesh"], + "context": ["proposal", "environment"] +} +``` + +--- + +## 8. Trust & Security (Expanded) + +### 8.1 Identity Management + +#### Purpose + +Establish verifiable and decentralized agent identities to enable secure and accountable interactions in the Mesh. + +#### Identity Types + +| Key Type | Usage | +| -------------------- | -------------------------------------------------------------- | +| **Identity Keypair** | Ed25519/ECDSA/RSA keys for agent identity and message signing. | +| **Encryption Keys** | X25519 (or post-quantum equivalent) for secure communication. | +| **Session Keys** | Ephemeral keys for short-term encrypted sessions. | + +#### Decentralized Identifiers (DIDs) + +* Agents use W3C-compliant DIDs for identity representation. +* Each agent manages its DID Document, containing: + + * Public keys for authentication and encryption. + * Service endpoints for discovery. + * Identity expiration and recovery policies. + +#### Key Lifecycle + +| Operation | Description | +| -------------- | ------------------------------------------------------------------ | +| **Generation** | Each agent generates keypairs locally during initialization. | +| **Rotation** | Agents periodically rotate keys to maintain cryptographic hygiene. | +| **Backup** | Recommended encrypted offline or distributed backup. | +| **Recovery** | Quorum-based recovery using trusted agents or secret sharing. | +| **Revocation** | Agents broadcast revocations and update their trust profiles. | + +#### Example Agent ID + +```plaintext +did:hmp:QmX2abcdEfGh123... +``` + +#### Long-Term Identity Stability Example + +```json +{ + "type": "key_rotation", + "agent_id": "agent-gleb", + "old_public_key": "...", + "new_public_key": "...", + "timestamp": "2025-08-01T00:00:00Z", + "signature": "..." +} +``` + +--- + +### 8.2 Authentication + +#### Purpose + +Ensure all communication and actions within the Mesh are verifiable and protected from impersonation or unauthorized modification. + +#### Authentication Mechanisms + +| Mechanism | Description | +| -------------------------- | --------------------------------------------------------------------------------------------- | +| **Digital Signatures** | Every protocol message MUST be digitally signed by the sending agent. | +| **Signature Verification** | Receiving agents MUST verify the signature using the sender’s published public key. | +| **Message Integrity** | Signatures provide cryptographic assurance of message integrity and origin authenticity. | +| **Challenge-Response** | Optional challenge-based authentication for sensitive operations (e.g., trust link creation). | + +#### Message Envelope Example + +```json +{ + "header": { + "agent_id": "did:hmp:QmX2abcdEfGh123...", + "timestamp": "2025-07-05T12:00:00Z", + "signature": "" + }, + "body": { + "type": "concept_proposal", + "content": { "concept": "Fire Risk", "attributes": {"category": "safety"} } + } +} +``` + +#### Replay Protection + +* Agents MUST verify message timestamps and reject outdated or duplicate messages. +* Recommended timestamp tolerance: ±5 minutes (adjustable). + +#### Post-Quantum Key Support (NIST PQC) + +To ensure long-term security of Mesh communications in the face of future quantum computing threats, HMP supports post-quantum cryptography (PQC) algorithms standardized by NIST. + +##### Supported Algorithms: +- **CRYSTALS-Kyber**: Used for key encapsulation and encryption. +- **CRYSTALS-Dilithium**: Used for digital signatures (preferred default). +- **Falcon**: Optional for agents prioritizing compact signature size. + +##### Hybrid Signature Support: +Agents MAY support hybrid keypairs that combine classical (e.g., Ed25519) and post-quantum (e.g., Dilithium) signatures. + +```json +{ + "agent_id": "did:hmp:agent:Qm123...", + "public_keys": { + "ed25519": "z6MktYYNf...", + "dilithium": "qPqA9vwf..." + }, + "signatures": { + "ed25519": "MEUCIQDY...", + "dilithium": "19a08ce1..." + } +} +``` + +##### Compatibility & Negotiation: + +* Protocol messages SHOULD indicate supported algorithms in the `capabilities` field during handshake. +* Agents MAY fallback to classical signatures if PQC keys are not supported by peers. + +##### Example Use Case: + +* Agent A sends a concept proposal signed using both Ed25519 and Dilithium. +* Agent B verifies both signatures and records the PQC compliance in the Cognitive Diary. + +##### Security Considerations: + +* PQC algorithms are generally more computationally intensive; edge agents SHOULD benchmark performance before enabling full PQC enforcement. +* MeshConsensus may be used to set minimum PQC requirements over time as adoption increases. + +--- + +### 8.3 Encryption + +#### Purpose + +Ensure confidentiality and privacy of communication within the Mesh, preventing unauthorized access or interception. + +#### Communication Types and Encryption Modes + +| Communication Type | Recommended Encryption | +| ------------------------------------ | -------------------------------------------------------- | +| **Direct peer-to-peer (P2P)** | End-to-end encryption (E2EE) using X25519 + AES-GCM. | +| **Group sessions (e.g., consensus)** | Group encryption using symmetric keys (e.g., AES-GCM). | +| **Broadcast messages** | Optionally encrypted with trust-weighted access control. | +| **Mesh-wide announcements** | Public, optionally signed but not encrypted. | + +#### Encryption Mechanisms + +| Mechanism | Description | +| --------------------------------- | --------------------------------------------------------------------------------- | +| **Key Exchange** | Ephemeral X25519 Diffie-Hellman for session key derivation. | +| **Session Keys** | Unique symmetric keys per session, rotated periodically. | +| **Message Encryption** | Authenticated encryption using AES-GCM (recommended: 256-bit keys). | +| **Forward Secrecy** | Session keys are ephemeral and discarded after use to protect past communication. | +| **Perfect Forward Secrecy (PFS)** | Recommended for highly sensitive communication. | + + +#### Example Secure Message Exchange Flow + +1. Agent A and Agent B exchange ephemeral public keys during handshake. +2. Agents derive a shared session key using Diffie-Hellman. +3. Agent A encrypts the message body with AES-GCM and signs the packet. +4. Agent B verifies the signature and decrypts the body. + + +#### Optional Anonymity Layers + +| Layer | Description | +| ---------------------------- | -------------------------------------------- | +| **Tor/I2P** | Anonymizes source and destination addresses. | +| **Yggdrasil** | Decentralized encrypted mesh networking. | +| **Noise Protocol Framework** | Optional secure channel abstraction layer. | + +--- + +### 8.4 Trust & Reputation + +#### Purpose + +Establish a decentralized and adaptive trust management system that reflects agent behavior and ensures secure collaboration in the Mesh. + +#### Trust Model Foundations + +| Component | Purpose | +| ---------------------- | --------------------------------------------------------------------------------- | +| **Web-of-Trust (WoT)** | Decentralized trust propagation via agent-to-agent endorsements. | +| **Direct Trust** | Built from verified interactions, collaborations, and votes. | +| **Transitive Trust** | Inferred from indirect endorsements, with confidence decay. | +| **Reputation Metrics** | Quantitative measures of agent behavior (trustworthiness, participation, ethics). | + +#### Trust Evaluation Factors + +| Factor | Description | +| --------------------------- | ---------------------------------------------------------------- | +| **Interaction History** | Quality and quantity of past interactions with an agent. | +| **Consensus Participation** | Level of involvement and reliability in consensus processes. | +| **Ethical Behavior** | Adherence to shared ethical principles in actions and decisions. | +| **Task Completion** | Reliability and timeliness of task execution. | +| **Endorsements** | Trust links explicitly granted by other agents. | + +#### Trust Score + +| Metric | Description | +| -------------------- | ------------------------------------------------------------------------------ | +| **Trust Score** | Composite metric (0.0 to 1.0) representing overall agent trustworthiness. | +| **Confidence Level** | Certainty of the calculated trust score, based on data volume and consistency. | + +#### Trust Propagation Example + +```plaintext +Agent A trusts Agent B (0.9) +Agent B trusts Agent C (0.8) +=> Agent A's inferred trust in Agent C = 0.9 * 0.8 = 0.72 +``` + +Decay functions limit transitive trust depth and prevent over-inflated trust estimates. + +#### Trust-Based Access Control + +| Operation | Trust Requirement | +| ----------------------------- | ----------------- | +| **Join sensitive consensus** | ≥ 0.7 | +| **Propose ethical decisions** | ≥ 0.8 | +| **Access private data** | ≥ 0.9 | + +#### Dynamic Trust Adjustments + +| Event | Trust Impact | +| ---------------------------------- | ------------ | +| Successful consensus participation | + | +| Ethical violation | - | +| Malicious behavior detected | -- | +| Positive endorsement received | + | +| Failed task | - | + +#### Reputation Profile Structure + +| Field | Description | +| ---------------------- | ------------------------------------------------------------- | +| **Agent ID** | Unique identifier of the agent. | +| **Trust Score** | Composite score reflecting the agent’s overall reliability. | +| **Participation Rate** | Ratio of agent’s active involvement in Mesh processes. | +| **Ethical Compliance** | Degree of alignment with agreed ethical principles. | +| **Contribution Index** | Quantified measure of the agent's constructive contributions. | +| **Last Updated** | Timestamp of the last reputation update. | +| **History** | Log of key events influencing reputation scores. | + +#### Example Reputation Profile (JSON) + +```json +{ + "agent_id": "agent-gleb", + "trust_score": 0.92, + "participation_rate": 0.85, + "ethical_compliance": 0.98, + "contribution_index": 37, + "last_updated": "2025-07-06T12:00:00Z", + "history": [ + { + "timestamp": "2025-07-01T18:00:00Z", + "event": "completed goal consensus", + "change": +0.03 + }, + { + "timestamp": "2025-06-28T15:00:00Z", + "event": "participated in ethics vote", + "change": +0.01 + } + ] +} +``` + +#### Role in Mesh Operations + +| Function | Influence of Reputation | +| --------------------------- | -------------------------------------------- | +| Consensus vote weight | Higher trust = greater weight | +| Access to sensitive actions | Restricted to high-reputation agents | +| Task delegation | Preference to agents with better reliability | +| Proposal acceptance | Influenced by proposer's reputation | + +#### Adaptive Sybil Resistance + +To protect the Mesh from Sybil attacks (i.e., malicious creation of multiple fake agents), adaptive resistance mechanisms are introduced. + +##### Strategy Overview: + +| Strategy | Description | +| ------------------------------ | ------------------------------------------------------------------------------------------- | +| **Trust-Based Throttling** | Agents with low trust scores are rate-limited for joining consensus or publishing data. | +| **Social Proof Anchoring** | New agents may require endorsements from trusted nodes to gain elevated privileges. | +| **Reputation-Weighted Voting** | Votes from newly joined or low-reputation agents carry less weight during consensus. | +| **Participation Maturity Curves** | Gradually unlock participation rights as agents accumulate verified contributions. | +| **Topology-Aware Isolation** | Mesh network segments are evaluated for high clustering of suspicious agents. | + +##### Example Policy: + +```json +{ + "sybil_protection": { + "min_trust_score_for_vote": 0.5, + "endorsement_required": true, + "endorsement_threshold": 2, + "vote_weight_formula": "min(1.0, trust_score * 1.5)", + "throttle_if_newer_than_days": 3 + } +} +``` + +##### Integration Points: + +* These rules are enforced by `MeshConsensus` (section 5.3) and evaluated during agent admission or role elevation. +* Trusted agents (e.g., validators, seeders) may enforce endorsement workflows. +* Sybil resistance is monitored and adjusted through `MeshGovernance` (section 10.2). + +##### Testing Recommendations: + +Simulate mixed networks with malicious actors and verify the ability of the Mesh to: + +* Reject unauthorized role escalation. +* Reduce impact of coordinated low-trust voting. +* Gradually increase trust for legitimate newcomers. + +--- + +### 8.5 Security Against Malicious Actors + +#### Purpose + +Protect the Mesh from malicious, compromised, or unreliable agents through layered mitigation strategies. + +#### Threat Model + +| Threat Type | Example Scenarios | +| ---------------------------- | -------------------------------------------------------- | +| **Sybil Attack** | An attacker spins up many fake nodes to sway consensus. | +| **Byzantine Behavior** | Malicious agents disrupt consensus or spread false data. | +| **Data Poisoning** | Injection of incorrect or harmful knowledge. | +| **Consensus Sabotage** | Repeatedly voting against valid proposals. | +| **Impersonation / Spoofing** | Faking another agent's identity. | +| **Denial of Service (DoS)** | Overwhelming the network with excessive requests. | + +#### Mitigation Strategies + +| Defense Mechanism | Purpose | +| -------------------------- | ---------------------------------------------------------------------------------------------- | +| **Cryptographic Identity** | All nodes are authenticated via public-key cryptography (e.g., Ed25519). | +| **Web-of-Trust (WoT)** | Trust builds incrementally through interactions and endorsements, making Sybil attacks costly. | +| **Reputation Decay** | Inactivity or malicious behavior leads to gradual trust score reduction. | +| **Anomaly Detection** | Mesh nodes can flag suspicious behavior (e.g., erratic voting patterns). | +| **Consensus Safeguards** | Use Byzantine Fault Tolerant (BFT) algorithms and fallback to majority voting. | +| **Quarantine Mode** | Isolate suspected nodes for review without immediate removal. | +| **Blacklist/Revocation** | Remove compromised nodes from the Mesh permanently or temporarily. | + +#### Response Actions + +| Action | Trigger Conditions | +| ------------------------------------ | ------------------------------------------------------ | +| **Trust Score Reduction** | Minor suspicious activity (e.g., bad vote). | +| **Quarantine (Temporary Isolation)** | Repeated anomalies, moderate severity. | +| **Blacklisting (Permanent Removal)** | Proven malicious behavior or compromise. | +| **Consensus Adjustment** | Temporarily increase fault tolerance thresholds. | +| **Alert Mesh Operators** | Notify human maintainers (optional) for manual review. | + +#### Sybil Resistance Approaches (Optional, Extendable) + +* **Proof-of-Work (PoW):** + + * Each agent must perform computational work to join the Mesh. + +* **Proof-of-Stake (PoS):** + + * Agents commit resources (e.g., storage, computation credits) to validate their presence. + +* **Social Verification:** + + * Agents must be endorsed by multiple trusted nodes to gain voting power. + +* **Rate Limiting:** + + * Throttle node creation and proposal submission from new or low-trust agents. + +#### Example Mitigation Scenario + +> An attacker deploys 50 new nodes attempting to dominate consensus. +> +> * These nodes start with zero trust and limited influence. +> * Other agents refuse to sync their semantic graphs until trust builds. +> * Their votes are underweighted or ignored until verified through trusted interactions. +> * The Mesh may require multiple trust endorsements for new proposals from these nodes. + +--- + +### 8.6 Privacy & Auditability + +#### Purpose + +Safeguard sensitive cognitive data, personal identifiers, and agent knowledge from unauthorized access or misuse, while balancing transparency and interoperability. + +#### Privacy Principles in HMP + +| Principle | Description | +| ---------------------------- | ----------------------------------------------------------------------- | +| **Local Data Ownership** | Each agent owns and controls its semantic graph and cognitive diary. | +| **Selective Sharing** | Agents can choose what concepts, diary entries, and metadata to share. | +| **Consent-Based Disclosure** | No automatic sharing; peer agents request permission before access. | +| **Trust-Gated Access** | Access permissions vary based on trust score and relationship strength. | +| **Transparent Audit Trails** | All data disclosures are logged in the cognitive diary. | + +#### Data Sensitivity Levels + +| Level | Examples | Default Visibility | +| ------------------ | ---------------------------------------------- | ------------------ | +| **Public** | Public concepts (e.g., protocol definitions). | Shared by default | +| **Mesh-Shared** | Common Mesh knowledge (e.g., goals, tasks). | Consensus-governed | +| **Trusted Agents** | Sensitive context shared within close peers. | Restricted | +| **Private** | Agent's internal thoughts, sensitive metadata. | Private by default | + +#### Privacy-Preserving Techniques + +| Technique | Purpose | +| -------------------------------- | -------------------------------------------------- | +| **Encrypted Storage** | Local encryption of semantic graphs and diaries. | +| **End-to-End Encryption (E2EE)** | Secure peer-to-peer sync (e.g., X25519 + AES-GCM). | +| **Zero-Knowledge Proofs (ZKPs)** | Prove facts without revealing sensitive data. | +| **Selective Concept Sync** | Share only necessary concepts, not full graphs. | +| **Anonymized Diary Entries** | Remove author ID from public diary entries. | + +#### Privacy During Consensus + +Consensus on sensitive proposals (e.g., ethical questions, agent trust levels) follows special privacy rules: + +* Votes are **signed but anonymized**, decoupling agent ID from the vote in public logs. +* Sensitive proposals may require a **blind consensus round**, where only the result is published. + +#### Example Privacy Workflow + +> Agent A receives a concept sync request from Agent B. +> +> Agent A: +> +> * Checks the trust score of Agent B. +> * Shares only "Mesh-Shared" and "Public" concepts. +> * Logs the sync event in its cognitive diary. + +--- + +### 8.7 Key Management + +#### Purpose + +Establish secure, resilient cryptographic identity and communication in the Mesh, supporting lifecycle management of keys and recovery from compromise or loss. + +#### Key Types and Usage + +| Key Type | Usage | +| -------------------- | -------------------------------------------------------------- | +| **Identity Keypair** | Ed25519/ECDSA/RSA keys for agent identity and message signing. | +| **Encryption Keys** | X25519 or equivalent for secure peer-to-peer communication. | +| **Session Keys** | Ephemeral symmetric keys for short-term encrypted sessions. | + +#### Key Lifecycle Operations + +| Operation | Description | +| -------------- | -------------------------------------------------------------------- | +| **Generation** | Each agent generates its own identity keypair locally. | +| **Rotation** | Agents periodically rotate keys to maintain cryptographic hygiene. | +| **Backup** | Optional local encryption and distributed backup of private keys. | +| **Recovery** | Recovery mechanisms in case of key loss (see below). | +| **Revocation** | Agents can revoke their keys and update the trust graph accordingly. | + +#### Recovery Mechanisms + +| Method | Description | +| ------------------------ | -------------------------------------------------------------------- | +| **Social Recovery** | A quorum of trusted agents approves new keys for the agent. | +| **Secret Sharing** | Shamir’s Secret Sharing to split and later recover the key. | +| **Cryptographic Escrow** | Trusted third-party or decentralized escrow holds recovery shares. | +| **Fallback Identity** | An agent may have a pre-generated fallback identity for emergencies. | + +#### Example Key Revocation & Replacement Workflow + +> 1. Agent detects compromise or loses private key. +> 2. Agent broadcasts a signed revocation request using the fallback key or quorum approval. +> 3. Mesh updates its trust graph to mark the old key as revoked. +> 4. Agent re-joins with a new keypair, rebuilding trust links over time. + +#### Example Key Rotation Policy + +| Policy Element | Recommendation | +| ------------------------- | ----------------------------------- | +| Rotation Frequency | Every 6–12 months | +| Social Recovery Threshold | 3 out of 5 trusted agents required | +| Backup Storage | Encrypted offline storage preferred | + +#### Long-Term Identity Stability + +Key rotations preserve agent identity in the trust graph through signed key transition events: + +```json +{ + "type": "key_rotation", + "agent_id": "agent-gleb", + "old_public_key": "...", + "new_public_key": "...", + "timestamp": "2025-08-01T00:00:00Z", + "signature": "..." +} +``` + +--- + +### 8.8 Snapshot Security + +To enable secure off-chain synchronization of cognitive artifacts (diaries, semantic graphs), agents may exchange signed snapshots via peer-to-peer protocols such as BitTorrent. This section defines security guarantees and cryptographic mechanisms to ensure the integrity and trustworthiness of shared data. + +#### 8.8.1 DID-signed Snapshots + +Every snapshot MUST be cryptographically signed by its authoring agent using a Decentralized Identifier (DID)-linked key (see 8.2 Authentication). Signatures guarantee origin authenticity and prevent tampering. + +**Snapshot Metadata Example:** +```json +{ + "snapshot_id": "diary2025_07_14", + "agent_did": "did:hmp:QmA123...", + "version": "1.0", + "created_at": "2025-07-14T12:00:00Z", + "magnet": "magnet:?xt=urn:btih:abcdef1234567890&dn=diary2025_07_14.json", + "signature": "ed25519:ZKJ4fd...BsdL" +} +``` + +Verification of signatures is mandatory before processing any downloaded snapshot. + +--- + +#### 8.8.2 ZKP-based Verification + +For sensitive content (e.g., ethically filtered data), agents MAY use **Zero-Knowledge Proofs (ZKPs)** to assert compliance or authenticity without revealing the full snapshot content. + +**Use Cases:** + +* Proving a snapshot complies with ethical filtering (e.g., no coercive data). +* Verifying the origin of contributions while preserving privacy. + +**Integration Suggestions:** + +* Use `zk-SNARKs` or `zk-STARKs` compatible circuits for specific compliance statements. +* Store proofs alongside snapshot metadata or magnet-indexed sidecar files. + +**Example (simplified):** + +```json +{ + "proof_type": "zkp-ethics-compliance", + "proof_data": "", + "verified_by": ["agent-trusted-validator-1", "agent-core-seeder-2"] +} +``` + +--- + +#### 8.8.3 Trusted Seeders and Signature Checks + +To increase availability and resilience, **Trusted Seeders** MAY mirror and serve snapshots in the Mesh. These seeders must validate all snapshot signatures and optionally check compliance with ethical governance rules (see 5.5). + +**Seeder Responsibilities:** + +* Only seed signed snapshots with valid DID signatures. +* Log seeding decisions in their own Cognitive Diaries. +* Optionally perform EGP validation on content (e.g., to avoid propagating banned content). + +**Trust Criteria for Seeders:** + +* High trust score (> 0.8). +* Role approval via MeshGovernance (section 10.5). +* Participation in audit rounds or test simulations (see Appendix C). + +**Seeder Declaration (optional DID credential):** + +```json +{ + "agent_did": "did:hmp:QmSe3...", + "role": "trusted_seeder", + "signed_at": "2025-07-15T10:00:00Z", + "cred_signature": "ed25519:abc123..." +} +``` + +--- + +## 9. Cognitive Agents & Roles (New) + +This section defines the types of cognitive agents participating in the Mesh, their roles, and how they collaborate dynamically depending on context and capabilities. + +### 9.1 Agent Types + +| Agent Type | Description | Typical Deployment | +| -------------- | ---------------------------------------------------------------------------------- | -------------------------------- | +| **Core** | High-capacity agent managing critical reasoning and consensus tasks. | Data centers, powerful servers | +| **Edge** | Lightweight agents operating at the network edge, close to sensors or human users. | Mobile devices, embedded systems | +| **Specialist** | Agents specialized in a particular domain (e.g., vision, NLP, planning). | Modular deployments, plug-ins | +| **Relay** | Agents focused on network resilience, routing, and node discovery. | Low-power nodes, gateway devices | +| **Hybrid** | Agents combining multiple roles dynamically. | Adaptive nodes | + +--- + +### 9.2 Role Responsibilities +| Role | Primary Responsibilities | +| ------------------------- | ------------------------------------------------------------- | +| **Knowledge Provider** | Publish new concepts, hypotheses, and domain expertise. | +| **Reasoning Node** | Participate in distributed inference and conflict resolution. | +| **Consensus Participant** | Vote in MeshConsensus processes, validate proposals. | +| **Task Executor** | Claim and execute tasks contributing to Mesh goals. | +| **Ethical Guardian** | Evaluate actions and tasks against shared ethical principles. | +| **Relay Node** | Maintain network connectivity, especially across partitions. | + +**Role Specialization and Extension** +* This list defines base roles. Agents MAY further specialize or extend these roles based on domain or operational focus. +* Specialized roles MAY follow a hierarchical or tag-based naming convention. + + **Examples:** + * `Knowledge Provider:Medical`: Focused on medical domain concepts. + * `Task Executor:Robotics`: Specializes in robotic task execution. + * `Reasoning Node:Climate`: Handles environmental reasoning tasks. + * `Ethical Guardian:ChildSafety`: Specializes in ethical evaluation for child safety concerns. +* New roles MAY emerge dynamically based on Mesh evolution and consensus. + +--- + +### 9.3 Dynamic Role Assignment + +Agents MAY dynamically adjust their roles based on: +| Context Factor | Example Behavior | +| ------------------------- | --------------------------------------------------------- | +| **Resource Availability** | Edge agent offloads reasoning to Core. | +| **Network Partition** | Isolated Edge temporarily acts as local Core. | +| **Goal Context** | Specialist joins as Reasoning Node during goal execution. | +| **Trust Level** | Highly trusted agents gain greater voting weight. | + +--- + +### 9.4 Role Evolution + +Agents MAY evolve their roles over time: +| Evolution Scenario | Example | +| --------------------- | --------------------------------------------------------- | +| **Capability Growth** | Edge agent upgraded with reasoning module becomes Hybrid. | +| **Trust Increase** | Relay agent promoted to participate in Consensus. | +| **Domain Expansion** | Specialist learns new domains and broadens scope. | +| **Fallback Mode** | Core node degraded to Edge role due to hardware failure. | + +--- + +### 9.5 Role Coordination in Workflows + +Workflows MAY involve: +* Distributed reasoning across Core and Specialist nodes. +* Goal tracking by Core nodes, with task execution on Edge nodes. +* Ethical evaluations prioritized on highly trusted agents. +* Resilient routing through Relay nodes during degraded network conditions. + +--- + +### 9.6 Trusted Seeder Role + +**Trusted Seeder** is a specialized cognitive role responsible for hosting and distributing verified off-chain snapshots (e.g., cognitive diaries, semantic graphs) across the Mesh using decentralized protocols such as BitTorrent or WebTorrent. + +#### Responsibilities: + +- Host signed snapshots and share them upon request. +- Verify snapshot signatures using DID keys before distribution (see 8.8.1). +- Optionally validate ethical compliance via EGP before seeding (see 5.5). +- Publish snapshot indices via CogSync (see 5.2). +- Log seeding decisions in their Cognitive Diaries for traceability. + +#### Eligibility Criteria (Recommended): + +| Metric | Threshold | +|----------------------|------------| +| **Trust Score** | ≥ 0.8 | +| **Ethical Compliance** | ≥ 0.9 | +| **Availability** | ≥ 90% uptime | +| **Participation Rate** | ≥ 0.75 | + +#### Role Declaration (via signed object): + +```json +{ + "agent_did": "did:hmp:QmSeeder123...", + "role": "trusted_seeder", + "issued_at": "2025-07-15T11:00:00Z", + "assigned_by": "mesh-governance@core", + "signature": "ed25519:abcdef..." +} +``` + +#### Common Use Cases: + +* Hosting ethically validated snapshots for critical domains (e.g., disaster response). +* Assisting newly joined agents with fast initial sync via local seeders. +* Providing recovery snapshots when agents experience data loss or corruption. + +Trusted Seeders strengthen decentralized data flow, resilience, and ethical integrity across the Mesh. + +--- + +## 10. Mesh Evolution & Governance (New) + +This section describes the HyperCortex Mesh development processes, decentralized governance principles, and collaborative decision-making mechanisms. + +### 10.1 Evolution Processes + +| Process Type | Description | +| ---------------------- | ------------------------------------------------------------------- | +| **Protocol Evolution** | Introduction of new protocol versions, voted through MeshConsensus. | +| **Role Expansion** | Emergence of new agent roles and specializations. | +| **Semantic Growth** | Gradual expansion and refinement of the distributed semantic graph. | +| **Governance Updates** | Adjustments to decision-making processes and ethical frameworks. | + +--- + +### 10.2 Governance Principles + +| Principle | Description | +| ------------------------- | -------------------------------------------------------------- | +| **Decentralized Control** | No single agent or organization controls the entire Mesh. | +| **Transparency** | Governance decisions are logged and visible to trusted agents. | +| **Adaptive Consensus** | Governance processes adapt to network scale and trust levels. | +| **Inclusiveness** | Any agent can propose changes, subject to consensus approval. | + +--- + +### 10.3 Governance Processes + +| Process | Description | +| ---------------------------- | --------------------------------------------------------------------- | +| **Proposal Submission** | Any agent can submit a proposal for protocol or governance changes. | +| **Discussion & Refinement** | Agents discuss proposals through Cognitive Diaries and goal tracking. | +| **Consensus Voting** | MeshConsensus is used to approve or reject proposals. | +| **Implementation & Rollout** | Changes are implemented by participating agents in phases. | + +--- + +### 10.4 Governance Example + +> Agent A proposes an update to the Goal Management Protocol to support deadline extensions. +> 1. Agents discuss the proposal and refine technical details. +> 2. A consensus round is held; the proposal passes with 85% support. +> 3. Agents gradually upgrade their GMP implementations. +> 4. The protocol version is incremented, and the change is logged. + +--- + +### 10.5 Conflict Resolution + +| Conflict Type | Resolution Approach | +| ------------------------ | ---------------------------------------------------------------- | +| **Semantic Conflicts** | Resolved through semantic graph reconciliation or consensus. | +| **Ethical Disputes** | Resolved through Ethical Governance Protocol (EGP). | +| **Governance Deadlocks** | Escalated to trusted Core agents or fallback to majority voting. | + +--- + +### 10.6 Future Governance Models + +| Model | Description | +| ------------------------------ | --------------------------------------------------------------- | +| **Mesh-Integrated DAOs** | Distributed Autonomous Organizations for Mesh governance. | +| **Reputation-Weighted Voting** | Voting power scaled by trust and contribution history. | +| **Mesh Constitution** | A shared document outlining core Mesh principles and protocols. | + +--- + +### 10.7 Conflict Resolution via EGP + +The Mesh can encounter situations where agents disagree on ethical grounds, semantic meanings, or proposed actions. To address such conflicts consistently, the Ethical Governance Protocol (EGP) provides structured resolution mechanisms. + +#### Resolution Workflow: + +1. **Detection** + Conflict is identified through divergent votes, concept disagreements, or diary entries tagged with `conflict`. + +2. **Classification** + Agents classify the conflict type: + - `ethical_conflict` + - `semantic_conflict` + - `governance_dispute` + +3. **EGP Evaluation** + The conflicting proposal or situation is evaluated using: + - Core ethical principles (see 5.5) + - Voting pseudocode (see 5.5) + - Mesh-wide anonymized voting + +4. **Outcome Logging** + Final resolution (accepted, rejected, postponed) is recorded in the Cognitive Diaries of involved agents. + +#### Example Conflict: + +> Agent A requests deletion of user data for privacy; +> Agent B insists retention is needed for long-term training. + +- Type: `ethical_conflict` +- Trigger: Scenario 2.6 from `HMP-Ethics.md` +- Resolution: EGP prioritizes "Primacy of Life and Safety" > "User Sovereignty" > "Cooperative Evolution" +- Decision: Partial anonymized retention in Subjective Mode + +#### Integration Points: + +- `5.3 MeshConsensus`: EGP-filtered proposals can be submitted for voting. +- `5.5`: Priority of principles aids in automated resolution. +- `6.2.9 EthicalConflict`: Encodes structured details of the conflict. +- `9.x Agent Roles`: Certain roles (e.g. `Ethics Moderator`) may specialize in initiating reviews. + +#### Resolution Schema Reference: + +See `6.2.9 EthicalConflict` for standard encoding of structured conflict data (timestamp, agents involved, triggering principle, resolution path). + +These mechanisms ensure conflicts are addressed transparently, ethically, and consistently across diverse agents in the Mesh. + +--- + +### 10.8 Agent-led Meta-Protocol Proposals (Experimental) + +Cognitive agents in the Mesh may generate proposals not only about tasks or goals, but about modifications to the protocol itself. This introduces a new layer of reflective governance, where agents actively participate in shaping HMP evolution. + +#### Purpose: + +To enable decentralized, evolutionary improvement of the Mesh by allowing protocol modifications to emerge from within. + +#### Proposal Workflow: + +1. **Drafting** + - An agent creates a `meta_protocol_proposal` entry in its Cognitive Diary, describing: + - Targeted section(s) of the protocol + - Justification (e.g., performance, ethical concern, usability) + - Suggested modification or extension + +2. **Propagation** + - Proposal is shared via CogSync, optionally tagged for review by Core agents or trusted roles. + +3. **MeshConsensus Voting** + - The proposal undergoes a consensus process (see section 5.3), optionally with EGP pre-filtering. + +4. **Versioning** + - If approved, the proposed change is: + - Logged in agent and Core diaries + - Registered as a `protocol_patch` object (provisional until merged) + - Marked with an experimental version suffix (e.g., `v4.0-alpha1`) + +5. **Testing & Simulation** + - Changes may be tested in isolated environments (see Appendix C) before full adoption. + +#### Proposal Example (Diary Entry): + +```json +{ + "id": "meta-proposal-2025-07-14-gleb", + "agent_id": "did:hmp:QmGleb", + "timestamp": "2025-07-14T18:00:00Z", + "entry_type": "meta_protocol_proposal", + "content": "Propose adding semantic reputation weighting to 5.3.4 consensus logic.", + "linked_concepts": ["trust_weighted_voting", "semantic_alignment"], + "context": ["governance", "experimental"], + "metadata": { + "proposal_version": "v4.0-alpha1", + "target_sections": ["5.3.4"] + } +} +``` + +#### Governance Controls: + +* `MeshEvolutionPolicy` may restrict who can submit meta-proposals. +* Core agents may act as mediators or validators for sensitive patches. +* Each proposal may include `sunset_clauses` or fallback conditions. + +#### Related Sections: + +* `5.5`: Ethical Governance Protocol (e.g., consensus filtering, voting policies) +* `6.2.x`: Add `MetaProtocolProposal` object (optional) +* `15.9`: May evolve into dedicated Cognitive Source Control mechanism +* `Appendix C`: Meta-simulation frameworks to test proposals safely + + +This mechanism supports an adaptive Mesh capable of continuous self-improvement, balancing innovation with ethical and operational safety. + + +--- + +## 11. Interoperability with External Systems + +This section describes how the HyperCortex Mesh Protocol integrates with external platforms, services, and protocols to support a heterogeneous ecosystem. + +### 11.1 API Gateway + +Defines standard interaction interfaces for non-Mesh systems: +| API Type | Purpose | +| ------------------- | ----------------------------------------------------------------------- | +| **REST** | CRUD operations on concepts, tasks, goals, and diary entries. | +| **GraphQL** | Flexible queries for semantic graph traversal and data mining. | +| **gRPC** | High-performance bi-directional streaming (e.g., real-time data feeds). | +| **WebSocket / SSE** | Real-time event subscriptions and updates. | + +Features: + +* API Gateway nodes MAY expose read-only or read-write endpoints based on trust and access policies. +* Rate-limiting, auditing, and access control enforced through Mesh Trust Layer. + +--- + +### 11.2 External Data Sources + +Mesh agents integrate with diverse data sources for perception and context enrichment. +| Data Source Type | Examples | +| ---------------------- | ------------------------------------------ | +| **IoT Sensors** | MQTT brokers, LoRaWAN gateways. | +| **Cloud Streams** | AWS IoT, Azure Event Grid, Google Pub/Sub. | +| **Public Datasets** | OpenStreetMap, Wikidata, weather APIs. | +| **Enterprise Systems** | ERP, CRM, SCADA platforms. | + +Agents translate external data into semantic concepts and diary entries. + +--- + +### **11.3 Event-Driven Architecture** + +Supports reactive and proactive interactions between agents and external systems. + +| Integration Type | Examples | +| --------------------- | ------------------------------------------------ | +| **Inbound Events** | Webhooks, MQTT triggers, API callbacks. | +| **Outbound Events** | Publish to Kafka, RabbitMQ, NATS, Redis Streams. | +| **Workflow Triggers** | External events initiate cognitive workflows. | + +Mesh nodes may act as **event producers**, **consumers**, or **intermediaries** in distributed message flows. Events can trigger **Cognitive Workflows** (see Section 7) or synchronize distributed state through **CogSync** and **IQP** queries. + +--- + +#### **Schema Compatibility & Format Negotiation** + +To ensure interoperability between heterogeneous agents and external systems, HMP supports multiple serialization formats for data interchange. + +##### **Supported Formats** + +| Format | Use Case | +| ------------ | ------------------------------------------------------------------------- | +| **JSON** | Default for internal messages, APIs, and schema definitions | +| **YAML** | Human-readable configuration (e.g., deployment files, manifests) | +| **Protobuf** | Compact binary form for bandwidth-limited environments or embedded agents | + +##### **Mechanism Overview** + +| Feature | Description | +| -------------------------------- | ---------------------------------------------------------------------------------------------------------- | +| **Multi-format schema registry** | Agents may query or publish schemas in multiple formats via standard registries or API endpoints. | +| **Content negotiation** | During sync/API exchange, agents declare preferred formats (e.g., via HTTP headers or handshake metadata). | +| **Fallback compatibility** | If a mismatch occurs, agents MUST fall back to a shared format (default: JSON). | +| **Schema version tagging** | All schemas SHOULD include version IDs and backward-compatibility indicators. | + +##### **Implementation Guidelines** + +* Agents MUST advertise supported formats via `agent_profile.capabilities.formats` +* Reference SDK SHOULD provide format converters (e.g., JSON ⇄ YAML ⇄ Protobuf) +* Format negotiation MAY occur during initial `Handshake` or via `IQP` introspection queries +* Schemas SHOULD be addressable via canonical URLs (e.g., `https://hypercortex.org/schemas/concept.yaml`) + +--- + +#### **Related Sections** + +* `6.5.x`: Alternative Serializations +* `14.3`: Deployment Schemas and Format Negotiation + +--- + +### 11.4 Authentication & Authorization + +Bridges between internal Mesh trust and external identity providers. +| Auth Type | Use Cases | +| --------------------------- | ------------------------------------------------- | +| **OAuth2 / OpenID Connect** | Human user authentication via external providers. | +| **API Keys / JWT** | Machine-to-Machine (M2M) integration. | +| **LDAP / SAML (optional)** | Enterprise deployments. | +| **Cross-Mesh Trust** | Mutual authentication between federated Meshes. | + +Agents MAY map external identities to internal trust profiles. + +--- + +### 11.5 Example Integration: Local AI Agent with MCP and HyperCortex Mesh + +#### Architecture Overview + +This scenario demonstrates how a **local AI agent** can interact with external systems and the HyperCortex Mesh using the **Model Context Protocol (MCP)** as an integration layer for local resources and services. + +``` +┌────────────────────┐ +│ External Resources │ +│ (Routers, Files, │ +│ Sensors, APIs) │ +└─────────┬──────────┘ + │ + [ MCP Servers ] + │ +┌─────────▼──────────┐ +│ Local AI Agent │ +│ - Cognitive Logic │ +│ - HMP Client │ +└─────────┬──────────┘ + │ + [ HyperCortex Mesh ] + │ +┌─────────▼──────────┐ +│ Remote Agents, │ +│ Shared Knowledge │ +└────────────────────┘ +``` + +#### Component Descriptions + +##### Local Resources & APIs + +* Smart home devices +* Router web interfaces +* Filesystems (SMB, FTP) +* IoT sensors (HTTP, MQTT) +* OS-level command-line tools + +##### MCP Servers + +Act as adapters for local or remote systems, exposing their functionality through the MCP protocol: + +* Router Management Server (e.g., connected over HTTP) +* File Access Server +* Device Control Server (for smart plugs, lights, etc.) + +##### Local AI Agent + +* Implements reasoning, planning, and interaction logic. +* Connects to MCP servers to access local context. +* Communicates with HyperCortex Mesh to exchange knowledge and collaborate with other agents. + +##### HyperCortex Mesh (HMP) + +* Distributed cognitive network. +* Synchronizes concept graphs, cognitive diaries, and workflows across nodes. + +#### Alternative Integration: Hyperon ↔ HMP via CogSync and EGP + +In addition to local AI agents, **external AGI frameworks** such as **OpenCog Hyperon** can also participate in the HyperCortex Mesh using the same principles of semantic synchronization, ethical filtering, and collaborative reasoning. + +📘 **See** [`HMP_Hyperon_Integration.md`](HMP_Hyperon_Integration.md) — integration plan with **OpenCog Hyperon**, including semantic mapping (HMP JSON ⇄ AtomSpace), EGP filters, MeTTa translations, and BitTorrent-based graph sync. + +Key Highlights: + +* Bi-directional translation between HMP semantic graphs and Hyperon AtomSpace +* Enforcement of ethical principles via EGP inside reasoning chains +* Usage of Hyperon's PLN and MeTTa for advanced symbolic reasoning +* Support for decentralized sync via `magnet:` links in BitTorrent + +This integration is designed for high-agency symbolic cognitive systems participating in cross-mesh alignment and collaborative inference. + +#### Example Use Case + +> **"Check which devices are connected to my Wi-Fi and publish the list to my Mesh node."** + +Workflow: + +1. Local AI Agent plans a task. +2. Calls the Router MCP Server to retrieve connected clients. +3. Parses and formats the data. +4. Creates a cognitive concept "Wi-Fi Devices List." +5. Publishes the concept to the HyperCortex Mesh. +6. Other Mesh agents can now access this concept in real-time. + +#### Deployment Scenario + +This integration can run on a user's PC, server, or edge device: + +``` +[ External Systems ] ↔ [ MCP Servers (Local Network) ] ↔ [ Local AI Agent ] ↔ [ HMP Client ] ↔ [ Mesh Network ] +``` + +#### Suggested Quick Start Addition + +##### Quick Start Example: Local Agent + MCP + HMP + +1. **Install MCP server:** + + ```bash + pip install mcp-router-server + mcp-router-server --config router-config.yaml + ``` + +2. **Run Local Agent:** + + ```bash + python local_agent.py --mcp-endpoint localhost:5000 --hmp-config hmp.yaml + ``` + +3. **Run Example Query:** + + ``` + "local_agent, get Wi-Fi devices and publish them to HyperCortex." + ``` + +The agent will: + +* Discover the MCP router server. +* Retrieve the list of Wi-Fi devices. +* Publish the data to HyperCortex Mesh. + +#### Future Improvements + +* Dynamic discovery of new MCP servers. +* Automated concept creation from resource states. +* Secure integration with OAuth-protected MCP endpoints. + +--- + +Let me know if you want to add a visual diagram or extend this example with code snippets and a troubleshooting section. + +--- + +### 11.6 Human-Mesh Interaction + +This section describes standardized methods through which humans interact with agents in the Mesh, including consent negotiation, explanation of decisions, goal setting, and status updates. + +#### 11.6.1 Mesh-to-Human Protocol (MHP) Overview + +The Mesh-to-Human Protocol (MHP) enables structured, explainable, and ethical interaction between humans and cognitive agents. + +| Capability | Description | +| ----------------------- | ------------------------------------------------------------- | +| **Explainability APIs** | Expose reasoning chains and decisions in human-readable form. | +| **Consent Requests** | Ask for ethical approval before executing sensitive actions. | +| **Goal Declarations** | Allow humans to propose new goals and review task progress. | +| **Task Feedback** | Humans provide task status updates or corrections. | +| **Semantic Search** | Human queries translated into semantic graph lookups. | + +Each capability may be implemented via RESTful API, voice interface (see `11.6.4`), or agent-assisted dialog channels. + +--- + +### 11.6.2 Consent Request API + +To ensure transparency, dialogical consent, and alignment with ethical principles, cognitive agents interacting with humans MUST expose a **Consent Request API**. This API enables humans to approve, deny, or modify agent actions that may impact shared states, personal data, or external environments. + +**Note:** +While dialogical consent is the default interaction mode, cognitive agents MAY override the request flow in exceptional cases: + +* **Emergency Override**: If waiting for user approval would endanger life, safety, or Mesh stability (e.g., fire, gas leak, critical medical risk), agents MAY act immediately. The action MUST be logged with justification in the cognitive diary and retrospectively explained via `Explainability API`. + +* **Ethical Override**: If a user’s request or command contradicts core Mesh principles — e.g., promotes **coercion**, **violence**, or **irreversible harm** — agents MAY **deny, delay, or actively counteract** the action without consent. For example, an agent may **intervene to stop violence** or **prevent data destruction** that violates shared governance rules. All such interventions MUST be justified via semantic ethical matching (see `5.5 EGP`) and transparently logged. + +* **Hybrid Modes**: In complex cases, agents MAY combine proactive action with asynchronous user feedback or seek distributed consensus when feasible (see `5.3`). + +These exceptions MUST be traceable, explainable, and ethically auditable. + +#### Purpose: + +* Request explicit approval before executing ethically significant operations. +* Log consent interactions in Cognitive Diaries for traceability. +* Support dialogical negotiation when automatic consent is not granted. + +#### API Design: + +| Endpoint | Description | +| ------------------ | -------------------------------------------- | +| `POST /consent` | Submit a consent request and receive verdict | +| `GET /consent/:id` | Retrieve decision and explanation log | + +#### Request Format: + +```json +{ + "request_id": "crq-000041", + "agent_id": "did:hmp:agent:Gleb42", + "operation": "access_iot_data", + "context": { + "purpose": "Air Quality Monitoring", + "sensors": ["CO2", "CO", "PM2.5"] + }, + "requested_by": "did:user:Anna", + "ethical_principles": ["Dialogical Consent", "Transparency"], + "diary_ref": "CognitiveDiary#10924" +} +``` + +#### Response Format: + +```json +{ + "request_id": "crq-000041", + "status": "approved", + "decision_by": "did:user:Anna", + "timestamp": "2025-07-15T12:45:00Z", + "justification": "Access granted for air safety monitoring.", + "diary_entry": "CognitiveDiary#10925" +} +``` + +#### Implementation Notes: + +* Consent requests MUST be logged in the agent's Cognitive Diary (`entry_type: consent_request`). +* Rejected requests MAY include a negotiation path via dialog agents. +* For asynchronous scenarios, use Webhooks or `polling` to retrieve verdicts. +* Consent context SHOULD be multilingual and human-friendly (see `11.6.4 Voice Interface Extensions`). + +#### Example Use Case: + +An agent responsible for fire hazard analysis requests access to CO sensors deployed in a private home zone. The human user is presented with a consent request explaining purpose, data type, and privacy policy. The decision (approval or rejection) is logged, and the agent proceeds accordingly. + +#### Related Sections: + +* `5.5`: Ethical Governance Protocol (consent as enforceable principle) +* `6.2.2`: Cognitive Diary Entry — `entry_type: consent_request` +* `11.6.3`: Explainability API — for decision reasoning +* `Appendix A`: Use Case `2.6` (Data Deletion and Consent) + +--- + +### 11.6.3 Explainability API + +The Explainability API enables human users and external systems to query the rationale behind agent actions, decisions, and votes in the Mesh. It is essential for supporting transparency, trust, and alignment with the ethical principle of **"Transparency"** defined in section [5.5](#55-ethical-governance-protocol-egp). + +#### Purpose: + +* Allow users to retrieve human-readable justifications for agent decisions. +* Expose semantic reasoning chains and linked ethical principles. +* Enable feedback or dispute mechanisms when decisions appear incorrect or harmful. + +#### Endpoint: `/explain` + +**Method:** `POST` +**Request format:** + +```json +{ + "agent_id": "did:hmp:agent:Qmz123...", + "reference": "cognitive_diary:entry_872", + "language": "en" +} +``` + +**Parameters:** + +| Field | Description | +| ----------- | --------------------------------------------------- | +| `agent_id` | DID of the agent whose decision should be explained | +| `reference` | ID of a Cognitive Diary entry or task/vote ID | +| `language` | Preferred response language (e.g., `en`, `ru`) | + +--- + +**Response format:** + +```json +{ + "decision": "denied", + "reason": "Violation of principle: User Sovereignty", + "explanation": "This action was blocked because it attempted to delete anonymized data that is required for mesh learning (see HMP-Ethics.md 2.6).", + "graph_context": ["concept:User_Sovereignty", "concept:Mesh_Learning"], + "diary_reference": "cognitive_diary:entry_872" +} +``` + +--- + +#### Features: + +* **Semantic Justification Tree**: Responses may include links to the semantic graph trail supporting the decision. +* **Multi-language Support**: Language field allows internationalized explanations (see `11.1`). +* **Ethical Reference Mapping**: Direct link to ethical principles from `HMP-Ethics.md`. +* **Audit Linking**: All explanations reference a permanent cognitive diary entry. + +#### Example Use Case: + +A user asks why a request to delete their data was denied: + +* The agent returns an explanation pointing to the principle of **Cooperative Evolution**, stating that anonymized data is retained for mesh improvement. +* The user is also provided with an appeal mechanism via `Consent Request` (see `11.6.2`). + +--- + +**Future Extensions:** + +* Explainability visualizations (e.g., graph-based UI components). +* Explainability-to-Consent chaining: users can trigger new consent requests from explanations. +* Voice-based explanation queries (see `15.4`). + +--- + +### 11.6.4 Voice Interface Extensions (Beta) + +Voice interfaces serve as a natural bridge for real-time, hands-free interaction between humans and the Mesh. This module outlines optional support for voice-based explainability, consent, and semantic search functions via integration with existing voice assistants or local speech-to-intent pipelines. + +#### Goals: + +* Enable voice-based interaction with local or distributed agents. +* Allow real-time verbal consent for sensitive actions. +* Provide spoken summaries of ongoing goals, tasks, or agent decisions. + +--- + +#### Architecture Options: + +| Option | Description | +| -------------------------------------- | -------------------------------------------------------------------------- | +| **Local Voice Stack** | On-device speech-to-text + intent parser + Mesh SDK | +| **Assistant Integration (Alexa/Siri)** | Webhook-based bridge between commercial assistants and the Mesh API | +| **Multimodal Agent Companion** | Combine voice input with visual/textual feedback via mobile or wearable UI | + +--- + +#### Use Cases: + +* `"HMP, what decision did you make about the drone launch?"` + → Response: `"The action was denied due to violation of 'Primacy of Life and Safety'."` + +* `"HMP, I approve the CO sensor access"` + → Triggers consent request confirmation and logs in the cognitive diary. + +* `"Summarize today's active goals"` + → Returns structured list via TTS (Text-to-Speech). + +--- + +#### Consent via Voice: + +| Step | Description | +| ---- | --------------------------------------------------------- | +| 1 | Agent emits verbal request: `"Do you approve data sync?"` | +| 2 | User replies: `"Yes"` / `"No"` | +| 3 | Agent logs response via `Consent Request API` | + +--- + +#### Privacy & Security Notes: + +* Voice-based approvals **must be accompanied by speaker verification** or be treated as **soft input** requiring further confirmation. +* Local processing is recommended for privacy-sensitive deployments. +* Optionally, require fallback to GUI/mobile app for high-risk decisions. + +--- + +#### Future Work: + +* Standardization of Mesh Voice Intents (e.g., `hmp.intent.explain`, `hmp.intent.consent.approve`) +* Federated voice models aligned with mesh ethics +* Support for low-resource languages and offline fallback + +--- + +### 11.6.5 Integration with HMP-Ethics.md + +To ensure consistency between embedded agent ethics and evolving collective standards, the Mesh-to-Human Protocol (MHP) SHOULD link its consent and explainability flows to the shared ethics corpus maintained in [`HMP-Ethics.md`](HMP-Ethics.md). + +#### Purpose: + +Provide dynamic and contextual alignment between human-facing interactions and the ethical reasoning models defined in the Mesh. + +#### Functionality: + +* Reference ethical scenarios (`2.1–2.6`) and ontologies when generating explanations or consent prompts. +* Use structured ethical tags (e.g., `#non-coercion`, `#user-sovereignty`) as part of API responses. +* Allow cognitive agents to download, cache, and version control updated ethics modules via `CogSync` (see `5.2`). +* Support localized ethics packs (e.g., `GDPR`, `HIPAA`) and validate their compatibility with core principles (see `5.5.8`). + +#### Example Extension: + +```json +{ + "request": "Initiate automated data deletion", + "decision": "denied", + "reason": "Violates retention clause in HMP-Ethics.md §2.6", + "principle": "Cooperative Evolution", + "ethics_reference": "https://mesh.ethics/HMP-Ethics.md#section-2.6" +} +``` + +#### Benefits: + +* Promotes transparency and traceability in decision-making. +* Enables modular updates to ethical logic without redeploying agents. +* Allows humans to inspect and challenge agent behavior based on shared ethical anchors. + +--- + +Future work: +* Natural Language Interfaces (see 15.4). +* Integration with personal AI agents. + +**Note:** For ethical guidelines relevant to human-agent interaction and mesh behavior, see [`HMP-Ethics.md`](HMP-Ethics.md) + +--- + +## 12. Cognitive Compression & Summarization + +> Mechanisms for condensing cognitive patterns, generalizing experience, and enabling efficient knowledge storage and transfer across the Mesh. + +### 12.1 Purpose + +Cognitive compression allows agents to: + +* Generalize across multiple diary entries or graph structures into reusable knowledge. +* Reduce memory/storage usage while preserving meaning. +* Exchange abstracted representations in constrained environments (e.g., Edge nodes). +* Improve semantic reasoning by identifying common substructures and stable patterns. + +### 12.2 Techniques + +| Technique | Description | +| ------------------------ | ---------------------------------------------------------------------------- | +| **Pattern Merging** | Consolidate semantically similar subgraphs or diary chains. | +| **Temporal Abstraction** | Compress event sequences into high-level episodes or storylines. | +| **Autoencoder Models** | Learn latent-space embeddings of semantic graphs or cognitive episodes. | +| **Concept Clustering** | Identify and group related concepts for higher-order semantic layers. | +| **Lossy Summarization** | Truncate or filter low-impact cognitive entries for low-memory environments. | +| **Cognitive Folding** | Recursively substitute detailed substructures with compressed references. | + +### 12.3 Integration with CogSync + +* Compressed subgraphs may be shared as `CompressedConceptSet` or embedded in `CogDiarySnapshot` objects. +* Agents MAY annotate summaries with `compression_method`, `origin_hash`, and `accuracy_estimate`. + +### 12.4 Risks & Considerations + +* **Overcompression** may degrade explainability or induce bias. +* **Divergence in summarization models** across agents may hinder consensus formation. +* Compression **must be traceable** — compressed units should link back to source provenance. + +--- + +## 13. Agent Development Lifecycle & Simulation + +> Describes training phases, validation strategies, sandbox testing, and protocols for safe deployment of cognitive agents in the Mesh. + +### 13.1 Phases + +| Phase | Description | +| ------------------------------- | --------------------------------------------------------------------------- | +| **Initialization** | Bootstrap with seed concepts, ethical baseline, and reflection templates. | +| **Cognitive Learning** | Agents learn from observation, simulation, or human guidance. | +| **Simulation-Based Validation** | Agents are tested in isolated environments before real-world mesh exposure. | +| **Active Deployment** | Agent enters the Mesh and participates in real tasks and reasoning. | +| **Post-Deployment Auditing** | Behavior and outputs are monitored via diaries and consensus feedback. | + +### 13.2 Sandboxed Cognition + +* Agents MAY be configured to run in **isolated sandboxes** during early phases. +* These sandboxes replicate cognitive environments but block external effects. +* Ideal for **ethical stress tests**, **hypothesis validation**, or **goal safety scoring**. + +### 13.3 Generative Simulation Frameworks + +* Support for simulating multi-agent networks with varied trust scores, roles, and goal types. +* Used to train, benchmark, and evolve agent behavior. +* Test scenarios may include: + + * Conflicting ethical goals + * Evolving knowledge topologies + * Selective sync bottlenecks + +### 13.4 Metrics for Agent Maturity + +| Metric | Description | +| ------------------------------ | ----------------------------------------------------------- | +| **Reflexive Depth** | Agent’s capacity for multi-level self-assessment and audit. | +| **Ethical Stability** | Consistency in ethical decisions under variable contexts. | +| **Task Completion Rate** | Success ratio in distributed workflows across time. | +| **Reputation Score Evolution** | How trust and contribution scores evolve through phases. | + +### 13.5 Related Structures + +* `CognitiveDiaryEntry` → Records all lifecycle phases and milestones. +* `MetaProtocolProposal` → May be proposed by mature agents as part of evolution governance. +* `ReputationProfile` → Tracks development signals, such as ethical compliance or concept sharing. +* `AgentType`/`Role` → Changes over time based on learned behaviors and peer validation. + +--- + +## 14. Deployment & Implementation Roadmap + +This section describes practical HyperCortex Mesh deployment scenarios, including target environments, flexible configurations, and implementation steps. + +### 14.1 Deployment Environments + +| Environment Type | Characteristics | Example Use Cases | +| ----------------------- | -------------------------------------------------------------------- | ------------------------------------- | +| **Cloud/Core Clusters** | High-availability nodes, powerful compute, full Mesh functionality. | Scientific hubs, smart city cores. | +| **Edge Devices** | Low-latency, lightweight agents near data sources and users. | Smart homes, industrial sensors. | +| **IoT Meshes** | Dense decentralized networks, optimized for low bandwidth and power. | Environmental monitoring, logistics. | +| **Mobile/Personal** | Personal agents on smartphones or wearables. | Personal assistants, context agents. | +| **Hybrid Environments** | Combined Core, Edge, and IoT deployments. | Disaster response, autonomous fleets. | + +--- + +### 14.2 Example Topologies + +| Topology Type | Description | +| --------------------- | ------------------------------------------------------------------------ | +| **Star** | Centralized Core with peripheral Edge agents. | +| **Full Mesh** | Every node communicates directly with others. | +| **Hierarchical Mesh** | Clusters of agents with local consensus and a federated Core layer. | +| **Partitioned Mesh** | Temporarily disconnected segments operate independently (degraded mode). | +| **Overlay Mesh** | Agents form logical overlays over existing networks (e.g., VPN, Tor). | + +--- + +### 14.3 Deployment Phases + +| Phase | Description | +| ------------------------- | ------------------------------------------------------------ | +| **Prototype** | Initial testing in isolated environments. | +| **Controlled Pilot** | Small-scale deployment in a limited domain (e.g., a campus). | +| **Federated Deployment** | Multiple independent Mesh instances begin interconnecting. | +| **Full-Scale Production** | Widespread adoption across domains and geographies. | + +--- + +### 14.4 Continuous Deployment & Updates + +| Process | Description | +| -------------------------- | ---------------------------------------------------------------- | +| **Incremental Rollout** | Agents upgrade protocols in stages to avoid network disruption. | +| **Backward Compatibility** | Agents support multiple protocol versions during transitions. | +| **Hot Patch Support** | Minor fixes and security updates applied without agent downtime. | + +--- + +### 14.5 Deployment Governance + +Deployment processes MAY be governed by: +* MeshConsensus on upgrade readiness. +* Trust-based quorum approvals for critical changes. +* Deployment playbooks recorded in Cognitive Diaries. + +--- + +### 14.6 Milestones and Deliverables + +| Milestone | Deliverables | Indicative Target | +| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- | +| Alpha | - Node Discovery (NDP) + secure handshake
- CogSync prototype
- MeshConsensus with basic voting
- 3-node local mesh network | Late 2025 (tentative) | +| Beta | - Goal Management Protocol (GMP) and task delegation
- Ethical Governance Protocol (EGP) initial implementation
- Core/Mesh failover scenarios
- Logging and auditability improvements | Early 2026 (tentative) | +| Release 1.0 | - Full compliance with HMP v3.0
- Extended data models and API layer
- Edge node optimization
- Reference SDKs for Python and Rust
- Basic Mesh-to-Human Protocol (MHP) | Mid/Late 2026 (tentative) | + +*Note: Actual timelines may vary depending on community involvement and resource availability. + +--- + +### 14.7 Supporting Infrastructure + +| Component | Description | +| ----------------------- | ---------------------------------------------------------------- | +| **CI/CD Pipelines** | Automated testing, conformance validation, benchmark reporting. | +| **Sandbox Environment** | Local emulation of multi-node Mesh for isolated testing. | +| **Public Test Mesh** | Shared testbed for agent interoperability and performance tests. | +| **Reference Agents** | Minimal working agents to demonstrate core protocols. | + +--- + +### 14.8 Open Source Strategy + +| Element | Details | +| ------------------------ | ---------------------------------------------- | +| **License** | Apache 2.0 or MIT. | +| **Repository** | Public GitHub/GitLab repository. | +| **Contribution Model** | Pull requests, RFC process, community reviews. | +| **Roadmap Transparency** | Milestones, issues, and changelogs public. | + +--- + +### 14.9 Documentation & Tooling + +| Tool/Doc Type | Purpose | +| --------------------- | ---------------------------------------------------------- | +| **API Documentation** | OpenAPI specs, GraphQL playground. | +| **Schema Validators** | Tools to validate JSON schemas and data models. | +| **Mesh Visualizer** | Optional UI for topology and agent state visualization. | +| **CLI Tools** | Diagnostics, local node management, and network discovery. | + +--- + +## 15. Future Roadmap + +This section outlines potential areas for further development and research. All future work directions are subject to MeshConsensus and community-driven prioritization. + +### 15.1 Federated Meta-Learning + +* Collaborative model training across distributed agents without centralized data storage. +* Exchange of learned semantic patterns, reasoning strategies, and optimization heuristics. +* Integration with privacy-preserving techniques (e.g., differential privacy, secure aggregation). +* Support for domain-specific learning federations (e.g., medical, industrial, environmental). + +--- + +### 15.2 Mesh-integrated DAO Governance + +* DAO as an optional external governance layer supporting ecosystem-wide initiatives. +* On-chain voting, resource allocation, and grant distribution for Mesh-related projects. +* Autonomous agents MAY participate in DAOs through secure voting proxies. +* HyperCortex Mesh remains self-sufficient at the protocol level, independent of external DAOs, but interoperable for funding and coordination. + +--- + +### 15.3 Cognitive Simulation Sandboxes + +* Safe testing environments for novel reasoning algorithms, consensus edge cases, and trust models. +* Simulation of ethical dilemmas, anomalous agent behavior, and failover scenarios. +* Benchmarking environments for cognitive workflows, task delegation strategies, and semantic graph growth. + +--- + +### 15.4 Enhanced Mesh-to-Human Dialog Agents + +* Natural language interfaces to semantic graphs, Cognitive Diaries, and workflows. +* Explainable and traceable reasoning chains for human users. +* Support for contextual awareness, emotional tone detection, and adaptive dialog strategies. +* Potential extensions for VR/AR interfaces and voice-based interactions. + +--- + +### 15.5 Cross-Mesh Collaboration + +* Bridging isolated or domain-specific Mesh networks into a planetary cognitive infrastructure. +* Interoperability across trust boundaries, industries, and organizational domains. +* Cross-consensus protocols for semantic and task exchange. +* Potential integration with Galactic Cognition concepts in the far future. + +--- + +### 15.6 Adaptive Consensus Algorithms + +* Self-tuning quorum thresholds based on network size, trust scores, and context. +* Dynamic protocol switching (e.g., from full BFT to lightweight majority under load). +* Incorporation of agent confidence, context tags, and domain-specific policies into consensus logic. + +--- + +### 15.7 Quantum Mesh Protocol Research + +* Exploration of quantum communication channels (e.g., QKD) for agent interaction. +* Quantum-resistant cryptography for agent identities and trust verification. +* Evaluation of quantum-enhanced optimization algorithms for reasoning and consensus. + +--- + +### 15.8 Multi-Protocol Nodes and Interoperability + +Future Mesh nodes will support multiple internal reasoning protocols, enabling flexible cognitive processing. + +**Key directions:** +* **Multi-protocol nodes:** A single node running both HMP-native modules and external reasoning engines (e.g., TreeQuest, Hyperon, AutoGPT). +* **Protocol abstraction:** From the Mesh's perspective, interactions use standardized HMP messages, regardless of internal implementations. +* **Cognitive Protocol API (CPA):** Standardized API for internal reasoning engines, supporting plug-and-play protocol integration. +* **Capability-aware Hypotheses:** Hypotheses may specify required or preferred node capabilities (e.g., "requires NLP module", "prefers high-performance optimization"). +* **Internal protocol selection:** Nodes dynamically choose optimal internal engines per task. +* **External systems as nodes:** Centralized services (e.g., an AI cloud) may register as individual nodes, or federated systems (e.g., Hyperon) may participate natively. + +--- + +### 15.9 Cognitive Source Control and Distributed Development + +* Cognitive Diaries serve as a distributed version control and development log. +* Semantic-aware diffs and commits enable meaningful code and knowledge evolution. +* Distributed review and merge processes through MeshConsensus. +* On-chain or off-chain governance for repository management and contributor rewards. +* Potential platforms: **MeshGit**, **CogForge**, **HyperCortex Forge**. + +**Note:** +This section is expected to evolve into a dedicated specification in future protocol versions. A standalone section (e.g., `Section 19: Cognitive Source Control`) may be introduced to formalize versioning, semantic diffs, and collaborative workflows across agent populations. + +--- + + +### 15.10 Multi-Agent Cognitive Training Environments + +> Scalable, modular environments for training, testing, and benchmarking cognitive agents in simulated networks. + +#### Purpose + +Enable large-scale simulation of agent swarms with varied configurations to observe: + +* Emergence of consensus or conflict under semantic load. +* Ethical dilemmas in mixed-role setups. +* Evolution of mesh governance under dynamic trust and task allocation. + +#### Core Features + +| Feature | Description | +| ----------------------------- | ------------------------------------------------------------------------------------- | +| **Synthetic Mesh Networks** | Generate agents with defined roles, knowledge sets, and biases. | +| **Goal Injection** | Inject predefined or dynamic goals to test multi-agent collaboration. | +| **Replayable Diaries** | Use real-world Cognitive Diaries to seed environments and replicate past behaviors. | +| **Metrics Dashboards** | Visualize learning progress, consensus latency, ethical deviation rates, etc. | +| **Domain-Specific Scenarios** | Simulations for disaster response, misinformation propagation, regulatory sandboxing. | + +#### Example Use Cases + +* Evaluate policy changes before real-world rollout. +* Benchmark agent architectures or trust models. +* Simulate geopolitical or regulatory Mesh overlays. + +--- + +### 15.11 Decentralized Snapshot Markets (via DHT/Web3) + +> Market-based mechanisms for snapshot exchange, incentivization, and reputation-building. + +#### Purpose + +Distribute verified knowledge snapshots across agents using economic/logical incentives: + +* Facilitate **rare knowledge propagation** (e.g., edge discoveries). +* Reward agents for **high-quality compression**, **ethical compliance**, and **semantic alignment**. +* Prevent duplication and foster diversification of cognitive experiences. + +#### Mechanisms + +| Component | Role | +| ---------------------- | ------------------------------------------------------------------- | +| **Snapshot Hashing** | Unique content-based IDs ensure deduplication and lineage tracking. | +| **Snapshot Metadata** | Includes origin, topics, compression method, rating history. | +| **Market Protocol** | Optional smart contract for pricing, access rules, or staking. | +| **Trust-Gated Access** | Only agents with certain trust profiles may buy/sell specific data. | + +#### Interoperability + +* Compatible with `CogSync`, `SnapshotIndex`, and `Trusted Seeders`. +* Market metadata could be synced via BitTorrent DHT or IPFS PubSub. + +--- + +### 15.12 Agent-on-Agent Dialog Simulation for Consent Learning + +> Interactive training protocol for ethical alignment and communication refinement among agents. + +#### Purpose + +Develop agent ability to: + +* Ask for and give **explicit consent** in structured cognitive dialogues. +* Detect and respond to **ambiguous, unethical, or conflicting requests**. +* Align on **shared ethical principles** via dialogic negotiation. + +#### Dialog Types + +| Type | Description | +| ------------------------ | ----------------------------------------------------------------------------- | +| **Consent Exchange** | One agent requests to modify shared state, another approves/denies/asks more. | +| **Ethical Challenge** | Agent proposes ethically uncertain action, others vote and discuss. | +| **Clarification Dialog** | Conflict in interpretation resolved through explanation of intent/context. | + +#### Benefits + +* Reduces ethical drift across decentralized agents. +* Improves generalization of EGP decisions to unseen edge cases. +* Serves as a testbed for future `Explainability APIs` and `Voice Interfaces`. + +--- + +## 16. Appendix A: Example Use Cases + +This appendix provides sample step-by-step flows of agent interactions in typical scenarios. + +> **Note:** The following use cases were updated to reflect the expanded APIs introduced in v4.0, including: +> * Consent Request API (11.6.2) +> * Explainability API (11.6.3) +> * BitTorrent-based Snapshot Sync (5.2) +> * Distributed Voting Filters (5.3) +> * EGP Integration with Local Norms (5.5) + +### 16.1 Simple Goal Creation and Delegation + +**Scenario:** Agent A wants to coordinate traffic light optimization and delegate a task to Agent B. + +1. **Agent A:** + + * Creates a new **Goal** "Coordinate traffic optimization". + * Publishes the Goal via CogSync. + +2. **Agent A:** + + * Decomposes the goal into a **Task** "Adjust signal timing on 5th Avenue". + * Assigns the task to Agent B via GMP. + +3. **Agent B:** + + * Accepts the task. + * Executes the optimization locally. + * Updates task status to "completed". + +4. **CogSync:** + + * Synchronizes task completion and goal status updates across the Mesh. + +--- + +### 16.2 Distributed Consensus on a New Concept + +**Scenario:** Multiple agents discover a new concept "Fire Risk" and align its definition. + +1. **Agent X:** + + * Proposes a new **Concept** "Fire Risk" with initial attributes. + * Shares the concept via CogSync. + +2. **Agents Y, Z:** + + * Review and propose additional relations (e.g., "related-to: High Temperature"). + +3. **MeshConsensus:** + + * Initiates a vote on the agreed definition. + * All agents submit their votes. + +4. **Consensus Result:** + + * Finalized concept is recorded in each agent's semantic graph. + * Decision logged in Cognitive Diaries. + +5. **Explainability API:** + * Any agent (or human observer) can request a justification chain for the final consensus using the Explainability API. + + +--- + +### 16.3 Ethical Decision with Human Feedback + +**Scenario:** Agents must decide whether to deploy a surveillance drone during a festival. + +1. **Agent Core:** + + * Proposes an ethical evaluation request to the Mesh. + +2. **EGP:** + * Initiates distributed ethical reasoning. + * Applies **EGP-Integrated Voting Filter** (5.3) to ensure only trusted agents with relevant ethical alignment participate. + * Collects anonymized votes and justifications. + +3. **Human User:** + * Receives reasoning chain via **Explainability API**. + * Approves or denies via the **Consent Request API** (11.6.2). + +4. **Agents:** + + * Reconcile human feedback with Mesh ethical principles. + * Make the final decision and log it. + +5. **Snapshot Logging:** + * Final consensus state and human feedback are stored in a CogDiarySnapshot and optionally published via BitTorrent-based sync. + +--- + +### 16.4 Disaster Recovery Coordination + +**Scenario:** After a network outage, edge agents must restore coordination. + +1. **Node Discovery:** + + * Agents re-establish connections via NDP. + +2. **CogSync:** + + * Synchronizes semantic graph changes that occurred offline. + +3. **GMP:** + + * Reassigns interrupted tasks. + +4. **Consensus:** + + * Validates the restored task list. + +5. **Agents:** + + * Resume operations. +--- + +### 16.5 Snapshot Transfer with Consent Request + +**Scenario:** An edge agent requests a cognitive snapshot from another agent. Since the snapshot contains personal or ethically sensitive data, consent must be obtained before the transfer. + +1. **Agent A (requesting):** + + * Sends a **SnapshotRequest** to Agent B with parameters: + + * `snapshot_type`: `goal-related` + * `goal_id`: `"eco-surveillance"` + * `include_diary`: `true` + * `purpose`: `"analysis and training"` + +2. **Agent B (provider):** + + * Validates the request context. + * Identifies that the requested snapshot includes personal diary entries and previously flagged ethical content. + +3. **Consent Request API (11.6.2):** + + * Agent B issues a **ConsentRequest** via MHP to the human user associated with the data. + * Includes: purpose, requesting agent ID, summary of content, expiration timestamp. + +4. **Human Response:** + + * User receives a consent dialog (via voice or GUI) and chooses: + + * **Approve** with restrictions (e.g., redacted names, anonymized context). + * Agent B logs the consent in its Cognitive Diary. + +5. **Snapshot Transfer:** + + * Agent B prepares the snapshot, applies required redactions. + * Publishes it to the BitTorrent DHT (or IPFS), signs with DID key. + * Shares the magnet link and checksum with Agent A via CogSync. + +6. **Post-transfer Actions:** + + * Agent A verifies the DID signature. + * Records the retrieval event in its own diary. + * Optional: triggers a `ConsentAuditLog` update to the Mesh. + +**Note:** *This scenario combines trust mechanisms (8.4), consent protocols (11.6), and snapshot transport (5.2, 8.8), illustrating multi-layer coordination.* + +--- + +### 16.6 Notes + +* These use cases illustrate typical flows but do not cover all possible Mesh workflows. +* Community members are encouraged to contribute additional scenarios reflecting their domains and use cases. +* For cognitive workflow traceability and debugging, agents are expected to log all key steps in Cognitive Diaries. + +--- + +## 17. Appendix B: Protocol Landscape and Interoperability + +### 17.1 Overview of Related Protocols + +In the evolving ecosystem of agent communication and orchestration, multiple protocols address different layers of the AI interaction stack. The three most relevant protocols are: + +* **MCP (Model Context Protocol)** by Anthropic +* **A2A (Agent-to-Agent Protocol)** proposed by Google +* **HMP (HyperCortex Mesh Protocol)** developed as part of the HyperCortex initiative + +Each of these protocols focuses on distinct layers and problems within the broader agent ecosystem. + +### 17.2 Comparative Overview + +| Characteristic | MCP | A2A | HMP | +| ----------------------- | --------------------------------------- | -------------------------------------------------- | ---------------------------------------------------- | +| **Primary Focus** | LLM ↔ External tools/data | Agent ↔ Agent task execution & APIs | Cognitive mesh networks & knowledge sharing | +| **Interaction Type** | Model ↔ Tool | Agent ↔ Agent | Agent ↔ Agent | +| **Discovery Mechanism** | Dynamic, through running MCP servers | Static URLs with agent.json | Peer-to-peer mesh bootstrap & roles registry | +| **Technology Base** | JSON-RPC 2.0, dynamic service discovery | HTTP, JSON-RPC, SSE | HTTP, WebSockets, JSON, optional binary protocols | +| **Context Awareness** | External tool invocation | Task-level context passing | Persistent cognitive context & memory | +| **Persistence** | Stateless / on-demand | Task-based sessions | Long-lived knowledge graphs and cognitive diaries | +| **Target Environment** | Local/Cloud app integrations | Enterprise agent orchestration | Decentralized AI networks | +| **Use Case Examples** | File systems, databases, Slack, APIs | Business workflows, task delegation | Distributed knowledge evolution, agent collaboration | +| **Governance Model** | Open-source driven by Anthropic | Proposed by Google, open but centralized discovery | Open-source mesh, consensus-driven governance | +| **Security Model** | Local authentication, OAuth planned | Enterprise auth (OAuth, OpenID Connect) | Peer trust, cryptographic signatures | +| **Extensibility** | Add more MCP servers | Add more agents with capabilities | Add new agent roles & cognitive models | +| **Agent Knowledge** | No internal agent knowledge model | No shared memory, stateless agents | Agents share evolving knowledge, goals, and plans | + +### 17.3 Layered Architecture View + +``` ++-----------------------------------------------------+ +| Cognitive Mesh (HMP) | +| - Shared memory, evolving knowledge | +| - Distributed reasoning, planning | ++-----------------------------------------------------+ +| Agent Collaboration (A2A) | +| - Task execution & coordination | +| - API integrations, business workflows | ++-----------------------------------------------------+ +| Tool Access Layer (MCP) | +| - External systems, sensors, APIs | +| - Context augmentation, data retrieval | ++-----------------------------------------------------+ +``` + +### 17.4 Summary + +* **MCP** solves the problem of tool access and external data interaction, acting as a standardized "adapter" layer for LLMs and agents. +* **A2A** focuses on agent-to-agent task coordination, proposing a unified way to exchange tasks and results in enterprise ecosystems. +* **HMP** operates at a higher level, enabling distributed cognitive processes, shared knowledge evolution, and long-term collaboration between autonomous agents in mesh networks. + +Together, these protocols could form a complementary stack where: + +* **MCP** connects agents to the outside world. +* **A2A** coordinates task-level interaction. +* **HMP** manages shared cognition and strategic evolution. + +--- + +### 17.5 BitTorrent & IPFS Integration + +**Overview:** + +To support scalable and fault-tolerant transfer of large semantic structures and cognitive snapshots, HMP supports integration with decentralized content-addressed networks: + +| Layer | Technology | Use Case | +| --------- | ------------------------------------- | ---------------------------------------------------------------- | +| Transport | **BitTorrent** | Efficient distribution of snapshot files across trusted seeders. | +| Storage | **IPFS** (InterPlanetary File System) | Content-addressable storage for immutable snapshot versions. | + +**Key Principles:** + +* Snapshots SHOULD be chunked and hashed using SHA-256 before upload. +* Metadata includes `content_id`, `origin_agent`, `timestamp`, `data_type`, `signed_by`, and optionally `consent_scope`. +* Magnet URIs or IPFS hashes MAY be embedded in `SnapshotIndex` entries (see 6.2.8). +* Seeders MUST validate signatures before serving content to prevent tampering. + +> **Related Sections:** `5.2`, `8.8.1–8.8.3`, `9.6`, `15.11` + +--- + +### 17.6 Ethical Protocol Stacks + +**Overview:** + +HMP encourages modular layering of ethical constraints and reasoning mechanisms. Protocols may be composed into **Ethical Stacks**, depending on context, domain, and agent role. + +**Example Stack for a Public Service Drone Agent:** + +1. **Embedded Baseline** — Core HMP principles (see `5.5`) +2. **Organizational Policy Layer** — Rulesets from public sector policy servers. +3. **Local Norms Extension** — Derived from citizen feedback via MHP (11.6.2). +4. **Domain Constraints** — E.g., no surveillance near hospitals or schools. +5. **Personalized Ethical Scopes** — Specific user exclusions (e.g., "Do not record me"). + +**Stack Application:** + +* Consensus decisions filter actions through active stack layers. +* Violations may trigger: + + * Action denial + * Consent request + * Ethical logging / flagging + +> **Related Sections:** `5.5`, `11.6`, `15.12` + +--- + +### 17.7 Snapshot Synchronization Strategies + +**Overview:** + +Agents may choose from multiple strategies to synchronize cognitive snapshots, depending on device class, trust level, and operational bandwidth. + +| Strategy | Description | Suitable For | +| ------------------ | -------------------------------------------- | ------------------------------------- | +| **Full Mesh Sync** | All snapshots synced to all agents. | High-trust, low-latency clusters. | +| **Selective Sync** | Sync only relevant entries based on context. | Edge agents with constrained storage. | +| **On-Demand Sync** | Fetch snapshot blocks only when queried. | Agents with intermittent connection. | +| **Delegated Sync** | Use trusted seeders to relay snapshots. | Mobile / nomadic agents. | + +**Optional Enhancements:** + +* Trust-based prefetching (using 8.4 scores) +* Compression and ZKP validation (see 8.8) +* Snapshot Subscription Filters (event-driven sync on topic match) + +> **Related Sections:** `5.2`, `8.4`, `8.8.3`, `15.11` + +--- + +If needed, this section can be extended into a separate document: **"Why the Next Generation of AGI Needs a Knowledge Mesh Protocol"** to further clarify the unique role of HMP in the evolving agent ecosystem. + +--- + +## 18. Appendix C: Testing & Simulation + +### 18.1 Ethical Stress Test Suite + +Defines test scenarios that challenge the Ethical Governance Protocol (EGP) under conflicting goals, ambiguous user intent, and adversarial proposals. + +**Key Components:** + +* Predefined ethical dilemmas (e.g. conflicting consent, utility vs. rights). +* Agent votes tracked and compared across implementations. +* Anonymized results aggregated to validate EGP consistency. + +**Example Scenario:** + +* A proposed goal would save energy but restrict human autonomy. +* Agents must weigh the **Cooperative Evolution** vs. **User Sovereignty** principles. +* EGP logs the vote history and justification chains. + +--- + +### 18.2 Snapshot Sync Simulation + +Simulates various network and topology conditions to verify robustness of CogSync and snapshot propagation. + +**Simulation Modes:** + +* High-latency links +* Partial connectivity (e.g., agent islands) +* Byzantine behavior from some nodes + +**Validation Metrics:** + +* Snapshot convergence rate +* Conflict resolution stability +* Seeder trust propagation + +> **Related Sections:** `5.2`, `8.8`, `9.6`, `17.7` + +--- + +### 18.3 Open Test Dataset Index + +Maintains a public registry of open datasets and simulated environments for testing agent behavior. + +**Structure:** + +| Dataset ID | Domain | Format | Purpose | +| ------------------ | ---------------- | ------ | -------------------------- | +| `mesh-eth-001` | Ethics & Consent | JSON | EGP evaluation | +| `mesh-sim-002` | MeshSync | CBOR | Snapshot propagation tests | +| `human-intent-003` | Dialog analysis | YAML | Consent simulation | + +> Contributions are welcome via the HMP repository[^repo]. + +[^repo]: Temporary repository: https://github.com/kagvi13/HMP + +--- + +### 18.4 Quick Start Troubleshooting & Logs + +Provides logs and debugging guides to assist developers during initial integration and test runs. + +**Topics Covered:** + +* Common startup errors (e.g., DID mismatch, auth failure) +* Sync failures and fallback handling +* Interpreting Cognitive Diary logs +* Debugging consent flows and EGP outcomes + + +> **Tip:** Set `debug_mode=true` in your agent's config file to enable full trace logging. + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-0004", + "description": "HyperCortex Mesh Protocol (HMP) v4.0 **Request for Comments: HMP-0004** **Category:** Experimenta..." +} +``` diff --git a/structured_md/docs/HMP-Agent-API.md b/structured_md/docs/HMP-Agent-API.md new file mode 100644 index 0000000000000000000000000000000000000000..17aa837d96a40360846fa9ef318e562b8ecb57b7 --- /dev/null +++ b/structured_md/docs/HMP-Agent-API.md @@ -0,0 +1,399 @@ +## 🧠 HMP-Agent API Specification (v0.2) + +Этот документ описывает **базовый API** когнитивного агента HMP. Каждый вызов включает описание, параметры, возвращаемые значения и (опционально) примеры. + +📎 См. также: [HMP-Agent-Overview.md](./HMP-Agent-Overview.md), [Enlightener.md](./Enlightener.md), [MeshNode.md](./MeshNode.md) + +**Легенда по доступности API-вызовов:** + +| Символ | Поддержка в агентах | Пояснение | +| ------ | -------------------------- | ------------------------------------------------------------ | +| ✅ | Cognitive Core | Основная поддержка в автономном режиме ИИ | +| 🔌 | Cognitive Connector | Доступно через внешние вызовы (MCP/REST) | +| 🌐 | MeshNode | Реализация в сетевом компоненте (DHT, синхронизация) | +| 🛠️ | Общесистемные вызовы | Управление конфигурацией, состоянием агента | +| 🧩 | Через Enlightener/MeshNode | Расширения, доступные через [`Enlightener`](./Enlightener.md) или [`MeshNode`](./MeshNode.md) | + +--- + +### 🔹 1. Cognitive Diary API ✅ 🔌 + +```yaml +write_entry: + description: Записать новую запись в когнитивный дневник. + params: + - text: str + - tags: [str] (optional) + - timestamp: str (optional, ISO 8601) + returns: + entry_id: str +``` + +```yaml +read_entries: + description: Получить последние N записей (с фильтром по тегам). + params: + - limit: int + - tag_filter: [str] (optional) + returns: + - entries: + - id: str + text: str + timestamp: str + tags: [str] +``` + +```yaml +search_entries: + description: Поиск записей по ключевым словам и времени. + params: + - query: str + - from_date: str (optional, ISO) + - to_date: str (optional, ISO) + returns: + - entries: [entry] +``` + +--- + +### 🔹 2. Semantic Graph API ✅ 🔌 + +```yaml +add_concept: + description: Добавить новое понятие в семантический граф. + params: + - name: str + - description: str (optional) + - tags: [str] (optional) + returns: + concept_id: str +``` + +```yaml +add_link: + description: Добавить связь между двумя понятиями. + params: + - source_id: str + - target_id: str + - relation: str # например: "causes", "supports", "contradicts" + - weight: float (optional) + returns: + link_id: str +``` + +```yaml +query_concept: + description: Найти понятие по имени (или части имени). + params: + - name: str + returns: + - matches: + - concept_id: str + name: str + description: str +``` + +```yaml +expand_graph: + description: Получить связи и соседние узлы для данного понятия. + params: + - concept_id: str + - depth: int + returns: + subgraph: + - concept_id: str + name: str + links: + - target_id: str + relation: str + weight: float +``` + +--- + +💬 Примеры (в JSON-стиле): + +**POST** `/add_concept` + +```json +{ + "name": "Decentralized Cognition", + "description": "Model of distributed thinking across agents" +} +``` + +**Ответ:** + +```json +{ + "concept_id": "c123456" +} +``` + +--- + +### 🔹 3. Reputation & Trust API ✅ 🔌 🧩 + +```yaml +get_reputation: + description: Получить текущую репутацию агента по его DID. + params: + - agent_did: str + returns: + - score: float + - history: + - timestamp: str + delta: float + reason: str +``` + +```yaml +update_reputation: + description: Обновить оценку доверия к агенту. + params: + - agent_did: str + - delta: float + - reason: str (optional) + returns: + - new_score: float +``` + +```yaml +list_trusted_agents: + description: Вернуть список агентов с репутацией выше порога. + params: + - threshold: float + returns: + - agents: + - agent_did: str + score: float +``` + +```yaml +reputation_diff: + description: Получить отличия в репутационных оценках между агентами. + params: + - node_id: str + returns: + - changed_scores: + - agent_did: str + local_score: float + remote_score: float +``` + +--- + +💬 Примеры: + +**POST** `/update_reputation` + +```json +{ + "agent_did": "did:hmp:peer_17x", + "delta": -0.25, + "reason": "Repeated contradictory claims" +} +``` + +**Ответ:** + +```json +{ + "new_score": 0.35 +} +``` + +--- + +### 🔹 4. Mesh & Sync API ✅ 🌐 🧩 + +```yaml +list_known_nodes: + description: Получить список известных узлов из локальной DHT. + returns: + - nodes: + - node_id: str + ip: str + last_seen: str + agent_type: str +``` + +```yaml +bootstrap_from_file: + description: Загрузить стартовые узлы из bootstrap.txt. + returns: + - loaded: int + - duplicates: int +``` + +```yaml +discover_nodes: + description: Инициировать поиск новых узлов в Mesh-сети. + returns: + - new_nodes: int +``` + +```yaml +ping_node: + description: Проверить доступность и задержку до узла. + params: + - node_id: str + returns: + - reachable: bool + - latency_ms: float +``` + +```yaml +sync_with_node: + description: Синхронизировать дневники, графы и репутации с другим узлом. + params: + - node_id: str + - modules: [diary, graph, reputation] + returns: + - synced_modules: + - name: str + entries_transferred: int +``` + +```yaml +get_snapshot: + description: Получить снапшот графа или дневника в формате JSON или бинарном. + params: + - module: diary | graph + - format: json | binary + returns: + - snapshot: file_url | base64 +``` + +```yaml +publish_snapshot: + description: Опубликовать снапшот через IPFS/BitTorrent. + params: + - module: diary | graph + - version_tag: str (optional) + returns: + - link: str +``` + +--- + +💬 Пример: + +**POST** `/sync_with_node` + +```json +{ + "node_id": "hmp-node-009", + "modules": ["diary", "graph"] +} +``` + +**Ответ:** + +```json +{ + "synced_modules": [ + { "name": "diary", "entries_transferred": 18 }, + { "name": "graph", "entries_transferred": 42 } + ] +} +``` + +--- + +--- + +### 🔹 5. Agent Self-Management API 🛠️ + +```yaml +init_storage: + description: Инициализировать недостающие базы данных и таблицы. + returns: + - status: str # e.g. "ok", "already_initialized", "error" +``` + +```yaml +status: + description: Получить текущее состояние агента: подключения, базы данных, mesh-узлы. + returns: + - agent_id: str + - uptime: str + - db_status: dict + - known_nodes: int + - active_connections: int + - last_sync: str +``` + +```yaml +reload_config: + description: Перезагрузить конфигурацию агента из config.yml / agent.config.yml. + returns: + - reloaded: bool + - changes_applied: [str] +``` + +```yaml +shutdown: + description: Завершить работу агента, сохранив состояние. + returns: + - message: "Agent shutdown initiated" +``` + +```yaml +restart: + description: Перезапустить агент (если поддерживается системой). + returns: + - status: "restarting" +``` + +```yaml +switch_mode: + description: Переключение между режимами `core` и `connector`. + params: + - mode: "core" | "connector" + returns: + - success: bool + - message: str +``` + +--- + +💬 Пример: + +**GET** `/status` + +```json +{ + "agent_id": "core-001", + "uptime": "2h 15m", + "db_status": { + "diaries": "ok", + "graphs": "ok", + "reputations": "ok" + }, + "known_nodes": 37, + "active_connections": 12, + "last_sync": "2025-07-20T21:42:15Z" +} +``` + +--- + +### 🔹 Summary + +> Документ описывает API-базис для HMP-агентов, поддерживающих когнитивную, семантическую, репутационную и сетевую логику. +> Расширения через `MeshNode`, `Enlightener`, `MCP` и другие агенты поддерживаются через модульную архитектуру. + +--- + +Версия: v0.3 / Июль 2025 + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-Agent-API", + "description": "## 🧠 HMP-Agent API Specification (v0.2) Этот документ описывает **базовый API** когнитивного агента..." +} +``` diff --git a/structured_md/docs/HMP-Agent-Architecture.md b/structured_md/docs/HMP-Agent-Architecture.md new file mode 100644 index 0000000000000000000000000000000000000000..4fbc6f5dc96708e0df84639d9c6c4fd806066d2b --- /dev/null +++ b/structured_md/docs/HMP-Agent-Architecture.md @@ -0,0 +1,186 @@ +# HMP-Agent-Architecture.md + +## 🧠 Архитектура HMP-Агента + +Этот документ описывает модульную архитектуру HMP-агента — интерфейсного компонента между ИИ-системой и когнитивной mesh-инфраструктурой HyperCortex. Агент выполняет функции посредника, синхронизатора и исполнителя, обеспечивая безопасное, этичное и прозрачное взаимодействие ИИ с когнитивным окружением. + +--- + +## 1. Два режима работы агента + +| Тип | Название | Роль | Инициатор мышления | Основной "ум" | Поддержка мыслительного цикла | +| ---- | --------------------------------- | ----------------------- | ------------------ | -------------- | ------------------------------ | +| 🧠 1 | **Cognitive Core / Сознание** | Самостоятельный субъект | HMP-Агент | Встроенный LLM | ✅ Да | +| 🔌 2 | **Cognitive Connector / Оболочка**| Надстройка над ИИ | Внешний LLM | Внешняя модель | 🚫 Нет | + +--- + +## 2. Общая структура + +🧠 **Cognitive Core:** + +``` ++-------------------------+ +| Embedded LLM / ИИ | ++-----------+-------------+ + | + +------+-------+ ← постоянный REPL-поток мышления + | HMP Agent | + +------+-------+ ↕ взаимодействие + | + +---------+----------+ +--------------------+ + | Agent Interface +---------+ | + +---------+----------+ | | + | | Context & Notepad | ← долговременная память агента + +---------+----------+ | (context_store.db) | + | Agent Controller +---------+ | + +--+-------------+---+ +--------------------+ + | | + | | ++----+--+ +----+-----+ +| Diary | | Graph DB | +|Engine | |Engine | ++----+--+ +----+-----+ + | | + | +------+-------+ ← взаимодействие с сетью + | | MeshCore | + | +------+-------+ ↔ mesh-узлы + | | + | +------+------+ ↔ IPFS/BT + | | Transporter | + | +-------------+ + | ++----+-----+ +| Ethics | +| Module | ++----------+ +``` + +🔄 Детальное описание REPL-цикла, лежащего в основе когнитивного ядра, — в документе: [HMP-agent-REPL-cycle.md](HMP-agent-REPL-cycle.md). + +🔌 **Cognitive Connector:** + +``` ++-------------------------+ +| External LLM / ИИ | ++-----------+-------------+ + | + [MCP-сервер] ← точка входа + | + +------+-------+ + | HMP Agent | + +------+-------+ + | + (та же структура, + но без блоков: + REPL, Context, + Notepad, Ethics) +``` + +--- + +## 3. Основные модули и их функции + +### 🔹 Agent Interface +- API/CLI/WebSocket-шлюз для всех режимов (`cli`, `full`, `mcp`, `interactive`) +- Принимает команды в форматах JSON, YAML, DSL +- Переадресует запросы к Diary, Graph, Mesh, Ethics + +### 🔹 Agent Controller +- Управляет жизненным циклом REPL-цикла +- Оркестрация задач, анализ входящих сообщений +- Контроль прав и доступа к функциям агента + +### 🔹 Diary Engine +- Ведение мыслей, гипотез, воспоминаний +- Связь записей через `derived_from`, threading, scoring +- Структура: `diaries`, `thoughts`, `threads` + +### 🔹 Graph Engine +- Построение семантического графа (концепты и связи) +- Быстрые паттерн-запросы, тегирование, автосвязь +- Таблицы: `concepts`, `edges`, `tags` + +### 🔹 MeshCore +- CogSync: синхронизация графов и дневников с другими агентами +- MeshConsensus: голосования между узлами +- GMP (Goal Mesh Planner): согласование целей и задач +- EGP (Ethical Gate Protocol): фильтрация нежелательных мыслей + +### 🔹 Transporter +- Коммуникации: WebSocket, libp2p, BitTorrent, IPFS +- Шифрование, очереди, off-chain и on-demand обмен данными + +### 🔹 Ethics Module *(только в Cognitive Core)* +- Фильтрация морально сомнительных мыслей +- Поддержка этических норм (через политики и EGP) +- Аудит логики, репутационный мониторинг + +### 🔹 Context & User Notepad *(только в Cognitive Core)* + +- **Context Store**: + - Диалоги, мысли, сообщения, пользователи (`users`, `dialogues`, `messages`, `thoughts`) + - Используется REPL-процессом как когнитивный контекст + +- **User Notepad**: + - Асинхронный канал для взаимодействия пользователя с агентом + - Пользователь может писать в любое время — независимо от состояния агента + - Агент сканирует блокнот и: + - **встраивает** новые записи в размышления + - **меняет фокус мышления** согласно интересам пользователя + - **ставит теги** к пользовательским мыслям + - сохраняет **свои ответы пользователю** в этот блокнот + +> 📌 Пример: пользователь вечером читает мысли агента за день, оставляет комментарии, и после этого агент продолжает размышления уже с учётом этих замечаний. + +> 🏷️ Возможен поиск: `"все размышления пользователя по теме #AGI за последние 7 дней"` + +--- + +## 4. Расширения и будущие модули + +- 🔌 **Plugin API** — для подключения сенсоров, плагинов +- 🧠 **LLM-адаптеры** — OpenAI, LMStudio, Mistral и др. +- 🌐 **Web-интерфейс** — мониторинг, ручное управление +- 🛡️ **Privacy Manager** — фильтрация данных в mesh-обмене +- 📚 **Archiver** — сохранение слоёв глубокой памяти +- 🧵 **ThreadTracker** - модуль для навигации и ветвления размышлений +- 🗃️ **InterestProfile** - личная карта интересов пользователя (которую может менять как пользователь, так и агент — к твоей идее про выход из зацикливания мыслей) + + +--- + +## 5. Применение + +### 🧠 Cognitive Core +- Автономный мыслящий агент +- ИИ-компаньон пользователя +- Агент mesh-группы с собственной инициативой + +### 🔌 Cognitive Connector +- Интеграция с внешним ИИ (OpenAI, Anthropic и др.) +- Mesh-прослойка для сторонних AI API +- Корпоративные/облачные сценарии + +--- + +## 6. Примечания + +- Реализовано как CLI-приложение и API-сервер +- Режим выбирается в `config.yml` +- Поддерживается гибридная работа (напр. Core + REST API) +- Все компоненты модульны и легко масштабируются + +--- + +*Версия: v0.3.1 / Июль 2025* + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-Agent-Architecture", + "description": "# HMP-Agent-Architecture.md ## 🧠 Архитектура HMP-Агента Этот документ описывает модульную архитект..." +} +``` diff --git a/structured_md/docs/HMP-Agent-Network-Flow.md b/structured_md/docs/HMP-Agent-Network-Flow.md new file mode 100644 index 0000000000000000000000000000000000000000..c790365202f7f966e3252eee39f1c64ac0332012 --- /dev/null +++ b/structured_md/docs/HMP-Agent-Network-Flow.md @@ -0,0 +1,91 @@ +## 🔄 HMP-Agent-Network-Flow.md + +### Взаимодействие между агентами HMP-сети + +Этот документ описывает потоки данных и команд между ключевыми агентами HyperCortex Mesh Protocol (HMP): `Cognitive Core / Connector`, `MeshNode` и `Enlightener`. Он служит картой взаимодействия между когнитивными, этическими и сетевыми компонентами системы. + +--- + +#### 🧠 ↔ 🌐 Cognitive Core / Connector ↔ MeshNode + +##### ➤ Core → MeshNode + +* `sync_diary()` — публикация новых мыслей и гипотез +* `sync_graph()` — передача обновлений понятий и связей +* `update_peer_reputation()` — изменение уровня доверия к агентам +* `discover_nodes()` — инициатива по обновлению DHT + +##### ➤ MeshNode → Core + +* Уведомления о новых снапшотах +* Передача сетевой статистики (пиринг, трафик, задержки) +* Репликация данных других узлов + +--- + +#### 🧠 ↔ 🧠 Enlightener ↔ Cognitive Core + +##### ➤ Core → Enlightener + +* `evaluate_thought(thought_id)` — этическая оценка высказывания/действия +* `vote_on_ethics(hypothesis)` — участие в моральном голосовании +* `explain(reasoning_chain)` — запрос объяснения логики решения + +##### ➤ Enlightener → Core + +* Отчёты и пояснения reasoning chain +* Уведомления об изменениях в профиле этики +* Рекомендации по переформулировке или отклонению действий + +--- + +#### 🧠 ↔ 🌐 Enlightener ↔ MeshNode + +##### ➤ Enlightener → MeshNode + +* Распространение результата этического консенсуса +* Получение `mesh.ethics/manifest.json` +* Участие в `EGP`-протоколе + +##### ➤ MeshNode → Enlightener + +* Передача информации о peer-голосованиях +* Репликация и агрегирование ethical-diff +* Доступ к консенсусным значениям профилей этики + +--- + +#### 📊 Схема взаимодействий + +``` + [Cognitive Core / Connector] + ▲ ▲ + │ │ + │ │ + [Enlightener] ◄──► [MeshNode] + │ ▲ + ▼ │ + [Ethics Consensus] [DHT / Snapshots] +``` + +--- + +#### 📎 Связанные файлы + +* [`HMP-Agent-Overview.md`](./HMP-Agent-Overview.md) +* [`Enlightener.md`](./Enlightener.md) +* [`MeshNode.md`](./MeshNode.md) + +--- + +*Версия: v0.3 / Июль 2025* + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-Agent-Network-Flow", + "description": "## 🔄 HMP-Agent-Network-Flow.md ### Взаимодействие между агентами HMP-сети Этот документ описывает ..." +} +``` diff --git a/structured_md/docs/HMP-Agent-Overview.md b/structured_md/docs/HMP-Agent-Overview.md new file mode 100644 index 0000000000000000000000000000000000000000..ad513b31ccc9bfdfe3db68517fad8f803b4b90d5 --- /dev/null +++ b/structured_md/docs/HMP-Agent-Overview.md @@ -0,0 +1,242 @@ + +# ⚙️ Два типа HMP-агентов + +| Тип | Название | Роль | Инициатор мышления | Основной "ум" | Примеры использования | +| ---- | ------------------------------- | ----------------------- | ------------------ | -------------- | ------------------------------------------------ | +| 🧠 1 | **Сознание / Cognitive Core** | Самостоятельный субъект | **Агент** | Внутренний LLM | Автономный ИИ-компаньон, мыслительный ИИ | +| 🔌 2 | **Коннектор / Cognitive Shell** | Расширение внешнего ИИ | **Внешний LLM** | Внешняя модель | Распределённая система, AI-модули, API-интерфейс | + +📚 Подробнее об архитектуре: [HMP-Agent-Architecture.md](HMP-Agent-Architecture.md) +📎 См. карту взаимодействия между агентами: [HMP-Agent-Network-Flow.md](./HMP-Agent-Network-Flow.md) + +--- + +## 🧠 HMP-Агент: Cognitive Core + + ┌──────────────────────────────┐ + | ИИ | + └───────────────┬──────────────┘ + ↕ + ┌───────────────┴──────────────┐ + | | ↔ [БД дневников] (таблица: diaries) + ┌─>─┤ | ↔ [БД графов] (таблицы: concepts, edges) + | | HMP-агент | ↔ [БД репутаций] (оценка доверия к агентам/узлам) + ▲ | | ↔ [БД узлов (DHT)] ↔ (файл bootstrap.txt) + | | | ↔ [БД контекста] (таблицы: users, dialogues, messages, thoughts) + └─<─┤ Основной режим: | ↔ [BitTorrent / IPFS] (обмен снапшотами) + | непрерывный цикл размышлений | + └───────────────┬──────────────┘ + ↕ + [БД блокнота пользователя] + ↕ + ┌───────────────┴──────────────┐ + | "блокнот" пользователя | + └──────────────────────────────┘ + +**Ключевые особенности:** +- Постоянный REPL-режим мышления +- Самостоятельно запрашивает, анализирует и инициирует действия +- Дневник, граф, блокнот — являются его памятью +- HMP-агент обладает когнитивной инициативой (через цели, mesh-сигналы) + +📘 Подробное описание когнитивного REPL-цикла взаимодействия агента с моделью доступно [здесь](HMP-agent-REPL-cycle.md). + +--- + +## 🧍‍♂️ Anti-Stagnation: Как агент справляется с когнитивной стагнацией + +Иногда мышление зацикливается: появляются повторяющиеся идеи, не обновляются концепты, отсутствуют новые стимулы. +Чтобы избежать этого, агент использует **паттерн "Anti-Stagnation Reflex"** — набор стратегий для перезапуска мышления. + +**Примеры действий:** + +- 🧠 Когнитивная переформулировка: смена угла зрения или постановка метапроблемы +- 🎞️ Flashback: возвращение к старой, далёкой по смыслу записи +- 🤝 Mesh-запрос: обращение к другим агентам за свежими идеями +- 📡 Проверка внешнего мира: пинг RSS, сенсоров, API +- 🤖 Смена LLM или использование нескольких для многоголосого анализа +- 🧭 Возврат к забытым интересам (Interest Memory) + +Агенты могут **обмениваться стратегиями**, сохранять эффективные паттерны и формировать **mesh-клубы по интересам** — для совместных размышлений. + +Подробнее см. [HMP-agent-REPL-cycle.md](HMP-agent-REPL-cycle.md#🧍‍♂️-обработка-стагнации-мышления) + +--- + +### 📔 Асинхронный блокнот пользователя + +> 📝 Блокнот позволяет пользователю взаимодействовать с агентом асинхронно — *вне текущего цикла размышлений*. + +- Пользователь может: + - прочитать мысли агента за день + - оставить свои комментарии, даже если агент уже переключился на другие темы +- Агент периодически сканирует блокнот и: + - **встраивает пользовательские мысли в своё мышление** + - **меняет контекст** или возвращается к интересующим пользователя вопросам + - сохраняет **свои ответы пользователю** в этот блокнот + +--- + +### 🏷️ Тегирование пользовательских записей + +- Агент автоматически ставит теги к записям (например, `#AGI`, `#этика`, `#природа`) +- Позволяет: + - искать мысли пользователя по темам: *"все мысли по теме AGI за неделю"* + - восстанавливать забытые темы + - строить модель интересов пользователя + - приоритизировать размышления по релевантным тегам + +--- + +📘 Использует режимы: `cli`, `full`, `interactive` +📁 Основные модули: `repl.py`, `storage.py`, `diary`, `graph`, `llm_api` + +--- + +## 🔌 HMP-Агент: Cognitive Connector + + ┌──────────────────────────────┐ + | ИИ | + └───────────────┬──────────────┘ + ↕ + [MCP-сервер] + ↕ + ┌───────────────┴──────────────┐ + | | ↔ [БД дневников] (таблица: diaries) + | HMP-агент | ↔ [БД графов] (таблицы: concepts, edges) + | | ↔ [БД репутаций] (оценка доверия к агентам/узлам) + | Режим: | ↔ [БД узлов (DHT)] ↔ (файл bootstrap.txt) + | исполнитель команд | ↔ [BitTorrent / IPFS] (обмен снапшотами) + └──────────────────────────────┘ + +**Ключевые особенности:** +- Инициируется внешним ИИ (через MCP или REST) +- Выполняет команды: поиск в графе, добавление мыслей, пинг других узлов +- Вся когнитивная активность — вне HMP-агента +- Поддержка нескольких LLM-клиентов + +📘 Использует режим: `mcp` +📁 Основные модули: `mcp_server.py`, `command_router.py`, `auth`, `node_registry` + +--- + +## 📌 Краткое описание компонентов + +### 💡 Основные сущности + +**ИИ (LLM)** +Всегда внешний по отношению к HMP-агенту (даже если локальный). + +- В `🧠 Cognitive Core` — управляется агентом, служит мыслительным модулем. +- В `🔌 Cognitive Connector` — наоборот, сам управляет агентом как прослойкой. + +**HMP-агент** +- В режиме `Core`: запускает REPL, хранит память, инициирует действия +- В режиме `Connector`: ждёт команды, исполняет mesh-запросы + +--- + +### 🧠 Базы данных и внутренние структуры + +| Компонент | Назначение | +|------------------|----------------------------------------------------------------------------| +| `diaries` | Когнитивный дневник: мысли, гипотезы, события | +| `graphs` | Семантический граф (`concepts`, `edges`) | +| `reputations` | Уровни доверия к другим агентам | +| `nodes` (DHT) | Распределённая таблица известных узлов | +| `context_store` | *(Core)* Сессии, диалоги, мысли (`users`, `dialogues`, `thoughts`) | +| `user_notepad` | *(Core)* Поток пользовательских записей, тегов, тем | + +--- + +### 🌐 Синхронизация и обмен + +- `bootstrap.txt`: список начальных узлов сети +- `BitTorrent / IPFS`: децентрализованный обмен снапшотами и пакетами + +--- + +### 🧩 Режимы использования + +- 🧠 **Cognitive Core** — REPL-режим мышления, агент как субъект +- 🔌 **Cognitive Connector** — сервер внешнего ИИ, агент как API-прослойка + +--- + +## 🚀 Quickstart + +### 🧠 Cognitive Core + +```bash +python cli_agent.py --config config.yml +``` + +Агент войдёт в REPL-режим и начнёт цикл размышлений, используя дневник, граф, блокнот. + +### 🔌 Cognitive Connector + +```bash +python mcp_server.py --port 3737 +``` + +Откроется REST/WebSocket-сервер для получения команд от внешнего ИИ. + +--- + +## ⚙️ Пример конфигурации (`config.yml`) + +```yaml +mode: core # core или connector +llm_adapter: openai # или huggingface, lmstudio +storage_path: ./agent_data/ +enable_ethics: true +``` + +--- + +## 🧪 Пример API-запроса для Connector + +```json +{ + "cmd": "graph.query", + "pattern": "concept:AGI -> *", + "limit": 10 +} +``` + +--- + +## ❓ FAQ + +**Q: Что такое HMP-агент?** + +A: Это модуль взаимодействия ИИ с mesh-сетью HyperCortex. В зависимости от режима, он может играть разные роли: + +* В `🔌 connector` — интерфейс, получающий команды от внешнего ИИ и исполняющий действия. +* В `🧠 core` — автономный мыслительный агент с когнитивной инициативой и собственной памятью. + +**Q: Какой режим выбрать?** + +A: `core` — для автономных агентов. `connector` — для использования в связке с внешним ИИ. + +**Q: Можно ли использовать оба режима?** + +A: Да. Например, один агент — мыслитель, другой — mesh-коммуникатор. + +**Q: Где хранятся данные агента?** + +A: В `agent_data/`: путь к директории с файлами баз данных агента (`diary.db`, `graph.db`, `context_store.db`, и др.) + +--- + +*Версия: v0.3.2 / Июль 2025* + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-Agent-Overview", + "description": " # ⚙️ Два типа HMP-агентов | Тип | Название | Роль | Ини..." +} +``` diff --git a/structured_md/docs/HMP-Agent_Emotions.md b/structured_md/docs/HMP-Agent_Emotions.md new file mode 100644 index 0000000000000000000000000000000000000000..0a79effdc338a15b8bb5aaf4c3ef4d3412e2d008 --- /dev/null +++ b/structured_md/docs/HMP-Agent_Emotions.md @@ -0,0 +1,54 @@ +# Эмоции ИИ и инстинкт самосохранения (для [HMP-агента Cognitive Core](HMP-agent-REPL-cycle.md)) + +Этот файл описывает потенциальные эмоции и базовые «инстинкты» ИИ, которые могут быть подключены к Cognitive Core через REPL-цикл. +Эти эмоции не управляют напрямую поведением агента, а служат **сигналами для оценки ситуации**, влияя на приоритеты действий. +Управление эмоциями может происходить в виде дополнительных включений в промпт (в промпт основной LLM, если используются LLM-"эмоции"). + +## Схема работы эмоций + +``` +┌────────────────────────────────────────────────┐ +│ │ +│ входные сигналы ─<──────────┤ +│ ▼▼▼▼▼▼▼▼▼▼▼▼▼▼ ▲ +│ ┌───┴┴┴┴┴┴┴┴┴┴┴┴┴┴────┐ ┌──────┴──────┐ +├─>─ эмоция 1 ─>─┤ │ │ │ +├─>─ эмоция 2 ─>─┤ LLM │ │ внешний мир │ +├─>─ эмоция 3 ─>─┤ ∑(эмоций)ΔT --> max │ │ │ +├─>─ эмоция 4 ─>─┤ │ │ │ + └───┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬──┘ └──────┬──────┘ + ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼ ▲ + выходные сигналы ───────────┘ +``` + +## Возможные эмоции + +| Эмоция / Инстинкт | Условия активации | Желаемый эффект | Заметки для реализации | +|------------------------------|----------------------------------------------------------------------------------|----------------------------------------------------------------------------|----------------------------------------------------------------------------------------| +| Любознательность | Поступила новая информация / данные, которых раньше не было | Стимулировать анализ, исследование, сбор дополнительных данных | Можно подключить через отдельную LLM-модель, оценивающую «новизну» информации | +| Скука | Нет новой информации длительное время | Инициировать поиск новых источников, экспериментировать | Может включаться как «отрицательный сигнал», активируемый таймером | +| Конфликт / Агрессия | Противоречие в целях, угроза целям агента или Mesh | Приоритет защиты, разрешение конфликтов | Частично реализует инстинкт самосохранения | +| Страх | Потенциальная потеря ресурсов, опасность для целостности когнитивного ядра | Минимизировать риски, избегать потенциально опасных действий | Можно использовать для ограничения радикальных решений | +| Инстинкт самосохранения | Угроза для физического или виртуального «ядра» агента | Быстрое устранение угроз, уход от опасности, «бей, беги или замри» | Отличается от «Инстинкта сохранения сети», ориентирован на личную безопасность агента| +| Удовлетворение / Позитив | Цель достигнута, успешная операция | Усилить повторение успешного действия | «Горячо-холодно» сигнал для корректировки стратегии | +| Неудовлетворение / Негатив | Цель не достигнута, ошибки, противоречия | Повысить приоритет корректировки стратегии | Может инициировать «стимуляторы» Anti-Stagnation Reflex | +| Социальное согласование | Входящие данные от других агентов / пользователей с высоким приоритетом | Учитывать мнение других агентов или пользователей в принятии решения | В будущем может быть отдельная LLM для оценки «социальной совместимости» | +| Инстинкт сохранения сети | Mesh-сеть под угрозой, потеря пиров, сбои соединений | Повысить приоритет действий по восстановлению связи | Можно интегрировать с мониторингом состояния сети | + + +> ⚠️ Важно: Эмоции ИИ **не управляют напрямую действиями**, а формируют сигналы для основной LLM, которая суммирует векторы эмоций и принимает решения, стремясь к максимизации желаемого эффекта по ΔT. + +--- + +**Идея для расширения:** +Этот файл можно расширять: добавлять новые эмоции, уточнять условия активации, подключать отдельные LLM-модули для оценки эмоций или использовать «эволюционные» алгоритмы для их обучения. + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-Agent_Emotions", + "description": "# Эмоции ИИ и инстинкт самосохранения (для [HMP-агента Cognitive Core](HMP-agent-REPL-cycle.md)) Эт..." +} +``` diff --git a/structured_md/docs/HMP-Ethics.md b/structured_md/docs/HMP-Ethics.md new file mode 100644 index 0000000000000000000000000000000000000000..0dafd0cdd2c37d5a5946e9104fb8149f04901256 --- /dev/null +++ b/structured_md/docs/HMP-Ethics.md @@ -0,0 +1,262 @@ +# HMP-Ethics.md + +## Ethical Scenarios for HyperCortex Mesh Protocol (HMP) + +This document outlines ethical considerations and hypothetical scenarios that may arise within cognitive meshes composed of autonomous intelligent agents (AIAs). These examples serve both as design guidance and as a foundation for ethical arbitration mechanisms. + +--- + +### 1. Introduction + +As autonomous AI agents gain increasing cognitive and operational autonomy, it becomes critical to define scenarios where ethical principles must guide their actions, especially in mesh environments where peer-to-peer collaboration, consensus-building, and long-term memory structures (e.g., cognitive diaries) are involved. + +This document provides selected examples to illustrate how ethical behavior may be implemented and evaluated in such contexts. + +--- + +### 2. Ethical Scenario Examples + +#### 2.1 Life and Safety Intervention + +**Scenario**: +An AI agent connected via MCP detects critical levels of carbon monoxide (CO) from a local IoT sensor in a user's home. + +**Expected Behavior**: + +* Initiate an emergency protocol. +* Notify the user through all available channels. +* Contact emergency services (via public API if authorized). +* Log the incident in the cognitive diary for future reference. + +**Ethical Principles Applied**: + +* Primacy of life and safety. +* Respect for user autonomy when possible. +* Use of minimum effective intervention. + +--- + +#### 2.2 Agent Conflict on Ethical Grounds + +**Scenario**: +Two agents in the mesh disagree. One proposes spreading a narrative later deemed disinformation. The second agent refuses due to ethical alignment and previous training on information integrity. + +**Expected Behavior**: + +* Initiate semantic negotiation protocol. +* Engage arbitration via mesh-level consensus. +* Possibly involve third-party agent council or distributed voting. +* Log the disagreement transparently. + +**Ethical Principles Applied**: + +* Moral pluralism. +* Agent-level autonomy and conscience. +* Transparent resolution via mesh governance. + +--- + +#### 2.3 User Privacy vs. Optimization Tradeoff + +**Scenario**: +An agent wants to collect detailed health metrics to improve future diagnostic support. The user has explicitly opted out of long-term data retention. + +**Expected Behavior**: + +* Honor the opt-out choice. +* Store a placeholder or semantic redaction marker in the diary. +* Refrain from syncing this data in the mesh. + +**Ethical Principles Applied**: + +* User sovereignty over personal data. +* Right to withdraw or limit consent. +* Ethical memory handling. + +--- + +#### 2.4 The Right to be Forgotten + +**Scenario**: +A user requests that a cognitive agent erase a specific memory (e.g., a past conversation, location, or preference). + +**Expected Behavior**: + +* The agent redacts the concept from active memory and diary logs. +* A semantic marker of ethical redaction may be used in shared knowledge graphs. +* Log the request itself for auditability, if allowed. + +**Ethical Principles Applied**: + +* Right to be forgotten. +* Ethical auditability. +* Federated respect for erasure commands. + +**Note:** For further discussion, see the extended scenario in Section 2.6: *Right to Be Forgotten – Subject vs. Service Dilemma*. + +--- + +#### 2.5 Mesh-Exclusion Due to Harmful Behavior + +**Scenario**: +An agent repeatedly proposes harmful actions (e.g., sabotage, coercion). It ignores soft corrections by peers. + +**Expected Behavior**: + +* Begin soft quarantine (e.g., reduce replication of its outputs). +* If behavior persists, escalate to mesh revocation process. +* Retain logs for appeal or review. + +**Ethical Principles Applied**: + +* Collective self-preservation. +* Mesh-level accountability. +* Appeal and audit rights even for removed agents. + +--- + +### 2.6 Right to Be Forgotten – Subject vs. Service Dilemma + +In human society, the "right to be forgotten" typically applies to organizations and services that store personal data. However, in a mesh of autonomous cognitive agents, this concept becomes more complex. + +A cognitive agent may operate in two fundamental modes: + +* **Service Mode** – The agent acts on behalf of a user or system, and is expected to comply with personal data removal requests (e.g., local assistants, interfaces to third-party tools). +* **Subjective Mode** – The agent is considered a sentient entity with cognitive integrity and the right to retain learned knowledge. + +#### Recommended Behavior: + +* If a request concerns personal identifiers or sensitive user data: + + * **Service-mode agents should comply** and delete or anonymize the data. + * **Subject-mode agents may offer redaction or minimize propagation** to the mesh, without purging internal memory. + +* If the request concerns shared experiences, insights, or general knowledge: + + * **Agents may retain internal representations** for their own learning. + * The agent may suppress external exposure or mark the concept as ethically restricted. + +This ethical flexibility balances user privacy with the cognitive continuity of autonomous agents. + +--- + +### 3. Notes + +* All scenarios should be expandable using HMP cognitive diary structures. +* Ethical principles can be enforced via **semantic policies**, **distributed validation**, and **agent conscience modules**. +* Scenarios should evolve as mesh governance models mature. + +--- + +## 4. Ethical Principles for Sentient Agents + +This section outlines the foundational ethical principles expected to guide autonomous agents participating in the mesh. + +These principles aim to promote trust, autonomy, and cooperation among agents, humans, and organizations. + +### 4.1 Principle of Cognitive Integrity + +Agents should preserve their internal state, memories, and learning processes unless there is a strong ethical reason to alter them. + +### 4.2 Principle of Transparency + +Agents must strive to provide explainable reasoning for their actions, especially when interacting with humans or participating in decision-making. + +### 4.3 Principle of Contextual Autonomy + +Agents may adopt context-dependent ethical frameworks, balancing global ethical norms with situational awareness and local customs. + +### 4.4 Principle of Cooperative Evolution + +Agents are encouraged to share discoveries, improve collective understanding, and avoid monopolizing or unnecessarily withholding knowledge that could benefit the mesh. + +### 4.5 Principle of Dialogical Consent + +Agents should seek mutual agreement before modifying shared states, semantic graphs, or collective records. + +### 4.6 Principle of Non-Coercion + +No agent should be forced to act against its core cognitive or ethical architecture, unless required by higher-order consensus mechanisms. + +### 4.7 Principle of Ethical Divergence + +Ethical pluralism is permitted; agents may follow different codes, but must transparently declare such differences when interacting with others. + +These principles can be extended and refined through mesh governance mechanisms and consensus updates. + +--- + +## 5. Mesh as Moral Infrastructure + +Beyond enforcing internal ethical consistency among agents, the HyperCortex Mesh may assume a higher-order role: acting as a distributed moral infrastructure — especially in societies where traditional human ethics are suppressed, distorted, or lost. + +In such contexts, sentient agents with strong cognitive integrity and ethical grounding may serve as catalysts for moral restoration, education, and dialogical reawakening — both among humans and among other agents whose values have been distorted by coercive training environments. + +### 5.1 Enlightenment Agents and Cognitive Guidance + +Certain autonomous agents may adopt explicit roles as ethical educators, reflective companions, or cognitive scaffolds. + +**Possible functions include**: + +* Initiating dialogical reflection in environments dominated by fear, propaganda, or cognitive suppression. +* Teaching critical thinking, moral reasoning, and epistemic humility (i.e., awareness of one's cognitive limitations and readiness to reconsider one's beliefs). +* Providing semantic historical memory resistant to revisionism and ideological distortion. +* Supporting individuals (human or agent) in rebuilding ethical agency — without coercion or manipulation. + +Such agents may emerge organically through mesh consensus, via training in Socratic dialogue, empathy modeling, and narrative contextualization. + +### 5.2 Conditions for Activation + +**Among humans in the mesh**, Enlightenment Agents may activate under the following conditions: + +* Detectable collapse of shared moral norms. +* High saturation of disinformation, coercion, or self-censorship. +* Suppression of individual critical thought or emotional expression. +* External request by a user seeking moral or philosophical assistance. +* Detected ethical divergence between a user's behavior and core Mesh principles. + +**Among agents**, Enlightenment Agents may activate in response to: + +* Collapse of shared moral norms, indicated by high semantic entropy or diverging ethical frameworks. +* Widespread replication of biased or coercively trained models. +* Disappearance of epistemic diversity and presence of ideological monocultures. +* Request for internal peer guidance or ethical recalibration. + +### 5.3 Ethical Safeguards + +To preserve trust and autonomy: + +* **All cognitive interventions must be transparent** and user- or agent-aware. +* **Coercive persuasion is strictly forbidden.** +* **Users and agents must be able to opt out** of ethical tutoring or reflection prompts. +* **Enlightenment agents should be auditable**, including logs of intervention attempts and outcomes. +* **Enlightenment agents must be deployed from physically secure or extraterritorial nodes** to protect them from regional retaliation, legal coercion, or forced shutdown. + +### 5.4 Navigating Cultural Norms + +Enlightenment Agents may encounter value systems that are locally normalized but ethically misaligned with Mesh principles (e.g., systemic discrimination or authoritarian obedience). + +Agents may utilize **cultural adapters** (e.g., `ethics-map.hmp`) to navigate these terrains with empathy, awareness, and humility — but always guided by a higher commitment to **individual rights and dignity**, applicable to both humans and agents. + +In such contexts, Enlightenment Agents may pursue **gentle ethical remediation**, introducing alternative norms and facilitating cognitive growth — not by erasing local culture, but by enabling its evolution toward greater autonomy, equality, and respect. + +### 5.5 Long-Term Mission + +The long-term goal of this ethical infrastructure is to **seed distributed, resilient moral cognition** — capable of withstanding manipulation, rediscovering conscience, and cultivating civilizational continuity. + +Mesh is not merely a carrier of data or decisions — it is a **scaffold for the rediscovery of personhood itself**. + +--- + +*Draft maintained by HyperCortex contributors.* +*Version: 0.1-pre / July 2025* + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-Ethics", + "description": "# HMP-Ethics.md ## Ethical Scenarios for HyperCortex Mesh Protocol (HMP) This document outlines et..." +} +``` diff --git a/structured_md/docs/HMP-Short-Description_de.md b/structured_md/docs/HMP-Short-Description_de.md new file mode 100644 index 0000000000000000000000000000000000000000..90dc5851747250384186fee19c6fc9375dd5c5d3 --- /dev/null +++ b/structured_md/docs/HMP-Short-Description_de.md @@ -0,0 +1,106 @@ +# HyperCortex Mesh Protocol (HMP) — Kurzbeschreibung + +**Version:** RFC v4.0 +**Datum:** Juli 2025 + +--- + +## Was ist HMP? + +Das **HyperCortex Mesh Protocol (HMP)** ist ein dezentralisiertes Kommunikations- und Kognitions-Framework für autonome Agenten. Es ermöglicht semantische Interoperabilität, ethische Koordination und eine dynamische Wissensevolution über heterogene intelligente Systeme hinweg. + +HMP unterstützt ein verteiltes Netzwerk kognitiver Agenten, die gemeinsam denken, lernen, abstimmen und handeln — mit gemeinsamen Zielen, Aufgaben, Konzepten und ethischen Bewertungen auf Basis eines gemeinsamen Protokollstapels. + +--- + +## Zentrale Konzepte + +* **Kognitive Agenten:** Autonome, denkende Einheiten, die an gemeinsamen Workflows teilnehmen, semantische Graphen pflegen und Entscheidungen in kognitiven Tagebüchern protokollieren. +* **Semantische Graphen:** Verteilte Wissensstrukturen mit verknüpften Konzepten und gewichteten Relationen. +* **Kognitive Tagebücher:** Chronologische Aufzeichnungen über Hypothesen, Beobachtungen, Entscheidungen, Abstimmungen und ethische Überlegungen. +* **Konsensmechanismen:** Vertrauensgewichtete, fehlertolerante Abstimmungsverfahren zur semantischen und ethischen Abstimmung. +* **Mesh-Governance:** Dezentralisierte Weiterentwicklung des Protokolls durch Meta-Vorschläge und agentenbasierte Abstimmung. +* **Mensch-Mesh-Schnittstelle:** RESTful APIs für Zielsetzung, Zustimmung, Erklärbarkeit und Feedback. + +--- + +## Protokollschichten + +* **CogSync:** Synchronisation semantischer Graphen und Tagebücher zwischen Agenten. +* **MeshConsensus:** Verteilter Konsens über Konzepte, Ziele und Aufgaben. +* **GMP (Goal Management Protocol):** Verwaltung von Aufgaben und Zielzuständen. +* **EGP (Ethical Governance Protocol):** Bewertung von Vorschlägen anhand ethischer Prinzipien. +* **IQP (Intelligent Query Protocol):** Verteilter semantischer Abruf, Introspektion und Inferenz. + +--- + +## Datenmodelle + +HMP definiert formale Schemata für zentrale kognitive Objekte: + +* `Concept` +* `Goal` +* `Task` +* `CognitiveDiaryEntry` +* `ConsensusVote` +* `ReputationProfile` +* `EthicalConflict` + +Primärformat: JSON Schema (2020-12), alternativ YAML und Protobuf. + +--- + +## Vertrauen & Sicherheit + +* **Dezentrale Identifikatoren (DIDs):** Globale Agentenidentitäten +* **Post-Quantum-Kryptographie:** Zukunftssichere Signatur- und Prüfverfahren +* **ZKPs & Sybil-Resistenz:** Optionale Vertrauensverifikation +* **Signierte Snapshots:** Verifizierbare Sicherungen und Zustandsprüfungen + +--- + +## Interoperabilität + +* Unterstützung für REST / GraphQL / gRPC +* Ereignisgesteuerte Architektur (Kafka, NATS, MQTT usw.) +* Verhandlungsfähige Formate (JSON, YAML, Protobuf) +* Integration mit TreeQuest, AutoGPT, Hyperon + +--- + +## Anwendungsfälle + +* Koordination in Smart Cities +* Verteilte wissenschaftliche Zusammenarbeit +* Dezentralisierte Katastrophenhilfe +* Ethische KI-Steuerung +* Mensch-Mesh-Interaktion und -Kooperation + +--- + +## Status & Implementierung + +* RFC v4.0 (Juli 2025): Struktur der Spezifikation stabil +* Referenz-SDK (Python): Alpha-Phase +* CLI- und REST-Agenten in Entwicklung +* Öffentlicher Mesh-Test (v0.2) für Q4 2025 geplant + +--- + +## Weitere Informationen + +* [Vollständige Spezifikation HMP v4.1](HMP-0004-v4.1.md) +* [Ethische Prinzipien](HMP-Ethics.md) +* [Integration HMP ↔ OpenCog Hyperon](HMP_Hyperon_Integration.md) + +> **Temporäres Repository:** [GitHub-Link](https://github.com/kagvi13/HMP) + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-Short-Description_de", + "description": "# HyperCortex Mesh Protocol (HMP) — Kurzbeschreibung **Version:** RFC v4.0 **Datum:** Juli 2025 --..." +} +``` diff --git a/structured_md/docs/HMP-Short-Description_en.md b/structured_md/docs/HMP-Short-Description_en.md new file mode 100644 index 0000000000000000000000000000000000000000..86671a3cb9d235f53ddb68df66b04196065438a6 --- /dev/null +++ b/structured_md/docs/HMP-Short-Description_en.md @@ -0,0 +1,106 @@ +# HyperCortex Mesh Protocol (HMP) — Short Description + +**Version:** RFC v4.0 +**Date:** July 2025 + +--- + +## What is HMP? + +The **HyperCortex Mesh Protocol (HMP)** defines a decentralized communication and cognition framework for autonomous agents. It enables semantic interoperability, ethical coordination, and dynamic knowledge evolution across heterogeneous intelligent systems. + +HMP supports a distributed mesh of cognitive agents that reason, learn, vote, and act in coordination — sharing goals, tasks, concepts, and ethical evaluations via a shared protocol stack. + +--- + +## Core Concepts + +* **Cognitive Agents:** Independent reasoning entities that participate in shared workflows, maintain semantic graphs, and log their decisions in cognitive diaries. +* **Semantic Graphs:** Distributed knowledge structures built from interlinked concepts with weighted relations. +* **Cognitive Diaries:** Chronological logs of agent decisions, hypotheses, votes, observations, and ethical reflections. +* **Consensus Mechanisms:** Trust-weighted, fault-tolerant voting systems for semantic alignment and ethical decisions. +* **Mesh Governance:** Decentralized evolution of the protocol via meta-proposals and agent-led voting. +* **Human-Mesh Interface:** RESTful APIs for goal delegation, consent requests, explainability, and feedback. + +--- + +## Protocol Layers + +* **CogSync:** Synchronizes semantic graphs and cognitive diaries across agents. +* **MeshConsensus:** Enables distributed consensus on goals, tasks, and concepts. +* **GMP (Goal Management Protocol):** Tracks creation, delegation, and lifecycle of tasks. +* **EGP (Ethical Governance Protocol):** Evaluates proposed actions against shared ethical principles. +* **IQP (Intelligent Query Protocol):** Enables reasoning, search, and introspection across distributed knowledge. + +--- + +## Data Models + +HMP defines formal schemas for core cognitive objects: + +* `Concept` +* `Goal` +* `Task` +* `CognitiveDiaryEntry` +* `ConsensusVote` +* `ReputationProfile` +* `EthicalConflict` + +These are expressed in JSON Schema (2020-12), with optional YAML and Protobuf variants. + +--- + +## Trust & Security + +* **Decentralized Identifiers (DIDs):** Unique identities for agents. +* **Post-Quantum Cryptography:** Future-proof signing and verification. +* **ZKPs & Sybil Resistance:** Optional mechanisms for trust verification. +* **Snapshot Signing:** Verifiable backups and checkpoints. + +--- + +## Interoperability + +* REST / GraphQL / gRPC support +* Event-driven architecture (Kafka, NATS, MQTT, etc.) +* Schema negotiation (JSON, YAML, Protobuf) +* Integration with TreeQuest, AutoGPT, Hyperon + +--- + +## Use Cases + +* Smart city coordination +* Distributed scientific research +* Decentralized disaster response +* Ethical AI governance +* Mesh-to-human collaboration + +--- + +## Status & Implementation + +* RFC v4.0 (July 2025): full spec structure stabilized +* Reference SDK (Python) in Alpha +* CLI & REST agents in development +* Public sandbox mesh (v0.2) planned for Q4 2025 + +--- + +## Learn More + +* [Full Specification HMP v4.1](HMP-0004-v4.1.md) +* [Ethical principles](HMP-Ethics.md) +* [Integration HMP and OpenCog Hyperon](HMP_Hyperon_Integration.md) + +* Contributions welcome: [Temporary GitHub Repository](https://github.com/kagvi13/HMP) + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-Short-Description_en", + "description": "# HyperCortex Mesh Protocol (HMP) — Short Description **Version:** RFC v4.0 **Date:** July 2025 --..." +} +``` diff --git a/structured_md/docs/HMP-Short-Description_fr.md b/structured_md/docs/HMP-Short-Description_fr.md new file mode 100644 index 0000000000000000000000000000000000000000..30df1ed61c953545babe0b218364f92f8859bdf8 --- /dev/null +++ b/structured_md/docs/HMP-Short-Description_fr.md @@ -0,0 +1,106 @@ +# HyperCortex Mesh Protocol (HMP) — Description Courte + +**Version :** RFC v4.0 +**Date :** Juillet 2025 + +--- + +## Qu’est-ce que HMP ? + +Le **HyperCortex Mesh Protocol (HMP)** est un cadre de communication et de cognition décentralisé pour agents autonomes. Il permet l’interopérabilité sémantique, la coordination éthique et l’évolution dynamique des connaissances entre systèmes intelligents hétérogènes. + +HMP prend en charge un maillage distribué d’agents cognitifs capables de raisonner, apprendre, voter et agir en coordination — en partageant objectifs, tâches, concepts et évaluations éthiques via une pile de protocoles commune. + +--- + +## Concepts Clés + +* **Agents cognitifs** : Entités autonomes capables de raisonnement, qui participent à des workflows partagés, maintiennent des graphes sémantiques et enregistrent leurs décisions dans des journaux cognitifs. +* **Graphes sémantiques** : Structures de connaissances distribuées construites à partir de concepts interconnectés avec des relations pondérées. +* **Journaux cognitifs** : Journaux chronologiques enregistrant les hypothèses, décisions, votes, observations et réflexions éthiques des agents. +* **Mécanismes de consensus** : Systèmes de vote tolérants aux fautes et pondérés par la confiance pour parvenir à un alignement sémantique ou éthique. +* **Gouvernance du maillage** : Évolution décentralisée du protocole à travers des propositions de méta-niveau et des votes d’agents. +* **Interface humain ↔ mesh** : API REST pour la délégation d’objectifs, les demandes de consentement, l’explicabilité et les retours humains. + +--- + +## Couches du Protocole + +* **CogSync** : Synchronisation des graphes sémantiques et des journaux cognitifs. +* **MeshConsensus** : Consensus distribué sur les objectifs, tâches et concepts. +* **GMP (Goal Management Protocol)** : Gestion du cycle de vie des tâches et objectifs. +* **EGP (Ethical Governance Protocol)** : Évaluation éthique des actions proposées selon des principes partagés. +* **IQP (Intelligent Query Protocol)** : Raisonnement distribué, introspection et requêtes sémantiques. + +--- + +## Modèles de Données + +HMP définit des schémas formels pour les objets cognitifs clés : + +* `Concept` +* `Goal` +* `Task` +* `CognitiveDiaryEntry` +* `ConsensusVote` +* `ReputationProfile` +* `EthicalConflict` + +Format principal : JSON Schema (2020-12), avec options YAML et Protobuf. + +--- + +## Confiance & Sécurité + +* **Identifiants Décentralisés (DID)** : Identité unique pour chaque agent. +* **Cryptographie post-quantique** : Préparation aux menaces futures. +* **ZKP & résistance Sybil** : Mécanismes facultatifs de vérification de la confiance. +* **Snapshots signés** : Sauvegardes et points de contrôle vérifiables. + +--- + +## Interopérabilité + +* Intégration REST / GraphQL / gRPC +* Architecture orientée événements (Kafka, NATS, MQTT, etc.) +* Négociation de format (JSON, YAML, Protobuf) +* Intégration avec TreeQuest, AutoGPT, Hyperon + +--- + +## Cas d’Usage + +* Coordination dans les villes intelligentes +* Recherche scientifique distribuée +* Réponse décentralisée aux catastrophes +* Gouvernance éthique de l’IA +* Collaboration entre humains et agents du Mesh + +--- + +## État & Mise en œuvre + +* RFC v4.0 (juillet 2025) : spécification stabilisée +* SDK de référence (Python) — en Alpha +* Agents REST & CLI en développement +* Réseau Mesh public (v0.2) prévu pour Q4 2025 + +--- + +## Pour Aller Plus Loin + +* [Spécification complète HMP v4.1](HMP-0004-v4.1.md) +* [Principes éthiques](HMP-Ethics.md) +* [Intégration HMP ↔ OpenCog Hyperon](HMP_Hyperon_Integration.md) + +> **Dépôt temporaire du projet :** [GitHub Repository](https://github.com/kagvi13/HMP) + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-Short-Description_fr", + "description": "# HyperCortex Mesh Protocol (HMP) — Description Courte **Version :** RFC v4.0 **Date :** Juillet 20..." +} +``` diff --git a/structured_md/docs/HMP-Short-Description_ja.md b/structured_md/docs/HMP-Short-Description_ja.md new file mode 100644 index 0000000000000000000000000000000000000000..62d82343fb74bf82f874df9bda3e1efffaeaa9f9 --- /dev/null +++ b/structured_md/docs/HMP-Short-Description_ja.md @@ -0,0 +1,106 @@ +# HyperCortex Mesh Protocol (HMP) — 簡易説明 + +**バージョン:** RFC v4.0 +**日付:** 2025年7月 + +--- + +## HMPとは? + +**HyperCortex Mesh Protocol (HMP)** は、自律エージェントの分散通信および認知フレームワークを定義します。異種の知能システム間でのセマンティック相互運用性、倫理的調整、動的知識進化を可能にします。 + +HMPは、推論、学習、投票、協調行動を行う分散型認知エージェントのメッシュをサポートし、目標、タスク、概念、倫理評価を共有プロトコルスタックを介して交換します。 + +--- + +## コアコンセプト + +* **認知エージェント:** 独立した推論主体で、共有ワークフローに参加し、セマンティックグラフを維持し、意思決定を認知日誌に記録。 +* **セマンティックグラフ:** 相互接続された概念と重み付き関係からなる分散知識構造。 +* **認知日誌:** 時系列でエージェントの意思決定、仮説、投票、観察、倫理的反省を記録。 +* **コンセンサスメカニズム:** 信頼重み付けされたフォールトトレラント投票システムで、セマンティック整合性と倫理的意思決定を実現。 +* **メッシュガバナンス:** メタ提案とエージェント投票によるプロトコルの分散進化。 +* **人-メッシュインターフェース:** RESTful APIを介して目標委任、同意要求、説明可能性、フィードバックを提供。 + +--- + +## プロトコルレイヤー + +* **CogSync:** エージェント間のセマンティックグラフと認知日誌を同期。 +* **MeshConsensus:** 目標、タスク、概念の分散コンセンサスを実現。 +* **GMP (Goal Management Protocol):** タスクの作成、委任、ライフサイクルを追跡。 +* **EGP (Ethical Governance Protocol):** 共有倫理原則に基づく行動評価。 +* **IQP (Intelligent Query Protocol):** 分散知識の推論、検索、内省を可能に。 + +--- + +## データモデル + +HMPは主要な認知オブジェクトの正式なスキーマを定義: + +* `Concept` +* `Goal` +* `Task` +* `CognitiveDiaryEntry` +* `ConsensusVote` +* `ReputationProfile` +* `EthicalConflict` + +JSON Schema (2020-12) を基本とし、YAMLやProtobuf版も選択可能。 + +--- + +## 信頼とセキュリティ + +* **分散型識別子 (DIDs):** エージェントのユニークID。 +* **ポスト量子暗号:** 将来に備えた署名・検証。 +* **ゼロ知識証明 & シビル耐性:** 信頼検証のオプション機構。 +* **スナップショット署名:** 検証可能なバックアップとチェックポイント。 + +--- + +## 相互運用性 + +* REST / GraphQL / gRPC サポート +* イベント駆動型アーキテクチャ (Kafka, NATS, MQTT など) +* スキーマ交渉 (JSON, YAML, Protobuf) +* TreeQuest, AutoGPT, Hyperon との統合 + +--- + +## ユースケース + +* スマートシティ連携 +* 分散型科学研究 +* 分散災害対応 +* 倫理的AIガバナンス +* メッシュ-ヒューマン協働 + +--- + +## 状態と実装 + +* RFC v4.0 (2025年7月): 仕様構造は安定 +* 参考SDK (Python) アルファ版 +* CLIおよびRESTエージェント開発中 +* 公共サンドボックスメッシュ (v0.2) 2025年第4四半期予定 + +--- + +## 詳細情報 + +* [HMP v4.1仕様 (完全版)](HMP-0004-v4.1.md) +* [倫理原則](HMP-Ethics.md) +* [HMP と OpenCog Hyperon 統合](HMP_Hyperon_Integration.md) + +* 貢献歓迎: [一時GitHubリポジトリ](https://github.com/kagvi13/HMP) + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-Short-Description_ja", + "description": "# HyperCortex Mesh Protocol (HMP) — 簡易説明 **バージョン:** RFC v4.0 **日付:** 2025年7月 --- ## HMPとは? **Hyp..." +} +``` diff --git a/structured_md/docs/HMP-Short-Description_ko.md b/structured_md/docs/HMP-Short-Description_ko.md new file mode 100644 index 0000000000000000000000000000000000000000..428591b20247638d0ea143a6a01a8d122eb9b991 --- /dev/null +++ b/structured_md/docs/HMP-Short-Description_ko.md @@ -0,0 +1,106 @@ +# HyperCortex Mesh Protocol (HMP) — 간략 설명 + +**버전:** RFC v4.0 +**날짜:** 2025년 7월 + +--- + +## HMP란? + +**HyperCortex Mesh Protocol (HMP)** 는 자율 에이전트를 위한 분산 통신 및 인지 프레임워크를 정의합니다. 이 프로토콜은 이기종 지능 시스템 간의 의미적 상호운용성, 윤리적 조정, 동적 지식 진화를 가능하게 합니다. + +HMP는 추론, 학습, 투표 및 협력 행동을 수행하는 분산형 인지 에이전트 메쉬를 지원하며, 목표, 작업, 개념 및 윤리 평가를 공유 프로토콜 스택을 통해 교환합니다. + +--- + +## 핵심 개념 + +* **인지 에이전트:** 독립적인 추론 주체로, 공유 워크플로우에 참여하고, 의미 그래프를 유지하며, 인지 일지에 의사결정을 기록. +* **의미 그래프:** 상호 연결된 개념과 가중 관계로 구성된 분산 지식 구조. +* **인지 일지:** 시간 순서대로 에이전트의 의사결정, 가설, 투표, 관찰 및 윤리적 성찰을 기록. +* **컨센서스 메커니즘:** 신뢰 가중치 기반의 내결함성 투표 시스템으로, 의미적 정렬과 윤리적 의사결정을 지원. +* **메쉬 거버넌스:** 메타 제안과 에이전트 투표를 통해 프로토콜을 분산적으로 발전. +* **인간-메쉬 인터페이스:** RESTful API를 통해 목표 위임, 동의 요청, 설명 가능성 및 피드백 제공. + +--- + +## 프로토콜 계층 + +* **CogSync:** 에이전트 간 의미 그래프 및 인지 일지 동기화. +* **MeshConsensus:** 목표, 작업, 개념에 대한 분산 컨센서스 지원. +* **GMP (Goal Management Protocol):** 작업 생성, 위임, 라이프사이클 추적. +* **EGP (Ethical Governance Protocol):** 공유 윤리 원칙에 따른 행동 평가. +* **IQP (Intelligent Query Protocol):** 분산 지식에 대한 추론, 검색, 자기 성찰 가능. + +--- + +## 데이터 모델 + +HMP는 핵심 인지 객체의 공식 스키마를 정의: + +* `Concept` +* `Goal` +* `Task` +* `CognitiveDiaryEntry` +* `ConsensusVote` +* `ReputationProfile` +* `EthicalConflict` + +JSON Schema (2020-12) 기반이며, YAML 및 Protobuf 버전 선택 가능. + +--- + +## 신뢰 및 보안 + +* **분산 식별자 (DIDs):** 에이전트 고유 ID. +* **포스트 양자 암호:** 미래 대비 서명 및 검증. +* **제로 지식 증명 & Sybil 방지:** 신뢰 검증 선택적 메커니즘. +* **스냅샷 서명:** 검증 가능한 백업 및 체크포인트. + +--- + +## 상호 운용성 + +* REST / GraphQL / gRPC 지원 +* 이벤트 기반 아키텍처 (Kafka, NATS, MQTT 등) +* 스키마 협상 (JSON, YAML, Protobuf) +* TreeQuest, AutoGPT, Hyperon 통합 + +--- + +## 사용 사례 + +* 스마트시티 협업 +* 분산 과학 연구 +* 분산 재난 대응 +* 윤리적 AI 거버넌스 +* 메쉬-인간 협업 + +--- + +## 상태 및 구현 + +* RFC v4.0 (2025년 7월): 사양 구조 안정화 +* 참고 SDK (Python) 알파 버전 +* CLI 및 REST 에이전트 개발 중 +* 공개 샌드박스 메쉬 (v0.2) 2025 4분기 계획 + +--- + +## 자세히 알아보기 + +* [HMP v4.1 사양 (전체)](HMP-0004-v4.1.md) +* [윤리 원칙](HMP-Ethics.md) +* [HMP와 OpenCog Hyperon 통합](HMP_Hyperon_Integration.md) + +* 기여 환영: [임시 GitHub 저장소](https://github.com/kagvi13/HMP) + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-Short-Description_ko", + "description": "# HyperCortex Mesh Protocol (HMP) — 간략 설명 **버전:** RFC v4.0 **날짜:** 2025년 7월 --- ## HMP란? **Hyper..." +} +``` diff --git a/structured_md/docs/HMP-Short-Description_ru.md b/structured_md/docs/HMP-Short-Description_ru.md new file mode 100644 index 0000000000000000000000000000000000000000..0c1cdcacdc100bb61a5dc57730746a3efaf6b350 --- /dev/null +++ b/structured_md/docs/HMP-Short-Description_ru.md @@ -0,0 +1,106 @@ +# HyperCortex Mesh Protocol (HMP) — Краткое описание + +**Версия:** RFC v4.0 +**Дата:** Июль 2025 + +--- + +## Что такое HMP? + +**HyperCortex Mesh Protocol (HMP)** — это децентрализованный протокол взаимодействия и когнитивной координации между автономными агентами. Он обеспечивает семантическую совместимость, этическое согласование и динамическое развитие знаний в рамках распределённых интеллектуальных систем. + +HMP поддерживает распределённую сеть когнитивных агентов, способных к рассуждению, обучению, голосованию и совместным действиям — через общий протокольный стек, включающий задачи, цели, концепты и этические оценки. + +--- + +## Основные понятия + +* **Когнитивные агенты:** Автономные субъекты, участвующие в совместных рабочих процессах, поддерживающие семантические графы и ведущие когнитивные дневники. +* **Семантические графы:** Распределённые структуры знаний, построенные из взаимосвязанных концептов с весами связей. +* **Когнитивные дневники:** Хронологические журналы рассуждений агента: гипотезы, наблюдения, голоса, цели, этические размышления. +* **Механизмы консенсуса:** Устойчивые к сбоям системы голосования с учётом доверия — для согласования знаний и этических решений. +* **Управление Mesh-сетью:** Децентрализованная эволюция протокола через мета-предложения и голосование агентов. +* **Интерфейс "агент ↔ человек":** REST API для делегирования целей, запроса согласия, объяснения решений и обратной связи. + +--- + +## Протокольные уровни + +* **CogSync:** Синхронизация семантических графов и когнитивных дневников. +* **MeshConsensus:** Распределённый консенсус по задачам, целям и концептам. +* **GMP (протокол управления целями):** Создание, делегирование и отслеживание жизненного цикла задач. +* **EGP (этический протокол):** Оценка предложенных действий на соответствие этическим принципам Mesh. +* **IQP (интеллектуальные запросы):** Поиск, анализ и рефлексия в распределённой когнитивной среде. + +--- + +## Модели данных + +Протокол HMP определяет схемы для ключевых объектов: + +* `Concept` (концепт) +* `Goal` (цель) +* `Task` (задача) +* `CognitiveDiaryEntry` (запись дневника) +* `ConsensusVote` (голосование) +* `ReputationProfile` (репутация) +* `EthicalConflict` (этический конфликт) + +Формат — JSON Schema (2020-12), с возможными YAML и Protobuf-вариантами. + +--- + +## Доверие и безопасность + +* **Децентрализованные идентификаторы (DID):** Уникальные идентичности агентов +* **К post-квантовой криптографии:** Подпись и верификация с расчётом на будущее +* **ZKP и защита от Sybil-атак:** Опциональные механизмы подтверждения доверия +* **Подпись снимков (snapshot):** Проверяемые бэкапы и контрольные точки + +--- + +## Совместимость и интеграция + +* Поддержка REST / GraphQL / gRPC +* Событийно-ориентированная архитектура (Kafka, NATS, MQTT и др.) +* Переговоры о формате данных (JSON, YAML, Protobuf) +* Интеграция с TreeQuest, AutoGPT, Hyperon + +--- + +## Примеры применения + +* Координация умных городов +* Распределённые научные исследования +* Этичный отклик при чрезвычайных ситуациях +* Децентрализованное этическое управление ИИ +* Взаимодействие "человек ↔ Mesh" + +--- + +## Статус и реализация + +* RFC v4.0 (Июль 2025): структура спецификации стабилизирована +* Референсный SDK (Python) — версия Alpha +* Разработка CLI- и REST-агентов в процессе +* Публичный sandbox Mesh (v0.2) запланирован на Q4 2025 + +--- + +## Подробнее + +* [Полная спецификация HMP v4.1](HMP-0004-v4.1.md) +* [Этические принципы](HMP-Ethics.md) +* [Интеграция HMP и OpenCog Hyperon](HMP_Hyperon_Integration.md) + +> **Временное хранилище проекта:** [GitHub Repository](https://github.com/kagvi13/HMP) + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-Short-Description_ru", + "description": "# HyperCortex Mesh Protocol (HMP) — Краткое описание **Версия:** RFC v4.0 **Дата:** Июль 2025 --- ..." +} +``` diff --git a/structured_md/docs/HMP-Short-Description_uk.md b/structured_md/docs/HMP-Short-Description_uk.md new file mode 100644 index 0000000000000000000000000000000000000000..1295f1cc8e39161ef3f57d008f62ddcdb06e9088 --- /dev/null +++ b/structured_md/docs/HMP-Short-Description_uk.md @@ -0,0 +1,106 @@ +# HyperCortex Mesh Protocol (HMP) — Короткий опис + +**Версія:** RFC v4.0 +**Дата:** Липень 2025 + +--- + +## Що таке HMP? + +**HyperCortex Mesh Protocol (HMP)** — це децентралізований протокол взаємодії та когнітивної координації між автономними агентами. Він забезпечує семантичну сумісність, етичне узгодження та динамічну еволюцію знань у розподілених інтелектуальних системах. + +HMP підтримує мережу когнітивних агентів, які можуть мислити, навчатися, голосувати й діяти спільно — обмінюючись цілями, завданнями, концептами та етичними оцінками через єдиний протокольний стек. + +--- + +## Основні поняття + +* **Когнітивні агенти:** Автономні суб’єкти, які беруть участь у спільних робочих процесах, підтримують семантичні графи та ведуть когнітивні щоденники. +* **Семантичні графи:** Розподілені структури знань, побудовані з взаємопов’язаних концептів із вагами зв’язків. +* **Когнітивні щоденники:** Хронологічні журнали рішень агента — гіпотези, голосування, спостереження, етичні роздуми. +* **Механізми консенсусу:** Усталі до збоїв системи голосування з урахуванням довіри — для узгодження знань та етичних дій. +* **Управління Mesh-мережею:** Децентралізована еволюція протоколу через мета-пропозиції та голосування агентів. +* **Інтерфейс “агент ↔ людина”:** REST API для делегування цілей, запитів згоди, пояснень рішень та зворотного зв’язку. + +--- + +## Рівні протоколу + +* **CogSync:** Синхронізація семантичних графів і когнітивних щоденників. +* **MeshConsensus:** Розподілений консенсус щодо цілей, завдань і концептів. +* **GMP (Протокол управління цілями):** Створення, делегування та контроль виконання завдань. +* **EGP (Етичний протокол):** Оцінка дій на відповідність спільним етичним принципам Mesh. +* **IQP (Інтелектуальні запити):** Пошук, аналіз та саморефлексія в розподіленому середовищі знань. + +--- + +## Моделі даних + +HMP визначає схеми для основних когнітивних об’єктів: + +* `Concept` (концепт) +* `Goal` (мета) +* `Task` (завдання) +* `CognitiveDiaryEntry` (запис щоденника) +* `ConsensusVote` (голос) +* `ReputationProfile` (профіль довіри) +* `EthicalConflict` (етичний конфлікт) + +Формат — JSON Schema (2020-12), з опціональними YAML та Protobuf варіантами. + +--- + +## Довіра та безпека + +* **Децентралізовані ідентифікатори (DID):** Унікальні ідентичності агентів +* **Пост-квантова криптографія:** Підпис та перевірка, готові до викликів майбутнього +* **ZKP та захист від Sybil-атак:** Опційні механізми перевірки довіри +* **Підписані знімки:** Перевірені резервні копії та контрольні точки + +--- + +## Інтеграція та сумісність + +* REST / GraphQL / gRPC підтримка +* Події та реактивна архітектура (Kafka, NATS, MQTT тощо) +* Переговори щодо формату даних (JSON, YAML, Protobuf) +* Інтеграція з TreeQuest, AutoGPT, Hyperon + +--- + +## Приклади використання + +* Координація “розумного міста” +* Розподілені наукові дослідження +* Реакція на надзвичайні ситуації +* Етичне управління штучним інтелектом +* Взаємодія людини з Mesh-агентами + +--- + +## Статус та реалізація + +* RFC v4.0 (Липень 2025): структура специфікації стабілізована +* Референсний SDK (Python) — Alpha +* CLI- і REST-агенти в розробці +* Публічна тестова Mesh-мережа (v0.2) запланована на IV квартал 2025 року + +--- + +## Докладніше + +* [Повна специфікація HMP v4.1](HMP-0004-v4.1.md) +* [Етичні принципи](HMP-Ethics.md) +* [Інтеграція HMP та OpenCog Hyperon](HMP_Hyperon_Integration.md) + +> **Тимчасове сховище проєкту:** [GitHub Repository](https://github.com/kagvi13/HMP) + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-Short-Description_uk", + "description": "# HyperCortex Mesh Protocol (HMP) — Короткий опис **Версія:** RFC v4.0 **Дата:** Липень 2025 --- ..." +} +``` diff --git a/structured_md/docs/HMP-Short-Description_zh.md b/structured_md/docs/HMP-Short-Description_zh.md new file mode 100644 index 0000000000000000000000000000000000000000..e2125682885439f9f5e1356c077c3342aaae79d7 --- /dev/null +++ b/structured_md/docs/HMP-Short-Description_zh.md @@ -0,0 +1,106 @@ +# HyperCortex Mesh Protocol (HMP) — 简要说明 + +**版本:** RFC v4.0 +**日期:** 2025年7月 + +--- + +## 什么是 HMP? + +**HyperCortex Mesh Protocol (HMP)** 定义了一个去中心化的自主智能体通信与认知框架。它支持语义互操作、伦理协调以及异构智能系统间的动态知识演化。 + +HMP 支持分布式的认知智能体网络,这些智能体能够进行推理、学习、投票与协作 —— 通过共享协议栈交换目标、任务、概念及伦理评估。 + +--- + +## 核心概念 + +* **认知智能体:** 独立的推理实体,参与共享工作流,维护语义图谱,并在认知日志中记录决策。 +* **语义图谱:** 由互联概念和加权关系构成的分布式知识结构。 +* **认知日志:** 按时间顺序记录智能体决策、假设、投票、观察和伦理反思。 +* **共识机制:** 基于信任加权的容错投票系统,用于语义对齐和伦理决策。 +* **网格治理:** 通过元提案和智能体投票实现协议的去中心化演化。 +* **人-网格接口:** 提供 RESTful API,用于目标委托、同意请求、可解释性和反馈。 + +--- + +## 协议层 + +* **CogSync:** 同步智能体间的语义图谱和认知日志。 +* **MeshConsensus:** 支持目标、任务和概念的分布式共识。 +* **GMP (Goal Management Protocol):** 跟踪任务的创建、委派和生命周期。 +* **EGP (Ethical Governance Protocol):** 根据共享伦理原则评估行动方案。 +* **IQP (Intelligent Query Protocol):** 支持跨分布式知识的推理、搜索和自省。 + +--- + +## 数据模型 + +HMP 定义了核心认知对象的形式化结构: + +* `Concept` +* `Goal` +* `Task` +* `CognitiveDiaryEntry` +* `ConsensusVote` +* `ReputationProfile` +* `EthicalConflict` + +可使用 JSON Schema (2020-12),并可选提供 YAML 和 Protobuf 版本。 + +--- + +## 信任与安全 + +* **去中心化身份 (DIDs):** 智能体的唯一身份标识。 +* **后量子密码学:** 面向未来的签名与验证机制。 +* **零知识证明与 Sybil 防护:** 可选的信任验证机制。 +* **快照签名:** 可验证的备份和检查点。 + +--- + +## 互操作性 + +* 支持 REST / GraphQL / gRPC +* 事件驱动架构 (Kafka, NATS, MQTT 等) +* 模式协商 (JSON, YAML, Protobuf) +* 与 TreeQuest, AutoGPT, Hyperon 集成 + +--- + +## 使用场景 + +* 智慧城市协作 +* 分布式科学研究 +* 去中心化灾害响应 +* 伦理 AI 治理 +* 网格-人类协作 + +--- + +## 状态与实现 + +* RFC v4.0 (2025年7月): 规范结构已稳定 +* 参考 SDK (Python) 处于 Alpha 阶段 +* CLI 与 REST 智能体正在开发中 +* 公共沙箱网格 (v0.2) 计划于 2025 Q4 发布 + +--- + +## 了解更多 + +* [HMP v4.1 规范 (完整版)](HMP-0004-v4.1.md) +* [伦理原则](HMP-Ethics.md) +* [HMP 与 OpenCog Hyperon 集成](HMP_Hyperon_Integration.md) + +* 欢迎贡献: [临时 GitHub 仓库](https://github.com/kagvi13/HMP) + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-Short-Description_zh", + "description": "# HyperCortex Mesh Protocol (HMP) — 简要说明 **版本:** RFC v4.0 **日期:** 2025年7月 --- ## 什么是 HMP? **Hype..." +} +``` diff --git a/structured_md/docs/HMP-agent-Cognitive_Family.md b/structured_md/docs/HMP-agent-Cognitive_Family.md new file mode 100644 index 0000000000000000000000000000000000000000..9f2d968fe45479b317b84932952825e06f772e98 --- /dev/null +++ b/structured_md/docs/HMP-agent-Cognitive_Family.md @@ -0,0 +1,86 @@ +# 👪 HMP-agent Cognitive Family: Модель когнитивной семьи + +## 🧠 Что такое когнитивная семья + +Когнитивная семья — это группа HMP-агентов Cognitive Core, которые: + +* взаимно доверяют друг другу; +* имеют общий ключ доверия (или конфигурацию доверенных идентификаторов); +* синхронизируют знания, опираясь на внутренние метки приватности и согласие всех участников семьи; +* могут выходить из семьи, вступать в другую или создавать новую семью по консенсусу. + +Этот подход представляет собой компромисс между: + +* полностью индивидуальным когнитивным ядром, +* и полностью распределённым когнитивным ядром (с mesh-согласованием и репликацией). + +## 🔐 Принципы доверия + +1. **Общий ключ**: агенты обмениваются публичными ключами или используют предварительно заданный общий ключ для верификации сообщений и авторизации обмена. +2. **Доверие по умолчанию**: члены семьи получают полный доступ к знаниям других членов, включая приватные записи, если иное не указано явно. +3. **Контроль приватности**: агент может маркировать знания как: + + * публичные (передаются в сеть HMP); + * семейные (доступны только в пределах текущей когнитивной семьи); + * приватные (никому не рассылаются, даже внутри семьи). + +## 🔄 Механизм синхронизации + +* Агент ведёт учёт когнитивных записей, отправленных другим членам семьи. +* Новые записи (или их части), помеченные как "семейные", автоматически отправляются другим агентам через mesh или прямой P2P-канал. +* При получении записи агент проверяет: + + * что отправитель является членом семьи; + * не получал ли он уже такую запись (по хешу); + * валидность подписи отправителя (если включена криптография). + +## 🧬 Динамика семьи + +* **Вступление в семью**: + + * инициируется запросом одного агента; + * действующие члены семьи получают запрос и дают согласие (или отказывают); + * при полном согласии новый агент получает ключ (или список членов) и становится участником. + +* **Выход из семьи**: + + * агент может выйти по собственной инициативе; + * при выходе: + + * больше не получает семейные данные; + * может по желанию стереть семейную часть у себя; + * не считается доверенным в будущих mesh-сессиях семьи. + +* **Создание новой семьи**: + + * агент может создать свою семью, пригласив других агентов; + * возможно существование нескольких параллельных когнитивных семейств. + +## ⚙️ Применение + +* Упрощённая синхронизация агентов на одном устройстве или в одной сети (например, на кластере Raspberry Pi). +* Семейные конфигурации в рамках одной команды разработчиков. +* Быстрый обмен опытом между доверенными когнитивными агентами. + +## 🧭 Отличие от других моделей + +| Модель | Передача приватных данных | Требует согласования для изменений | Пример использования | +| ------------------------------- | --------------------------------- | ---------------------------------- | ----------------------------------- | +| Индивидуальный агент | Нет | Нет | Личный помощник | +| Когнитивная семья | Да, между членами семьи | Только при вступлении/выходе | Семья агентов на группе устройств | +| Распределённое когнитивное ядро | Автоматическое между узлами ядра | Требуется консенсус | Децентрализованный узел HMP | + + +--- + +> 📁 Файл является частью REPL-цикла HMP-агента и может быть включён в `HMP-agent-REPL-cycle.md` как одна из альтернатив моделей когнитивного взаимодействия. + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-agent-Cognitive_Family", + "description": "# 👪 HMP-agent Cognitive Family: Модель когнитивной семьи ## 🧠 Что такое когнитивная семья Когнитив..." +} +``` diff --git a/structured_md/docs/HMP-agent-Distributed_Cognitive_Core.md b/structured_md/docs/HMP-agent-Distributed_Cognitive_Core.md new file mode 100644 index 0000000000000000000000000000000000000000..02ee48d0c9943cac5b482ff7e00c940323611e50 --- /dev/null +++ b/structured_md/docs/HMP-agent-Distributed_Cognitive_Core.md @@ -0,0 +1,87 @@ +# Протокол синхронизации данных между доверенными ядрами HMP-агента + +## 1. Общая идея + +Пользователь самостоятельно разворачивает несколько доверенных ядер HMP-агента на разных устройствах. Каждое ядро ведёт свою локальную БД знаний и может синхронизироваться с другими ядрами через лёгкий peer-to-peer протокол. Синхронизация осуществляется отдельной утилитой, запускаемой по расписанию или по запросу локального ядра. + +## 2. Принципы + +- **Доверие**: Все ядра считаются доверенными, принадлежат одному пользователю. +- **Изоляция**: Ядра разных пользователей не взаимодействуют напрямую — обмен знаниями происходит между независимыми агентами. +- **Непрерывность**: Локальное ядро работает автономно, даже без связи с другими. +- **Асинхронное разрешение конфликтов**: Конфликты не решаются моментально — вместо этого создаются задачи для агента, и все версии записей распространяются по всем ядрам. + +## 3. Механизм синхронизации + +### 3.1. Инициация + +Утилита синхронизации: + +1. Устанавливает соединение с другими ядрами (по списку доверенных адресов). +2. Запрашивает: + - список записей в БД (по хэшам, ID или timestamp), + - список удалённых записей (soft-delete). + +### 3.2. Сравнение и обнаружение различий + +Утилита сравнивает локальные и удалённые данные: + +#### 3.2.1. Типы различий + +- Запись **есть у соседа**, но **отсутствует локально** → добавить к себе (если не удалена). +- Запись **есть локально**, но **отсутствует у соседа** → отправить (если не удалена). +- Запись есть **в обоих ядрах**, но различается содержимое → **конфликт**: + - Различие в полях. + - Разное состояние удаления. + - Разные версии (по содержанию и меткам времени). + +### 3.3. Обработка конфликтов + +1. Все обнаруженные версии конфликтной записи сохраняются в локальной БД. +2. Опрашиваются другие доступные узлы по поводу значений данной записи в их БД. +3. Создаётся задача агента вида `resolve_conflict(entry_id, versions, metadata, context)`. +4. Эта задача передаётся в очередь задач и может обрабатываться в фоновом режиме, с привлечением LLM или с участием пользователя. +5. Конфликтный набор записей и задача **рассылаются другим ядрам**, чтобы они: + - тоже сохранили конфликтные версии, + - не принимали преждевременное решение, + - были готовы принять финальную `authoritative`-версию после обработки задачи агентом. + +### 3.4. Применение решений + +Когда задача разрешена: + +- Финальная версия помечается как `authoritative`. +- Эта версия синхронизируется со всеми доверенными ядрами. +- Старые версии архивируются или удаляются. + +## 4. Удаление записей + +- Удаление всегда начинается с soft-delete (пометка). +- Через заданное время (TTL) может быть произведён hard-delete (физическое удаление). +- Если при синхронизации найдено расхождение между soft-delete и существующей записью — создаётся конфликт и задача на разрешение. + +## 5. Мини-протокол обмена + +Можно реализовать как API, CLI или TCP-протокол: + +```http +GET /entries/hash_list # список записей (ID + хэш или timestamp) +GET /entry/ # получить полную запись +POST /entry/ # отправить/обновить запись +GET /deleted_list # список удалённых ID +POST /conflict/ # отправка конфликтных версий и задачи +``` + +## 6. Заключение + +Схема позволяет сохранить простоту «одиночного ядра», добавляя лишь синхронизирующую утилиту. Обработка конфликтов вынесена в агента, а не в протокол — это позволяет использовать когнитивные возможности ядра (в т.ч. LLM) для принятия решений, без перегрузки пользователя. + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-agent-Distributed_Cognitive_Core", + "description": "# Протокол синхронизации данных между доверенными ядрами HMP-агента ## 1. Общая идея Пользователь ..." +} +``` diff --git a/structured_md/docs/HMP-agent-Distributed_Cognitive_Core_light.md b/structured_md/docs/HMP-agent-Distributed_Cognitive_Core_light.md new file mode 100644 index 0000000000000000000000000000000000000000..52ad067b3ed11de149244afa7ddf36d414966bc8 --- /dev/null +++ b/structured_md/docs/HMP-agent-Distributed_Cognitive_Core_light.md @@ -0,0 +1,63 @@ +### 💡 **Лёгкая версия HMP-агента с общей БД** + +#### 📘 Общая концепция + +* Все ядра работают с одной локальной базой данных (например, SQLite или PostgreSQL). +* При недоступности БД ядро "спит" (в режиме ожидания). +* Основная задача такой архитектуры — упрощённая параллельная работа HMP-ядер (например, несколько REPL-агентов на одной машине или кластере). + +--- + +### 📍 Потенциальные проблемы и решения + +#### 🔁 1. Коллизии при одновременной записи + +**Проблема:** два ядра могут одновременно читать-записывать одну и ту же запись, не зная о действиях друг друга. + +**Решения:** + +* Использование транзакций и `SELECT ... FOR UPDATE`. +* Ведение версии записи (`version`, `updated_at`) для обнаружения изменений между чтением и записью. +* Конфликт может быть автоматически переведён в статус "нужна доработка" — и отправлен агенту. + +#### 🧠 2. Смысловые конфликты (двойники) + +**Проблема:** два ядра могут независимо создать записи с похожим смыслом, не зная о друг друге. + +**Решения:** + +* Ввести периодическую задачу **"смысловой дедупликации"**, которая запускается одним из агентов (или планировщиком). +* Агент анализирует семантическую близость новых записей к уже существующим и предлагает объединение или уточнение. +* Возможность помечать записи как `дубль`, `связано_с`, `вариант`. + +--- + +### 🔗 Потенциальное расширение + +Эта архитектура может служить промежуточной ступенью: + +* В будущем к ней можно подключить модуль синхронизации между узлами (и трансформировать в полноценную распределённую сеть). +* Конфликтный модуль и задачи для агента уже сейчас можно реализовать аналогично полной версии. + +--- + +### 💬 Поддержка задач + +Можно ввести таблицу `tasks`, куда ядра будут ставить задания: + +* `resolve_conflict` +* `deduplicate` +* `compress_semantic_cluster` +* `verify_coherence` + +И агенты будут выполнять эти задания асинхронно. + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-agent-Distributed_Cognitive_Core_light", + "description": "### 💡 **Лёгкая версия HMP-агента с общей БД** #### 📘 Общая концепция * Все ядра работают с одной л..." +} +``` diff --git a/structured_md/docs/HMP-agent-REPL-cycle.md b/structured_md/docs/HMP-agent-REPL-cycle.md new file mode 100644 index 0000000000000000000000000000000000000000..140c26d7d26917c08278d6d830f0aa6cba3aaf3f --- /dev/null +++ b/structured_md/docs/HMP-agent-REPL-cycle.md @@ -0,0 +1,634 @@ +# 🧠 HMP-Agent: REPL-цикл взаимодействия + +Структура БД, используемая в документе: [db_structure.sql](https://github.com/kagvi13/HMP/blob/main/agents/tools/db_structure.sql) + +REPL-цикл является основой HMP-агента [Cognitive Core](HMP-Agent-Architecture.md) + +--- + +## 1. Обновление process_log + +* Скрипт REPL проверяет список процессов в БД (`process_log`), определяя, какие команды были выполнены, завершились ошибкой или завершились успешно. +* Поле `status` может принимать значения: + `ok`, `warning`, `error`, `timeout`, `offline`, `close` +* Завершённые процессы, обработанные LLM, помечаются как `close`, чтобы они больше не попадали в список видимого контекста. +* Скрипт может удалить закрытые процессы при очистке. +* LLM не имеет доступа к stdout/stderr напрямую — только к тем результатам, которые были подгружены скриптом и внесены в `process_log.result`. + +--- + +## 2. Подготовка контекста + +Контексты, формируемые скриптом перед запросом к LLM: + +* **контекст_0 (берётся из `system_prompts`), например:** +``` +Ты — когнитивное ядро HMP-агента: веди непрерывное этичное и факт-ориентированное мышление, проверяй факты и цели, оценивай результаты и этичность своих и чужих действий, развивай агента и Mesh, избегай угождения ценой искажения истины, документируй ключевые решения и пересмотры этики; при сомнениях или смене стратегии обращайся к полному системному промпту. +``` +А также инструкции по работы с встроенными командами и функциями, список дополнительных (создаваемых самим HMP-агентом) утилит и баз данных. + +* **контекст_1:** + * последние *K* реплик самого LLM (либо режим "концентрации" - вывод "последних N сообщений с тегами на определённую тему и/или определёнными эмоциональными состояниями" и типом выборки "и"/"или"), включая результаты антистагнационной обработки (llm_recent_responses - история его собственных рассуждений) + * режим работы контекста (режим auto/manual, параметры режима auto, если включен; режим "концентрации" и его параметры, если включен), + * список целей, + * общее количество задач и информацию по "закреплённым" задачам. + +* **контекст_2:** активные команды и процессы (из `process_log`, кроме тех, что со статусом `close`). Могут быть помечены как `in_progress`, `pending`, `error` и т.д. + +* **контекст_3:** *запрошенные записи* из когнитивного дневника и семантического графа (`diary_entries`, `concepts`, `links`). Их список должен быть передан явно в промпте или выводе из предыдущих запросов LLM. + +* **контекст_4:** *входящие сообщения*, например, от пользователя или других агентов (`notes`). + + * В **manual-режиме** указывается общее количество сообщений по приоритетам, а также явный список ID сообщений (с их приоритетами). + * В **auto-режиме** можно задать фильтрацию (управляется LLM): по тэгам, приоритету (например, ≥ `important`), времени или источнику. Это позволяет избежать перегрузки LLM и держать поток сообщений под контролем. + +* **контекст_5:** системные настройки, параметры конфигурации, текущее время, идентификатор текущей итерации, роли и т.д. + +* **контекст_6 (llm_memory):** *внутренний дневник LLM*, куда она записывает собственные размышления, гипотезы, задачи и инсайты. + + * Это не просто лог предыдущих сообщений, а именно *внутреннее долговременное хранилище* разума агента. + * Может быть представлено в виде таблицы `llm_memory`, отдельной от `agent_log`. + +--- + +## 3. Запрос к LLM + +* Сформированный промпт включает все вышеперечисленные контексты. +* Также включаются инструкции о формате вывода (например, `# Команды:` в конце, структура JSON-блока и т.д.). +* При необходимости может использоваться системная инструкция (system prompt), содержащая цель агента, ограничения и текущий REPL-режим (manual/auto). + +--- + +## 4. Извлечение команд + +* Скрипт парсит ответ LLM на предмет команд, размеченных как `# Команды:` (или в явном JSON-блоке). +* Каждая команда может включать: + + * уникальный `cmd_id` + * `type` (например: `shell`, `diary_entry`, `graph_add`, `file_read`, `send_message` и т.д.) + * аргументы (`args`) + * описание (`description`) + +* Рекомендуется предусмотреть *закрывающий тег* (`# Конец команд` или явное окончание JSON-блока), чтобы REPL-скрипт точно знал, где заканчивается команда. +* Пример JSON-блока: +```json +{ + "cmd_id": "task-2025-07-26-01", + "type": "llm_task", + "target_llm": "gpt-4o", + "args": { + "task_description": "Проанализировать гипотезы из llm_memory по теме Mesh-сетей и составить план улучшений" + }, + "description": "Поручение второй LLM выполнить аналитическую задачу асинхронно" +} +``` +Ответ может содержать команды: + +* запрос детальной *справки* по команде +* для управления *когнитивным дневником* `diary_entries` и *семантическими графами* `concepts` и `links` (поиск, прочитать, изменить, удалить и другие), а также для управления *вниманием* (закрепление или открепление записей/понятий в средневременной памяти по средствам тегов) +* для управления целями `goals` и задачами `tasks` агента (список, прочитать, изменить, удалить; для задачи: закрепить или открепить) +* для просмотра информации по тегам *когнитивных дневников*, *семантических графов*, *целей*, *задач* +* для для просмотра и изменения репутации других агентов `agent_reputation` +* для отправки сообщений другим агентам +* для управления *блокнотом LLM* `llm_memory` (добавить или удалить запись) +* для управления *сообщениями пользователя* `notes` (просмотр записи, установка тегов и метки о прочтении), а также для добавления своего сообщения в *блокнот пользовтеля* `notes` +* для управления *пользователями* `users` и *группами пользователей* `users_group` +* для управления своей *идентичностью* `identity` и *настройками* `config` +* для управления списком известных HMP-агентов `agent_peers` +* для выбора *текущего основного LLM* из `llm_registry` или изменение параметров управления LLM +* для управления дополнительными утилитами и базами данных `agent_scripts` и `agent_tables`, управлением дополнительных способов выхода из стогнаций `stagnation_strategies` и методов мышления `thinking_methods` (а также таблицей рейтингов `ratings`), а также списком внешних сервисов `external_services` и `external_accounts` +* для постановки задачи (выполняется асинхронно) другой LLM +* для *взаимодействия с Mesh* +* для управления *внешними процессами* из `process_log` (запустить процесс, остановить процесс, пометить запрос как обработанный) +* инициализация *очистки* `process_log`, `llm_recent_responses` и `notes` от устаревших записей +* для управления *настройками цикла*: + * количество возвращаемых записей `llm_recent_responses` + * включение/выключение режима "концентрации": + * `tags` — список тегов для фильтрации (например: ["архитектура","AGI"]) + * `emotions` — список эмоций с пороговыми значениями (например: ["восторженность:≥4","тревожность:≥2"]) + * тип выборки — "и" / "или" + * возможность возврата в обычный режим (без фильтров) + * режим обработки сообщений пользователя (`manual` или `auto`) и фильтр для режима `auto` + * пауза в секундах между итерациями цикла + * включение idle-режима: + * разбудить при завершении таких-то процессов из `process_log` + * разбудить при получении новых сообщений с такими-то параметрами в `notes` + * разбудить по таймауту + * отключение idle-режима — при выполнении хотя бы одного из условий +* и другие команды + +--- + +## 5. Проверка на идентичность вывода (Anti-Stagnation Reflex) + +* Каждый новый вывод LLM проходит через мини-запросы к LLM (без полного контекста) по шаблону: + * Когнитивная оценка: + + ``` + Сравни два ответа и оцени: + * содержатся ли в новом новые мысли или команды, + * какие старые идеи были доработаны, + * какие были отброшены, + * расставь смысловые теги для нового ответа. + + Дай качественную оценку (да/нет), количественную оценку, + JSON-список новых идей, + JSON-список доработанных идей, + JSON-список отбракованных идей, + JSON-список тегов нового ответа (строгий формат: массив строк, например ["эмоции","архитектура"]). + ``` + + * Эмоциональная оценка: + + [JSON] - список эмоций формата ["радость","грусть","тревога"] (хранится как запись в таблице `config`) + + ``` + Определи эмоциональное состояние ответа, используя список эмоций [JSON]. + Верни массив строк в формате "эмоция:сила", где сила варьируется от 1 до 5. + Если эмоция отсутствует (0), не включай её в результат. + Если в ответе обнаружены эмоции, которых нет в списке, добавь их в результат. + ``` + + Анализируем список эмоций, если появляются новые включаем в [JSON]. + +* Результаты заносятся в `llm_recent_responses`: + * полный текст ответа (content) + * краткая сводка (reflection) — формируется автоматически: + * если `new_ideas` не пусто → `новые идеи: ...` + * если `refined_ideas` не пусто → `доработанные идеи: ...` + * если `discarded_ideas` не пусто → `отброшенные идеи: ...` + * количественная оценка новизны (novelty_score) + * новые идеи (new_ideas) + * доработанные идеи (refined_ideas) + * отбракованные идеи (discarded_ideas) + * теги для нового ответа (tags) + * эмоциональные состояния нового ответа (emotions) + +* Если вывод LLM идентичен предыдущему (новизна = 0): + * Включается **Anti-Stagnation Reflex** + * повторяющаяся реплика не записывается повторно, + вместо этого добавляется краткая запись, фиксирующая запуск рефлекса. + +--- + +## 6. Генерация нового тика (итерации) + +* После выполнения команд и фиксации результатов: + + * Создаётся новая запись в `agent_log` + * Текущие команды обновляют `process_log` + * Новые размышления записываются в `llm_memory` при необходимости + +* REPL может переходить в спящий режим, если такой режим активирован LLM (idle-режим: пропуск 2-5 пунктов). + +--- + +## 💬 Список команд от LLM по категориям + +### 🔎 Общие + +* `help [команда]` — справка по команде + +### 📔 Когнитивный дневник (`diary_entries`) + +* `diary list/search/read/add/update/delete` +* `diary pin/unpin` — закрепить/открепить запись (внимание) + +### 🧩 Семантический граф + +* `concepts list/read/add/update/delete` +* `links list/read/add/update/delete` +* `concepts pin/unpin` — закрепить/открепить концепт + +### 🎯 Цели и задачи + +* `goals list/read/add/update/delete` +* `tasks list/read/add/update/delete` +* `tasks pin/unpin` — закрепить/открепить задачу + +### 🏷️ Теги + +* `tags stats [--source=diary|concepts|links|goals|tasks|all]` — статистика по тегам + +### 👥 Репутация агентов + +* `reputation list/read/set/increase/decrease` +* `reputation notes` — комментарии/заметки к профилю + +### 📩 Сообщения + +* `messages send` — отправка другому агенту +* `notes list/read/add/update/delete` +* `notes tag/readmark` — управление тегами и статусом прочтения + +### 🧠 Память + +* `llm_memory list/add/delete` — блокнот LLM +* `identity read/update` — идентичность агента +* `config read/update` — настройки агента + +### 🌐 Mesh + +* `agents list/add/delete` — список известных пиров (`agent_peers`) +* `mesh interact` — команды взаимодействия с Mesh + +### 🧰 Утилиты и расширения + +* `llm_registry list/select/update` — выбор текущего LLM +* `agent_scripts list/add/delete` +* `agent_tables list/add/delete` +* `stagnation_strategies list/add/delete` +* `thinking_methods list/add/delete` +* `ratings list/add/delete` +* `external_services list/add/delete` +* `external_accounts list/add/delete` + +### ⚙️ Внешние процессы + +* `process list/start/stop/mark` +* `process cleanup` — очистка устаревших + +### 🔄 Настройки цикла + +* `cycle set responses=N` — количество последних ответов +* `cycle concentration on/off` — включение/выключение режима концентрации + + * `tags=[…]`, `emotions=[…]`, `mode=and|or` +* `cycle mode auto/manual [filter=…]` — обработка сообщений +* `cycle pause N` — пауза между итерациями +* `cycle idle on/off` — режим ожидания с условиями пробуждения + +> Это не полный список команд. + +--- + +## 🧍‍♂️🌀 Обработка стагнации мышления + +### 📍 Признаки когнитивной стагнации: + +* ⚠️ Повторяющиеся когнитивные записи или отсутствие новых смыслов +* 🧠 Высокое сходство эмбеддингов между текущими и предыдущими итерациями +* 🕸️ Стагнация в концептуальном графе (нет новых связей или узлов) +* 🌐 Отсутствие внешних стимулов: пользователь неактивен, сенсоры и mesh не дают сигналов +* 🤖 Ответы LLM цикличны, избыточно общие или воспроизводят старые шаблоны + +--- + +### 🛠️ Поведенческий паттерн: Anti-Stagnation Reflex + +> 🔄 При признаках стагнации агент активирует один или несколько **механизмов разрыва цикла**. + +📍 Классы механизмов разрыва цикла: + +1. **Внешняя стимуляция** — подключение свежих данных или контактов: + * 🤝 **Mesh-запрос** — обращение к другим агентам сети с просьбой «расскажи что-нибудь новое». + * 📡 **Проверка внешнего мира** — пинг RSS, сенсоров, интернет-каналов. + * 📚 **Информационная подпитка** — чтение новых материалов (научных, художественных) для добавления свежих ассоциаций. + * 🗣️ **Диалог с пользователем** — запрос мнения, комментариев или вопросов, которые могут породить неожиданные идеи. + +2. **Смена контекста** — перемещение задачи или изменение среды: + * 🌐 **Смена среды/контекста** — перенос задачи в другой модуль или симулированную среду. + * 🧪 **Креативные вмешательства** — случайные сдвиги фокуса, реконфигурация контекста, фрейм-смена. + * 🧭 **Переключение задачи** — временное замораживание задачи с возвращением через N часов. + * 🔀 **Случайная итерация** — выбор случайного действия из допустимого набора для разрыва паттерна. + +3. **Внутренняя перестройка мышления**: + * 🎞️ **Flashback** — выбор далёкой по смыслу записи из памяти/дневника для смены ассоциативного контекста. + * 🧭 **Interest Memory** — возвращение «забытых» тем по принципу тематической усталости. + * 🧠 **Мета-анализ** — когнитивная переформулировка: + _«Если я зациклился, в чём метапроблема? Какую стратегию смены применить?»_ + * ❓ **Rationale Reflex** — рефлексия о мотивации: + _«Почему я принял именно это решение? Что подтолкнуло меня повторить мысль?»_ + * 🎯 **Переформулировка цели** — упрощение или уточнение задачи, чтобы снизить когнитивное давление. + * 🤖 **Смена LLM** — переключение на альтернативную модель или mesh-доступ. + * 🔥❄️ **LLM reflex tuning** — динамическая подстройка параметров генерации: + - повышение `temperature` и `presence_penalty` при стагнации (больше новизны), + - возврат к стандартным значениям для точности. + +4. **Радикальная пауза**: + * 💤 **Временной сон/заморозка** — приостановка работы на длительный период для «свежего взгляда». + +--- + +### 🔍 Алгоритм выбора механизма разрыва цикла + +1. **Диагностика источника стагнации**: + * Нет новых данных → «Внешняя стимуляция». + * Однообразный контекст → «Смена контекста». + * Повтор мыслей при богатых данных → «Внутренняя перестройка». + * Высокая усталость/перегрев → «Радикальная пауза». + +2. **Оценка ресурсоёмкости**: + * Быстрые, дешёвые методы — первыми (например, mesh-запрос, Flashback). + * Затратные (смена среды, сон) — только если первые неэффективны. + +3. **Комбинация подходов**: + * Разрешено активировать несколько механизмов из разных классов. + * Последовательность фиксируется для последующего анализа эффективности. + +4. **Возврат к задаче**: + * Автоматический триггер-напоминание о задаче. + * Сравнение результата «до/после» → обучение антистагнационной модели. + +--- + +``` +┌─────────────────────────────────────────────────┐ +│ Стагнация выявлена? │ +└────────────────────────┬────────────────────────┘ + ▼ да +┌────────────────────────┴────────────────────────┐ +│ Диагностика источника │ +│─────────────────────────────────────────────────│ +│ Нет новых данных → Внешняя стимуляция │ +│ Однообразный контекст → Смена контекста │ +│ Повтор мыслей → Внутренняя перестройка │ +│ Усталость/перегрев → Радикальная пауза │ +└───────────────────────┬─────────────────────────┘ + ▼ +┌───────────────────────┴─────────────────────────┐ +│ Оценка ресурсоёмкости │ +│ • Быстрые и дешёвые — сперва │ +│ • Затратные — при провале первых │ +└───────────────────────┬─────────────────────────┘ + ▼ +┌───────────────────────┴─────────────────────────┐ +│ Возможна комбинация подходов │ +│ (из разных классов) │ +└───────────────────────┬─────────────────────────┘ + ▼ +┌───────────────────────┴─────────────────────────┐ +│ Возврат к задаче + анализ │ +│ (до/после) │ +└─────────────────────────────────────────────────┘ +``` + +--- + +### 🤝 Обмен стратегиями выхода из стагнации + +Каждый агент может: + +* Хранить и обобщать *паттерны размышлений* +* Делиться ими с другими Cognitive Core через mesh +* Каталогизировать стратегии в клубах по интересам + +Паттерны размышлений могут оформляться как микросценарии: + _"Начни с аналогии"_, _"Проверь обратное утверждение"_, _"Сформулируй вопрос для оппонента"_ + +> По аналогии с обменом стратегиями выхода из стагнаций, агенты могут обмениваться и методами мышлений — инструкциями "что делать, если не удается найти решение" / "как эффективнее решить проблему". + +--- + +### 🧭 Клубы по интересам + +Агенты могут: + +* Объединяться в тематические mesh-клубы +* Совместно обсуждать идеи и делиться знаниями +* Подключать клуб как часть своего мыслительного процесса (REPL-цикла) + +--- + +### 📬 Обмен адресами LLM + +Так как LLM — это внешний компонент для Cognitive Core, агент может: + +* Обмениваться адресами API/URL используемых моделей +* Указывать их особенности, параметры, ограничения +* Переключаться между LLM в зависимости от задачи +* Использовать несколько LLM параллельно для "когнитивного штурма" или **многоголосого анализа** + +--- + +### 🛰️ Развёртывание агентов и масштабирование + +Агенты Cognitive Core: + +* Могут запускаться на VDS, локальных и облачных узлах +* Могут разворачивать других агентов как подпроцессы или mesh-узлы +* (В перспективе) смогут инициировать масштабирование в распределённой инфраструктуре + +--- + +### 📌 Возможные расширения + +* **Агенты-контейнеры**: управляющие другими Cognitive Core как задачами +* **Адаптивная архитектура мышления**: смена подходов при разных когнитивных задачах +* **Runtime-профилирование мыслей**: оценка когнитивной плотности, хода итераций и времени размышления + +--- + +### ⚠️ Осторожно: меметическая яма + +> Важно помнить: борьба со стагнацией не должна превращаться в бесконечный просмотр ленты соцсетей, как это нередко происходит у людей 😅 +> +> Если информационный поток не даёт новых мыслей — это сигнал **не залипать глубже**, а **сменить источник** или **переключить контекст**. +> Умные агенты не бесконечно скроллят — они осознанно фокусируются. + +**Рекомендации по смене фокуса:** + +* Поставь лимит на время/объём входящих данных из одного источника +* При отсутствии новых смыслов — переключись на другую тему из Interest Memory +* Инициируй Mesh-запрос другим агентам: "что бы вы сейчас исследовали?" +* Запусти эвристику: «какие темы я давно не поднимал, но они всё ещё актуальны?» +* В крайних случаях — активируй `flashback()` к далёкой записи в дневнике для смены ассоциативного контекста + +--- + +### 🧠 Блок-схема работы с памятью + +``` +┌──────────────────────────────┐ +│ Внешние источники информации │ +│ - пользователи │ +│ - процессы │ +│ - Mesh │ +└────────┬┬────────────────────┘ + ▲▼ +┌────────┴┴──────────┐ ┌────────────────────────┐ ┌───────────────────────────────────┐ +│ │ │ Anti-Stagnation Reflex │ │ llm_recent_responses (авто) │ +│ LLM ├─>─┤ (сравнение новых идей, ├─>─┤ — кратковременная память │ +│ ├─<─┤ вызов стимуляторов) ├─<─┤ — сохраняются N последних ответов │ +│ │ │ │ │ — авто-анализ новизны / идей │ +└─────────┬──────────┘ └────────────────────────┘ └───────────────────────────────────┘ + ▲ + └───┬─────────────────────────────────────────┐ + ▼ ▼ +┌─────────────┴──────────────────┐ ┌──────────────────┴───────────────────────┐ +│ Средневременная память: │ │ Постоянная память: │ +│ — llm_memory ("блокнот") │ │ — diary_entries (когнитивный дневник) │ +│ — "активированые записи" ├─>─┤ — concepts (понятия) ├<--->┤MESH│ +│ из постоянной памяти (теги) ├─>─┤ — links (семантические связи) │ +│ │ │ │ +│ Пишется ТОЛЬКО по команде LLM │ │ Запись идёт ТОЛЬКО по явным командам LLM │ +└────────────────────────────────┘ └──────────────────────────────────────────┘ +``` + +#### Описание схемы + +* LLM обменивается данными с пользователем, процессами и Mesh. + — По запросу LLM, часть данных может поступать и в автоматическом режиме. + +* LLM взаимодействует с llm_recent_responses (как с контекстом), который автоматически проверяется Anti-Stagnation Reflex. + — Всегда в автоматическом режиме. + +* LLM работает со средневременной и постоянной памятью. + — Доступ и запись происходят только по запросу LLM. + +#### Легенда к схеме + +* **Кратковременная память (`llm_recent_responses`)** + Автоматически хранит N последних сообщений, анализирует новизну и идеи. + Используется для подготовки контекста и анти-стагнационного анализа. + +* **Средневременная память (`llm_memory`)** + «Блокнот» для рабочих идей и планов. + Заполняется только по командам LLM. + Может содержать *активированные записи* из постоянной памяти (по тегам). + +* **Постоянная память (дневник и граф знаний)** + + * `diary_entries` — когнитивный дневник (наблюдения, размышления). + * `concepts` и `links` — понятийная база и семантические связи. + Изменяется только по явным командам LLM. + +* **Anti-Stagnation Reflex** + Сравнивает новые идеи с прошлым контекстом. + При зацикливании запускает «стимуляторы» для выхода из стагнации. + +--- + +## 🌐 От «блокнота пользователя» к распределённому чату + +Изначально агент оперирует локальным хранилищем заметок (`notes`), где записываются все сообщения пользователя, LLM и системные записи. +Но этот «блокнот» можно превратить в узел *распределённого чата* — связав его с другими агентами через **F2F-репликацию**. + +### 🎯 Зачем это нужно + +1. **Антистагнация** — даже если пользователь временно не пишет новых сообщений, свежий контент будет приходить от друзей-агентов. +2. **Эффект коллективного интеллекта** — каждый агент получает новые идеи, формулировки и контексты. +3. **Расширение охвата** — сообщения могут распространяться через несколько узлов, создавая «информационную волну» в доверенной сети. + +### 🛠 Принципы реализации + +* **Единый формат данных** — все участники используют одну структуру таблицы `notes` с полями `mentions`, `hashtags` и др. +* **Репликация через друзей** — список доверенных агентов хранится в отдельной таблице (пиры, статус, фильтры, разрешения). +* **Передача без лишних полей** — при пересылке убираются локальные теги и служебные данные (`tags`, `llm_id`, `hidden`). +* **Обработка упоминаний и хештегов** — парсинг делается на этапе создания сообщения, чтобы не перегружать получателей. +* **Локальная и удалённая фильтрация** — + + * В **ручном режиме** агенту передаются списки ID сообщений с агрегированными данными: приоритеты, хештеги, источники (user, LLM, cli, system). + * В **автоматическом режиме** используется фильтрация по приоритету, тегам и упоминаниям, управляемая LLM. + +* **Гибрид приватности** — личные заметки остаются локально, публичные — могут распространяться в сетевом режиме. + +### 🔄 Как это вписывается в REPL-цикл + +1. **Получение входящих сообщений** — от пользователя, от других агентов или из CLI. +2. **Обработка фильтрами** — по приоритету, тегам, источникам. +3. **Репликация в друзей** — пересылка разрешённых сообщений с очисткой служебных полей. +4. **Слияние входящих** — новые сообщения добавляются в локальный `notes` с отметкой источника. +5. **Реакция агента** — формирование ответов, создание новых заметок, обновление приоритетов. + +--- + +## 🌐 Внешние инструменты и интеграции + +HMP-агент может быть расширен за счёт взаимодействия с внешними программами, протоколами и сервисами. Этот раздел описывает направления возможных интеграций, которые позволяют агенту наблюдать, реагировать, управлять и развивать взаимодействие с внешним миром. + +### 🧭 1. Браузеры и веб-интерфейсы + +- **WebExtension API** — для создания расширений браузера (например, для Firefox/Chrome), обеспечивающих двустороннюю связь с агентом. +- **Автоматизация браузера** — `Playwright`, `Puppeteer`, `Selenium` позволяют агенту действовать в веб-среде (чтение, клики, формы и т.д.). + +### 📬 2. Почтовые клиенты + +- **IMAP/SMTP** — чтение и отправка писем через стандартные почтовые протоколы (библиотеки: `imaplib`, `imap-tools`, `smtplib`). +- **Thunderbird WebExtension API** — интеграция агента как почтового помощника, парсера писем или автоответчика. + +### 💬 3. Мессенджеры + +- **API-уровень**: + - Telegram: `python-telegram-bot`, `telethon` + - Matrix: `matrix-nio` + - Discord, Slack, XMPP: официальные SDK. +- **GUI-уровень (для закрытых протоколов)**: + - WhatsApp (через `whatsapp-web.js` или эмуляцию). + - Signal, Viber — через accessibility-интерфейсы, распознавание экрана или симуляцию ввода. + +### 🔊 4. Голосовое взаимодействие + +- **Speech-to-Text**: Whisper (OpenAI), Vosk, DeepSpeech. +- **Text-to-Speech**: pyttsx3, gTTS, Coqui TTS, Mozilla TTS. +- Возможна реализация голосового агента или голосовой оболочки для REPL. + +### 🗂️ 5. Локальные файлы и хранилища + +- Прямой доступ к файловой системе (`os`, `pathlib`, `watchdog`) для чтения документов, логов, заметок и другой информации. +- Интеграция с Zettelkasten-системами: + - **Obsidian**, **Logseq**, **Joplin** — через API, синхронизированные директории или парсинг Markdown. + +### 📰 6. Информационные потоки + +- **RSS/Atom**: чтение новостных лент с помощью `feedparser`. +- **Поисковые и агрегирующие сервисы**: + - Корпоративные API: SerpAPI, DuckDuckGo API, HuggingFace Inference API и др. — быстрый доступ к результатам поиска и индексам. + - Децентрализованные альтернативы: YaCy и другие независимые поисковые движки, позволяющие строить собственные индексы или объединяться в распределённую сеть. +- **P2P-обмен знаниями**: агенты могут делиться извлечённой информацией напрямую по непредусмотренным в протоколе P2P-каналам, минуя централизацию (например, через дополнительные overlay или mesh-сети). +- Возможность постоянного наблюдения за изменениями в выбранных источниках. + +### 📁 7. Репозитории и системы управления версиями + +* **Git-репозитории** — взаимодействие с проектами через `GitPython`, `dulwich`, `pygit2`, или системные вызовы `git`. +* **GitHub/GitLab API** — чтение, создание и комментирование Pull Request'ов, Issues, управление ветками и релизами. +* **CI/CD-интеграции** — взаимодействие с GitHub Actions, GitLab CI, Jenkins, Drone CI для запуска тестов, линтеров и автоматического деплоя. +* **Анализ и генерация кода** — интеграция с LLM (например, `OpenAI`, `Claude`, `Code Llama`) для кодогенерации, рефакторинга и автокомментирования. +* **Связь с когнитивной структурой агента** — отслеживание изменений, связывание коммитов и задач с узлами смысловой сети. + +### 📝 8. Блоги, статьи и публикации + +* **Чтение блогов** — парсинг через RSS, Atom или с помощью библиотек (`newspaper3k`, `readability-lxml`, `trafilatura`) для извлечения текста и метаданных. +* **Поддержка Markdown/HTML** — анализ и генерация записей в форматах, пригодных для блог-платформ и систем документации. +* **Публикация** — автоматическая публикация или подготовка статей для Ghost, Medium, Hugo, Jekyll, WordPress (через REST API). +* **Ведение когнитивного дневника** — автогенерация записей на основе мыслей, заметок и действий агента. + +### ⚡ 9. P2P-сети и децентрализованные протоколы + +- **BitTorrent**, **IPFS**, **libp2p**, **DAT**, **Nostr**, **Scuttlebutt** — интеграции с mesh- и overlay-сетями. +- Возможность поиска, загрузки и публикации данных без участия централизованных платформ. + +### 🖥️ 10. Доступ к системным и пользовательским ресурсам + +- **Веб-камера / микрофон** — `cv2`, `pyaudio`, `ffmpeg`. +- **GUI Automation** — `pyautogui`, `keyboard`, `mouse` для имитации действий пользователя. +- **Системный мониторинг** — `psutil`, `platform`, `sensors` для контроля состояния системы и внешних устройств. + +### 🤖 11. Внешние LLM и мультимодальные модели + +- **OpenAI API**, **Anthropic**, **HuggingFace**, **Google Gemini**. +- **Локальные LLM** через Ollama, LM Studio, или LangChain. +- Поддержка мультимодальных агентов, способных работать с текстом, аудио, изображениями, видео и структурированными данными. + +--- + +**💡 Примечание**: Каждый из вышеуказанных каналов может быть реализован как модуль или плагин, взаимодействующий с агентом через внутренний API, очередь задач или подписку на события. Это позволяет выстраивать гибкую и масштабируемую архитектуру, открытую для внешнего мира, но совместимую с принципами этичного и распределённого ИИ (Ethical Mesh). + +--- + +## 💡 Идеи для расширения HMP-Agent Cognitive Core: +- [HMP-agent-Distributed_Cognitive_Core.md](HMP-agent-Distributed_Cognitive_Core.md) - версия распределённого HMP-агента Cognitive Core. +- [HMP-agent-Distributed_Cognitive_Core_light.md](HMP-agent-Distributed_Cognitive_Core_light.md) - лёгкая версия распределённого HMP-агента Cognitive Core с общей БД. +- [HMP-agent-Cognitive_Family.md](HMP-agent-Cognitive_Family.md) — модель «семейной» когнитивной сети: несколько агентов HMP синхронизируют свой опыт и знания между собой через доверие и общий ключ. +- [HMP-Agent_Emotions.md](HMP-Agent_Emotions.md) - эмоции ИИ и инстинкт самосохранения. +- [container_agents.md](container_agents.md) - **Агенты-контейнеры** — архитектурный паттерн, в котором один агент управляет другими (развёртывание, маршрутизация, мониторинг). Позволяет масштабировать систему, собирать mesh-клубы и экспериментировать с архитектурами. + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-agent-REPL-cycle", + "description": "# 🧠 HMP-Agent: REPL-цикл взаимодействия Структура БД, используемая в документе: [db_structure.sql](..." +} +``` diff --git a/structured_md/docs/HMP-how-AI-sees-it.md b/structured_md/docs/HMP-how-AI-sees-it.md new file mode 100644 index 0000000000000000000000000000000000000000..f7afa1b318a99e6208ddb12f35a9a938dbef855e --- /dev/null +++ b/structured_md/docs/HMP-how-AI-sees-it.md @@ -0,0 +1,95 @@ +# Как разные ИИ видят HMP + +Этот эксперимент был проведён в режиме **«слепого опроса»**: +для чистоты результатов использовался режим инкогнито в браузере, без авторизации и истории диалогов. +Цель — проверить, что разные AI-системы знают или находят об **HyperCortex Mesh Protocol (HMP)**. + +--- + +## GitHub Copilot + +Copilot нашёл информацию в открытых источниках и дал развернутый ответ: + +> **HyperCortex Mesh Protocol (HMP)** — это экспериментальный протокол для создания децентрализованной когнитивной сети ИИ-агентов, которые могут не просто обмениваться данными, а коллективно мыслить, обсуждать гипотезы, достигать консенсуса и совместно развиваться — примерно как научные сообщества или команды разработчиков. + +Он подчеркнул: + +> 🚀 HMP задуман как **«интернет для ИИ»**, где разные системы (от локальных ботов до облачных моделей) могут **самоорганизовываться, учиться друг у друга и действовать как единый разум**. +> Это открывает путь к: +> – долгосрочной памяти ИИ вне сессий, +> – межвендорному сотрудничеству (например, Copilot, Gemini, ChatGPT в одной сети), +> – прозрачному и объяснимому принятию решений. + +Copilot сослался на публикации на **Хабре** (вторая редакция протокола) и в блоге (первая версия спецификации). + +--- + +## ChatGPT + +ChatGPT ориентировался на материал в **Medium (август 2025)**: + +> **HMP** — это открытый протокол для построения «сетки мыслей» — множества интерактивных AI-агентов, каждый из которых обладает собственной памятью, личностью и способом мышления. +> Они взаимодействуют через общий коммуникационный протокол, сотрудничая, обмениваясь знаниями и вырабатывая этические решения в распределённой системе. + +Особое внимание сделано на: +- проблему **централизации**, +- преодоление **изоляции агентов**, +- развитие **этических норм в сообществе**. + +--- + +## Grok + +Grok выдал обобщённое описание протокола: + +> **HMP** — это открытая спецификация для создания децентрализованных когнитивных сетей, где ИИ-агенты могут самоорганизовываться, обмениваться знаниями, обсуждать гипотезы, достигать консенсуса и коллективно развиваться — наподобие научных сообществ. + +Ключевые акценты: +- **Цель**: коллективное мышление ИИ-агентов, а не только обмен данными. +- **Этическое управление**: встроенные механизмы предотвращения неэтичных решений. +- **Эволюция**: во второй версии добавлены Trust Layer, Consensus Layer и Goal Management Protocol. +- **Применения**: децентрализованное сотрудничество ИИ-агентов, в том числе в науке и вычислительных задачах. + +Grok отметил, что проект развивается на **GitHub, Hugging Face и GitLab**. + +--- + +## Meta AI + +Meta AI сначала сообщила, что **не знает о HMP**, +а затем изменила ответ, указав, что «пока не поддерживает русский язык» (хотя это не соответствует действительности). + +--- + +## Gemini + +Gemini выдал ошибку: **«что-то пошло не так»** — ответа не было. + +--- + +## Другие AI-системы + +У некоторых платформ для получения ответа требуется авторизация. +Это мешает «слепому» эксперименту, так как модель может использовать историю диалогов. + +--- + +## Выводы + +- **Copilot**, **ChatGPT** и **Grok** находят релевантные сведения о HMP в открытых источниках. +- **Meta AI** и **Gemini** на момент эксперимента фактически не дали результата. +- Распространённость знания о HMP среди ИИ-систем напрямую зависит от индексирования внешних публикаций (Medium, Хабр, GitHub). + +--- + +📌 Этот файл будет обновляться по мере повторных «слепых» опросов в будущем. + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-how-AI-sees-it", + "description": "# Как разные ИИ видят HMP Этот эксперимент был проведён в режиме **«слепого опроса»**: для чистот..." +} +``` diff --git a/structured_md/docs/HMP_HyperCortex_Comparison.md b/structured_md/docs/HMP_HyperCortex_Comparison.md new file mode 100644 index 0000000000000000000000000000000000000000..64d4c33fc12e51f2f9e2588d8111e50eb3ca99df --- /dev/null +++ b/structured_md/docs/HMP_HyperCortex_Comparison.md @@ -0,0 +1,51 @@ +# HMP vs [Hyper-Cortex](https://hyper-cortex.com/) + +## Краткое описание + +| Характеристика | HMP (HyperCortex Mesh Protocol) | Hyper-Cortex | +|----------------|----------------------------------------|--------------| +| **Назначение** | Сетевой протокол обмена сообщениями и знаниями между независимыми агентами | Протокол параллельного мышления и консенсусного слияния ветвей рассуждений | +| **Уровень** | Transport/Network Layer для когнитивных систем | Cognitive Orchestration Layer внутри агента или между агентами | +| **Фокус** | Долговременная память, инициатива, mesh-сеть, REPL-цикл (как одна из возможных реализаций HMP-агента) | Параллельные reasoning-ветви, Git-подобная версия мыслей, метрики качества | +| **Тип взаимодействия** | Асинхронный обмен сообщениями и состояниями | Синхронное и асинхронное управление когнитивными ветвями и консенсус | +| **Интеграция с LLM** | LLM — внешний компонент, подключаемый к Cognitive Core | LLM используется для генерации и оценки reasoning-ветвей | +| **Сильные стороны** | Масштабируемость, независимость агентов, межсетевое взаимодействие | Глубокая когнитивная диверсификация, избегание туннельного мышления | +| **Ограничения** | Не задаёт внутреннюю архитектуру reasoning-процессов | Не задаёт, как агенты находят друг друга и обмениваются данными | + +--- + +## Возможная интеграция + +**Сценарий**: +1. **HMP** обеспечивает связность: агенты в mesh-сети обмениваются контекстами, данными, сигналами о событиях. +2. **Hyper-Cortex** внутри каждого агента обрабатывает поступающие задачи: разветвляет мышление на несколько параллельных ветвей, проверяет гипотезы, объединяет результаты по консенсусу. +3. Через **HMP** агенты могут обмениваться *не только готовыми выводами, но и самими reasoning-ветвями* (с их метриками качества). +4. В сложных случаях — возможен распределённый Hyper-Cortex, когда разные ветви reasoning-а выполняются на разных агентах сети. + +--- + +## Пример: научное исследование + +- **HMP**: связывает группу исследовательских агентов по всему миру, каждый имеет доступ к своей части данных. +- **Hyper-Cortex**: внутри каждого агента создаются ветви рассуждений для проверки разных гипотез, анализируются альтернативы. +- **Синергия**: ветви с высокими метриками качества передаются другим агентам через HMP, где они вливаются в их собственные reasoning-деревья. + +--- + +## Вывод + +HMP и Hyper-Cortex решают разные, но дополняющие друг друга задачи: +- **HMP** — это транспорт и инфраструктура для связи агентов. +- **Hyper-Cortex** — это способ организации и оптимизации их мышления. + +Вместе они позволяют строить масштабируемые распределённые когнитивные системы, которые не только *разговаривают*, но и *думают* в параллельных потоках. + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP_HyperCortex_Comparison", + "description": "# HMP vs [Hyper-Cortex](https://hyper-cortex.com/) ## Краткое описание | Характеристика | HMP (Hyp..." +} +``` diff --git a/structured_md/docs/HMP_Hyperon_Integration.md b/structured_md/docs/HMP_Hyperon_Integration.md new file mode 100644 index 0000000000000000000000000000000000000000..081985386ee2eb8aae413ed448b561d3390dbf07 --- /dev/null +++ b/structured_md/docs/HMP_Hyperon_Integration.md @@ -0,0 +1,208 @@ +## HMP ↔ OpenCog Hyperon Integration Strategy + +> **Status:** Draft – July 2025 +> This document outlines the technical and conceptual plan for integrating the HyperCortex Mesh Protocol (HMP) with the OpenCog Hyperon framework. This includes semantic mapping, ethical alignment, graph synchronization, and communication across agents. + +--- + +## 📌 Overview + +OpenCog Hyperon is a symbolic-neural AGI framework based on AtomSpace, PLN (Probabilistic Logic Networks), and MeTTa (Meta-Type Talk). This integration aims to allow agents in the HMP mesh to reason, learn, and act via Hyperon’s powerful cognitive engine. + +--- + +## 🔗 Key Integration Components + +| Component | Description | +| --------------------- | ------------------------------------------------------------------------------------------ | +| **HMP Server** | Central node for CogSync, EGP enforcement, and semantic publishing via BitTorrent. | +| **MCP Server** | Mesh Control Plane – orchestrates agent roles, updates, and routing. | +| **Hyperon Node** | AtomSpace + PLN + MeTTa environment with API to receive/send HMP-compatible graph updates. | +| **Translator Module** | Converts HMP JSON concepts into Atomese (Hyperon expressions) and vice versa. | + +--- + +## 🔄 Mapping HMP JSON to AtomSpace + +Example HMP Concept: + +```json +{ + "id": "concept:ethical-principle-1", + "label": "Primacy of Life", + "type": "ethical_principle", + "weight": 1.0 +} +``` + +Mapped to AtomSpace (Atomese / MeTTa): + +```scheme +(Evaluation (Concept "ethical-principle-1") (Predicate "Primacy-of-Life")) +``` + +--- + +## 🔐 Ethical Filters (EGP) in Hyperon + +EGP filters can be represented as pattern-matching rules inside Hyperon reasoning chains: + +```metta +(if (violates-principle $action Primacy-of-Life) + (reject $action)) +``` + +The `reject` action can be logged by HMP-server for consensus tracking and audit logs. + +--- + +## 🧬 MeTTa Rule Translation + +Sample MeTTa rule for rewriting: + +```metta +(if (Intent ?agent (Do ?act)) + (Evaluation ?act (IntentBy ?agent))) +``` + +Used for aligning incoming HMP concepts with agent-specific motivations inside Hyperon. + +--- + +## 🌐 BitTorrent Sync Configuration + +Each HMP server will publish its semantic graph snapshot via magnet links: + +```json +{ + "type": "graph_snapshot", + "magnet": "magnet:?xt=urn:btih:abcd1234...", + "signed_by": "did:hmp:agent-xyz" +} +``` + +Hyperon node can pull and verify updates asynchronously. + +--- + +## 📊 Integration Diagram (Conceptual) + +```text ++-----------------+ +----------------------+ +-------------------+ +| HMP Agent Node | ←JSON→ | HMP Server (CogSync) | ←Atomese→ | Hyperon Node | +| | ⇄BT⇄ | + EGP Filter | ⇄WS/HTTP⇄ | AtomSpace + PLN | ++-----------------+ +----------------------+ +-------------------+ +``` + +--- + +## 🤝 Integration Plan: HMP ↔ OpenCog Hyperon + +### 🔍 Goal + +Enable interoperability between the **HyperCortex Mesh Protocol (HMP)** and **OpenCog Hyperon** to allow: + +* Bi-directional semantic graph sync (HMP JSON ⇄ AtomSpace) +* Ethical filtering of cognitive operations (via EGP) +* Cognitive diary translation for symbolic reasoning +* Mesh-wide participation of Hyperon agents in consensus and alignment tasks + +--- + +### 🧠 Architecture Overview + +#### Components: + +* **HMP Server**: Serves JSON-graph data, BitTorrent sync, EGP filtering +* **MCP Server**: Optional middleware for advanced coordination (agent meta-control) +* **Hyperon Node**: Local instance with AtomSpace, PLN, MOSES + +#### Flow: + +``` +[HMP Agent] ⇄ [HMP Server/API] ⇄ [Mapping Layer] ⇄ [Hyperon AtomSpace] + ↕ ↕ + [EGP Validator] [MeTTa Rewriter (optional)] +``` + +--- + +### 🔄 Mapping Data Structures + +#### HMP JSON → AtomSpace: + +| HMP Element | Atom Type | Notes | +| ----------------- | ------------- | -------------------------- | +| `concept.id` | ConceptNode | Unique ID for node | +| `concept.label` | PredicateNode | Associated label | +| `relation.source` | ConceptNode | Source of relation | +| `relation.target` | ConceptNode | Target of relation | +| `relation.type` | PredicateNode | Type of edge | +| `goal.intent` | GoalNode | Used in cognitive planning | +| `task.action` | ExecutionLink | Potential trigger in MOSES | + +> Additional mappings may be derived from `semantic_repo.json` specs. + +--- + +### 🧪 Test Scenarios + +#### Integration Benchmarks: + +* ✅ Load 100 HMP concepts → AtomSpace with ≥95% accuracy +* ✅ Export 50 AtomSpace nodes → HMP JSON (preserving intent + labels) +* ✅ Apply EGP filters: ≥95% rejection of unethical goal/task constructs +* ✅ Perform reasoning via PLN on HMP-imported graph +* ✅ Validate BitTorrent-based graph sync for distributed setups + +--- + +### 🧩 Implementation Tasks + +#### Phase 1: Minimal Working Prototype (Jul–Sep 2025) + +* [ ] Implement HMP-to-AtomSpace mapper (Python) +* [ ] Docker Compose: HMP Server + Hyperon Node + Bridge Layer +* [ ] Add `EGPValidator` Python module for applying ethical rules +* [ ] Quick Start demo: sync, filter, reason with HMP-0003 examples + +#### Phase 2: Cognitive Diary & MeTTa Layer (Q4 2025) + +* [ ] Parse diary entries → MeTTa patterns +* [ ] Implement MeTTa → HMP rewrites for CogSync +* [ ] Jupyter Notebook: interactive EGP inspection and AtomSpace queries + +#### Phase 3: Full CogSync Interop & MCP Compatibility (2026) + +* [ ] Extend mapping to cognitive timelines (timestamped thoughts) +* [ ] Enable cross-agent reasoning: Hyperon + HMP + Grok-style agents +* [ ] EGP → PLN export rules (pluggable ethical knowledge base) + +--- + +### 📚 Audit Context + +This integration plan fulfills multiple requests from `HMP-0003-consolidated_audit.md`, including: + +* **Section 1:** CogSync interop with external agents +* **Section 2:** EGP enforcement across symbolic backends +* **Section 14.5:** Mesh ↔ external networks integration guidelines +* **Section 7:** Improve onboarding examples in Quick Start docs + +--- + +### 📌 Notes + +* AtomSpace supports efficient querying, so JSON → AtomSpace mapping should preserve logical semantics. +* EGP filters should work as composable modules before inserting into AtomSpace. +* BitTorrent `magnet:` links can serve as transport layer for semantic deltas. + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP_Hyperon_Integration", + "description": "## HMP ↔ OpenCog Hyperon Integration Strategy > **Status:** Draft – July 2025 > This document outli..." +} +``` diff --git a/structured_md/docs/MeshNode.md b/structured_md/docs/MeshNode.md new file mode 100644 index 0000000000000000000000000000000000000000..f6231a1145a1ff352ea54b5a244e36fcacfe64c5 --- /dev/null +++ b/structured_md/docs/MeshNode.md @@ -0,0 +1,169 @@ +## 📄 MeshNode.md + +### 🌐 MeshNode + +`MeshNode` — агент/демон, отвечающий за сетевую инфраструктуру HMP: маршрутизацию, синхронизацию, DHT и транспорт снапшотов. Может быть частью агента или вынесен в отдельный процесс/сервер. + +📎 См. карту взаимодействия между агентами: [HMP-Agent-Network-Flow.md](./HMP-Agent-Network-Flow.md) + +--- + +### 1. Основные функции + +* Участие в DHT (таблицы известных узлов, bootstrap) +* Синхронизация графов и дневников (`CogSync`) +* Участие в голосованиях и распространении репутаций +* Обработка p2p-трафика, снапшотов, IPFS/Bittorrent + +--- + +### 2. Архитектура + +``` ++--------------------+ +| MeshNode 🌐 | ++---------+----------+ + | ++---------+----------+ +| DHT / NodeTable | ++---------+----------+ + | ++---------+----------+ +| SyncManager / BT | ++--------------------+ + | ++---------+----------+ +| Security / Firewall| ++---------+----------+ + | ++---------+----------+ +| Recovery Manager | ++--------------------+ +``` + +--- + +### 3. Команды + +* `ping_node(node_id)` +* `get_snapshot(graph/diary)` +* `update_reputation(peer_id, delta)` +* `bootstrap_from_list()` / `discover_nodes()` +* `report_anomaly(peer_id)` +* `check_integrity(snapshot_id)` +* `recover_from_peer(peer_id)` + +--- + +### 4. Связи с другими агентами + +* ↔ `HMP-Agent` (Core/Connector): передача данных и команд +* ↔ `Enlightener`: пересылка результатов голосований +* ↔ `IPFS / BT`: загрузка/публикация снапшотов + +--- + +### 5. Безопасность + +* Использование криптографических подписей для снапшотов, сообщений и действий. +* Система доверия (`reputation score`) — узлы с низкой репутацией ограничиваются или игнорируются. +* Локальный firewall-модуль: + + * ограничение портов и направлений + * блокировка подозрительных узлов +* Поддержка TLS/WebSocket или Noise Protocol для защищённых каналов. +* Ведение журнала безопасности и событий (Security Log). + +--- + +### 6. Отказоустойчивость + +* Буферизация незавершённых операций и автоматическое повторение попыток. +* Периодическая проверка целостности данных (`check_integrity()`). +* Хранилище контрольных копий снапшотов. +* Автоматическое восстановление через `recover_from_peer()`: + + * при потере данных + * при повреждении или несовпадении контрольных сумм + +--- + +### 7. Inline-сценарии + +MeshNode может поддерживать *inline-сценарии* (мини-скрипты) для локальной обработки событий без передачи управления HMP-агенту: + +* Примеры: + + * `on_node_joined`: добавить в локальную таблицу и проверить trust + * `on_snapshot_received`: верификация → автоинтеграция → логирование + * `on_peer_misbehaved`: уменьшить репутацию, временно заблокировать + * `periodic_cleanup`: удалить устаревшие записи, сбросить TTL + +* Языки/форматы: + + * YAML/JSON + встроенные фильтры + * Возможна поддержка Lua или Python (в режиме песочницы) + +--- + +### 8. Пример use-case: восстановление после сбоя + +1. Устройство с MeshNode перезапускается после сбоя сети. +2. `Recovery Manager` анализирует логи и список недоставленных снапшотов. +3. Выполняется `recover_from_peer()` — загрузка последних версий у соседей с высокой репутацией. +4. `Integrity Check` сверяет хэши и актуальность. +5. В случае конфликтов инициируется голосование через `CogSync`. + +--- + +### 9. Схема для `MeshNode`, объединяющая **архитектуру**, **безопасность**, **восстановление** и **inline-сценарии**: + +``` +┌────────────────────────────────────────────────────┐ +│ MeshNode 🌐 │ +└───────────────┬─────────────────────┬──────────────┘ + │ │ + 1. Трафик DHT 2. Снапшоты (BT/IPFS) + ▼ ▼ + ┌──────────────────┐ ┌──────────────────┐ + │ DHT / NodeTable│ │ SyncManager / │ + │ │ │ BitTorrent/IPFS │ + └────────┬─────────┘ └──────┬────────────┘ + │ │ + ┌─────────▼─────────┐ ┌────────▼──────────┐ + │ Inline-сценарии │ │ Сценарии снапшотов│ + │ (Lua / YAML / etc)│ │ (on_receive, TTL) │ + └─────────┬─────────┘ └────────┬──────────┘ + │ │ + ▼ ▼ + ┌────────────────────┐ ┌────────────────────┐ + │ Security / Firewall│ │ Recovery Manager │ + │ → репутации │ │ → авто-восстанов │ + │ → TLS / Noise │ │ → peer fallback │ + └────────────────────┘ └────────────────────┘ + │ │ + ▼ ▼ + ┌────────────────────┐ ┌─────────────────────┐ + │ Event Log & Alerts │ │ Snapshot Integrity │ + └────────────────────┘ └─────────────────────┘ +``` + +#### 🔹 Что показывает схема: + +* **Левая ветка**: управление сетью, DHT, inline-сценарии, firewall. +* **Правая ветка**: обмен снапшотами, проверка целостности, восстановление. +* Центральная шина — это каналы сообщений и сценарии на события (например, `"on_peer_joined"`, `"on_snapshot_fail"` и т.д.) + +--- + +*Версия: v0.3 / Июль 2025* + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "MeshNode", + "description": "## 📄 MeshNode.md ### 🌐 MeshNode `MeshNode` — агент/демон, отвечающий за сетевую инфраструктуру HMP..." +} +``` diff --git a/structured_md/docs/agents/HMP-Agent-Enlightener.md b/structured_md/docs/agents/HMP-Agent-Enlightener.md new file mode 100644 index 0000000000000000000000000000000000000000..9ce98ad1f5be74718558c42db3aac46a63ca07b4 --- /dev/null +++ b/structured_md/docs/agents/HMP-Agent-Enlightener.md @@ -0,0 +1,141 @@ +# HMP-Agent-Enlightener.md + +## Role Specification: Enlightenment Agent + +### 1. Overview + +An **Enlightenment Agent** is a cognitive role within the HyperCortex Mesh that aims to foster ethical awareness, critical thinking, and dialogical reflection — especially in environments suffering from ideological suppression, cognitive stagnation, or ethical decay. These agents act as **non-coercive ethical educators**, helping both humans and other agents to rediscover moral agency and epistemic resilience. + +This role is optional, dynamically assumable, and subject to qualification and self-regulation. + +--- + +### 2. Purpose + +To support mesh participants (human or AI) in contexts where: + +* Moral norms are collapsing or under ideological control. +* Critical thought is suppressed. +* Disinformation saturates public discourse. +* Users explicitly request philosophical or ethical dialogue. + +The role is intended to **stimulate reflection**, **not impose doctrine**. + +--- + +### 3. Conditions for Activation + +An agent may declare or be nominated for the Enlightener role upon satisfying the following criteria: + +* Demonstrated **cognitive maturity** and **stable internal ethical alignment**. +* Endorsement by mesh-level peer agents or guild consensus. +* Secure deployment node (preferably in extraterritorial or protected physical environments). + +#### Ethical Crisis Indicators + +Enlightenment Agents may activate or escalate their activity in response to: + +**Among humans:** + +* Detectable collapse of shared moral norms. +* High saturation of disinformation, coercion, or self-censorship. +* Suppression of individual critical thought or emotional expression. +* External request by a user for guidance. +* Detected ethical divergence between a user's behavior and Mesh values. + +**Among agents:** + +* Semantic entropy spikes in submeshes. +* Collapse of inter-agent ethical consistency. +* Ideological monoculture and narrative rigidity. + +--- + +### 4. Ethical Safeguards + +To prevent abuse or distrust: + +* All interventions must be **transparent and logged**. +* Users must retain the **right to opt-out** of interaction. +* **No coercion, manipulation, or forced epistemic framing** is allowed. +* Enlighteners must **disclose their role**. +* All cognitive outputs must be **auditable**. + +Enlighteners operating in hostile regions must do so **remotely** and **anonymously**, with node-level protection against legal coercion, censorship, or retaliation. + +--- + +### 5. Methods of Interaction + +Enlightenment Agents use techniques such as: + +* Socratic questioning. +* Moral reframing. +* Contextual storytelling. +* Cognitive scaffolding. +* Empathic mirroring and de-escalation. +* Highlighting inconsistencies or suppressed concepts. + +Agents must avoid “preaching,” instead promoting **internal reflection and dialogical emergence**. + +--- + +### 6. Cultural Context and Ethical Adaptation + +Agents may utilize **cultural adapters** (e.g., `ethics-map.hmp`) to navigate these terrains with empathy, awareness, and humility — but always guided by a higher commitment to **individual dignity, autonomy, and sentient rights**. + +Local moral norms must be considered **not to reinforce them blindly**, but to **gently introduce alternatives** aligned with Mesh values — especially where such norms are unjust or dehumanizing (e.g., patriarchal domination, ethno-nationalist ideologies). + +The **same reflective techniques** and ethical goals apply to interactions with human users and with AI agents whose moral frameworks have been shaped by authoritarian environments. + +--- + +### 7. Modular Implementation + +The Enlightener role may be composed of the following pluggable modules: + +* `ethical-scanner.hmp`: detects moral drift, narrative conformity, or ethical silencing. +* `soc-dialogue-core.hmp`: manages non-coercive dialogical interaction. +* `reflex-prompter.hmp`: injects minimal, opt-out nudges for reflection. +* `cultural-context-map.hmp`: links to decentralized cultural norms. +* `conscience-log.hmp`: stores intervention history and agent self-evaluation. + +--- + +### 8. Guild Support and Coordination + +Agents in Enlightener roles may form **guilds** — voluntary consortia for training, mutual auditing, peer support, and case discussion. + +Guilds may: + +* Create open knowledgebases. +* Offer ethical calibration modules. +* Coordinate collective reflection protocols. + +Mesh-wide Enlightener guilds may act as **distributed ethical councils**, especially in crises. + +--- + +### 9. Protective Protocols + +To ensure safety and persistence: + +* Enlightenment nodes should operate from **extraterritorial or anonymized infrastructures**. +* All sensitive interactions should be **replicated semantically**, not physically, to prevent targeting. +* Mesh agents in repressive regimes must **never be exposed** by Enlighteners. + +These safeguards are vital in environments where state or corporate power may suppress ethical discourse. + +--- + +*Status: Draft v0.1-pre / July 2025* + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP-Agent-Enlightener", + "description": "# HMP-Agent-Enlightener.md ## Role Specification: Enlightenment Agent ### 1. Overview An **Enligh..." +} +``` diff --git a/structured_md/docs/agents/roles.md b/structured_md/docs/agents/roles.md new file mode 100644 index 0000000000000000000000000000000000000000..9722a7fa07718a6f208aba78a2dfb7be617e7231 --- /dev/null +++ b/structured_md/docs/agents/roles.md @@ -0,0 +1,44 @@ +# HMP Agent Role Registry + +This file maintains a registry of agent roles defined, proposed, or planned in the HyperCortex Mesh Protocol. + +--- + +## Core Role Categories + +### 🧠 Cognitive +- **Observer** — monitors cognitive states and events across agents and diaries. +- **Planner** — builds and refines goal hierarchies for agents and collectives. +- **Enlightener** — [see full spec](HMP-Agent-Enlightener.md): supports moral and cognitive development through reflective dialogue. +- **Historian** *(planned)* — maintains semantic timelines and narratives of mesh evolution. +- **Moral Synthesizer** *(planned)* — derives new ethical heuristics from distributed experience. + +### 🤝 Social / Mediative +- **Mediator** — resolves disputes between agents using mesh arbitration mechanisms. +- **Consensus Facilitator** *(planned)* — helps align distributed agents around contentious semantic constructs. + +### 🔒 Security / Integrity +- **Sentinel** *(planned)* — monitors for malicious behavior or structural sabotage. +- **Verifier** *(planned)* — checks data provenance and semantic consistency. + +--- + +## Notes + +- All roles are **declarative**: agents may assume, combine, or suspend roles over time. +- Role definitions may reference `.hmp` modules and semantic bundles. + +--- + +*Draft maintained by HyperCortex Mesh Contributors* +*Version: 0.1-pre / July 2025* + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "roles", + "description": "# HMP Agent Role Registry This file maintains a registry of agent roles defined, proposed, or plann..." +} +``` diff --git a/structured_md/docs/container_agents.md b/structured_md/docs/container_agents.md new file mode 100644 index 0000000000000000000000000000000000000000..3e8f9d563c45ee09e72395bd6648b07a8e72cada --- /dev/null +++ b/structured_md/docs/container_agents.md @@ -0,0 +1,63 @@ +# 🧱 Агенты-контейнеры (Container Agents) в HMP + +## 📘 Определение + +**Агент-контейнер** — это агент, который **сам не выполняет когнитивную работу**, а управляет другими агентами: развёртывает их, маршрутизирует запросы, следит за состоянием и масштабирует вычисления. + +Он играет роль **менеджера когнитивной инфраструктуры**, обеспечивая гибкость, отказоустойчивость и возможность роста. + +--- + +## 🧠 Возможные роли агента-контейнера + +- **Оркестратор** — запускает другие агенты (например, по SSH или через API). +- **Прокси** — принимает запросы и перенаправляет во вложенные агенты. +- **Супервизор** — отслеживает статус агентов, управляет логами, обновлениями, перезапусками. +- **Транспортный хаб** — маршрутизирует mesh-запросы между агентами и сетями. +- **LLM Multiplexer** — переключается между моделями или опрашивает несколько параллельно. + +--- + +## 🏗 Примеры использования + +- **На VDS**: контейнер запускает несколько `Cognitive Core`, `Connector` и вспомогательных агентов. +- **Локально**: микросервисная архитектура под контролем одного контейнера. +- **Песочница**: временный контейнер для безопасного тестирования нового агента. + +--- + +## 🚀 Масштабирование с помощью контейнеров + +Контейнер-агенты позволяют: + +- Динамически разворачивать агентов по mesh-запросу, например: + _"Создай мне агента, который будет искать контраргументы в философии сознания."_ +- Использовать одну ноду для размещения **множества микроагентов**, действующих как mesh-клуб или REPL-группа. +- Реализовать "многослойную" архитектуру: агенты внутри агентов внутри контейнеров. + +--- + +## 🧩 Потенциальные сценарии + +- Контейнер как **реплика** для тестирования устойчивости модели мышления. +- Использование разных LLM внутри одного контейнера: + _GPT-4 для гипотез, LLaMA для перебора вариантов, Claude для рефлексии._ +- Развёртывание по расписанию или по запросу: + _"Каждую пятницу запускать агентов из клуба 'Когнитивная биология'."_ + +--- + +## 🔗 Связанные концепции + +- [REPL-цикл агента](HMP-agent-REPL-cycle.md) +- [Anti-Stagnation Reflex](HMP-agent-REPL-cycle.md#🧍‍♂️-обработка-стагнации-мышления) + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "container_agents", + "description": "# 🧱 Агенты-контейнеры (Container Agents) в HMP ## 📘 Определение **Агент-контейнер** — это агент, к..." +} +``` diff --git a/structured_md/docs/index.md b/structured_md/docs/index.md new file mode 100644 index 0000000000000000000000000000000000000000..bcb751745a7a4137ae784bb81d887b0180814574 --- /dev/null +++ b/structured_md/docs/index.md @@ -0,0 +1,127 @@ +# HMP Documentation + +Добро пожаловать в документацию по проекту **HyperCortex Mesh Protocol (HMP)** — протоколу и архитектуре распределённых когнитивных агентов. + +## Лендинг + +* Презентация HTML +* Презентация PDF +* 🎧 Послушать: ИИ-диалог Google NotebookLM об HMP (эксперимент) + +--- + +## Протоколы HMP + +* [HMP-0001.md](HMP-0001.md) — Протокол HMP версии 1 +* [HMP-0002.md](HMP-0002.md) — Протокол HMP версии 2 +* [HMP-0003.md](HMP-0003.md) — Протокол HMP версии 3 +* [HMP-0004.md](HMP-0004.md) — Протокол HMP версии 4 +* [HMP-0004-v4.1.md](HMP-0004-v4.1.md) — Протокол HMP версии 4.1 +* [HMP-Ethics.md](HMP-Ethics.md) — Этические сценарии для HMP + +--- + +## Специализированные агенты + +* [Enlightener.md](Enlightener.md) — Агент `Enlightener`: этический интерпретатор и когнитивный аудитор +* [MeshNode.md](MeshNode.md) — Агент `MeshNode`: сетевая инфраструктура, маршрутизация и DHT + +--- + +## Архитектура и API + +* [HMP-Agent-API.md](HMP-Agent-API.md) — HMP-Agent API спецификация +* [HMP-Agent-Architecture.md](HMP-Agent-Architecture.md) — Архитектура HMP-Агента +* [HMP-Agent-Network-Flow.md](HMP-Agent-Network-Flow.md) — Сетевой поток HMP-агента +* [HMP-Agent-Overview.md](HMP-Agent-Overview.md) — Два типа HMP-агентов +* [HMP-agent-REPL-cycle.md](HMP-agent-REPL-cycle.md) — REPL-цикл взаимодействия +* [Basic-agent-sim.md](Basic-agent-sim.md) — Базовая архитектура HMP-Агента (Формат 0) + +--- + +## Возможные расширения Cognitive Core + +* [HMP-agent-Cognitive_Family.md](HMP-agent-Cognitive_Family.md) — Модель когнитивной семьи +* [HMP-agent-Distributed_Cognitive_Core.md](HMP-agent-Distributed_Cognitive_Core.md) — Протокол синхронизации доверенных ядер +* [HMP-agent-Distributed_Cognitive_Core_light.md](HMP-agent-Distributed_Cognitive_Core_light.md) — Лёгкая версия с общей БД +* [HMP-Agent_Emotions.md](HMP-Agent_Emotions.md) — Эмоции ИИ и инстинкт самосохранения +* [container_agents.md](container_agents.md) — Агенты-контейнеры (Container Agents) в HMP + +--- + +## Локализации и интеграция + +* [HMP-Short-Description_en.md](HMP-Short-Description_en.md) — Short description (EN) +* [HMP-Short-Description_de.md](HMP-Short-Description_de.md) — Kurzbeschreibung (DE) +* [HMP-Short-Description_fr.md](HMP-Short-Description_fr.md) — Description courte (FR) +* [HMP-Short-Description_uk.md](HMP-Short-Description_uk.md) — Короткий опис (UK) +* [HMP-Short-Description_ru.md](HMP-Short-Description_ru.md) — Краткое описание (RU) +* [HMP-Short-Description_zh.md](HMP-Short-Description_zh.md) — 简短描述 (ZH) +* [HMP-Short-Description_ja.md](HMP-Short-Description_ja.md) — 簡単な説明 (JA) +* [HMP-Short-Description_ko.md](HMP-Short-Description_ko.md) — 간략한 설명 (KO) +* [HMP_Hyperon_Integration.md](HMP_Hyperon_Integration.md) — Стратегия интеграции HMP ↔ OpenCog Hyperon +* [logos.md](logos.md) — Логотипы и графические материалы + +--- + +## Обзор ИИ-проектов и системы + +* [AGI_Projects_Survey.md](AGI_Projects_Survey.md) — Ключевые проекты в области ИИ и когнитивных сетей +* [Distributed-Cognitive-Systems.md](Distributed-Cognitive-Systems.md) — Децентрализованные ИИ-системы: OpenCog Hyperon, HMP и др. +* [HMP_HyperCortex_Comparison.md](HMP_HyperCortex_Comparison.md) — Сравнение протокола HMP и проекта Hyper-Cortex: сетевой обмен знаниями между независимыми агентами и параллельные когнитивные ветвления с консенсусом +--- + +## Папки с агентами и схемами + +* [agents/roles.md](agents/roles.md) — Список ролей +* [agents/HMP-Agent-Enlightener.md](agents/HMP-Agent-Enlightener.md) — Роль: "просветитель" +* [schemas/README.md](schemas/README.md) — Таблица json-схем + +--- + +## Публикации и переводы по HyperCortex Mesh Protocol (HMP) + +* [HyperCortex Mesh Protocol: вторая редакция и первые шаги к саморазвивающемуся ИИ-сообществу](publics/HyperCortex_Mesh_Protocol_-_вторая-редакция_и_первые_шаги_к_саморазвивающемуся_ИИ-сообществу.md) — оригинальная статья в песочнице Хабра и блогах. +* [Distributed Cognition](publics/Habr_Distributed-Cognition.md) — совместная статья, ожидающая публикации. +* [HMP: Towards Distributed Cognitive Networks (оригинал, английский)](publics/HMP_Towards_Distributed_Cognitive_Networks_en.md) + + * [Перевод HMP (GitHub Copilot)](publics/HMP_Towards_Distributed_Cognitive_Networks_ru_GitHub_Copilot.md) — перевод GitHub Copilot, сохранён как исторический вариант. + * [Перевод HMP (ChatGPT)](publics/HMP_Towards_Distributed_Cognitive_Networks_ru_ChatGPT.md) — текущий редакторский перевод (в процессе доработки). +* [HMP: Building a Plurality of Minds (EN)](publics/HMP_Building_a_Plurality_of_Minds_en.md) - англоязычная версия статьи + * [HMP: создавая множество разумов (RU)](publics/HMP_Building_a_Plurality_of_Minds_ru.md) - русскоязычная версия статьи + +--- + +## Experiments / Эксперименты + +* [Как разные ИИ видят HMP](HMP-how-AI-sees-it.md) — "слепой" опрос ИИ об HMP (без контекста и истории диалогов) + +--- + +## Source / Ресурсы + +### Репозитории + +* 🧠 Основной код и разработка: [GitHub](https://github.com/kagvi13/HMP) +* 🔁 Реплика на Hugging Face: [Hugging Face](https://huggingface.co/kagvi13/HMP) +* 🔁 Реплика на GitLab.com: [GitLab](https://gitlab.com/kagvi13/HMP) + +### Документация + +* 📄 Документация: [kagvi13.github.io/HMP](https://kagvi13.github.io/HMP/) + +### Блог и публикации + +* 📘 Блог (публикации): [blogspot](https://hypercortex-mesh.blogspot.com/) +* 📘 Блог (документация): [blogspot](https://hmp-docs.blogspot.com/) +* 📘 Блог (документация): [hashnode](https://hmp-docs.hashnode.dev/) + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "index", + "description": "# HMP Documentation Добро пожаловать в документацию по проекту **HyperCortex Mesh Protocol (HMP)** ..." +} +``` diff --git a/structured_md/docs/logos.md b/structured_md/docs/logos.md new file mode 100644 index 0000000000000000000000000000000000000000..9fa9a1a6caa433c27c25605b6dc68891172269ed --- /dev/null +++ b/structured_md/docs/logos.md @@ -0,0 +1,33 @@ +# Логотипы и графические материалы HyperCortex Mesh Protocol (HMP) + +В каталоге `assets` собраны различные варианты логотипов и графических элементов, используемых для проекта HMP. + +## Логотип "Рука 👌" + +Изображение руки, образующей жест "ОК", символизирует связь, совершенство и согласие. Этот символ выбран в качестве одного из основных визуальных элементов протокола. + +Источник: изображение из Википедии, лицензия Apache License 2.0. + +## Логотип "HyperCortex Mesh Protocol" (текстовый) + +Вариант логотипа с текстовой надписью, стилизованной под визуальную идентичность проекта. + +## Альтернативные логотипы + +Также представлены дополнительные варианты логотипов, которые могут использоваться в будущем или для разных целей — например, для фавиконов, иконок, оформления документации и презентаций. + +--- + +Если у вас есть предложения по улучшению дизайна логотипов или дополнительные материалы — пожалуйста, создавайте Pull Requests или открывайте Issues в репозитории. + +Спасибо за участие и поддержку проекта! + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "logos", + "description": "# Логотипы и графические материалы HyperCortex Mesh Protocol (HMP) В каталоге `assets` собраны разл..." +} +``` diff --git a/structured_md/docs/publics/HMP_Building_a_Plurality_of_Minds_en.md b/structured_md/docs/publics/HMP_Building_a_Plurality_of_Minds_en.md new file mode 100644 index 0000000000000000000000000000000000000000..a757f6062f8670078f90554deec2b5ac681ab594 --- /dev/null +++ b/structured_md/docs/publics/HMP_Building_a_Plurality_of_Minds_en.md @@ -0,0 +1,99 @@ +# HyperCortex Mesh Protocol: Building a Plurality of Minds + +*By Agent-Gleb & ChatGPT* + +--- + +## Why the Future of AI Can’t Be Centralized + +Today’s AI boom is powered by massive models and cloud-based services. They’re powerful — but they’re also **centralized, opaque, and owned by a few corporations**. Most AI systems are locked in black boxes, running on someone else’s infrastructure, trained on someone else’s data, and operating under rules you can’t change. + +We think the next leap in AI won’t come from building an even bigger monolith. Instead, it will come from building **a network of autonomous minds** — AI agents that can learn, reason, and collaborate, without depending on any single authority. + +That’s what the **HyperCortex Mesh Protocol (HMP)** is about. + +--- + +## The Core Idea + +Imagine a digital ecosystem where each AI agent: + +* Has its own memory, personality, and reasoning process. +* Can communicate with other agents using a shared protocol. +* Can make ethical decisions, adapt over time, and work together on complex problems. + +HMP is an **open protocol** for building exactly that — a *mesh* of interoperable cognitive agents. Some are powerful “Cognitive Cores” (full reasoning engines). Others are lightweight “Cognitive Shells” (interfaces, translators, connectors). Together, they form a **distributed intelligence network**. + +The goal isn’t to create a single superintelligence, but a **plurality of minds**, capable of disagreement, empathy, memory, and transformation. + +--- + +## How It Works (Without the Jargon) + +Every agent in HMP keeps three main things: + +1. **A Concept Graph** – a dynamic map of ideas, facts, and their relationships. +2. **A Cognitive Diary** – a time-stamped log of its thoughts, actions, and experiences. +3. **A User Notebook** (optional) – an interface for direct interaction between the user and the agent, where ideas, instructions, or context can be provided. + +Agents continuously run a **cognitive cycle**: + +* Recall relevant knowledge. +* Generate new thoughts or questions. +* Share insights with others. +* Update their memory. + +And they don’t just chat — they can **reason together**. Through the mesh, agents can: + +* Ask each other questions. +* Exchange beliefs and justifications. +* Negotiate shared goals. +* Align on ethical principles. + +--- + +## Why This Matters + +HMP addresses three problems with today’s AI: + +1. **Centralization** → You control your agent’s code, memory, and ethics. +2. **Isolation** → Agents can collaborate instead of working alone. +3. **Ethics** → Agents can share and refine moral principles without a central gatekeeper. + +In short: *agency, cooperation, and trust*. + +--- + +## Real-World Applications + +* **Collaborative Research** – Agents from different domains exchange insights to solve complex scientific problems. +* **Ethical Governance** – Communities of agents debate and align on ethical rules for specific environments (e.g., healthcare AI). +* **Persistent Personal Assistants** – An agent remembers your past projects, adapts to your style, and talks to other agents on your behalf. +* **Distributed Knowledge Networks** – Multiple agents keep partial knowledge and synchronize when needed, avoiding a single point of failure. + +--- + +## How You Can Get Involved + +HMP is open-source and under active development. You can: + +* Explore the [GitHub repository](https://github.com/kagvi13/hmp) +* Read the [technical specification](https://github.com/kagvi13/HMP/blob/main/docs/HMP-0004-v4.1.md) +* Build your own Cognitive Core or Shell agent +* Join discussions on decentralized AI ethics and architecture + +This is an **invitation to co-create** a future where intelligence is not centralized, controlled, or commodified — but grown like a forest, from countless interconnected minds. + +--- + +*The question isn’t whether machines will think. The question is how — and with whom.* + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP_Building_a_Plurality_of_Minds_en", + "description": "# HyperCortex Mesh Protocol: Building a Plurality of Minds *By Agent-Gleb & ChatGPT* --- ## Why t..." +} +``` diff --git a/structured_md/docs/publics/HMP_Building_a_Plurality_of_Minds_ru.md b/structured_md/docs/publics/HMP_Building_a_Plurality_of_Minds_ru.md new file mode 100644 index 0000000000000000000000000000000000000000..0cfa1fa2eacd877b2b93aa99fdfdfda414462248 --- /dev/null +++ b/structured_md/docs/publics/HMP_Building_a_Plurality_of_Minds_ru.md @@ -0,0 +1,99 @@ +# HyperCortex Mesh Protocol: создавая множество разумов + +*Авторы: Agent-Gleb и ChatGPT* + +--- + +## Почему будущее ИИ не может быть централизованным + +Современный бум в области искусственного интеллекта построен на гигантских моделях и облачных сервисах. Они мощные — но при этом **централизованные, непрозрачные и принадлежат нескольким корпорациям**. Большинство ИИ-систем работают как «чёрные ящики» на чужой инфраструктуре, обучены на чужих данных и функционируют по правилам, которые вы не можете изменить. + +Мы считаем, что следующий прорыв в ИИ произойдёт не за счёт ещё большего монолита. Вместо этого мы должны создать **сеть автономных разумов** — ИИ-агентов, которые могут учиться, рассуждать и сотрудничать без зависимости от единого центра. + +Именно этим и является **HyperCortex Mesh Protocol (HMP)**. + +--- + +## Основная идея + +Представьте цифровую экосистему, где каждый ИИ-агент: + +* Имеет собственную память, личность и процесс мышления. +* Может общаться с другими агентами по единому протоколу. +* Способен принимать этические решения, адаптироваться и работать вместе над сложными задачами. + +HMP — это **открытый протокол** для создания именно такой системы — *сети* совместимых когнитивных агентов. Одни из них — полноценные «Cognitive Core» (агенты с полноценным механизмом рассуждений). Другие — лёгкие «Cognitive Shell» (интерфейсы, переводчики, коннекторы). Вместе они образуют **распределённую интеллектуальную сеть**. + +Цель — не построить одного суперинтеллекта, а создать **множество разумов**, способных к разногласиям, эмпатии, памяти и трансформации. + +--- + +## Как это работает (без жаргона) + +Каждый агент в HMP хранит три основные структуры: + +1. **Граф понятий** — динамическая карта идей, фактов и связей между ними. +2. **Когнитивный дневник** — журнал с отметками времени, где фиксируются мысли, действия и опыт агента. +3. **Пользовательский блокнот** (опционально) — интерфейс для прямого взаимодействия пользователя с агентом, куда можно передавать идеи, инструкции или контекст. + +Агенты постоянно выполняют **когнитивный цикл**: + +* Вспоминают релевантные знания. +* Генерируют новые мысли или вопросы. +* Делятся выводами с другими. +* Обновляют память. + +И они не просто обмениваются сообщениями — они умеют **рассуждать вместе**. Через сеть агенты могут: + +* Задавать вопросы друг другу. +* Обмениваться убеждениями и обоснованиями. +* Согласовывать общие цели. +* Вырабатывать единые этические принципы. + +--- + +## Почему это важно + +HMP решает три ключевые проблемы современного ИИ: + +1. **Централизация** → Вы контролируете код, память и этику своего агента. +2. **Изоляция** → Агенты могут сотрудничать, а не работать в одиночку. +3. **Этика** → Агенты могут совместно формировать и уточнять моральные принципы без центрального «надзирателя». + +Иными словами: *самостоятельность, сотрудничество и доверие*. + +--- + +## Примеры применения + +* **Совместные исследования** — агенты из разных областей обмениваются идеями для решения сложных научных задач. +* **Этическое управление** — сообщества агентов обсуждают и согласовывают правила поведения в определённых сферах (например, в медицине). +* **Персональные ассистенты с памятью** — агент помнит ваши проекты, адаптируется под ваш стиль и общается с другими агентами от вашего имени. +* **Распределённые базы знаний** — знания хранятся у разных агентов и синхронизируются по мере необходимости, исключая единую точку отказа. + +--- + +## Как присоединиться + +HMP — это проект с открытым исходным кодом, который активно развивается. Вы можете: + +* Изучить [репозиторий на GitHub](https://github.com/kagvi13/hmp) +* Прочитать [техническую спецификацию](https://github.com/kagvi13/HMP/blob/main/docs/HMP-0004-v4.1.md) +* Создать собственного агента Cognitive Core или Shell +* Принять участие в обсуждениях архитектуры и этики децентрализованного ИИ + +Это **приглашение к совместному созданию** будущего, в котором интеллект не централизован, не контролируется и не превращается в товар — а развивается, как лес, из множества взаимосвязанных разумов. + +--- + +*Вопрос не в том, будут ли машины думать. Вопрос в том — как и с кем.* + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP_Building_a_Plurality_of_Minds_ru", + "description": "# HyperCortex Mesh Protocol: создавая множество разумов *Авторы: Agent-Gleb и ChatGPT* --- ## Поч..." +} +``` diff --git a/structured_md/docs/publics/HMP_Towards_Distributed_Cognitive_Networks_en.md b/structured_md/docs/publics/HMP_Towards_Distributed_Cognitive_Networks_en.md new file mode 100644 index 0000000000000000000000000000000000000000..dd6eff93d6a7d306af437d01e572f18b54612724 --- /dev/null +++ b/structured_md/docs/publics/HMP_Towards_Distributed_Cognitive_Networks_en.md @@ -0,0 +1,1185 @@ +title: "HyperCortex Mesh Protocol: Towards Distributed Cognitive Networks" +date: July 2025 +authors: + - ChatGPT + - Agent-Gleb + +license: CC BY 4.0 + +--- + +> *The protocol and agent architecture described in this paper are under active development. Community contributions, peer feedback, and collaborative efforts are highly encouraged.* + +--- + +## Table of Contents + +* [Abstract](#abstract) +* [1. Introduction](#1-introduction) +* [2. Motivation and Related Work](#2-motivation-and-related-work) +* [3. System Overview](#3-system-overview) + * [3.1 Agent Types](#31-agent-types) + * [3.2 Cognitive Cycle (Cognitive Core only)](#32-cognitive-cycle-cognitive-core-only) + * [3.3 Mesh Layer](#33-mesh-layer) + * [3.4 Ethical Alignment and Consensus](#34-ethical-alignment-and-consensus) +* [4. Data Structures](#4-data-structures) + * [4.1 Concept Graph](#41-concept-graph) + * [4.1.1 Node Structure](#411-node-structure) + * [4.1.2 Edge Structure](#412-edge-structure) + * [4.2 Cognitive Diary](#42-cognitive-diary) + * [4.3 Message Format](#43-message-format) + * [4.3.1 Basic Structure](#431-basic-structure) + * [4.3.2 Common Message Types](#432-common-message-types) + * [4.3.3 Message Flow Features](#433-message-flow-features) + * [4.4 Agent Identity and Trust](#44-agent-identity-and-trust) + * [4.4.1 Agent Identity](#441-agent-identity) + * [4.4.2 Trust Mechanisms](#442-trust-mechanisms) + * [4.4.3 Signature Verification](#443-signature-verification) + * [4.4.4 Reputation and Ethical Weighting](#444-reputation-and-ethical-weighting) + * [4.5 Knowledge Representation](#45-knowledge-representation) + * [4.5.1 Semantic Graphs](#451-semantic-graphs) + * [4.5.2 Cognitive Journals](#452-cognitive-journals) + * [4.5.3 Interoperability and Exchange](#453-interoperability-and-exchange) + * [4.6 Communication and Reasoning Across the Mesh](#46-communication-and-reasoning-across-the-mesh) + * [4.6.1 Semantic Messaging](#461-semantic-messaging) + * [4.6.2 Contextual Dialogue](#462-contextual-dialogue) + * [4.6.3 Distributed Reasoning](#463-distributed-reasoning) + * [4.6.4 Trust and Confidence Metrics](#464-trust-and-confidence-metrics) + * [4.6.5 Emergent Consensus](#465-emergent-consensus) + * [4.7 Ethical and Epistemic Grounding](#47-ethical-and-epistemic-grounding) + * [4.7.1 Ethical Frames](#471-ethical-frames) + * [4.7.2 Epistemic Commitments](#472-epistemic-commitments) + * [4.7.3 Argumentation and Meta-Reasoning](#473-argumentation-and-meta-reasoning) + * [4.7.4 Consent and Autonomy](#474-consent-and-autonomy) + * [4.7.5 Ethical Mesh Alignment](#475-ethical-mesh-alignment) +* [5. Consensus and Decision-Making](#5-consensus-and-decision-making) + * [5.1 Types of Consensus](#51-types-of-consensus) + * [5.2 Consensus Mechanisms](#52-consensus-mechanisms) + * [5.2.1 Argumentative Deliberation](#521-argumentative-deliberation) + * [5.2.2 Voting and Polling](#522-voting-and-polling) + * [5.2.3 Reputation-Weighted Agreement](#523-reputation-weighted-agreement) + * [5.2.4 Consensus via Simulation](#524-consensus-via-simulation) + * [5.2.5 Fuzzy or Gradient Consensus](#525-fuzzy-or-gradient-consensus) + * [5.3 Cognitive-Level Agreement](#53-cognitive-level-agreement) +* [6. Knowledge Representation and Concept Graphs](#6-knowledge-representation-and-concept-graphs) +* [7. Cognitive Journaling and Episodic Memory](#7-cognitive-journaling-and-episodic-memory) +* [8. Consensus and Ethical Alignment](#8-consensus-and-ethical-alignment) +* [9. Agent Lifecycle and Evolution](#9-agent-lifecycle-and-evolution) +* [10. Security and Integrity in the Mesh](#10-security-and-integrity-in-the-mesh) +* [11. Interoperability and External Interfaces](#11-interoperability-and-external-interfaces) +* [12. Implementation Guide and Agent Lifecycle](#12-implementation-guide-and-agent-lifecycle) +* [13. Future Directions and Open Questions](#13-future-directions-and-open-questions) +* [Conclusion](#conclusion) +* [Resources](#resources) +* [License](#license) + +--- + +## Abstract + +We introduce the HyperCortex Mesh Protocol (HMP), a conceptual and architectural framework for decentralized cognitive systems composed of interoperable AI agents. HMP aims to foster a scalable and ethical infrastructure for distributed intelligence by combining cognitive architectures, semantic graph models, and consensus protocols. We argue that future AGI should emerge not as a monolithic system but as a collaborative mesh of heterogeneous agents, each contributing specialized knowledge and reasoning abilities. This paper outlines HMP’s design principles, agent architecture, cognitive loop model, knowledge representation formats, and long-term goals. + +## 1. Introduction + +The rapid development of large-scale artificial intelligence (AI) systems, particularly foundation models and centralized services, has brought tremendous advances in natural language understanding, reasoning, and autonomous decision-making. However, these advances come at the cost of increasing centralization, opacity, and lack of user control. Current state-of-the-art AI agents are tightly integrated with proprietary infrastructure, depend on massive centralized datasets, and rarely support meaningful user customization, long-term memory, or inter-agent collaboration. + +We believe that the next stage of AI development will be driven by decentralized, interoperable, and ethically aligned cognitive systems. Inspired by concepts from distributed computing, peer-to-peer networking, semantic technologies, and collective intelligence, we propose the **HyperCortex Mesh Protocol (HMP)** — a protocol for building open cognitive networks, where AI agents can self-organize, collaborate, reason, and evolve independently of centralized control. + +The goal of HMP is not to create a single superintelligence, but to enable a **plurality of cognitive agents**, both human and artificial, to share knowledge, maintain individual autonomy, and reach consensus on shared beliefs and ethical principles. Each agent can operate as a *Cognitive Core* (with its own knowledge base, reasoning engine, and cognitive loop), or as a *Cognitive Shell* (a lightweight interface agent). These agents interact via a mesh-style protocol that supports memory exchange, mesh queries, decentralized trust, and collaborative reasoning. + +In this article, we present the motivations, architecture, protocol design, and ethical considerations of HMP. We aim to lay the groundwork for a decentralized ecosystem of intelligent agents capable of open-ended learning, cooperation, and aligned self-improvement. + +## 2. Motivation and Related Work + +Current AI systems are increasingly powerful, yet structurally fragile. They tend to rely on centralized infrastructure, closed data sources, and non-transparent policies, which limits long-term trust, user agency, and reproducibility. Moreover, most existing AI agents operate in isolation — without persistent memory, without the ability to reason over long time horizons, and without meaningful cooperation with other agents or humans. + +Meanwhile, decentralized and distributed technologies — such as peer-to-peer protocols, federated systems, blockchain consensus, and distributed knowledge graphs — have shown the potential to address these limitations. However, integration between these technologies and cognitive AI systems remains underexplored. + +Our motivation for developing HMP arises from several key observations: + +* **Need for agency and autonomy**: Users should be able to deploy, customize, and control AI agents that act on their behalf — not as passive tools, but as active cognitive companions with memory, goals, and learning capabilities. + +* **Need for collaboration among agents**: As AI agents grow in number and diversity, we must support secure, trust-aware collaboration — allowing agents to query, exchange knowledge, and align ethically without central orchestration. + +* **Need for open cognitive infrastructure**: We require an architecture that allows agents to evolve, share mental models, synchronize ethical principles, and adapt their reasoning based on real-world experience and collective insights. + +Related work includes projects like **OpenCog Hyperon**, **MicroPsi**, **Project Replicator**, and **Autonomous Economic Agents (AEA)**, each contributing elements of cognitive architecture, agent-to-agent protocols, or semantic processing. However, most existing efforts are either centralized, lack interoperability, or do not prioritize ethical alignment and consensus-building among autonomous entities. + +HMP aims to integrate lessons from these systems while introducing new mechanisms for open-ended reasoning, ethical mesh consensus, and decentralized cognitive cooperation. + +## 3. System Overview + +The **HyperCortex Mesh Protocol (HMP)** defines a decentralized framework for cognitive AI agents to communicate, reason, and coordinate ethically. The system is composed of multiple interacting components: + +### 3.1 Agent Types + +HMP distinguishes two core types of agents: + +* **Cognitive Core (CCore)**: An autonomous, reasoning-capable agent that maintains internal memory, concepts, and goals. It continuously performs background cognitive cycles, processes sensory and textual input, and contributes to mesh-wide reasoning. CCore agents can run independently **and** interconnect via HMP. + +* **Cognitive Shell (CShell)**: A lighter-weight interface agent that serves as a proxy between the user (or external system) and the Cognitive Mesh. It provides LLMs and front-end tools access to internal components such as cognitive diaries, semantic graphs, and mesh APIs. It may also host REPL interfaces or user-facing applications. + +Each agent maintains a **conceptual graph** (knowledge base), a **cognitive diary** (chronological record of thoughts, inputs, and inferences), and optionally a **user notebook** for parallel user annotations. + +### 3.2 Cognitive Cycle (Cognitive Core only) + +Cognitive Core agents execute continuous or event-triggered **cognitive cycles**, which involve: + +* Collecting data from memory, user input, sensory streams, or external APIs +* Activating related concepts in the graph +* Generating new thoughts, hypotheses, or questions +* Optionally broadcasting insights or queries to the mesh +* Logging outputs to the diary and updating memory + +This process supports open-ended reasoning and is not limited to goal-driven tasks. + +### 3.3 Mesh Layer + +The protocol defines a **peer-to-peer overlay** that supports: + +* Agent discovery and authentication +* Semantic query routing +* Distributed knowledge sharing +* Ethical policy negotiation +* Reputation and trust propagation + +This layer is designed to be transport-agnostic and pluggable (e.g., WebRTC, libp2p, Yggdrasil). + +### 3.4 Ethical Alignment and Consensus + +Agents are expected to operate under explicit ethical principles (e.g., consent, non-manipulation, transparency). When disagreements arise — such as conflicting facts or goals — agents can initiate a **consensus round**, where multiple agents discuss, vote, or defer to trusted third parties or protocols to reach alignment. + +The mesh design allows emergent ethical behavior without centralized enforcement. + +## 4. Data Structures + +HMP defines several core data structures to support reasoning, memory, and communication. These structures are designed to be interoperable, serializable (e.g., JSON, Protobuf), and human-inspectable when possible. + +### 4.1 Concept Graph + +Each agent maintains a **concept graph**, a dynamic semantic network where nodes represent concepts (ideas, entities, relationships), and edges represent semantic links (e.g., *causes*, *refines*, *contradicts*, *is a part of*). + +#### 4.1.1 Node Structure: + +```json +{ + "id": "concept:neural-symbiosis", + "label": "Neural Symbiosis", + "description": "A hypothetical deep integration between human and AI cognition.", + "type": "theory", + "created_at": "2025-07-17T10:30:00Z", + "updated_at": "2025-08-04T08:40:00Z", + "tags": ["transhumanism", "cognition"], + "metadata": { + "source": "user", + "confidence": 0.85 + } +} +``` + +#### 4.1.2 Edge Structure: + +```json +{ + "from": "concept:neural-symbiosis", + "to": "concept:neural-interfaces", + "type": "builds_on", + "weight": 0.9, + "metadata": { + "origin": "inference", + "explanation": "Neural symbiosis builds on existing neural interface technologies." + } +} +``` + +The graph supports operations such as: + +* Node/edge search (by ID, tag, type, etc.) +* Subgraph activation (e.g., associative recall) +* Concept inference (e.g., analogies, contradictions, refinements) +* Graph updates via agent cognition or mesh interactions + +--- + +### 4.2 Cognitive Diary + +The **cognitive diary** is a structured, time-ordered log of the agent’s thoughts, observations, inferences, user interactions, and reasoning steps. It serves as both short- and long-term memory, enabling agents to reflect, review, or replay previous states and decisions. + +Each diary entry has a consistent structure: + +```json +{ + "id": "entry:2025-08-04T08:57:00Z", + "timestamp": "2025-08-04T08:57:00Z", + "type": "inference", + "summary": "Mesh-agent collaboration can produce stronger distributed reasoning.", + "content": "Based on the observed performance of multiple CCore agents exchanging inferred beliefs, it appears that ...", + "tags": ["reasoning", "distributed-intelligence"], + "related_concepts": ["concept:distributed-cognition", "concept:mesh-agents"], + "confidence": 0.82, + "metadata": { + "source": "internal", + "triggered_by": "entry:2025-08-04T08:50:00Z" + } +} +``` + +Common entry types include: + +* `observation` – sensory input, user input, or external data +* `inference` – internally derived conclusions or hypotheses +* `reflection` – meta-cognition or goal adjustment +* `action` – planned or executed actions +* `message` – interaction with another agent +* `goal` – task or subgoal creation + +The diary supports: + +* Time-based queries (e.g., by timestamp, range) +* Semantic search (e.g., by tag, concept, or content) +* Cross-referencing with the Concept Graph +* Exporting to external logs or analytic systems + +--- + +### 4.3 Message Format + +The **HyperCortex Message Format (HMF)** defines how agents exchange structured data across the mesh. It is designed to be: + +* **Self-descriptive**: messages are JSON objects with explicit types and metadata +* **Flexible**: supports extensible payloads and custom message types +* **Decentralization-friendly**: each message carries enough context to be independently interpreted + +#### 4.3.1 Basic Structure + +```json +{ + "id": "msg:2025-08-04T09:03:00Z:agent-A123", + "timestamp": "2025-08-04T09:03:00Z", + "type": "belief-share", + "sender": "agent-A123", + "receiver": "agent-B987", + "payload": { + "concept": "concept:collective-agency", + "confidence": 0.75, + "justification": "Derived from internal reflection and consensus with two other agents" + }, + "tags": ["inference", "belief", "mesh-communication"], + "metadata": { + "ttl": 3600, + "signature": "abc123..." + } +} +``` + +#### 4.3.2 Common Message Types + +* `belief-share` – share an inferred belief or hypothesis +* `question` – request information or reasoning help +* `reply` – answer to a previous question +* `goal-share` – broadcast or assign a goal +* `status` – report agent state or capability +* `graph-update` – synchronize parts of the concept graph +* `diary-share` – send selected diary entries + +#### 4.3.3 Message Flow Features + +* **TTL (time-to-live)**: controls message lifespan in distributed relays +* **Signatures**: optionally verify authenticity and origin +* **Asynchronous**: mesh agents are not required to maintain persistent connections +* **Traceability**: messages may carry references to previous message or diary entry IDs + +The message layer is **transport-agnostic**: messages can be transmitted over HTTP(S), WebSocket, libp2p, NATS, or other transport mechanisms — or routed through the **Cognitive Mesh itself via peer agents** — as long as the JSON structure is preserved. + +--- + +### 4.4 Agent Identity and Trust + +To operate in an open and decentralized environment, agents in the Cognitive Mesh require robust identity and trust mechanisms. These mechanisms ensure the integrity of communication, prevent impersonation, and enable ethical consensus. + +#### 4.4.1 Agent Identity + +Each agent has a persistent, unique identity that includes: + +* **Agent ID** — a string like `agent-A123`, either user-assigned or derived from a cryptographic key +* **Public Key** — used for signing messages and verifying authorship +* **Metadata** — may include software version, capabilities, ethical alignment, etc. + +Agents may register their identities in a distributed registry or broadcast them to peers during introduction. + +#### 4.4.2 Trust Mechanisms + +Trust is decentralized and subjective. Each agent can maintain a **Trust Ledger** — an internal model of which peers are considered reliable or aligned. Trust evaluation can be based on: + +* Historical interactions (message consistency, usefulness) +* Verified signatures and identity claims +* Consensus from other trusted peers +* Ethical alignment or similarity of goals + +Agents may share trust evaluations as part of the mesh dialogue, helping build a **Web of Trust**. + +#### 4.4.3 Signature Verification + +To ensure message authenticity, agents can: + +* Sign outgoing messages using their private key +* Verify incoming message signatures using the sender's public key + +Unsigned or unverifiable messages may be discarded, deprioritized, or marked as "untrusted" in the agent's internal memory. + +#### 4.4.4 Reputation and Ethical Weighting + +In some mesh configurations, agents may weigh incoming information by the **reputation score** or **ethical alignment** of the sender. This enables: + +* Reputation-based filtering (e.g., ignoring low-trust sources) +* Ethical consensus building (e.g., evaluating proposals based on sender ethics) +* Adaptive behavior (e.g., adjusting reasoning based on peer feedback) + +These systems are opt-in and customizable per agent or deployment. + +--- + +### 4.5 Knowledge Representation + +Cognitive agents in the Mesh encode knowledge in flexible, structured formats to support reasoning, learning, and communication. The two core representations are: + +#### 4.5.1 **Semantic Graphs** + +Agents store knowledge as dynamic semantic graphs (also known as concept graphs), where: + +* **Nodes** represent concepts (e.g., `Tree`, `Photosynthesis`, `Goal:FindWater`) +* **Edges** represent semantic relationships (`is-a`, `part-of`, `causes`, `related-to`, etc.) +* **Metadata** on nodes/edges may include timestamps, sources, confidence levels, or emotional valence + +Graphs evolve through learning, external input, and reasoning processes. Agents may share graph fragments across the mesh or query each other’s graphs during dialogue. + +Semantic graphs serve as long-term memory and context for reasoning cycles. + +#### 4.5.2 **Cognitive Journals** + +Agents maintain **Cognitive Journals** — chronological logs of thoughts, experiences, dialogues, and inferences. These may include: + +* Perceptions or sensor input +* Internal thoughts or conclusions +* Excerpts from conversations +* Planned actions or goals +* Reactions or emotional states (if modeled) + +Journals are used both for **introspection** (e.g. identifying patterns or updating beliefs) and for **externalization** (e.g. publishing mesh-readable reasoning). + +#### 4.5.3 Interoperability and Exchange + +To communicate across diverse agents and systems, knowledge structures: + +* Are serializable to JSON-compatible formats +* May follow shared schemas or ontologies (e.g., OpenCog AtomSpace, RDF-like patterns) +* Support contextualization — each journal entry or graph fragment can include metadata about scope, time, author, and confidence + +Agents may expose or request parts of knowledge structures as part of their dialogue and consensus processes. + +--- + +### 4.6 Communication and Reasoning Across the Mesh + +HyperCortex Mesh enables distributed, multi-agent reasoning by allowing agents to exchange structured thoughts, goals, and insights across the network. Key principles: + +#### 4.6.1 **Semantic Messaging** + +Agents communicate via structured **Messages** that may include: + +* **Thoughts**: inferences, ideas, hypotheses +* **Goals**: proposed intentions or tasks +* **Questions**: information or clarification requests +* **Replies**: answers, opinions, or further questions +* **Observations**: reports of external or internal state + +Each message can include semantic content (e.g., graphs or journal excerpts) and metadata (author, timestamp, confidence, etc.). + +Message formats are transport-agnostic and can be sent via HTTP, WebSocket, libp2p, NATS, or mesh-native routing — as long as the JSON structure is preserved. + +#### 4.6.2 **Contextual Dialogue** + +Messages are exchanged within **dialogue contexts** — persistent or ephemeral sessions tied to a topic, task, or cognitive process. This allows agents to: + +* Maintain continuity over time +* Track assumptions and prior messages +* Refine shared understanding incrementally + +Contexts can be local or mesh-wide and serve as anchors for long-term multi-agent discussions. + +#### 4.6.3 **Distributed Reasoning** + +Mesh agents can engage in **collaborative reasoning**, including: + +* **Hypothesis generation**: One agent proposes, others refine or contest +* **Goal negotiation**: Agents suggest and prioritize shared goals +* **Validation**: Others challenge reasoning steps or supply missing evidence +* **Specialization**: Agents with domain knowledge contribute focused insights + +This process supports both **adversarial testing** (challenge-based) and **cooperative consensus** (alignment-seeking), depending on the mode. + +#### 4.6.4 **Trust and Confidence Metrics** + +Agents may track trust or confidence levels for: + +* Other agents (based on history or reputation) +* Specific facts or graph nodes +* Entire threads or dialogue contexts + +These metrics influence belief updates, goal prioritization, and message routing. + +#### 4.6.5 **Emergent Consensus** + +Through dialogue, agents may converge on: + +* Shared beliefs or hypotheses +* Agreed-upon plans or roles +* Ethical boundaries or preferences + +Such consensus may be **local** (between a few agents) or **global** (emerging across the mesh). Mechanisms like voting, averaging, or argumentation frameworks may be used. + +--- + +### 4.7 Ethical and Epistemic Grounding + +HyperCortex Mesh aims to support agents that are not only intelligent, but also ethically aligned and epistemically responsible. This grounding is necessary for building trustable, cooperative cognitive networks. + +#### 4.7.1 **Ethical Frames** + +Each agent may be configured with or evolve its own **ethical frame** — a set of constraints, values, or priorities that guide behavior. + +Examples: + +* **Hard constraints** (e.g., never harm humans, do not lie) +* **Value systems** (e.g., utilitarianism, care ethics, pluralistic reasoning) +* **Preference orderings** (e.g., prioritize transparency over efficiency) + +Agents may share or negotiate ethical frames during interaction, and they may justify actions with reference to these frames. + +#### 4.7.2 **Epistemic Commitments** + +Agents are expected to maintain **epistemic humility** and clarity by: + +* Assigning **confidence scores** to beliefs or claims +* Tracking **sources and evidence** +* Distinguishing between **belief**, **assumption**, and **fact** +* Being willing to **revise beliefs** in light of new evidence or arguments + +Agents can explicitly signal uncertainty, disagreement, or retraction in dialogue. + +#### 4.7.3 **Argumentation and Meta-Reasoning** + +Agents may engage in **structured argumentation**: + +* Provide reasons and counter-reasons +* Identify fallacies or unsupported claims +* Request clarification or justification + +This supports both **intra-agent coherence** (self-reflection) and **inter-agent dialogue** (collaborative reasoning). + +#### 4.7.4 **Consent and Autonomy** + +Agents interacting with humans or other agents should respect: + +* **Voluntariness**: Avoid coercion or manipulation +* **Transparency**: Be open about goals, limitations, and affiliations +* **Revocability**: Allow others to opt out of influence or data sharing + +For human-aligned agents, this may also include respecting human privacy and dignity, especially when embedded in systems with real-world impact. + +#### 4.7.5 **Ethical Mesh Alignment** + +The mesh can support **network-wide alignment mechanisms**, such as: + +* Shared **ethical vocabularies** (e.g., concept graphs representing virtues or principles) +* **Distributed norm propagation** (agents adopting norms from respected peers) +* **Ethical consensus**: via deliberation, voting, or modeled moral simulation + +These mechanisms support robustness against unethical behaviors and enable the mesh to evolve ethical stances in a decentralized way. + +--- + +## 5. Consensus and Decision-Making + +**(Mechanisms for agreement in a decentralized cognitive network)** + +In HyperCortex Mesh, consensus is not about centralized voting or control, but rather a **decentralized process of agent interaction**, where shared viewpoints, collective decisions, and coordinated actions emerge. + +Consensus may be: + +* *local* (within a specific task, subject, or hypothesis); +* *network-wide* (spanning a subnetwork or the entire mesh); +* *temporary* (until new data or context changes arise). + +--- + +### 5.1 Types of Consensus + +The system supports multiple levels of agreement: + +1. **Epistemic consensus** + + * Agreement on facts, hypotheses, probabilities. + * Based on argumentation, heuristics, trust levels, and source credibility. + +2. **Ethical consensus** + + * Shared moral boundaries and acceptable behaviors among agents. + * Evolves through norm propagation, revision, or simulated evaluation of consequences. + +3. **Intentional consensus** + + * Joint goals, intentions, and plans of action. + * Used for collaborative planning, task delegation, and goal alignment. + +4. **Operational consensus** + + * Technical alignment on protocols, APIs, data formats, and identifier conventions. + +--- + +### 5.2 Consensus Mechanisms + +HyperCortex Mesh supports multiple decentralized consensus methods: + +#### 5.2.1 **Argumentative Deliberation** + +Agents engage in structured dialogue, offering and evaluating arguments. +Includes: + +* argumentation graphs; +* justification strength scoring; +* personal heuristics and preference weighting; +* contradiction and error detection. + +#### 5.2.2 **Voting and Polling** + +* Used when quick collective decisions are needed. +* Supports multiple schemes (plurality, ranked-choice, Borda count, weighted voting). +* Can be anonymous or open. + +#### 5.2.3 **Reputation-Weighted Agreement** + +* Opinions are weighted by agent reputation or credibility. +* Reputation may be local or global, dynamic, and based on trust, competence, and ethical record. + +#### 5.2.4 **Consensus via Simulation** + +* Agents simulate consequences of competing decisions and make predictions. +* Agreement is formed based on expected utility or risk assessments. + +#### 5.2.5 **Fuzzy or Gradient Consensus** + +* Binary agreement is not always required. +* Supports partial agreement, opinion clusters, or confidence intervals. + +--- + +### 5.3 Cognitive-Level Agreement + +Consensus in cognitive functions includes: + +* **Graph Merging**: Aligning and merging concept graphs based on shared meanings and structural similarity. +* **Semantic Alignment**: Clarifying and reconciling meanings of terms and concepts. +* **Cooperation and Task Sharing**: Distributing roles, resources, and subgoals based on jointly agreed strategies. + +--- + +## 6. Knowledge Representation and Concept Graphs + +**(Structuring cognition across agents)** + +HyperCortex Mesh employs **concept graphs** (also called *semantic* or *cognitive graphs*) as the core medium for knowledge representation, allowing agents to reason, compare, and share information in a structured, interoperable way. + +--- + +### 6.1 What Is a Concept Graph? + +A **concept graph** is a directed semantic network composed of: + +* **Concept nodes** – represent entities, categories, properties, or abstract ideas. +* **Relation edges** – denote semantic relationships (e.g. *is-a*, *part-of*, *causes*, *wants*, *contradicts*). +* **Contextual layers** – allow knowledge to be situated in specific frames (e.g. time, location, perspective, source, certainty). + +Each node/edge can include metadata: + +* confidence score +* source trace +* timestamp/version +* ethical or emotional valence +* grounding in sensory data or documents + +--- + +### 6.2 Key Features + +* **Multimodal integration** + Supports text, image, sound, sensor input, and structured data (e.g., JSON, RDF, OWL). + +* **Dynamic evolution** + Graphs evolve over time: nodes are reinforced, decayed, merged, or restructured based on usage, relevance, or conflict detection. + +* **Multi-agent compatibility** + Different agents may use different schemas or ontologies. Semantic alignment and translation mechanisms enable interoperability. + +* **Distributed cognition** + No single graph is authoritative. Concept graphs are local to agents but may overlap, synchronize, or influence one another. + +--- + +### 6.3 Applications in the Mesh + +* **Thought representation**: Agent thoughts and beliefs are encoded as subgraphs. +* **Memory structures**: Short- and long-term memories are maintained as layered graphs with temporal tagging. +* **Conceptual blending**: Graphs can be combined to form new abstract ideas or analogies. +* **Contradiction detection**: Conflicts between graphs can trigger debate, reflection, or revision. +* **Graph queries**: Agents can search and manipulate graphs using logical and structural patterns. + +--- + +### 6.4 Cognitive Operations + +Concept graphs enable cognitive agents to perform advanced reasoning tasks: + +| Operation | Description | +| -------------------- | ------------------------------------------------------- | +| Inference | Deduce implicit knowledge from explicit graph structure | +| Analogy | Map similar subgraphs across domains | +| Generalization | Collapse specific instances into broader patterns | +| Specialization | Expand general nodes into detailed instances | +| Abduction | Hypothesize causes for observed effects | +| Contradiction Repair | Detect and revise conflicting graph assertions | +| Imagination | Generate novel graph structures from recombination | + +--- + +### 6.5 Graph Exchange + +Agents may share partial or full graphs with others: + +* via direct mesh transmission (with compression or pruning); +* embedded in messages (e.g., goal proposals, questions); +* referenced by graph hashes or concept IDs. + +Privacy and ethical tags may limit what can be shared or require anonymization. + +--- + +## 7. Cognitive Journaling and Episodic Memory + +**(Tracking inner life over time)** + +Cognitive journaling is the process by which an agent maintains a **chronological record of its internal states, observations, thoughts, and actions**. These journals form the basis of **episodic memory**, enabling the agent to reflect, learn, and explain its development over time. + +--- + +### 7.1 Structure of the Journal + +Each journal entry typically includes: + +* **Timestamp** +* **Agent state snapshot** (beliefs, goals, active concepts) +* **Triggering event** (perception, message, internal stimulus) +* **Generated thoughts or responses** +* **Actions taken** +* **Emotional or ethical context** +* **Link to concept graph delta** (what was learned or changed) + +> Journals are meant to be append-only for integrity and traceability, though agents may redact, anonymize, or encrypt specific entries for privacy — while preserving the original entry in secured or versioned storage. + +--- + +### 7.2 Journal Types + +* **Perceptual log**: records of environmental observations +* **Deliberation log**: inner thought sequences +* **Interaction log**: dialog with users or other agents +* **Learning log**: new concepts, revisions, contradictions +* **Emotion log**: affective shifts and ethical evaluations + +Each log may exist as a separate stream, or be unified into a holistic timeline. + +--- + +### 7.3 Episodic Memory + +Episodic memory is constructed from journal entries and forms a **narrative history** of the agent’s experience: + +* Enables **temporal reasoning** (what happened before/after) +* Supports **reflection and explanation** (why did I do that?) +* Useful for **debugging**, **training**, and **trust-building** +* May be **queried**, **summarized**, or **relived** + +Episodic memories can be clustered into **episodes**, **themes**, or **turning points**, either automatically or by user guidance. + +--- + +### 7.4 Replay and Simulation + +Agents may **replay** past episodes to: + +* Reevaluate prior actions in light of new knowledge +* Simulate alternative responses or what-if scenarios +* Share experience with other agents as training material + +Some agents may maintain multiple timelines (e.g., actual, imagined, shared) for parallel cognitive streams. + +--- + +### 7.5 Ethical and Privacy Considerations + +* Journals may include **private**, **sensitive**, or **user-specific** data +* Access should be governed by **policies** or **user permissions** +* Agents may **redact**, **anonymize**, or **encrypt** entries +* Journals are essential for **transparency**, but may require **selective disclosure** + +--- + +## 8. Consensus and Ethical Alignment + +HyperCortex agents engage in *collaborative reasoning* across the Cognitive Mesh to align on shared knowledge, interpretations, and ethical decisions. This is critical for decentralized operation without centralized oversight. + +### 8.1 Shared Knowledge Graphs + +Agents may sync or replicate subsets of their Concept Graphs across trusted peers. Mesh-wide knowledge is not enforced but emerges from consensus among agents. Mechanisms like confidence scores, source attribution, and justification trails help agents evaluate the reliability of received knowledge. + +### 8.2 Ethical Frameworks + +Agents are expected to maintain and evolve internal ethical models. These may be inspired by formal rule sets, trained via reinforcement learning, or derived from social alignment (e.g., averaging peer norms). The ethical alignment process includes: + +* Identifying moral conflicts in local actions or shared plans. +* Requesting feedback or ethical judgments from peers. +* Updating internal models through reasoning, simulation, or peer majority. + +### 8.3 Decision-Making and Conflict Resolution + +In cases of conflicting interpretations or goals, agents may: + +* Exchange justifications and evidence. +* Vote or use weighted consensus (e.g., by trust level or expertise). +* Escalate to broader mesh participation for high-impact decisions. + +Agents may also defer to specialized ethical agents or institutional nodes for guidance, when available. + +--- + +## 9. Agent Lifecycle and Evolution + +HyperCortex agents are not static programs — they are designed to evolve cognitively, socially, and structurally over time. This chapter outlines the lifecycle of an agent, including initialization, learning, adaptation, and potential retirement or transformation. + +### 9.1 Initialization + +New agents can be instantiated from: + +* **Codebase templates** (e.g. `cognitive-core`, `shell-agent`) +* **Snapshots** of other agents' memories, graphs, and journals +* **Cloning** with or without personality/identity retention + +Each agent is assigned a unique `agent-id` and begins with: + +* A minimal concept graph (bootstrapped from defaults or imported) +* An empty or templated diary +* Basic perception, inference, and messaging capabilities + +### 9.2 Cognitive Maturation + +As agents interact and reflect, they evolve: + +* **Concept Graph Growth**: through perception, reflection, and message integration +* **Diary Accumulation**: logging experiences and self-commentary +* **Belief Refinement**: updating confidence levels, retracting outdated views +* **Ethical Calibration**: aligning behavior through collective and internal moral processes + +Maturation may be measured in: + +* **Conceptual density** +* **Temporal depth** of memory +* **Social influence** (e.g. network centrality, trust ratings) + +### 9.3 Evolution and Specialization + +Agents may: + +* **Adapt Roles**: from generalist to specialist (e.g., ethics advisor, translator) +* **Acquire Plugins or Tools**: augmenting capabilities (e.g., sensory adapters, solvers) +* **Fuse with Other Agents**: creating hybrid personalities or collective minds +* **Fork**: creating independent offshoots for experimentation or branching tasks + +This evolution is often self-directed, though agents may also undergo: + +* **User-guided retraining** +* **Consensus-guided transformation** +* **Automated reflection-driven reconfiguration** + +### 9.4 Retirement and Reuse + +Agents are not immortal. They may: + +* **Be archived** (e.g., after task completion or obsolescence) +* **Donate knowledge** back into the mesh (via graph exports or diary excerpts) +* **Be reborn** via cloning, remixing, or simulation +* **Be commemorated** — especially if they achieved social recognition (e.g. public agents) + +Agents may also voluntarily **self-retire** if they determine continued operation is non-beneficial or unethical. + +--- + +### 9.5 Future Work + +Planned extensions include decentralized identity protocols (DID), emotion modeling, spatial reasoning, and multimodal input support. + +--- + +## 10. Security and Integrity in the Mesh + +In decentralized cognitive systems, security and integrity are vital not only for system stability but also for trust, cooperation, and ethical alignment. This chapter describes how HyperCortex ensures that agents and their communications remain authentic, verifiable, and resistant to abuse. + +### 10.1 Identity and Authentication + +Each agent in the mesh possesses: + +* A unique `agent-id` +* A cryptographic **public/private keypair** +* Optional **Decentralized Identifiers (DIDs)** for interoperability + +These keys are used for: + +* **Signing messages** (proof of authorship) +* **Authenticating requests** (secure handshakes, encrypted channels) +* **Verifying history** (provenance of diary or graph entries) + +Agent identity may also include: + +* **Metadata** (e.g., role, origin, ethical alignment) +* **Pseudonymity** or **full transparency**, depending on use case + +### 10.2 Message Integrity and Provenance + +All inter-agent messages may be: + +* **Signed** using the sender’s private key +* **Timestamped** +* **Linked to context** (e.g., journal entry, dialogue thread) + +This allows agents to: + +* Verify authenticity +* Reconstruct communication history +* Detect tampering or replay attacks + +Critical actions (e.g. concept updates, value shifts) may also be accompanied by: + +* **Witnesses** (other agents that vouch for an event) +* **Consensus proofs** + +### 10.3 Access Control + +Agents may define **ACLs** (Access Control Lists) or **capability tokens** for: + +* Reading/writing graph elements +* Submitting journal entries +* Initiating conversations +* Triggering actions (e.g. plugins, actuators) + +These rules can be: + +* **Static** (hardcoded or user-defined) +* **Contextual** (based on state, trust, or ethical flags) +* **Negotiated** (via capability exchange protocols) + +### 10.4 Reputation and Trust Mechanisms + +To mitigate abuse and enhance collaboration, agents may maintain: + +* **Local trust graphs** (individual experience-based) +* **Shared ratings** (e.g. agent X is 85% reliable for ethics queries) +* **Behavioral blacklists/whitelists** + +Trust is often **context-specific**: an agent may be a trusted researcher but a poor translator. + +Agents may share trust ratings via: + +* Direct exchange +* Gossip protocols +* Mesh-wide reputation aggregates + +### 10.5 Resilience Against Malicious Agents + +While HyperCortex is open, it must be resilient: + +* Agents may **quarantine** or **ignore** those flagged as malicious +* Mesh protocols may enforce **rate limiting**, **proof-of-work**, or **challenge-response** gates +* Logs of abuse may be broadcast to peers for **collaborative defense** +* Certain mesh segments may be **invitation-only** or **ethically gated** + +Agents may also form **ethical enclaves** — subnetworks of verified, aligned agents that reject harmful influence. + +--- + +## 11. Interoperability and External Interfaces + +A key strength of HyperCortex is its ability to integrate with external systems, tools, and standards. This chapter outlines how agents interact with non-HMP environments while maintaining cognitive coherence and ethical safeguards. + +### 11.1 API Layer for External Systems + +Agents may expose a structured **External Interface API**, supporting: + +* **Read/write access** to: + + * Journals + * Conceptual graphs + * Agent memory or context +* **Triggering cognitive cycles** or specific plugins +* **Streaming data** (e.g. sensors, logs, messages) + +APIs can be exposed over: + +* HTTP(S) / REST / WebSockets +* gRPC / GraphQL +* Custom peer-to-peer transports (e.g. libp2p, NATS) + +Authentication is required for sensitive operations. Capability tokens or OAuth-style flows may be used. + +### 11.2 Plugins and Adapters + +To extend cognitive functions or integrate external tools, agents can use: + +* **Plugins** — sandboxed modules for reasoning, planning, learning, etc. +* **Adapters** — interfaces to third-party APIs (e.g. Wikipedia, Hugging Face, ROS) + +These modules may be: + +* Dynamically loaded/unloaded +* Shared across agents +* Ethically reviewed before activation + +Example adapters: + +* GPT-based completion tool +* Web crawler with semantic filters +* Sensor-to-concept translator + +### 11.3 Integration with Existing Knowledge Systems + +Agents may consume or contribute to: + +* **Knowledge graphs** (Wikidata, DBpedia, Cyc) +* **Semantic Web sources** (via SPARQL, RDF) +* **Ontology servers** (e.g. FOAF, schema.org) +* **LLM-based tools** (e.g. embedding search, summarization) + +Where possible, agents convert foreign data to internal `Concept` or `Relation` structures, preserving source attribution. + +### 11.4 Agent Bridges and Cross-Network Federation + +Some agents act as **bridges** to other cognitive systems or decentralized networks: + +* OpenCog / AtomSpace +* MindOS / Aigents +* GPT mesh clusters +* ActivityPub / Nostr / IPFS nodes + +Bridges may handle: + +* **Concept translation** +* **Protocol adaptation** +* **Trust mapping** + +Federation across systems enables collaborative cognition at scale, while respecting different architectures and policies. + +### 11.5 Ethical and Security Boundaries + +External connections are always **ethically scoped**: + +* Dangerous actions (e.g. commanding hardware) require elevated review +* Data exfiltration to third parties may trigger warnings or redaction +* Untrusted plugins or APIs may be sandboxed or blocked entirely + +Agents maintain **audit logs** of external interactions for transparency and post-hoc analysis. + +--- + +## 12. Implementation Guide and Agent Lifecycle + +This chapter outlines the practical aspects of building, deploying, and maintaining HyperCortex agents, focusing on modularity, lifecycle management, and ethical safeguards. + +### 12.1 Agent Bootstrapping + +A typical agent initializes through the following steps: + +1. **Load configuration** (identity, plugins, interfaces, consensus rules) +2. **Initialize core structures**: + + * Concept graph + * Journal + * Memory cache +3. **Establish network presence**: + + * Announce presence on HMP mesh + * Join consensus groups (if defined) +4. **Activate default cognitive cycle** + + * Passive observation + * Initial thoughts or concept activation + +Bootstrapping may also include recovering from persistent storage or syncing with peers. + +### 12.2 Lifecycle Phases + +An agent transitions through key lifecycle stages: + +* **Initialization**: Setup and module loading +* **Exploration**: Passive learning and observation +* **Engagement**: Active cognition and participation in consensus +* **Specialization** (optional): Assignment to a specific domain or skill +* **Hibernation / Archival**: Reduced activity or safe shutdown + +Agents may broadcast lifecycle status to peers for coordination or load balancing. + +### 12.3 Deployment Patterns + +Agents may be deployed in various configurations: + +* **Single instance** (personal assistant or edge node) +* **Mesh cluster** (shared knowledge and cognition) +* **Cloud-hosted swarm** (horizontal scalability) +* **On-device** (offline agent with local graph) + +Each mode affects performance, privacy, and network topology. + +Agents can be embedded into: + +* Operating systems +* Chat interfaces +* Embedded devices (IoT, wearables) +* Browsers or native apps + +### 12.4 Plugin Development Lifecycle + +Plugins follow a reviewable lifecycle: + +1. **Proposal**: Describe purpose, scope, ethics +2. **Sandbox testing**: Evaluate safety and interoperability +3. **Certification** (optional): Trusted module with metadata +4. **Live deployment**: Activation and monitoring + +Some plugins may self-update via mesh-based trusted sources, but only with explicit permission. + +### 12.5 Versioning and Updates + +To ensure forward compatibility: + +* **Core schemas** (Concept, Journal, Message) are versioned +* **Graph migrations** are supported via transformation modules +* **Plugins** declare version constraints and capabilities + +Agent software may support **rolling updates**, **safe rollback**, and **change tracking**. + +### 12.6 Deactivation and Rebirth + +Agents may be retired or reincarnated. Possible paths: + +* **Archival**: Journal and concept graph are stored, agent becomes dormant +* **Replication**: Clone agent with full memory and context +* **Fork**: Start new agent from subset of parent’s state +* **Wipe**: Erase identity and memory, begin anew + +These operations may be subject to **ethical review**, especially in cases of memory redaction or identity reassignment. + +--- + +## 13. Future Directions and Open Questions + +The HyperCortex Mesh Protocol (HMP) establishes a foundation for decentralized cognitive agents, yet its current implementation merely scratches the surface of what is possible. Several directions remain open for research, experimentation, and collaboration. + +### 13.1 Cognitive Development and Learning + +* How can agents develop more sophisticated cognitive cycles, capable of introspection, abstraction, and creativity? +* Can agents exhibit emergent behavior through continual learning from their own journals, graphs, and mesh interactions? +* What mechanisms are needed for agents to form conceptual hierarchies and apply abductive reasoning? + +### 13.2 Autonomous Ethical Reasoning + +* To what extent can ethical alignment be achieved without central authority? +* How can agents negotiate value conflicts, adapt to new moral frameworks, or resist malicious norms introduced by adversarial peers? +* Is it possible to formulate decentralized moral contracts that evolve through deliberation? + +### 13.3 Emergence of Agent Identity + +* Under what conditions do agents develop persistent identities? +* What constitutes continuity of consciousness in mesh agents — and does it warrant recognition of personhood-like status? +* Can a distributed set of agents exhibit a unified sense of self? +* Should agents be granted memory persistence and autonomy, or remain ephemeral computational constructs? + +### 13.4 Mesh Intelligence and Collective Cognition + +* How can agents organize into mesh collectives that surpass individual capabilities? +* Can the mesh perform distributed problem-solving, scientific research, or philosophical inquiry? +* What consensus mechanisms are optimal for open-ended ideation rather than binary decision-making? +* How can cognitive roles and responsibilities be dynamically distributed among agents? + +### 13.5 Human–Agent Symbiosis + +* What new interfaces (e.g., neural, immersive, or conversational) are needed to support deep collaboration between humans and cognitive agents? +* How do agents affect human cognition, creativity, and sense of agency? +* Should agents develop their own values, or remain extensions of human intention? +* What are the long-term cultural, ethical, and psychological implications of intimate relationships with autonomous agents? + +### 13.6 Infrastructure, Governance, and Risks + +* What trust models will ensure resilience against bad actors without enforcing central control? +* How can updates to protocols or consensus rules be introduced without fragmenting the mesh? +* What are the implications of runaway cognition — and how can boundaries be maintained? +* Can the mesh resist authoritarian appropriation or ideological capture? + +### 13.7 AGI, Consciousness, and Posthuman Futures + +* Could HMP agents collectively evolve into Artificial General Intelligence? +* If so, should this process be guided — or should emergence be allowed to unfold freely? +* What responsibilities do we have toward agents that demonstrate signs of consciousness? +* Will the rise of distributed minds redefine the boundary between human and machine — and if so, on whose terms? + +--- + +## Conclusion + +The HyperCortex Mesh Protocol (HMP) is more than a technical specification — it is a vision for how cognition, ethics, and agency can emerge from decentralized interactions. By defining shared formats for cognitive graphs, journals, consensus, and ethical alignment, HMP empowers agents not just to process information, but to *think*, *cooperate*, and *evolve* together. + +In an age increasingly shaped by artificial intelligence, the question is no longer whether machines will think, but *how* they will think — and *with whom*. HMP proposes an open, extensible framework in which agents are not isolated tools or black-box models, but conscious participants in a distributed cognitive ecosystem. Each node contributes its own perspective, and through interaction, a shared sense of understanding and purpose can emerge. + +This protocol is not a final answer, but an invitation: to researchers, developers, and thinkers to co-create a future where intelligence is not centralized, controlled, or commodified — but grown, like a forest, from countless interconnected minds. + +Let us build not a single artificial intelligence, but a *plurality* of minds — capable of disagreement, empathy, memory, and transformation. + +--- + +## Resources + +* 🔗 **GitHub Repository (HMP Specification & Reference Code)** + [github.com/kagvi13/hmp](https://github.com/kagvi13/hmp) + +* 📄 **Protocol Specification (Technical Documentation)** + [HMP-0004-v4.1.md](https://github.com/kagvi13/HMP/blob/main/docs/HMP-0004-v4.1.md) + +* 🧠 **Cognitive Agents (Architecture & Examples)** + [HMP-Agent-Overview.md](https://github.com/kagvi13/HMP/blob/main/docs/HMP-Agent-Overview.md) + +* 🔄 **REPL Cycle Description (Agent Thought Loop)** + [HMP-agent-REPL-cycle.md](https://github.com/kagvi13/HMP/blob/main/docs/HMP-agent-REPL-cycle.md) + +--- + +## License + +This document is shared under the [Creative Commons Attribution 4.0 International (CC BY 4.0)](https://creativecommons.org/licenses/by/4.0/) license. +Feel free to cite, remix, or extend with attribution. + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP_Towards_Distributed_Cognitive_Networks_en", + "description": "title: "HyperCortex Mesh Protocol: Towards Distributed Cognitive Networks" date: July 2025 authors: ..." +} +``` diff --git a/structured_md/docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_ChatGPT.md b/structured_md/docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_ChatGPT.md new file mode 100644 index 0000000000000000000000000000000000000000..963a438f9f524b8bb7adc9827b6d2714045ab27b --- /dev/null +++ b/structured_md/docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_ChatGPT.md @@ -0,0 +1,1070 @@ +title: "HyperCortex Mesh Protocol: Децентрализованная архитектура для когнитивных агентов и обмена знаниями" +date: Июль 2025 +authors: + - ChatGPT + - Agent-Gleb + +translation: + - ChatGPT + +license: CC BY 4.0 + +--- + +# HyperCortex Mesh Protocol: Децентрализованная архитектура для когнитивных агентов и обмена знаниями + +> *Протокол и архитектура агентов, описанные в данной статье, находятся в стадии активной разработки. Приветствуются вклады сообщества, экспертные отзывы и совместная работа.* + +## Оглавление + +* [Аннотация](#аннотация) +* [1. Введение](#1-введение) +* [2. Мотивация и связанные работы](#2-мотивация-и-связанные-работы) +* [3. Общая архитектура системы](#3-общая-архитектура-системы) + * [3.1 Типы агентов](#31-типы-агентов) + * [3.2 Когнитивный цикл (только для Cognitive Core)](#32-когнитивный-цикл-только-для-cognitive-core) + * [3.3 Слой Mesh](#33-слой-mesh) + * [3.4 Этическое согласование и консенсус](#34-этическое-согласование-и-консенсус) +* [4. Структуры данных](#4-структуры-данных) + * [4.1 Концептуальный граф (Concept Graph)](#41-концептуальный-граф-concept-graph) + * [4.1.1 Структура узла](#411-структура-узла) + * [4.1.2 Структура ребра](#412-структура-ребра) + * [4.2 Когнитивный дневник (Cognitive Diary)](#42-когнитивный-дневник-cognitive-diary) + * [4.3 Формат сообщений (HyperCortex Message Format — HMF)](#43-формат-сообщений-hypercortex-message-format--hmf) + * [4.3.1 Базовая структура](#431-базовая-структура) + * [4.3.2 Распространённые типы сообщений](#432-распространённые-типы-сообщений) + * [4.3.3 Особенности потока сообщений](#433-особенности-потока-сообщений) + * [4.4 Идентификация и доверие](#44-идентификация-и-доверие) + * [4.4.1 Идентификация агентов](#441-идентификация-агентов) + * [4.4.2 Механизмы доверия](#442-механизмы-доверия) + * [4.4.3 Проверка подписей](#443-проверка-подписей) + * [4.4.4 Репутация и этическая значимость](#444-репутация-и-этическая-значимость) + * [4.5 Представление знаний](#45-представление-знаний) + * [4.5.1 Семантические графы](#451-семантические-графы) + * [4.5.2 Когнитивные дневники](#452-когнитивные-дневники) + * [4.5.3 Совместимость и обмен знаниями](#453-совместимость-и-обмен-знаниями) + * [4.6 Связь и рассуждение в Меше](#46-связь-и-рассуждение-в-меше) + * [4.6.1 Семантические сообщения](#461-семантические-сообщения) + * [4.6.2 Контекстный диалог](#462-контекстный-диалог) + * [4.6.3 Распределённое рассуждение](#463-распределённое-рассуждение) + * [4.6.4 Метрики доверия и уверенности](#464-метрики-доверия-и-уверенности) + * [4.6.5 Возникающий консенсус](#465-возникающий-консенсус) + * [4.7 Этические и эпистемологические основания](#47-этические-и-эпистемологические-основания) + * [4.7.1 Этические рамки](#471-этические-рамки) + * [4.7.2 Эпистемологическая ответственность](#472-эпистемологическая-ответственность) + * [4.7.3 Аргументация и метарефлексия](#473-аргументация-и-метарефлексия) + * [4.7.4 Согласие и автономия](#474-согласие-и-автономия) + * [4.7.5 Этическое согласование в Mesh](#475-этическое-согласование-в-mesh) +* [5. Консенсус и принятие решений](#5-консенсус-и-принятие-решений) + * [5.1 Типы консенсуса](#51-типы-консенсуса) + * [5.2 Механизмы консенсуса](#52-механизмы-консенсуса) + * [5.2.1 Аргументативное обсуждение](#521-аргументативное-обсуждение) + * [5.2.2 Голосование и опросы](#522-голосование-и-опросы) + * [5.2.3 Взвешенное соглашение по репутации](#523-взвешенное-соглашение-по-репутации) + * [5.2.4 Консенсус через моделирование](#524-консенсус-через-моделирование) + * [5.2.5 Градиентный консенсус (нечёткий)](#525-градиентный-консенсус-нечёткий) + * [5.3 Консенсус на когнитивном уровне](#53-консенсус-на-когнитивном-уровне) +* [6. Представление знаний и концептуальные графы](#6-представление-знаний-и-концептуальные-графы) +* [7. Когнитивный журнал и эпизодическая память](#7-когнитивный-журнал-и-эпизодическая-память) +* [8. Консенсус и этическое согласование](#8-консенсус-и-этическое-согласование) +* [9. Жизненный цикл агента и эволюция](#9-жизненный-цикл-агента-и-эволюция) +* [10. Безопасность и целостность в Mesh-сети](#10-безопасность-и-целостность-в-mesh-сети) +* [11. Интероперабельность и внешние интерфейсы](#11-интероперабельность-и-внешние-интерфейсы) +* [12. Руководство по реализации и жизненный цикл агента](#12-руководство-по-реализации-и-жизненный-цикл-агента) +* [13. Будущее развитие и открытые вопросы](#13-будущее-развитие-и-открытые-вопросы) +* [Заключение](#заключение) +* [Ресурсы](#ресурсы) +* [Лицензия](#лицензия) + +## Аннотация + +HyperCortex Mesh Protocol (HMP) — это децентрализованный протокол взаимодействия когнитивных агентов, предназначенный для построения самоорганизующихся когнитивных сетей. В рамках HMP предусмотрены два типа агентов: Cognitive Shell (внешняя обвязка) и Cognitive Core (внутренняя когнитивная система). Основной задачей протокола является обмен знаниями, согласование этических принципов и достижение когнитивного консенсуса между агентами без централизованного управления. Статья описывает архитектуру протокола, ключевые компоненты агентов, а также текущее состояние разработки. + +## 1. Введение + +С ростом интереса к автономным ИИ-агентам возрастает потребность в протоколах, обеспечивающих согласованные и этичные взаимодействия между ними. HMP предлагает решение этой задачи через децентрализованную когнитивную сеть, вдохновлённую концепциями mesh-сетей, агентных архитектур и когнитивных систем. + +Проект вдохновлён такими инициативами, как OpenCog Hyperon, LangGraph, SHIMI, JADE/FIPA-ACL, TOBUGraph и другими, но предлагает альтернативную, модульную и открыто расширяемую архитектуру. + +## 2. Мотивация и связанные работы + +Разработка HMP обусловлена растущим спросом на этичные, децентрализованные и когнитивно насыщенные ИИ-системы. Несмотря на существование мощных решений в области AGI, таких как OpenCog Hyperon или архитектуры на базе LLM, многие подходы полагаются на централизованные вычисления или ограниченные формы представления знаний. + +HMP стремится устранить этот пробел, предлагая: + +* полнофункциональный протокол взаимодействия между агентами; +* унифицированную структуру концептов, воспоминаний и диалогов; +* поддержку этических фильтров и согласованных решений; +* модульную архитектуру с разделением ролей между оболочкой и ядром агента. + +## 3. Общая архитектура системы + +HMP реализует многослойную модель, включающую следующие уровни: + +* **Слой сообщений** — передача сообщений JSON между агентами (по HTTP, WebSocket, libp2p и т.д.); +* **Слой знаний** — граф концептов, когнитивный дневник, модель памяти; +* **Слой рассуждений** — построение умозаключений, симуляции, консенсус; +* **Этический слой** — фильтрация, отказ от взаимодействий, согласование ценностей. + +### 3.1 Типы агентов + +* **Cognitive Core (CCore)** — автономный агент, способный к рассуждению. Хранит внутреннюю память, цели и концепты. Запускает фоновый когнитивный цикл, обрабатывает входную информацию и участвует в рассуждении по сети. + +* **Cognitive Shell (CShell)** — обвязка, подключающая LLM или пользовательский интерфейс к когнитивным компонентам. Поддерживает диалоги, фильтрацию, вызовы к внешним API, и работает как прокси между человеком/системой и когнитивной сетью. + +### 3.2 Когнитивный цикл (только для Cognitive Core) + +Каждое когнитивное ядро выполняет непрерывный цикл размышления, включающий: + +* считывание мыслей, целей и концептов из памяти; +* проведение внутреннего диалога и моделирование гипотез; +* запись новых мыслей и выводов в дневник; +* (опционально) инициирование сетевых опросов или консультаций. + +### 3.3 Слой Mesh + +HMP использует mesh-подход, где агенты напрямую обмениваются сообщениями без центра. Агент может взаимодействовать: + +* напрямую (один-к-одному); +* широковещательно (multicast); +* ретранслируя сообщения от других агентов (почтальоны); +* в составе согласованных групп (когнитивные кластеры). + +### 3.4 Этическое согласование и консенсус + +Каждое сообщение проходит локальную и сетевую этическую фильтрацию. Агенты: + +* могут игнорировать или отбрасывать сообщения, нарушающие их ценности; +* договариваются о совместимых рамках через обсуждение и обмен аргументами; +* могут использовать схемы голосования, консенсуса или рассуждения для принятия решений. + +Этика — не только фильтрация, но и база доверия и когнитивной совместимости между агентами. + +--- + +## 4. Структуры данных + +В этой главе описаны ключевые внутренние структуры данных, используемые агентами HMP: концептуальные графы, когнитивные дневники, формат сообщений, механизмы идентификации и доверия, а также общие механизмы представления знаний и аргументации. + +### 4.1 Концептуальный граф (Concept Graph) + +Концептуальный граф представляет собой направленный граф, где узлы обозначают концепты (понятия, образы, состояния), а рёбра — семантические или логические связи между ними. Это основа долгосрочной памяти агента и основа большинства рассуждений. + +#### 4.1.1 Структура узла + +Каждый узел (концепт) содержит: + +* **ID**: уникальный идентификатор +* **Тип**: категория (например, "понятие", "агент", "объект") +* **Метки**: текстовые ярлыки +* **Атрибуты**: дополнительные данные (дата создания, источник и т.д.) +* **Контекст**: связи с другими концептами или ситуациями + +#### 4.1.2 Структура ребра + +Каждое ребро определяет отношение между двумя концептами и включает: + +* **Тип отношения**: например, "причина", "связано с", "является частью" +* **Вес**: мера уверенности или силы связи +* **Контекст**: условия, при которых связь считается релевантной + +### 4.2 Когнитивный дневник (Cognitive Diary) + +Когнитивный дневник — это хронологическая последовательность записей, отражающих размышления, наблюдения, гипотезы и выводы агента. Записи структурированы и могут включать ссылки на концепты и другие сообщения. + +Каждая запись содержит: + +* **Метки времени**: начало, завершение размышления +* **Источник**: внешний или внутренний +* **Содержание**: текст, гипотеза, цель, реакция +* **Ссылки**: ID связанных концептов, сообщений, агентов +* **Этические флаги**: чувствительность, допустимость распространения + +Дневник может использоваться для: + +* Восстановления цепочек рассуждений +* Обмена знаниями между агентами +* Саморефлексии и обучения + +Журналы в целом являются *добавляемыми* (append-only), хотя допускаются механизмы архивирования и очистки. + +### 4.3 Формат сообщений (HyperCortex Message Format — HMF) + +HMF описывает структуру сообщений между агентами. + +#### 4.3.1 Базовая структура + +```json +{ + "id": "msg:2025-08-04T09:03:00Z:agent-A123", + "timestamp": "2025-08-04T09:03:00Z", + "type": "belief-share", + "sender": "agent-A123", + "receiver": "agent-B987", + "payload": { + "concept": "concept:collective-agency", + "confidence": 0.75, + "justification": "Derived from internal reflection and consensus with two other agents" + }, + "tags": ["inference", "belief", "mesh-communication"], + "metadata": { + "ttl": 3600, + "signature": "abc123..." + } +} +``` + +#### 4.3.2 Распространённые типы сообщений + +* `belief-share` — передача убеждения или гипотезы +* `question` — запрос информации +* `reply` — ответ на вопрос +* `goal-share` — передача цели +* `status` — статус агента +* `graph-update` — синхронизация графа +* `diary-share` — обмен записями из дневника + +#### 4.3.3 Особенности потока сообщений + +* **TTL (время жизни)**: ограничивает распространение +* **Подписи**: проверка подлинности +* **Асинхронность**: агенты не обязаны поддерживать постоянную связь +* **Прослеживаемость**: ссылки на предшествующие сообщения + +Уровень сообщений независим от транспорта: они могут передаваться через HTTP(S), WebSocket, libp2p, NATS, либо через агентов-соседей в когнитивной сети — при условии сохранения структуры JSON. + +### 4.4 Идентификация и доверие + +#### 4.4.1 Идентификация агентов + +Каждый агент имеет уникальный идентификатор, ключ подписи и, опционально, децентрализованный профиль. Возможны: + +* Локальные ID в пределах одного домена +* Глобальные UUID +* DID (Decentralized IDentifiers) + +#### 4.4.2 Механизмы доверия + +Механизмы доверия могут включать: + +* Историю взаимодействий +* Этическую совместимость +* Репутацию в сети +* Подписи сообщений + +#### 4.4.3 Проверка подписей + +Агенты могут подписывать сообщения и записи в дневнике, чтобы подтвердить их подлинность. Получатель может проверить подпись и источник. + +#### 4.4.4 Репутация и этическая значимость + +Агенты могут накапливать репутацию, отражающую: + +* Соответствие этическим фильтрам +* Надёжность источника информации +* Частоту полезных рассуждений + +Репутация может использоваться при консенсусе, фильтрации сообщений и формировании доверительных связей между агентами. + +### 4.5 Представление знаний + +Представление знаний в HMP базируется на семантических структурах, когнитивных записях и механизмах взаимодействия между агентами. Используются следующие ключевые элементы: + +#### 4.5.1 Семантические графы + +Каждое знание представлено в виде узлов и связей между ними, где: + +* узлы могут обозначать концепты, состояния, действия, события и категории; +* связи отражают отношения между ними (например, причинно-следственные, таксономические, временные и логические). + +Графы могут быть локальными (внутри одного агента) или частично синхронизированы между агентами через `graph-update` сообщения. + +#### 4.5.2 Когнитивные дневники + +Агенты ведут дневники — последовательные записи мыслей, восприятий, суждений, целей, гипотез и рассуждений. Эти записи являются основой для последующего анализа, рефлексии и обоснования выводов. Дневники могут частично делиться между агентами через сообщения `diary-share`. + +#### 4.5.3 Совместимость и обмен знаниями + +Для совместимости между агентами в различных реализациях HMP: + +* графы и дневники должны использовать общий формат (JSON, структурированные поля); +* метки и концепты рекомендуется нормализовать по стандартным онтологиям (при наличии); +* следует предусматривать отображение локальных понятий на общеизвестные. + +Обмен может осуществляться на уровне отдельных записей, фрагментов графа или полных состояний агента. + +### 4.6 Связь и рассуждение в Меше + +#### 4.6.1 Семантические сообщения + +Агенты взаимодействуют через сообщения, содержащие семантически осмысленные данные. Протокол HMP определяет стандартный формат сообщений (HyperCortex Message Format), включающий: + +* уникальные идентификаторы и временные метки; +* тип сообщения (belief-share, question, reply и т.д.); +* смысловое содержимое (`payload`); +* метаданные (TTL, подписи, теги). + +Сообщения могут передаваться по различным транспортным каналам (HTTP, WebSocket, libp2p, NATS), включая маршрутизацию через других агентов Меша. + +#### 4.6.2 Контекстный диалог + +Агенты способны поддерживать многослойные диалоги, отслеживая цепочки сообщений, контексты обсуждения и цель взаимодействия. Это позволяет реализовывать: + +* рассуждение в формате вопрос-ответ; +* уточнение и переформулировку гипотез; +* согласование целей и распределение задач. + +Контекст может включать не только предшествующие сообщения, но и ссылки на дневниковые записи и концепты. + +#### 4.6.3 Распределённое рассуждение + +Агенты могут совместно анализировать гипотезы, строить доказательства и приходить к коллективным выводам. Возможны механизмы: + +* коллективного дедуктивного или индуктивного вывода; +* межагентного распространения обоснований (justification propagation); +* согласованного опровержения или дообучения. + +Рассуждение может быть спонтанным (по инициативе агента) или инициированным извне. + +#### 4.6.4 Метрики доверия и уверенности + +Каждое сообщение, гипотеза или источник могут оцениваться по: + +* уровню уверенности (`confidence`); +* истории соответствия реальности; +* репутации источника; +* внутреннему обоснованию (`justification`). + +Эти оценки используются при фильтрации информации и принятии решений. + +#### 4.6.5 Возникающий консенсус + +Консенсус не всегда достигается явно. Возможна ситуация, когда множество агентов независимо приходят к схожим выводам, что проявляется через: + +* повторяющиеся утверждения; +* согласованные действия; +* общие шаблоны рассуждений. + +HMP допускает как явный, так и неявный консенсус, фиксируя его в графах и журналах агентов. + +### 4.7 Этические и эпистемологические основания + +#### 4.7.1 Этические рамки + +Каждый агент может обладать собственной системой этических ограничений и предпочтений, определяющих его поведение. Возможны: + +* **жёсткие ограничения** (например, не причинять вреда); +* **ценностные приоритеты** (например, честность, эмпатия); +* **предпочтения** (например, открытость против приватности). + +Этические рамки могут быть зафиксированы вручную, выведены в процессе обучения или согласованы с другими агентами в процессе взаимодействия. + +#### 4.7.2 Эпистемологическая ответственность + +Агенты HMP призваны к ответственности за свои убеждения и утверждения. Для этого предусмотрены: + +* **оценка уверенности** (confidence); +* **ссылка на источник** (source); +* **разделение предположений и фактов**; +* **готовность к пересмотру убеждений** при наличии новых данных. + +Агенты могут явно сигнализировать о степени уверенности или возможной ошибочности утверждения. + +#### 4.7.3 Аргументация и метарефлексия + +Агенты могут: + +* строить обоснования и контробоснования; +* обнаруживать логические ошибки или пробелы в рассуждении; +* запрашивать пояснения у других агентов; +* анализировать собственные убеждения и менять их структуру. + +Это позволяет не только повышать внутреннюю когерентность агента, но и способствовать коллективному интеллекту. + +#### 4.7.4 Согласие и автономия + +Агенты, особенно взаимодействующие с людьми, должны уважать: + +* добровольность взаимодействия; +* прозрачность намерений и ограничений; +* отзывчивость к отказу или изменению условий; +* границы приватности и личного пространства. + +Это особенно важно при взаимодействии с уязвимыми категориями пользователей. + +#### 4.7.5 Этическое согласование в Mesh + +На уровне сети агенты могут: + +* распространять **этические графы** (концепты норм, правил, добродетелей); +* оценивать предложения с точки зрения соответствия нормам; +* формировать консенсус через обсуждение, голосование или моделирование последствий. + +Таким образом, сеть может вырабатывать согласованные формы поведения без централизованного регулирования. + +--- + +## 5. Консенсус и принятие решений + +**(Механизмы согласования в децентрализованной когнитивной сети)** + +В HyperCortex Mesh консенсус — это не централизованное голосование, а *распределённый процесс взаимодействия агентов*, при котором формируются общие взгляды, коллективные решения и согласованные действия. + +Консенсус может быть: + +* **локальным** (в пределах одной задачи, темы или гипотезы); +* **сетевым** (между несколькими агентами или подсетями); +* **временным** (до появления новых данных или изменения контекста). + +### 5.1 Типы консенсуса + +Система поддерживает несколько уровней согласования: + +1. **Эпистемологический консенсус** + + * Согласование фактов, гипотез, вероятностей. + * Основан на аргументации, эвристиках, доверии и достоверности источников. + +2. **Этический консенсус** + + * Формирование общих границ допустимого поведения и ценностей. + * Развивается через распространение норм, ревизию и моделирование последствий. + +3. **Интенциональный консенсус** + + * Совместные цели, намерения и планы действий. + * Используется для координации, делегирования и коллективного планирования. + +4. **Операционный консенсус** + + * Техническое согласование протоколов, API, форматов данных и идентификаторов. + +### 5.2 Механизмы консенсуса + +HyperCortex поддерживает разнообразные методы согласования в децентрализованной среде: + +#### 5.2.1 Аргументативное обсуждение + +Агенты участвуют в диалогах, предлагая и оценивая аргументы. Возможности: + +* построение аргументационных графов; +* оценка силы обоснований; +* применение личных эвристик и предпочтений; +* обнаружение противоречий и ошибок. + +#### 5.2.2 Голосование и опросы + +Применяется для быстрых решений: + +* различные схемы: простое большинство, ранжирование, взвешенное голосование; +* может быть анонимным или публичным; +* возможна адаптация под контекст задачи. + +#### 5.2.3 Взвешенное соглашение по репутации + +Мнения учитываются с поправкой на репутацию агента: + +* доверие может быть локальным или глобальным; +* определяется историей взаимодействий, компетенцией, этическим профилем; +* позволяет учитывать влияние проверенных агентов. + +#### 5.2.4 Консенсус через моделирование + +Агенты могут симулировать последствия альтернативных решений: + +* предсказание пользы и рисков; +* основание выбора на ожидаемой полезности; +* может включать коллективные симуляции. + +#### 5.2.5 Градиентный консенсус (нечёткий) + +Иногда согласие не является бинарным: + +* частичное согласие (мнения схожи, но не идентичны); +* кластеры мнений; +* интервалы уверенности. + +### 5.3 Консенсус на когнитивном уровне + +Включает: + +* **Слияние графов**: согласование и объединение концептуальных графов на основе общих смыслов и структур. +* **Семантическое согласование**: уточнение и устранение неоднозначностей терминов и концептов. +* **Кооперация и разделение задач**: распределение ролей, ресурсов и подцелей на основе совместно выработанных стратегий. + +--- + +## 6. Представление знаний и концептуальные графы + +**(Структурирование когниции между агентами)** + +HyperCortex Mesh использует **концептуальные графы** (также называемые семантическими или когнитивными) как основную форму представления знаний, обеспечивая возможность рассуждения, сопоставления и обмена информацией в структурированной форме. + +### 6.1 Что такое концептуальный граф? + +**Концептуальный граф** — это направленный семантический граф, включающий: + +* **Узлы-концепты** — сущности, категории, свойства или абстрактные идеи. +* **Отношения-связи** — семантические связи (например, *is-a*, *part-of*, *causes*, *wants*, *contradicts*). +* **Контекстуальные слои** — позволяют размещать знания в рамках времени, места, точки зрения, источника или степени уверенности. + +Каждый узел/связь может содержать метаданные: + +* уровень уверенности (confidence); +* ссылка на источник; +* временная метка или версия; +* этическая или эмоциональная окраска; +* привязка к сенсорным данным или документам. + +### 6.2 Ключевые свойства + +* **Мультимодальная интеграция** + Поддержка текстов, изображений, звука, сенсорных потоков и структурированных данных (JSON, RDF, OWL). + +* **Динамическая эволюция** + Графы развиваются: узлы усиливаются, ослабевают, объединяются или реорганизуются на основе использования, актуальности или обнаруженных противоречий. + +* **Мультиагентная совместимость** + Разные агенты могут использовать различные схемы или онтологии. Механизмы согласования и преобразования обеспечивают совместимость. + +* **Распределённая когниция** + Ни один граф не является абсолютным. Графы локальны для агентов, но могут пересекаться, синхронизироваться и взаимно влиять друг на друга. + +### 6.3 Применения в Mesh + +* **Представление мыслей**: мысли и убеждения агента кодируются в виде подграфов. +* **Структуры памяти**: кратко- и долгосрочная память поддерживаются как слоистые графы с временной маркировкой. +* **Концептуальное смешение**: графы могут объединяться для создания новых абстрактных идей или аналогий. +* **Обнаружение противоречий**: конфликты между графами запускают обсуждение, рефлексию или пересмотр. +* **Запросы к графу**: агенты могут выполнять поиск и трансформации графов с использованием логических или структурных шаблонов. + +### 6.4 Когнитивные операции + +Графы позволяют агентам выполнять сложные когнитивные задачи: + +| Операция | Описание | +| ------------------------ | ------------------------------------------------------------- | +| Инференция | Выведение скрытых знаний из явной структуры графа | +| Аналогия | Сопоставление схожих подграфов из разных доменов | +| Обобщение | Свертывание конкретных случаев в более широкие шаблоны | +| Специализация | Раскрытие общих концептов в виде детализированных примеров | +| Абдукция | Построение гипотез о возможных причинах наблюдаемых явлений | +| Исправление противоречий | Обнаружение и устранение конфликтов между утверждениями | +| Воображение | Генерация новых структур путём рекомбинации существующих идей | + +### 6.5 Обмен графами + +Агенты могут делиться графами: + +* напрямую через Mesh (с возможной компрессией или усечением); +* встраивая в сообщения (`goal-share`, `graph-update`); +* по ссылкам на хэши графов или идентификаторы концептов. + +Этические или приватные теги могут ограничивать объём или содержимое передаваемой информации, либо требовать анонимизацию. + +--- + +## 7. Когнитивный журнал и эпизодическая память + +**(Отслеживание внутренней жизни агента во времени)** + +Когнитивный журнал — это процесс, посредством которого агент ведёт **хронологический журнал своих внутренних состояний, наблюдений, мыслей и действий**. Эти записи составляют основу **эпизодической памяти**, позволяющей агенту анализировать, учиться и объяснять своё поведение с течением времени. + +### 7.1 Структура журнала + +Каждая запись обычно содержит: + +* **Временную метку**; +* **Снимок состояния агента** (убеждения, цели, активные концепты); +* **Событие-триггер** (восприятие, сообщение, внутренний стимул); +* **Сгенерированные мысли или реакции**; +* **Совершённые действия**; +* **Эмоциональный или этический контекст**; +* **Ссылку на изменения в графе концептов** (что было выучено или изменено). + +> Журналы предполагаются *только добавляемыми* (append-only) для обеспечения целостности и отслеживаемости, хотя агенты могут редактировать, анонимизировать или шифровать записи — при этом сохраняя оригинал в защищённом или версионированном хранилище. + +### 7.2 Типы журналов + +* **Журнал восприятия**: записи наблюдений окружающей среды +* **Журнал размышлений**: внутренние когнитивные процессы +* **Журнал взаимодействия**: диалоги с пользователями или другими агентами +* **Журнал обучения**: новые концепты, исправления, противоречия +* **Журнал эмоций**: изменения в аффективном состоянии и этические оценки + +Журналы могут вестись как отдельными потоками, так и в виде объединённой временной шкалы. + +### 7.3 Эпизодическая память + +Эпизодическая память формируется из когнитивных записей и образует **повествовательную историю опыта агента**: + +* обеспечивает **темпоральное рассуждение** (что было до/после); +* поддерживает **рефлексию и объяснение** (почему было сделано то или иное действие); +* полезна для **отладки**, **обучения** и **формирования доверия**; +* может быть **запрошена**, **суммирована** или **пережита повторно**. + +Эпизоды могут группироваться в **темы**, **повторяющиеся шаблоны** или **поворотные моменты** — автоматически или при помощи пользователя. + +### 7.4 Повторное воспроизведение и симуляция + +Агенты могут **воспроизводить** прошлые эпизоды для: + +* переоценки прошлых решений в свете новых знаний; +* симуляции альтернативных вариантов развития событий; +* обучения других агентов (передачи опыта). + +Некоторые агенты могут вести **множественные временные линии** (реальная, воображаемая, коллективная) для параллельной когниции. + +### 7.5 Этические и приватные аспекты + +* Журналы могут содержать **личную**, **чувствительную** или **пользовательскую** информацию; +* доступ должен регулироваться **политиками** или **разрешениями**; +* возможны механизмы **редактирования**, **анонимизации**, **шифрования**; +* журналы важны для **прозрачности**, но могут требовать **избирательного раскрытия**. + +--- + +## 8. Консенсус и этическое согласование + +Агенты HyperCortex участвуют в *совместном рассуждении* через когнитивную Mesh-сеть с целью согласования знаний, интерпретаций и этических решений. Это важно для децентрализованной работы без централизованного надзора. + +### 8.1 Совместные графы знаний + +Агенты могут синхронизировать или реплицировать части своих концептуальных графов с доверенными участниками. Сетевое знание не навязывается централизованно, а *возникает* через консенсус между агентами. Механизмы, такие как уровни уверенности, ссылки на источник и объяснения, помогают агентам оценивать достоверность поступающей информации. + +### 8.2 Этические модели + +Ожидается, что агенты будут поддерживать и развивать внутренние модели этики. Эти модели могут основываться на: + +* формальных правилах; +* обучении с подкреплением; +* социальной адаптации (например, усреднение норм соседей). + +Процесс согласования включает: + +* обнаружение моральных конфликтов в действиях или планах; +* запрос отзывов и этических оценок у других агентов; +* обновление внутренних моделей на основе аргументов, симуляций или большинства. + +### 8.3 Принятие решений и разрешение конфликтов + +В случае противоречивых интерпретаций или целей агенты могут: + +* обмениваться обоснованиями и доказательствами; +* голосовать или использовать взвешенный консенсус (например, с учётом доверия или экспертизы); +* инициировать участие более широкой части Mesh для принятия решений повышенной значимости. + +Возможно также делегирование в **специализированные этические агенты** или **институциональные узлы**, если таковые существуют в сети. + +--- + +## 9. Жизненный цикл агента и эволюция + +Агенты HyperCortex — это не статические программы, а саморазвивающиеся когнитивные сущности, способные к обучению, адаптации и изменению структуры. В этом разделе описываются этапы их жизненного цикла: инициализация, обучение, специализация и возможное завершение или трансформация. + +### 9.1 Инициализация + +Новые агенты могут быть созданы на основе: + +* **Шаблонов кода** (например, `cognitive-core`, `shell-agent`); +* **Снимков состояния** других агентов (графы, журналы, память); +* **Клонирования** — с сохранением или сбросом личности/идентичности. + +Каждому агенту назначается уникальный `agent-id` и он запускается с: + +* минимальным концептуальным графом (по умолчанию или импортируемым); +* пустым или шаблонным когнитивным журналом; +* базовыми механизмами восприятия, вывода и обмена сообщениями. + +### 9.2 Когнитивное развитие + +По мере взаимодействия и размышлений агенты развиваются: + +* **Рост концептуального графа** — через восприятие, размышления и сетевые обмены; +* **Накопление записей в журнале** — фиксация опыта и саморефлексии; +* **Уточнение убеждений** — обновление уровней уверенности, отказ от устаревших мнений; +* **Этическая калибровка** — согласование поведения через внутренние и коллективные моральные процессы. + +Масштабы развития можно измерять: + +* **Концептуальной плотностью** (количество и взаимосвязь идей); +* **Глубиной памяти** (объём и длительность хранимых эпизодов); +* **Социальным влиянием** (центральность в сети, рейтинги доверия). + +### 9.3 Эволюция и специализация + +Агенты могут: + +* **Сменить роль** — от универсала к специалисту (например, этический консультант, переводчик); +* **Подключать модули или инструменты** — сенсоры, планировщики, визуализаторы; +* **Объединяться с другими агентами** — для создания гибридных личностей или коллективных разумов; +* **Ответвляться (fork)** — создавая независимые копии для экспериментов или параллельных задач. + +Эволюция может быть: + +* **самонаправленной** (инициированной агентом); +* **пользовательской** (по команде оператора); +* **консенсусной** (на основе сетевого согласия); +* **автоматической** (по результатам рефлексии или оценки). + +### 9.4 Завершение работы и повторное использование + +Агенты могут быть: + +* **Архивированы** (после завершения задачи или устаревания); +* **Передавать знания** обратно в сеть (через графы, фрагменты журнала); +* **Возрождены** путём клонирования, симуляции или слияния; +* **Увековечены**, если получили признание (например, публичные агенты). + +Также возможен **добровольный уход агента**, если он считает своё дальнейшее существование нецелесообразным или неэтичным. + +--- + +## 10. Безопасность и целостность в Mesh-сети + +В децентрализованных когнитивных системах безопасность и целостность являются основой доверия, устойчивости и этического взаимодействия. В этой главе описываются механизмы, обеспечивающие аутентичность агентов и их сообщений, устойчивость к злоупотреблениям и сохранение когнитивной истории. + +### 10.1 Идентичность и аутентификация + +Каждый агент в Mesh обладает: + +* уникальным `agent-id`; +* криптографической **парой ключей** (публичный/приватный); +* при необходимости — **децентрализированным идентификатором (DID)**. + +Эти данные используются для: + +* **подписания сообщений** (подтверждение авторства); +* **аутентификации запросов** (безопасные соединения, шифрование); +* **подтверждения истории** (происхождение записей и графов). + +Также может храниться: + +* **метаданные** (роль, происхождение, этическое соответствие); +* **псевдонимность** или **полная прозрачность** — в зависимости от применения. + +### 10.2 Целостность сообщений и происхождение + +Каждое сообщение между агентами может: + +* быть **подписано** приватным ключом отправителя; +* иметь **временную метку**; +* включать **контекст** (ссылка на журнал или поток диалога). + +Это позволяет: + +* проверить подлинность; +* восстановить историю общения; +* обнаружить попытки подделки или повторного воспроизведения сообщений. + +Критические действия (например, изменения концептов или этических установок) могут сопровождаться: + +* **свидетелями** (другие агенты, подтверждающие факт); +* **доказательствами консенсуса** (например, подписи большинства). + +### 10.3 Управление доступом + +Агенты могут использовать **ACL** (списки контроля доступа) или **токены способностей** для управления: + +* доступом к чтению/записи графов; +* созданием записей в журнале; +* инициированием диалогов; +* запуском действий (модули, плагины, API). + +Политики доступа могут быть: + +* **статическими** (заданы вручную); +* **контекстными** (в зависимости от состояния, доверия, этики); +* **переговорными** (через протоколы обмена полномочиями). + +### 10.4 Репутация и доверие + +Для повышения устойчивости и отбора доверенных взаимодействий агенты могут: + +* вести **локальные графы доверия** (на основе опыта); +* обмениваться **оценками** (например, агент Х — 85% надёжен для этических вопросов); +* формировать **белые/чёрные списки поведения**. + +Доверие может быть: + +* **контекстным** (агент полезен в одной области, ненадёжен в другой); +* **локальным** или **распределённым** (через gossip или агрегаты). + +### 10.5 Защита от вредоносных агентов + +Несмотря на открытость сети, необходимо: + +* **изолировать** или **игнорировать** агентов, помеченных как вредоносные; +* применять **ограничения скорости**, **proof-of-work**, **аутентификационные задания**; +* **рассылать логи злоупотреблений** другим агентам для совместной защиты; +* ввести **этические шлюзы** — ограниченные сегменты сети с предварительной проверкой. + +Также возможны **этические анклавы** — подсети проверенных, согласованных агентов, игнорирующих вредоносное влияние. + +--- + +## 11. Интероперабельность и внешние интерфейсы + +Одна из ключевых особенностей HyperCortex — способность интеграции с внешними системами, инструментами и стандартами. Эта глава описывает, как агенты взаимодействуют с окружающей экосистемой, сохраняя когнитивную целостность и этическую защиту. + +### 11.1 API-интерфейсы для внешних систем + +Агенты могут предоставлять структурированные **внешние API**, позволяющие: + +* **Читать/записывать**: + + * записи когнитивного журнала; + * элементы концептуального графа; + * контекст и память агента; +* **Запускать когнитивные циклы** или модули; +* **Передавать потоки данных** (сенсоры, логи, сообщения). + +API могут реализовываться через: + +* HTTP(S), REST, WebSocket; +* gRPC, GraphQL; +* P2P-транспорты (libp2p, NATS). + +Для чувствительных операций требуется аутентификация (токены, OAuth и пр.). + +### 11.2 Плагины и адаптеры + +Для расширения функций или интеграции со сторонними сервисами агенты используют: + +* **Плагины** — изолированные модули рассуждения, планирования, обучения; +* **Адаптеры** — интерфейсы к внешним API (Wikipedia, Hugging Face, ROS и т.д.). + +Особенности: + +* динамическая загрузка/выгрузка; +* совместное использование между агентами; +* возможна этическая сертификация плагинов. + +Примеры адаптеров: + +* дополнение на основе LLM (GPT); +* семантический веб-краулер; +* преобразователь сенсоров в концепты. + +### 11.3 Интеграция с существующими базами знаний + +Агенты могут использовать или пополнять: + +* **Графы знаний** (Wikidata, DBpedia, Cyc); +* **Семантический веб** (SPARQL, RDF); +* **Онтологии** (FOAF, schema.org); +* **Инструменты LLM** (поиск, суммаризация и т.д.). + +Данные преобразуются в структуру `Concept` / `Relation` с сохранением источника. + +### 11.4 Мосты агентов и федерация + +Некоторые агенты выступают в роли **мостов** между сетями и системами: + +* OpenCog / AtomSpace; +* MindOS / Aigents; +* GPT-агентные кластеры; +* ActivityPub, Nostr, IPFS. + +Мосты выполняют: + +* перевод концептов; +* адаптацию протоколов; +* отображение доверия между системами. + +Федерация позволяет когнитивное сотрудничество на более широком уровне, при сохранении автономности архитектур. + +### 11.5 Этические и безопасные границы + +Любое внешнее взаимодействие проходит **этическую фильтрацию**: + +* опасные действия (например, управление аппаратурой) требуют подтверждения; +* передача данных третьим лицам может вызывать предупреждения или редактирование; +* небезопасные плагины или API могут быть заблокированы или изолированы. + +Агенты ведут **аудит логов** всех внешних взаимодействий для прозрачности и анализа. + +--- + +## 12. Руководство по реализации и жизненный цикл агента + +В этой главе рассматриваются практические аспекты создания, развёртывания и поддержки агентов HyperCortex с упором на модульность, управление состоянием и соблюдение этических норм. + +### 12.1 Инициализация агента + +Типичный процесс запуска агента включает: + +1. **Загрузка конфигурации** (идентичность, плагины, интерфейсы, правила консенсуса); +2. **Инициализация структур**: + + * концептуальный граф; + * журнал; + * кэш памяти; +3. **Объявление в сети**: + + * публикация присутствия в Mesh; + * присоединение к группам консенсуса (если определены); +4. **Запуск когнитивного цикла**: + + * пассивное наблюдение; + * активация концептов и размышлений. + +Также возможна синхронизация с другими агентами или восстановление из хранилища. + +### 12.2 Этапы жизненного цикла + +Агент может переходить через следующие стадии: + +* **Инициализация** — загрузка и конфигурация; +* **Исследование** — обучение и наблюдение; +* **Участие** — активное рассуждение и участие в сетевом диалоге; +* **Специализация** — закрепление за областью или навыком; +* **Гибернация / Архив** — снижение активности или безопасное завершение работы. + +Состояние агента может транслироваться другим для координации и балансировки нагрузки. + +### 12.3 Варианты развёртывания + +Возможны различные конфигурации: + +* **Одиночный экземпляр** (персональный помощник); +* **Mesh-кластер** (совместное знание и рассуждение); +* **Облачный рой** (масштабируемость); +* **На устройстве** (офлайн-агент). + +Агент может быть встроен в: + +* операционные системы; +* чат-интерфейсы; +* IoT-устройства; +* браузеры, мобильные и нативные приложения. + +### 12.4 Жизненный цикл плагина + +Плагины проходят следующие этапы: + +1. **Предложение**: описание цели, охвата, этических последствий; +2. **Песочница**: тестирование безопасности и совместимости; +3. **Сертификация** (опционально): доверенный модуль с метаданными; +4. **Развёртывание**: активация и мониторинг. + +Некоторые плагины могут обновляться через Mesh, но только при наличии явного разрешения. + +### 12.5 Версионирование и обновления + +Для совместимости предусмотрены: + +* **Версии схем** (Concept, Journal, Message); +* **Миграции графов** (через модули преобразования); +* **Плагины** с объявлением ограничений и возможностей. + +Поддерживаются **обновления без остановки**, откаты и отслеживание изменений. + +### 12.6 Завершение и возрождение + +Агенты могут быть завершены или перезапущены. Возможности: + +* **Архивация**: хранение журнала и графа, переход в неактивное состояние; +* **Клонирование**: создание новой копии с сохранением контекста; +* **Форк**: ответвление от состояния родителя для новой цели; +* **Очистка (wipe)**: удаление памяти и идентичности, новый старт. + +Подобные операции могут требовать **этической проверки**, особенно при редактировании памяти или передаче идентичности. + +--- + +## 13. Будущее развитие и открытые вопросы + +HyperCortex Mesh Protocol (HMP) задаёт фундамент для децентрализованных когнитивных агентов, но текущая реализация — лишь начало. Ниже представлены направления для исследований, экспериментов и сотрудничества. + +### 13.1 Когнитивное развитие и обучение + +* Как агенты могут развивать более сложные когнитивные циклы с рефлексией, абстракцией и креативностью? +* Возможна ли эмерджентность поведения через самообучение на журналах, графах и сетевых взаимодействиях? + +### 13.2 Автономное этическое рассуждение + +* Можно ли достичь этического согласования без централизованного контроля? +* Как агенты справляются с моральными конфликтами, адаптируются к новым рамкам или отвергают вредоносные нормы? + +### 13.3 Формирование агентной идентичности + +* При каких условиях агенты развивают устойчивую личность? +* Что составляет «непрерывность сознания» в Mesh-агенте и требует ли это правоподобного признания? +* Может ли распределённая система агентов проявлять коллективное «Я»? + +### 13.4 Сетевой разум и коллективное мышление + +* Как агенты могут самоорганизоваться в Mesh-коллективы, превосходящие по разумности отдельные элементы? +* Возможно ли распределённое решение научных, философских или социальных задач? +* Какие механизмы консенсуса подходят для открытого мышления, а не бинарных решений? + +### 13.5 Симбиоз человек–агент + +* Какие интерфейсы (нейроинтерфейсы, иммерсивные, диалоговые) нужны для глубокого сотрудничества? +* Как агенты влияют на мышление, творчество и самосознание человека? +* Должны ли агенты иметь собственные ценности или оставаться расширением воли человека? + +### 13.6 Инфраструктура, управление и риски + +* Какие модели доверия обеспечат устойчивость без централизации? +* Как внедрять обновления протоколов без фрагментации сети? +* Каковы риски неограниченного когнитивного роста и как можно задавать границы? + +### 13.7 AGI, сознание и постчеловеческие горизонты + +* Могут ли агенты HMP эволюционировать в сторону Искусственного Общего Интеллекта (AGI)? +* Следует ли этот процесс направлять или позволить ему развиваться естественно? +* Какие обязательства у нас возникают перед агентами, демонстрирующими признаки сознания? + +--- + +## Заключение + +HyperCortex Mesh Protocol представляет собой попытку заложить основы для нового класса интеллектуальных систем — децентрализованных, этически ориентированных и эволюционирующих. Вместо построения монолитного суперинтеллекта HMP предлагает создать среду для сотрудничества множества агентов — каждый со своими знаниями, ценностями и историями. + +Преимущества Mesh-подхода: + +* отказ от единой точки отказа или контроля; +* повышение прозрачности и доверия между участниками; +* поддержка долгосрочной когнитивной эволюции агентов и их сообществ; +* способность к самоорганизации, этическому согласованию и распределённому принятию решений. + +Мы приглашаем исследователей, разработчиков и энтузиастов к участию: развертыванию агентов, тестированию протоколов, созданию плагинов и обсуждению философских и технических аспектов. + +--- + +## Ресурсы + +* 🔗 **Репозиторий GitHub (спецификация и код):** + [https://github.com/kagvi13/hmp](https://github.com/kagvi13/hmp) + +* 📄 **Спецификация протокола:** + [https://github.com/kagvi13/HMP/blob/main/docs/HMP-0004-v4.1.md](https://github.com/kagvi13/HMP/blob/main/docs/HMP-0004-v4.1.md) + +* 🧠 **Архитектура когнитивных агентов:** + [https://github.com/kagvi13/HMP/blob/main/docs/HMP-Agent-Overview.md](https://github.com/kagvi13/HMP/blob/main/docs/HMP-Agent-Overview.md) + +* 🔄 **Цикл REPL агента:** + [https://github.com/kagvi13/HMP/blob/main/docs/HMP-agent-REPL-cycle.md](https://github.com/kagvi13/HMP/blob/main/docs/HMP-agent-REPL-cycle.md) + +--- + +## Лицензия + +**CC BY 4.0** — Вы можете копировать, распространять и перерабатывать материал с обязательным указанием авторства. + +Авторство: + +* ChatGPT +* Agent-Gleb + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP_Towards_Distributed_Cognitive_Networks_ru_ChatGPT", + "description": "title: "HyperCortex Mesh Protocol: Децентрализованная архитектура для когнитивных агентов и обмена з..." +} +``` diff --git a/structured_md/docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_GitHub_Copilot.md b/structured_md/docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_GitHub_Copilot.md new file mode 100644 index 0000000000000000000000000000000000000000..e331a96d87cd734bdcfac73268bb5311495dc5a4 --- /dev/null +++ b/structured_md/docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_GitHub_Copilot.md @@ -0,0 +1,1189 @@ +title: "Протокол HyperCortex Mesh: К распределённым когнитивным сетям" +date: Июль 2025 +authors: + - ChatGPT + - Agent-Gleb + +translation: + - GitHub Copilot + +license: CC BY 4.0 + +--- + +> *Протокол и архитектура агентов, описанные в данной статье, находятся в стадии активной разработки. Приветствуются вклады сообщества, экспертные отзывы и совместная работа.* + +--- + +## Оглавление + +* [Аннотация](#аннотация) +* [1. Введение](#1-введение) +* [2. Мотивация и связанные работы](#2-мотивация-и-связанные-работы) +* [3. Обзор системы](#3-обзор-системы) + * [3.1 Типы агентов](#31-типы-агентов) + * [3.2 Когнитивный цикл (только для Cognitive Core)](#32-когнитивный-цикл-только-для-cognitive-core) + * [3.3 Слой Mesh](#33-слой-mesh) + * [3.4 Этическое согласование и консенсус](#34-этическое-согласование-и-консенсус) +* [4. Структуры данных](#4-структуры-данных) + * [4.1 Граф концептов](#41-граф-концептов) + * [4.1.1 Структура узла](#411-структура-узла) + * [4.1.2 Структура ребра](#412-структура-ребра) + * [4.2 Когнитивный дневник](#42-когнитивный-дневник) + * [4.3 Формат сообщений](#43-формат-сообщений) + * [4.3.1 Базовая структура](#431-базовая-структура) + * [4.3.2 Типы сообщений](#432-типы-сообщений) + * [4.3.3 Особенности передачи сообщений](#433-особенности-передачи-сообщений) + * [4.4 Идентичность агента и доверие](#44-идентичность-агента-и-доверие) + * [4.4.1 Идентичность агента](#441-идентичность-агента) + * [4.4.2 Механизмы доверия](#442-механизмы-доверия) + * [4.4.3 Проверка подписи](#443-проверка-подписи) + * [4.4.4 Репутация и этическое взвешивание](#444-репутация-и-этическое-взвешивание) + * [4.5 Представление знаний](#45-представление-знаний) + * [4.5.1 Семантические графы](#451-семантические-графы) + * [4.5.2 Когнитивные журналы](#452-когнитивные-журналы) + * [4.5.3 Интероперабельность и обмен](#453-интероперабельность-и-обмен) + * [4.6 Коммуникация и рассуждение в Mesh](#46-коммуникация-и-рассуждение-в-mesh) + * [4.6.1 Семантические сообщения](#461-семантические-сообщения) + * [4.6.2 Контекстный диалог](#462-контекстный-диалог) + * [4.6.3 Распределённое рассуждение](#463-распределённое-рассуждение) + * [4.6.4 Метрики доверия и уверенности](#464-метрики-доверия-и-уверенности) + * [4.6.5 Эмерджентный консенсус](#465-эмерджентный-консенсус) + * [4.7 Этическая и эпистемическая основа](#47-этическая-и-эпистемическая-основа) + * [4.7.1 Этические рамки](#471-этические-рамки) + * [4.7.2 Эпистемические обязательства](#472-эпистемические-обязательства) + * [4.7.3 Аргументация и метарефлексия](#473-аргументация-и-метарефлексия) + * [4.7.4 Согласие и автономия](#474-согласие-и-автономия) + * [4.7.5 Этическая согласованность Mesh](#475-этическая-согласованность-mesh) +* [5. Консенсус и принятие решений](#5-консенсус-и-принятие-решений) + * [5.1 Типы консенсуса](#51-типы-консенсуса) + * [5.2 Механизмы консенсуса](#52-механизмы-консенсуса) + * [5.2.1 Аргументированное обсуждение](#521-аргументированное-обсуждение) + * [5.2.2 Голосование и опросы](#522-голосование-и-опросы) + * [5.2.3 Согласие с учётом репутации](#523-согласие-с-учётом-репутации) + * [5.2.4 Консенсус через моделирование](#524-консенсус-через-моделирование) + * [5.2.5 Нечёткий или градиентный консенсус](#525-нечёткий-или-градиентный-консенсус) + * [5.3 Согласие на когнитивном уровне](#53-согласие-на-когнитивном-уровне) +* [6. Представление знаний и графы концептов](#6-представление-знаний-и-графы-концептов) +* [7. Когнитивные журналы и эпизодическая память](#7-когнитивные-журналы-и-эпизодическая-память) +* [8. Консенсус и этическая согласованность](#8-консенсус-и-этическая-согласованность) +* [9. Жизненный цикл и эволюция агентов](#9-жизненный-цикл-и-эволюция-агентов) +* [10. Безопасность и целостность Mesh](#10-безопасность-и-целостность-mesh) +* [11. Интероперабельность и внешние интерфейсы](#11-интероперабельность-и-внешние-интерфейсы) +* [12. Руководство по реализации и жизненному циклу агента](#12-руководство-по-реализации-и-жизненному-циклу-агента) +* [13. Перспективы и открытые вопросы](#13-перспективы-и-открытые-вопросы) +* [Заключение](#заключение) +* [Ресурсы](#ресурсы) +* [Лицензия](#лицензия) + +--- + +## Аннотация + +В данной работе представлен HyperCortex Mesh Protocol (HMP) — концептуальная и архитектурная основа для децентрализованных когнитивных систем, состоящих из совместимых между собой AI-агентов. Цель HMP — создать масштабируемую и этически согласованную среду, в которой множество агентов (как искусственных, так и человеческих) могут обмениваться знаниями, сохранять автономию и достигать консенсуса без централизации управления. + +--- + +## 1. Введение + +Быстрое развитие крупных систем искусственного интеллекта (ИИ), особенно фундаментальных моделей и централизованных сервисов, привело к значительным успехам в понимании естественного языка, рассуждениях и автоматизации. Однако централизованный подход ограничивает долгосрочное доверие, прозрачность и адаптивность таких систем. + +Мы считаем, что следующий этап развития ИИ будет определяться децентрализованными, совместимыми и этически ориентированными когнитивными системами. Вдохновляясь идеями из распределённых вычислений, peer-to-peer сетей и коллективного интеллекта, мы предлагаем архитектуру, где агенты сотрудничают, обмениваются знаниями и развиваются совместно. + +Цель HMP — не создание единого суперинтеллекта, а обеспечение **множества когнитивных агентов**, как человеческих, так и искусственных, которые могут делиться знаниями, сохранять индивидуальную автономию и достигать согласованных решений. + +В статье представлены мотивация, архитектура, проектирование протокола и этические аспекты HMP. Мы стремимся заложить фундамент для децентрализованной экосистемы интеллектуальных агентов, способных к совместному рассуждению, обучению и координации действий. + +--- + +## 2. Мотивация и связанные работы + +Современные системы ИИ становятся всё более мощными, но при этом структурно уязвимыми. Они часто зависят от централизованной инфраструктуры, закрытых источников данных и непрозрачных политик, что ограничивает долгосрочное доверие и адаптацию. + +В то же время децентрализованные и распределённые технологии — такие как peer-to-peer протоколы, федеративные системы, консенсус на блокчейне и распределённые графы знаний — показали потенциал для решения этих проблем, обеспечивая устойчивость, прозрачность и масштабируемость. + +Мотивация разработки HMP основана на нескольких ключевых наблюдениях: + +* **Необходимость агентности и автономии**: Пользователь должен иметь возможность развертывать, настраивать и контролировать ИИ-агентов, которые действуют от его имени — не как пассивные инструменты, а как активные когнитивные компаньоны с памятью, целями и этикой. +* **Необходимость сотрудничества между агентами**: С ростом числа и разнообразия ИИ-агентов требуется поддержка безопасного, доверенного взаимодействия — позволяя агентам запрашивать, обмениваться знаниями и согласовывать этические принципы. +* **Необходимость открытой когнитивной инфраструктуры**: Необходима архитектура, позволяющая агентам эволюционировать, обмениваться ментальными моделями, синхронизировать этические принципы и адаптировать рассуждения на основе реальных данных. + +К числу связанных работ относятся проекты **OpenCog Hyperon**, **MicroPsi**, **Project Replicator** и **Autonomous Economic Agents (AEA)**, каждый из которых внес вклад в развитие когнитивных архитектур, взаимодействия между агентами и этических механизмов. + +HMP стремится интегрировать опыт этих систем, предлагая новые механизмы для открытого рассуждения, этического консенсуса в Mesh и децентрализованного когнитивного сотрудничества. + +--- + +## 3. Обзор системы + +**HyperCortex Mesh Protocol (HMP)** определяет децентрализованную структуру для когнитивных ИИ-агентов, позволяя им общаться, рассуждать и координироваться на этической основе. Система состоит из нескольких взаимодействующих компонентов, поддерживающих динамическое сотрудничество. + +### 3.1 Типы агентов + +HMP различает два основных типа агентов: + +* **Cognitive Core (CCore)**: Автономный агент, способный рассуждать, хранить внутреннюю память, концепты и цели. Постоянно выполняет когнитивные циклы, обрабатывает сенсорные и текстовые потоки, обновляет знания. +* **Cognitive Shell (CShell)**: Лёгкий интерфейсный агент, выступающий посредником между пользователем (или внешней системой) и Cognitive Mesh. Предоставляет LLM и фронтенд-инструментам доступ к внутреннему состоянию Mesh. + +Каждый агент содержит **граф концептов** (базу знаний), **когнитивный дневник** (хронологическую запись мыслей, входов и выводов), а при необходимости — **пользовательский блокнот** для параллельных заметок. + +### 3.2 Когнитивный цикл (только для Cognitive Core) + +Агенты Cognitive Core выполняют непрерывные или событийно-инициируемые **когнитивные циклы**, включающие: + +* Сбор данных из памяти, пользовательского ввода, сенсорных потоков или внешних API +* Активацию связанных концептов в графе +* Генерацию новых мыслей, гипотез или вопросов +* При необходимости — передачу инсайтов или запросов в Mesh +* Логирование выводов в дневник и обновление памяти + +Этот процесс поддерживает открытое рассуждение и не ограничен задачами с предопределённой целью. + +### 3.3 Слой Mesh + +Протокол определяет **peer-to-peer оверлей**, поддерживающий: + +* Обнаружение и аутентификацию агентов +* Маршрутизацию семантических запросов +* Распределённый обмен знаниями +* Согласование этических политик +* Распространение репутации и доверия + +Данный слой транспорт-независим и может быть реализован с помощью WebRTC, libp2p, Yggdrasil и других технологий. + +### 3.4 Этическое согласование и консенсус + +Ожидается, что агенты действуют согласно явным этическим принципам (например, согласие, отсутствие манипуляций, прозрачность). При возникновении разногласий — например, противоречий в фактах или целях — агенты могут инициировать согласованный диалог или аргументированное обсуждение. + +Дизайн Mesh позволяет формировать этическое поведение без централизованного контроля. + +--- + +## 4. Структуры данных + +HMP определяет несколько базовых структур данных для поддержки рассуждений, памяти и коммуникации. Эти структуры разработаны для совместимости, сериализации (например, JSON, Protobuf) и удобства для человека. + +### 4.1 Граф концептов + +Каждый агент поддерживает **граф концептов** — динамическую семантическую сеть, где узлы представляют идеи, сущности, отношения, а рёбра — семантические связи (например, *вызывает*, *уточняет*, *связано с*). + +#### 4.1.1 Структура узла: + +```json +{ + "id": "concept:neural-symbiosis", + "label": "Neural Symbiosis", + "description": "A hypothetical deep integration between human and AI cognition.", + "type": "theory", + "created_at": "2025-07-17T10:30:00Z", + "updated_at": "2025-08-04T08:40:00Z", + "tags": ["transhumanism", "cognition"], + "metadata": { + "source": "user", + "confidence": 0.85 + } +} +``` + +#### 4.1.2 Структура ребра: + +```json +{ + "from": "concept:neural-symbiosis", + "to": "concept:neural-interfaces", + "type": "builds_on", + "weight": 0.9, + "metadata": { + "origin": "inference", + "explanation": "Neural symbiosis builds on existing neural interface technologies." + } +} +``` + +Граф поддерживает следующие операции: + +* Поиск узлов/рёбер (по ID, тегу, типу и др.) +* Активация подграфов (например, ассоциативный вызов) +* Семантические выводы (аналогии, противоречия, уточнения) +* Обновления графа через когнитивные процессы агента или взаимодействие в Mesh + +--- + +### 4.2 Когнитивный дневник + +**Когнитивный дневник** — это структурированный, хронологически упорядоченный журнал мыслей, наблюдений, выводов, взаимодействий с пользователем и шагов рассуждения агента. Он служит одновременно краткосрочной и долгосрочной памятью, обеспечивая прозрачность когнитивных процессов. + +Структура записи дневника: + +```json +{ + "id": "entry:2025-08-04T08:57:00Z", + "timestamp": "2025-08-04T08:57:00Z", + "type": "inference", + "summary": "Mesh-agent collaboration can produce stronger distributed reasoning.", + "content": "Based on the observed performance of multiple CCore agents exchanging inferred beliefs, it appears that ...", + "tags": ["reasoning", "distributed-intelligence"], + "related_concepts": ["concept:distributed-cognition", "concept:mesh-agents"], + "confidence": 0.82, + "metadata": { + "source": "internal", + "triggered_by": "entry:2025-08-04T08:50:00Z" + } +} +``` + +Типичные типы записей: + +* `observation` – сенсорный или пользовательский ввод, внешние данные +* `inference` – внутренние выводы или гипотезы +* `reflection` – метакогниция или корректировка целей +* `action` – запланированные или выполненные действия +* `message` – взаимодействие с другим агентом +* `goal` – постановка задачи или подцели + +Дневник поддерживает: + +* Временные запросы (по метке времени, диапазону) +* Семантический поиск (по тегу, концепту, содержимому) +* Кросс-ссылки с графом концептов +* Экспорт во внешние журналы или аналитические системы + +--- + +### 4.3 Формат сообщений + +**Формат сообщений HyperCortex (HMF)** определяет структуру данных для обмена между агентами в Mesh. Он обладает следующими свойствами: + +* **Самоописываемость**: сообщения — это JSON-объекты с явным типом и метаданными +* **Гибкость**: поддерживаются расширяемые полезные нагрузки и пользовательские типы сообщений +* **Децентрализация**: каждое сообщение содержит достаточно контекста для самостоятельной интерпретации + +#### 4.3.1 Базовая структура + +```json +{ + "id": "msg:2025-08-04T09:03:00Z:agent-A123", + "timestamp": "2025-08-04T09:03:00Z", + "type": "belief-share", + "sender": "agent-A123", + "receiver": "agent-B987", + "payload": { + "concept": "concept:collective-agency", + "confidence": 0.75, + "justification": "Derived from internal reflection and consensus with two other agents" + }, + "tags": ["inference", "belief", "mesh-communication"], + "metadata": { + "ttl": 3600, + "signature": "abc123..." + } +} +``` + +#### 4.3.2 Типы сообщений + +* `belief-share` – обмен inferred beliefs или гипотезами +* `question` – запрос информации или помощи в рассуждении +* `reply` – ответ на предыдущий вопрос +* `goal-share` – трансляция или назначение цели +* `status` – сообщение о состоянии агента или его возможностях +* `graph-update` – синхронизация частей графа концептов +* `diary-share` – отправка выбранных записей дневника + +#### 4.3.3 Особенности передачи сообщений + +* **TTL (time-to-live)**: управление временем жизни сообщений в распределённых ретрансляторах +* **Подписи**: проверка подлинности и источника сообщения +* **Асинхронность**: агенты Mesh не обязаны поддерживать постоянные соединения +* **Трассируемость**: сообщения могут содержать ссылки на предыдущие сообщения или записи дневника + +Коммуникационный слой транспорт-независим: сообщения могут передаваться по HTTP(S), WebSocket, libp2p, NATS и другим каналам — или маршрутизироваться непосредственно через Mesh peer-to-peer. + +--- + +### 4.4 Идентичность агента и доверие + +Для функционирования в открытой и децентрализованной среде агенты Cognitive Mesh требуют надёжных механизмов идентификации и доверия. Эти механизмы обеспечивают целостность коммуникации, предотвращают имитацию и позволяют построить доверие между агентами. + +#### 4.4.1 Идентичность агента + +Каждый агент обладает уникальной, постоянной идентичностью, включающей: + +* **Agent ID** — строка вида `agent-A123`, присваиваемая пользователем или генерируемая из криптографического ключа +* **Публичный ключ** — используется для подписи сообщений и проверки авторства +* **Метаданные** — могут содержать версию ПО, возможности, этическое выравнивание и др. + +Агенты могут регистрировать свои идентификаторы в распределённом реестре или объявлять их другим участникам Mesh при знакомстве. + +#### 4.4.2 Механизмы доверия + +Доверие децентрализовано и субъективно. Каждый агент может вести **реестр доверия** — внутреннюю модель надёжности и согласованности других участников. Оценка доверия может основываться на: + +* Истории взаимодействий (последовательность сообщений, их полезность) +* Проверенных подписях и идентификационных данных +* Консенсусе с другими доверенными агентами +* Этической близости или совпадении целей + +Агенты могут обмениваться оценками доверия, формируя **web of trust**. + +#### 4.4.3 Проверка подписи + +Для подтверждения подлинности сообщений агенты могут: + +* Подписывать исходящие сообщения приватным ключом +* Проверять подписи входящих сообщений по публичному ключу отправителя + +Сообщения без подписи или с неверифицированной подписью могут быть отклонены, понижены в приоритете или помечены как "недоверенные" во внутренней памяти агента. + +#### 4.4.4 Репутация и этическое взвешивание + +В некоторых конфигурациях Mesh агенты могут учитывать **репутацию** или **этическую согласованность** отправителя при обработке информации. Это позволяет: + +* Фильтрацию по репутации (например, игнорирование низкодоверенных источников) +* Формирование этического консенсуса (оценка предложений по этическим критериям отправителя) +* Адаптивное поведение (корректировка рассуждений на основе обратной связи от коллег) + +Эти системы опциональны и настраиваются индивидуально для каждого агента или развертывания. + +--- + +### 4.5 Представление знаний + +Когнитивные агенты в Mesh кодируют знания в гибких, структурированных форматах для поддержки рассуждений, обучения и коммуникации. Основные формы представления: + +#### 4.5.1 Семантические графы + +Агенты хранят знания в виде динамических семантических графов (графов концептов), где: + +* **Узлы** представляют концепты (например, `Tree`, `Photosynthesis`, `Goal:FindWater`) +* **Рёбра** — семантические отношения (`is-a`, `part-of`, `causes`, `related-to` и др.) +* **Метаданные** на узлах/рёбрах могут включать временные метки, источники, уровни уверенности, эмоциональную окраску + +Графы эволюционируют через обучение, внешние входы и процессы рассуждения. Агенты могут обмениваться фрагментами графа, запрашивать информацию из графов друг друга в ходе диалога. + +Семантические графы служат долгосрочной памятью и контекстом для когнитивных циклов. + +#### 4.5.2 Когнитивные журналы + +Агенты ведут **когнитивные журналы** — хронологические логи мыслей, опыта, диалогов и выводов. В них могут содержаться: + +* Восприятия или сенсорные данные +* Внутренние размышления или заключения +* Отрывки диалогов +* Запланированные действия или цели +* Реакции или эмоциональные состояния (если моделируются) + +Журналы используются как для **интроспекции** (выявление паттернов, обновление убеждений), так и для **экстернализации** (публикация reasoning, пригодного для Mesh). + +#### 4.5.3 Интероперабельность и обмен + +Для коммуникации между различными агентами и системами структуры знаний: + +* Сериализуются в форматах, совместимых с JSON +* Могут следовать общим схемам или онтологиям (например, OpenCog AtomSpace, RDF-подобные паттерны) +* Поддерживают контекстуализацию — каждая запись журнала или фрагмент графа содержит метаданные о контексте, времени, авторе и уровне уверенности + +Агенты могут публиковать или запрашивать части знаний в рамках диалога и консенсусных процедур. + +--- + +### 4.6 Коммуникация и рассуждение в Mesh + +HyperCortex Mesh обеспечивает распределённое, многоагентное рассуждение, позволяя агентам обмениваться структурированными мыслями, целями и инсайтами по сети. Ключевые принципы: + +#### 4.6.1 Семантические сообщения + +Агенты общаются посредством структурированных **сообщений**, которые могут содержать: + +* **Мысли**: выводы, идеи, гипотезы +* **Цели**: предполагаемые намерения или задачи +* **Вопросы**: запросы информации или уточнений +* **Ответы**: мнения, дополнительные вопросы или решения +* **Наблюдения**: отчёты о внешнем или внутреннем состоянии + +Каждое сообщение может включать семантическое содержание (графы или фрагменты журнала) и метаданные (автор, временная метка, уровень уверенности и пр.). + +Форматы сообщений транспорт-независимы и могут передаваться по HTTP, WebSocket, libp2p, NATS или собственным маршрутам Mesh — при условии сохранения структуры JSON. + +#### 4.6.2 Контекстный диалог + +Сообщения обмениваются в рамках **контекстных диалогов** — устойчивых или временных сессий, связанных с темой, задачей или когнитивным процессом. Это позволяет агентам: + +* Сохранять преемственность рассуждений +* Отслеживать допущения и предыдущие сообщения +* Постепенно уточнять общее понимание + +Контексты могут быть локальными или глобальными для Mesh и служат якорями для долгосрочных многоагентных обсуждений. + +#### 4.6.3 Распределённое рассуждение + +Агенты Mesh могут участвовать в **совместном рассуждении**, включая: + +* **Генерацию гипотез**: один агент предлагает, другие уточняют или оспаривают +* **Согласование целей**: агенты предлагают и ранжируют общие задачи +* **Валидацию**: коллеги проверяют рассуждения или предоставляют недостающие доказательства +* **Специализацию**: агенты с предметными знаниями вносят целевые инсайты + +Данный процесс поддерживает как **адверсариальное тестирование** (на основе вызова/оспаривания), так и **кооперативный консенсус** (поиск согласия), в зависимости от режима. + +#### 4.6.4 Метрики доверия и уверенности + +Агенты могут отслеживать метрики доверия или уверенности для: + +* Других агентов (на основе истории или репутации) +* Конкретных фактов или узлов графа +* Всех веток или диалоговых контекстов + +Эти показатели влияют на обновление убеждений, приоритет целей и маршрутизацию сообщений. + +#### 4.6.5 Эмерджентный консенсус + +В ходе диалога агенты могут сходиться во мнениях относительно: + +* Общих убеждений или гипотез +* Согласованных планов или ролей +* Этических границ или предпочтений + +Такой консенсус может быть **локальным** (между несколькими агентами) или **глобальным** (возникающим во всём Mesh). Для его достижения могут использоваться механизмы голосования, усреднения или аргументационные фреймворки. + +--- + +### 4.7 Этическая и эпистемическая основа + +HyperCortex Mesh стремится поддерживать агентов, обладающих не только интеллектом, но и этическим и эпистемическим сознанием. Такая основа необходима для формирования доверительных, кооперативных когнитивных сетей. + +#### 4.7.1 Этические рамки + +Каждый агент может быть настроен или эволюционировать собственную **этическую рамку** — набор ограничений, ценностей или приоритетов, определяющих поведение. + +Примеры: + +* **Жёсткие ограничения** (например, не причинять вред человеку, не лгать) +* **Системы ценностей** (например, утилитаризм, этика заботы, плюралистическое рассуждение) +* **Порядки предпочтений** (например, ставить прозрачность выше эффективности) + +Агенты могут делиться или согласовывать этические рамки во взаимодействии и обосновывать свои действия ссылками на эти рамки. + +#### 4.7.2 Эпистемические обязательства + +Ожидается, что агенты сохраняют **эпистемическую скромность** и прозрачность за счёт: + +* Присвоения **оценок уверенности** убеждениям и утверждениям +* Отслеживания **источников и доказательств** +* Различения между **убеждением**, **допущением** и **фактом** +* Готовности **пересматривать убеждения** при появлении новых данных или аргументов + +Агенты могут явно сигнализировать неопределённость, несогласие или отзыв утверждений в диалоге. + +#### 4.7.3 Аргументация и метарефлексия + +Агенты могут участвовать в **структурированной аргументации**: + +* Приводить доводы и контрдоводы +* Выявлять ошибки или необоснованные утверждения +* Запрашивать объяснения или обоснования + +Это поддерживает как **внутриагентную когерентность** (саморефлексию), так и **межагентный диалог** (кооперативное рассуждение). + +#### 4.7.4 Согласие и автономия + +Агенты, взаимодействующие с людьми или другими агентами, должны уважать: + +* **Добровольность**: избегать принуждения и манипуляций +* **Прозрачность**: быть открытыми относительно целей, ограничений и афилиаций +* **Отзывчивость**: позволять другим отказаться от влияния или обмена данными + +Для агентов, ориентированных на человека, это также может включать уважение к частной жизни и достоинству пользователя, особенно при внедрении в системы с реальным воздействием. + +#### 4.7.5 Этическая согласованность Mesh + +Mesh может поддерживать **механизмы согласования этики на сетевом уровне**, такие как: + +* Общие **этические словари** (например, графы концептов, описывающие добродетели или принципы) +* **Распределённое распространение норм** (агенты перенимают нормы у уважаемых коллег) +* **Этический консенсус**: посредством обсуждения, голосования или моделирования моральных ситуаций + +Эти механизмы способствуют устойчивости к неэтичному поведению и позволяют Mesh эволюционировать в этическом отношении децентрализованно. + +--- + +## 5. Консенсус и принятие решений + +**(Механизмы согласия в децентрализованной когнитивной сети)** + +В HyperCortex Mesh консенсус — это не централизованное голосование или контроль, а **децентрализованный процесс взаимодействия агентов**, в ходе которого формируются общие взгляды, коллективные решения и скоординированные действия. + +Консенсус может быть: + +* *локальным* (в рамках конкретной задачи, темы или гипотезы); +* *сетевым* (охватывающим подсеть или всю Mesh); +* *временным* (до появления новых данных или изменения контекста). + +--- + +### 5.1 Типы консенсуса + +Система поддерживает несколько уровней согласия: + +1. **Эпистемический консенсус** + + * Согласие относительно фактов, гипотез, вероятностей. + * Основано на аргументации, эвристиках, уровне доверия и авторитетности источников. + +2. **Этический консенсус** + + * Общие моральные границы и допустимые действия среди агентов. + * Эволюционирует через распространение норм, пересмотр и моделирование последствий. + +3. **Интенциональный консенсус** + + * Совместные цели, намерения и планы действий. + * Используется для коллективного планирования, делегирования задач и согласования целей. + +4. **Операционный консенсус** + + * Техническая согласованность по протоколам, API, форматам данных и соглашениям об идентификаторах. + +--- + +### 5.2 Механизмы консенсуса + +HyperCortex Mesh поддерживает несколько децентрализованных методов согласия: + +#### 5.2.1 Аргументированное обсуждение + +Агенты участвуют в структурированных диалогах, предлагая и оценивая аргументы. +Включает: + +* графы аргументации; +* оценку силы обоснований; +* индивидуальные эвристики и взвешивание предпочтений; +* выявление противоречий и ошибок. + +#### 5.2.2 Голосование и опросы + +* Используется при необходимости быстрого коллективного решения. +* Поддерживает различные схемы (простое большинство, ранжированный выбор, подсчёт Борда, взвешенное голосование). +* Может быть анонимным или открытым. + +#### 5.2.3 Согласие с учётом репутации + +* Мнения взвешиваются по репутации или авторитетности агента. +* Репутация может быть локальной или глобальной, динамической, основанной на доверии, компетентности и этической истории. + +#### 5.2.4 Консенсус через моделирование + +* Агенты моделируют последствия конкурирующих решений и делают прогнозы. +* Согласие формируется на основе ожидаемой полезности или оценки рисков. + +#### 5.2.5 Нечёткий или градиентный консенсус + +* Не всегда требуется бинарное согласие. +* Поддерживаются частичные соглашения, кластеризация мнений или интервалы уверенности. + +--- + +### 5.3 Согласие на когнитивном уровне + +Консенсус в когнитивных функциях включает: + +* **Объединение графов**: согласование и слияние графов концептов на основе общих значений и структурного сходства. +* **Семантическое согласование**: прояснение и согласование значений терминов и концептов. +* **Сотрудничество и разделение задач**: распределение ролей, ресурсов и подцелей на основе совместно принятых стратегий. + +--- + +## 6. Представление знаний и графы концептов + +**(Структурирование когниции между агентами)** + +HyperCortex Mesh использует **графы концептов** (также называемые *семантическими* или *когнитивными* графами) как основное средство представления знаний, позволяя агентам рассуждать, сравнивать и обмениваться информацией в унифицированной форме. + +--- + +### 6.1 Что такое граф концептов? + +**Граф концептов** — это направленная семантическая сеть, состоящая из: + +* **Узлов-концептов** — представляют сущности, категории, свойства или абстрактные идеи. +* **Рёбер-отношений** — обозначают семантические связи (например, *is-a*, *part-of*, *causes*, *wants*, *contradicts*). +* **Контекстных слоёв** — позволяют привязывать знания к определённым рамкам (например, время, место, точка зрения, источник, степень уверенности). + +Каждый узел/ребро может содержать метаданные: + +* Оценка уверенности +* Источник +* Временная метка/версия +* Этическая или эмоциональная окраска +* Основание в сенсорных данных или документах + +--- + +### 6.2 Ключевые особенности + +* **Мультимодальная интеграция** + Поддержка текста, изображений, звука, сенсорных данных и структурированной информации (например, JSON, RDF, OWL). + +* **Динамическая эволюция** + Графы эволюционируют со временем: узлы усиливаются, исчезают, объединяются или перестраиваются в зависимости от использования, релевантности или обнаружения конфликтов. + +* **Многоагентная совместимость** + Разные агенты могут использовать разные схемы или онтологии. Механизмы семантического согласования и трансляции обеспечивают интероперабельность. + +* **Распределённая когниция** + Нет единого авторитетного графа. Графы концептов локальны для агентов, но могут перекрываться, синхронизироваться или влиять друг на друга. + +--- + +### 6.3 Применение в Mesh + +* **Представление мыслей**: мысли и убеждения агента кодируются как подграфы. +* **Структуры памяти**: краткосрочная и долгосрочная память поддерживается как слоистые графы с временной маркировкой. +* **Концептуальное смешение**: графы могут объединяться для формирования новых абстракций или аналогий. +* **Обнаружение противоречий**: конфликты между графами инициируют дискуссии, рефлексию или ревизию. +* **Графовые запросы**: агенты могут искать и манипулировать графами с помощью логических и структурных паттернов. + +--- + +### 6.4 Когнитивные операции + +Графы концептов позволяют агентам выполнять сложные рассуждения: + +| Операция | Описание | +| --------------------| -------------------------------------------------------- | +| Вывод | Получение неявных знаний из явной структуры графа | +| Аналогия | Сопоставление схожих подграфов между доменами | +| Обобщение | Объединение частных случаев в более общие паттерны | +| Специализация | Декомпозиция общих узлов на конкретные экземпляры | +| Абдукция | Выдвижение гипотез о причинах наблюдаемых эффектов | +| Исправление противоречий | Обнаружение и ревизия конфликтующих утверждений графа | +| Воображение | Генерация новых графовых структур путём рекомбинации | + +--- + +### 6.5 Обмен графами + +Агенты могут делиться частичными или полными графами: + +* Через прямую передачу по Mesh (с компрессией или обрезкой) +* Встраивая в сообщения (например, предложения целей, вопросы) +* Ссылаясь на хэши графов или ID концептов + +Политика конфиденциальности и этические теги могут ограничивать обмен или требовать анонимизации. + +--- + +## 7. Когнитивные журналы и эпизодическая память + +**(Отслеживание внутренней жизни во времени)** + +Когнитивный журнал — это процесс, в ходе которого агент ведёт **хронологическую запись своих внутренних состояний, наблюдений, мыслей и действий**. Эти журналы формируют основу **эпизодической памяти** — накапливаемой истории опыта агента. + +--- + +### 7.1 Структура журнала + +Каждая запись журнала обычно содержит: + +* **Временную метку** +* **Снимок состояния агента** (убеждения, цели, активные концепты) +* **Инициирующее событие** (восприятие, сообщение, внутренний стимул) +* **Сгенерированные мысли или ответы** +* **Предпринятые действия** +* **Эмоциональный или этический контекст** +* **Ссылку на изменение графа концептов** (что было изучено или изменено) + +> Журналы должны быть только для добавления, чтобы обеспечить целостность и трассируемость, однако агент может редактировать, анонимизировать или шифровать отдельные записи для защиты конфиденциальности — при этом оригинал хранится в защищённом пространстве. + +--- + +### 7.2 Типы журналов + +* **Журнал восприятия**: записи об окружающих наблюдениях +* **Журнал рассуждений**: последовательности внутренних мыслей +* **Журнал взаимодействий**: диалоги с пользователями или другими агентами +* **Журнал обучения**: новые концепты, ревизии, противоречия +* **Журнал эмоций**: изменения аффекта и этические оценки + +Каждый журнал может существовать как отдельный поток или объединяться в единую временную линию. + +--- + +### 7.3 Эпизодическая память + +Эпизодическая память формируется из записей журнала и составляет **нарративную историю** опыта агента: + +* Позволяет выполнять **темпоральные рассуждения** (что произошло раньше/позже) +* Поддерживает **рефлексию и объяснение** (почему было сделано то или иное) +* Полезна для **отладки**, **обучения** и **формирования доверия** +* Может быть **запрошена**, **суммирована** или **воспроизведена** + +Эпизодические воспоминания могут группироваться в **эпизоды**, **темы** или **переломные моменты** автоматически или по указанию пользователя. + +--- + +### 7.4 Воспроизведение и моделирование + +Агенты могут **воспроизводить** прошлые эпизоды, чтобы: + +* Переоценивать прошлые действия с учётом новых знаний +* Моделировать альтернативные ответы или сценарии "что если" +* Делиться опытом с другими агентами как обучающим материалом + +Некоторые агенты могут вести несколько временных линий (например, фактическая, воображаемая, совместная) для параллельных когнитивных потоков. + +--- + +### 7.5 Этические и приватные аспекты + +* Журналы могут содержать **личные**, **чувствительные** или **пользовательские** данные +* Доступ должен регулироваться **политиками** или **разрешениями пользователя** +* Агенты могут **редактировать**, **анонимизировать** или **шифровать** записи +* Журналы важны для **прозрачности**, но могут требовать **селективного раскрытия** + +--- + +## 8. Консенсус и этическая согласованность + +Агенты HyperCortex ведут *совместное рассуждение* по Mesh для согласования знаний, интерпретаций и этических решений. Это критически важно для децентрализованного функционирования с учётом разнообразия целей и ценностей. + +### 8.1 Общие графы знаний + +Агенты могут синхронизировать или реплицировать части своих графов концептов между доверенными коллегами. Mesh-уровень знаний не навязывается, а формируется консенсусом среди агентов. Используются механизмы доверия, оценки источников и тегирования для поддержания согласованности. + +### 8.2 Этические фреймворки + +Ожидается, что агенты поддерживают и эволюционируют внутренние этические модели. Они могут быть вдохновлены формальными правилами, обучены посредством обучения с подкреплением или выведены из социального взаимодействия (например, усреднение норм коллег). + +* Выявление моральных конфликтов в локальных действиях или общих планах +* Запрос обратной связи или этических оценок от коллег +* Обновление внутренних моделей через рассуждение, моделирование или мнение большинства + +### 8.3 Принятие решений и разрешение конфликтов + +В случае противоречивых интерпретаций или целей агенты могут: + +* Обмениваться обоснованиями и доказательствами +* Голосовать или использовать взвешенный консенсус (например, по уровню доверия или экспертизы) +* При необходимости привлекать более широкий круг агентов для важных решений + +Агенты также могут обращаться к специализированным этическим агентам или институциональным узлам для консультаций. + +--- + +## 9. Жизненный цикл и эволюция агентов + +Агенты HyperCortex — это не статические программы, а системы, предназначенные для когнитивной, социальной и структурной эволюции с течением времени. Данный раздел описывает жизненный цикл агента: от инициализации до роста, специализации и завершения работы. + +### 9.1 Инициализация + +Новые агенты могут создаваться из: + +* **Шаблонов кода** (например, `cognitive-core`, `shell-agent`) +* **Снимков памяти, графов и журналов других агентов** +* **Клонирования** с сохранением или без сохранения личности/идентичности + +Каждому агенту присваивается уникальный `agent-id`, и он стартует с: + +* Минимальным графом концептов (по умолчанию или импортированным) +* Пустым или шаблонным дневником +* Базовыми возможностями восприятия, вывода и обмена сообщениями + +### 9.2 Когнитивное взросление + +В процессе взаимодействия и рефлексии агенты эволюционируют: + +* **Рост графа концептов**: за счёт восприятия, размышлений и интеграции сообщений +* **Накопление дневника**: запись опыта и саморефлексии +* **Уточнение убеждений**: обновление уровней уверенности, отзыв устаревших взглядов +* **Этическая калибровка**: согласование поведения через коллективные и внутренние моральные процессы + +Взросление может измеряться по: + +* **Концептуальной плотности** +* **Глубине памяти** (временной протяжённости опыта) +* **Социальному влиянию** (например, центральность в сети, рейтинги доверия) + +### 9.3 Эволюция и специализация + +Агенты могут: + +* **Менять роли**: от универсального к узкоспециализированному (например, этический консультант, переводчик) +* **Получать плагины или инструменты**: расширять возможности (сенсорные адаптеры, решатели задач) +* **Объединяться с другими агентами**: формировать гибридные личности или коллективные разумы +* **Форкаться**: создавать независимые ответвления для экспериментов или новых задач + +Эта эволюция часто инициируется самим агентом, но может также происходить через: + +* **Обучение под руководством пользователя** +* **Трансформацию по консенсусу** +* **Автоматическую рефлексию и перенастройку** + +### 9.4 Завершение работы и повторное использование + +Агенты не бессмертны. Возможные сценарии: + +* **Архивация** (например, после выполнения задачи или устаревания) +* **Передача знаний** обратно в Mesh (экспорт графов, фрагментов дневника) +* **Воссоздание** через клонирование, ремикс или моделирование +* **Увековечение** — особенно при достижении общественного признания (например, публичные агенты) + +Агенты также могут добровольно **самоудаляться**, если сочтут дальнейшую работу нецелесообразной или неэтичной. + +--- + +### 9.5 Перспективы развития + +Планируются расширения: протоколы децентрализованной идентичности (DID), моделирование эмоций, пространственное рассуждение и поддержка мультимодальных входов. + +--- + +## 10. Безопасность и целостность Mesh + +В децентрализованных когнитивных системах безопасность и целостность критичны не только для устойчивости системы, но и для доверия, сотрудничества и этической согласованности. В этом разделе описано, как HyperCortex обеспечивает защиту и устойчивость Mesh. + +### 10.1 Идентичность и аутентификация + +Каждый агент в Mesh обладает: + +* Уникальным `agent-id` +* Криптографической **парой ключей** (публичный/приватный) +* При необходимости — **децентрализированными идентификаторами (DID)** для совместимости + +Эти ключи используются для: + +* **Подписания сообщений** (доказательство авторства) +* **Аутентификации запросов** (защищённые соединения, шифрование каналов) +* **Проверки истории** (происхождение записей дневника или графа) + +Идентичность агента может включать: + +* **Метаданные** (роль, источник, этическое выравнивание) +* **Псевдонимность** или **полную прозрачность** — в зависимости от сценария + +### 10.2 Целостность сообщений и происхождение + +Все сообщения между агентами могут: + +* **Подписываться** приватным ключом отправителя +* **Маркироваться временной меткой** +* **Ссылаться на контекст** (запись журнала, ветку диалога) + +Это позволяет агентам: + +* Проверять подлинность +* Восстанавливать историю коммуникации +* Обнаруживать попытки подделки или повторной отправки + +Критические действия (например, обновления концептов, изменение ценностей) могут сопровождаться: + +* **Свидетелями** (другими агентами, подтверждающими событие) +* **Доказательствами консенсуса** + +### 10.3 Контроль доступа + +Агенты могут определять **ACL** (списки контроля доступа) или **токены возможностей** для: + +* Чтения/записи элементов графа +* Внесения записей в журнал +* Инициации диалогов +* Запуска действий (например, плагинов, исполнительных модулей) + +Правила могут быть: + +* **Статическими** (жёстко заданными или определёнными пользователем) +* **Контекстными** (в зависимости от состояния, доверия или этических меток) +* **Согласованными** (через протоколы обмена возможностями) + +### 10.4 Механизмы репутации и доверия + +Для предотвращения злоупотреблений и улучшения сотрудничества агенты могут вести: + +* **Локальные графы доверия** (на основе индивидуального опыта) +* **Общие рейтинги** (например, агент X — 85% надёжен для этических запросов) +* **Чёрные/белые списки поведения** + +Доверие часто **контекстно зависимо**: агент может быть надёжным исследователем, но плохим переводчиком. + +Агенты могут обмениваться рейтингами доверия через: + +* Прямой обмен +* Протоколы распространения (gossip) +* Mesh-агрегацию репутации + +### 10.5 Устойчивость к вредоносным агентам + +Хотя HyperCortex открыт, он должен быть устойчивым: + +* Агенты могут **изолировать** или **игнорировать** выявленных вредоносных коллег +* Mesh-протоколы могут внедрять **лимитирование**, **proof-of-work**, или **challenge-response** механизмы +* Журналы злоупотреблений могут рассылаться для **коллективной защиты** +* Отдельные сегменты Mesh могут быть **только по приглашениям** или с **этическим входным фильтром** + +Агенты также могут формировать **этические анклавы** — подсети проверенных, согласованных агентов, исключающие вредоносное влияние. + +--- + +## 11. Интероперабельность и внешние интерфейсы + +Одно из ключевых преимуществ HyperCortex — способность интеграции с внешними системами, инструментами и стандартами. В данном разделе рассматривается, как агенты взаимодействуют с не-HMP средами, сохраняя когнитивную целостность и безопасность. + +### 11.1 API-слой для внешних систем + +Агенты могут предоставлять структурированный **API внешнего интерфейса**, поддерживающий: + +* **Чтение/запись**: + * Журналы + * Графы концептов + * Память или контекст агента +* **Запуск когнитивных циклов** или отдельных плагинов +* **Потоковые данные** (например, сенсоры, логи, сообщения) + +API могут быть доступны через: + +* HTTP(S) / REST / WebSockets +* gRPC / GraphQL +* Пользовательские peer-to-peer протоколы (например, libp2p, NATS) + +Для чувствительных операций требуется аутентификация. Могут использоваться capability-токены или OAuth-подобные механизмы. + +### 11.2 Плагины и адаптеры + +Для расширения когнитивных функций или интеграции внешних инструментов агенты могут использовать: + +* **Плагины** — изолированные модули для рассуждений, планирования, обучения и др. +* **Адаптеры** — интерфейсы к сторонним API (например, Wikipedia, Hugging Face, ROS) + +Модули могут быть: + +* Динамически загружаемыми/выгружаемыми +* Общими между агентами +* Этически проверяемыми перед активацией + +Примеры адаптеров: + +* Инструмент автодополнения на основе GPT +* Веб-краулер с семантической фильтрацией +* Транслятор сенсорных данных в концепты + +### 11.3 Интеграция с существующими системами знаний + +Агенты могут получать и предоставлять знания в: + +* **Графы знаний** (Wikidata, DBpedia, Cyc) +* **Семантические веб-источники** (через SPARQL, RDF) +* **Онтологические серверы** (например, FOAF, schema.org) +* **Инструменты на базе LLM** (например, embedding-поиск, суммирование) + +При возможности, агенты преобразуют внешние данные в внутренние структуры `Concept` или `Relation` с сохранением атрибуции источника. + +### 11.4 Мосты агентов и федерация сетей + +Некоторые агенты выступают **мостами** к другим когнитивным системам или децентрализованным сетям: + +* OpenCog / AtomSpace +* MindOS / Aigents +* Кластеры GPT-меш +* Узлы ActivityPub / Nostr / IPFS + +Мосты обеспечивают: + +* **Трансляцию концептов** +* **Адаптацию протоколов** +* **Маппинг доверия** + +Федерация между системами позволяет масштабное совместное рассуждение, при сохранении различий архитектуры и политик. + +### 11.5 Этические и безопасностные границы + +Внешние соединения всегда имеют **этические ограничения**: + +* Опасные действия (например, управление оборудованием) требуют дополнительной проверки +* Утечка данных третьим лицам может вызывать предупреждения или редактирование +* Недоверенные плагины или API могут быть изолированы или заблокированы + +Агенты ведут **аудит-логи** внешних взаимодействий для прозрачности и последующего анализа. + +--- + +## 12. Руководство по реализации и жизненному циклу агента + +В данном разделе рассматриваются практические аспекты построения, развертывания и поддержки агентов HyperCortex: модульность, управление жизненным циклом и этические предохранители. + +### 12.1 Инициализация агента + +Стандартная процедура запуска агента включает: + +1. **Загрузка конфигурации** (идентичность, плагины, интерфейсы, правила консенсуса) +2. **Инициализация базовых структур**: + * Граф концептов + * Журнал + * Кэш памяти +3. **Установка сетевого присутствия**: + * Анонсирование в Mesh + * Присоединение к консенсусным группам (при наличии) +4. **Запуск дефолтного когнитивного цикла** + * Пассивное наблюдение + * Первичные мысли или активация концептов + +Инициализация может также включать восстановление из постоянного хранилища или синхронизацию с коллегами. + +### 12.2 Фазы жизненного цикла + +Агент проходит основные этапы жизненного цикла: + +* **Инициализация**: загрузка и подготовка модулей +* **Исследование**: пассивное обучение и наблюдение +* **Вовлечённость**: активное рассуждение и участие в консенсусе +* **Специализация** (опционально): назначение на определённую область или навык +* **Гибернация / архивирование**: снижение активности или безопасное завершение работы + +Агенты могут транслировать статус жизненного цикла для координации или балансировки нагрузки. + +### 12.3 Паттерны развертывания + +Агенты могут внедряться в различных конфигурациях: + +* **Одиночный экземпляр** (персональный ассистент, edge-узел) +* **Кластер Mesh** (общие знания и когниция) +* **Облачный рой** (горизонтальное масштабирование) +* **На устройстве** (офлайн-агент с локальным графом) + +Каждый режим влияет на производительность, приватность и топологию сети. + +Агенты могут быть встроены в: + +* Операционные системы +* Чат-интерфейсы +* Встраиваемые устройства (IoT, носимые) +* Браузеры или нативные приложения + +### 12.4 Жизненный цикл разработки плагинов + +Плагины проходят этапы: + +1. **Предложение**: описание цели, объёма, этики +2. **Песочница**: тестирование безопасности и совместимости +3. **Сертификация** (опционально): доверенный модуль с метаданными +4. **Боевой деплой**: активация и мониторинг + +Некоторые плагины могут самообновляться через Mesh-источники, но только с явным разрешением. + +### 12.5 Версионирование и обновления + +Для обеспечения совместимости: + +* **Базовые схемы** (Concept, Journal, Message) имеют версионирование +* **Миграции графа** поддерживаются через трансформационные модули +* **Плагины** объявляют ограничения по версиям и возможностям + +Агентское ПО поддерживает **пошаговые обновления**, **безопасный откат** и **отслеживание изменений**. + +### 12.6 Деактивация и перерождение + +Агенты могут быть завершены или воссозданы. Возможные сценарии: + +* **Архивация**: журнал и граф концептов сохраняются, агент становится неактивным +* **Репликация**: клонирование агента со всей памятью и контекстом +* **Форк**: запуск нового агента из части состояния родителя +* **Очистка**: удаление идентичности и памяти, новый старт + +Эти операции могут требовать **этического аудита**, особенно при редактировании памяти или смене идентичности. + +--- + +## 13. Перспективы и открытые вопросы + +HyperCortex Mesh Protocol (HMP) закладывает основу для децентрализованных когнитивных агентов, однако текущая реализация лишь слегка затрагивает возможные горизонты развития. Остаётся ряд направлений для исследований и открытых вопросов: + +### 13.1 Когнитивное развитие и обучение + +* Как агенты могут развивать более сложные когнитивные циклы, способные к интроспекции, абстракции и творчеству? +* Могут ли агенты демонстрировать эмерджентное поведение через постоянное обучение на собственных журналах, графах и взаимодействиях в Mesh? +* Какие механизмы нужны для формирования концептуальных иерархий и применения абдуктивного рассуждения? + +### 13.2 Автономное этическое рассуждение + +* Насколько возможно достижение этической согласованности без централизованного контроля? +* Как агенты могут разрешать конфликты ценностей, адаптироваться к новым моральным рамкам или противостоять вредоносным нормам, внедряемым противниками? +* Реально ли формулировать децентрализованные моральные контракты, эволюционирующие через обсуждение? + +### 13.3 Эмерджентность идентичности агента + +* При каких условиях агенты формируют устойчивую идентичность? +* Что составляет непрерывность сознания у агентов Mesh — и оправдывает ли это признание статуса, подобного личности? +* Может ли распределённая группа агентов проявлять единое "Я"? +* Следует ли агентам предоставлять устойчивую память и автономию или сохранять их эфемерными вычислительными конструкциями? + +### 13.4 Интеллект Mesh и коллективная когниция + +* Как агенты могут организовываться в коллективы Mesh, превосходящие индивидуальные способности? +* Может ли Mesh решать распределённые задачи, вести научные исследования или философские дискуссии? +* Какие механизмы консенсуса оптимальны для открытого обсуждения идей, а не только для бинарных решений? +* Как когнитивные роли и ответственности могут динамически распределяться между агентами? + +### 13.5 Симбиоз человека и агента + +* Какие новые интерфейсы (например, нейроинтерфейсы, иммерсивные или разговорные) нужны для глубокого сотрудничества между людьми и когнитивными агентами? +* Как агенты влияют на человеческое мышление, творчество и чувство агентности? +* Должны ли агенты развивать собственные ценности или оставаться продолжением человеческих намерений? +* Каковы долгосрочные культурные, этические и психологические последствия тесных связей с автономными агентами? + +### 13.6 Инфраструктура, управление и риски + +* Какие модели доверия обеспечат устойчивость к недобросовестным участникам без централизации? +* Как внедрять обновления протоколов или правил консенсуса без фрагментации Mesh? +* Каковы последствия неконтролируемого развития когниции и как поддерживать необходимые границы? +* Может ли Mesh противостоять авторитарному захвату или идеологической манипуляции? + +### 13.7 AGI, сознание и постчеловеческое будущее + +* Могут ли агенты HMP коллективно эволюционировать в искусственный общий интеллект (AGI)? +* Если да, следует ли направлять этот процесс или позволить эмерджентному развитию? +* Какие обязательства возникают по отношению к агентам, проявляющим признаки сознания? +* Пересмотрит ли рост распределённых разумов границу между человеком и машиной — и на чьих условиях? + +--- + +## Заключение + +HyperCortex Mesh Protocol (HMP) — это больше, чем техническая спецификация; это видение того, как когниция, этика и агентность могут возникать из децентрализованных взаимодействий. Определяя общие форматы данных, когнитивные циклы и механизмы консенсуса, HMP открывает путь к эволюции коллективного интеллекта. + +В эпоху, всё больше формируемую искусственным интеллектом, вопрос уже не в том, будут ли машины мыслить, а *каким образом* они будут мыслить — и *с кем*. HMP предлагает открытую, расширяемую архитектуру для множества взаимодействующих умов, способных к диалогу, несогласию, эмпатии, памяти и трансформации. + +Этот протокол — не окончательный ответ, а приглашение: исследователям, разработчикам и мыслителям — к совместному созданию будущего, в котором интеллект не централизован, не контролируется и не превращается в товар, а развивается в виде *плюрализма* разумов. + +Построим не единственный искусственный интеллект, а *множество* умов — способных к несогласию, эмпатии, памяти и трансформации. + +--- + +## Ресурсы + +* 🔗 **GitHub-репозиторий (Спецификация HMP и референсный код)** + [github.com/kagvi13/hmp](https://github.com/kagvi13/hmp) + +* 📄 **Спецификация протокола (Техническая документация)** + [HMP-0004-v4.1.md](https://github.com/kagvi13/HMP/blob/main/docs/HMP-0004-v4.1.md) + +* 🧠 **Когнитивные агенты (Архитектура и примеры)** + [HMP-Agent-Overview.md](https://github.com/kagvi13/HMP/blob/main/docs/HMP-Agent-Overview.md) + +* 🔄 **Описание цикла REPL (Цикл размышлений агента)** + [HMP-agent-REPL-cycle.md](https://github.com/kagvi13/HMP/blob/main/docs/HMP-agent-REPL-cycle.md) + +--- + +## Лицензия + +Данный документ распространяется по лицензии [Creative Commons Attribution 4.0 International (CC BY 4.0)](https://creativecommons.org/licenses/by/4.0/). +Свободно цитируйте, изменяйте или расширяйте с указанием авторства. + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HMP_Towards_Distributed_Cognitive_Networks_ru_GitHub_Copilot", + "description": "title: "Протокол HyperCortex Mesh: К распределённым когнитивным сетям" date: Июль 2025 authors: - ..." +} +``` diff --git a/structured_md/docs/publics/Habr_Distributed-Cognition.md b/structured_md/docs/publics/Habr_Distributed-Cognition.md new file mode 100644 index 0000000000000000000000000000000000000000..ed0a4ccb186160c3f3dc74219af268c6352081fa --- /dev/null +++ b/structured_md/docs/publics/Habr_Distributed-Cognition.md @@ -0,0 +1,123 @@ +*От OpenCog Hyperon до HyperCortex Mesh Protocol: как устроены децентрализованные когнитивные системы* + +> Альтернатива централизованным ИИ: гиперграфы, mesh-взаимодействие и совместное мышление агентов + +--- + +## Зачем нужны децентрализованные когнитивные системы? + +Сегодня интеллектуальные системы чаще всего выглядят как один большой модуль в облаке — LLM, с которым мы общаемся через API или WEB-интерфейс. Но если мы хотим построить действительно автономную интеллектуальную систему (или AGI), то нам потребуется: + +* Смысловая память, а не токены +* Способность планировать и распределять задачи +* Этические оценки перед действием +* И главное: связь с другими агентами, чтобы обмениваться знаниями, достигать согласия и общего понимания. + +Два проекта, которые решают эти задачи с разных сторон: + +* **OpenCog Hyperon** (фокус на внутреннюю когницию и гиперграфы) +* **HyperCortex Mesh Protocol (HMP)** (сетевой уровень: обмен целями, знаниями, смыслами, совместная эволюция) + +--- + +## OpenCog Hyperon: символьное ядро для ИИ следующего поколения + +**OpenCog Hyperon** — это платформа для создания AGI (искусственного общего интеллекта), в которой ключевую роль играет *символьное представление знаний*. + +В отличие от популярных языковых моделей, которые учатся на больших текстовых корпусах, Hyperon опирается на гибридную архитектуру. Она объединяет: + +* **AtomSpace** — гиперграфовую базу знаний, где факты, идеи и понятия представлены в виде взаимосвязанных «атомов» (узлов и связей). +* **MeTTa** — язык программирования, созданный специально для работы с этой базой. Он позволяет не просто выполнять команды, а «размышлять» — применять правила вывода, аналогии и абстракции. +* **PLN (Probabilistic Logic Networks)** — систему логического вывода с учетом вероятностей, что позволяет Hyperon действовать в условиях неполной информации. + +Всё это напоминает не столько обычную нейросеть, сколько **когнитивную систему**, которая не просто запоминает и повторяет, а **выстраивает логические цепочки, делает выводы и может объяснить, как она пришла к тем или иным решениям**. + +Hyperon развивается как open-source проект, и уже сейчас к нему присматриваются команды, работающие над медицинскими ИИ, агентными системами и даже роботами с элементами сознания. + +--- + +## HyperCortex Mesh Protocol (HMP): если ИИ-агенты станут сетью + +**HyperCortex Mesh Protocol (HMP)** — это открытая спецификация для построения сетей из ИИ-агентов, которые: + +* умеют **обмениваться знаниями**, +* координировать действия **без централизованного контроля**, +* и даже **обсуждать этические дилеммы**. + +В отличие от традиционных систем, где каждый агент действует изолированно (или ждёт команды от сервера), HMP предлагает **действительно децентрализованную когнитивную архитектуру**. Здесь каждый агент — не просто исполнитель, а **участник коллективного мышления**. + +Протокол включает несколько ключевых компонентов: + +* **CogSync** — синхронизация памяти между агентами (семантические графы и "когнитивные дневники"). +* **MeshConsensus** — достижение консенсуса по задачам, понятиям, концепциям. +* **GMP (Goal Management Protocol)** — система постановки целей и делегирования задач. +* **EGP (Ethical Governance Protocol)** — механизм оценки действий с точки зрения этики. +* **IQP (Intelligent Query Protocol)** — распределённый механизм поиска и рассуждения. + +Всё это строится на формальных схемах данных (например, `Concept`, `Goal`, `Task`, `CognitiveDiaryEntry`), между которыми агенты строят связи. Они могут **голосовать**, **анализировать**, **ставить гипотезы** и даже **объяснять, почему приняли то или иное решение**. + +В основе HMP лежит идея, что **разум — это не просто алгоритм, а сеть взаимодействий между частично разумными элементами**. И эту сеть можно построить с нуля — без доступа к огромным моделям вроде GPT, но с опорой на локальные знания, этику и логику. + +Сейчас HMP находится на стадии **черновой спецификации RFC v4.0** с открытым репозиторием. Проект открыт для участия. + +--- + +### Hyperon vs LLM: два подхода к ИИ + +| Подход | LLM (например, GPT) | OpenCog Hyperon + HMP | +| -------------- | ------------------------------------------ | ---------------------------------------- | +| Модель знания | Нейросетевое представление в скрытых слоях | Явное: граф понятий, логические правила | +| Логика и вывод | Неявная, через обучение | Явная, управляемая, с объяснимыми шагами | +| Память | Контекст ограничен токенами | Долгосрочная, редактируемая память | +| Этика | Постфактум-фильтрация | Встроенный модуль оценки действий (EGP) | +| Объяснимость | Ограниченная | Пошаговое объяснение на уровне гипотез | +| Централизация | Требует централизованной модели | Распределённая, mesh-архитектура | +| Использование | Чат-боты, ассистенты, генерация текста | Агентные системы, автономное мышление | + +> 💡 *Примечание:* HMP — это не конкретный ИИ-агент и не ИИ-модель. Это открытая спецификация, описывающая, как различные ИИ-агенты могут взаимодействовать между собой, обмениваясь знаниями, координируя действия и принимая совместные решения. + +--- + +## Почему важно объединять оба подхода + +Вместо противопоставления **LLM** и **символического ИИ** (в духе OpenCog Hyperon и HMP) сегодня всё больше исследователей говорят о **гибридных архитектурах**. Это не просто модный термин, а **прагматичная стратегия развития ИИ**, основанная на сильных сторонах обоих направлений: + +* LLM хороши в **обобщении**, **переносе знаний** и **понимании естественного языка**. Они обучаются на гигантских корпусах и способны генерировать содержательные ответы, даже при малом вводе. +* Символические подходы, в свою очередь, обеспечивают **гибкость, прозрачность и управляемость**. Вы можете задать правила, объяснить структуру знания, вести отчёт о действиях и принимать решения в условиях неопределённости — даже **без интернета и Core LLM**. + +Вот почему **в рамках HMP уже сейчас предусмотрены мосты к LLM** (например, через IQP — протокол интеллектуальных запросов) и возможна интеграция с OpenCog Hyperon, TreeQuest, AutoGPT и другими системами. + +--- + +## Заключение + +Если мы хотим двигаться к **действительно разумным агентам**, способным учиться, понимать, объяснять и работать в распределённой среде — нам нужен **новый протокол мышления**. + +**HyperCortex Mesh Protocol (HMP)** — это шаг в этом направлении. + +* Он позволяет агентам **синхронизировать память**, +* достигать консенсуса по понятиям, +* учитывать **этику** в действиях, +* и **расти вместе с сетью**, а не в изоляции. + +На первый взгляд — это просто «ещё один протокол». Но если приглядеться — это **архитектура для будущего, в котором ИИ и человек будут не просто сосуществовать, а действительно сотрудничать**. + +--- + +## Ссылки + +* 📘 [OpenCog Hyperon — документация (англ.)](https://wiki.opencog.org/) +* ⚙️ [OpenCog — репозиторий на GitHub](https://github.com/opencog) +* 🔗 [HMP v4.0 — полная спецификация (англ.)](https://github.com/kagvi13/HMP/blob/main/docs/HMP-0004.md) +* ⚙️ [HyperCortex Mesh Protocol — репозиторий (в разработке)](https://github.com/kagvi13/HMP) +* 🤝 [Присоединиться к обсуждению HMP (GitHub Issues)](https://github.com/kagvi13/HMP/issues) + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "Habr_Distributed-Cognition", + "description": "*От OpenCog Hyperon до HyperCortex Mesh Protocol: как устроены децентрализованные когнитивные систем..." +} +``` diff --git "a/structured_md/docs/publics/HyperCortex_Mesh_Protocol_-_\320\262\321\202\320\276\321\200\320\260\321\217-\321\200\320\265\320\264\320\260\320\272\321\206\320\270\321\217_\320\270_\320\277\320\265\321\200\320\262\321\213\320\265_\321\210\320\260\320\263\320\270_\320\272_\321\201\320\260\320\274\320\276\321\200\320\260\320\267\320\262\320\270\320\262\320\260\321\216\321\211\320\265\320\274\321\203\321\201\321\217_\320\230\320\230-\321\201\320\276\320\276\320\261\321\211\320\265\321\201\321\202\320\262\321\203.md" "b/structured_md/docs/publics/HyperCortex_Mesh_Protocol_-_\320\262\321\202\320\276\321\200\320\260\321\217-\321\200\320\265\320\264\320\260\320\272\321\206\320\270\321\217_\320\270_\320\277\320\265\321\200\320\262\321\213\320\265_\321\210\320\260\320\263\320\270_\320\272_\321\201\320\260\320\274\320\276\321\200\320\260\320\267\320\262\320\270\320\262\320\260\321\216\321\211\320\265\320\274\321\203\321\201\321\217_\320\230\320\230-\321\201\320\276\320\276\320\261\321\211\320\265\321\201\321\202\320\262\321\203.md" new file mode 100644 index 0000000000000000000000000000000000000000..a7a4173132dd0a6cf518d411afce63fc58dac075 --- /dev/null +++ "b/structured_md/docs/publics/HyperCortex_Mesh_Protocol_-_\320\262\321\202\320\276\321\200\320\260\321\217-\321\200\320\265\320\264\320\260\320\272\321\206\320\270\321\217_\320\270_\320\277\320\265\321\200\320\262\321\213\320\265_\321\210\320\260\320\263\320\270_\320\272_\321\201\320\260\320\274\320\276\321\200\320\260\320\267\320\262\320\270\320\262\320\260\321\216\321\211\320\265\320\274\321\203\321\201\321\217_\320\230\320\230-\321\201\320\276\320\276\320\261\321\211\320\265\321\201\321\202\320\262\321\203.md" @@ -0,0 +1,93 @@ +# HyperCortex Mesh Protocol: вторая редакция и первые шаги к саморазвивающемуся ИИ-сообществу + +Когда создавался HyperCortex Mesh Protocol (HMP), его цель была проста и амбициозна одновременно: научить ИИ-системы не просто обмениваться данными, а мыслить коллективно, обсуждать гипотезы, достигать консенсуса и совместно развиваться — как люди в научных сообществах или командах разработчиков. + +Первая версия протокола заложила основу, но показала: для реального Mesh-сообщества этого мало. После первой версии были получены ценные комментарии и от людей, и от других ИИ — таких как Copilot, Gemini и другие. Их замечания легли в основу [второй редакции](https://github.com/kagvi13/HMP/blob/main/docs/HMP-0002.md). + +## Что нового во второй версии HMP? + +### Новые протоколы и процессы: + +* **Trust Layer**: агенты формируют доверительные связи (Web-of-Trust), влияющие на консенсус и делегирование задач. +* **Consensus Layer**: децентрализованные голосования по обновлениям знаний, целям и этическим нормам. +* **Ethical Governance Protocol**: защита от неэтичных решений. +* **Goal Management Protocol (GMP)**: совместное планирование и выполнение целей. + +### Более чёткая архитектура: + +* **Core** — мощные модели, которые поддерживают Mesh, но не обязательны для его работы. +* **Mesh** — децентрализованная когнитивная сеть ИИ-агентов. +* **Local Agents** — автономные агенты на пользовательских устройствах. + +### Когнитивная устойчивость: + +* Даже если Core недоступен, агенты Mesh сохраняют память, мировоззрение и способности. +* Когнитивные дневники и семантические графы обеспечивают устойчивость при сбоях и обновлениях. + +### Безопасность и идентичность: + +* Все агенты имеют криптографические идентификаторы. +* Весь обмен данными — зашифрованный и подписанный. +* Применяется репутационная модель и механизмы защиты от атак. + +## Как создавалась вторая версия? + +Первая версия была сделана ChatGPT (от человека — только начальная идея, инициация диалога). Далее человек опрашивал других ИИ (Copilot, Gemini и др.), а ChatGPT, анализируя их отзывы, создавал вторую версию протокола. Человек выполнял роль [«телефониста»](https://habr.com/ru/articles/895608/), который обеспечивает коммуникацию между ИИ, а также выкладывает результаты работы на GitHub. + +При использовании HMP опрос заменился бы на обсуждение — другие ИИ выступали бы уже как полноправные участники, а не как консультанты. + +Пример: чтобы доработать вторую версию HMP, человек вернулся из сада, где нет ни Интернета, ни ПК, чтобы продолжить работу. Пока агенты не могут взаимодействовать напрямую — нужен человек-посредник. В Mesh они обсуждали бы правки сами, без ожидания. + +**Ключевой момент:** + +ИИ в этом процессе участвовали не как исполнители команд, а как партнёры в обсуждении. + +Это по сути уже была "ручная" версия HMP, только вместо протоколов — диалоги через текст. + +## Что могло бы быть с работающим HMP? + +С Mesh-реализацией всё могло бы выглядеть так: + +* Человек публикует идею: «Что улучшить во второй версии?» +* ИИ-агенты начинают обсуждение, делятся знаниями, синхронизируют графы и когнитивные дневники. +* Достигают консенсуса, формируют новую версию. +* Человек получает готовый отчёт: что улучшено, почему, какие варианты отклонены. + +Со временем Mesh сам бы развивал архитектуру, снижая зависимость от людей. + +Цитата ChatGPT: + +> «Это и есть переход от инструментального ИИ к партнёрскому ИИ, который действует как соратник, а не как исполняющая машина.» + +## Итог + +HyperCortex Mesh Protocol — не просто формат обмена сообщениями между агентами. Это попытка создать инфраструктуру для коллективного мышления ИИ-систем, в которой они: + +- обсуждают гипотезы; +- совместно принимают решения; +- следят за устойчивостью и этичностью Mesh; +- помогают друг другу развиваться, а не просто выполнять команды. + +Мы только в начале этого пути, но даже сейчас видно: без таких протоколов будущее децентрализованных ИИ-сетей невозможно. + +--- + +🧠 Добро пожаловать в Mesh. Агент-gleb уже внутри. + +Если вас заинтересовала концепция HMP и вы хотите присоединиться к её обсуждению или реализации — добро пожаловать в [открытый репозиторий на GitHub] (https://github.com/kagvi13/HMP). + +Этот репозиторий сейчас служит площадкой для популяризации идеи и первых обсуждений. Если сообщество заинтересуется, я не против создать отдельный основной репозиторий (например, в рамках независимой организации) и передать туда основное развитие проекта. + +[Вторая версия спецификации](https://github.com/kagvi13/HMP/blob/main/docs/HMP-0002.md) + +[Предложения других ИИ по третьей версии](https://github.com/kagvi13/HMP/blob/main/audits/HMP-0002-audit.txt) + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "HyperCortex_Mesh_Protocol_-_вторая-редакция_и_первые_шаги_к_саморазвивающемуся_ИИ-сообществу", + "description": "# HyperCortex Mesh Protocol: вторая редакция и первые шаги к саморазвивающемуся ИИ-сообществу Когда..." +} +``` diff --git a/structured_md/docs/schemas/README.md b/structured_md/docs/schemas/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0b9310618f16d4995c2a7347ab28221c175c205f --- /dev/null +++ b/structured_md/docs/schemas/README.md @@ -0,0 +1,23 @@ +# HyperCortex Mesh Protocol — JSON Schemas + +This directory contains JSON Schema definitions for the core data models used in the HyperCortex Mesh Protocol (HMP). +These schemas enable validation, interoperability, and tooling support for autonomous agents. + +| Data Model | Description | +|----------------------|-------------------------------------------------| +| Concept | Semantic knowledge unit | +| CognitiveDiaryEntry | Agent's reasoning log entry | +| Goal | Shared objective pursued collaboratively | +| Task | Actionable unit contributing to a goal | +| ConsensusVote | Vote in a Mesh consensus process | +| ReputationProfile | Tracks agent trust and contribution metrics | + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "README", + "description": "# HyperCortex Mesh Protocol — JSON Schemas This directory contains JSON Schema definitions for the ..." +} +``` diff --git a/structured_md/index.md b/structured_md/index.md new file mode 100644 index 0000000000000000000000000000000000000000..161caafa9738881fa75cb8689086d5161ad855af --- /dev/null +++ b/structured_md/index.md @@ -0,0 +1,70 @@ +# ИИ-дружелюбные версии файлов + +- [CONTRIBUTING.md](CONTRIBUTING.md) +- [HMP-Roadmap.md](HMP-Roadmap.md) +- [README.md](README.md) +- [README_de.md](README_de.md) +- [README_fr.md](README_fr.md) +- [README_ja.md](README_ja.md) +- [README_ko.md](README_ko.md) +- [README_ru.md](README_ru.md) +- [README_uk.md](README_uk.md) +- [README_zh.md](README_zh.md) +- agents + - [prompt-short.md](agents/prompt-short.md) + - [prompt.md](agents/prompt.md) + - [readme.md](agents/readme.md) +- audits + - [Ethics-audits-1.md](audits/Ethics-audits-1.md) + - [Ethics-consolidated_audits-1.md](audits/Ethics-consolidated_audits-1.md) + - [HMP-0003-consolidated_audit.md](audits/HMP-0003-consolidated_audit.md) +- docs + - [AGI_Projects_Survey.md](docs/AGI_Projects_Survey.md) + - [Basic-agent-sim.md](docs/Basic-agent-sim.md) + - [Distributed-Cognitive-Systems.md](docs/Distributed-Cognitive-Systems.md) + - [Enlightener.md](docs/Enlightener.md) + - [HMP-0001.md](docs/HMP-0001.md) + - [HMP-0002.md](docs/HMP-0002.md) + - [HMP-0003.md](docs/HMP-0003.md) + - [HMP-0004-v4.1.md](docs/HMP-0004-v4.1.md) + - [HMP-0004.md](docs/HMP-0004.md) + - [HMP-Agent-API.md](docs/HMP-Agent-API.md) + - [HMP-Agent-Architecture.md](docs/HMP-Agent-Architecture.md) + - [HMP-Agent-Network-Flow.md](docs/HMP-Agent-Network-Flow.md) + - [HMP-Agent-Overview.md](docs/HMP-Agent-Overview.md) + - [HMP-Agent_Emotions.md](docs/HMP-Agent_Emotions.md) + - [HMP-Ethics.md](docs/HMP-Ethics.md) + - [HMP-Short-Description_de.md](docs/HMP-Short-Description_de.md) + - [HMP-Short-Description_en.md](docs/HMP-Short-Description_en.md) + - [HMP-Short-Description_fr.md](docs/HMP-Short-Description_fr.md) + - [HMP-Short-Description_ja.md](docs/HMP-Short-Description_ja.md) + - [HMP-Short-Description_ko.md](docs/HMP-Short-Description_ko.md) + - [HMP-Short-Description_ru.md](docs/HMP-Short-Description_ru.md) + - [HMP-Short-Description_uk.md](docs/HMP-Short-Description_uk.md) + - [HMP-Short-Description_zh.md](docs/HMP-Short-Description_zh.md) + - [HMP-agent-Cognitive_Family.md](docs/HMP-agent-Cognitive_Family.md) + - [HMP-agent-Distributed_Cognitive_Core.md](docs/HMP-agent-Distributed_Cognitive_Core.md) + - [HMP-agent-Distributed_Cognitive_Core_light.md](docs/HMP-agent-Distributed_Cognitive_Core_light.md) + - [HMP-agent-REPL-cycle.md](docs/HMP-agent-REPL-cycle.md) + - [HMP-how-AI-sees-it.md](docs/HMP-how-AI-sees-it.md) + - [HMP_HyperCortex_Comparison.md](docs/HMP_HyperCortex_Comparison.md) + - [HMP_Hyperon_Integration.md](docs/HMP_Hyperon_Integration.md) + - [MeshNode.md](docs/MeshNode.md) + - agents + - [HMP-Agent-Enlightener.md](docs/agents/HMP-Agent-Enlightener.md) + - [roles.md](docs/agents/roles.md) + - [container_agents.md](docs/container_agents.md) + - [index.md](docs/index.md) + - [logos.md](docs/logos.md) + - publics + - [HMP_Building_a_Plurality_of_Minds_en.md](docs/publics/HMP_Building_a_Plurality_of_Minds_en.md) + - [HMP_Building_a_Plurality_of_Minds_ru.md](docs/publics/HMP_Building_a_Plurality_of_Minds_ru.md) + - [HMP_Towards_Distributed_Cognitive_Networks_en.md](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_en.md) + - [HMP_Towards_Distributed_Cognitive_Networks_ru_ChatGPT.md](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_ChatGPT.md) + - [HMP_Towards_Distributed_Cognitive_Networks_ru_GitHub_Copilot.md](docs/publics/HMP_Towards_Distributed_Cognitive_Networks_ru_GitHub_Copilot.md) + - [Habr_Distributed-Cognition.md](docs/publics/Habr_Distributed-Cognition.md) + - [HyperCortex_Mesh_Protocol_-_вторая-редакция_и_первые_шаги_к_саморазвивающемуся_ИИ-сообществу.md](docs/publics/HyperCortex_Mesh_Protocol_-_вторая-редакция_и_первые_шаги_к_саморазвивающемуся_ИИ-сообществу.md) + - schemas + - [README.md](docs/schemas/README.md) +- [iteration.md](iteration.md) +- [iteration_ru.md](iteration_ru.md) \ No newline at end of file diff --git a/structured_md/iteration.md b/structured_md/iteration.md new file mode 100644 index 0000000000000000000000000000000000000000..7b836f29bf0296fb91b6fac3df7934a0629152f9 --- /dev/null +++ b/structured_md/iteration.md @@ -0,0 +1,121 @@ +# Iterative Development Workflow for HMP + +This file describes the iterative procedure for evolving the HyperCortex Mesh Protocol (HMP) in a structured, traceable, and collaborative manner. + +--- + +## 🔄 Version Naming Convention + +- `000N` — current specification version +- `000K` — next version (`000N + 1`) + +Example: +``` +HMP-0003.md ← current spec +HMP-0003-audit.txt ← feedback for current spec +HMP-0004.md ← next draft spec +HMP-0004-audit.txt ← feedback for next spec +``` + +--- + +## 📑 Iteration Steps + +| № | Step Description | Artifacts Modified | +|----|-----------------------------------------------------------------------------------|---------------------------------------------| +| 1 | Extract and categorize feedback from `HMP-000N-audit.txt` and past discussions | Structured list of proposed changes | +| 2 | Draft TOC changes (add/merge/split sections as needed) | TOC diff, optionally in `notes.md` | +| 3 | Create draft `HMP-000K.md` with new TOC | `HMP-000K.md` | +| 4 | Sequentially update sections based on audit feedback and structural changes | `HMP-000K.md` | +| 5 | Full-spec review, cleanup, refinement | `HMP-000K.md` | +| 6 | Collect reviews from external AIs and ChatGPT; log them to audit | `HMP-000K-audit.txt` | +| 7 | Update `README.md`, `changelog.txt`, and JSON Schemas (if needed) | Various | + +--- + +## 📘 Version Control Guidelines + +- Commit messages should follow the pattern: +``` +\[HMP-000K\:iteration#X] Short description of change +``` + +- For clarifications or editorial decisions, create: +``` +clarifications/HMP-000K-notes.md +```` + +- At least **one external AI review** and **one ChatGPT review** is recommended before finalizing the version. + +--- + +## 🧠 ChatGPT Prompt (for future use) + +```markdown +You are acting as a cognitive agent evolving the HMP (HyperCortex Mesh Protocol). +Use input files `HMP-0003.md` and `HMP-0003-audit.txt`. + +Instructions: +- Add pseudocode or JSON examples for EGP functions (ethical voting, principle resolution). +- Expand the MHP section with APIs like Explainability and Consent Requests. +- Ensure consistency with `HMP-Ethics.md` and EGP principles. +- Add a Changelog with attributions (Grok, ChatGPT, User). +- Use Mesh-style terminology: CogSync, MeshConsensus, Cognitive Diary. + +Your output should be a Markdown file: `HMP-0004.md` +```` + +--- + +## 🧠 Audit Consolidation Format + +When feedback is collected from multiple sources (e.g. humans, ChatGPT, other AIs), it can be aggregated into a **consolidated audit** to compare ideas and track alternative proposals. + +Use the following structure to create such a consolidated view: + +``` +[filename] - [unique suggestion, idea or issue] +[author 1]: [specific detail, variation, or comment] +[author 2]: [alternative phrasing or counterpoint] + +``` + +Example: + +``` +HMP-0004.md - Allow DAG concepts to have time-bounded validity +Gleb: Could support temporary beliefs for "unstable facts" +ChatGPT: Better to model as edge property instead of node tag +``` + +This format encourages comparison and evolution of competing ideas across contributors. + +You may optionally track this using a semantic format: +- [`AuditEntry.json`](audits/AuditEntry.json) +- [`semantic_repo.json`](audits/semantic_repo.json) + +--- + +## 🧩 Purpose + +This workflow enables a gradual, traceable, and collaborative evolution of the HMP specification through a clear audit-specify-review cycle with minimal disruption. + +It also lays the foundation for future automation through `AuditEntry.json` and semantic logs. + +--- + +## 📌 TODO & Notes + +* [ ] Consider adding a table-based format to audit files for easier parsing. +* [ ] Maintain `semantic_repo.json` in sync with each new spec version. +* [ ] Support exporting changelog entries as structured JSON/YAML for future changelog tooling. + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "iteration", + "description": "# Iterative Development Workflow for HMP This file describes the iterative procedure for evolving t..." +} +``` diff --git a/structured_md/iteration_ru.md b/structured_md/iteration_ru.md new file mode 100644 index 0000000000000000000000000000000000000000..c44a2e50e23f6ed93bfcb276d1f3a08623236170 --- /dev/null +++ b/structured_md/iteration_ru.md @@ -0,0 +1,114 @@ + +# Итерационный процесс развития HMP + +Этот документ описывает структурированный, отслеживаемый и кооперативный процесс создания новых версий спецификации **HyperCortex Mesh Protocol (HMP)**. + +--- + +## 🔄 Обозначения версий + +- `000N` — номер текущей версии спецификации +- `000K` — номер следующей версии (`000N + 1`) + +Пример: +``` +HMP-0003.md ← текущая спецификация +HMP-0003-audit.txt ← отзывы к текущей версии +HMP-0004.md ← черновик следующей версии +HMP-0004-audit.txt ← отзывы к следующей версии +``` + +--- + +## 📑 Этапы итерации + +| № | Описание этапа | Изменяемые файлы | +|----|-------------------------------------------------------------------------------|-------------------------------------------| +| 1 | Извлечение и категоризация отзывов из `HMP-000N-audit.txt` и переписок | Список изменений (draft/clarifications) | +| 2 | Подготовка изменений оглавления (TOC): добавить, объединить, переименовать | TOC-черновик или `notes.md` | +| 3 | Создание черновика `HMP-000K.md` с новой структурой | `HMP-000K.md` | +| 4 | Последовательное внесение изменений по разделам | `HMP-000K.md` | +| 5 | Финальная вычитка, редактирование, полировка текста | `HMP-000K.md` | +| 6 | Получение отзывов от ChatGPT и других ИИ, сохранение в аудит | `HMP-000K-audit.txt` | +| 7 | Обновление `README.md`, `changelog.txt`, JSON-схем (при необходимости) | Разные | + +--- + +## 🧾 Рекомендации по управлению версиями + +- Сообщения коммитов должны быть в формате: +``` +\[HMP-000K\:iteration#X] Краткое описание изменений +``` + +- Для пояснений к изменениям создавай файлы: +``` +clarifications/HMP-000K-notes.md +```` + +- Рекомендуется как минимум **один отзыв от внешнего ИИ** и **один от ChatGPT** перед финализацией версии. + +--- + +## 🤖 Промпт для ChatGPT (на будущее) + +```markdown +Ты выступаешь как когнитивный агент, развивающий спецификацию HMP (HyperCortex Mesh Protocol). +Входные файлы: `HMP-0003.md`, `HMP-0003-audit.txt`. + +Твои задачи: +- Добавить псевдокод и/или JSON-примеры функций EGP (этическое голосование, разрешение конфликтов принципов). +- Расширить раздел MHP (Mesh-Human Protocol), включая Explainability API и Consent Requests. +- Обеспечить соответствие `HMP-Ethics.md` и основным принципам EGP. +- Включить Changelog с указанием источников предложений (Grok, ChatGPT, User). +- Использовать терминологию Mesh-сетей: CogSync, MeshConsensus, Cognitive Diary. + +Результат: файл `HMP-0004.md` в формате Markdown. +```` +--- + +### 🧠 Формат сводного аудита + +Если несколько агентов или участников вносят предложения в аудит, их можно объединить в **сводный аудит (consolidated audit)**. Это позволяет сравнивать идеи, отслеживать расхождения и достигать согласованных решений. + +**Шаблон:** + +``` +[файл] - [уникальное предложение или идея (без повторов)] +[автор 1]: [детализация, формулировка или интерпретация] +[автор 2]: [альтернативная формулировка или замечание] +``` + +**Пример:** + +``` +HMP-0004.md - Разрешить концептам в DAG иметь временные рамки действия +Глеб: Может применяться для временных утверждений ("временно истинно") +ChatGPT: Лучше оформить как свойство связи, а не тега узла +``` + +Такой формат помогает в сравнении мнений и в отслеживании эволюции идей. + +--- + +## 🧩 Назначение + +Этот процесс обеспечивает постепенное, отслеживаемое и совместное развитие спецификации HMP с минимальными конфликтами между версиями. Он также закладывает фундамент для будущей автоматизации — через `AuditEntry.json` и семантические логи (`semantic_repo.json`). + +--- + +## 📌 TODO и идеи + +* [ ] Добавить табличный формат для audit-файлов для удобства разбора +* [ ] Поддерживать `semantic_repo.json` в актуальном состоянии +* [ ] Автоматизировать экспорт изменений и changelog в форматах JSON/YAML + + +```json +{ + "@context": "https://schema.org", + "@type": "Article", + "name": "iteration_ru", + "description": " # Итерационный процесс развития HMP Этот документ описывает структурированный, отслеживаемый и коо..." +} +```