Chris4K commited on
Commit
8acffe0
·
verified ·
1 Parent(s): 2ec79d9

initial PRD

Browse files

next contract and splitting up

Files changed (1) hide show
  1. docs/prd_v2.md +1856 -0
docs/prd_v2.md ADDED
@@ -0,0 +1,1856 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HearthNet — Technical PRD v2
2
+
3
+ **Distributed neighbourhood AI mesh**
4
+ *Resilient, community-owned local AI infrastructure that survives internet outages.*
5
+
6
+ ---
7
+
8
+ | | |
9
+ |---|---|
10
+ | **Status** | Draft v2 — supersedes v1 (2025) |
11
+ | **Author** | Christof |
12
+ | **Target** | Gradio Winter '25 Hackathon submission + post-hackathon product roadmap |
13
+ | **License (planned)** | AGPLv3 for the kernel, MIT for clients |
14
+ | **Repo (planned)** | github.com/Chris4K/hearthnet |
15
+ | **Demo (planned)** | huggingface.co/spaces/Chris4K/hearthnet-demo |
16
+
17
+ ---
18
+
19
+ ## 0. The 2-minute pitch
20
+
21
+ Imagine the internet cable in your neighbourhood gets cut. Right now, that means no Google, no ChatGPT, no maps, no marketplace, no messaging. The cloud goes silent and you're alone with whatever's on your phone.
22
+
23
+ HearthNet changes that. It's a local AI mesh that turns the computers already in your neighbourhood — your gaming PC, your neighbour's old laptop, the Raspberry Pi in someone's attic — into a shared, resilient AI cooperative. Discovery is automatic. You don't configure anything. You open the app, it finds the nodes nearby, you ask a question. The answer is generated locally, on someone's GPU, three streets away.
24
+
25
+ When the internet is up, it federates with the cloud. When the internet drops, you don't even notice — the system switches to local mode, and the AI, the file library, the neighbourhood marketplace, and the local chat all keep working.
26
+
27
+ The architecture is built around one idea: a **capability bus**. Every node announces what it can do — run inference, store files, hold a vector index, relay messages. Every request finds the best node for the job. New service? Plug it in. New transport — LoRa, mesh radio? Plug it in below. The kernel stays small. The system gets stronger as the community grows.
28
+
29
+ For the hackathon, we demo the full loop live: a mesh of three real nodes on stage, LLM routing across them, RAG over an emergency PDF library, a community marketplace, and a clean fail-over when we unplug the WAN cable. Phase 2 brings real-distance transports and federated learning across communities. Phase 3 explores actual distributed inference.
30
+
31
+ The cloud owns AI today. HearthNet is the bet that communities will own it tomorrow.
32
+
33
+ ---
34
+
35
+ ## 1. Executive summary
36
+
37
+ HearthNet is a peer-to-peer software stack that lets a small number of devices on the same network (or, later, the same neighbourhood) discover each other, share compute and storage, and provide AI services to each other and to thin clients. The system is designed to keep working when the wider internet does not.
38
+
39
+ The technical core is a **capability bus**: a small, transport-agnostic routing layer that knows which nodes can fulfil which request, picks the best one, enforces a schema contract, handles backpressure, and reports health. Everything else — the LLM, the RAG, the file share, the marketplace, the UI — is a plug-in.
40
+
41
+ The MVP is a single-binary Python application that runs on Linux, macOS, and Windows, exposes a Gradio web UI on `localhost:7860`, joins a LAN mesh via mDNS, and uses llama.cpp or Ollama for inference. The demo runs on three machines: a workstation with a GPU, a laptop, and a Raspberry Pi acting as a thin client.
42
+
43
+ Post-hackathon the project has three viable commercial paths: retail-continuity offering, a municipal/civil-defence pilot in NRW, and a "HearthNet-in-a-Box" appliance for community groups.
44
+
45
+ ---
46
+
47
+ ## 2. Vision & positioning
48
+
49
+ ### 2.1 The problem we're solving
50
+
51
+ Modern households are now utterly dependent on cloud AI. The same is increasingly true for businesses, schools, and emergency services. When the cable, the DSL line, or the cloud provider drops, productivity stops. Communities have no fallback.
52
+
53
+ At the same time, the average household has multiple idle computers — a gaming PC at 5% utilisation, a workstation that runs Slack, an old laptop in a drawer. Aggregated across a neighbourhood, this is a non-trivial amount of compute. None of it cooperates today.
54
+
55
+ ### 2.2 What HearthNet is
56
+
57
+ A peer-to-peer, local-first AI fabric that:
58
+
59
+ - Discovers nodes automatically on the local network
60
+ - Routes AI/data requests to the best available node
61
+ - Tolerates partitions, internet outages, and node churn
62
+ - Federates with the cloud when available, falls back gracefully when not
63
+ - Is owned by its participants — no central operator, no telemetry pipeline to a vendor
64
+
65
+ ### 2.3 What HearthNet is not
66
+
67
+ - Not a replacement for high-end cloud AI on always-online workloads
68
+ - Not a competitor to Tor or I2P — anonymity is not a goal
69
+ - Not Petals — distributed-tensor inference is an experimental Phase 3 explore, not the core
70
+ - Not a blockchain. There are no tokens, no consensus across communities, no incentive design beyond reciprocity
71
+ - Not magic. It will not let you run GPT-4-class models on a Raspberry Pi
72
+
73
+ ### 2.4 Differentiation
74
+
75
+ Most hackathon AI projects today use cloud APIs and are dead the moment the API goes down or runs out of credits. HearthNet's whole point is the opposite: it gets *more* useful as the network gets less reliable.
76
+
77
+ ---
78
+
79
+ ## 3. Goals & non-goals
80
+
81
+ ### 3.1 Primary goals (P0)
82
+
83
+ - Zero-configuration discovery on a LAN
84
+ - Capability-based service routing across nodes
85
+ - One real AI service (LLM inference) routed across at least 3 nodes
86
+ - One real data service (RAG over a small PDF corpus)
87
+ - Persistent local marketplace with offline-tolerant sync
88
+ - A clean emergency-mode UX triggered by WAN failure
89
+ - A live topology visualisation suitable for stage demo
90
+ - Single-binary install on Linux, macOS, Windows
91
+
92
+ ### 3.2 Secondary goals (P1)
93
+
94
+ - Mobile-friendly client that connects to a host node
95
+ - Content-addressed file sharing with chunk-level dedup
96
+ - Cross-community federation over the internet when available
97
+ - Embedded skill library reuse from existing FORGE work
98
+
99
+ ### 3.3 Stretch goals (P2)
100
+
101
+ - One experimental Petals-style distributed-layer demo on a small model (1.5B or smaller), as a feature flag
102
+ - LoRa beacon for "node alive" pings over distance, no AI traffic
103
+ - Translation service for German ↔ English ↔ Plattdeutsch
104
+
105
+ ### 3.4 Explicit non-goals (this release)
106
+
107
+ - Full distributed-tensor inference for production use
108
+ - WireGuard or Tailscale overlay (use plain TLS on LAN)
109
+ - Anonymous routing (Tor-style)
110
+ - Cryptocurrency, token, or financial-incentive layer
111
+ - Sub-millisecond latency for any operation
112
+ - Replacing professional emergency-response systems
113
+ - Storing personally-identifying data centrally anywhere
114
+
115
+ ---
116
+
117
+ ## 4. The demo loop
118
+
119
+ The full hackathon demo is one continuous two-minute story, scripted to hit every feature exactly once. Build only what this story needs; everything else is a slide.
120
+
121
+ ### 4.1 Setup on stage
122
+
123
+ - Three physical machines: workstation with GPU ("**Forge**"), laptop ("**Hearth**"), Raspberry Pi 5 ("**Spark**")
124
+ - One travel router with a clearly-visible WAN cable
125
+ - All three nodes pre-joined to a community called `niederrhein-demo`
126
+ - A pre-loaded RAG corpus: 6 PDFs covering rainwater purification, generator safety, first aid, German civil-defence procedure, and a Sankt-Martin children's song book
127
+ - Three pre-populated marketplace posts so the page is not empty on open
128
+
129
+ ### 4.2 The script (~120 seconds)
130
+
131
+ | t | What happens | What it demonstrates |
132
+ |---|---|---|
133
+ | 0:00 | Open the Gradio UI on the laptop. Topology shows 3 connected nodes, green | Discovery works |
134
+ | 0:10 | Ask: *"Wie reinige ich Regenwasser ohne Strom?"* | LLM + RAG over local PDFs |
135
+ | 0:15 | Animated edge from Hearth → Forge → Hearth as the request routes and streams back | Capability routing visible |
136
+ | 0:35 | Open marketplace tab, post: *"Suche Wasserkanister, 20L"* | Marketplace + signed events |
137
+ | 0:50 | **Yank the WAN cable** | Trigger |
138
+ | 0:54 | Banner appears: *"INTERNET OFFLINE — LOKAL AKTIV"*, UI re-skins amber | Emergency mode |
139
+ | 1:00 | Same question, different phrasing | Still works, now visibly local |
140
+ | 1:20 | Send a chat message to "Frank" (Spark node) — store-and-forward across mesh | Local comms |
141
+ | 1:35 | Plug WAN cable back in | Trigger |
142
+ | 1:40 | Banner clears, federation event log replays, new cloud-side node appears greying-in | Reconciliation |
143
+ | 1:55 | Closing line | — |
144
+
145
+ ### 4.3 Design implications of the demo
146
+
147
+ - The topology viz must animate request flow, not just node presence
148
+ - The emergency banner must trigger in under 5 seconds
149
+ - Marketplace posts must be content-addressed and signed so the rejoin merge has something to demonstrate
150
+ - The LLM must stream tokens — silence for 10 seconds while a model loads will lose the room
151
+ - A "fake mesh" mode is needed for dry runs (and as a fallback if something dies on stage)
152
+
153
+ ---
154
+
155
+ ## 5. System architecture
156
+
157
+ ### 5.1 Layered model
158
+
159
+ ```
160
+ ┌──────────────────────────────────────────────────────────────┐
161
+ │ L5 — Application │
162
+ │ Gradio dashboard · topology viz · emergency UX · mobile │
163
+ ├──────────────────────────────────────────────────────────────┤
164
+ │ L4 — Service plane │
165
+ │ LLM · RAG · files · marketplace · chat · embeddings │
166
+ ├══════════════════════════════════════════════════════════════┤
167
+ │ L3 — CAPABILITY BUS ← the integration point │
168
+ │ Registry · router · health · schema · backpressure │
169
+ ├══════════════════════════════════════════════════════════════┤
170
+ │ L2 — Messaging │
171
+ │ RPC · pub-sub · streams · content-addressed chunks │
172
+ ├──────────────────────────────────────────────────────────────┤
173
+ │ L1 — Identity & discovery │
174
+ │ Device keys · signed manifests · mDNS · UDP · DHT later │
175
+ ├──────────────────────────────────────────────────────────────┤
176
+ │ L0 — Physical transport │
177
+ │ LAN/WiFi · ethernet · hotspot · internet relay · LoRa │
178
+ └──────────────────────────────────────────────────────────────┘
179
+ Trust & federation (signed community manifests) cross-cut L1–L4
180
+ Observability (logs, traces, metrics) cross-cut all layers
181
+ ```
182
+
183
+ ### 5.2 Loose coupling, in one rule
184
+
185
+ > No service knows about a transport. No transport knows about a service. Both speak only to the capability bus.
186
+
187
+ This is the only structural rule that matters. If a feature requires a service to import a transport module, the design is wrong and the feature should be redesigned to register a new capability instead.
188
+
189
+ ### 5.3 Process model
190
+
191
+ A HearthNet node is **one process** by default. Internally it runs:
192
+
193
+ - The L1 discovery loop (asyncio task)
194
+ - The L2 messaging server (FastAPI on a configurable port, default `:7080`)
195
+ - The L3 capability bus
196
+ - One or more L4 services as in-process modules registered with the bus
197
+ - The L5 Gradio app on a separate port (default `:7860`)
198
+
199
+ Services *may* run out of process and connect to the bus over local IPC, for sandboxing or because they need a different runtime (e.g. llama.cpp in C++). This is supported but not required for MVP.
200
+
201
+ ### 5.4 Node profiles
202
+
203
+ | Profile | Hardware | Services it runs | Network role |
204
+ |---|---|---|---|
205
+ | **Anchor** | GPU workstation, ≥32GB RAM, ≥1TB disk | LLM, RAG, files, marketplace, chat, embeddings | Provider |
206
+ | **Hearth** | Laptop, 16GB RAM | RAG, files, marketplace, chat, embeddings | Mixed |
207
+ | **Spark** | Raspberry Pi 4/5, mobile, browser | Chat, marketplace UI, file cache | Client |
208
+ | **Bridge** | Cloud VM | None inferring, only relay & federation | Relay (Phase 2) |
209
+
210
+ A node decides its profile at startup based on detected hardware, but the user can override.
211
+
212
+ ---
213
+
214
+ ## 6. Layered specification
215
+
216
+ ### 6.1 L0 — Physical transport
217
+
218
+ The system runs over whatever IP transport is present. No L0 abstraction is exposed to higher layers beyond "is internet up" and "is LAN up". MVP supports:
219
+
220
+ - WiFi on the local subnet
221
+ - Ethernet
222
+ - Mobile hotspot (one node acts as router)
223
+ - Internet relay (Phase 2: an HTTPS relay node helps two NAT'd peers reach each other)
224
+ - LoRa beacons (Phase 3: one-way "I am alive" pings only, no data)
225
+
226
+ Heuristics for "is internet up":
227
+
228
+ 1. DNS resolve two unrelated anchors (`1.1.1.1`, `8.8.8.8`)
229
+ 2. HTTPS HEAD to two unrelated anchors with short timeouts
230
+ 3. ICMP if available, but never relied on
231
+ 4. Both must succeed within 3 seconds to count as "up"
232
+
233
+ The detector runs every 10 seconds when up, every 2 seconds when down (to detect restore quickly).
234
+
235
+ ### 6.2 L1 — Identity & discovery
236
+
237
+ #### 6.2.1 Device keys
238
+
239
+ Each node generates an Ed25519 keypair on first run. Stored in `~/.hearthnet/keys/` with `0600` permissions. The private key never leaves the device. The public key is the node's permanent ID.
240
+
241
+ Display form for humans: first 8 bytes of the public key, base32-encoded, formatted as `XXXX-XXXX-XXXX-XXXX`. Long enough to avoid collisions in a community, short enough to read aloud.
242
+
243
+ #### 6.2.2 Node manifest
244
+
245
+ A signed JSON document describing what this node is and what it can do. Re-signed and re-broadcast on any change. Schema in §7.1.
246
+
247
+ #### 6.2.3 Community manifest
248
+
249
+ A signed JSON document describing the community: name, root key, members, policies. Signed by the root key (the community founder's device key). New members are added by appending a signed invite event. Schema in §8.3.
250
+
251
+ #### 6.2.4 Discovery transports
252
+
253
+ - **mDNS / Zeroconf** — primary, works out of the box on LAN. Service type: `_hearthnet._tcp.local.`
254
+ - **UDP broadcast** — secondary, for networks that block mDNS. Multicast group `239.255.42.42:42424`. Payload: a one-line manifest summary
255
+ - **DHT (Kademlia)** — Phase 2, for cross-LAN discovery via internet relay
256
+ - **LoRa beacon** — Phase 3, for long-distance "this community exists" pings
257
+
258
+ Discovery flow:
259
+
260
+ 1. Node starts, generates manifest, signs it
261
+ 2. Broadcasts via all available discovery transports
262
+ 3. Listens for other manifests
263
+ 4. For each new node: verify signature against community manifest (if same community), then establish an L2 connection
264
+ 5. Send a probe RPC: get health, latency, declared capabilities
265
+ 6. Register the remote capabilities locally with provenance
266
+
267
+ ### 6.3 L2 — Messaging
268
+
269
+ #### 6.3.1 Wire protocol
270
+
271
+ Plain HTTP/1.1 over TLS for MVP. Connection per peer, reused. Headers carry capability name, request ID, and signature. Body is JSON (or binary for chunks). Streaming responses use Server-Sent Events.
272
+
273
+ Phase 2 considers HTTP/3 (QUIC) for better mobile and lossy-link behaviour, especially for streamed token output. The capability bus does not care which is used.
274
+
275
+ #### 6.3.2 Message types
276
+
277
+ - **Request/reply** — one-shot RPC, standard pattern
278
+ - **Stream** — server-streams a sequence of frames (LLM tokens, file chunks, progress events)
279
+ - **Pub-sub** — fire-and-forget event topic with subscription, used for manifest updates and marketplace events
280
+ - **Chunk transfer** — bulk binary, content-addressed, may be parallel from multiple sources
281
+
282
+ #### 6.3.3 Content-addressed storage
283
+
284
+ Files larger than 64KB are split into 256KB chunks. Each chunk is hashed with BLAKE3. The file is described by a small **manifest** listing chunk CIDs and the merkle root.
285
+
286
+ Nodes advertise which CIDs they hold. When a node needs a file, it asks the bus for sources by CID, then fetches chunks in parallel.
287
+
288
+ #### 6.3.4 Backpressure
289
+
290
+ Every stream has a flow-control window (frames-in-flight). Servers stop sending when the window is full; clients refresh the window with ACK frames. Default window: 16 frames. Token streams use this so a slow client doesn't blow up server memory.
291
+
292
+ #### 6.3.5 Retries
293
+
294
+ Idempotent requests retry up to 3 times with exponential backoff. Non-idempotent requests (anything mutating, e.g. marketplace post) carry a client-generated UUID so the server can dedupe.
295
+
296
+ ### 6.4 L3 — Capability bus
297
+
298
+ This is the part of the system that justifies the whole project. Spec in §11.
299
+
300
+ ### 6.5 L4 — Service plane
301
+
302
+ Each service is a Python module that implements a small interface:
303
+
304
+ ```python
305
+ class Service(Protocol):
306
+ name: str
307
+ version: str
308
+ def capabilities(self) -> list[CapabilityDescriptor]: ...
309
+ async def handle(self, capability: str, payload: dict) -> dict | AsyncIterator[dict]: ...
310
+ ```
311
+
312
+ Services in §12.
313
+
314
+ ### 6.6 L5 — Application plane
315
+
316
+ The Gradio web UI is the primary interface for MVP. Mobile is a thin web client (no native app for hackathon). The dashboard is the only UI surface — there is no separate admin interface. Power users get a CLI (`hearthnet status`, `hearthnet capability list`, etc.).
317
+
318
+ ---
319
+
320
+ ## 7. Capability contract — the key abstraction
321
+
322
+ This is the most important section. If anything in this PRD is wrong, fix this last. If anything is right, build this first.
323
+
324
+ ### 7.1 Node manifest schema
325
+
326
+ ```json
327
+ {
328
+ "version": 1,
329
+ "node_id": "ed25519:7H4G-Y9KL-2P3M-X8QR",
330
+ "display_name": "garage-pc",
331
+ "community_id": "ed25519:NIEDERRHEIN-DEMO-...",
332
+ "profile": "anchor",
333
+ "endpoints": [
334
+ {"transport": "https", "host": "192.168.188.25", "port": 7080}
335
+ ],
336
+ "hardware": {
337
+ "gpu": "RTX 5090",
338
+ "vram_gb": 32,
339
+ "ram_gb": 128,
340
+ "cpu_cores": 24,
341
+ "disk_free_gb": 4000
342
+ },
343
+ "capabilities": [
344
+ {
345
+ "name": "llm.chat",
346
+ "version": "1.0",
347
+ "params": {
348
+ "model": "qwen2.5-7b-instruct",
349
+ "quant": "q4_k_m",
350
+ "ctx": 8192,
351
+ "modality": ["text"]
352
+ },
353
+ "schema_hash": "blake3:..."
354
+ },
355
+ {
356
+ "name": "rag.query",
357
+ "version": "1.0",
358
+ "params": {"corpus": "niederrhein-emergency", "k_max": 20},
359
+ "schema_hash": "blake3:..."
360
+ }
361
+ ],
362
+ "uptime_seconds": 43210,
363
+ "load": {"cpu": 0.12, "vram_used_gb": 6.4},
364
+ "issued_at": "2026-05-26T08:14:22Z",
365
+ "expires_at": "2026-05-26T08:14:52Z",
366
+ "signature": "ed25519:..."
367
+ }
368
+ ```
369
+
370
+ Notes:
371
+
372
+ - Manifests **expire** in 30 seconds. A node re-broadcasts before expiry. This is the heartbeat.
373
+ - `schema_hash` is the hash of the request/response JSON schema for that capability. Two nodes with the same hash speak the exact same contract.
374
+ - `load` is advisory; the router uses it to pick under-loaded nodes.
375
+
376
+ ### 7.2 Capability descriptor schema
377
+
378
+ ```json
379
+ {
380
+ "name": "llm.chat",
381
+ "version": "1.0",
382
+ "stability": "stable",
383
+ "request_schema": { /* JSON Schema */ },
384
+ "response_schema": { /* JSON Schema */ },
385
+ "stream": true,
386
+ "params": {
387
+ "model": "qwen2.5-7b-instruct",
388
+ "quant": "q4_k_m",
389
+ "ctx": 8192
390
+ },
391
+ "guarantees": {
392
+ "max_latency_ms_p50": 1200,
393
+ "max_concurrent": 4
394
+ }
395
+ }
396
+ ```
397
+
398
+ `name` is a dotted namespace (`llm.*`, `rag.*`, `file.*`, `market.*`, `chat.*`, `embed.*`, `ocr.*`, `tts.*`, `stt.*`, `trans.*`).
399
+
400
+ `version` is semver, but only major.minor — patch is irrelevant on the wire.
401
+
402
+ `stability` is `experimental`, `beta`, or `stable`. Clients can filter.
403
+
404
+ ### 7.3 Wire format — request
405
+
406
+ ```http
407
+ POST /bus/v1/call HTTP/1.1
408
+ Host: 192.168.188.25:7080
409
+ Content-Type: application/json
410
+ X-HearthNet-Capability: llm.chat
411
+ X-HearthNet-Capability-Version: 1.0
412
+ X-HearthNet-Request-Id: 01HXR8...
413
+ X-HearthNet-From: ed25519:CLIENT-NODE-ID
414
+ X-HearthNet-Signature: ed25519:...
415
+ Accept: application/json, text/event-stream
416
+
417
+ {
418
+ "params": {"model": "qwen2.5-7b-instruct", "ctx": 8192},
419
+ "input": {
420
+ "messages": [
421
+ {"role": "user", "content": "Wie reinige ich Regenwasser ohne Strom?"}
422
+ ],
423
+ "max_tokens": 512,
424
+ "temperature": 0.7
425
+ }
426
+ }
427
+ ```
428
+
429
+ ### 7.4 Wire format — non-stream response
430
+
431
+ ```http
432
+ HTTP/1.1 200 OK
433
+ Content-Type: application/json
434
+ X-HearthNet-Request-Id: 01HXR8...
435
+ X-HearthNet-From: ed25519:SERVER-NODE-ID
436
+ X-HearthNet-Signature: ed25519:...
437
+
438
+ {
439
+ "output": {
440
+ "message": {"role": "assistant", "content": "..."}
441
+ },
442
+ "meta": {
443
+ "tokens_in": 42,
444
+ "tokens_out": 178,
445
+ "ms": 1834,
446
+ "model": "qwen2.5-7b-instruct"
447
+ }
448
+ }
449
+ ```
450
+
451
+ ### 7.5 Wire format — stream response
452
+
453
+ ```http
454
+ HTTP/1.1 200 OK
455
+ Content-Type: text/event-stream
456
+ X-HearthNet-Request-Id: 01HXR8...
457
+ X-HearthNet-From: ed25519:SERVER-NODE-ID
458
+
459
+ event: token
460
+ data: {"text":"Sie"}
461
+
462
+ event: token
463
+ data: {"text":" können"}
464
+
465
+ event: token
466
+ data: {"text":" Regenwasser"}
467
+
468
+ event: done
469
+ data: {"tokens_out":3,"ms":380,"signature":"ed25519:..."}
470
+ ```
471
+
472
+ ### 7.6 Wire format — error
473
+
474
+ ```http
475
+ HTTP/1.1 503 Service Unavailable
476
+ X-HearthNet-Request-Id: 01HXR8...
477
+
478
+ {
479
+ "error": "capacity_exceeded",
480
+ "retry_after_ms": 2000,
481
+ "alt_capabilities": ["llm.chat@0.9"],
482
+ "alt_nodes": ["ed25519:OTHER-ANCHOR-NODE-ID"]
483
+ }
484
+ ```
485
+
486
+ Error codes are a closed set: `not_found`, `capacity_exceeded`, `schema_mismatch`, `unauthorized`, `revoked`, `internal_error`, `not_implemented`, `timeout`, `partition`.
487
+
488
+ ### 7.7 Versioning rules
489
+
490
+ - Major version bump → breaking change. Old clients must be rejected with `schema_mismatch`.
491
+ - Minor version bump → additive. Old clients still work, new fields are optional.
492
+ - Two nodes match on capability if `name` matches and `version` major is equal and the requested version minor ≤ offered version minor.
493
+ - `schema_hash` is computed from the canonical (sorted-key, no-whitespace) JSON of the request+response schemas. Two nodes with identical hashes can call each other with zero coordination.
494
+
495
+ ### 7.8 Capability discovery flow
496
+
497
+ 1. Client wants to do `llm.chat`
498
+ 2. Asks local bus: "who offers `llm.chat@>=1.0`?"
499
+ 3. Bus returns a ranked list of remote nodes that meet the criteria
500
+ 4. Client picks the top one (or the bus does — see §11)
501
+ 5. Client sends the request with the chosen node's signature requirement
502
+ 6. Server validates, executes, replies (or streams)
503
+ 7. Bus records latency, success/failure, updates ranking
504
+
505
+ ---
506
+
507
+ ## 8. Identity, trust & federation
508
+
509
+ ### 8.1 Trust model in one paragraph
510
+
511
+ Trust is **community-scoped**. A community has a root key (the founder's device key). Members are added by signed invite events. To join, a new device generates a key, presents its public key to an existing member (in person, via QR code), and receives a signed invite. The invite is a signed event appended to the community log. The new device is now a member. All capability calls within the community are signed; signatures are checked against the community member list.
512
+
513
+ There are no certificate authorities, no PKI, no chains of trust. This is good enough for a neighbourhood. It is not good enough for the whole internet, and that is fine.
514
+
515
+ ### 8.2 Trust levels
516
+
517
+ | Level | Meaning | Who can be this |
518
+ |---|---|---|
519
+ | `unknown` | Just discovered, not in any community | Random discoverable nodes |
520
+ | `member` | Signed in to this community | Default for invited devices |
521
+ | `trusted` | Marked by 3+ members as trusted | Used for risky capabilities (file delete, federation gateway) |
522
+ | `anchor` | Marked by the root key as infrastructure | Always-on, primary providers |
523
+
524
+ A node's level changes via signed events. Demoting needs more signatures than promoting (3 to demote a `trusted`, 1 to promote to `trusted`).
525
+
526
+ ### 8.3 Community manifest schema
527
+
528
+ ```json
529
+ {
530
+ "version": 1,
531
+ "community_id": "ed25519:...",
532
+ "name": "Niederrhein Demo",
533
+ "root_key": "ed25519:...",
534
+ "created_at": "2026-05-26T08:00:00Z",
535
+ "policy": {
536
+ "min_signatures_to_invite": 1,
537
+ "min_signatures_to_demote": 3,
538
+ "capability_token_ttl_seconds": 86400,
539
+ "federation_enabled": true
540
+ },
541
+ "members": [
542
+ {"node_id": "ed25519:...", "level": "anchor", "added_at": "..."},
543
+ {"node_id": "ed25519:...", "level": "member", "added_at": "..."}
544
+ ],
545
+ "signature": "ed25519:..."
546
+ }
547
+ ```
548
+
549
+ The manifest is the result of replaying the community event log; it is materialised so new nodes don't have to replay everything to join.
550
+
551
+ ### 8.4 Capability tokens
552
+
553
+ Optional layer for fine-grained delegation. A node can issue a short-lived token allowing a specific other node to make a specific capability call. Used in Phase 2 for federation across communities: community A's anchor signs a token allowing community B's anchor to query its RAG. MVP does not use tokens; signing is per-request.
554
+
555
+ ### 8.5 Revocation
556
+
557
+ To revoke a member, three other members publish a signed `revoke` event. The community manifest is regenerated. All other nodes update their local copy and refuse to honour signatures from the revoked node going forward.
558
+
559
+ There is no online revocation list. The community manifest itself is the revocation mechanism.
560
+
561
+ ### 8.6 Federation between communities (Phase 2)
562
+
563
+ Two communities pair when their root keys cross-sign a federation manifest. Federation grants specific capabilities (e.g. "you may query our RAG, but not our marketplace"). Federated calls travel via a Bridge node or a public relay.
564
+
565
+ ### 8.7 Threat model (MVP)
566
+
567
+ In scope:
568
+
569
+ - **Drop-in node**: a random LAN device tries to join; rejected, not a member
570
+ - **Stale manifest replay**: old signed manifest re-broadcast; rejected by expiry
571
+ - **Single member compromised**: can act as themselves but cannot promote others without colluders; revocable
572
+ - **Network observer**: sees who talks to whom; we accept this (no anonymity goal)
573
+
574
+ Out of scope:
575
+
576
+ - **Root key compromised**: catastrophic; community must regenerate
577
+ - **Sybil at community level**: not protected against — communities are trust roots, not Sybil-resistant
578
+ - **Side-channel attacks**: not protected against on shared hardware
579
+ - **Malicious model output**: not protected against; this is a content policy problem, not a protocol one
580
+
581
+ ---
582
+
583
+ ## 9. Discovery in detail
584
+
585
+ ### 9.1 mDNS service definition
586
+
587
+ ```
588
+ Service type: _hearthnet._tcp.local.
589
+ Instance name: <display_name>-<short_node_id>
590
+ Port: 7080
591
+ TXT records:
592
+ v=1
593
+ node=<short_node_id>
594
+ community=<short_community_id>
595
+ profile=anchor|hearth|spark|bridge
596
+ caps=llm.chat,rag.query,file.read,...
597
+ manifest_url=https://<host>:<port>/manifest
598
+ ```
599
+
600
+ `caps` lists capability names only. Full descriptors are fetched via `manifest_url`.
601
+
602
+ ### 9.2 UDP broadcast format
603
+
604
+ Plain JSON line, ≤ 1KB, on `239.255.42.42:42424`:
605
+
606
+ ```json
607
+ {"v":1,"node":"short_id","community":"short_id","port":7080,"caps":["llm.chat","rag.query"]}
608
+ ```
609
+
610
+ Rate: every 5 seconds when discovering, every 30 seconds when stable.
611
+
612
+ ### 9.3 Internet-relay discovery (Phase 2)
613
+
614
+ A small relay node accepts manifest registrations from communities and serves a "members of community X seen recently" query. Used to bootstrap cross-LAN federation. Anyone can run a relay; communities decide which to trust.
615
+
616
+ ### 9.4 LoRa beacon (Phase 3)
617
+
618
+ 868MHz (EU) or 915MHz (US), short payload: `<community_short_id, node_short_id, seq>`. One way, no AI traffic. Purpose: a phone with a LoRa module knows a HearthNet community exists in range, even with no WiFi.
619
+
620
+ ### 9.5 First-run UX
621
+
622
+ The first time a user runs HearthNet:
623
+
624
+ 1. Generate device key (silent)
625
+ 2. Ask: *Create a new community or join existing?*
626
+ 3. If create: prompt for community name, sign founding manifest. Show a QR code with the community ID and invite policy.
627
+ 4. If join: prompt for QR scan or invite link. Acquire signed invite from an existing member (in person, via the app). Now a member.
628
+
629
+ Total time to first useful state: under 60 seconds.
630
+
631
+ ---
632
+
633
+ ## 10. Messaging & transport detail
634
+
635
+ ### 10.1 Connection lifecycle
636
+
637
+ - Peer discovered via L1
638
+ - Bus initiates TLS handshake (self-signed cert, pinned to the node's key on first contact)
639
+ - Subsequent connections re-use the pinned cert; mismatch = refused + log
640
+ - Idle connections close after 60 seconds
641
+ - Failed reconnect uses exponential backoff capped at 30 seconds
642
+
643
+ ### 10.2 Streaming protocol details
644
+
645
+ LLM token streams use SSE for simplicity (works in browsers, easy to debug, fits HTTP/2). Per-frame format:
646
+
647
+ ```
648
+ event: token
649
+ data: {"text":"...", "logprobs":[...], "stop":false}
650
+
651
+ event: token
652
+ data: {"text":"...", "stop":false}
653
+
654
+ event: done
655
+ data: {"tokens_out":N, "stop_reason":"end", "ms":M}
656
+ ```
657
+
658
+ Clients close the connection to cancel. Servers respect cancellation within 200ms.
659
+
660
+ ### 10.3 Chunk transfer
661
+
662
+ A file with CID `blake3:abc...` is described by a manifest:
663
+
664
+ ```json
665
+ {
666
+ "cid": "blake3:abc...",
667
+ "size": 4824711,
668
+ "chunk_size": 262144,
669
+ "chunks": [
670
+ {"i": 0, "cid": "blake3:..."},
671
+ {"i": 1, "cid": "blake3:..."}
672
+ ]
673
+ }
674
+ ```
675
+
676
+ A client wanting the file:
677
+
678
+ 1. Asks the bus: who has `blake3:abc...`?
679
+ 2. Gets a list of source nodes
680
+ 3. For each chunk, picks a source (round-robin or load-aware), requests it
681
+ 4. Verifies the chunk hash before accepting
682
+ 5. Reassembles when all chunks received
683
+
684
+ This is BitTorrent-lite. About 300 lines of Python. Provides dedup, integrity, and parallel transfer for free.
685
+
686
+ ### 10.4 Pub-sub topics
687
+
688
+ | Topic | Producer | Consumer | Payload |
689
+ |---|---|---|---|
690
+ | `community.member.added` | Any member with invite right | All members | Signed invite event |
691
+ | `community.member.revoked` | 3 members | All members | Signed revoke event |
692
+ | `node.manifest.updated` | Each node | All members | Updated node manifest |
693
+ | `marketplace.post.created` | Posting member | All members | Signed marketplace event |
694
+ | `marketplace.post.expired` | Original poster or auto | All members | Signed expiry event |
695
+ | `chat.message.<recipient>` | Sending member | Recipient | Signed chat message |
696
+ | `emergency.mode.changed` | Each node locally | UI only | `{"online": bool, "since": "..."}` |
697
+ | `federation.peer.added` | Anchor with federation right | All anchors | Signed federation event |
698
+
699
+ All events are signed. All have a Lamport timestamp. All can be replayed.
700
+
701
+ ### 10.5 Backpressure detail
702
+
703
+ Each stream has:
704
+
705
+ - `window_size`: max frames in flight (default 16)
706
+ - `frames_sent`: count
707
+ - `frames_acked`: count
708
+ - When `frames_sent - frames_acked >= window_size`, sender pauses
709
+
710
+ ACK frame:
711
+
712
+ ```
713
+ event: ack
714
+ data: {"upto": 42}
715
+ ```
716
+
717
+ Client sends ACKs every 8 frames received (half-window). If 5 seconds pass with no ACK, sender treats stream as broken.
718
+
719
+ ---
720
+
721
+ ## 11. Capability bus internals
722
+
723
+ ### 11.1 Data structures
724
+
725
+ ```python
726
+ class CapabilityEntry:
727
+ node_id: str
728
+ capability: str # "llm.chat"
729
+ version: tuple[int,int] # (1, 0)
730
+ schema_hash: str
731
+ params: dict
732
+ last_seen: float
733
+ p50_latency_ms: float
734
+ p99_latency_ms: float
735
+ success_rate: float # rolling 100 calls
736
+ in_flight: int
737
+ declared_max_concurrent: int
738
+ ```
739
+
740
+ The bus keeps one of these per (node, capability) pair.
741
+
742
+ ### 11.2 Routing algorithm
743
+
744
+ When a local service or client requests capability `C@V`:
745
+
746
+ ```python
747
+ def route(capability: str, version_req: VersionReq, params: dict) -> CapabilityEntry | None:
748
+ candidates = [
749
+ e for e in registry
750
+ if e.capability == capability
751
+ and version_compatible(e.version, version_req)
752
+ and params_compatible(e.params, params)
753
+ and e.last_seen > now() - 60
754
+ and e.in_flight < e.declared_max_concurrent
755
+ ]
756
+ if not candidates:
757
+ return None
758
+ # Score: lower is better
759
+ def score(e):
760
+ latency = e.p50_latency_ms
761
+ load = e.in_flight / max(e.declared_max_concurrent, 1)
762
+ reliability_penalty = (1 - e.success_rate) * 1000
763
+ return latency * (1 + load) + reliability_penalty
764
+ return min(candidates, key=score)
765
+ ```
766
+
767
+ `params_compatible` is capability-specific. For `llm.chat`, the model name and minimum context length must match. For `rag.query`, the corpus name must match.
768
+
769
+ ### 11.3 Local vs remote
770
+
771
+ If the local node also offers the capability, prefer local unless local load exceeds a threshold (default 80% of `declared_max_concurrent`). This biases toward local execution which is faster and avoids network for offline mode.
772
+
773
+ ### 11.4 Sticky routing
774
+
775
+ For multi-turn capabilities (chat continuations referencing a prior conversation), the bus keeps a session → node binding for the conversation duration. Default TTL: 10 minutes idle.
776
+
777
+ ### 11.5 Health tracking
778
+
779
+ After each call, record:
780
+
781
+ - success / fail
782
+ - latency
783
+ - response size
784
+
785
+ Ideally uses gradio trackio https://github.com/gradio-app/trackio
786
+ Rolling window of last 100 calls per (node, capability). Old entries decayed. A node with success rate < 0.5 over the last 20 calls is **quarantined** (skipped for 60 seconds, then probed).
787
+
788
+ ### 11.6 Schema enforcement
789
+
790
+ Both sides validate against the JSON schema declared in the capability descriptor. Reject mismatches with `schema_mismatch` and the expected `schema_hash`. This is the contract.
791
+
792
+ ### 11.7 Backpressure at the bus level
793
+
794
+ The bus has a max in-flight per (capability, node) pair. When saturated, new requests either:
795
+
796
+ - Queue with a configurable timeout, or
797
+ - Get rejected with `capacity_exceeded` and an `alt_nodes` list
798
+
799
+ MVP: queue with 1s timeout, then reject.
800
+
801
+ ### 11.8 Observability hooks
802
+
803
+ Every call emits a trace event:
804
+
805
+ ```json
806
+ {
807
+ "ts": "2026-05-26T08:14:33.281Z",
808
+ "trace_id": "01HXR8...",
809
+ "capability": "llm.chat",
810
+ "from": "node_short_id_A",
811
+ "to": "node_short_id_B",
812
+ "version": "1.0",
813
+ "result": "ok",
814
+ "ms": 1234,
815
+ "tokens_in": 42,
816
+ "tokens_out": 178
817
+ }
818
+ ```
819
+
820
+ Traces go to a local SQLite ring buffer. Optionally exported to OpenTelemetry in Phase 2.
821
+
822
+ ---
823
+
824
+ ## 12. Services
825
+
826
+ ### 12.1 LLM inference service (`llm.*`)
827
+
828
+ #### Capabilities
829
+
830
+ - `llm.chat@1.0` — multi-turn chat
831
+ - `llm.complete@1.0` — single-shot completion
832
+ - `llm.embed@1.0` — text embeddings (often a separate model)
833
+ - `llm.classify@1.0` — zero-shot classification (Phase 2)
834
+
835
+ #### Backends
836
+
837
+ - llama.cpp server (primary)
838
+ - Ollama (drop-in)
839
+ - vLLM (Phase 2, for batched throughput on the anchor)
840
+ - LM Studio (Christof's existing setup at `192.168.188.25:1234`)
841
+ - HF Inference API (when internet is up, as another route the bus may pick)
842
+ - Anthropic / OpenAI / others (Phase 2, with user-supplied keys)
843
+
844
+ The adapter pattern:
845
+
846
+ ```python
847
+ class LlmBackend(Protocol):
848
+ name: str
849
+ async def chat(self, messages, **params) -> AsyncIterator[Token]: ...
850
+ async def embed(self, texts) -> list[list[float]]: ...
851
+ ```
852
+
853
+ The service module registers one capability per backend × model × quant combination, so the bus sees `llm.chat:qwen2.5-7b@q4`, `llm.chat:qwen2.5-7b@q8`, `llm.chat:gemma-3-9b@q4` as separate things.
854
+
855
+ #### MVP models
856
+
857
+ - `qwen2.5-7b-instruct@q4_k_m` (anchor) — primary chat
858
+ - `qwen2.5-1.5b-instruct@q4` (hearth) — fallback when anchor busy
859
+ - BGE-small embedding model (anchor + hearth) — RAG
860
+ - Christof's existing Proto-Cognitive Architecture v5.2 model as an experimental third option (HybridLLM with PinnedEpisodicStore)
861
+
862
+ #### Resource control
863
+
864
+ - Each backend declares `max_concurrent` based on VRAM
865
+ - Bus respects this hard limit
866
+ - Long requests can be **cancelled** mid-generation by closing the stream
867
+
868
+ ### 12.2 RAG service (`rag.*`)
869
+
870
+ #### Capabilities
871
+
872
+ - `rag.query@1.0` — query a corpus, return chunks with scores
873
+ - `rag.ingest@1.0` — add a document to a corpus (member-only)
874
+ - `rag.list_corpora@1.0` — list local corpora
875
+
876
+ #### Storage
877
+
878
+ - ChromaDB for vectors (local file-based)
879
+ - Documents stored as content-addressed blobs (§10.3)
880
+ - One Chroma collection per corpus
881
+
882
+ #### Corpora
883
+
884
+ - `niederrhein-emergency` — the demo corpus (6 emergency PDFs)
885
+ - `community-knowledge` — user-contributed
886
+ - `personal` — per-user, not shared
887
+
888
+ #### Query flow
889
+
890
+ 1. Embed query (via local `llm.embed` capability, routed by bus)
891
+ 2. Search Chroma top-K
892
+ 3. Return chunks with metadata: source doc CID, page, score
893
+ 4. Caller passes chunks as LLM context
894
+
895
+ #### Ingest flow
896
+
897
+ 1. Member uploads PDF via UI
898
+ 2. PDF parsed (PyPDF2 → text + page numbers)
899
+ 3. Chunked (1000 tokens, 200 overlap)
900
+ 4. Each chunk embedded
901
+ 5. Stored in Chroma with metadata
902
+ 6. Original PDF stored as CID blob, advertised on the chunk service
903
+ 7. `marketplace.knowledge.added` event published
904
+
905
+ ### 12.3 File / chunk service (`file.*`)
906
+
907
+ #### Capabilities
908
+
909
+ - `file.read@1.0` — fetch a chunk by CID
910
+ - `file.list@1.0` — list locally-held CIDs
911
+ - `file.advertise@1.0` — claim to hold a CID (Phase 2: gossip)
912
+ - `file.put@1.0` — accept a chunk (member-only, opt-in)
913
+
914
+ #### Storage layout
915
+
916
+ ```
917
+ ~/.hearthnet/blobs/
918
+ <first2bytes>/<rest of CID>.bin
919
+ ```
920
+
921
+ Sharded for filesystem performance.
922
+
923
+ #### Garbage collection
924
+
925
+ - Default LRU eviction at 80% disk capacity threshold
926
+ - "Pinned" CIDs (user-marked) never evicted
927
+ - Marketplace event log + community manifest are always pinned
928
+
929
+ ### 12.4 Marketplace service (`market.*`)
930
+
931
+ #### Capabilities
932
+
933
+ - `market.list@1.0` — list current posts
934
+ - `market.post@1.0` — create a post (signed)
935
+ - `market.expire@1.0` — mark expired (signed by original poster or after TTL)
936
+ - `market.search@1.0` — semantic search using embeddings
937
+
938
+ #### Data model
939
+
940
+ A post is an **event**:
941
+
942
+ ```json
943
+ {
944
+ "event_type": "market.post.created",
945
+ "event_id": "01HXR8...",
946
+ "lamport": 4218,
947
+ "wall_clock": "2026-05-26T08:14:22Z",
948
+ "author": "ed25519:NODE-ID",
949
+ "community": "ed25519:COMMUNITY-ID",
950
+ "data": {
951
+ "category": "offer|request|info|emergency",
952
+ "title": "Suche Wasserkanister, 20L",
953
+ "body": "...",
954
+ "location": {"lat": 51.5, "lng": 6.2, "label": "Issum"},
955
+ "ttl_seconds": 86400,
956
+ "tags": ["wasser","notfall"]
957
+ },
958
+ "signature": "ed25519:..."
959
+ }
960
+ ```
961
+
962
+ This is EBKH-shaped on purpose. Reuse the event sourcing patterns Christof already built.
963
+
964
+ #### Sync semantics
965
+
966
+ Append-only log. Lamport timestamps for ordering. CRDT-style merge on rejoin: replay events in Lamport order, dedupe by `event_id`. Last-writer-wins on conflicting updates to the same post (rare, since posts are mostly create+expire).
967
+
968
+ ### 12.5 Chat service (`chat.*`)
969
+
970
+ #### Capabilities
971
+
972
+ - `chat.send@1.0` — send a direct message (signed)
973
+ - `chat.history@1.0` — local history retrieval
974
+ - `chat.thread@1.0` — group conversation (Phase 2)
975
+
976
+ #### Delivery
977
+
978
+ - Direct messages are signed, addressed by recipient node ID
979
+ - If recipient is online, deliver directly
980
+ - If recipient is offline, **store-and-forward**: encrypted blob held by 2 randomly-chosen anchor nodes, delivered when recipient reconnects
981
+ - Read receipts are signed events
982
+
983
+ #### Encryption
984
+
985
+ MVP: TLS at transport, signed at app layer, no end-to-end encryption between users. Acceptable inside a trusted community.
986
+
987
+ Phase 2: optional E2E using X25519 + ChaCha20Poly1305. Signal-style ratchet deferred to Phase 3.
988
+
989
+ ### 12.6 Embedding service (`embed.*`)
990
+
991
+ Separated from `llm.*` because embeddings have different scaling characteristics (small model, high throughput, often batch).
992
+
993
+ Capabilities:
994
+
995
+ - `embed.text@1.0` — embed a list of strings
996
+ - `embed.image@1.0` — embed an image (Phase 2, CLIP)
997
+
998
+ ### 12.7 OCR service (Phase 2, `ocr.*`)
999
+
1000
+ For ingesting scanned PDFs and photos of documents (emergency notices on lampposts, hand-written notes).
1001
+
1002
+ Backends: Tesseract for MVP, TrOCR for handwriting.
1003
+
1004
+ ### 12.8 Translation service (Phase 2, `trans.*`)
1005
+
1006
+ German ↔ English ↔ Plattdeutsch (the Niederrhein angle).
1007
+
1008
+ Backends: NLLB for general, optional fine-tune for Plattdeutsch (likely a Christof project).
1009
+
1010
+ ### 12.9 Speech services (Phase 2, `tts.*` `stt.*`)
1011
+
1012
+ - Whisper for STT
1013
+ - Edge-TTS or XTTS-v2 for TTS (Christof already has the XTTS pipeline from his podcast generator)
1014
+
1015
+ ### 12.10 Image services (Phase 2, `img.*`)
1016
+
1017
+ - Florence-2 for captioning (Christof's pipeline)
1018
+ - FLUX.1-dev LoRA for generation (Christof's pipeline)
1019
+ - Particularly useful for "describe this damage photo" emergency use cases
1020
+
1021
+ ---
1022
+
1023
+ ## 13. Emergency mode
1024
+
1025
+ ### 13.1 Detection
1026
+
1027
+ A small daemon runs in every node. Every 10 seconds when believed-online, every 2 seconds when believed-offline.
1028
+
1029
+ Probes:
1030
+
1031
+ 1. DNS resolve `cloudflare.com` and `quad9.net`
1032
+ 2. HTTPS HEAD `https://1.1.1.1/cdn-cgi/trace` and `https://www.google.com/generate_204`
1033
+ 3. All four with 2-second timeouts
1034
+ 4. Online = ≥3 of 4 succeed
1035
+
1036
+ State machine:
1037
+
1038
+ - `ONLINE` → `DEGRADED` (one probe failed) → `OFFLINE` (≥2 failed for 30s)
1039
+ - `OFFLINE` → `ONLINE` directly when all 4 succeed for 10s
1040
+
1041
+ Each transition publishes `emergency.mode.changed` locally.
1042
+
1043
+ ### 13.2 UX changes when offline
1044
+
1045
+ - Top banner: `INTERNET OFFLINE — LOKAL AKTIV` (amber)
1046
+ - Topology graph collapses to local nodes only (cloud-side bridges go grey)
1047
+ - Cloud-routed LLM backends (HF API, Anthropic) drop out of the capability registry
1048
+ - Marketplace shows a "Notfall-Modus" filter prominent
1049
+ - A new tab appears: **Notfall** — direct links to the emergency PDF corpus, neighbour list with last-seen times, generator/water/light shared resources
1050
+ - Chat switches to store-and-forward UI
1051
+
1052
+ ### 13.3 Behavioural changes when offline
1053
+
1054
+ - LLM router prefers local-only models
1055
+ - File transfers stop seeking internet-hosted sources
1056
+ - Federation pause (peer communities cannot be reached)
1057
+ - Discovery rate increases (UDP broadcasts more often, to find newly-arrived neighbours faster)
1058
+
1059
+ ### 13.4 Restore behaviour
1060
+
1061
+ When internet returns:
1062
+
1063
+ 1. Banner clears
1064
+ 2. Re-register cloud capabilities
1065
+ 3. Replay any queued federation events to peer communities
1066
+ 4. Resync marketplace event log with bridge nodes if any
1067
+ 5. Send queued chat messages
1068
+ 6. Optional: notify the user of how many events synced
1069
+
1070
+ ### 13.5 Anti-flapping
1071
+
1072
+ If transitions occur more than 3 times in 60 seconds, system stays in the more pessimistic state for the rest of that window. Prevents banner flicker.
1073
+
1074
+ ---
1075
+
1076
+ ## 14. Reconciliation & sync
1077
+
1078
+ ### 14.1 The event log
1079
+
1080
+ Every community has a single conceptual append-only log. In practice it lives as a SQLite database per node, plus a CID-addressed snapshot file recreated nightly.
1081
+
1082
+ Schema (simplified):
1083
+
1084
+ ```sql
1085
+ CREATE TABLE events (
1086
+ event_id TEXT PRIMARY KEY, -- ULID
1087
+ lamport INTEGER NOT NULL,
1088
+ wall_clock TEXT NOT NULL,
1089
+ community_id TEXT NOT NULL,
1090
+ author_node TEXT NOT NULL,
1091
+ event_type TEXT NOT NULL,
1092
+ data JSON NOT NULL,
1093
+ signature TEXT NOT NULL,
1094
+ received_at TEXT NOT NULL
1095
+ );
1096
+ CREATE INDEX idx_events_lamport ON events(community_id, lamport);
1097
+ CREATE INDEX idx_events_type ON events(community_id, event_type, lamport);
1098
+ ```
1099
+
1100
+ ### 14.2 Materialised views
1101
+
1102
+ Reading the raw log every time is slow. Each node maintains materialised views:
1103
+
1104
+ - `community_manifest` (current member list)
1105
+ - `marketplace_current` (un-expired posts)
1106
+ - `chat_history_per_peer`
1107
+ - `node_health_snapshot`
1108
+
1109
+ Views are rebuilt by replaying events from the last snapshot.
1110
+
1111
+ ### 14.3 Lamport clocks
1112
+
1113
+ Each node maintains a Lamport counter. Every event written or received bumps it:
1114
+
1115
+ ```python
1116
+ def receive(event):
1117
+ lamport = max(self.lamport, event.lamport) + 1
1118
+ store(event)
1119
+ ```
1120
+
1121
+ ### 14.4 Sync protocol
1122
+
1123
+ When node A meets node B:
1124
+
1125
+ 1. A asks B: "what is your highest Lamport per (community, event_type)?"
1126
+ 2. B responds with a vector
1127
+ 3. A computes the delta and sends its missing events
1128
+ 4. B does the same in the other direction
1129
+ 5. Both verify signatures, store events, update materialised views
1130
+
1131
+ This is gossip-based, eventually consistent, and resilient to partition.
1132
+
1133
+ ### 14.5 Conflict resolution
1134
+
1135
+ - **Marketplace post update** (e.g. price change): last-writer-wins by Lamport timestamp
1136
+ - **Member revoke vs. member action**: revoke wins if Lamport(revoke) < Lamport(action); otherwise the action is honoured
1137
+ - **Two communities with same name**: not a conflict — communities are identified by root key, not by name
1138
+
1139
+ ### 14.6 Snapshot & compaction
1140
+
1141
+ Once per night, each node:
1142
+
1143
+ 1. Computes the materialised state at `lamport = current_max - 1000`
1144
+ 2. Writes it as a signed snapshot blob (CID-addressed)
1145
+ 3. Marks events below that Lamport as "snapshot-covered"
1146
+ 4. Optionally garbage-collects old events (configurable; default keeps 30 days)
1147
+
1148
+ New joiners fetch the latest snapshot + recent events, instead of replaying from genesis.
1149
+
1150
+ ---
1151
+
1152
+ ## 15. Application plane
1153
+
1154
+ ### 15.1 UI surfaces
1155
+
1156
+ | Surface | Tech | Purpose |
1157
+ |---|---|---|
1158
+ | Gradio dashboard | Gradio 6.0.0 | Primary local-host UI |
1159
+ | Topology viz | Cytoscape.js inside Gradio | Live mesh state with request animation |
1160
+ | Chat tab | Gradio chat component | Per-peer conversation |
1161
+ | Files tab | Gradio file explorer | Browse + upload CID blobs |
1162
+ | Marketplace tab | Gradio dataframe | Filter, post, search |
1163
+ | Emergency tab | Bespoke layout | Visible only when offline; large buttons |
1164
+ | CLI | Click | `hearthnet status`, `hearthnet caps`, `hearthnet log` |
1165
+ | Mobile web | Vanilla HTML + JS | Lightweight, served from any anchor |
1166
+
1167
+ ### 15.2 Topology visualisation requirements
1168
+
1169
+ - Real-time node list with online/offline indicators
1170
+ - Animated request flow along edges when a call is in flight
1171
+ - Color codes capability per edge (LLM = teal, RAG = purple, file = amber, chat = blue)
1172
+ - Node tooltip shows capabilities, load, latency
1173
+ - Click a node → opens its public manifest in a side panel
1174
+ - Edge thickness scales with recent traffic
1175
+
1176
+ This is the single visual element judges remember. Build it early.
1177
+
1178
+ ### 15.3 Mobile client (lightweight)
1179
+
1180
+ A static HTML+JS file served from any anchor at `/mobile`. Communicates with the host node via the same bus API. No installation; bookmark to home screen.
1181
+
1182
+ Features for MVP: chat, marketplace browse, emergency mode banner, ask-a-question (LLM passthrough). No topology viz on mobile.
1183
+
1184
+ ### 15.4 First-time install UX
1185
+
1186
+ 1. `pip install hearthnet` (or download single binary)
1187
+ 2. `hearthnet init` — generates keys, asks for community
1188
+ 3. `hearthnet run` — starts the node
1189
+ 4. Browser opens to `http://localhost:7860`
1190
+ 5. If joining an existing community, displays a "scan invite QR" screen
1191
+ 6. If creating, displays the new community QR code for others to scan
1192
+
1193
+ Total time: under 2 minutes from download to first message.
1194
+
1195
+ ---
1196
+
1197
+ ## 16. Data model summary
1198
+
1199
+ ### 16.1 Event types (canonical list)
1200
+
1201
+ | Type | Producer | Consumer |
1202
+ |---|---|---|
1203
+ | `community.created` | Founder | All |
1204
+ | `community.member.invited` | Member with right | All |
1205
+ | `community.member.joined` | Joining device | All |
1206
+ | `community.member.revoked` | 3 members | All |
1207
+ | `community.policy.updated` | Root key | All |
1208
+ | `node.manifest.updated` | Each node | All |
1209
+ | `capability.registered` | Each node | Local bus only |
1210
+ | `capability.deregistered` | Each node | Local bus only |
1211
+ | `market.post.created` | Member | All |
1212
+ | `market.post.updated` | Author | All |
1213
+ | `market.post.expired` | Author or auto | All |
1214
+ | `chat.message.sent` | Sender | Recipient |
1215
+ | `chat.message.delivered` | Recipient | Sender |
1216
+ | `chat.message.read` | Recipient | Sender (optional) |
1217
+ | `file.cid.advertised` | Holder | Local bus, then gossip |
1218
+ | `file.cid.unpinned` | Holder | Local bus |
1219
+ | `rag.document.ingested` | Ingester | All members |
1220
+ | `federation.peer.added` | Anchor | All anchors |
1221
+ | `federation.peer.removed` | Anchor | All anchors |
1222
+ | `emergency.mode.changed` | Each node locally | UI only, not in log |
1223
+
1224
+ ### 16.2 Schema versioning
1225
+
1226
+ Every event has a `schema_version`. Old events are kept verbatim; new readers translate via a versioned schema registry. Never rewrite history.
1227
+
1228
+ ### 16.3 Storage locations
1229
+
1230
+ ```
1231
+ ~/.hearthnet/
1232
+ keys/
1233
+ device.ed25519 (private, 0600)
1234
+ device.pub
1235
+ communities/
1236
+ <community_id>/
1237
+ manifest.json (latest signed materialised manifest)
1238
+ events.sqlite (event log)
1239
+ snapshots/<lamport>.bin (signed snapshots)
1240
+ blobs/<aa>/<bb...> (CID-addressed)
1241
+ config.toml
1242
+ logs/<date>.log
1243
+ ```
1244
+
1245
+ ---
1246
+
1247
+ ## 17. Security
1248
+
1249
+ ### 17.1 Cryptographic primitives
1250
+
1251
+ - **Identity**: Ed25519 (signatures)
1252
+ - **Key agreement** (Phase 2 E2E): X25519
1253
+ - **Symmetric** (Phase 2 E2E): ChaCha20-Poly1305
1254
+ - **Hashing**: BLAKE3 for CIDs, SHA-256 for compatibility where needed
1255
+ - **TLS**: rustls or Python `ssl` defaults, TLS 1.3 only
1256
+
1257
+ ### 17.2 Signature scopes
1258
+
1259
+ Every:
1260
+
1261
+ - Node manifest
1262
+ - Capability descriptor (signed as part of the node manifest)
1263
+ - Marketplace event
1264
+ - Chat message
1265
+ - Community manifest (root-signed)
1266
+
1267
+ is signed. Signature verification is **mandatory** on receipt. Unsigned or invalid events are dropped without log spam (single counter increment).
1268
+
1269
+ ### 17.3 Sandboxing
1270
+
1271
+ User-uploaded content (PDFs, images) is processed in subprocess workers with `nice`-restricted resource limits. No `exec` of user-provided data. No URL fetching from user input without explicit allowlist.
1272
+
1273
+ ### 17.4 Rate limiting
1274
+
1275
+ Per (peer, capability):
1276
+
1277
+ - 10 RPS soft limit (responds with `capacity_exceeded`)
1278
+ - 100 RPS hard limit (drops with no response)
1279
+
1280
+ Per (peer, all capabilities):
1281
+
1282
+ - 100 RPS soft, 1000 RPS hard
1283
+
1284
+ ### 17.5 GDPR considerations
1285
+
1286
+ This is a Christof project. GDPR-correct from day one is a requirement.
1287
+
1288
+ - All personal data (chat, marketplace) is local-first. No central server holds it.
1289
+ - Users can run `hearthnet erase` to wipe their event participation (best-effort: their signed events still exist on other nodes, but their device key is destroyed, so they cannot be linked back to a person).
1290
+ - A `personal` corpus in RAG never leaves the device.
1291
+ - Deletion of marketplace posts: a `market.post.expired` event with `reason: "user_request"` is published; consuming nodes hide the original.
1292
+ - Right to data export: `hearthnet export` produces a zip of all local data signed by the user.
1293
+
1294
+
1295
+ ---
1296
+
1297
+ ## 18. Observability
1298
+
1299
+ ### 18.1 Logging
1300
+
1301
+ Structured JSON to `~/.hearthnet/logs/<date>.log`. Levels: `debug`, `info`, `warn`, `error`. Default `info`. Log rotation daily, retention 14 days.
1302
+
1303
+ ### 18.2 Metrics
1304
+
1305
+ Prometheus-format scrape endpoint at `:7080/metrics`:
1306
+
1307
+ - `hearthnet_requests_total{capability, result}`
1308
+ - `hearthnet_request_duration_ms{capability, quantile}`
1309
+ - `hearthnet_nodes_online{community}`
1310
+ - `hearthnet_event_log_size{community}`
1311
+ - `hearthnet_emergency_mode{state}`
1312
+ - `hearthnet_blob_storage_bytes`
1313
+ - `hearthnet_llm_tokens_generated_total{model}`
1314
+
1315
+ ### 18.3 Tracing
1316
+
1317
+ Every bus call gets a trace ID. Traces are stored locally in SQLite (ring buffer, 10k events). Optional OTLP export in Phase 2.
1318
+
1319
+ ### 18.4 Health endpoints
1320
+
1321
+ - `GET /health` — 200 if process alive
1322
+ - `GET /ready` — 200 if at least one peer discovered AND at least one capability registered
1323
+ - `GET /metrics` — Prometheus
1324
+
1325
+ ### 18.5 Self-diagnostics
1326
+
1327
+ `hearthnet doctor` runs a battery of checks:
1328
+
1329
+ - mDNS reachable?
1330
+ - TLS cert valid?
1331
+ - Discovery sending and receiving?
1332
+ - At least one peer visible?
1333
+ - Local services registered?
1334
+ - Disk space healthy?
1335
+ - Recent error rate?
1336
+
1337
+ Returns a coloured report and a non-zero exit code on failure. Drop-in for CI and on-stage troubleshooting.
1338
+
1339
+ ---
1340
+
1341
+ ## 19. Testing strategy
1342
+
1343
+ ### 19.1 Unit
1344
+
1345
+ Every service has unit tests for its capability handlers using a `FakeBus`. Coverage target: 70% on services, 90% on bus.
1346
+
1347
+ ### 19.2 Integration
1348
+
1349
+ A test harness spins up 3 in-process nodes on different ports in the same Python process, with mocked discovery. Integration tests cover:
1350
+
1351
+ - Discovery → manifest exchange → first call
1352
+ - LLM routing prefers low-latency node
1353
+ - Marketplace event syncs after re-connection
1354
+ - File transfer with one chunk source going offline mid-stream
1355
+ - Schema mismatch rejection
1356
+ - Capability quarantine after failures
1357
+
1358
+ ### 19.3 Chaos
1359
+
1360
+ Three real OS-level processes on the same machine, with `tc` (Linux traffic control) introducing latency, packet loss, and partitions. Scenarios:
1361
+
1362
+ - Anchor reboots mid-RAG-query
1363
+ - 70% packet loss for 30 seconds
1364
+ - Network partition where 1 node sees 2 others see each other but not it
1365
+ - Clock skew of ±60 seconds between nodes
1366
+
1367
+ ### 19.4 Demo dry-runs
1368
+
1369
+ Daily in the week before the demo, run the full 2-minute script end to end. Record. Watch for the dead-air moments (model loading, mDNS delay, banner appearance latency). Fix.
1370
+
1371
+ ### 19.5 Adversarial
1372
+
1373
+ - Send malformed manifests
1374
+ - Send manifests signed by a non-member key
1375
+ - Send replayed (old) events
1376
+ - Send oversized payloads
1377
+ - Send valid signatures from a revoked member
1378
+
1379
+ All must fail closed with no leak and no crash.
1380
+
1381
+ ---
1382
+
1383
+ ## 20. Hackathon MVP scope
1384
+
1385
+ ### 20.1 Modules and effort
1386
+
1387
+ | ID | Module | Effort (evening hours) | Reuse from existing work |
1388
+ |---|---|---|---|
1389
+ | M1 | Node identity & manifest | 4–6 | — |
1390
+ | M2 | Discovery (mDNS + UDP) | 4–6 | — |
1391
+ | M3 | Capability bus | 8–12 | NEXUS gateway patterns |
1392
+ | M4 | LLM inference service | 4–6 | LM Studio at 192.168.188.25, FORGE |
1393
+ | M5 | RAG service | 6–8 | Christof's existing RAG pipelines |
1394
+ | M6 | Marketplace service | 4–6 | EBKH event-sourcing patterns |
1395
+ | M7 | File/chunk service | 6–10 | — |
1396
+ | M8 | Gradio dashboard + topology viz | 12–16 | FORGE Spaces patterns |
1397
+ | M9 | Emergency-mode detector | 2–3 | — |
1398
+ | M10 | Chat service | 4–6 | — |
1399
+ | M11 | Embedding service | 2–3 | sentence-transformers, existing |
1400
+ | M12 | CLI (`hearthnet status`, etc.) | 2–4 | — |
1401
+ | M13 | First-run UX + invite QR | 3–5 | — |
1402
+ | **Total** | | **61–91h** | |
1403
+
1404
+ ### 20.2 Build order (demo-driven)
1405
+
1406
+ 1. **M1 + M2** (identity + discovery) — first because nothing works without them
1407
+ 2. **M3** (bus) with a fake echo service — proves the contract
1408
+ 3. **M4** (LLM) plugged in — first real value
1409
+ 4. **M8** (UI shell + topology viz) — connected to bus, shows mocked nodes initially, then real
1410
+ 5. **M5** (RAG) — demo value
1411
+ 6. **M9** (emergency detector) — wire the banner
1412
+ 7. **M6** (marketplace) — reuses EBKH
1413
+ 8. **M10** (chat) — store-and-forward as bonus
1414
+ 9. **M7** (file/chunk) — last; if cut, files just upload to one node
1415
+ 10. **M11–M13** as time allows
1416
+
1417
+ ### 20.3 Risk-driven cuts (if behind schedule)
1418
+
1419
+ In order of "cut first":
1420
+
1421
+ 1. **M7 file/chunk** — keep file upload but single-node only
1422
+ 2. **M10 chat** — show in slides only
1423
+ 3. **M13 first-run UX** — judges don't need to install
1424
+ 4. **M12 CLI** — UI is enough
1425
+ 5. **M11 embeddings as separate service** — fold into M5
1426
+
1427
+ Never cut: M1, M2, M3, M4, M5, M8, M9.
1428
+
1429
+ ### 20.4 Definition of done for the demo
1430
+
1431
+ - [ ] Three real nodes auto-discover each other on the demo LAN
1432
+ - [ ] One full LLM query completes with visible token streaming and visible routing
1433
+ - [ ] One RAG-grounded answer with source citation
1434
+ - [ ] Two marketplace posts visible across all three nodes
1435
+ - [ ] WAN-cable unplug triggers the offline banner in ≤5s
1436
+ - [ ] One question answered while offline using local-only capabilities
1437
+ - [ ] WAN restore triggers reconciliation visibly
1438
+ - [ ] Topology viz updates in real time throughout
1439
+
1440
+ ---
1441
+
1442
+ ## 21. Out of scope for hackathon
1443
+
1444
+ The following are mentioned in the design but **not implemented in MVP**. They are designed-in (no future rewrite needed), just not built yet.
1445
+
1446
+ - WireGuard / Tailscale overlay
1447
+ - LoRa or BLE transports
1448
+ - DHT-based cross-LAN discovery
1449
+ - Petals-style distributed-tensor inference
1450
+ - Federated MoE expert routing across nodes
1451
+ - Cross-community federation
1452
+ - End-to-end encryption of chat between users
1453
+ - Capability tokens (auth is per-request signing only)
1454
+ - OCR, translation, speech, image generation services (designed; not coded)
1455
+ - Mobile native app (web only)
1456
+ - OTLP trace export
1457
+ - The signed nightly snapshot mechanism (events keep accumulating in MVP)
1458
+
1459
+ ---
1460
+
1461
+ ## 22. Phase 2 — post-hackathon (1–3 months)
1462
+
1463
+ ### 22.1 Internet relay & cross-LAN federation
1464
+
1465
+ A small Rust or Python relay any participant can host. Helps NAT'd peers reach each other. Used to bootstrap federation between, e.g., Issum and Geldern communities.
1466
+
1467
+ ### 22.2 Federated learning experiments
1468
+
1469
+ Each anchor periodically computes LoRA gradients on local conversations (consent-required), sends only the gradient deltas to other anchors, averages, applies. A simple version of FedAvg, scoped to LoRA layers of the local LLM. Not full federated learning — practical and scoped.
1470
+
1471
+ ### 22.3 Capability tokens
1472
+
1473
+ OAuth-style short-lived tokens for fine-grained delegation. Especially useful for Bridge nodes between communities.
1474
+
1475
+ ### 22.4 OCR + translation services
1476
+
1477
+ For ingesting paper documents (lamppost notices) and serving the Plattdeutsch / Niederrhein angle.
1478
+
1479
+ ### 22.5 Speech I/O
1480
+
1481
+ STT (Whisper) and TTS (Christof's existing XTTS-v2 + Edge-TTS pipeline). Particularly valuable for elderly community members in an emergency context.
1482
+
1483
+ ### 22.6 Hetzner / IONOS deployment
1484
+
1485
+ A relay tier hosted by Christof at `relay.hearthnet.de`, with the existing PHP 8.3 + Python bridge infrastructure used for ki-fusion-labs. Free for small communities, paid for larger ones (revenue path 1).
1486
+
1487
+ ### 22.7 Mobile native client
1488
+
1489
+ Flutter or React Native. Bypasses the "must keep browser tab open" limitation. Push notifications via the existing relay tier.
1490
+
1491
+ ### 22.8 Marketplace search via embeddings
1492
+
1493
+ `market.search@1.0` registered as a capability. Embed posts on creation, semantic search. Probably <1 day given the infrastructure is there.
1494
+
1495
+ ### 22.9 Federated identity import
1496
+
1497
+ Optional: import an existing identity (HF, GitHub key, etc.) to bootstrap trust. Decouples HearthNet identity from device.
1498
+
1499
+ ### 22.10 Improved topology visualisation
1500
+
1501
+ 3D mesh, request heatmaps, historical replay. Pure polish, but valuable for demos and selling.
1502
+
1503
+ ---
1504
+
1505
+ ## 23. Phase 3 — research-shaped (6–12 months)
1506
+
1507
+ ### 23.1 Distributed-layer inference experiment
1508
+
1509
+ A genuinely-distributed inference path for one specific small model (1.5B–3B), Petals-style, as a feature flag. Acceptable latency probably only on Ethernet-connected nodes within the same household. The point is the demo, not production. Wire it under the existing `llm.chat` capability with a `distributed: true` parameter and a clear latency warning.
1510
+
1511
+ ### 23.2 MoE-style expert routing
1512
+
1513
+ Each community has expert nodes: "the electrician's node has the Schaltplan corpus", "the gardener's node has the Pflanzen knowledge". The router learns which questions to send where. Mix human + AI experts: route a question to a real neighbour as fallback. Connect to the marketplace.
1514
+
1515
+ ### 23.3 LoRa "I exist" beacons
1516
+
1517
+ 868MHz transmitter on an anchor. Phones with LoRa modules learn community exists in range. Useful in real disaster scenarios where WiFi is gone.
1518
+
1519
+ ### 23.4 Christof's research integrations
1520
+
1521
+ - **Proto-Cognitive Architecture v5.2** as an `llm.chat` backend with experimental episodic-memory features
1522
+ - **Hebbian residual memory** experiments on Qwen2.5-1.5B as another backend
1523
+ - **BitNet 1.58-bit** quantised models for very low resource nodes (Pi 5 + USB SSD)
1524
+ - **EBKH** as the evidence layer for marketplace truth-checking (claim-graph for "is this actually safe drinking water?")
1525
+
1526
+ ### 23.5 Civil-defence pilot
1527
+
1528
+ Pilot with one NRW municipality. Bevölkerungsschutz partners. Real test under a planned blackout exercise. This is the credibility-building step toward larger deployments.
1529
+
1530
+ ---
1531
+
1532
+ ## 24. Phase 4 — long-term vision
1533
+
1534
+ A "neighbourhood internet" where:
1535
+
1536
+ - Communities own their compute
1537
+ - Communities federate with adjacent communities
1538
+ - Communities can survive multi-day outages
1539
+ - AI is a community resource like a library or a kitchen, not a subscription
1540
+ - The protocol is open, the implementation is reference, the ecosystem is many
1541
+
1542
+ The grand version of HearthNet looks more like a protocol (think Matrix or ActivityPub) than a product. We are building the reference implementation that proves the protocol is worth standardising.
1543
+
1544
+ ---
1545
+
1546
+ ## 25. Reuse from existing systems
1547
+
1548
+ Christof has built a lot of this stuff already. The PRD is *not* "build everything from scratch". It is "compose the existing FORGE/EBKH/NEXUS/PicoClaw work behind a coherent mesh protocol". Concretely:
1549
+
1550
+ | Existing system | What it gives HearthNet |
1551
+ |---|---|
1552
+ | **FORGE** (15 HF Spaces, multi-agent platform) | Service skeleton, tool plumbing, GDPR delete endpoints, auto-seeding patterns |
1553
+ | **EBKH** (event-sourced claim graph, 28 packages, 48 event types) | The event log, snapshot pattern, schema-versioned events |
1554
+ | **NEXUS** (LLM gateway) | Multi-provider LLM adapter with health/latency tracking |
1555
+ | **htmlClaw / OpenClaw** (single-file WebGPU browser agent) | Possible browser-only node profile (Phase 2): a HearthNet node that lives entirely in a tab |
1556
+ | **Proto-Cognitive Architecture v5.2** | Optional advanced LLM backend with episodic memory |
1557
+ | **BitNet kernel** | Backend for ultra-low-resource nodes |
1558
+ | **DSGVO Löschprotokoll** (MinIO + PostgreSQL + FastAPI + Streamlit) | Audit-trail and erase patterns for compliance |
1559
+ | **Florence-2 + FLUX.1 pipeline** | Image services backend |
1560
+ | **smolagents + Edge-TTS / XTTS-v2 podcast generator** | Speech services backend |
1561
+ | **LM Studio at 192.168.188.25:1234** | The first real LLM backend during dev |
1562
+ | **JARVIS / TheCore notes** | Agent architecture inspiration for the router |
1563
+ | **HuggingFace MCP work (Chris4K)** | MCP integration in Phase 2 (HearthNet nodes as MCP servers) |
1564
+
1565
+ The build effort is real, but it is integration effort, not invention effort. That ratio is what makes this hackathon-doable.
1566
+
1567
+ ---
1568
+
1569
+ ## 26. Technology stack
1570
+
1571
+ ### 26.1 Languages
1572
+
1573
+ - **Python +3.11+** — primary, for everything except where noted
1574
+ - **Rust** — Phase 2 relay (optional, Python relay fine for MVP)
1575
+ - **HTML/CSS/JavaScript** — UI, front, mobile client, no frameworks (Christof preference)
1576
+ - **C++** — only via llama.cpp, not authored
1577
+
1578
+ ### 26.2 Libraries
1579
+
1580
+ | Concern | Library | Why |
1581
+ |---|---|---|
1582
+ | Web server | FastAPI + uvicorn | Christof's existing stack |
1583
+ | UI | Gradio 6.0.0 | Hackathon requirement, Christof familiar |
1584
+ | Discovery | python-zeroconf | de-facto for mDNS |
1585
+ | Crypto | PyNaCl (Ed25519) + cryptography (TLS) | Boring, secure |
1586
+ | Hashing | blake3 | Fast CID hashing |
1587
+ | Vector DB | ChromaDB (file-based) | Local-first, simple |
1588
+ | Embeddings | sentence-transformers | BGE-small is plenty |
1589
+ | LLM | llama-cpp-python OR ollama HTTP | Backend-agnostic via adapter |
1590
+ | Event store | SQLite + JSON | Zero-config, transactional |
1591
+ | Pub-sub | In-process asyncio + HTTP push for remote | No broker needed |
1592
+ | Topology viz | Cytoscape.js embedded in Gradio HTML | Christof has used Cytoscape before |
1593
+ | Charts | Chart.js | Christof has used Chart.js before |
1594
+ | CLI | Click | Standard |
1595
+ | Testing | pytest + pytest-asyncio | Standard |
1596
+ | Tracing | OpenTelemetry SDK (Phase 2) | Optional |
1597
+
1598
+ ### 26.3 Explicit non-choices
1599
+
1600
+ - **Not** Node.js or npm — Christof preference
1601
+ - **Not** React or any heavy frontend framework — Christof preference, also Gradio doesn't need it
1602
+ - **Not** Docker as a hard requirement — single-binary install must work
1603
+ - **Not** a custom binary protocol — JSON over HTTP is enough and debuggable
1604
+
1605
+ ---
1606
+
1607
+ ## 27. Deployment topologies
1608
+
1609
+ ### 27.1 Home (3 nodes typical)
1610
+
1611
+ - Anchor on a workstation
1612
+ - 1–2 Hearth nodes on laptops
1613
+ - 0–3 Spark thin clients on phones / Pi
1614
+
1615
+ ### 27.2 Small business
1616
+
1617
+ - 1–2 Anchors in the back office
1618
+ - 5–15 Spark clients at workstations
1619
+ - Optional Bridge to a sister branch via Phase 2 relay
1620
+
1621
+ ### 27.3 Civic / municipal
1622
+
1623
+ - Anchor per community building (Feuerwache, Bürgerhaus, Kirche)
1624
+ - Federation between buildings
1625
+ - Sparks via citizen smartphones with the mobile client
1626
+ - Bridge to civil defence systems (Phase 3, requires policy work)
1627
+
1628
+ ### 27.4 Disaster pilot
1629
+
1630
+ - Mobile anchor (camper-van rig with battery + Starlink fallback)
1631
+ - LoRa beacons for spread
1632
+ - Manual Spark distribution (USB drives with the mobile client)
1633
+
1634
+ ---
1635
+
1636
+ ## 28. Go-to-market & monetisation
1637
+
1638
+ These are aspirational, not part of the hackathon. Including them because the PRD is also a thinking document.
1639
+
1640
+ ### 28.1 Path A — retail-continuity pilot
1641
+
1642
+ stores depend on technical devices. Internet drops happen. A small HearthNet anchor in the back room of every store plus Sparks at every cashier desk = an internal mesh for orders, inventory checks, and customer comms that survives a WAN outage. Internal pilot first; later an outward-facing product offered to other cold-chain retailers.
1643
+
1644
+ Estimated revenue path: 1–2 year horizon, internal first.
1645
+
1646
+ ### 28.2 Path B — NRW Bevölkerungsschutz pilot
1647
+
1648
+ Each Kreis has civil-defence mandates. A neighbourhood AI mesh that works without internet fits exactly. Grant-fundable. Stakeholders: Kreis Kleve Bevölkerungsschutz, THW, optionally DRK. Christof's local Sankt-Martins-Comité contacts are a wedge.
1649
+
1650
+ Estimated revenue path: 6–12 months, public-sector procurement realities apply.
1651
+
1652
+ ### 28.3 Path C — HearthNet-in-a-Box appliance
1653
+
1654
+ Mini-PC (e.g. Beelink + small NVIDIA GPU or Intel Arc) pre-installed with the stack, a 1TB SSD, a curated emergency corpus, a default model. Ships with a printed booklet for the non-technical setup. Customers: community groups, churches, Vereine, prepper-adjacent, off-grid-curious.
1655
+
1656
+ Margins thin on hardware, real margin on optional yearly support + corpus updates.
1657
+
1658
+ Estimated revenue path: 3–6 months to first prototype, viable hobby-business scale.
1659
+
1660
+ ### 28.4 Path D — hosted relay tier
1661
+
1662
+ `relay.hearthnet.de` on Hetzner. Free for tiny communities (≤5 anchors), paid above. Bring-your-own-domain for organisations. Used for cross-LAN bootstrap, mobile push, and store-and-forward when no anchor is online for a recipient.
1663
+
1664
+ Estimated revenue path: 3 months to launch, low-margin but recurring.
1665
+
1666
+ ### 28.5 Path E — open-source consulting
1667
+
1668
+ The AGPL kernel + paid integration for organisations that want HearthNet inside their infrastructure. Standard open-core business model. Probably the highest near-term revenue per hour.
1669
+
1670
+ ### 28.6 Anti-paths
1671
+
1672
+ - No "neighbourhood crypto-token". Tempting and wrong.
1673
+ - No ad-supported model. Defeats the purpose.
1674
+ - No closed-source kernel. Defeats the trust model.
1675
+
1676
+ ---
1677
+
1678
+ ## 29. Risks & mitigations
1679
+
1680
+ | Risk | Likelihood | Impact | Mitigation |
1681
+ |---|---|---|---|
1682
+ | mDNS blocked on demo venue WiFi | Medium | High | Travel router on stage, UDP broadcast as fallback, fake-mesh dry-run mode |
1683
+ | GPU node OOM mid-demo | Low | High | Pre-warmed model, conservative `max_concurrent`, smaller model as fallback |
1684
+ | Demo computer dies | Low | Catastrophic | Two laptops, identical config, hot-swappable |
1685
+ | Distributed inference (Phase 3) attempted in MVP | Medium | High | Crossed-out in scope, behind feature flag if anyone tries |
1686
+ | Capability schema churn | Medium | Medium | Lock v1 schemas before M4 starts, treat as ABI |
1687
+ | Christof's bandwidth (newborn, Elternzeit) | High | High | Demo-driven scope; M7 and M10 are cuttable |
1688
+ | Privacy backlash ("you're routing my data through neighbours?") | Medium | Medium | Clear local-first defaults, signed-and-encrypted-in-transit, explicit "personal" corpus that never leaves device |
1689
+ | GDPR review | Medium | Medium | Reuse DSGVO Löschprotokoll patterns; explicit erase path |
1690
+ | Hardware vendor lock-in (NVIDIA-only) | Medium | Low | llama.cpp + ollama supports Apple Silicon and AMD; Ollama is the default for non-NVIDIA |
1691
+ | "It's just a worse cloud" criticism | High | Medium | Lead with the resilience demo, not the AI quality argument |
1692
+
1693
+ ---
1694
+
1695
+ ## 30. Success metrics
1696
+
1697
+ ### 30.1 Hackathon success
1698
+
1699
+ - Demo runs end-to-end without intervention on first try in the judge session
1700
+ - Topology visualisation is clear enough that a non-technical observer can describe what is happening
1701
+ - At least one judge asks "can I run this at home?"
1702
+ - Submission is delivered before deadline
1703
+ - Code is published, repo is clean, README has a one-command quickstart
1704
+
1705
+ ### 30.2 Post-hackathon technical success (3 months)
1706
+
1707
+ - Three real households running HearthNet for at least a week each
1708
+ - Median end-to-end latency under 2s for `llm.chat` in a typical home LAN
1709
+ - Zero data-loss incidents in event log under partition + rejoin scenarios
1710
+ - Mobile client usable on iOS Safari and Android Chrome
1711
+ - 80%+ test coverage on the bus
1712
+
1713
+ ### 30.3 Product success (12 months)
1714
+
1715
+ - At least one of the four monetisation paths has produced revenue
1716
+ - One outside contributor merged code
1717
+ - One academic citation or thoughtful blog post about the architecture
1718
+ - 100+ HF Spaces stars (proxy for community interest)
1719
+
1720
+ ---
1721
+
1722
+ ## 31. Open questions
1723
+
1724
+ These need resolution but do not block the hackathon.
1725
+
1726
+ 1. **Single binary or pip install?** Hackathon: pip. Long-term: single binary built with PyInstaller or Nuitka.
1727
+ 2. **Storage location standard?** XDG on Linux/macOS, `%APPDATA%` on Windows. Decision: follow `platformdirs` library.
1728
+ 3. **Time sync?** Lamport clocks make us mostly clock-independent, but UI timestamps suffer if clocks drift. Decision: display "X minutes ago" only; show absolute time only on the local device's wall clock.
1729
+ 4. **Mobile client served from any anchor — what about the URL?** mDNS for `hearthnet.local` is the goal. Browser support varies. Decision: print the IP+port in the QR code as a fallback.
1730
+ 5. **How does a Spark survive its anchor going down?** With a list of known peers. Decision: each Spark caches the last 10 peer manifests; tries them in order if the bound anchor disappears.
1731
+ 6. **What's the bus's behaviour when two local services register the same capability?** Both registered; router prefers based on declared params. No conflict.
1732
+ 7. **Can a non-member observe public traffic?** Yes — they see signed manifests by virtue of mDNS. They cannot make calls. Decision: keep this; visibility is the price of zero-config.
1733
+ 8. **Federation between communities with conflicting member sets?** Out of scope for MVP.
1734
+ 9. **Web of trust visualisation?** Phase 2 polish.
1735
+ 10. **Should anchors be able to refuse a capability call?** Yes — `unauthorized` is a valid response. Refusal is fine.
1736
+
1737
+ ---
1738
+
1739
+ ## 32. Glossary
1740
+
1741
+ | Term | Meaning |
1742
+ |---|---|
1743
+ | **Anchor** | Always-on node with GPU + storage, primary provider |
1744
+ | **Bus (capability bus)** | The L3 routing component every service registers with |
1745
+ | **Capability** | A named, versioned, schema-bound RPC offered by a node |
1746
+ | **CID** | Content identifier (BLAKE3 hash) used for content-addressed storage |
1747
+ | **Community** | A trust root; a group of nodes sharing a root key and event log |
1748
+ | **Emergency mode** | UI + behavioural state when internet detection reports offline |
1749
+ | **Federation** | Cross-community trust and capability access |
1750
+ | **Hearth** | Mid-tier node, typically a laptop |
1751
+ | **Lamport clock** | Logical counter used for event ordering |
1752
+ | **Manifest** | A signed JSON document (node manifest or community manifest) |
1753
+ | **Node** | One running HearthNet process |
1754
+ | **Profile** | One of `anchor`, `hearth`, `spark`, `bridge` — determines services |
1755
+ | **Service** | An L4 module providing one or more capabilities |
1756
+ | **Spark** | Thin client (Pi, mobile, browser) |
1757
+ | **Stable / experimental** | Capability stability flags |
1758
+
1759
+ ---
1760
+
1761
+ ## 33. Appendix A — capability namespace allocation
1762
+
1763
+ | Prefix | Owner service | Examples |
1764
+ |---|---|---|
1765
+ | `llm.*` | LLM service | `llm.chat`, `llm.complete`, `llm.classify` |
1766
+ | `embed.*` | Embedding service | `embed.text`, `embed.image` |
1767
+ | `rag.*` | RAG service | `rag.query`, `rag.ingest`, `rag.list_corpora` |
1768
+ | `file.*` | File service | `file.read`, `file.list`, `file.advertise` |
1769
+ | `market.*` | Marketplace | `market.list`, `market.post`, `market.search` |
1770
+ | `chat.*` | Chat | `chat.send`, `chat.history` |
1771
+ | `community.*` | Trust ops | `community.invite`, `community.revoke` |
1772
+ | `federation.*` | Cross-community | `federation.peer.add`, `federation.relay` |
1773
+ | `ocr.*` | OCR (Phase 2) | `ocr.image`, `ocr.pdf` |
1774
+ | `tts.*` `stt.*` | Speech (Phase 2) | `tts.synthesize`, `stt.transcribe` |
1775
+ | `trans.*` | Translation (Phase 2) | `trans.text` |
1776
+ | `img.*` | Images (Phase 2) | `img.describe`, `img.generate` |
1777
+ | `experimental.*` | Anything not promoted | `experimental.distributed_llm.chat` |
1778
+
1779
+ Reserved prefixes; no service may take a name outside its declared prefix.
1780
+
1781
+ ---
1782
+
1783
+ ## 34. Appendix B — example end-to-end trace
1784
+
1785
+ A user on the laptop asks *"Wie reinige ich Regenwasser ohne Strom?"*. The trace, as it would appear in the trace log:
1786
+
1787
+ ```
1788
+ t+0ms UI: user submits query, calls local bus capability "llm.chat@1.0"
1789
+ t+1ms Bus: routing query, looking for "llm.chat" providers
1790
+ t+2ms Bus: candidates: [anchor: 7H4G-..., self: 9JKM-...]
1791
+ anchor: p50=820ms, in_flight=0/4, success=0.99
1792
+ self: would-be: needs to load model, ~3000ms cold
1793
+ t+3ms Bus: scoring → anchor wins (lower latency)
1794
+ t+4ms Bus: opening stream to anchor
1795
+ t+7ms Anchor: receives request, validates signature, schema OK
1796
+ t+8ms Anchor LLM: starts generation
1797
+ t+9ms Anchor: calls local "rag.query@1.0" with the user message
1798
+ t+11ms Anchor RAG: embeds query (local embed.text)
1799
+ t+24ms Anchor RAG: vector search returns 4 chunks from emergency PDF
1800
+ t+25ms Anchor LLM: receives chunks, builds context, continues
1801
+ t+182ms Anchor: streams first token to laptop
1802
+ t+184ms Laptop UI: animates edge from anchor → self, shows first token
1803
+ t+1402ms Anchor: emits "done" event, stream closes
1804
+ t+1404ms Laptop UI: animation completes, shows source citation
1805
+ t+1405ms Bus: records trace: 1401ms, 178 tokens, success
1806
+ ```
1807
+
1808
+ Total perceived latency: under 1.5 seconds, with token streaming from ~200ms. Visible routing on screen.
1809
+
1810
+ ---
1811
+
1812
+ ## 35. Appendix C — example minimal node startup code
1813
+
1814
+ This is illustrative, not normative. Real implementation is split across modules.
1815
+
1816
+ ```python
1817
+ # hearthnet/node.py
1818
+ import asyncio
1819
+ from hearthnet.identity import load_or_generate_keys, load_community
1820
+ from hearthnet.discovery import mdns_loop, udp_broadcast_loop
1821
+ from hearthnet.bus import CapabilityBus
1822
+ from hearthnet.transport import HttpServer
1823
+ from hearthnet.services.llm import LlmService
1824
+ from hearthnet.services.rag import RagService
1825
+ from hearthnet.services.market import MarketplaceService
1826
+ from hearthnet.ui.gradio_app import build_ui
1827
+
1828
+ async def main():
1829
+ keys = load_or_generate_keys()
1830
+ community = load_community()
1831
+ bus = CapabilityBus(node_id=keys.node_id, community=community)
1832
+
1833
+ # Register local services
1834
+ bus.register_service(LlmService(backend="llama_cpp", model="qwen2.5-7b@q4"))
1835
+ bus.register_service(RagService(corpus="niederrhein-emergency"))
1836
+ bus.register_service(MarketplaceService(community=community))
1837
+
1838
+ # Start transport + discovery
1839
+ server = HttpServer(bus=bus, port=7080, keys=keys)
1840
+ await asyncio.gather(
1841
+ server.run(),
1842
+ mdns_loop(bus),
1843
+ udp_broadcast_loop(bus),
1844
+ emergency_detector(bus),
1845
+ build_ui(bus).launch_async(port=7860),
1846
+ )
1847
+
1848
+ if __name__ == "__main__":
1849
+ asyncio.run(main())
1850
+ ```
1851
+
1852
+ That is the whole shape. Everything else is filling in.
1853
+
1854
+ ---
1855
+
1856
+ *End of HearthNet PRD v2. Split into per-section docs once implementation starts.*